Source code for qdpy.containers.pareto

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Bounded Pareto fronts in descriptor grid cells.

"""Pareto grid admission and two-objective hypervolume."""

from collections import defaultdict
from itertools import groupby
from math import dist, isfinite
from operator import index
import random

import numpy as np

from qdpy.base import registry
from qdpy.phenotype import Fitness
from .base import Container
from .grids import Grid

__all__ = ["ParetoGrid", "LocalParetoArchive"]

_PARETO_SCALARS = frozenset((int, float, np.float16, np.float32, np.float64))
_DOUBLE_SCALARS = frozenset((float, np.float64))
_PYTHON_SCALARS = frozenset((int, float))


## @brief Find nondominated slots for two finite weighted objectives.
def _sweep_front(fitnesses):
    """Return slots in storage order, or None for general dominance."""
    points = []
    types = set()
    try:
        with np.errstate(over="raise", under="raise", invalid="raise"):
            for fitness in fitnesses:
                if (type(fitness) is not Fitness or fitness.__dict__.keys() != {"weights", "_values"}
                        or type(fitness.values) is not tuple or type(fitness.weights) is not tuple
                        or len(fitness.values) != 2 or len(fitness.weights) != 2
                        or any(type(value) not in _PARETO_SCALARS for value in (*fitness.values, *fitness.weights))):
                    return None
                point = fitness.weighted_values(fitness.weights)
                if not all(map(isfinite, point)):
                    return None
                points.append(point)
                types.update(map(type, point))
    except (FloatingPointError, OverflowError):
        # Let the general comparisons apply the caller's NumPy error policy.
        return None
    if len(types) > 1 and not (types <= _DOUBLE_SCALARS or types <= _PYTHON_SCALARS):
        # Mixed NumPy precisions can round the other operand during comparison.
        return None

    order = sorted(range(len(points)), key=points.__getitem__, reverse=True)
    front = []
    best_second = -np.inf
    for _, group in groupby(order, key=lambda slot: points[slot][0]):
        first = next(group)
        second = points[first][1]
        if second > best_second:
            front.append(first)
            front.extend(slot for slot in group if points[slot][1] == second)
            best_second = second
    # Keep the same list order for both admission and seeded random.sample().
    return sorted(front)


def _hypervolume_2d(points, reference):
    """Sweep the union of rectangles in maximisation coordinates."""
    area = 0.0
    height = reference[1]
    for x, y in sorted(points, reverse=True):
        if x < reference[0] or y < reference[1]:
            raise ValueError("The reference point must be weakly dominated by every scored point.")
        if y > height:
            area += (x - reference[0]) * (y - height)
            height = y
    return area


def _volume_front(front, fitnesses, capacity, directions, domain):
    domain = np.asarray(domain, dtype=float)
    lower, upper = np.min(domain * directions[:, None], axis=1), np.max(domain * directions[:, None], axis=1)
    points = (directions * np.asarray([fitness.values for fitness in fitnesses]) - lower) / (upper - lower)
    front = list(front)
    while len(front) > capacity:
        # Removing the smallest contributor leaves the highest remaining volume.
        remove = max(range(len(front)), key=lambda i: (
            _hypervolume_2d(map(tuple, points[front[:i] + front[i + 1:]]), (0., 0.)), i))
        del front[remove]
    return front


def _crowding_distance(points):
    """Sum normalized neighbor gaps in objective space, preserving extremes."""
    points = np.asarray(points, dtype=float)
    distance = np.zeros(len(points))
    if len(points) <= 2:
        distance.fill(np.inf)
        return distance
    for axis in points.T:
        order = np.argsort(axis, kind="stable")
        values = axis[order]
        # Scaling first keeps extreme finite ranges representable.
        maximum = np.max(np.abs(values))
        scaled = values / maximum if maximum else values
        span = scaled[-1] - scaled[0]
        if span:
            distance[order[[0, -1]]] = np.inf
            distance[order[1:-1]] += (scaled[2:] - scaled[:-2]) / span
    return distance


def _sampling_crowding(points):
    """Use finite one-sided neighbour gaps at each objective's boundaries."""
    points = np.asarray(points, dtype=float)
    distance = np.zeros(len(points))
    if len(points) < 2:
        return distance
    for axis in points.T:
        order = np.argsort(axis, kind="stable")
        scale = np.abs(axis).max() or 1.
        values = axis[order] / scale
        span = values[-1] - values[0]
        if span:
            gaps = np.diff(values) / span
            distance[order[0]] += gaps[0]
            distance[order[-1]] += gaps[-1]
            distance[order[1:-1]] += .5 * (gaps[:-1] + gaps[1:])
    return distance


