69 """Build one MILP per requested cell and verify its incumbent before admission.
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.
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.
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.")
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.")
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.")
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),)
140 self.
_weights = tuple(archive.fitness_weights)
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))
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")
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():
161 rounded = np.rint(point[self.
_integer])
162 if np.any(abs(point[self.
_integer] - rounded) > 1e-6):
166 if np.any(point < low - 1e-7)
or np.any(point > high + 1e-7):
168 point = np.clip(point, low, high)
170 values = row.A @ point
171 if not np.all(np.isfinite(values) & (values >= row.lb - 1e-7) & (values <= row.ub + 1e-7)):
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):
179 genome = tuple(int(value)
if integer
else float(value)
for value, integer
in zip(point, self.
_integer))
180 return genome, fitness, features
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)
190 status = int(result.status)
191 message = str(result.message)
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
205 return MILPCellResult(cell,
"optimal" if status == 0
else "unresolved", genome, fitness, features,
206 objective_bound, status, message)
209 def run(self, cells=None):
210 """Return a MILPCellResult for each requested cell, including empty ones.
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.
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)