42 """Solve independent grid cells using an existing integer CP-SAT model.
44 :param archive: Empty best-only rectangular Grid with one configured
45 objective and room for every cell. Use finite objective and
46 descriptor bounds within the float64 exact-integer range.
47 :param model: OR-Tools CpModel containing the design constraints.
48 :param objective: Integral linear expression over that model's variables.
49 The grid's fitness direction governs the solve.
50 :param descriptors: Integral linear expressions over the model variables
51 in grid axis order, including constant integer expressions if desired.
52 :param time_limit: Optional positive seconds per solve.
53 :param deterministic_time_limit: Optional positive CP-SAT work limit per cell.
54 :param seed: Nonnegative 32-bit CP-SAT seed. Each cell uses one worker.
57 def __init__(self, archive, model, *, objective, descriptors, time_limit=None,
58 deterministic_time_limit=None, seed=0):
59 _validate_grid(archive)
60 if (type(archive)
is not Grid
or archive.capacity < len(archive.solutions)
61 or archive.fitness_score_names
or archive.features_score_names
or not archive.fitness_weights):
62 raise ValueError(
"Supply a rectangular grid with a signed objective and capacity for every cell.")
63 for lower, upper
in (*archive.fitness_domain, *archive.features_domain):
64 if not -2**53 <= lower <= upper <= 2**53:
65 raise ValueError(
"Use finite archive bounds within the float64 exact-integer range.")
66 if any(lower >= upper
for lower, upper
in archive.features_domain):
67 raise ValueError(
"Supply increasing descriptor domains.")
68 descriptors = tuple(descriptors)
69 if len(descriptors) != len(archive.shape):
70 raise ValueError(
"Supply one integer expression per descriptor axis.")
72 if not 0 <= seed < 2**31:
73 raise ValueError(
"Use a nonnegative 32-bit seed.")
74 for limit
in (time_limit, deterministic_time_limit):
75 if limit
is not None and (
not isfinite(limit)
or limit <= 0.):
76 raise ValueError(
"Solver limits must be positive and finite.")
78 from ortools.sat.python
import cp_model
79 except ImportError
as error:
80 raise ImportError(
"CPSATArchiveSearch requires OR-Tools. Install qdpy[cpsat].")
from error
81 if not isinstance(model, cp_model.CpModel):
82 raise TypeError(
"model must be an OR-Tools CpModel.")
85 self.
_model = model.clone()
87 self.
_weights = tuple(archive.fitness_weights)
89 self.
_limits = tuple(_integer_bin_limits(domain, size)
90 for domain, size
in zip(archive.features_domain, archive.shape))
91 fit_low, fit_high = archive.fitness_domain[0]
93 expressions = (objective, *descriptors)
94 for expression, (low, high)
in zip(expressions, (*archive.fitness_domain, *archive.features_domain)):
95 lower, upper = ceil(low), floor(high)
97 self.
_model.add_linear_constraint(expression, lower, max(lower, upper))
99 self.
_model.maximize(objective)
101 self.
_model.minimize(objective)
106 def _validate_model(model):
107 issue = model.validate()
109 raise ValueError(f
"Invalid CP-SAT model: {issue}")
111 def _solve(self, cell):
112 from ortools.sat.python
import cp_model
114 limits = tuple(axis[i]
for axis, i
in zip(self.
_limits, cell))
115 if self.
_empty_fitness or any(low > high
for low, high
in limits):
117 model = self.
_model.clone()
118 for expression, (low, high)
in zip(self.
_descriptors, limits):
119 model.add_linear_constraint(expression, low, high)
120 solver = cp_model.CpSolver()
121 solver.parameters.num_search_workers = 1
122 solver.parameters.random_seed = self.
_seed
123 solver.parameters.relative_gap_limit = 0.
124 solver.parameters.absolute_gap_limit = 0.
126 solver.parameters.max_time_in_seconds = self.
_time_limit
128 solver.parameters.max_deterministic_time = self.
_work_limit
130 status = solver.solve(model)
131 name = solver.status_name(status)
132 if status == cp_model.MODEL_INVALID:
134 raise ValueError(
"CP-SAT rejected the model for this cell.")
135 if status == cp_model.INFEASIBLE:
137 if status
not in (cp_model.OPTIMAL, cp_model.FEASIBLE):
140 genome = tuple(solver.value(model.get_int_var_from_proto_index(i))
143 features = tuple(solver.value(expr)
for expr
in self.
_descriptors)
145 if (
not archive.in_bounds((fitness,), archive.fitness_domain)
146 or not archive.in_bounds(features, archive.features_domain)
or archive.index_grid(features) != cell):
147 raise RuntimeError(
"The solver incumbent does not satisfy the requested archive cell.")
150 optimal = status == cp_model.OPTIMAL
151 bound = fitness
if optimal
else solver.best_objective_bound
153 genome, fitness, features, bound, name)
156 def run(self, cells=None):
157 """Return one CP-SAT report per selected cell. Call again to retry cells."""
159 raise ValueError(
"The archive objective weights changed.")
160 selected = tuple(self.
archive.solutions)
if cells
is None else tuple(tuple(map(index, cell))
for cell
in cells)
161 if len(set(selected)) != len(selected)
or any(cell
not in self.
archive.solutions
for cell
in selected):
162 raise ValueError(
"Specify distinct valid grid cells.")
163 return tuple(self.
_solve(cell)
for cell
in selected)