Source code for qdpy.algorithms.milp_portfolio

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Joint mixed-integer optimization of high-quality binary portfolios.
# @see https://cdn.aaai.org/AAAI/2005/AAAI05-059.pdf
# @see https://ijcai.org/proceedings/2015/43

"""Maximize minimum Hamming distance subject to a common quality floor."""

from dataclasses import dataclass
from itertools import combinations

import numpy as np
from scipy.optimize import Bounds, LinearConstraint, milp
from scipy.sparse import coo_matrix, csr_matrix

from .modern import _positive_int

__all__ = ["MILPPortfolioResult", "solve_binary_portfolio"]


## @brief Verified designs and solver outcomes for a near-optimal portfolio.
[docs] @dataclass(frozen=True) class MILPPortfolioResult: """Report raw objective values and a bound in units of Hamming distance. A status of optimal requires solver optimality and independent checks on the rounded incumbent. An unresolved portfolio may still contain a complete, verified set from a limited solve. A certified single-design optimum is required before solving the portfolio problem. """ status: str designs: tuple[tuple[int, ...], ...] = () qualities: tuple[float, ...] = () optimum: float | None = None quality_cutoff: float | None = None minimum_distance: int | None = None distance_upper_bound: float | None = None solver_calls: int = 0 message: str = ""
def _constraints(rows, width): rows = (rows,) if isinstance(rows, LinearConstraint) else tuple(rows) copied = [] for row in rows: if not isinstance(row, LinearConstraint): raise TypeError("Supply scipy.optimize.LinearConstraint objects.") matrix = csr_matrix(row.A, dtype=float, copy=True) lower, upper = np.asarray(row.lb, dtype=float), np.asarray(row.ub, dtype=float) if (matrix.shape[1] != width or not np.isfinite(matrix.data).all() or np.isnan(lower).any() or np.isnan(upper).any() or np.any(lower > upper) or np.isposinf(lower).any() or np.isneginf(upper).any()): raise ValueError("Supply finite coefficients and valid constraint bounds.") copied.append(LinearConstraint(matrix, lower.copy(), upper.copy())) return tuple(copied) def _binary_rows(values, size, width, constraints): if values is None: return None values = np.asarray(values, dtype=float) if values.ndim != 1 or len(values) < size * width: return None values = values[:size * width].reshape(size, width) rounded = np.rint(values) if (not np.isfinite(values).all() or not np.isin(rounded, (0., 1.)).all() or np.any(abs(values - rounded) > 1e-6)): return None for row in constraints: measured = row.A @ rounded.T if not (np.isfinite(measured) & (measured >= row.lb[:, None] - 1e-7) & (measured <= row.ub[:, None] + 1e-7)).all(): return None return rounded.astype(np.int8) def _joint_model(size, width, rows): """Create sparse independent design rows and exact XOR distance rows.""" pairs = tuple(combinations(range(size), 2)) variables = (size + len(pairs)) * width + 1 values, row_ids, columns, lower, upper = [], [], [], [], [] def add(indices, coefficients, low, high): values.extend(coefficients) row_ids.extend([len(lower)] * len(indices)) columns.extend(indices) lower.append(low) upper.append(high) for design in range(size): offset = design * width for row in rows: for i, (low, high) in enumerate(zip(row.lb, row.ub, strict=True)): start, stop = row.A.indptr[i:i + 2] add(offset + row.A.indices[start:stop], row.A.data[start:stop], low, high) for pair_id, (first, second) in enumerate(pairs): start = (size + pair_id) * width for j in range(width): x, y, z = first * width + j, second * width + j, start + j add((x, y, z), (1., 1., -1.), 0., np.inf) add((x, y, z), (1., 1., 1.), -np.inf, 2.) add((x, y, z), (-1., 1., 1.), 0., np.inf) add((x, y, z), (1., -1., 1.), 0., np.inf) add((*range(start, start + width), variables - 1), (*np.ones(width), -1.), 0., np.inf) matrix = coo_matrix((values, (row_ids, columns)), shape=(len(lower), variables)).tocsc() objective = np.zeros(variables) objective[-1] = -1. bounds = Bounds(np.r_[np.zeros(variables - 1), 1.], np.r_[np.ones(variables - 1), width]) return objective, bounds, LinearConstraint(matrix, lower, upper), pairs ## @brief Find a joint portfolio of distinct binary designs under a quality tolerance. # @param objective Finite linear objective coefficients for one binary design. # @param size Number of distinct designs to return, at least two. # @param quality_loss Largest absolute loss from the single-design optimum. # @param maximize Whether higher raw quality is better. # @param constraints LinearConstraint objects applied independently to each design. # @param time_limit Optional positive time limit per solver call, in seconds. # @param node_limit Optional positive HiGHS node limit per solver call. # @return A verified portfolio with termination state and Hamming bound.
[docs] def solve_binary_portfolio(objective, size, *, quality_loss=0., maximize=True, constraints=(), time_limit=None, node_limit=None): """First certify the quality reference, then optimize the portfolio jointly. Both solves request zero relative MIP gap. Constraint verification uses absolute tolerance 1e-7. Solver certificates retain the solver's numerical tolerances. Solver calls and their limits apply separately to the reference optimum and the joint problem. """ objective = np.array(objective, dtype=float, copy=True) if objective.ndim != 1 or not len(objective) or not np.isfinite(abs(objective).sum()): raise ValueError("Supply a nonempty, finite and bounded objective vector.") size = _positive_int(size, "size") if size < 2 or type(maximize) is not bool or not 0. <= quality_loss < np.inf: raise ValueError("Use size >= 2, a Boolean maximize, and finite nonnegative quality_loss.") options = {"mip_rel_gap": 0.} if time_limit is not None: if not 0. < time_limit < np.inf: raise ValueError("time_limit must be positive and finite.") options["time_limit"] = time_limit if node_limit is not None: options["node_limit"] = _positive_int(node_limit, "node_limit") width = len(objective) constraints = _constraints(constraints, width) if (size - 1).bit_length() > width: return MILPPortfolioResult("infeasible", message="There are fewer binary designs than requested.") sign = 1. if maximize else -1. base = milp(-sign * objective, integrality=np.ones(width), bounds=Bounds(0., 1.), constraints=constraints, options=options) if base.status == 2: return MILPPortfolioResult("infeasible", solver_calls=1, message=str(base.message)) point = _binary_rows(base.x, 1, width, constraints) if base.status == 0 else None if point is None: return MILPPortfolioResult("unresolved", solver_calls=1, message=f"No certified quality reference. {base.message}") optimum = float(point[0] @ objective) cutoff = optimum - sign * quality_loss if not np.isfinite(cutoff): raise ValueError("The quality cutoff must be finite.") quality = LinearConstraint(csr_matrix([sign * objective]), sign * cutoff, np.inf) model, bounds, joint, pairs = _joint_model(size, width, (*constraints, quality)) result = milp(model, integrality=np.ones(len(model)), bounds=bounds, constraints=joint, options=options) bound = getattr(result, "mip_dual_bound", None) common = dict(optimum=optimum, quality_cutoff=cutoff, solver_calls=2, message=str(result.message), distance_upper_bound=-float(bound) if bound is not None and np.isfinite(bound) else None) if result.status == 2: return MILPPortfolioResult("infeasible", **common) points = _binary_rows(result.x, size, width, (*constraints, quality)) if result.status in (0, 1) else None if points is not None: distance = min(int(np.count_nonzero(points[i] != points[j])) for i, j in pairs) if distance > 0: optimal = result.status == 0 and abs(distance - result.x[-1]) <= 1e-6 designs = tuple(sorted(tuple(map(int, point)) for point in points)) qualities = tuple(float(np.dot(point, objective)) for point in designs) return MILPPortfolioResult("optimal" if optimal else "unresolved", designs, qualities, minimum_distance=distance, **common) return MILPPortfolioResult("unresolved", **common)