QDpy
Loading...
Searching...
No Matches
cpsat_archive.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Solve one clone of an OR-Tools model per requested descriptor cell."""
7
8from dataclasses import dataclass
9from math import ceil, floor, isfinite
10from operator import index
11
12from qdpy.containers import Grid
13from qdpy.phenotype import Features, Fitness, Individual
14
15from .milp_archive import _integer_bin_limits
16from .task_search import _validate_grid
17
18__all__ = ["CPSATArchiveSearch", "CPSATCellResult"]
19
20
21
22@dataclass(frozen=True)
24 """Report solver status, incumbent, and raw-objective bound when available.
25
26 The status is "optimal", "feasible", "infeasible", or "unresolved".
27 The genome lists values of all model variables in model index order.
28 Integer-empty cells are infeasible without calling the solver.
29 """
30
31 cell: tuple[int, ...]
32 status: str
33 genome: tuple[int, ...] | None = None
34 fitness: int | None = None
35 features: tuple[int, ...] | None = None
36 objective_bound: int | float | None = None
37 solver_status: str | None = None
38
39
40
42 """Solve independent grid cells using an existing integer CP-SAT model.
43
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.
55 """
56
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.")
71 seed = index(seed)
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.")
77 try:
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.")
83
84 self.archive = archive
85 self._model = model.clone()
86 self._variable_count = len(model.proto.variables)
87 self._weights = tuple(archive.fitness_weights)
88 self._objective, self._descriptors = objective, descriptors
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]
92 self._empty_fitness = ceil(fit_low) > floor(fit_high)
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)
96 # Have CP-SAT validate integrality even when an axis has no integer values.
97 self._model.add_linear_constraint(expression, lower, max(lower, upper))
98 if self._weights[0] > 0.:
99 self._model.maximize(objective)
100 else:
101 self._model.minimize(objective)
102 self._validate_model(self._model)
103 self._time_limit, self._work_limit, self._seed = time_limit, deterministic_time_limit, seed
104
105 @staticmethod
106 def _validate_model(model):
107 issue = model.validate()
108 if issue:
109 raise ValueError(f"Invalid CP-SAT model: {issue}")
110
111 def _solve(self, cell):
112 from ortools.sat.python import cp_model
113
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):
116 return CPSATCellResult(cell, "infeasible")
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.
125 if self._time_limit is not None:
126 solver.parameters.max_time_in_seconds = self._time_limit
127 if self._work_limit is not None:
128 solver.parameters.max_deterministic_time = self._work_limit
129
130 status = solver.solve(model)
131 name = solver.status_name(status)
132 if status == cp_model.MODEL_INVALID:
133 self._validate_model(model)
134 raise ValueError("CP-SAT rejected the model for this cell.")
135 if status == cp_model.INFEASIBLE:
136 return CPSATCellResult(cell, "infeasible", solver_status=name)
137 if status not in (cp_model.OPTIMAL, cp_model.FEASIBLE):
138 return CPSATCellResult(cell, "unresolved", solver_status=name)
139
140 genome = tuple(solver.value(model.get_int_var_from_proto_index(i))
141 for i in range(self._variable_count))
142 fitness = solver.value(self._objective)
143 features = tuple(solver.value(expr) for expr in self._descriptors)
144 archive = self.archive
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.")
148 archive.add(Individual(genome, fitness=Fitness((fitness,), weights=self._weights),
149 features=Features(features)))
150 optimal = status == cp_model.OPTIMAL
151 bound = fitness if optimal else solver.best_objective_bound
152 return CPSATCellResult(cell, "optimal" if optimal else "feasible",
153 genome, fitness, features, bound, name)
154
155
156 def run(self, cells=None):
157 """Return one CP-SAT report per selected cell. Call again to retry cells."""
158 if tuple(self.archive.fitness_weights or ()) != self._weights:
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)
Add one optimal or verified feasible assignment per grid niche.
run(self, cells=None)
Solve all grid cells or an explicit subset in order.
Record a solver proof or the best verified solution in one cell.
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405