7"""Maximize minimum Hamming distance subject to a common quality floor."""
9from dataclasses
import dataclass
10from itertools
import combinations
13from scipy.optimize
import Bounds, LinearConstraint, milp
14from scipy.sparse
import coo_matrix, csr_matrix
16from .modern
import _positive_int
18__all__ = [
"MILPPortfolioResult",
"solve_binary_portfolio"]
22@dataclass(frozen=True)
24 """Report raw objective values and a bound in units of Hamming distance.
26 A status of optimal requires solver optimality and independent checks
27 on the rounded incumbent. An unresolved portfolio may still contain
28 a complete, verified set from a limited solve. A certified single-design
29 optimum is required before solving the portfolio problem.
33 designs: tuple[tuple[int, ...], ...] = ()
34 qualities: tuple[float, ...] = ()
35 optimum: float |
None =
None
36 quality_cutoff: float |
None =
None
37 minimum_distance: int |
None =
None
38 distance_upper_bound: float |
None =
None
43def _constraints(rows, width):
44 rows = (rows,)
if isinstance(rows, LinearConstraint)
else tuple(rows)
47 if not isinstance(row, LinearConstraint):
48 raise TypeError(
"Supply scipy.optimize.LinearConstraint objects.")
49 matrix = csr_matrix(row.A, dtype=float, copy=
True)
50 lower, upper = np.asarray(row.lb, dtype=float), np.asarray(row.ub, dtype=float)
51 if (matrix.shape[1] != width
or not np.isfinite(matrix.data).all()
52 or np.isnan(lower).any()
or np.isnan(upper).any()
or np.any(lower > upper)
53 or np.isposinf(lower).any()
or np.isneginf(upper).any()):
54 raise ValueError(
"Supply finite coefficients and valid constraint bounds.")
55 copied.append(LinearConstraint(matrix, lower.copy(), upper.copy()))
59def _binary_rows(values, size, width, constraints):
62 values = np.asarray(values, dtype=float)
63 if values.ndim != 1
or len(values) < size * width:
65 values = values[:size * width].reshape(size, width)
66 rounded = np.rint(values)
67 if (
not np.isfinite(values).all()
or not np.isin(rounded, (0., 1.)).all()
68 or np.any(abs(values - rounded) > 1e-6)):
70 for row
in constraints:
71 measured = row.A @ rounded.T
72 if not (np.isfinite(measured) & (measured >= row.lb[:,
None] - 1e-7)
73 & (measured <= row.ub[:,
None] + 1e-7)).all():
75 return rounded.astype(np.int8)
78def _joint_model(size, width, rows):
79 """Create sparse independent design rows and exact XOR distance rows."""
80 pairs = tuple(combinations(range(size), 2))
81 variables = (size + len(pairs)) * width + 1
82 values, row_ids, columns, lower, upper = [], [], [], [], []
84 def add(indices, coefficients, low, high):
85 values.extend(coefficients)
86 row_ids.extend([len(lower)] * len(indices))
87 columns.extend(indices)
91 for design
in range(size):
92 offset = design * width
94 for i, (low, high)
in enumerate(zip(row.lb, row.ub, strict=
True)):
95 start, stop = row.A.indptr[i:i + 2]
96 add(offset + row.A.indices[start:stop], row.A.data[start:stop], low, high)
98 for pair_id, (first, second)
in enumerate(pairs):
99 start = (size + pair_id) * width
100 for j
in range(width):
101 x, y, z = first * width + j, second * width + j, start + j
102 add((x, y, z), (1., 1., -1.), 0., np.inf)
103 add((x, y, z), (1., 1., 1.), -np.inf, 2.)
104 add((x, y, z), (-1., 1., 1.), 0., np.inf)
105 add((x, y, z), (1., -1., 1.), 0., np.inf)
106 add((*range(start, start + width), variables - 1), (*np.ones(width), -1.), 0., np.inf)
108 matrix = coo_matrix((values, (row_ids, columns)), shape=(len(lower), variables)).tocsc()
109 objective = np.zeros(variables)
111 bounds = Bounds(np.r_[np.zeros(variables - 1), 1.], np.r_[np.ones(variables - 1), width])
112 return objective, bounds, LinearConstraint(matrix, lower, upper), pairs
124def solve_binary_portfolio(objective, size, *, quality_loss=0., maximize=True, constraints=(),
125 time_limit=
None, node_limit=
None):
126 """First certify the quality reference, then optimize the portfolio jointly.
128 Both solves request zero relative MIP gap. Constraint verification uses
129 absolute tolerance 1e-7. Solver certificates retain the solver's
130 numerical tolerances. Solver calls and their limits apply separately
131 to the reference optimum and the joint problem.
133 objective = np.array(objective, dtype=float, copy=
True)
134 if objective.ndim != 1
or not len(objective)
or not np.isfinite(abs(objective).sum()):
135 raise ValueError(
"Supply a nonempty, finite and bounded objective vector.")
136 size = _positive_int(size,
"size")
137 if size < 2
or type(maximize)
is not bool
or not 0. <= quality_loss < np.inf:
138 raise ValueError(
"Use size >= 2, a Boolean maximize, and finite nonnegative quality_loss.")
139 options = {
"mip_rel_gap": 0.}
140 if time_limit
is not None:
141 if not 0. < time_limit < np.inf:
142 raise ValueError(
"time_limit must be positive and finite.")
143 options[
"time_limit"] = time_limit
144 if node_limit
is not None:
145 options[
"node_limit"] = _positive_int(node_limit,
"node_limit")
146 width = len(objective)
147 constraints = _constraints(constraints, width)
148 if (size - 1).bit_length() > width:
149 return MILPPortfolioResult(
"infeasible", message=
"There are fewer binary designs than requested.")
150 sign = 1.
if maximize
else -1.
151 base = milp(-sign * objective, integrality=np.ones(width), bounds=Bounds(0., 1.),
152 constraints=constraints, options=options)
155 point = _binary_rows(base.x, 1, width, constraints)
if base.status == 0
else None
158 message=f
"No certified quality reference. {base.message}")
159 optimum = float(point[0] @ objective)
160 cutoff = optimum - sign * quality_loss
161 if not np.isfinite(cutoff):
162 raise ValueError(
"The quality cutoff must be finite.")
163 quality = LinearConstraint(csr_matrix([sign * objective]), sign * cutoff, np.inf)
164 model, bounds, joint, pairs = _joint_model(size, width, (*constraints, quality))
165 result = milp(model, integrality=np.ones(len(model)), bounds=bounds, constraints=joint, options=options)
166 bound = getattr(result,
"mip_dual_bound",
None)
167 common = dict(optimum=optimum, quality_cutoff=cutoff, solver_calls=2, message=str(result.message),
168 distance_upper_bound=-float(bound)
if bound
is not None and np.isfinite(bound)
else None)
169 if result.status == 2:
171 points = _binary_rows(result.x, size, width, (*constraints, quality))
if result.status
in (0, 1)
else None
172 if points
is not None:
173 distance = min(int(np.count_nonzero(points[i] != points[j]))
for i, j
in pairs)
175 optimal = result.status == 0
and abs(distance - result.x[-1]) <= 1e-6
176 designs = tuple(sorted(tuple(map(int, point))
for point
in points))
177 qualities = tuple(float(np.dot(point, objective))
for point
in designs)
179 minimum_distance=distance, **common)
Verified designs and solver outcomes for a near-optimal portfolio.