QDpy
Loading...
Searching...
No Matches
diversitree.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Find diverse near-optimal designs with a bounded hierarchy of SciPy MILP solves."""
7
8from dataclasses import dataclass
9from operator import index
10
11import numpy as np
12from scipy.optimize import Bounds, LinearConstraint, milp
13from scipy.sparse import csr_matrix
14
15from ._population import _attempt_budget
16from .milp_portfolio import _constraints
17from .modern import _positive_int
18
19__all__ = ["DiversiTreeResult", "solve_diversitree"]
20
21
22
23@dataclass(frozen=True)
25 """Keep one mixed-integer point per distinct selected binary projection."""
26
27 status: str
28 designs: tuple[tuple[int | float, ...], ...]
29 qualities: tuple[float, ...]
30 binary_indices: tuple[int, ...]
31 solver_calls: int
32 optimum: float | None
33 quality_cutoff: float | None
34 message: str = ""
35
36 @property
38 """Return the mean pairwise Hamming distance divided by the binary dimension."""
39 size = len(self.designs)
40 if size < 2:
41 return 0.
42 ones = np.asarray(self.designs)[:, self.binary_indices].sum(axis=0)
43 return float(np.sum(ones * (size - ones)) / (size * (size - 1) / 2 * len(self.binary_indices)))
44
45
46@dataclass(frozen=True)
47class _Node:
48 prefix: tuple[int, ...]
49 bound: float
50
51
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)
59
60 def priority(i):
61 node = queue[i]
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
65
66 return min(range(len(queue)), key=priority)
67
68
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():
72 return None
73 rounded = np.rint(point[integer])
74 if np.any(np.abs(point[integer] - rounded) > 1e-6):
75 return None
76 point[integer] = rounded
77 if np.any(point < low - 1e-7) or np.any(point > high + 1e-7):
78 return None
79 point = np.clip(point, low, high)
80 for row in rows:
81 values = row.A @ point
82 if not (np.isfinite(values) & (values >= row.lb - 1e-7) & (values <= row.ub + 1e-7)).all():
83 return None
84 return point
85
86
87
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.
105
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.
112 """
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"
147 return DiversiTreeResult(status, (), (), axes, 1, None, None, str(base.message))
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 = [], [], [], []
153
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)))
160
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)
169 calls += 1
170 if solved.status == 2:
171 continue
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)
176 continue
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.