QDpy
Loading...
Searching...
No Matches
feasible_mome.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Store feasible local Pareto fronts and breed near-feasible candidates independently."""
6
7from math import isfinite
8import random
9
10import numpy as np
11
12from qdpy.base import registry
13from qdpy.containers import ParetoGrid
14from qdpy.tools import iso_line_dd
15from .constrained import _constraint_violation, _names
16from .modern import MOME
17
18__all__ = ["FeasibleMOME"]
19
20
21
22@registry.register
24 """Apply explicit inequalities to MOME without changing its objective weights.
25
26 Evaluators return fitness, descriptors, and named constraint scores.
27 Each residual g(x) must be finite, with g(x) <= 0 denoting feasibility.
28 Only feasible candidates enter the reporting ParetoGrid. Infeasible
29 candidates compete by the sum of their positive residuals in a
30 separate slot per cell. Scale residuals in the evaluator when units differ.
31
32 :param container: Empty ParetoGrid for feasible trade-offs.
33 :param budget: Exact evaluation attempts.
34 :param dimension: Number of real-valued genome coordinates.
35 :param batch_size: Number of proposals before committing feedback.
36 :param constraint_names: Score names holding the inequality residuals.
37 :param infeasible_parent_probability: Chance of drawing a least-violation
38 breeder when both pools have entries. Zero disables these parents.
39 :param seed: Private mutation, selection, and truncation seed.
40 :param kwargs: MOME settings, including decision bounds and variation scales.
41 """
42
43 _requires_proposed_genome = True
44
45 def __init__(self, container, budget, dimension, batch_size=1, *,
46 constraint_names, infeasible_parent_probability=.25, seed=0, **kwargs):
47 if not isinstance(container, ParetoGrid):
48 raise ValueError("FeasibleMOME requires a ParetoGrid.")
49 names = _names(constraint_names, "constraint scores")
50 if not names or set(names).intersection((*container.fitness_score_names, *container.features_score_names)):
51 raise ValueError("Supply separate, nonempty constraint score names.")
52 if len(container):
53 raise ValueError("FeasibleMOME starts with an empty ParetoGrid.")
54 if not 0. <= infeasible_parent_probability <= 1.:
55 raise ValueError("infeasible_parent_probability must be in [0, 1].")
56 self.constraint_names = names
57 self.infeasible_parent_probability = infeasible_parent_probability
58 self.seed = seed
59 super().__init__(container, budget, dimension, batch_size, **kwargs)
60 if not isfinite(self.ind_domain[1] - self.ind_domain[0]):
61 raise ValueError("Provide decision bounds with a finite span.")
62
63 def reinit(self):
64 """Reset the proposal stream and auxiliary breeding slots."""
65 super().reinit()
66 self._rng = np.random.default_rng(self.seed)
67 self._truncation_rng = random.Random(None if self.seed is None else int(self.seed))
68 self._infeasible = {}
69
70 @property
72 """Return an independent mapping of cells to their least-violation breeders."""
73 return {cell: candidate for cell, (_, candidate) in self._infeasible.items()}
74
75 def _start_fixed_batch(self, size):
76 super()._start_fixed_batch(size)
77 self._auxiliary = (tuple(candidate for _, candidate in self._infeasible.values())
78 if self.infeasible_parent_probability else ())
79
80 def _parent(self):
81 if self._auxiliary and (not self._occupied or self._rng.random() < self.infeasible_parent_probability):
82 return self._auxiliary[self._rng.integers(len(self._auxiliary))]
83 front = self._occupied[self._rng.integers(len(self._occupied))]
84 return front[self._rng.integers(len(front))]
85
86 def _internal_ask(self, base_ind):
87 if self._occupied or self._auxiliary:
88 base_ind[:] = iso_line_dd(self._parent(), self._parent(), iso_sigma=self.iso_sigma,
89 line_sigma=self.line_sigma, bounds=self.ind_domain, rng=self._rng)
90 else:
91 base_ind[:] = self._rng.uniform(*self.ind_domain, size=self.dimension)
92 return base_ind
93
94 def _check_candidate(self, individual):
95 super()._check_candidate(individual)
96 if not isfinite(_constraint_violation(individual, self.constraint_names)):
97 raise ValueError("The aggregate constraint violation must be finite.")
98
99 def _commit_generation(self, evaluated):
100 feasible = []
101 for candidate in evaluated:
102 if candidate is None:
103 continue
104 violation = _constraint_violation(candidate, self.constraint_names)
105 if violation == 0.:
106 feasible.append(candidate)
107 else:
108 cell = self.container.index_grid(candidate)
109 previous = self._infeasible.get(cell)
110 if previous is None or violation < previous[0]:
111 self._infeasible[cell] = violation, candidate
112 admitted = self.container._merge_fronts(feasible, truncation_rng=self._truncation_rng)
113 return {slot for slot, candidate in enumerate(evaluated) if id(candidate) in admitted}
Evolve feasible Pareto fronts and preserve a least-violation breeder per cell.
Sample occupied cells and evolve their bounded Pareto fronts.
Definition modern.py:545