QDpy
Loading...
Searching...
No Matches
symmetry_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Evaluate each canonical design at most once in a deterministic search."""
7
8from collections import Counter
9from dataclasses import dataclass
10
11import numpy as np
12
13from .modern import _positive_int
14from .task_search import _measurement, _offer, _validate_grid
15
16__all__ = ["SymmetryAwareMAPElites", "SymmetryQDStats"]
17
18
19
20@dataclass(frozen=True)
22 """Cumulative proposals, evaluator attempts, repeats, and accepted archive updates."""
23
24 proposals: int = 0
25 evaluations: int = 0
26 duplicates: int = 0
27 archive_updates: int = 0
28
29
30
32 """Search only distinct canonical representatives in a best-only Grid or CVTGrid.
33
34 :param archive: Empty reporting archive with scalar fitness.
35 :param canonicalize: Callback (genome_tuple) producing a canonical
36 genome iterable with hashable entries. It must be deterministic and
37 idempotent, and preserve fitness, descriptors, and feasibility.
38 :param propose: Callback (rng) producing an initial iterable genome.
39 :param mutate: Callback (parent_tuple, rng) producing an offspring genome.
40 :param seed: Private proposal and parent selection seed.
41
42 The search owns a cache of successfully evaluated representatives,
43 including measurements outside the reporting domain. Keep the
44 evaluator, geometry, and canonicalization fixed across calls.
45 """
46
47 def __init__(self, archive, *, canonicalize, propose, mutate, seed=0):
48 _validate_grid(archive)
49 if not all(map(callable, (canonicalize, propose, mutate))):
50 raise TypeError("Supply callable canonicalize, propose, and mutate functions.")
51 self.archive = archive
52 self._canonicalize, self._propose, self._mutate = canonicalize, propose, mutate
53 self._rng = np.random.default_rng(seed)
54 self._seen = set()
55 self._counts = Counter()
56
57 @property
58 def stats(self):
59 """Return an immutable snapshot of proposal and evaluation costs."""
60 return SymmetryQDStats(**self._counts)
61
62
63 def run(self, evaluate, *, proposals, max_evaluations=None):
64 """Return cumulative stats. The optional evaluation limit applies to this call.
65
66 Evaluate the canonical tuple and return ((fitness,), descriptors).
67 Failed or invalid measurements propagate and leave the candidate
68 eligible for a later attempt.
69 """
70 if not callable(evaluate):
71 raise TypeError("evaluate must be callable.")
72 proposals = _positive_int(proposals, "proposals")
73 limit = (None if max_evaluations is None
74 else self._counts["evaluations"] + _positive_int(max_evaluations, "max_evaluations"))
75 for _ in range(proposals):
76 if limit is not None and self._counts["evaluations"] >= limit:
77 break
78 self._counts["proposals"] += 1
79 if self.archive:
80 parent = tuple(self.archive[int(self._rng.integers(len(self.archive)))])
81 genome = self._mutate(parent, self._rng)
82 else:
83 genome = self._propose(self._rng)
84 canonical = tuple(self._canonicalize(tuple(genome)))
85 if canonical in self._seen:
86 self._counts["duplicates"] += 1
87 continue
88 self._counts["evaluations"] += 1
89 measurement = _measurement(self.archive, evaluate(canonical), canonical)
90 before = self.archive.nb_added
91 _offer(self.archive, measurement)
92 self._seen.add(canonical)
93 self._counts["archive_updates"] += self.archive.nb_added - before
94 return self.stats
Canonicalize each design before evaluation and archive admission.
run(self, evaluate, *, proposals, max_evaluations=None)
Run additional proposals, skipping evaluation of repeated canonical designs.
Separate proposals, expensive evaluations, and repeated representatives.