Source code for qdpy.algorithms.evolutionary_portfolios

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Evolutionary multi-objective diversity optimization over binary portfolios.
# @see https://doi.org/10.1007/978-3-031-70085-9_8

"""Evolve sets as individuals, using member quality and within-set diversity."""

from dataclasses import dataclass
from math import fsum, isfinite

import numpy as np
from scipy.spatial.distance import cdist

from ._population import _attempt_budget, _nsga_order, _pareto_fronts, _tournament
from .modern import _positive_int

__all__ = ["EvolutionaryPortfolio", "EvolutionaryPortfolioResult", "evolutionary_portfolios"]


## @brief Store one evaluated set and its measured quality and diversity objectives.
[docs] @dataclass(frozen=True, slots=True) class EvolutionaryPortfolio: """The diversity is the sum of Hamming distances over unordered member pairs.""" members: tuple[tuple[int, ...], ...] member_qualities: tuple[float, ...] quality: float diversity: int
## @brief Return the final nondominated portfolios and exact search accounting.
[docs] @dataclass(frozen=True, slots=True) class EvolutionaryPortfolioResult: """The evaluation budget counts calls for each member, including failures and repeats.""" portfolios: tuple[EvolutionaryPortfolio, ...] member_evaluations: int failed_members: int portfolio_attempts: int generations: int
def _binary(bits, name, width=None): bits = np.asarray(bits) if bits.ndim != 1 or not bits.size or (width is not None and len(bits) != width) or not np.isin(bits, (0, 1)).all(): raise ValueError(f"{name} must be a nonempty binary vector of the configured length.") return tuple(map(int, bits)) def _hamming_total(descriptors): ones = np.sum(descriptors, axis=0, dtype=np.int64) return int(sum(int(count) * (len(descriptors) - int(count)) for count in ones)) def _spea2_order(scores, capacity): dominates = ((scores[:, None] >= scores).all(axis=2) & (scores[:, None] > scores).any(axis=2)) raw = dominates.T @ dominates.sum(axis=1) # A common normalized scale keeps the density tie-break comparable across objectives. scaled = scores / np.maximum(1., np.abs(scores).max(axis=0)) width = np.ptp(scaled, axis=0) distances = cdist(scaled / np.where(width, width, 1.), scaled / np.where(width, width, 1.)) np.fill_diagonal(distances, np.inf) k = min(int(np.sqrt(len(scores))) - 1, len(scores) - 1) fitness = raw + 1. / (2. + np.partition(distances, k, axis=1)[:, k]) selected = np.flatnonzero(raw == 0).tolist() if len(selected) <= capacity: selected = np.argsort(fitness, kind="stable")[:capacity].tolist() else: while len(selected) > capacity: neighborhood = np.sort(distances[np.ix_(selected, selected)], axis=1) crowded = min(range(len(selected)), key=lambda i: (tuple(neighborhood[i]), -selected[i])) selected.pop(crowded) return selected, [(fitness[i],) for i in selected] ## @brief Evolve binary portfolios with paper-style aligned crossover and a set-level Pareto front. # @param evaluate Callable (bits) returning scalar quality to maximize or None for a failed member. # @param dimension Number of decision bits per member. # @param portfolio_size Number of member slots per portfolio. # @param budget Total member evaluation attempts. A partial portfolio is never started. # @param population_size Number of live portfolios and maximum offspring batch size. # @param quality Portfolio quality reducer, "mean" or "worst". # @param method Population selection method, "nsga2", "spea2", or "uniform" control. # @param crossover_probability Probability of aligned uniform crossover. # @param mutation_probability Optional probability per bit, default 0.5/dimension. # @param descriptor Optional callable (bits) returning a binary vector used for Hamming diversity. # @param repair Optional callable (bits) returning a valid binary member before evaluation. # @param seed Private variation and parent-selection seed. # @return Nondominated portfolios and measurement accounting.
[docs] def evolutionary_portfolios(evaluate, *, dimension, portfolio_size, budget, population_size=20, quality="mean", method="nsga2", crossover_probability=.8, mutation_probability=None, descriptor=None, repair=None, seed=0): """Treat a concatenation of member bit strings as a single evolutionary individual. Uniform crossover shuffles the second parent's member order before exchanging bits. Mutation flips bits independently. The optional descriptor changes the space where Hamming distances are computed, for example from vertex indicators to cut-edge indicators. Every member slot is evaluated. Repeated designs are allowed and contribute zero pair distance to an identical descriptor. A failed member excludes its portfolio from selection. Pass a repair callback to enforce constraints before evaluation, or handle them in the evaluator. The uniform control uses random proposals and the same bounded NSGA-II survival rule. """ dimension = _positive_int(dimension, "dimension") portfolio_size = _positive_int(portfolio_size, "portfolio_size") population_size = _positive_int(population_size, "population_size") budget = _attempt_budget(budget) if method not in ("nsga2", "spea2", "uniform") or quality not in ("mean", "worst"): raise ValueError("Choose nsga2, spea2, or uniform and mean or worst portfolio quality.") rate = .5 / dimension if mutation_probability is None else mutation_probability if not (0. <= crossover_probability <= 1. and 0. <= rate <= 1.): raise ValueError("Mutation and crossover probabilities must be in [0, 1].") if not callable(evaluate) or any(callback is not None and not callable(callback) for callback in (descriptor, repair)): raise TypeError("Supply a callable evaluator and optional descriptor and repair callbacks.") rng = np.random.default_rng(seed) population, keys = [], [] attempts = failures = generations = 0 descriptor_width = None while (count := min(population_size, budget // portfolio_size - attempts)) > 0: children = [] for _ in range(count): if not population or method == "uniform": bits = rng.integers(2, size=(portfolio_size, dimension)) else: first = np.asarray(_tournament(population, keys, rng).members) if rng.random() < crossover_probability: second = np.asarray(_tournament(population, keys, rng).members)[rng.permutation(portfolio_size)] first = np.where(rng.random(first.shape) < .5, first, second) bits = np.bitwise_xor(first, rng.random(first.shape) < rate) members, values, descriptors = [], [], [] attempts += 1 for row in bits: member = tuple(map(int, row)) if repair is not None: member = _binary(repair(member), "Repaired member", dimension) result = evaluate(member) if result is None: failures += 1 continue value = float(result) if not isfinite(value): raise ValueError("Member quality must be finite.") measured = member if descriptor is None else _binary(descriptor(member), "Descriptor", descriptor_width) descriptor_width = len(measured) members.append(member) descriptors.append(measured) values.append(value) if len(members) == portfolio_size: score = min(values) if quality == "worst" else fsum(value / portfolio_size for value in values) children.append(EvolutionaryPortfolio(tuple(members), tuple(values), score, _hamming_total(descriptors))) combined = population + children if combined: scores = np.asarray([(row.quality, row.diversity) for row in combined]) survivor = _spea2_order if method == "spea2" else _nsga_order selected, keys = survivor(scores, population_size) population = [combined[i] for i in selected] generations += 1 front = {} if population: scores = np.asarray([(row.quality, row.diversity) for row in population]) for i in next(_pareto_fronts(scores)): row = population[i] front.setdefault((row.quality, row.diversity), row) return EvolutionaryPortfolioResult(tuple(front[key] for key in sorted(front, reverse=True)), attempts * portfolio_size, failures, attempts, generations)