QDpy
Loading...
Searching...
No Matches
mole.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Trace local Pareto sets by joint descent and predictor-corrector continuation."""
7
8from dataclasses import dataclass
9from math import sqrt
10
11import numpy as np
12from scipy.linalg import norm
13
14from .modern import _positive_int
15
16__all__ = ["MOLE", "MOLEResult", "MOLEPoint"]
17
18
19
20@dataclass(frozen=True)
22 """Store a decision vector and its two measured objective values."""
23
24 genome: tuple
25 objectives: tuple
26
27
28
29@dataclass(frozen=True)
31 """Report the approximate local sets recovered within the callback budget.
32
33 :ivar sets: Curves of MOLEPoint records ordered by continuation.
34 :ivar transitions: Directed (source_set_index, destination_set_index) pairs.
35 :ivar evaluations: Number of joint objective and Jacobian evaluations.
36 """
37
38 sets: tuple
39 transitions: tuple
40 evaluations: int
41
42
43class _BudgetExhausted(Exception):
44 """Stop the current search step once the exact-call budget has been used."""
45
46
47@dataclass(frozen=True)
49 point: np.ndarray
50 values: np.ndarray
51 gradients: np.ndarray
52
53
54def _dominates(first, second):
55 return np.all(first <= second) and np.any(first < second)
56
57
58
59class MOLE:
60 """Use joint descent, then trace each discovered set in both objective directions.
61
62 A callback supplies both objective values and their analytic Jacobian
63 at each evaluated point. MOLE corrects secant predictions with local
64 multi-objective descent and queues corrected points when continuation
65 crosses into another basin. All calls share one evaluation budget.
66
67 :param bounds: Sequence of finite increasing (lower, upper) pairs, one per coordinate.
68 :param step_size: Maximum spatial step for descent and tracing. Defaults
69 to one hundredth of the decision box diagonal.
70 :param min_step: Smallest continuation and backtracking step. Defaults
71 to one thousandth of step_size.
72 :param gradient_tolerance: Joint-gradient norm considered stationary.
73 :param max_descent_steps: Maximum accepted descent steps per correction.
74 """
75
76 def __init__(self, bounds, *, step_size=None, min_step=None,
77 gradient_tolerance=1e-6, max_descent_steps=256):
78 domain = np.asarray(bounds, dtype=float)
79 if (domain.ndim != 2 or domain.shape[1] != 2 or not len(domain)
80 or not np.isfinite(domain).all() or np.any(domain[:, 0] >= domain[:, 1])):
81 raise ValueError("Supply finite increasing bounds for each decision coordinate.")
82 self._lower, self._upper = domain.T
83 if step_size is None:
84 step_size = norm(self._upper - self._lower) / 100
85 if min_step is None:
86 min_step = step_size / 1000
87 if not (0 < min_step <= step_size < np.inf and 0 < gradient_tolerance < np.inf):
88 raise ValueError("Use finite positive steps and gradient tolerance with min_step <= step_size.")
89 self.step_size, self.min_step = step_size, min_step
90 self.gradient_tolerance = gradient_tolerance
91 self.max_descent_steps = _positive_int(max_descent_steps, "max_descent_steps")
92
93 def _descent_direction(self, measurement):
94 # Project the individual objective gradients for the active box faces.
95 slopes = measurement.gradients.copy()
96 slopes[(measurement.point <= self._lower) & (slopes > 0)] = 0.
97 slopes[(measurement.point >= self._upper) & (slopes < 0)] = 0.
98 first, second = map(norm, slopes)
99 if first == 0 or second == 0:
100 return np.zeros_like(measurement.point)
101 # Geometric-mean normalization preserves both objectives' directions.
102 return -sqrt(first) * sqrt(second) * (.5 * (slopes[0] / first + slopes[1] / second))
103
104 def _descent(self, measure, start):
105 current = start
106 last_direction = last_delta = None
107 for _ in range(self.max_descent_steps):
108 direction = self._descent_direction(current)
109 length = norm(direction)
110 if length <= self.gradient_tolerance:
111 break
112 unit = direction / length
113 step = float(np.clip(length, self.min_step, self.step_size))
114 if last_delta is not None:
115 change = last_direction - direction
116 curvature = last_delta @ change
117 if curvature > 0:
118 estimate = max((last_delta @ last_delta) / curvature, norm(last_delta) / norm(change))
119 step = float(np.clip(estimate * length, self.min_step, self.step_size))
120 while True:
121 point = np.clip(current.point + step * unit, self._lower, self._upper)
122 delta = point - current.point
123 slope = current.gradients @ delta
124 if np.any(delta) and np.all(slope <= 0.):
125 trial = measure(point)
126 if (_dominates(trial.values, current.values)
127 and np.all(trial.values <= current.values + 1e-4 * slope)):
128 break
129 if step <= self.min_step:
130 return current
131 step = max(self.min_step, step / 2.)
132 last_direction, last_delta = direction, delta
133 current = trial
134 return current
135
136 def _trace(self, measure, seed, objective, trace, other_basins):
137 current = seed
138 secant = None
139 step = self.min_step
140 while True:
141 direction = -current.gradients[objective] if secant is None else secant
142 length = norm(direction)
143 if length == 0.:
144 break
145 point = np.clip(current.point + step * direction / length, self._lower, self._upper)
146 accepted = False
147 trial = None if np.array_equal(point, current.point) else measure(point)
148 if trial is not None and trial.values[objective] < current.values[objective]:
149 corrected = self._descent(measure, trial)
150 delta = corrected.point - current.point
151 distance = norm(delta)
152 correction = norm(corrected.point - trial.point)
153 aligned = secant is None or delta @ secant >= distance * norm(secant) / sqrt(2.)
154 if secant is None or (correction <= step and aligned):
155 if (_dominates(corrected.values, current.values)
156 or distance > self.step_size + self.min_step):
157 other_basins.append(corrected)
158 break
159 if distance >= self.min_step / 4 and corrected.values[objective] < current.values[objective]:
160 trace.append(corrected)
161 current, secant = corrected, delta
162 step = min(self.step_size, 2 * step)
163 accepted = True
164 if accepted:
165 continue
166 if step > self.min_step:
167 step = max(self.min_step, step / 2.)
168 elif secant is not None:
169 secant = None
170 else:
171 break
172
173 def _containing_set(self, sets, candidate):
174 for index, (origin, left, right) in enumerate(sets):
175 chain = [*reversed(left), origin, *right]
176 distances = [norm(point.point - candidate.point) for point in chain]
177 if min(distances) <= self.min_step:
178 return index
179 for first, second, d1, d2 in zip(chain, chain[1:], distances, distances[1:]):
180 if (max(d1, d2) < norm(first.point - second.point)
181 and np.all(candidate.values >= np.minimum(first.values, second.values))
182 and np.all(candidate.values <= np.maximum(first.values, second.values))):
183 return index
184 return None
185
186
187 def run(self, evaluate, starts, budget):
188 """Return approximate local curves from a bounded continuous problem.
189
190 evaluate receives a copy of a one-dimensional NumPy genome and
191 returns (two costs, a 2-by-dimension Jacobian). Both costs are minimized.
192 A run starts with empty traces. The result includes points already
193 retained when a correction runs out of evaluations.
194 """
195 budget = _positive_int(budget, "budget")
196 starts = np.asarray(starts, dtype=float)
197 if (not callable(evaluate) or starts.ndim != 2 or starts.shape[1:] != self._lower.shape
198 or not len(starts) or not np.isfinite(starts).all()
199 or np.any(starts < self._lower) or np.any(starts > self._upper)):
200 raise ValueError("Provide a callable and a nonempty matrix of in-bounds starting points.")
201 evaluations = 0
202 sets, transitions = [], set()
203
204 def measure(point):
205 nonlocal evaluations
206 if evaluations == budget:
207 raise _BudgetExhausted
208 evaluations += 1
209 values, gradients = evaluate(point.copy())
210 values, gradients = np.array(values, dtype=float, copy=True), np.array(gradients, dtype=float, copy=True)
211 if (values.shape != (2,) or gradients.shape != (2, len(self._lower))
212 or not np.isfinite(values).all() or not np.isfinite(gradients).all()):
213 raise ValueError("MOLE needs two finite costs and one finite Jacobian row per cost.")
214 return _Measurement(point, values, gradients)
215
216 try:
217 for start in starts:
218 pending = [(None, self._descent(measure, measure(start)))]
219 while pending:
220 source, candidate = pending.pop()
221 index = self._containing_set(sets, candidate)
222 explore = index is None
223 if explore:
224 index = len(sets)
225 sets.append((candidate, [], []))
226 if source is not None and source != index:
227 transitions.add((source, index))
228 if explore:
229 _, left, right = sets[index]
230 other_basins = []
231 self._trace(measure, candidate, 0, left, other_basins)
232 self._trace(measure, candidate, 1, right, other_basins)
233 pending.extend((index, point) for point in other_basins)
234 except _BudgetExhausted:
235 pass
236 rows = tuple(tuple(MOLEPoint(tuple(p.point), tuple(p.values))
237 for p in (*reversed(left), origin, *right))
238 for origin, left, right in sets)
239 return MOLEResult(rows, tuple(sorted(transitions)), evaluations)
One measured point on an approximate local Pareto set.
Definition mole.py:21
Ordered local Pareto set traces and directed transitions.
Definition mole.py:30
Discover and connect locally efficient sets for two differentiable costs.
Definition mole.py:59
_trace(self, measure, seed, objective, trace, other_basins)
Definition mole.py:136
_containing_set(self, sets, candidate)
Definition mole.py:173
_descent_direction(self, measurement)
Definition mole.py:93
run(self, evaluate, starts, budget)
Explore from caller-supplied starting points with a strict shared budget.
Definition mole.py:187
_descent(self, measure, start)
Definition mole.py:104