QDpy
Loading...
Searching...
No Matches
milp_portfolio.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
6
7"""Maximize minimum Hamming distance subject to a common quality floor."""
8
9from dataclasses import dataclass
10from itertools import combinations
11
12import numpy as np
13from scipy.optimize import Bounds, LinearConstraint, milp
14from scipy.sparse import coo_matrix, csr_matrix
15
16from .modern import _positive_int
17
18__all__ = ["MILPPortfolioResult", "solve_binary_portfolio"]
19
20
21
22@dataclass(frozen=True)
24 """Report raw objective values and a bound in units of Hamming distance.
25
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.
30 """
31
32 status: str
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
39 solver_calls: int = 0
40 message: str = ""
41
42
43def _constraints(rows, width):
44 rows = (rows,) if isinstance(rows, LinearConstraint) else tuple(rows)
45 copied = []
46 for row in 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()))
56 return tuple(copied)
57
58
59def _binary_rows(values, size, width, constraints):
60 if values is None:
61 return None
62 values = np.asarray(values, dtype=float)
63 if values.ndim != 1 or len(values) < size * width:
64 return None
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)):
69 return None
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():
74 return None
75 return rounded.astype(np.int8)
76
77
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 = [], [], [], [], []
83
84 def add(indices, coefficients, low, high):
85 values.extend(coefficients)
86 row_ids.extend([len(lower)] * len(indices))
87 columns.extend(indices)
88 lower.append(low)
89 upper.append(high)
90
91 for design in range(size):
92 offset = design * width
93 for row in rows:
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)
97
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)
107
108 matrix = coo_matrix((values, (row_ids, columns)), shape=(len(lower), variables)).tocsc()
109 objective = np.zeros(variables)
110 objective[-1] = -1.
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
113
114
115
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.
127
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.
132 """
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)
153 if base.status == 2:
154 return MILPPortfolioResult("infeasible", solver_calls=1, message=str(base.message))
155 point = _binary_rows(base.x, 1, width, constraints) if base.status == 0 else None
156 if point is None:
157 return MILPPortfolioResult("unresolved", solver_calls=1,
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:
170 return MILPPortfolioResult("infeasible", **common)
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)
174 if distance > 0:
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)
178 return MILPPortfolioResult("optimal" if optimal else "unresolved", designs, qualities,
179 minimum_distance=distance, **common)
180 return MILPPortfolioResult("unresolved", **common)
Verified designs and solver outcomes for a near-optimal portfolio.