metaheuristic_designer.operators.operator_functions package¶
Submodules¶
metaheuristic_designer.operators.operator_functions.crossover module¶
- random_split(population_array: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator) tuple[ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool]][source]¶
Randomly partition the population into two equal-sized groups.
The population rows are randomly permuted and split in half. When the population size is odd, the phantom index (one beyond the original length) is replaced by a random valid index from the opposite group, ensuring both groups have the same shape and no individual is lost.
- Parameters:
population_array (MatrixLike) – 2D array of shape (N, M) containing the current population.
fitness_array (VectorLike) – Fitness values (unused in this split, kept for interface consistency).
random_state (RNGLike) – Random number generator.
- Returns:
Two arrays
(parents1, parents2)of equal shape(ceil(N/2), M)representing the randomly paired groups.- Return type:
tuple[MatrixLike, MatrixLike]
- stable_split(population_array: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator) tuple[ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool]][source]¶
Deterministically split the population into two halves preserving order.
For an even population the first and second halves are returned directly. For an odd population the arrays are made equal by cyclically wrapping indices modulo the original size, i.e. the extra slot is filled with the first individual (index 0). No randomness is used.
- Parameters:
population_array (MatrixLike) – 2D array of shape (N, M) containing the current population.
fitness_array (VectorLike) – Fitness values (unused).
random_state (RNGLike) – Random number generator (kept for API compatibility; not used).
- Returns:
Two arrays
(parents1, parents2)of equal shape(ceil(N/2), M).- Return type:
tuple[MatrixLike, MatrixLike]
- create_pairing_fn(method: str) Callable[source]¶
Retrieve a pairing function by name.
- Parameters:
method (str) – Key into the
pairing_mapdictionary. Supported values are"random"and"stable".- Returns:
A function with signature
(population_array, fitness_array, random_state) -> (parents1, parents2).- Return type:
Callable
- Raises:
ValueError – If method is not present in
pairing_map.
- k_point_crossover(population_array: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], k: int = 1, pairing_method: str = 'random', crossover_prob: float = 1, random_state: int | Generator | None = None) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
k-point crossover with per-pair probability.
The population is split into paired halves using pairing_method. For each pair, k distinct crossover points are drawn uniformly from \(\{1, \dots, M-1\}\) (sorted). The alternating mask built from these points determines which parent contributes each gene.
With probability crossover_prob the children are formed using the mask; otherwise the parents are copied unchanged. The operator returns exactly N offspring.
- Parameters:
population_array (MatrixLike) – Population of shape (N, M).
fitness_array (VectorLike) – Fitness values (unused by this operator).
k (int) – Number of crossover points. Must satisfy
1 <= k < M.pairing_method (str, optional) – Pairing strategy (
"random"or"stable").crossover_prob (float, optional) – Probability of applying the crossover to a given pair.
random_state (RNGLike, optional) – Random number generator.
- Returns:
Offspring population of shape (N, M).
- Return type:
MatrixLike
- uniform_crossover(population_array: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], pairing_method: str = 'random', crossover_prob: float = 1, random_state: int | Generator | None = None) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Uniform crossover with per-pair probability.
For each gene of a pair, the contributing parent is chosen independently with probability 0.5. The per-pair decision follows the same pattern as
k_point_crossover(): with probability crossover_prob the pair undergoes crossover, otherwise the parents are kept unchanged.- Parameters:
population_array (MatrixLike) – Population of shape (N, M).
fitness_array (VectorLike) – Fitness values (unused).
pairing_method (str, optional) – Pairing strategy (
"random"or"stable").crossover_prob (float, optional) – Probability of applying crossover to a pair.
random_state (RNGLike, optional) – Random number generator.
- Returns:
Offspring population of shape (N, M).
- Return type:
MatrixLike
- averaged_crossover(population_array: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], pairing_method: str = 'random', alpha: float = 0.5, crossover_prob: float = 1, random_state: int | Generator | None = None) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Arithmetic (averaged) crossover with per-pair probability.
For a pair of parents \(p_1, p_2\) the two children are defined as
\[\begin{split}c_1 &= (1-\alpha)\,p_1 + \alpha\,p_2,\\ c_2 &= (1-\alpha)\,p_2 + \alpha\,p_1,\end{split}\]where \(\alpha \in [0,1]\) controls the blend. With probability crossover_prob the pair is recombined; otherwise the parents are copied unchanged.
- Parameters:
population_array (MatrixLike) – Population of shape (N, M).
fitness_array (VectorLike) – Fitness values (unused).
pairing_method (str, optional) – Pairing strategy.
alpha (float, optional) – Blend factor.
alpha=0gives pure parent 1;alpha=1gives pure parent 2;alpha=0.5gives the midpoint.crossover_prob (float, optional) – Probability of applying crossover to a pair.
random_state (RNGLike, optional) – Random number generator.
- Returns:
Offspring population of shape (N, M).
- Return type:
MatrixLike
- blend_crossover(population_array: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], pairing_method: str = 'random', alpha: float = 0.5, crossover_prob: float = 1, random_state: int | Generator | None = None) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Blend crossover (BLX-\(\alpha\)) with per-pair probability.
For a pair of parents the smaller/larger values per gene are taken as \(x_{\min}\) and \(x_{\max}\). Each child gene is then sampled uniformly from the expanded interval
\[[x_{\min} - \alpha\,(x_{\max}-x_{\min}),\; x_{\max} + \alpha\,(x_{\max}-x_{\min})].\]The pair undergoes crossover with probability crossover_prob; otherwise the parents are kept intact.
Reference¶
Eshelman & Schaffer (1993): Real-coded genetic algorithms and interval schemata.
- param population_array:
Population of shape (N, M).
- type population_array:
MatrixLike
- param fitness_array:
Fitness values (unused).
- type fitness_array:
VectorLike
- param pairing_method:
Pairing strategy.
- type pairing_method:
str, optional
- param alpha:
Expansion factor (>=0).
- type alpha:
float, optional
- param crossover_prob:
Probability of applying crossover to a pair.
- type crossover_prob:
float, optional
- param random_state:
Random number generator.
- type random_state:
RNGLike, optional
- returns:
Offspring population of shape (N, M).
- rtype:
MatrixLike
- sbx_crossover(population_array: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], pairing_method: str = 'random', eta: float = 0.5, crossover_prob: float = 1, random_state: int | Generator | None = None) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Simulated Binary Crossover (SBX) with per-pair probability.
For a pair of parents \(p_1, p_2\) the children are computed as
\[\begin{split}c_1 &= 0.5(p_1+p_2) - 0.5\,\beta\,|p_1-p_2|,\\ c_2 &= 0.5(p_1+p_2) + 0.5\,\beta\,|p_1-p_2|,\end{split}\]where the spread factor \(\beta\) is drawn from a polynomial distribution with index \(\eta\):
\[\begin{split}\beta = \begin{cases} (2u)^{1/(\eta+1)}, & u \le 0.5,\\ \bigl(\frac{1}{2(1-u)}\bigr)^{1/(\eta+1)}, & u > 0.5, \end{cases}\end{split}\]with \(u \sim \mathcal{U}(0,1)\). Larger eta keeps children closer to the parents.
Reference¶
Deb & Agrawal (1995): Simulated binary crossover for continuous search space.
- param population_array:
Population of shape (N, M).
- type population_array:
MatrixLike
- param fitness_array:
Fitness values (unused).
- type fitness_array:
VectorLike
- param pairing_method:
Pairing strategy.
- type pairing_method:
str, optional
- param eta:
Distribution index for the spread factor (>=0).
- type eta:
float, optional
- param crossover_prob:
Probability of applying crossover to a pair.
- type crossover_prob:
float, optional
- param random_state:
Random number generator.
- type random_state:
RNGLike, optional
- returns:
Offspring population of shape (N, M).
- rtype:
MatrixLike
- bitwise_xor_crossover(population_array: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], pairing_method: str = 'random', crossover_prob: float = 1, random_state: int | Generator | None = None) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Bitwise XOR crossover for binary-valued populations.
For a pair of parents \(p_1, p_2\) the two children are
\[\begin{split}c_1 &= p_1 \oplus p_2,\\ c_2 &= p_1 \oplus \neg p_2,\end{split}\]where \(\oplus\) denotes bitwise XOR and \(\neg\) is bitwise NOT. This operator is intended for Boolean arrays (0/1). With probability crossover_prob the pair is crossed; otherwise the parents are kept unchanged.
- Parameters:
population_array (MatrixLike) – Population of shape (N, M). Should be of a Boolean or integer type where bitwise operations are meaningful.
fitness_array (VectorLike) – Fitness values (unused).
pairing_method (str, optional) – Pairing strategy.
crossover_prob (float, optional) – Probability of applying crossover to a pair.
random_state (RNGLike, optional) – Random number generator.
- Returns:
Offspring population of shape (N, M).
- Return type:
MatrixLike
- multiparent_discrete_crossover(population_array: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool] | None = None, k: int = 3, crossover_prob: float = 1.0, replace: bool = False, random_state: int | Generator | None = None) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Multi-parent discrete crossover (uniform scanning).
For each of the N offspring, k parents are drawn (with or without replacement) from the whole population. Every gene of the offspring is then taken uniformly at random from one of those k parents.
With probability crossover_prob an offspring is produced by recombination; otherwise it is a direct copy of the original individual at the same index.
- Parameters:
population_array (MatrixLike) – Population of shape (N, M).
fitness_array (VectorLike, optional) – Fitness values (unused).
k (int, optional) – Number of parents per offspring.
crossover_prob (float, optional) – Probability of applying crossover to an individual.
replace (bool, optional) – If False (default), the k parents are distinct (no replacement). If True, parents are sampled independently (with replacement).
random_state (RNGLike, optional) – Random number generator.
- Returns:
Offspring population of shape (N, M).
- Return type:
MatrixLike
- multiparent_intermediate_crossover(population_array: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool] | None = None, k: int = 3, crossover_prob: float = 1.0, replace: bool = False, random_state: int | Generator | None = None) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Multi-parent intermediate crossover (averaging recombination).
For each offspring, k parents are drawn (with or without replacement). The offspring is the arithmetic mean of those k parents.
With probability crossover_prob the offspring is the averaged vector; otherwise it is the original individual at the same index.
- Parameters:
population_array (MatrixLike) – Population of shape (N, M).
fitness_array (VectorLike, optional) – Fitness values (unused).
k (int, optional) – Number of parents per offspring.
crossover_prob (float, optional) – Probability of applying crossover to an individual.
replace (bool, optional) – If False (default), the k parents are distinct. If True, parents are sampled with replacement.
random_state (RNGLike, optional) – Random number generator.
- Returns:
Offspring population of shape (N, M).
- Return type:
MatrixLike
metaheuristic_designer.operators.operator_functions.differential_evolution module¶
Differential evolution operator implementations.
- differential_evolution_rand1(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator | None = None, F: float = 0.8, Cr: float = 0.9, **kwargs) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
DE/rand/1 mutation and binomial crossover.
For each target vector, three distinct random individuals are chosen. A donor vector is formed as
x_r1 + F * (x_r2 - x_r3). Components are then taken from the donor with probability Cr and from the target otherwise.- Parameters:
population_matrix (MatrixLike) – Current population, shape
(N, M).fitness_array (VectorLike) – Fitness values (used only by the
/best/variants).random_state (RNGLike, optional) – Random number generator.
F (float, optional) – Scale factor (default 0.8).
Cr (float, optional) – Crossover probability (default 0.9).
- Returns:
Trial population of the same shape.
- Return type:
MatrixLike
- differential_evolution_best1(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator | None = None, F: float = 0.8, Cr: float = 0.9, **kwargs) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
DE/best/1 mutation and binomial crossover.
The donor is formed using the best individual as the base:
x_best + F * (x_r1 - x_r2)where r1 and r2 are distinct and different from best.- Parameters:
population_matrix (MatrixLike) – Current population.
fitness_array (VectorLike) – Fitness values; the index of the maximum is used as best.
random_state (RNGLike, optional) – Random number generator.
F (float, optional) – Scale factor (default 0.8).
Cr (float, optional) – Crossover probability (default 0.9).
- Returns:
Trial population of the same shape.
- Return type:
MatrixLike
- differential_evolution_rand2(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator | None = None, F: float = 0.8, Cr: float = 0.9, **kwargs) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
DE/rand/2 mutation and binomial crossover.
Two difference vectors are used:
x_r1 + F*(x_r2 - x_r3) + F*(x_r4 - x_r5).- Parameters:
population_matrix (MatrixLike) – Current population.
fitness_array (VectorLike) – Fitness values (unused in this variant).
random_state (RNGLike, optional) – Random number generator.
F (float, optional) – Scale factor (default 0.8).
Cr (float, optional) – Crossover probability (default 0.9).
- Returns:
Trial population of the same shape.
- Return type:
MatrixLike
- differential_evolution_best2(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator | None = None, F: float = 0.8, Cr: float = 0.9, **kwargs) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
DE/best/2 mutation and binomial crossover.
The best individual is the base, and two difference vectors are added:
x_best + F*(x_r1 - x_r2) + F*(x_r3 - x_r4).- Parameters:
population_matrix (MatrixLike) – Current population.
fitness_array (VectorLike) – Fitness values; the best is the one with highest fitness.
random_state (RNGLike, optional) – Random number generator.
F (float, optional) – Scale factor (default 0.8).
Cr (float, optional) – Crossover probability (default 0.9).
- Returns:
Trial population of the same shape.
- Return type:
MatrixLike
- differential_evolution_current_to_rand1(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator | None = None, F: float = 0.8, Cr: float = 0.9, **kwargs) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
DE/current-to-rand/1 mutation and binomial crossover.
Each target vector x_i is combined with a random individual and a difference vector:
x_i + K*(x_r1 - x_i) + F*(x_r2 - x_r3), where K is drawn uniformly in [0,1] per individual.- Parameters:
population_matrix (MatrixLike) – Current population.
fitness_array (VectorLike) – Fitness values (unused).
random_state (RNGLike, optional) – Random number generator.
F (float, optional) – Scale factor (default 0.8).
Cr (float, optional) – Crossover probability (default 0.9).
- Returns:
Trial population of the same shape.
- Return type:
MatrixLike
- differential_evolution_current_to_best1(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator | None = None, F: float = 0.8, Cr: float = 0.9, **kwargs) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
DE/current-to-best/1 mutation and binomial crossover.
x_i + K*(x_best - x_i) + F*(x_r1 - x_r2).- Parameters:
population_matrix (MatrixLike) – Current population.
fitness_array (VectorLike) – Fitness values; the best is the one with highest fitness.
random_state (RNGLike, optional) – Random number generator.
F (float, optional) – Scale factor (default 0.8).
Cr (float, optional) – Crossover probability (default 0.9).
- Returns:
Trial population of the same shape.
- Return type:
MatrixLike
- differential_evolution_current_to_pbest1(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator | None = None, F: float = 0.8, Cr: float = 0.9, p: float = 0.1, **kwargs) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
DE/current-to-pbest/1 mutation and binomial crossover.
Instead of the single best, one of the top
p*Nindividuals is randomly chosen as pbest:x_i + K*(x_pbest - x_i) + F*(x_r1 - x_r2).- Parameters:
population_matrix (MatrixLike) – Current population.
fitness_array (VectorLike) – Fitness values; the top p fraction is selected.
random_state (RNGLike, optional) – Random number generator.
F (float, optional) – Scale factor (default 0.8).
Cr (float, optional) – Crossover probability (default 0.9).
p (float, optional) – Fraction of the population considered as elite (default 0.1).
- Returns:
Trial population of the same shape.
- Return type:
MatrixLike
metaheuristic_designer.operators.operator_functions.mutation module¶
Mutation operator implementations based on probability distributions.
- mutate_sample(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], distribution: str, N: int, random_state: int | Generator | None = None, **kwargs) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Replace N components of each individual with random values.
The new values are sampled from the probability distribution specified by distribution. The remaining components are left unchanged.
- Parameters:
population_matrix (MatrixLike) – Population of shape
(N_indiv, N_comp).fitness_array (VectorLike) – Fitness values (unused; kept for interface consistency).
distribution (str) – Key of the distribution to use (see
create_prob_distribution()).N (int) – Number of components to resample per individual.
random_state (RNGLike, optional) – Random number generator.
**kwargs – Forwarded to
create_prob_distribution()(e.g.loc,scale).
- Returns:
The modified population.
- Return type:
MatrixLike
- mutate_noise(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], distribution: str, F: number | float | int | ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], N: int, random_state: int | Generator | None = None, **kwargs) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Add random noise to N components of each individual.
The noise is drawn from distribution, multiplied by the strength factor F, and added to the selected components.
- Parameters:
population_matrix (MatrixLike) – Population of shape
(N_indiv, N_comp).fitness_array (VectorLike) – Fitness values (unused).
distribution (str) – Key of the distribution to use.
F (ScalarLike | VectorLike) – Strength factor (scalar or per-individual array).
N (int) – Number of components to mutate per individual.
random_state (RNGLike, optional) – Random number generator.
**kwargs – Forwarded to
create_prob_distribution().
- Returns:
The mutated population.
- Return type:
MatrixLike
- rand_sample(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], distribution: str, random_state: int | Generator | None = None, **kwargs) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Replace the entire population with new random values.
Each element of the genotype matrix is independently resampled from distribution.
- Parameters:
population_matrix (MatrixLike) – Population of shape
(N_indiv, N_comp). Only its shape is used.fitness_array (VectorLike) – Fitness values (unused).
distribution (str) – Key of the distribution to use.
random_state (RNGLike, optional) – Random number generator.
**kwargs – Forwarded to
create_prob_distribution().
- Returns:
A new matrix of the same shape filled with random samples.
- Return type:
MatrixLike
- rand_noise(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], distribution: str, F: number | float | int, random_state: int | Generator | None = None, **kwargs) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Add random noise to the entire population.
The noise is drawn from distribution, scaled by F, and added to every element of the genotype matrix.
- Parameters:
population_matrix (MatrixLike) – Population of shape
(N_indiv, N_comp).fitness_array (VectorLike) – Fitness values (unused).
distribution (str) – Key of the distribution to use.
F (ScalarLike) – Strength factor (scalar or per-individual array).
random_state (RNGLike, optional) – Random number generator.
**kwargs – Forwarded to
create_prob_distribution().
- Returns:
Noisy population of the same shape.
- Return type:
MatrixLike
- sample_1_sigma(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator | None = None, **kwargs) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Replace n components using a log-normal perturbation with a stored sigma value.
This is a self-adaptation helper for Evolution Strategies. The sigma values are expected to be passed in
kwargs.- Parameters:
population_matrix (MatrixLike) – Population.
fitness_array (VectorLike) – Fitness values (unused).
random_state (RNGLike, optional) – Random number generator.
**kwargs – Must contain
epsilon,sigma,tau,n.
- Returns:
The mutated population.
- Return type:
MatrixLike
- mutate_1_sigma(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator | None = None, **kwargs) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Mutate a single sigma value using a log-normal update.
The new sigma is
max(epsilon, old_sigma * exp(tau * N(0,1))).- Parameters:
population_matrix (MatrixLike) – Current sigma values (one per individual, or per dimension).
fitness_array (VectorLike) – Fitness values (unused).
random_state (RNGLike, optional) – Random number generator.
**kwargs – Must contain
epsilonandtau.
- Returns:
Updated sigma values.
- Return type:
MatrixLike
- mutate_n_sigmas(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator | None = None, **kwargs) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Mutate multiple sigma values with global and local learning rates.
max(epsilon, old_sigma * exp(tau*N(0,1) + tau_multiple*N(0,1))).- Parameters:
population_matrix (MatrixLike) – Current sigma values.
fitness_array (VectorLike) – Fitness values (unused).
random_state (RNGLike, optional) – Random number generator.
**kwargs – Must contain
epsilon,tau,tau_multiple.
- Returns:
Updated sigma values.
- Return type:
MatrixLike
- xor_mask(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], N: int, mode: str = 'byte', random_state: int | Generator | None = None, **kwargs) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Apply bitwise XOR with random masks to N components per individual.
The mask is drawn as random bytes, integers, or single bits depending on mode.
- Parameters:
population_matrix (MatrixLike) – Population.
fitness_array (VectorLike) – Fitness values (unused).
N (int) – Number of components to mask per individual.
mode (str, optional) – Mask format:
"bin","byte", or"int"(default"byte").random_state (RNGLike, optional) – Random number generator.
- Returns:
The masked population.
- Return type:
MatrixLike
metaheuristic_designer.operators.operator_functions.permutation module¶
Permutation-specific genetic operators (mutations and crossover).
- permute_mutation(population_array: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator | None = None, N: int | None = None) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Randomly permute
Ncomponents of each individual.When
Nis not given, all components are shuffled (a full permutation). The same subset of positions is used for every row, but a different random permutation is applied to each individual.- Parameters:
population_array (MatrixLike) – Population of shape
(pop_size, num_components).fitness_array (VectorLike) – Fitness values (unused; kept for interface consistency).
random_state (RNGLike, optional) – Random number generator.
N (int, optional) – Number of components to permute. Clipped between 2 and the number of components. Defaults to the population size when
None.
- Returns:
The mutated population with permuted components.
- Return type:
MatrixLike
- roll_mutation(population_array: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator | None = None, N: int = 1) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Cyclically shift (roll) a random segment of each individual.
For each solution, a contiguous interval
[start, end)is chosen uniformly. That segment is then rolled byNpositions.Ndefaults to 1, which effectively moves the first element of the segment to the end.- Parameters:
population_array (MatrixLike) – Population of shape
(pop_size, num_components).fitness_array (VectorLike) – Fitness values (unused).
random_state (RNGLike, optional) – Random number generator.
N (int, optional) – Number of positions to roll inside the segment. Default is 1.
- Returns:
The mutated population.
- Return type:
MatrixLike
- invert_mutation(population_array: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator | None = None) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Reverse the order of a random contiguous segment in each individual.
A segment
[start, end)is selected uniformly for every row, and its elements are reversed in place.- Parameters:
population_array (MatrixLike) – Population of shape
(pop_size, num_components).fitness_array (VectorLike) – Fitness values (unused).
random_state (RNGLike, optional) – Random number generator.
- Returns:
The mutated population.
- Return type:
MatrixLike
- pmx(population_array: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], pairing_method: str = 'random', crossover_prob: float = 1, random_state: int | Generator | None = None) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Partially Mapped Crossover (PMX) for permutation chromosomes.
Parents are paired using the given pairing_method. For each pair, two children are created by the standard PMX procedure, which preserves a randomly chosen segment from one parent and maps the remaining positions from the other parent. With probability crossover_prob the children are replaced by exact copies of the parents.
- Parameters:
population_array (MatrixLike) – Population of shape
(N, M), where each row is a permutation of integers0 … M-1.fitness_array (VectorLike) – Fitness values (unused).
pairing_method (str, optional) – Pairing strategy (
"random"or"stable").crossover_prob (float, optional) – Probability of applying crossover to a pair.
random_state (RNGLike, optional) – Random number generator.
- Returns:
Offspring population of shape
(N, M).- Return type:
MatrixLike
- pmx_single(vector1: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], vector2: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator | None = None) ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool][source]¶
Core PMX operation for a single pair of parents.
Original implementation found in https://github.com/cosminmarina/A1_ComputacionEvolutiva
- Parameters:
vector1 (VectorLike) – Two parent permutations (1-D arrays).
vector2 (VectorLike) – Two parent permutations (1-D arrays).
random_state (RNGLike, optional) – Random number generator.
- Returns:
One offspring permutation.
- Return type:
VectorLike
- order_cross(population_array: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], fitness_array: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], pairing_method: str = 'random', crossover_prob: float = 1, random_state: int | Generator | None = None) ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool][source]¶
Order Crossover (OX) for permutation chromosomes.
Builds offspring by preserving a randomly chosen segment from one parent and filling the remaining positions with the order of the other parent. The pairing and probability logic is identical to
pmx().- Parameters:
population_array (MatrixLike) – Population of shape
(N, M).fitness_array (VectorLike) – Fitness values (unused).
pairing_method (str, optional) – Pairing strategy.
crossover_prob (float, optional) – Probability of applying crossover to a pair.
random_state (RNGLike, optional) – Random number generator.
- Returns:
Offspring population of shape
(N, M).- Return type:
MatrixLike
- order_cross_single(vector1: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], vector2: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool], random_state: int | Generator | None = None) ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool][source]¶
Core OX operation for a single pair of parents.
- Parameters:
vector1 (VectorLike) – Two parent permutations.
vector2 (VectorLike) – Two parent permutations.
random_state (RNGLike, optional) – Random number generator.
- Returns:
One offspring permutation.
- Return type:
VectorLike
metaheuristic_designer.operators.operator_functions.probability_distributions module¶
- class Distribution[source]¶
Bases:
ABCAbstract base class for all probability distributions.
Defines the interface that every distribution must implement: a
samplemethod to generate random variates and an optionalestimate_parametersmethod to compute heuristic parameters from data.- abstract sample(shape: tuple, random_state: int | Generator) ndarray[tuple[int, ...], floating] | ndarray[tuple[int, ...], integer] | ndarray[tuple[int, ...], uint8 | bool][source]¶
Draw random samples from the distribution.
- Parameters:
shape (tuple) – Shape of the requested output array.
random_state (RNGLike) – Random number generator.
- Returns:
Array of samples with the requested shape.
- Return type:
TensorLike
- estimate_parameters(data_matrix, **kwargs)[source]¶
Compute heuristic distribution parameters from a data matrix.
This method is optional and may be overridden by subclasses. The default implementation does nothing and returns
None.- Parameters:
data_matrix (np.ndarray) – 2-D array of shape
(N, M)containing the data used for estimation.**kwargs – Additional keyword arguments that may influence the estimation.
- Return type:
None
- class ScipyUnivarDistribution(distribution_cls, **kwargs)[source]¶
Bases:
DistributionWraps a SciPy univariate distribution.
- Parameters:
distribution_cls (type) – A SciPy distribution class (e.g.,
scipy.stats.norm).**kwargs – Parameters forwarded to the distribution constructor.
- sample(shape: tuple, random_state: int | Generator) ndarray[tuple[int, ...], floating] | ndarray[tuple[int, ...], integer] | ndarray[tuple[int, ...], uint8 | bool][source]¶
Draw random samples.
- Parameters:
shape (tuple) – Desired output shape, e.g.,
(N, M).random_state (RNGLike) – Random number generator.
- Returns:
Array of independent samples of the requested shape.
- Return type:
np.ndarray
- class ScipyMultivarDistribution(distribution_cls, **kwargs)[source]¶
Bases:
DistributionWraps a SciPy multivariate distribution.
- Parameters:
distribution_cls (type) – A SciPy multivariate distribution class (e.g.,
scipy.stats.multivariate_normal).**kwargs – Parameters forwarded to the distribution constructor.
- sample(shape: tuple, random_state: int | Generator) ndarray[tuple[int, ...], floating] | ndarray[tuple[int, ...], integer] | ndarray[tuple[int, ...], uint8 | bool][source]¶
Draw random samples.
For a multivariate distribution,
shape[1]is ignored; the output shape is determined by the number of individuals (shape[0]) and the dimension of the distribution.- Parameters:
shape (tuple) – Requested shape; only
shape[0]is used.random_state (RNGLike) – Random number generator.
- Returns:
Array of shape
(shape[0], dim).- Return type:
np.ndarray
- class multivariate_categorical(categories, weight_matrix)[source]¶
Bases:
DistributionMultivariate categorical distribution with per-row probability weights.
- Parameters:
categories (array-like) – List of category values.
weight_matrix (np.ndarray) – 2-D array of shape
(N, K)containing non-negative weights for each of theKcategories in each row. Weights are normalised row-wise before sampling.
- sample(shape: tuple, random_state: int | Generator) ndarray[tuple[int, ...], floating] | ndarray[tuple[int, ...], integer] | ndarray[tuple[int, ...], uint8 | bool][source]¶
Draw random samples.
- Parameters:
shape (tuple) – Requested shape; if
Nonethe number of rows is taken fromself.cumsum_matrix.shape[0]. Otherwise the first element gives the number of rows, and additional dimensions are appended.random_state (RNGLike) – Random number generator.
- Returns:
Array of categorical samples with shape determined by shape.
- Return type:
np.ndarray
- uniform_param_fix(min=None, max=None, **kwargs)[source]¶
Convert
min/maxarguments toloc/scalefor a uniform distribution.- Parameters:
min (float or array-like, optional) – Lower bound of the uniform interval.
max (float or array-like, optional) – Upper bound of the uniform interval.
**kwargs (dict) – Remaining keyword arguments (e.g.,
loc,scale).
- Returns:
A copy of kwargs with
locandscaleset appropriately when both min and max are provided. min and max are removed from the dictionary.- Return type:
dict
- normal_heuristic(population_matrix, loc=None, scale=None, **kwargs)[source]¶
Heuristic parameter estimation for the normal distribution.
When loc or scale is the string
"calculated", the sample mean or standard deviation (computed over axis 0) is used.- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, M).loc (None, float, array-like, or
"calculated") – Location parameter. If"calculated", it is replaced by the per-column mean.scale (None, float, array-like, or
"calculated") – Scale parameter. If"calculated", it is replaced by the per-column standard deviation.**kwargs – Additional keyword arguments passed through unchanged.
- Returns:
The updated kwargs with resolved
locandscale.- Return type:
dict
- uniform_heuristic(population_matrix, loc=None, scale=None, **kwargs)[source]¶
Heuristic parameter estimation for the uniform distribution.
When loc or scale is
"calculated", the per-column minimum is used as loc, andmax - minis used as scale.- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, M).loc (None, float, array-like, or
"calculated") – Lower bound. If"calculated", it is replaced by the per-column minimum.scale (None, float, array-like, or
"calculated") – Interval length. If"calculated", it is set tomax - minper column.**kwargs – Additional keyword arguments passed through unchanged.
- Returns:
The updated kwargs with resolved
locandscale.- Return type:
dict
- cauchy_heuristic(population_matrix, loc=None, scale=None, **kwargs)[source]¶
Heuristic parameter estimation for the Cauchy distribution.
loc is estimated by the per-column median; scale is estimated by half the per-column interquartile range (IQR / 2).
- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, M).loc (None, float, array-like, or
"calculated") – Location parameter. If"calculated", it is replaced by the per-column median.scale (None, float, array-like, or
"calculated") – Scale parameter. If"calculated", it is estimated asscipy.stats.iqr(data, axis=0) / 2.**kwargs – Additional keyword arguments passed through unchanged.
- Returns:
The updated kwargs with resolved
locandscale.- Return type:
dict
- laplace_heuristic(population_matrix, loc=None, scale=None, **kwargs)[source]¶
Heuristic parameter estimation for the Laplace distribution.
loc is estimated by the per-column median; scale is estimated by the median absolute deviation (MAD).
- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, M).loc (None, float, array-like, or
"calculated") – Location parameter. If"calculated", it is replaced by the per-column median.scale (None, float, array-like, or
"calculated") – Scale parameter. If"calculated", it is estimated usingscipy.stats.median_abs_deviationalong axis 0.**kwargs – Additional keyword arguments passed through unchanged.
- Returns:
The updated kwargs with resolved
locandscale.- Return type:
dict
- gamma_heuristic(population_matrix, a=None, scale=None, **kwargs)[source]¶
Heuristic parameter estimation for the gamma distribution.
Uses method of moments: shape
a = mean² / varianceandscale = variance / mean.- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, M).a (None, float, array-like, or
"calculated") – Shape parameter. If"calculated", it is computed asmean² / var.scale (None, float, array-like, or
"calculated") – Scale parameter. If"calculated", it is computed asvar / mean.**kwargs – Additional keyword arguments passed through unchanged.
- Returns:
The updated kwargs with resolved
aandscale.- Return type:
dict
- expon_heuristic(population_matrix, scale=None, **kwargs)[source]¶
Heuristic parameter estimation for the exponential distribution.
If scale is
"calculated", it is set to the per-column mean minus loc (which defaults to 0).- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, M).scale (None, float, array-like, or
"calculated") – Scale parameter. If"calculated",scale = mean - loc.**kwargs – Additional keyword arguments passed through unchanged; expected to contain loc if a non-zero shift is used.
- Returns:
The updated kwargs with resolved scale.
- Return type:
dict
- levy_stable_heuristic(population_matrix, loc=None, scale=None, **kwargs)[source]¶
Heuristic parameter estimation for the Lévy-stable distribution.
loc is estimated by the per-column median; scale by the median absolute deviation (MAD). Note: this is a very rough approximation and should be used only when no better estimator is available.
- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, M).loc (None, float, array-like, or
"calculated") – Location parameter. If"calculated", it is replaced by the per-column median.scale (None, float, array-like, or
"calculated") – Scale parameter. If"calculated", it is estimated usingscipy.stats.median_abs_deviationalong axis 0.**kwargs – Additional keyword arguments passed through unchanged.
- Returns:
The updated kwargs with resolved
locandscale.- Return type:
dict
- poisson_heuristic(population_matrix, mu=None, **kwargs)[source]¶
Heuristic parameter estimation for the Poisson distribution.
If mu is
"calculated", it is set to the per-column mean minus loc (default 0).- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, M).mu (None, float, array-like, or
"calculated") – Rate parameter. If"calculated",mu = mean - loc.**kwargs – Additional keyword arguments passed through unchanged; expected to contain loc if a non-zero shift is used.
- Returns:
The updated kwargs with resolved mu.
- Return type:
dict
- bernoulli_heuristic(population_matrix, p=None, **kwargs)[source]¶
Heuristic parameter estimation for the Bernoulli distribution.
If p is
"calculated", it is estimated as the per-column mean (proportion of ones), adjusting for loc if given (default 0).- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, M).p (None, float, array-like, or
"calculated") – Success probability. If"calculated",p = mean - loc.**kwargs – Additional keyword arguments passed through unchanged.
- Returns:
The updated kwargs with resolved p.
- Return type:
dict
- binomial_heuristic(population_matrix, p=None, **kwargs)[source]¶
Heuristic parameter estimation for the binomial distribution.
n must be provided externally. If p is
"calculated", it is estimated as(mean - loc) / n.- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, M).p (None, float, array-like, or
"calculated") – Success probability. If"calculated",p = (mean - loc) / n.**kwargs – Additional keyword arguments passed through unchanged; must contain the integer n (number of trials) and optionally loc.
- Returns:
The updated kwargs with resolved p.
- Return type:
dict
- tikhinov_heuristic(population_matrix, loc=None, kappa=None, **kwargs)[source]¶
Heuristic parameter estimation for the von Mises (circular) distribution.
loc is estimated as the circular mean (
arctan2(mean sin, mean cos)). kappa is approximated from the mean resultant length R askappa = R / (1 - R).- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, M)of angles in radians.loc (None, float, array-like, or
"calculated") – Mean direction. If"calculated", the per-column circular mean is used.kappa (None, float, array-like, or
"calculated") – Concentration parameter. If"calculated", it is approximated from the mean resultant length.**kwargs – Additional keyword arguments passed through unchanged.
- Returns:
The updated kwargs with resolved
locandkappa.- Return type:
dict
- multivariate_normal_heuristic(population_matrix, mean=None, cov=None, **kwargs)[source]¶
Heuristic parameter estimation for the multivariate normal distribution.
mean is estimated as the per-column average. Automatic estimation of the full covariance matrix is not supported, use with caution.
- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, M).mean (None, array-like, or
"calculated") – Mean vector. If"calculated", it is set to the per-column mean.cov (None, array-like, or
"calculated") – Covariance matrix. If"calculated", an error is raised because automatic estimation is not implemented.**kwargs – Additional keyword arguments passed through unchanged.
- Returns:
The updated kwargs with resolved mean (and possibly cov).
- Return type:
dict
- Raises:
ValueError – If cov is
"calculated", automatic covariance estimation is not supported.
- dirichlet_heuristic(population_matrix, alpha=None, **kwargs)[source]¶
Heuristic parameter estimation for the Dirichlet distribution.
Automatic estimation of the concentration parameter vector alpha is not supported.
- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, M).alpha (None, array-like, or
"calculated") – Concentration parameters. If"calculated", an error is raised.**kwargs – Additional keyword arguments passed through unchanged.
- Returns:
The updated kwargs with resolved alpha.
- Return type:
dict
- Raises:
ValueError – If alpha is
"calculated", automatic estimation is not supported.
- tikhinov_fisher_heuristic(population_matrix, loc=None, kappa=None, **kwargs)[source]¶
Heuristic parameter estimation for the von Mises-Fisher distribution.
loc is estimated by normalising the mean vector of the data. kappa is approximated using the mean resultant length R and the dimension d:
kappa = R * (d - R²) / (1 - R²).- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, d)where each row is a point on the d-dimensional sphere.loc (None, array-like, or
"calculated") – Mean direction (unit vector). If"calculated", it is set to the normalised sample mean.kappa (None, float, or
"calculated") – Concentration parameter. If"calculated", it is approximated from the mean resultant length.**kwargs – Additional keyword arguments passed through unchanged.
- Returns:
The updated kwargs with resolved
locandkappa.- Return type:
dict
metaheuristic_designer.operators.operator_functions.probability_distributions_factory module¶
Factory and registry for probability distributions
- create_prob_distribution(distribution_name: str, population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool] | None = None, parameter_heuristic_fn: Callable | None = None, **kwargs) Distribution[source]¶
Instantiate a probability distribution by name.
- Parameters:
distribution_name (str) – Distribution key. Can use dot-notation (e.g.,
"scipy-univar.norm") or a short name ("norm") if unambiguous.population_matrix (MatrixLike) – Population data used when automatic parameter estimation (
"calculated") is requested.parameter_heuristic_fn (Callable, optional) – An optional callable that overrides the registered heuristic for this call. If
None, the registered heuristic (or a no-op) is used.**kwargs – Parameters forwarded to the distribution constructor (e.g.,
loc,scale,min,max).
- Returns:
A callable distribution object ready for sampling.
- Return type:
- add_distribution_entry(distribution_class: Distribution, distribution_name: str, registry: str = 'custom', param_processor: Callable | None = None, heuristic_fn: Callable | None = None)[source]¶
Register a new probability distribution so that it can be created via
create_prob_distribution().- Parameters:
distribution_class (type[Distribution]) – A concrete
Distributionsubclass (or a callable that returns one). For SciPy distributions, pass the SciPy class directly (e.g.,scipy.stats.norm); it will be wrapped automatically.distribution_name (str) – Key used to retrieve this distribution (e.g.,
"my_noise").registry (str, optional) – Sub-registry to add the distribution to. Currently supported values are
"scipy-univar","scipy-multivar", and"custom"(default). If the registry does not exist, it is created.param_processor (callable, optional) – A function that receives
**kwargsand returns a modified dictionary before passing it to the distribution constructor. Useful for converting parameter names (seeuniform_param_fix()).heuristic_fn (callable, optional) – A function
(population_matrix, **kwargs) -> kwargsthat computes default parameter values when"calculated"is requested. IfNone(the default), the distribution does not support automatic parameter estimation.
- list_distributions() list[str][source]¶
Return a list of all available distribution keys.
The keys are formatted as
"registry.distribution_name"and can be passed directly tocreate_prob_distribution().- Returns:
Fully qualified distribution names.
- Return type:
list of str
metaheuristic_designer.operators.operator_functions.random_generation module¶
- compute_statistic(population_matrix, stat_name='mean', weights=None)[source]¶
- Parameters:
population_matrix (numpy.array) – Matrix containing the set of tentative solutions.
initializer (Initializer) – Initializer instance that handles random initializtion of the population.
stat_name (str, optional) – Name of the statistic to use, options are “mean”, “average”, “median” and “std”, by default “mean”.
weights (numpy.array, optional) – Vector indicating the weights to apply if “average” is selected, by default None.
- Return type:
Component-wise statistic vector.
- random_initialize(population_matrix, initializer: Initializer, random_state=None)[source]¶
Randomly regenerate the entire population from scratch with the initializer’s distribution.
- Parameters:
population_matrix (numpy.array) – Matrix containing the set of tentative solutions.
initializer (Initializer) – Initializer instance that handles random initializtion of the population.
- Return type:
Randomly initialized population
- random_reset(population_matrix, initializer: Initializer, random_state=None, n: int = 1)[source]¶
Randomly resets n components of each solution.
- Parameters:
population_matrix (numpy.array) – Matrix containing the set of tentative solutions.
initializer (Initializer) – Initializer instance that handles random initializtion of the population.
n (int, optional) – Number of components to reset, by default 1
- Return type:
Population matrix with randomly changed components.
metaheuristic_designer.operators.operator_functions.swarm module¶
Swarm intelligence operator implementations.
- pso_operator(population_matrix: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], population_speed: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], historical_best: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], global_best: ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], random_state: int | Generator | None = None, w: float = 0.7, c1: float = 1.5, c2: float = 1.5) tuple[ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool], ndarray[tuple[int, int], floating] | ndarray[tuple[int, int], integer] | ndarray[tuple[int, int], uint8 | bool]][source]¶
Perform a single step of the standard Particle Swarm Optimisation (PSO).
Velocity is updated as:
\[v_{i} = w v_{i} + c_1 r_1 (p_{i} - x_{i}) + c_2 r_2 (g - x_{i})\]where \(p_{i}\) is the historical best of particle i, \(g\) is the global best, and \(r_1\), \(r_2\) are uniform random numbers in [0, 1].
The new position is \(x_{i} + v_{i}\).
- Parameters:
population_matrix (MatrixLike) – Current positions, shape
(N, D).population_speed (MatrixLike) – Current velocities, shape
(N, D).historical_best (MatrixLike) – Personal best positions, shape
(N, D).global_best (MatrixLike) – Global best position, shape
(D,)(broadcast to(N, D)).random_state (RNGLike, optional) – Random number generator.
w (float, optional) – Inertia weight (default 0.7).
c1 (float, optional) – Cognitive acceleration coefficient (default 1.5).
c2 (float, optional) – Social acceleration coefficient (default 1.5).
- Returns:
The new positions and the new velocities, both shape
(N, D).- Return type:
tuple[MatrixLike, MatrixLike]
- pso_operator_wrapper(population: Population, initializer: Initializer, random_state: int | Generator | None = None, w: float = 0.7, c1: float = 1.5, c2: float = 1.5) Population[source]¶
Wrapper that integrates the PSO operator with the library’s Population API.
Extracts the solution and velocity parts from the population (which must use a
ParameterExtendingEncodingwith a"speed"parameter), applies the standard PSO update, and encodes the result back into the population’s genotype matrix.- Parameters:
population (Population) – Current population. Its encoding must be a
ParameterExtendingEncodingthat includes a"speed"parameter._initializer (Initializer) – Initializer (unused; kept for interface compatibility).
random_state (RNGLike, optional) – Random number generator.
w (float, optional) – Inertia weight (default 0.7).
c1 (float, optional) – Cognitive coefficient (default 1.5).
c2 (float, optional) – Social coefficient (default 1.5).
- Returns:
The updated population with new positions and velocities.
- Return type:
metaheuristic_designer.operators.operator_functions.utils module¶
- dummy_op(population_matrix: ndarray, fitness_array: ndarray, random_state: Generator | None = None, f: number | float | int = 0) ndarray[source]¶
Return a matrix of constant value f with the same shape as the input.
This operator is intended only for debugging and testing. It ignores the population contents and produces an array where every gene equals f.
- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, M)(ignored, but its shape is used)._fitness_array (np.ndarray) – Fitness values (unused, kept for interface compatibility).
random_state (np.random.Generator, optional) – Random number generator (unused).
f (ScalarLike, optional) – Value to fill the array with. Default is
0.
- Returns:
A
(N, M)array filled with the constant f.- Return type:
np.ndarray
- add_const(population_matrix: ndarray, fitness_array: ndarray, random_state: Generator | None = None, f: ndarray[tuple[int], floating] | ndarray[tuple[int], integer] | ndarray[tuple[int], uint8 | bool] | number | float | int = 0) ndarray[source]¶
Add a constant (or vector) to every gene of the population.
Useful as a trivial baseline operator: it simply returns
population_matrix + f, where f can be a scalar (added to all genes) or a vector (added per gene).- Parameters:
population_matrix (np.ndarray) – 2-D array of shape
(N, M).fitness_array (np.ndarray) – Fitness values (unused).
random_state (np.random.Generator, optional) – Random number generator (unused).
f (VectorLike or ScalarLike, optional) – Value(s) to add. A scalar is broadcast to every gene; a 1-D array of length M is added per gene. Default is
0.
- Returns:
population_matrix + f.- Return type:
np.ndarray
- class OperatorFnDef(operator_fn: callable, params: dict = <factory>, forced_params: dict = <factory>)[source]¶
Bases:
objectBridge a matrix-to-matrix operator function into an
Operator.This wrapper accepts a callable that operates on a genotype matrix, fitness array, and random state, and turns it into an object that can be used directly on a
Population. It merges user-supplied keyword arguments with stored defaults and forced parameters, then invokes the underlying function and updates the population’s genotype.- Parameters:
operator_fn (callable) – Function with signature
(population_matrix, fitness_array, random_state, **kwargs) -> np.ndarray.params (dict, optional) – Default keyword arguments for the operator.
forced_params (dict, optional) – Keyword arguments that always override user-supplied ones.
- operator_fn: callable¶
- params: dict¶
- forced_params: dict¶
- class OperatorRandomDef(operator_fn: callable, params: dict = <factory>, forced_params: dict = <factory>)[source]¶
Bases:
objectBridge a random-style operator function into an
Operator.This wrapper is intended for operators that replace the genotype with entirely new random values (e.g., uniform sampling, initializer-based reset). It passes the population’s genotype matrix, the initializer, and the random state to the underlying function.
- Parameters:
operator_fn (callable) – Function with signature
(population_matrix, initializer, random_state, **kwargs) -> np.ndarray.params (dict, optional) – Default keyword arguments.
forced_params (dict, optional) – Keyword arguments that override any user-supplied ones.
- operator_fn: callable¶
- params: dict¶
- forced_params: dict¶
- class ObtainStatisticDef(operator_fn: callable, params: dict = <factory>, forced_params: dict = <factory>)[source]¶
Bases:
objectWrap a statistic‑computing function into an
Operator.This adapter is used for functions that compute a single summary vector (e.g., population mean, median, standard deviation) and store it as the new genotype (usually a single-row population).
- Parameters:
operator_fn (callable) – Function with signature
(population_matrix, random_state, **kwargs) -> np.ndarray.params (dict, optional) – Default keyword arguments.
forced_params (dict, optional) – Keyword arguments that override user-supplied ones.
- operator_fn: callable¶
- params: dict¶
- forced_params: dict¶
- class OperatorSwarmDef(operator_fn: callable, params: dict = <factory>, forced_params: dict = <factory>)[source]¶
Bases:
objectBridge a swarm operator function into an
Operator.This wrapper is designed for operators that directly receive the whole
Populationobject and the initializer, and are responsible for returning an updatedPopulationthemselves (e.g., PSO operators that need access to historical bests).- Parameters:
operator_fn (callable) – Function with signature
(population, initializer, random_state, **kwargs) -> Population.params (dict, optional) – Default keyword arguments.
forced_params (dict, optional) – Keyword arguments that override user-supplied ones.
- operator_fn: callable¶
- params: dict¶
- forced_params: dict¶
Module contents¶
Pure function implementation of mutation operators
- class ObtainStatisticDef(operator_fn: callable, params: dict = <factory>, forced_params: dict = <factory>)[source]¶
Bases:
objectWrap a statistic‑computing function into an
Operator.This adapter is used for functions that compute a single summary vector (e.g., population mean, median, standard deviation) and store it as the new genotype (usually a single-row population).
- Parameters:
operator_fn (callable) – Function with signature
(population_matrix, random_state, **kwargs) -> np.ndarray.params (dict, optional) – Default keyword arguments.
forced_params (dict, optional) – Keyword arguments that override user-supplied ones.
- operator_fn: callable¶
- params: dict¶
- forced_params: dict¶
- class OperatorRandomDef(operator_fn: callable, params: dict = <factory>, forced_params: dict = <factory>)[source]¶
Bases:
objectBridge a random-style operator function into an
Operator.This wrapper is intended for operators that replace the genotype with entirely new random values (e.g., uniform sampling, initializer-based reset). It passes the population’s genotype matrix, the initializer, and the random state to the underlying function.
- Parameters:
operator_fn (callable) – Function with signature
(population_matrix, initializer, random_state, **kwargs) -> np.ndarray.params (dict, optional) – Default keyword arguments.
forced_params (dict, optional) – Keyword arguments that override any user-supplied ones.
- operator_fn: callable¶
- params: dict¶
- forced_params: dict¶
- class OperatorSwarmDef(operator_fn: callable, params: dict = <factory>, forced_params: dict = <factory>)[source]¶
Bases:
objectBridge a swarm operator function into an
Operator.This wrapper is designed for operators that directly receive the whole
Populationobject and the initializer, and are responsible for returning an updatedPopulationthemselves (e.g., PSO operators that need access to historical bests).- Parameters:
operator_fn (callable) – Function with signature
(population, initializer, random_state, **kwargs) -> Population.params (dict, optional) – Default keyword arguments.
forced_params (dict, optional) – Keyword arguments that override user-supplied ones.
- operator_fn: callable¶
- params: dict¶
- forced_params: dict¶
- class OperatorFnDef(operator_fn: callable, params: dict = <factory>, forced_params: dict = <factory>)[source]¶
Bases:
objectBridge a matrix-to-matrix operator function into an
Operator.This wrapper accepts a callable that operates on a genotype matrix, fitness array, and random state, and turns it into an object that can be used directly on a
Population. It merges user-supplied keyword arguments with stored defaults and forced parameters, then invokes the underlying function and updates the population’s genotype.- Parameters:
operator_fn (callable) – Function with signature
(population_matrix, fitness_array, random_state, **kwargs) -> np.ndarray.params (dict, optional) – Default keyword arguments for the operator.
forced_params (dict, optional) – Keyword arguments that always override user-supplied ones.
- operator_fn: callable¶
- params: dict¶
- forced_params: dict¶