Source code for qdpy.tools

#    This file is part of qdpy.
#
#    qdpy is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as
#    published by the Free Software Foundation, either version 3 of
#    the License, or (at your option) any later version.
#
#    qdpy is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public
#    License along with qdpy. If not, see <http://www.gnu.org/licenses/>.

## @file
# @brief Selection, mutation, and trusted result-file helpers.

"""Basic operators and tools used to design QD or evolutionary algorithms."""

import numpy as np
import random
from typing import Sequence, Callable, Tuple
from itertools import repeat
import copy
import pickle

from qdpy.phenotype import *
from qdpy.base import *
from qdpy import containers


########### SELECTION ########### {{{1

def sel_random(collection: Sequence[Any]) -> Sequence[Any]:
    """Select and return one individual at random among `collection`.

    Parameters
    ----------
    :param collection: Sequence[Any]
        The individuals to select from.
    """
    return random.choice(collection)


def non_trivial_sel_random(container: containers.Container) -> Any:
    """Select and return one individual at random among `container`.
    Ignore individuals with a trivial fitness (i.e. equal to the minimum fitness value),
    except if there are only individuals with trivial fitness.

    Parameters
    ----------
    :param container: Container
        The individuals to select from.
    """
    fst_ind: Any = container[0]
    min_fitness: Any = copy.deepcopy(fst_ind.fitness)
    assert container.fitness_domain is not None and len(min_fitness.values) == len(container.fitness_domain), f"You must specify `fitness_domain` in Container, and use individuals with fitness values of the same length as `fitness_domain`."
    min_fitness.values = tuple([x[0] for x in container.fitness_domain])
    candidates: MutableSequence[Any] = [ind for ind in container if ind.fitness.dominates(min_fitness)]
    if len(candidates):
        return random.choice(candidates)
    else:
        return random.choice(container)