def _crowded_front(front, fitnesses, capacity):
    """Evict the most crowded point repeatedly and favor incumbents on ties."""
    front = list(front)
    while len(front) > capacity:
        distances = _crowding_distance([fitnesses[slot].values for slot in front])
        tied = np.flatnonzero(distances == distances.min())
        del front[tied[-1]]
    return front


## @brief Store a bounded nondominated front in each occupied grid cell.
[docs] @registry.register class ParetoGrid(Grid): """A descriptor grid with configurable truncation of overfull Pareto fronts. Configure the objective directions before adding candidates. Bounds and bin geometry follow Grid. This archive uses local storage without parents. :param shape: Number of bins along each descriptor coordinate. :param max_items_per_bin: Maximum number of nondominated entries per cell. :param fitness_domain: One interval per objective. :param features_domain: One interval per descriptor coordinate. :param fitness_weights: Signed weights. The default minimises each objective. :param truncation: Choose "random", normalized "crowding", or "hypervolume" contribution with two objectives and finite fitness intervals. """ def __init__(self, iterable=None, *, shape, max_items_per_bin, fitness_domain, features_domain, fitness_weights=None, name=None, truncation="random"): cap = index(max_items_per_bin) if cap < 1 or len(fitness_domain) < 2: raise ValueError("ParetoGrid needs positive front capacity and at least two objectives.") if fitness_weights is None: fitness_weights = (-1.0,) * len(fitness_domain) if len(fitness_weights) != len(fitness_domain) or not all(np.isfinite(w) and w != 0 for w in fitness_weights): raise ValueError("Provide one finite, nonzero weight per objective.") if truncation not in ("random", "crowding", "hypervolume"): raise ValueError("Choose random, crowding, or hypervolume Pareto truncation.") if truncation == "hypervolume": spans = [float(upper) - float(lower) for lower, upper in fitness_domain] if len(spans) != 2 or not all(0. < span < np.inf for span in spans): raise ValueError("Hypervolume truncation needs two finite, positive fitness spans.") self.truncation = truncation super().__init__(iterable, shape=shape, max_items_per_bin=cap, fitness_domain=fitness_domain, features_domain=features_domain, fitness_weights=tuple(fitness_weights), name=name) def _set_fitness_weights(self, weights): if len(weights) != len(self.fitness_domain) or not all(np.isfinite(w) and w != 0 for w in weights): raise ValueError("Provide one finite, nonzero weight per objective.") if len(self) and tuple(weights) != tuple(self.fitness_weights): raise ValueError("Set the objective weights before populating a ParetoGrid.") super()._set_fitness_weights(weights) ## @brief Read the nondominated entries in a descriptor cell.
[docs] def front(self, cell): """Return the stored front as a tuple of live individual references.""" return tuple(self.solutions[cell])
def _merge_fronts(self, candidates, *, truncation_rng=random): """Choose fronts before applying any removals or admissions.""" incoming = defaultdict(list) seen = [] for ind in candidates: if self._index_of(ind) is None and ind not in seen: incoming[self.index_grid(ind)].append(ind) seen.append(ind) retained = {} for cell, offspring in incoming.items(): merged = self.solutions[cell] + offspring fitnesses = [self.get_ind_fitness(ind) for ind in merged] front = _sweep_front(fitnesses) if len(fitnesses) >= 4 else None if front is None: front = [ slot for slot, fitness in enumerate(fitnesses) if not any(other.dominates(fitness) for other in fitnesses) ] if len(front) > self.max_items_per_bin: truncation = getattr(self, "truncation", "random") if truncation == "crowding": front = _crowded_front(front, fitnesses, self.max_items_per_bin) elif truncation == "hypervolume": front = _volume_front(front, fitnesses, self.max_items_per_bin, np.sign(self.fitness_weights), self.fitness_domain) else: front = sorted(truncation_rng.sample(front, self.max_items_per_bin)) retained[cell] = [merged[slot] for slot in front] admitted = set() for cell, front in retained.items(): old = self.solutions[cell].copy() old_ids = {id(ind) for ind in old} kept_ids = {id(ind) for ind in front} for ind in old: if id(ind) not in kept_ids: self.discard(ind) for ind in front: if id(ind) not in old_ids: self._add_to_grid(ind, cell, False) admitted.add(id(ind)) return admitted def _add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents): if only_to_parents: return None stored = self._index_of(individual) if stored is not None: return stored admitted = self._merge_fronts([individual]) return self._index_of(individual) if id(individual) in admitted else None def _check_if_can_be_added(self, individual): super()._check_if_can_be_added(individual) values = self.get_ind_fitness(individual).values if not all(np.isfinite(value) for value in values): raise ValueError("ParetoGrid requires finite objective values.") self.index_grid(individual) def _hypervolume(self, candidates, reference): ref = np.asarray(reference, dtype=float) if len(self.fitness_domain) != 2 or ref.shape != (2,) or not np.all(np.isfinite(ref)): raise ValueError("Hypervolume requires two objectives and a finite two-coordinate reference point.") direction = np.sign(self.fitness_weights) points = [tuple(direction * self.get_ind_fitness(ind).values) for ind in candidates] return float(_hypervolume_2d(points, direction * ref)) ## @brief Measure the two-objective hypervolume of one cell.
[docs] def cell_hypervolume(self, cell, reference): """Return the front's hypervolume with a reference in raw objective units.""" return self._hypervolume(self.solutions[cell], reference)
## @brief Sum the two-objective hypervolumes across descriptor cells.
[docs] def qd_hypervolume(self, reference): """Return the sum of per-cell hypervolumes with a shared raw reference.""" return sum(self._hypervolume(front, reference) for front in self.solutions.values())
## @brief Measure the two-objective hypervolume of all retained solutions.
[docs] def global_hypervolume(self, reference): """Return the union hypervolume across all fronts with a raw reference.""" return self._hypervolume(self, reference)
## @brief Store locally nondominated solutions in continuous descriptor space.
[docs] @registry.register class LocalParetoArchive(Container): """Apply the fixed-radius MOUR-QD admission rule in descriptor units. Each candidate competes with incumbents at Euclidean distance strictly below the radius. A dominated candidate leaves the archive unchanged. Otherwise it enters and removes every incumbent it dominates nearby. Equal genomes keep their first retained evaluation. Distinct genomes with equal objective values can coexist. :param iterable: Initial candidates, admitted in the supplied order. :param radius: Positive finite distance threshold. :param descriptor_size: Number of finite descriptor coordinates. :param fitness_weights: Two or more signed, finite nonzero weights. :param fitness_domain: Optional intervals in raw objective units. :param capacity: Optional limit on archive entries. At capacity, a new entry must replace at least one incumbent. :param name: Display name used by loggers. """ def __init__(self, iterable=None, *, radius, descriptor_size, fitness_weights, fitness_domain=None, capacity=None, name=None): if not isfinite(radius) or radius <= 0: raise ValueError("Provide a finite positive radius.") descriptor_size = index(descriptor_size) if descriptor_size < 1: raise ValueError("Provide a positive descriptor size.") weights = tuple(fitness_weights) if len(weights) < 2 or any(not isfinite(weight) or weight == 0 for weight in weights): raise ValueError("Provide at least two finite nonzero objective weights.") if fitness_domain is None: fitness_domain = ((-np.inf, np.inf),) * len(weights) if len(fitness_domain) != len(weights): raise ValueError("Provide one objective interval per weight.") if capacity is not None: capacity = index(capacity) if capacity < 1: raise ValueError("Provide a positive capacity.") self.radius = radius self.descriptor_size = descriptor_size super().__init__(iterable, fitness_domain=fitness_domain, fitness_weights=weights, capacity=capacity, name=name) def _set_fitness_weights(self, weights): if len(weights) != len(self.fitness_domain) or any(not isfinite(w) or w == 0 for w in weights): raise ValueError("Provide one finite nonzero weight per objective.") if len(self) and tuple(weights) != self.fitness_weights: raise ValueError("Set the objective weights before populating a LocalParetoArchive.") super()._set_fitness_weights(weights) def _check_if_can_be_added(self, individual): super()._check_if_can_be_added(individual) fitness = self.get_ind_fitness(individual) features = self.get_ind_features(individual) if (len(features) != self.descriptor_size or not all(map(isfinite, features)) or not all(map(isfinite, fitness.weighted_values(self.fitness_weights)))): raise ValueError("LocalParetoArchive requires finite objectives and descriptors of the configured size.") ## @brief Check local dominance and commit the surviving measurement. # @param individual Validated candidate to compare with neighbors. # @param raise_if_not_added_to_parents Base admission option. # @param only_to_parents Decline parent-only offers. def _add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents): if only_to_parents: return None stored = self._index_of(individual) if stored is not None: return stored features = tuple(self.get_ind_features(individual)) fitness = self.get_ind_fitness(individual) dominated = [] for slot, incumbent in enumerate(self): if dist(features, self.get_ind_features(incumbent)) < self.radius: other = self.get_ind_fitness(incumbent) if other.dominates(fitness): return None if fitness.dominates(other): dominated.append(slot) if self.free < 1 and not dominated: return None replace_index = dominated.pop() if dominated else None slot = super()._add_internal(individual, raise_if_not_added_to_parents, False, replace_index=replace_index) for old_slot in reversed(dominated): self._discard_by_index(self.items[old_slot], old_slot) return slot - len(dominated)