QDpy
Loading...
Searching...
No Matches
milp_archive.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Populate a Grid with verified solutions and one solver result per requested cell."""
7
8from dataclasses import dataclass
9from math import ceil, floor
10from operator import index
11
12import numpy as np
13from scipy.optimize import Bounds, LinearConstraint, milp
14
15from qdpy.containers import Grid
16from qdpy.containers.grids import _bin_index
17from qdpy.phenotype import Features, Fitness, Individual
18from .constrained import _validate_grid
19from .modern import _positive_int
20
21__all__ = ["MILPArchiveSearch", "MILPCellResult"]
22
23
24
25@dataclass(frozen=True)
27 """Keep the verified incumbent and the original termination details.
28
29 :ivar cell: Rectangular cell index.
30 :ivar status: "optimal", "infeasible", or "unresolved".
31 :ivar genome: Verified incumbent, if available.
32 :ivar fitness: Raw linear objective of the incumbent.
33 :ivar features: Integer-valued descriptors of the incumbent.
34 :ivar objective_bound: Solver bound in raw units, when reported.
35 :ivar solver_status: SciPy status code, or None if no solver call was needed.
36 :ivar message: Original termination or verification message.
37 """
38
39 cell: tuple
40 status: str
41 genome: tuple | None = None
42 fitness: float | None = None
43 features: tuple | None = None
44 objective_bound: float | None = None
45 solver_status: int | None = None
46 message: str = ""
47
48
49def _integer_bin_limits(domain, size):
50 lo, hi = map(float, domain)
51 width = (hi - lo) / size
52
53 def first_at_least(target):
54 left, right = ceil(lo), floor(hi) + 1
55 while left < right:
56 mid = (left + right) // 2
57 if _bin_index(mid, lo, hi, size, width) < target:
58 left = mid + 1
59 else:
60 right = mid
61 return left
62
63 edges = (ceil(lo), *(first_at_least(i) for i in range(1, size)), floor(hi) + 1)
64 return tuple((a, b - 1) for a, b in zip(edges, edges[1:]))
65
66
67
69 """Build one MILP per requested cell and verify its incumbent before admission.
70
71 Decision coordinates can be continuous or integer. Each descriptor is
72 an integer affine function of integer decision coordinates. Cell
73 constraints use the exact integer endpoints implied by Grid.index_grid.
74 The supplied grid's objective direction and objective bounds govern
75 optimization. An "optimal" result means HiGHS reported optimality with
76 zero requested relative gap and QDpy verified the incumbent.
77
78 :param archive: Empty parentless rectangular one-elite Grid with room for every cell.
79 :param objective: One finite linear objective coefficient per coordinate.
80 :param bounds: Finite lower and upper scipy.optimize.Bounds for the decision vector.
81 :param descriptor_matrix: One integer coefficient row per descriptor.
82 :param descriptor_offset: Optional integer constant per descriptor (default zero).
83 :param integrality: Boolean mask with 1 for integer and 0 for continuous coordinates.
84 Defaults to integer on every axis.
85 :param constraints: A LinearConstraint or sequence of shared constraints.
86 :param time_limit: Optional positive time limit in seconds per cell.
87 :param node_limit: Optional positive node limit per cell.
88 """
89
90 def __init__(self, archive, objective, bounds, descriptor_matrix, *, descriptor_offset=None,
91 integrality=None, constraints=(), time_limit=None, node_limit=None):
92 _validate_grid(archive)
93 if (type(archive) is not Grid or archive.parents or archive.capacity < len(archive.solutions)
94 or archive.fitness_score_names or archive.features_score_names
95 or len(archive.fitness_weights or ()) != 1 or not np.isfinite(archive.fitness_weights[0])
96 or not archive.fitness_weights[0]):
97 raise ValueError("Use a parentless Grid with one signed objective and capacity for every cell.")
98 objective = np.array(objective, dtype=float, copy=True)
99 if objective.ndim != 1 or not len(objective) or not np.isfinite(objective).all():
100 raise ValueError("Provide a nonempty finite objective vector.")
101 if not isinstance(bounds, Bounds):
102 raise TypeError("bounds must be scipy.optimize.Bounds.")
103 dim = len(objective)
104 low = np.broadcast_to(np.asarray(bounds.lb, dtype=float), (dim,)).copy()
105 high = np.broadcast_to(np.asarray(bounds.ub, dtype=float), (dim,)).copy()
106 mask = np.ones(dim) if integrality is None else np.broadcast_to(np.asarray(integrality), (dim,))
107 if not np.isin(mask, (0, 1)).all():
108 raise ValueError("integrality must contain only 0 and 1.")
109 integer = mask.astype(bool)
110 if (not np.isfinite(low).all() or not np.isfinite(high).all() or np.any(low > high)
111 or np.any(np.ceil(low[integer]) > np.floor(high[integer]))):
112 raise ValueError("Use finite, nonempty decision bounds.")
113 # Integer coordinates are rounded and then verified after the solve.
114 low[integer], high[integer] = np.ceil(low[integer]), np.floor(high[integer])
115 if np.any(np.maximum(abs(low[integer]), abs(high[integer])) > 2**53):
116 raise ValueError("Integer bounds must be exactly representable in float64.")
117 axes = len(archive.shape)
118 domain = np.asarray(archive.features_domain, dtype=float)
119 matrix = np.array(descriptor_matrix, dtype=float, copy=True)
120 offset = np.zeros(axes) if descriptor_offset is None else np.array(descriptor_offset, dtype=float, copy=True)
121 if (domain.shape != (axes, 2) or not np.isfinite(domain).all() or np.max(abs(domain)) > 2**53
122 or np.any(domain[:, 0] >= domain[:, 1])):
123 raise ValueError("Use finite increasing descriptor bounds within the float64 exact-integer range.")
124 if (matrix.shape != (axes, dim) or offset.shape != (axes,)
125 or not np.isfinite(matrix).all() or not np.isfinite(offset).all()
126 or np.any(matrix != np.rint(matrix)) or np.any(offset != np.rint(offset))
127 or np.any(matrix[:, ~integer] != 0) or np.max(abs(matrix)) > 2**53
128 or np.any(abs(matrix) @ np.maximum(abs(low), abs(high)) + abs(offset) > 2**53)):
129 raise ValueError("Descriptors must be integer affine functions of integer variables within the exact range.")
130
131 rows = (constraints,) if isinstance(constraints, LinearConstraint) else tuple(constraints)
132 if any(not isinstance(row, LinearConstraint) or row.A.shape[1] != dim for row in rows):
133 raise ValueError("Use linear constraints with one column per decision coordinate.")
134 fit_low, fit_high = archive.fitness_domain[0]
135 if np.isnan(fit_low) or np.isnan(fit_high) or fit_low > fit_high:
136 raise ValueError("Invalid archive objective bounds.")
137 if np.isfinite(fit_low) or np.isfinite(fit_high):
138 rows += (LinearConstraint(objective[None, :], fit_low, fit_high),)
139 self.archive, self._objective = archive, objective
140 self._weights = tuple(archive.fitness_weights)
141 self._sign = -1. if self._weights[0] > 0 else 1.
142 self._bounds, self._integer, self._constraints = Bounds(low, high), integer, rows
143 self._matrix, self._offset = matrix, offset
144 least = np.minimum(matrix * low, matrix * high).sum(axis=1) + offset
145 most = np.maximum(matrix * low, matrix * high).sum(axis=1) + offset
146 self._limits = tuple(tuple((max(a, int(lo)), min(b, int(hi)))
147 for a, b in _integer_bin_limits(axis, count))
148 for axis, count, lo, hi in zip(domain, archive.shape, least, most))
149 self._options = {"mip_rel_gap": 0.}
150 if time_limit is not None:
151 if not 0. < time_limit < np.inf:
152 raise ValueError("time_limit must be positive and finite.")
153 self._options["time_limit"] = time_limit
154 if node_limit is not None:
155 self._options["node_limit"] = _positive_int(node_limit, "node_limit")
156
157 def _verify(self, candidate, cell):
158 point = np.asarray(candidate, dtype=float).copy()
159 if point.shape != self._objective.shape or not np.isfinite(point).all():
160 return None
161 rounded = np.rint(point[self._integer])
162 if np.any(abs(point[self._integer] - rounded) > 1e-6):
163 return None
164 point[self._integer] = rounded
165 low, high = self._bounds.lb, self._bounds.ub
166 if np.any(point < low - 1e-7) or np.any(point > high + 1e-7):
167 return None
168 point = np.clip(point, low, high)
169 for row in self._constraints:
170 values = row.A @ point
171 if not np.all(np.isfinite(values) & (values >= row.lb - 1e-7) & (values <= row.ub + 1e-7)):
172 return None
173 features = tuple(map(int, self._matrix @ point + self._offset))
174 fitness = float(self._objective @ point)
175 grid = self.archive
176 if (not np.isfinite(fitness) or not grid.in_bounds((fitness,), grid.fitness_domain)
177 or not grid.in_bounds(features, grid.features_domain) or grid.index_grid(features) != cell):
178 return None
179 genome = tuple(int(value) if integer else float(value) for value, integer in zip(point, self._integer))
180 return genome, fitness, features
181
182 def _solve(self, cell):
183 lo, hi = zip(*(axis[i] for axis, i in zip(self._limits, cell)))
184 if any(a > b for a, b in zip(lo, hi)):
185 return MILPCellResult(cell, "infeasible", message="The cell contains no reachable integer descriptor values under the decision bounds.")
186 niche = LinearConstraint(self._matrix, np.asarray(lo, dtype=float) - self._offset,
187 np.asarray(hi, dtype=float) - self._offset)
188 result = milp(self._sign * self._objective, bounds=self._bounds, integrality=self._integer,
189 constraints=(*self._constraints, niche), options=self._options)
190 status = int(result.status)
191 message = str(result.message)
192 if status == 2:
193 return MILPCellResult(cell, "infeasible", solver_status=status, message=message)
194 limit = getattr(result, "mip_dual_bound", None)
195 objective_bound = self._sign * float(limit) if limit is not None and np.isfinite(limit) else None
196 incumbent = self._verify(result.x, cell) if status in (0, 1) and result.x is not None else None
197 if incumbent is None:
198 if status == 0 or result.x is not None:
199 message += " No independently verified incumbent."
200 return MILPCellResult(cell, "unresolved", objective_bound=objective_bound,
201 solver_status=status, message=message)
202 genome, fitness, features = incumbent
203 elite = Individual(list(genome), fitness=Fitness((fitness,), weights=self._weights), features=Features(features))
204 self.archive.add(elite)
205 return MILPCellResult(cell, "optimal" if status == 0 else "unresolved", genome, fitness, features,
206 objective_bound, status, message)
207
208
209 def run(self, cells=None):
210 """Return a MILPCellResult for each requested cell, including empty ones.
211
212 Call again with a subset to retry unresolved cells. Verified incumbents
213 can enter the grid even when the solve reaches its time or node limit.
214 """
215 if tuple(self.archive.fitness_weights or ()) != self._weights:
216 raise ValueError("The archive objective direction has changed.")
217 selected = tuple(self.archive.solutions) if cells is None else tuple(tuple(map(index, cell)) for cell in cells)
218 if len(set(selected)) != len(selected) or any(cell not in self.archive.solutions for cell in selected):
219 raise ValueError("Specify distinct valid grid cells.")
220 return tuple(self._solve(cell) for cell in selected)
Obtain a solver-backed reference archive for a bounded linear problem.
run(self, cells=None)
Solve all cells or a requested subset in order.
Solver outcome for a single requested descriptor cell.
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405