6"""Find diverse near-optimal designs with a bounded hierarchy of SciPy MILP solves."""
8from dataclasses
import dataclass
9from operator
import index
12from scipy.optimize
import Bounds, LinearConstraint, milp
13from scipy.sparse
import csr_matrix
15from ._population
import _attempt_budget
16from .milp_portfolio
import _constraints
17from .modern
import _positive_int
19__all__ = [
"DiversiTreeResult",
"solve_diversitree"]
23@dataclass(frozen=True)
25 """Keep one mixed-integer point per distinct selected binary projection."""
28 designs: tuple[tuple[int | float, ...], ...]
29 qualities: tuple[float, ...]
30 binary_indices: tuple[int, ...]
33 quality_cutoff: float |
None
38 """Return the mean pairwise Hamming distance divided by the binary dimension."""
43 return float(np.sum(ones * (size - ones)) / (size * (size - 1) / 2 * len(self.
binary_indices)))
46@dataclass(frozen=True)
48 prefix: tuple[int, ...]
52def _select_node(queue, signatures, width, alpha, beta, seed_solutions):
53 if len(signatures) < seed_solutions
or (
not alpha
and not beta):
54 return min(range(len(queue)), key=
lambda i: queue[i].bound)
55 bounds = np.asarray([node.bound
for node
in queue])
56 scaled = bounds / max(1., float(np.abs(bounds).max()))
57 relative = (scaled - scaled.min()) / (float(np.ptp(scaled))
or 1.)
58 frequency = np.asarray(signatures, dtype=float).mean(axis=0)
62 depth = len(node.prefix)
63 agreement = float(np.mean(np.where(node.prefix, frequency[:depth], 1. - frequency[:depth])))
if depth
else .5
64 return (1. - alpha - beta) * relative[i] + alpha * agreement + beta * depth / width
66 return min(range(len(queue)), key=priority)
69def _verify(candidate, low, high, integer, rows):
70 point = np.asarray(candidate, dtype=float).copy()
71 if point.shape != low.shape
or not np.isfinite(point).all():
73 rounded = np.rint(point[integer])
74 if np.any(np.abs(point[integer] - rounded) > 1e-6):
76 point[integer] = rounded
77 if np.any(point < low - 1e-7)
or np.any(point > high + 1e-7):
79 point = np.clip(point, low, high)
81 values = row.A @ point
82 if not (np.isfinite(values) & (values >= row.lb - 1e-7) & (values <= row.ub + 1e-7)).all():
102def solve_diversitree(objective, bounds, size, *, budget, integrality=None, constraints=(), binary_indices=
None,
103 quality_loss=0., maximize=
True, alpha=.7, beta=.1, seed_solutions=2, time_limit=
None):
104 """Use DiversiTree's bound, partial diversity, and depth priorities.
106 The outer tree branches over binary projections. Each node uses SciPy
107 MILP as an exact subproblem oracle. A verified node optimum contributes
108 one representative. Partition the remaining node by the first bit
109 where its projection differs from that representative. Open nodes
110 inherit their parent's valid objective bound. The method returns a
111 bounded collection, with a certificate for the reference fitness.
113 objective = np.asarray(objective, dtype=float)
114 if objective.ndim != 1
or not len(objective)
or not np.isfinite(objective).all():
115 raise ValueError(
"Supply one finite objective coefficient per coordinate.")
116 if not isinstance(bounds, Bounds):
117 raise TypeError(
"bounds must be scipy.optimize.Bounds.")
118 size, budget = _positive_int(size,
"size"), _positive_int(budget,
"budget")
119 seed_solutions = _attempt_budget(seed_solutions)
120 if type(maximize)
is not bool
or not 0. <= quality_loss < np.inf
or not (alpha >= 0
and beta >= 0
and alpha + beta <= 1.):
121 raise ValueError(
"Use nonnegative finite quality_loss and nonnegative alpha and beta summing to at most one.")
122 options = {
"mip_rel_gap": 0.}
123 if time_limit
is not None:
124 if not 0. < time_limit < np.inf:
125 raise ValueError(
"time_limit must be positive and finite.")
126 options[
"time_limit"] = time_limit
127 low = np.broadcast_to(np.asarray(bounds.lb, dtype=float), objective.shape).copy()
128 high = np.broadcast_to(np.asarray(bounds.ub, dtype=float), objective.shape).copy()
129 mask = np.ones(len(objective))
if integrality
is None else np.broadcast_to(np.asarray(integrality), objective.shape)
130 if not np.isin(mask, (0, 1)).all()
or not np.isfinite(low).all()
or not np.isfinite(high).all():
131 raise ValueError(
"Use finite bounds and an integrality mask containing zeros and ones.")
132 integer = mask.astype(bool)
133 low[integer], high[integer] = np.ceil(low[integer]), np.floor(high[integer])
134 if np.any(low > high)
or np.any(np.maximum(np.abs(low[integer]), np.abs(high[integer])) > 2**53):
135 raise ValueError(
"Supply nonempty bounds and exactly representable integer endpoints.")
136 free_binary = set(map(int, np.flatnonzero(integer & (low == 0.) & (high == 1.))))
137 axes = tuple(sorted(free_binary))
if binary_indices
is None else tuple(map(index, binary_indices))
138 if not axes
or len(axes) != len(set(axes))
or not set(axes) <= free_binary:
139 raise ValueError(
"Select distinct free binary coordinates for diversity.")
140 rows = _constraints(constraints, len(objective))
141 costs = -objective
if maximize
else objective
142 base = milp(costs, bounds=Bounds(low, high), integrality=mask, constraints=rows, options=options)
143 root = _verify(base.x, low, high, integer, rows)
if base.status == 0
else None
144 best_cost =
None if root
is None else float(costs @ root)
145 if best_cost
is None or not np.isfinite(best_cost):
146 status =
"infeasible" if base.status == 2
else "unresolved"
148 cutoff = best_cost + quality_loss
149 if not np.isfinite(cutoff):
150 raise ValueError(
"The resulting quality cutoff must be finite.")
151 bounded_rows = (*rows, LinearConstraint(csr_matrix([costs]), -np.inf, cutoff))
152 queue, designs, values, signatures = [], [], [], []
154 def collect(prefix, point, bound):
155 signature = tuple(int(point[i])
for i
in axes)
156 signatures.append(signature)
157 designs.append(tuple(int(x)
if discrete
else float(x)
for x, discrete
in zip(point, integer)))
158 values.append(float(objective @ point))
159 queue.extend(
_Node(signature[:i] + (1 - signature[i],), bound)
for i
in range(len(prefix), len(axes)))
161 collect((), root, best_cost)
162 calls, message = 1,
""
163 while queue
and len(designs) < size
and calls < budget:
164 node = queue.pop(_select_node(queue, signatures, len(axes), alpha, beta, seed_solutions))
165 lower, upper = low.copy(), high.copy()
166 fixed = list(axes[:len(node.prefix)])
167 lower[fixed] = upper[fixed] = node.prefix
168 solved = milp(costs, bounds=Bounds(lower, upper), integrality=mask, constraints=bounded_rows, options=options)
170 if solved.status == 2:
172 point = _verify(solved.x, lower, upper, integer, bounded_rows)
if solved.status == 0
else None
173 value =
None if point
is None else float(costs @ point)
174 if value
is None or not np.isfinite(value)
or value > cutoff + 1e-7:
175 message = str(solved.message)
177 collect(node.prefix, point, value)
178 status = (
"target-reached" if len(designs) == size
else "unresolved" if message
else
179 "budget-exhausted" if queue
else "search-exhausted")
180 sign = -1.
if maximize
else 1.
181 return DiversiTreeResult(status, tuple(designs), tuple(values), axes, calls, sign * best_cost, sign * cutoff, message)
Measured representatives, solver termination, and the certified quality reference.
mean_binary_distance(self)