QDpy
Loading...
Searching...
No Matches
gsemo_d.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Keep one representative per nondominated objective vector."""
7
8from dataclasses import dataclass
9from operator import index
10
11import numpy as np
12
13from ._population import _attempt_budget, _finite_vector
14from .modern import _positive_int
15
16__all__ = ["GSEMOD", "GSEMODStats", "BinaryParetoPoint"]
17
18
19
20@dataclass(frozen=True, slots=True)
22 """An immutable snapshot of one Pareto representative."""
23
24 genome: tuple[int, ...]
25 objectives: tuple[float, ...]
26
27
28
29@dataclass(frozen=True, slots=True)
31 """Unevaluated or failed candidates do not contribute to imbalance."""
32
33 evaluations: int
34 failures: int
35 admissions: int
36 tie_replacements: int
37 population_size: int
38 imbalance: tuple[int, ...]
39
40 @property
41 def total_imbalance(self):
42 """Return the sum of absolute zero/one count differences."""
43 return sum(self.imbalance)
44
45
46def _dominates(left, right):
47 """Compare different objective vectors by weak coordinate dominance."""
48 return all(a >= b for a, b in zip(left, right))
49
50
51
52class GSEMOD:
53 """Run Antipov et al.'s GSEMO with diversity-aware tie replacement.
54
55 Sample a parent uniformly and flip each bit independently with
56 probability 1/dimension. For a previously seen objective vector,
57 replace its incumbent if population imbalance improves or ties.
58 For other vectors, use Pareto dominance on maximization objectives.
59
60 :param dimension: Number of bits per solution.
61 :param diversity: ``total`` minimizes summed imbalance and ``lexicographic``
62 minimizes the sorted imbalance vector. ``none`` is the GSEMO control.
63 :param initial: Optional binary starting genome.
64 :param seed: Seed for variation, parent selection, and evaluator calls.
65 """
66
67 def __init__(self, dimension, *, diversity="total", initial=None, seed=0):
68 self._dimension = _positive_int(dimension, "dimension")
69 if diversity not in ("total", "lexicographic", "none"):
70 raise ValueError("Choose total, lexicographic, or none diversity.")
71 self._diversity = diversity
72 self._initial = None if initial is None else tuple(map(index, initial))
73 if self._initial is not None and (len(self._initial) != self._dimension or set(self._initial) - {0, 1}):
74 raise ValueError("initial must match dimension and contain only zero or one.")
75 self._rng, self._evaluation = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
76 self._population = {}
77 self._ones = np.zeros(dimension, dtype=int)
78 self._objectives = None
79 self._evaluations = self._failures = self._admissions = self._ties = 0
80
81 @property
82 def population(self):
83 """Return the nondominated representatives in admission order."""
84 return tuple(BinaryParetoPoint(bits, objectives) for objectives, bits in self._population.items())
85
86 @property
87 def stats(self):
88 """Return a snapshot of attempted evaluations and population diversity."""
89 return GSEMODStats(self._evaluations, self._failures, self._admissions, self._ties,
90 len(self._population), tuple(map(int, self._imbalance(self._ones))))
91
92 def _imbalance(self, ones):
93 return np.abs(ones * 2 - len(self._population))
94
95 def _diversity_key(self, ones):
96 imbalance = self._imbalance(ones)
97 return int(imbalance.sum()) if self._diversity == "total" else tuple(sorted(imbalance, reverse=True))
98
99 def _offer(self, genome, objectives):
100 previous = self._population.get(objectives)
101 if previous is not None:
102 if genome == previous:
103 return
104 replacement = self._ones + np.asarray(genome) - np.asarray(previous)
105 if self._diversity != "none" and self._diversity_key(replacement) > self._diversity_key(self._ones):
106 return
107 self._population[objectives], self._ones = genome, replacement
108 self._ties += 1
109 elif not any(_dominates(other, objectives) for other in self._population):
110 for other in [other for other in self._population if _dominates(objectives, other)]:
111 self._ones -= self._population.pop(other)
112 self._population[objectives] = genome
113 self._ones += genome
114 self._admissions += 1
115
116
120 def run(self, evaluate, budget):
121 """Continue from the last Pareto population and random state."""
122 for _ in range(_attempt_budget(budget)):
123 if self._population:
124 parents = tuple(self._population.values())
125 parent = parents[self._rng.integers(len(parents))]
126 changed = self._rng.random(self._dimension) < 1. / self._dimension
127 genome = tuple(map(int, np.bitwise_xor(parent, changed)))
128 elif self._initial is not None:
129 genome = self._initial
130 else:
131 genome = tuple(map(int, self._rng.integers(2, size=self._dimension)))
132 self._evaluations += 1
133 result = evaluate(genome, int(self._evaluation.integers(2**32)))
134 if result is None:
135 self._failures += 1
136 continue
137 objectives = _finite_vector(result, "Objective vector", self._objectives)
138 self._objectives = len(objectives)
139 self._offer(genome, objectives)
140 return self.stats
An evaluated binary solution and its maximization objectives.
Definition gsemo_d.py:21
Track Pareto admissions and per-locus population imbalance.
Definition gsemo_d.py:30
Run GSEMO and choose objective ties using the diversity of the complete population.
Definition gsemo_d.py:52
_offer(self, genome, objectives)
Definition gsemo_d.py:99
run(self, evaluate, budget)
Grow or diversify the Pareto population within an additional evaluation budget.
Definition gsemo_d.py:120