# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Gradient-based exploration of continuous bi-objective locally efficient sets.
# @see https://arxiv.org/abs/2204.10848
"""Trace local Pareto sets by joint descent and predictor-corrector continuation."""
from dataclasses import dataclass
from math import sqrt
import numpy as np
from scipy.linalg import norm
from .modern import _positive_int
__all__ = ["MOLE", "MOLEResult", "MOLEPoint"]
## @brief One measured point on an approximate local Pareto set.
[docs]
@dataclass(frozen=True)
class MOLEPoint:
"""Store a decision vector and its two measured objective values."""
genome: tuple
objectives: tuple
## @brief Ordered local Pareto set traces and directed transitions.
[docs]
@dataclass(frozen=True)
class MOLEResult:
"""Report the approximate local sets recovered within the callback budget.
:ivar sets: Curves of MOLEPoint records ordered by continuation.
:ivar transitions: Directed (source_set_index, destination_set_index) pairs.
:ivar evaluations: Number of joint objective and Jacobian evaluations.
"""
sets: tuple
transitions: tuple
evaluations: int
class _BudgetExhausted(Exception):
"""Stop the current search step once the exact-call budget has been used."""
@dataclass(frozen=True)
class _Measurement:
point: np.ndarray
values: np.ndarray
gradients: np.ndarray
def _dominates(first, second):
return np.all(first <= second) and np.any(first < second)
## @brief Discover and connect locally efficient sets for two differentiable costs.
[docs]
class MOLE:
"""Use joint descent, then trace each discovered set in both objective directions.
A callback supplies both objective values and their analytic Jacobian
at each evaluated point. MOLE corrects secant predictions with local
multi-objective descent and queues corrected points when continuation
crosses into another basin. All calls share one evaluation budget.
:param bounds: Sequence of finite increasing (lower, upper) pairs, one per coordinate.
:param step_size: Maximum spatial step for descent and tracing. Defaults
to one hundredth of the decision box diagonal.
:param min_step: Smallest continuation and backtracking step. Defaults
to one thousandth of step_size.
:param gradient_tolerance: Joint-gradient norm considered stationary.
:param max_descent_steps: Maximum accepted descent steps per correction.
"""
def __init__(self, bounds, *, step_size=None, min_step=None,
gradient_tolerance=1e-6, max_descent_steps=256):
domain = np.asarray(bounds, dtype=float)
if (domain.ndim != 2 or domain.shape[1] != 2 or not len(domain)
or not np.isfinite(domain).all() or np.any(domain[:, 0] >= domain[:, 1])):
raise ValueError("Supply finite increasing bounds for each decision coordinate.")
self._lower, self._upper = domain.T
if step_size is None:
step_size = norm(self._upper - self._lower) / 100
if min_step is None:
min_step = step_size / 1000
if not (0 < min_step <= step_size < np.inf and 0 < gradient_tolerance < np.inf):
raise ValueError("Use finite positive steps and gradient tolerance with min_step <= step_size.")
self.step_size, self.min_step = step_size, min_step
self.gradient_tolerance = gradient_tolerance
self.max_descent_steps = _positive_int(max_descent_steps, "max_descent_steps")
def _descent_direction(self, measurement):
# Project the individual objective gradients for the active box faces.
slopes = measurement.gradients.copy()
slopes[(measurement.point <= self._lower) & (slopes > 0)] = 0.
slopes[(measurement.point >= self._upper) & (slopes < 0)] = 0.
first, second = map(norm, slopes)
if first == 0 or second == 0:
return np.zeros_like(measurement.point)
# Geometric-mean normalization preserves both objectives' directions.
return -sqrt(first) * sqrt(second) * (.5 * (slopes[0] / first + slopes[1] / second))
def _descent(self, measure, start):
current = start
last_direction = last_delta = None
for _ in range(self.max_descent_steps):
direction = self._descent_direction(current)
length = norm(direction)
if length <= self.gradient_tolerance:
break
unit = direction / length
step = float(np.clip(length, self.min_step, self.step_size))
if last_delta is not None:
change = last_direction - direction
curvature = last_delta @ change
if curvature > 0:
estimate = max((last_delta @ last_delta) / curvature, norm(last_delta) / norm(change))
step = float(np.clip(estimate * length, self.min_step, self.step_size))
while True:
point = np.clip(current.point + step * unit, self._lower, self._upper)
delta = point - current.point
slope = current.gradients @ delta
if np.any(delta) and np.all(slope <= 0.):
trial = measure(point)
if (_dominates(trial.values, current.values)
and np.all(trial.values <= current.values + 1e-4 * slope)):
break
if step <= self.min_step:
return current
step = max(self.min_step, step / 2.)
last_direction, last_delta = direction, delta
current = trial
return current
def _trace(self, measure, seed, objective, trace, other_basins):
current = seed
secant = None
step = self.min_step
while True:
direction = -current.gradients[objective] if secant is None else secant
length = norm(direction)
if length == 0.:
break
point = np.clip(current.point + step * direction / length, self._lower, self._upper)
accepted = False
trial = None if np.array_equal(point, current.point) else measure(point)
if trial is not None and trial.values[objective] < current.values[objective]:
corrected = self._descent(measure, trial)
delta = corrected.point - current.point
distance = norm(delta)
correction = norm(corrected.point - trial.point)
aligned = secant is None or delta @ secant >= distance * norm(secant) / sqrt(2.)
if secant is None or (correction <= step and aligned):
if (_dominates(corrected.values, current.values)
or distance > self.step_size + self.min_step):
other_basins.append(corrected)
break
if distance >= self.min_step / 4 and corrected.values[objective] < current.values[objective]:
trace.append(corrected)
current, secant = corrected, delta
step = min(self.step_size, 2 * step)
accepted = True
if accepted:
continue
if step > self.min_step:
step = max(self.min_step, step / 2.)
elif secant is not None:
secant = None
else:
break
def _containing_set(self, sets, candidate):
for index, (origin, left, right) in enumerate(sets):
chain = [*reversed(left), origin, *right]
distances = [norm(point.point - candidate.point) for point in chain]
if min(distances) <= self.min_step:
return index
for first, second, d1, d2 in zip(chain, chain[1:], distances, distances[1:]):
if (max(d1, d2) < norm(first.point - second.point)
and np.all(candidate.values >= np.minimum(first.values, second.values))
and np.all(candidate.values <= np.maximum(first.values, second.values))):
return index
return None
## @brief Explore from caller-supplied starting points with a strict shared budget.
[docs]
def run(self, evaluate, starts, budget):
"""Return approximate local curves from a bounded continuous problem.
evaluate receives a copy of a one-dimensional NumPy genome and
returns (two costs, a 2-by-dimension Jacobian). Both costs are minimized.
A run starts with empty traces. The result includes points already
retained when a correction runs out of evaluations.
"""
budget = _positive_int(budget, "budget")
starts = np.asarray(starts, dtype=float)
if (not callable(evaluate) or starts.ndim != 2 or starts.shape[1:] != self._lower.shape
or not len(starts) or not np.isfinite(starts).all()
or np.any(starts < self._lower) or np.any(starts > self._upper)):
raise ValueError("Provide a callable and a nonempty matrix of in-bounds starting points.")
evaluations = 0
sets, transitions = [], set()
def measure(point):
nonlocal evaluations
if evaluations == budget:
raise _BudgetExhausted
evaluations += 1
values, gradients = evaluate(point.copy())
values, gradients = np.array(values, dtype=float, copy=True), np.array(gradients, dtype=float, copy=True)
if (values.shape != (2,) or gradients.shape != (2, len(self._lower))
or not np.isfinite(values).all() or not np.isfinite(gradients).all()):
raise ValueError("MOLE needs two finite costs and one finite Jacobian row per cost.")
return _Measurement(point, values, gradients)
try:
for start in starts:
pending = [(None, self._descent(measure, measure(start)))]
while pending:
source, candidate = pending.pop()
index = self._containing_set(sets, candidate)
explore = index is None
if explore:
index = len(sets)
sets.append((candidate, [], []))
if source is not None and source != index:
transitions.add((source, index))
if explore:
_, left, right = sets[index]
other_basins = []
self._trace(measure, candidate, 0, left, other_basins)
self._trace(measure, candidate, 1, right, other_basins)
pending.extend((index, point) for point in other_basins)
except _BudgetExhausted:
pass
rows = tuple(tuple(MOLEPoint(tuple(p.point), tuple(p.values))
for p in (*reversed(left), origin, *right))
for origin, left, right in sets)
return MOLEResult(rows, tuple(sorted(transitions)), evaluations)