[docs] def sel_roulette(collection: Sequence[Any]) -> Sequence[Any]: """Select a member by its sum of raw objective values. The supplied values should define valid nonnegative roulette probabilities. A total of zero falls back to a uniform choice. """ assert(len(collection)) sum_fit_val = [sum(i.fitness.values) for i in collection] sum_all_fit = sum(sum_fit_val) if sum_all_fit == 0: probs = [1. / len(collection) for _ in sum_fit_val] else: probs = [f / sum_all_fit for f in sum_fit_val] return random.choices(collection, weights=probs)[0]
## @brief Draw one candidate with weights derived from a named scalar score. # @param collection Nonempty sequence of candidates. # @param score_name Candidate score used for weighting. # @param default_score Score for candidates that lack the named measurement. # @return A member of the input sequence.
[docs] def sel_roulette_score(collection, score_name: str = "curiosity", default_score: float = 0.0): """Select by a finite named score, with support for negative scores. Shift all scores by the same amount when the minimum is negative. If every resulting weight is zero, draw uniformly. """ if len(collection) == 0: raise ValueError("Cannot select from an empty collection.") scores = [float(ind.scores.get(score_name, default_score)) for ind in collection] if not all(math.isfinite(score) for score in scores): raise ValueError(f"Roulette score {score_name!r} must be finite.") scale = max(map(abs, scores)) if scale == 0.0: return random.choice(collection) offset = min(0.0, min(scores) / scale) weights = [score / scale - offset for score in scores] return random.choices(collection, weights=weights)[0] if any(weights) else random.choice(collection)
[docs] def sel_grid_roulette(collection: Sequence[Any]) -> Sequence[Any]: """Select a grid member and use its cell for roulette selection. The first draw is uniform over stored entries, so cells with more members are visited more often. The second draw applies roulette weights to the chosen cell's population. """ assert(isinstance(collection, containers.Grid)) assert(len(collection)) # Select randomly an occupied bin of the grid tmp_idx = random.randint(0, len(collection)-1) tmp_ind: IndividualLike = collection[tmp_idx] bin_coord = collection.index_grid(tmp_ind) bin_pop = collection.solutions[bin_coord] return sel_roulette(bin_pop)
########### MUTATIONS ########### {{{1 ## @brief Generate real-valued offspring with independent and directional noise.
[docs] def iso_line_dd(first, second, *, iso_sigma=0.01, line_sigma=0.2, bounds=None, rng=None): """Return an Iso+LineDD offspring as a new NumPy vector. Each coordinate receives independent isotropic noise. One Gaussian draw scales the difference between the parents for the entire offspring. :param first: Base parent vector. :param second: Parent defining the direction from the base. :param iso_sigma: Standard deviation of independent coordinate noise. :param line_sigma: Standard deviation of the shared direction coefficient. :param bounds: Optional lower and upper coordinate bounds for clipping. :param rng: Random generator. By default use NumPy's global random stream. """ first = np.asarray(first, dtype=float) second = np.asarray(second, dtype=float) if first.ndim != 1 or first.size == 0 or first.shape != second.shape: raise ValueError("Iso+LineDD requires two matching nonempty vectors.") if not (0 <= iso_sigma < np.inf and 0 <= line_sigma < np.inf): raise ValueError("Iso+LineDD scales must be finite and nonnegative.") rng = np.random if rng is None else rng child = first + iso_sigma * rng.normal(size=first.size) + line_sigma * rng.normal() * (second - first) return np.clip(child, *bounds) if bounds is not None else child
## @brief Combine independently varied parents using a segment crossover mask.
[docs] def iso_line_cross(first, second, *, iso_sigma=0.005, line_sigma=0.05, crossover_probability=0.5, crossover_rate=0.1, bounds=None, rng=None): """Return one IsoLineCross offspring without changing its parents. Apply Iso+LineDD in both directions and alternate parental segments at the scaled cumulative exponential breakpoints. Set line_sigma to zero for IsoCross. A zero crossover probability consumes the same random draws as Iso+LineDD. :param first: Base parent vector. :param second: Other parent vector with the same shape. :param iso_sigma: Isotropic noise scale. :param line_sigma: Directional noise scale. :param crossover_probability: Probability of mixing the two varied vectors. :param crossover_rate: Number of sampled breakpoints per gene, in [0, 1]. :param bounds: Optional clipping bounds. :param rng: Generator or the default NumPy global stream. """ if not (0 <= crossover_probability <= 1 and 0 <= crossover_rate <= 1): raise ValueError("Crossover probability and rate must be in [0, 1].") rng = np.random if rng is None else rng offspring = iso_line_dd(first, second, iso_sigma=iso_sigma, line_sigma=line_sigma, bounds=bounds, rng=rng) size = len(offspring) if size == 1 or crossover_probability == 0 or rng.random() >= crossover_probability: return offspring other = iso_line_dd(second, first, iso_sigma=iso_sigma, line_sigma=line_sigma, bounds=bounds, rng=rng) spacing = np.cumsum(rng.exponential(size=max(1, int(crossover_rate * size)))) # An all-zero draw would have no meaningful normalized breakpoints. positions = (spacing / spacing[-1] * (size - 1)).astype(np.intp) if spacing[-1] else np.full( len(spacing), size - 1, dtype=np.intp) swap = np.searchsorted(positions, np.arange(size), side="right") % 2 == 1 return np.where(swap, other, offspring)
[docs] def mut_gaussian(individual: MutableSequence[Any], mu: float, sigma: float, mut_pb: float, bounds: Optional[Sequence[float]] = None) -> MutableSequence[Any]: """Add Gaussian noise to selected coordinates in place. :param individual: Mutable genome to vary. :param mu: Mean of the perturbation. :param sigma: Standard deviation of the perturbation. :param mut_pb: Per-coordinate selection probability. :param bounds: Optional common lower and upper clipping bounds. :returns: The same mutated genome object. """ for i in range(len(individual)): if random.random() < mut_pb: individual[i] += random.gauss(mu, sigma) if bounds is not None and len(bounds) > 1: individual[:] = np.clip(individual[:],bounds[0],bounds[1]) return individual
[docs] def mut_polynomial_bounded(individual: MutableSequence[Any], eta: float, low: float, up: float, mut_pb: float, *, rng=None) -> MutableSequence[Any]: """Apply bounded polynomial mutation to selected coordinates in place. Use a strictly ordered interval and start with a genome inside its bounds. The operator uses Deb's polynomial distribution and clips the mutated coordinates to that interval. :param individual: Mutable genome to vary. :param eta: Distribution index controlling typical change size. :param low: Lower bound shared by the coordinates. :param up: Upper bound shared by the coordinates. :param mut_pb: Per-coordinate selection probability. :param rng: Optional random generator. Defaults to Python's random module. :returns: The same mutated genome object. """ rng = random if rng is None else rng for i in range(len(individual)): if rng.random() < mut_pb: x = individual[i] delta_1 = (x - low) / (up - low) delta_2 = (up - x) / (up - low) rand = rng.random() mut_pow = 1. / (eta + 1.) if rand < 0.5: xy = 1. - delta_1 val = 2. * rand + (1. - 2. * rand) * xy**(eta + 1.) delta_q = val**mut_pow - 1. else: xy = 1. - delta_2 val = 2. * (1. - rand) + 2. * (rand - 0.5) * xy**(eta + 1.) delta_q = 1. - val**mut_pow x += delta_q * (up - low) x = min(max(x, low), up) individual[i] = x return individual
########### COMBINED OPERATORS ########### {{{1 def sel_or_init(collection: Sequence[IndividualLike], base_ind: IndividualLike, sel_fn: Callable, sel_pb: float, init_fn: Callable, init_pb: float = 0., return_flag: bool = True): """Either select an individual from `collection` by using function `sel_pb`, or initialise a new individual by using function `init_pb`. If `collection` is empty, it will always initialise a new individual, not perform selection. Parameters ---------- :param collection: Sequence[IndividualLike] The individuals to select from. :param base_ind: IndividualLike The base individual to initialise. :param sel_fn: Callable The selection function. :param sel_pb: float The probability of performing selection. :param init_fn: Callable The initialisation function. :param init_pb: float The probability of performing initialisation. :param return_flag: bool If set to True, the function will return a Tuple[IndividualLike, bool] with a first item corresponding to the selected or initialised individual, and the second item a flag set to True if the first item was selected, and set to False if it was initialised. If set to False, the function will return the selected or initialised IndividualLike. """ def ret(res, f): return (res, f) if return_flag else res if len(collection) == 0: return ret(init_fn(base_ind), False) if type(sel_pb) is type(init_pb) is float and sel_pb == init_pb == 0.5: # choice with explicit probabilities uses this same draw and cutoff. selected = np.random.random_sample() < 0.5 else: selected = np.random.choice(range(2), p=[sel_pb, init_pb]) == 0 if selected: return ret(sel_fn(collection), True) return ret(init_fn(base_ind), False) def mut_or_cx(individuals: Union[IndividualLike, Sequence[IndividualLike]], mut_fn: Callable, cx_fn: Callable) -> Sequence[IndividualLike]: """Either perform a mutation (using function `mut_fn`) or a crossover (using function `cx_fn`) depending on the nature and length of `individuals`. If `individuals` is an IndividualLike or a Sequence of one IndividualLike, a mutation will be performed. If `individuals` is a Sequence of two IndividualLike, a crossover will be performed. Parameters ---------- :param individuals: Union[IndividualLike, Sequence[IndividualLike]] The individual(s) to mutate or crossover. :param mut_fn: Callable The mutation function. :param cx_fn: Callable The crossover function. Return ------ The resulting individual(s). """ if isinstance(individuals, IndividualLike): return [mut_fn(individuals)] elif isinstance(individuals, Sequence) and len(individuals) == 1: return [mut_fn(individuals[0])] elif isinstance(individuals, Sequence) and len(individuals) > 1: return cx_fn(individuals) else: raise ValueError(f'`individuals` can be an Individual or a Sequence.') class _ResultUnpickler(pickle.Unpickler): """Resolve historical phenotype globals independently of import order.""" def find_class(self, module, name): if module == "qdpy.base" and name in {"Individual", "Fitness", "Features", "Score", "ScoresDict"}: module = "qdpy.phenotype" return super().find_class(module, name)
[docs] def open_pickle_file(filename): """Deserialize a trusted result file. Standard native result dictionaries include the container and may include evaluation and iteration tables. Recreate older runs with the current version when their fitness snapshot format is unsupported. """ with open(filename, "rb") as file: return _ResultUnpickler(file).load()
# MODELINE "{{{1 # vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8 # vim:foldmethod=marker