QDpy
Loading...
Searching...
No Matches
melita.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Recombine one changed component with occupants of the matching descriptor slice."""
7
8from dataclasses import dataclass
9
10import numpy as np
11
12from qdpy.containers import Grid
13from qdpy.phenotype import Features, Fitness, Individual
14from .modern import _positive_int
15
16__all__ = ["MEliTA", "MEliTAStats"]
17
18
19
20@dataclass(frozen=True)
22 """Report edits, total assessments, cross-component assessments, and admissions."""
23
24 proposals: int
25 assessments: int
26 transverse_assessments: int
27 archive_updates: int
28
29
30
31class MEliTA:
32 """Mutate one component and consider partners from its new descriptor slice.
33
34 A component is an immutable hashable value. Each component determines
35 one independent grid axis. Assess the combination with its original
36 partners and with partners from other cells on the changed axis's
37 slice. Per edit, admit the highest-ranked combination that improves
38 its cell. Assessments have their own budget because one edit can
39 produce multiple combinations.
40
41 :param archive: Empty parentless regular best-only Grid with one signed objective.
42 :param initialize: Callable taking a local Generator and returning the initial components.
43 :param mutations: One callable per component, accepting (components, rng).
44 :param descriptors: One scalar descriptor callable per component.
45 :param coherence: Callable accepting the complete tuple and returning raw scalar quality.
46 :param transverse: If false, score the direct edited combination only.
47 :param seed: Private proposal seed.
48 """
49
50 def __init__(self, archive, *, initialize, mutations, descriptors, coherence, transverse=True, seed=0):
51 if (type(archive) is not Grid or archive.parents or archive.max_items_per_bin != 1 or len(archive)
52 or archive.discard_random_on_bin_overload or len(archive.fitness_domain or ()) != 1
53 or len(archive.fitness_weights or ()) != 1 or not np.isfinite(archive.fitness_weights[0])
54 or not archive.fitness_weights[0] or archive.fitness_score_names or archive.features_score_names):
55 raise ValueError("Use an empty regular best-only Grid with one signed native objective.")
56 self._mutations, self._descriptors = tuple(mutations), tuple(descriptors)
57 self._size = len(archive.shape)
58 if (self._size < 2 or len(self._mutations) != self._size or len(self._descriptors) != self._size
59 or not all(map(callable, (initialize, coherence, *self._mutations, *self._descriptors)))):
60 raise ValueError("Provide an initializer, a scorer, and callbacks for each of two or more grid axes.")
61 self.archive, self._initialize, self._coherence = archive, initialize, coherence
62 self._transverse, self._rng = transverse, np.random.default_rng(seed)
63 self._weight = archive.fitness_weights[0]
64
65 def _measure(self, parts):
66 if len(parts) != self._size:
67 raise ValueError("Return one component per archive axis.")
68 hash(parts)
69 features = tuple(float(describe(part)) for describe, part in zip(self._descriptors, parts))
70 if not np.isfinite(features).all():
71 raise ValueError("Component descriptors must be finite.")
72 return features
73
74
78 def run(self, budget, *, proposal_limit=None):
79 """Score distinct combinations in direct-first order when the final edit is budget-cut."""
80 budget = _positive_int(budget, "budget")
81 maximum = 10 * budget if proposal_limit is None else _positive_int(proposal_limit, "proposal_limit")
82 edits = assessments = cross_assessments = accepted = 0
83 archive = self.archive
84 while edits < maximum and assessments < budget:
85 edits += 1
86 if len(archive):
87 parent = tuple(archive[self._rng.integers(len(archive))])
88 index = int(self._rng.integers(self._size))
89 changed = self._mutations[index](parent, self._rng)
90 direct = (*parent[:index], changed, *parent[index + 1:])
91 else:
92 index = None
93 direct = tuple(self._initialize(self._rng))
94 measured = self._measure(direct)
95 if not archive.in_bounds(measured, archive.features_domain):
96 continue
97 cell = archive.index_grid(measured)
98 choices = {direct: measured}
99 if index is not None and self._transverse:
100 for other_cell, items in archive.solutions.items():
101 if other_cell[index] == cell[index] and items:
102 other = tuple(items[0])
103 parts = (*other[:index], changed, *other[index + 1:])
104 if parts not in choices:
105 features = list(archive.get_ind_features(items[0]))
106 features[index] = measured[index]
107 choices[parts] = tuple(features)
108 ranked = []
109 for number, (parts, features) in enumerate(choices.items()):
110 if assessments == budget:
111 break
112 quality = float(self._coherence(parts))
113 assessments += 1
114 cross_assessments += number > 0
115 if not np.isfinite(quality):
116 raise ValueError("Coherence must be finite.")
117 if archive.in_bounds((quality,), archive.fitness_domain):
118 ranked.append((quality, parts, features))
119 for quality, parts, features in sorted(ranked, key=lambda row: self._weight * row[0], reverse=True):
120 if archive.free < 1 and not archive.solutions[archive.index_grid(features)]:
121 continue
122 elite = Individual(list(parts), fitness=Fitness((quality,), weights=(self._weight,)),
123 features=Features(features))
124 if archive.add(elite) is not None:
125 accepted += 1
126 break
127 return MEliTAStats(edits, assessments, cross_assessments, accepted)
Counts from one transverse assessment run.
Definition melita.py:21
Search separable components and rank their combinations by coherence.
Definition melita.py:31
run(self, budget, *, proposal_limit=None)
Spend up to budget coherence calls with a separate edit cap.
Definition melita.py:78
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405