QDpy
Loading...
Searching...
No Matches
deep_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Deep quality-diversity with HiGeME proposals and shared descriptor geometry."""
7
8from copy import deepcopy
9from operator import index
10from types import MappingProxyType
11
12from qdpy.base import registry
13from qdpy.containers import CVTGrid, Grid
14from qdpy.containers.base import _IndexedOrderedSet
15from qdpy.phenotype import _CellIndividual
16
17from .constrained import HiGeME, _constraint_violation
18
19__all__ = ["DeepQD", "DeepQDArchive"]
20
21
22
24 """Index measurements by descriptor cell and configuration.
25
26 The cells contain one best feasible measurement per configuration.
27 Iteration and len() operate over all cell/configuration entries.
28 best_grid is the live native projection of the best entry in each
29 occupied cell. Obtain a separate native snapshot for a single
30 configuration with configuration_grid().
31 """
32
33 def __init__(self, best_grid, configurations):
34 self.best_grid = best_grid
35 self.configurations = tuple(configurations)
36 self._cells = {}
38
39 def __len__(self):
40 """Count occupied cell/configuration pairs."""
41 return len(self._entries)
42
43 def __iter__(self):
44 """Iterate configuration elites in admission order."""
45 return iter(self._entries)
46
47 def __getitem__(self, position):
48 """Get a configuration elite by position in admission order."""
49 return self._entries[position]
50
51 @property
52 def filled_bins(self):
53 """Count cells with at least one feasible configuration elite."""
54 return len(self._cells)
55
56 @property
58 """Return occupied cell counts in the order of the declared configurations."""
59 counts = [0] * len(self.configurations)
60 for alternatives in self._cells.values():
61 for branch in alternatives:
62 counts[branch] += 1
63 return tuple(counts)
64
65 @property
67 """Return mean retained configurations per occupied cell, or zero when empty."""
68 return len(self) / self.filled_bins if self.filled_bins else 0.
69
70
71 def cell_elites(self, cell):
72 """Return a read-only map from configuration indices to the retained individuals."""
73 return MappingProxyType(self._cells.get(tuple(cell), {}))
74
75
76 def configuration_grid(self, configuration):
77 """Copy one layer by configuration index into an independent native grid."""
78 configuration = index(configuration)
79 if not 0 <= configuration < len(self.configurations):
80 raise IndexError("Configuration index is out of range.")
81 grid = deepcopy(self.best_grid)
82 grid.clear()
83 for alternatives in self._cells.values():
84 if configuration in alternatives:
85 grid.add(deepcopy(alternatives[configuration]))
86 return grid
87
88 def _offer(self, individual):
89 grid = self.best_grid
90 branch = individual[0]
91 cell = grid.index_grid(individual)
92 alternatives = self._cells.get(cell)
93 previous = alternatives.get(branch) if alternatives else None
94 if previous is not None and not grid.get_ind_fitness(individual).dominates(grid.get_ind_fitness(previous)):
95 return False
96 record = _CellIndividual(individual, cell, name=individual.name,
97 fitness=deepcopy(individual.fitness), features=deepcopy(individual.features),
98 scores=deepcopy(individual.scores))
99 record.elapsed = individual.elapsed
100 grid.add(record)
101 if previous is not None:
102 self._entries.discard(previous)
103 self._entries.add(record)
104 self._cells.setdefault(cell, {})[branch] = record
105 return True
106
107
108
109@registry.register
111 """Evolve feasible conditional designs into a layered archive.
112
113 Accept the same conditional variables, constraints and evaluator
114 results as HiGeME. Parent selection uses all retained configuration
115 elites. Standard QDpy callbacks, best() and the supplied container
116 use the per-cell best projection. Access all alternatives through
117 deep_archive and update the live archives through the search.
118
119 :param container: Empty parentless Grid or CVTGrid with one slot per cell.
120 :param budget: Attempted evaluations.
121 :param variables: Mapping of names to the shared variable schema.
122 :param configurations: Sequence of ConditionalConfiguration objects.
123 :param kwargs: HiGeME variation, batching, and optimisation settings.
124 """
125
126 def __init__(self, container, budget, variables, *, configurations, **kwargs):
127 if (type(container) not in (Grid, CVTGrid) or container.parents
128 or container.capacity < len(container.solutions)):
129 raise ValueError("Supply a parentless Grid or CVTGrid with capacity for every cell.")
130 if container.fitness_weights is not None:
131 kwargs.setdefault("optimisation_task", container.fitness_weights)
132 super().__init__(container, budget, variables, configurations=configurations, **kwargs)
133 self.deep_archive = DeepQDArchive(container, self.configurations)
134
135 def __deepcopy__(self, memo):
136 # QDAlgorithm copies share their supplied container. Keep the
137 # configuration layers with that same live projection.
138 memo[id(self.deep_archive)] = self.deep_archive
139 return super().__deepcopy__(memo)
140
141 def _parent_pool(self):
142 return self.deep_archive
143
144 def _commit_generation(self, evaluated):
145 return {slot for slot, ind in enumerate(evaluated)
146 if ind is not None
147 and _constraint_violation(ind, self.configurations[ind[0]].constraints) == 0
148 and self.deep_archive._offer(ind)}
Search a union of conditional design spaces using hidden numeric genes.
Read the configuration alternatives held by a DeepQD search.
Definition deep_qd.py:23
cell_elites(self, cell)
Inspect alternatives in a native Grid or CVTGrid cell.
Definition deep_qd.py:71
configuration_grid(self, configuration)
Materialize a configuration on the same descriptor geometry.
Definition deep_qd.py:76
Use HiGeME variation and preserve one winner per configuration per cell.
Definition deep_qd.py:110
_commit_generation(self, evaluated)
Definition deep_qd.py:144