QDpy
Loading...
Searching...
No Matches
dissimilarity_nsga.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Pareto evolution with dissimilarity-based crowding."""
7
8from dataclasses import dataclass
9
10import numpy as np
11
12from ._population import _attempt_budget, _finite_vector, _mean_dissimilarity, _nsga_order, _tournament
13from .modern import _positive_int
14
15__all__ = ["DiversityEnhancingNSGAII", "DissimilarityEntry", "DissimilarityStats"]
16
17
18
19@dataclass(frozen=True)
21 """The behavior object is passed to user-supplied dissimilarity functions."""
22
23 genome: tuple
24 objectives: tuple[float, ...]
25 behavior: object
26
27
28
29@dataclass(frozen=True)
31 """Separate failed measurement attempts from committed generations."""
32
33 evaluations: int
34 failures: int
35 generations: int
36
37
38
40 """Apply DE-NSGA-II to encodings with an application-defined distance.
41
42 Each merged population receives an extra objective equal to mean
43 behavioral dissimilarity. Its Pareto ranks guide survival and
44 tournament selection. To break rank ties, the default uses average
45 behavioral dissimilarity. A separate callback can use the genomes.
46
47 :param objective_count: Number of raw objectives.
48 :param sample: Callable (rng) returning a genome.
49 :param mutate: Callable (parent_genome, rng) returning an offspring.
50 :param distance: Symmetric nonnegative callable over two behavior objects.
51 Treat the genome elements and observed behavior as immutable.
52 :param crowding_distance: Optional symmetric callable over two DissimilarityEntry
53 instances. Omit it to share the diversity objective's distance matrix.
54 :param population_size: Parent and offspring population capacity.
55 :param maximize: A Boolean or one Boolean direction per objective.
56 :param standard_crowding: Use standard objective-space NSGA-II crowding for an ablation.
57 :param seed: Private sampling and evaluation seed.
58 """
59
60 def __init__(self, objective_count, *, sample, mutate, distance, crowding_distance=None,
61 population_size=32, maximize=True, standard_crowding=False, seed=0):
62 self._objective_count = _positive_int(objective_count, "objective_count")
63 self._size = _positive_int(population_size, "population_size")
64 if not all(map(callable, (sample, mutate, distance))) or (
65 crowding_distance is not None and not callable(crowding_distance)):
66 raise TypeError("Supply callable variation and dissimilarity functions.")
67 directions = np.asarray(maximize)
68 if directions.dtype.kind != "b" or directions.shape not in ((), (self._objective_count,)):
69 raise ValueError("maximize must supply a Boolean or one Boolean per objective.")
70 self._sign = np.broadcast_to(np.where(directions, 1., -1.), (self._objective_count,))
71 self._sample, self._mutate = sample, mutate
72 self._distance, self._crowding = distance, crowding_distance
73 self._standard = standard_crowding
74 self._variation, self._evaluation = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
75 self._population, self._keys = (), ()
76 self._children = []
77 self._pending = self._evaluations = self._failures = self._generations = 0
78
79 @property
80 def population(self):
81 """Return survivors from the last completed selection, in tournament order."""
82 return self._population
83
84 @property
85 def stats(self):
86 """Return cumulative evaluation attempts and completed selections."""
88
89 def _commit(self):
90 candidates = self._population + tuple(self._children)
91 if candidates:
92 diversity = _mean_dissimilarity([row.behavior for row in candidates], self._distance)
93 objectives = self._sign * np.asarray([row.objectives for row in candidates])
94 crowding = None
95 if not self._standard:
96 crowding = diversity if self._crowding is None else _mean_dissimilarity(candidates, self._crowding)
97 ordered, keys = _nsga_order(np.column_stack((objectives, diversity)), self._size, crowding)
98 self._population = tuple(candidates[i] for i in ordered)
99 self._keys = keys
100 self._children.clear()
101 self._pending = 0
102 self._generations += 1
103
104
108 def run(self, evaluate, budget):
109 """Spend the budget and keep an unfinished offspring batch for a later call."""
110 budget = _attempt_budget(budget)
111 if self._pending == self._size:
112 self._commit()
113 for _ in range(budget):
114 if self._population:
115 parent = _tournament(self._population, self._keys, self._variation)
116 genome = tuple(self._mutate(parent.genome, self._variation))
117 else:
118 genome = tuple(self._sample(self._variation))
119 self._evaluations += 1
120 result = evaluate(genome, int(self._evaluation.integers(2**32)))
121 if result is None:
122 self._failures += 1
123 else:
124 objectives, behavior = result
125 values = _finite_vector(objectives, "Objectives", self._objective_count)
126 self._children.append(DissimilarityEntry(genome, values, behavior))
127 self._pending += 1
128 if self._pending == self._size:
129 self._commit()
130 return self.stats
An evaluated solution with raw quality objectives and a behavior object.
Cumulative evaluation and generation counts.
Rank by quality and average diversity, then crowd by dissimilarity.
run(self, evaluate, budget)
Breed and evaluate additional slots, then select from the merged population.