# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Solve each rectangular archive niche as a separate mixed-integer program.
# @see https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.milp.html
"""Populate a Grid with verified solutions and one solver result per requested cell."""
from dataclasses import dataclass
from math import ceil, floor
from operator import index
import numpy as np
from scipy.optimize import Bounds, LinearConstraint, milp
from qdpy.containers import Grid
from qdpy.containers.grids import _bin_index
from qdpy.phenotype import Features, Fitness, Individual
from .constrained import _validate_grid
from .modern import _positive_int
__all__ = ["MILPArchiveSearch", "MILPCellResult"]
## @brief Solver outcome for a single requested descriptor cell.
[docs]
@dataclass(frozen=True)
class MILPCellResult:
"""Keep the verified incumbent and the original termination details.
:ivar cell: Rectangular cell index.
:ivar status: "optimal", "infeasible", or "unresolved".
:ivar genome: Verified incumbent, if available.
:ivar fitness: Raw linear objective of the incumbent.
:ivar features: Integer-valued descriptors of the incumbent.
:ivar objective_bound: Solver bound in raw units, when reported.
:ivar solver_status: SciPy status code, or None if no solver call was needed.
:ivar message: Original termination or verification message.
"""
cell: tuple
status: str
genome: tuple | None = None
fitness: float | None = None
features: tuple | None = None
objective_bound: float | None = None
solver_status: int | None = None
message: str = ""
def _integer_bin_limits(domain, size):
lo, hi = map(float, domain)
width = (hi - lo) / size
def first_at_least(target):
left, right = ceil(lo), floor(hi) + 1
while left < right:
mid = (left + right) // 2
if _bin_index(mid, lo, hi, size, width) < target:
left = mid + 1
else:
right = mid
return left
edges = (ceil(lo), *(first_at_least(i) for i in range(1, size)), floor(hi) + 1)
return tuple((a, b - 1) for a, b in zip(edges, edges[1:]))
## @brief Obtain a solver-backed reference archive for a bounded linear problem.
[docs]
class MILPArchiveSearch:
"""Build one MILP per requested cell and verify its incumbent before admission.
Decision coordinates can be continuous or integer. Each descriptor is
an integer affine function of integer decision coordinates. Cell
constraints use the exact integer endpoints implied by Grid.index_grid.
The supplied grid's objective direction and objective bounds govern
optimization. An "optimal" result means HiGHS reported optimality with
zero requested relative gap and QDpy verified the incumbent.
:param archive: Empty parentless rectangular one-elite Grid with room for every cell.
:param objective: One finite linear objective coefficient per coordinate.
:param bounds: Finite lower and upper scipy.optimize.Bounds for the decision vector.
:param descriptor_matrix: One integer coefficient row per descriptor.
:param descriptor_offset: Optional integer constant per descriptor (default zero).
:param integrality: Boolean mask with 1 for integer and 0 for continuous coordinates.
Defaults to integer on every axis.
:param constraints: A LinearConstraint or sequence of shared constraints.
:param time_limit: Optional positive time limit in seconds per cell.
:param node_limit: Optional positive node limit per cell.
"""
def __init__(self, archive, objective, bounds, descriptor_matrix, *, descriptor_offset=None,
integrality=None, constraints=(), time_limit=None, node_limit=None):
_validate_grid(archive)
if (type(archive) is not Grid or archive.parents or archive.capacity < len(archive.solutions)
or archive.fitness_score_names or archive.features_score_names
or len(archive.fitness_weights or ()) != 1 or not np.isfinite(archive.fitness_weights[0])
or not archive.fitness_weights[0]):
raise ValueError("Use a parentless Grid with one signed objective and capacity for every cell.")
objective = np.array(objective, dtype=float, copy=True)
if objective.ndim != 1 or not len(objective) or not np.isfinite(objective).all():
raise ValueError("Provide a nonempty finite objective vector.")
if not isinstance(bounds, Bounds):
raise TypeError("bounds must be scipy.optimize.Bounds.")
dim = len(objective)
low = np.broadcast_to(np.asarray(bounds.lb, dtype=float), (dim,)).copy()
high = np.broadcast_to(np.asarray(bounds.ub, dtype=float), (dim,)).copy()
mask = np.ones(dim) if integrality is None else np.broadcast_to(np.asarray(integrality), (dim,))
if not np.isin(mask, (0, 1)).all():
raise ValueError("integrality must contain only 0 and 1.")
integer = mask.astype(bool)
if (not np.isfinite(low).all() or not np.isfinite(high).all() or np.any(low > high)
or np.any(np.ceil(low[integer]) > np.floor(high[integer]))):
raise ValueError("Use finite, nonempty decision bounds.")
# Integer coordinates are rounded and then verified after the solve.
low[integer], high[integer] = np.ceil(low[integer]), np.floor(high[integer])
if np.any(np.maximum(abs(low[integer]), abs(high[integer])) > 2**53):
raise ValueError("Integer bounds must be exactly representable in float64.")
axes = len(archive.shape)
domain = np.asarray(archive.features_domain, dtype=float)
matrix = np.array(descriptor_matrix, dtype=float, copy=True)
offset = np.zeros(axes) if descriptor_offset is None else np.array(descriptor_offset, dtype=float, copy=True)
if (domain.shape != (axes, 2) or not np.isfinite(domain).all() or np.max(abs(domain)) > 2**53
or np.any(domain[:, 0] >= domain[:, 1])):
raise ValueError("Use finite increasing descriptor bounds within the float64 exact-integer range.")
if (matrix.shape != (axes, dim) or offset.shape != (axes,)
or not np.isfinite(matrix).all() or not np.isfinite(offset).all()
or np.any(matrix != np.rint(matrix)) or np.any(offset != np.rint(offset))
or np.any(matrix[:, ~integer] != 0) or np.max(abs(matrix)) > 2**53
or np.any(abs(matrix) @ np.maximum(abs(low), abs(high)) + abs(offset) > 2**53)):
raise ValueError("Descriptors must be integer affine functions of integer variables within the exact range.")
rows = (constraints,) if isinstance(constraints, LinearConstraint) else tuple(constraints)
if any(not isinstance(row, LinearConstraint) or row.A.shape[1] != dim for row in rows):
raise ValueError("Use linear constraints with one column per decision coordinate.")
fit_low, fit_high = archive.fitness_domain[0]
if np.isnan(fit_low) or np.isnan(fit_high) or fit_low > fit_high:
raise ValueError("Invalid archive objective bounds.")
if np.isfinite(fit_low) or np.isfinite(fit_high):
rows += (LinearConstraint(objective[None, :], fit_low, fit_high),)
self.archive, self._objective = archive, objective
self._weights = tuple(archive.fitness_weights)
self._sign = -1. if self._weights[0] > 0 else 1.
self._bounds, self._integer, self._constraints = Bounds(low, high), integer, rows
self._matrix, self._offset = matrix, offset
least = np.minimum(matrix * low, matrix * high).sum(axis=1) + offset
most = np.maximum(matrix * low, matrix * high).sum(axis=1) + offset
self._limits = tuple(tuple((max(a, int(lo)), min(b, int(hi)))
for a, b in _integer_bin_limits(axis, count))
for axis, count, lo, hi in zip(domain, archive.shape, least, most))
self._options = {"mip_rel_gap": 0.}
if time_limit is not None:
if not 0. < time_limit < np.inf:
raise ValueError("time_limit must be positive and finite.")
self._options["time_limit"] = time_limit
if node_limit is not None:
self._options["node_limit"] = _positive_int(node_limit, "node_limit")
def _verify(self, candidate, cell):
point = np.asarray(candidate, dtype=float).copy()
if point.shape != self._objective.shape or not np.isfinite(point).all():
return None
rounded = np.rint(point[self._integer])
if np.any(abs(point[self._integer] - rounded) > 1e-6):
return None
point[self._integer] = rounded
low, high = self._bounds.lb, self._bounds.ub
if np.any(point < low - 1e-7) or np.any(point > high + 1e-7):
return None
point = np.clip(point, low, high)
for row in self._constraints:
values = row.A @ point
if not np.all(np.isfinite(values) & (values >= row.lb - 1e-7) & (values <= row.ub + 1e-7)):
return None
features = tuple(map(int, self._matrix @ point + self._offset))
fitness = float(self._objective @ point)
grid = self.archive
if (not np.isfinite(fitness) or not grid.in_bounds((fitness,), grid.fitness_domain)
or not grid.in_bounds(features, grid.features_domain) or grid.index_grid(features) != cell):
return None
genome = tuple(int(value) if integer else float(value) for value, integer in zip(point, self._integer))
return genome, fitness, features
def _solve(self, cell):
lo, hi = zip(*(axis[i] for axis, i in zip(self._limits, cell)))
if any(a > b for a, b in zip(lo, hi)):
return MILPCellResult(cell, "infeasible", message="The cell contains no reachable integer descriptor values under the decision bounds.")
niche = LinearConstraint(self._matrix, np.asarray(lo, dtype=float) - self._offset,
np.asarray(hi, dtype=float) - self._offset)
result = milp(self._sign * self._objective, bounds=self._bounds, integrality=self._integer,
constraints=(*self._constraints, niche), options=self._options)
status = int(result.status)
message = str(result.message)
if status == 2:
return MILPCellResult(cell, "infeasible", solver_status=status, message=message)
limit = getattr(result, "mip_dual_bound", None)
objective_bound = self._sign * float(limit) if limit is not None and np.isfinite(limit) else None
incumbent = self._verify(result.x, cell) if status in (0, 1) and result.x is not None else None
if incumbent is None:
if status == 0 or result.x is not None:
message += " No independently verified incumbent."
return MILPCellResult(cell, "unresolved", objective_bound=objective_bound,
solver_status=status, message=message)
genome, fitness, features = incumbent
elite = Individual(list(genome), fitness=Fitness((fitness,), weights=self._weights), features=Features(features))
self.archive.add(elite)
return MILPCellResult(cell, "optimal" if status == 0 else "unresolved", genome, fitness, features,
objective_bound, status, message)
## @brief Solve all cells or a requested subset in order.
[docs]
def run(self, cells=None):
"""Return a MILPCellResult for each requested cell, including empty ones.
Call again with a subset to retry unresolved cells. Verified incumbents
can enter the grid even when the solve reaches its time or node limit.
"""
if tuple(self.archive.fitness_weights or ()) != self._weights:
raise ValueError("The archive objective direction has changed.")
selected = tuple(self.archive.solutions) if cells is None else tuple(tuple(map(index, cell)) for cell in cells)
if len(set(selected)) != len(selected) or any(cell not in self.archive.solutions for cell in selected):
raise ValueError("Specify distinct valid grid cells.")
return tuple(self._solve(cell) for cell in selected)