# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Diversity-guided branching over binary projections of mixed-integer programs.
# @see https://doi.org/10.1287/ijoc.2022.0164
"""Find diverse near-optimal designs with a bounded hierarchy of SciPy MILP solves."""
from dataclasses import dataclass
from operator import index
import numpy as np
from scipy.optimize import Bounds, LinearConstraint, milp
from scipy.sparse import csr_matrix
from ._population import _attempt_budget
from .milp_portfolio import _constraints
from .modern import _positive_int
__all__ = ["DiversiTreeResult", "solve_diversitree"]
## @brief Measured representatives, solver termination, and the certified quality reference.
[docs]
@dataclass(frozen=True)
class DiversiTreeResult:
"""Keep one mixed-integer point per distinct selected binary projection."""
status: str
designs: tuple[tuple[int | float, ...], ...]
qualities: tuple[float, ...]
binary_indices: tuple[int, ...]
solver_calls: int
optimum: float | None
quality_cutoff: float | None
message: str = ""
@property
def mean_binary_distance(self):
"""Return the mean pairwise Hamming distance divided by the binary dimension."""
size = len(self.designs)
if size < 2:
return 0.
ones = np.asarray(self.designs)[:, self.binary_indices].sum(axis=0)
return float(np.sum(ones * (size - ones)) / (size * (size - 1) / 2 * len(self.binary_indices)))
@dataclass(frozen=True)
class _Node:
prefix: tuple[int, ...]
bound: float
def _select_node(queue, signatures, width, alpha, beta, seed_solutions):
if len(signatures) < seed_solutions or (not alpha and not beta):
return min(range(len(queue)), key=lambda i: queue[i].bound)
bounds = np.asarray([node.bound for node in queue])
scaled = bounds / max(1., float(np.abs(bounds).max()))
relative = (scaled - scaled.min()) / (float(np.ptp(scaled)) or 1.)
frequency = np.asarray(signatures, dtype=float).mean(axis=0)
def priority(i):
node = queue[i]
depth = len(node.prefix)
agreement = float(np.mean(np.where(node.prefix, frequency[:depth], 1. - frequency[:depth]))) if depth else .5
return (1. - alpha - beta) * relative[i] + alpha * agreement + beta * depth / width
return min(range(len(queue)), key=priority)
def _verify(candidate, low, high, integer, rows):
point = np.asarray(candidate, dtype=float).copy()
if point.shape != low.shape or not np.isfinite(point).all():
return None
rounded = np.rint(point[integer])
if np.any(np.abs(point[integer] - rounded) > 1e-6):
return None
point[integer] = rounded
if np.any(point < low - 1e-7) or np.any(point > high + 1e-7):
return None
point = np.clip(point, low, high)
for row in rows:
values = row.A @ point
if not (np.isfinite(values) & (values >= row.lb - 1e-7) & (values <= row.ub + 1e-7)).all():
return None
return point
## @brief Search the binary projection tree of a bounded mixed-integer problem.
# @param objective Finite linear objective coefficients.
# @param bounds Finite scipy.optimize.Bounds for all coordinates.
# @param size Maximum number of distinct projections to collect.
# @param budget Total MILP calls, including the reference solve.
# @param integrality Zero/one mask for continuous/integer coordinates, default all integer.
# @param constraints One LinearConstraint or a sequence of them.
# @param binary_indices Optional free binary coordinates to diversify, default all free binary coordinates.
# @param quality_loss Maximum additive objective deterioration from the certified reference.
# @param maximize Whether larger raw objective values are better.
# @param alpha Weight on partial binary agreement with the collected set.
# @param beta Weight on the depth of the partial assignment.
# @param seed_solutions Number of solutions before activating the diversity and depth weights.
# @param time_limit Optional positive time limit per MILP call.
# @return Verified solutions and explicit solver termination status.
[docs]
def solve_diversitree(objective, bounds, size, *, budget, integrality=None, constraints=(), binary_indices=None,
quality_loss=0., maximize=True, alpha=.7, beta=.1, seed_solutions=2, time_limit=None):
"""Use DiversiTree's bound, partial diversity, and depth priorities.
The outer tree branches over binary projections. Each node uses SciPy
MILP as an exact subproblem oracle. A verified node optimum contributes
one representative. Partition the remaining node by the first bit
where its projection differs from that representative. Open nodes
inherit their parent's valid objective bound. The method returns a
bounded collection, with a certificate for the reference fitness.
"""
objective = np.asarray(objective, dtype=float)
if objective.ndim != 1 or not len(objective) or not np.isfinite(objective).all():
raise ValueError("Supply one finite objective coefficient per coordinate.")
if not isinstance(bounds, Bounds):
raise TypeError("bounds must be scipy.optimize.Bounds.")
size, budget = _positive_int(size, "size"), _positive_int(budget, "budget")
seed_solutions = _attempt_budget(seed_solutions)
if type(maximize) is not bool or not 0. <= quality_loss < np.inf or not (alpha >= 0 and beta >= 0 and alpha + beta <= 1.):
raise ValueError("Use nonnegative finite quality_loss and nonnegative alpha and beta summing to at most one.")
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
low = np.broadcast_to(np.asarray(bounds.lb, dtype=float), objective.shape).copy()
high = np.broadcast_to(np.asarray(bounds.ub, dtype=float), objective.shape).copy()
mask = np.ones(len(objective)) if integrality is None else np.broadcast_to(np.asarray(integrality), objective.shape)
if not np.isin(mask, (0, 1)).all() or not np.isfinite(low).all() or not np.isfinite(high).all():
raise ValueError("Use finite bounds and an integrality mask containing zeros and ones.")
integer = mask.astype(bool)
low[integer], high[integer] = np.ceil(low[integer]), np.floor(high[integer])
if np.any(low > high) or np.any(np.maximum(np.abs(low[integer]), np.abs(high[integer])) > 2**53):
raise ValueError("Supply nonempty bounds and exactly representable integer endpoints.")
free_binary = set(map(int, np.flatnonzero(integer & (low == 0.) & (high == 1.))))
axes = tuple(sorted(free_binary)) if binary_indices is None else tuple(map(index, binary_indices))
if not axes or len(axes) != len(set(axes)) or not set(axes) <= free_binary:
raise ValueError("Select distinct free binary coordinates for diversity.")
rows = _constraints(constraints, len(objective))
costs = -objective if maximize else objective
base = milp(costs, bounds=Bounds(low, high), integrality=mask, constraints=rows, options=options)
root = _verify(base.x, low, high, integer, rows) if base.status == 0 else None
best_cost = None if root is None else float(costs @ root)
if best_cost is None or not np.isfinite(best_cost):
status = "infeasible" if base.status == 2 else "unresolved"
return DiversiTreeResult(status, (), (), axes, 1, None, None, str(base.message))
cutoff = best_cost + quality_loss
if not np.isfinite(cutoff):
raise ValueError("The resulting quality cutoff must be finite.")
bounded_rows = (*rows, LinearConstraint(csr_matrix([costs]), -np.inf, cutoff))
queue, designs, values, signatures = [], [], [], []
def collect(prefix, point, bound):
signature = tuple(int(point[i]) for i in axes)
signatures.append(signature)
designs.append(tuple(int(x) if discrete else float(x) for x, discrete in zip(point, integer)))
values.append(float(objective @ point))
queue.extend(_Node(signature[:i] + (1 - signature[i],), bound) for i in range(len(prefix), len(axes)))
collect((), root, best_cost)
calls, message = 1, ""
while queue and len(designs) < size and calls < budget:
node = queue.pop(_select_node(queue, signatures, len(axes), alpha, beta, seed_solutions))
lower, upper = low.copy(), high.copy()
fixed = list(axes[:len(node.prefix)])
lower[fixed] = upper[fixed] = node.prefix
solved = milp(costs, bounds=Bounds(lower, upper), integrality=mask, constraints=bounded_rows, options=options)
calls += 1
if solved.status == 2:
continue
point = _verify(solved.x, lower, upper, integer, bounded_rows) if solved.status == 0 else None
value = None if point is None else float(costs @ point)
if value is None or not np.isfinite(value) or value > cutoff + 1e-7:
message = str(solved.message)
continue
collect(node.prefix, point, value)
status = ("target-reached" if len(designs) == size else "unresolved" if message else
"budget-exhausted" if queue else "search-exhausted")
sign = -1. if maximize else 1.
return DiversiTreeResult(status, tuple(designs), tuple(values), axes, calls, sign * best_cost, sign * cutoff, message)