Skip to content

geometry ¤

Polytope geometry used by ORACLE.

Everything in this module is model-independent: it works on

  • an outer approximation given in halfspace form {z : A z <= b}, and
  • an inner approximation given as the convex hull of a set of points (one point per row of points).

Distances are measured with the (weighted) L-infinity norm max_i |z_i - y_i|, as in the ORACLE paper. Pass coordinates that are already scaled if the dimensions have different units.

Classes:

  • FurthestPoint –

    Solution of the ORACLE metric: the point of the outer approximation that is furthest from the inner one.

Functions:

  • bounding_box –

    Smallest axis-aligned box containing {z : A z <= b} (two LPs per dimension).

  • chebyshev_center –

    Centre and radius of the largest ball inside {z : A z <= b}.

  • distance_to_hull –

    L-infinity distance from z to the convex hull of points (one LP).

  • furthest_point –

    The ORACLE metric: max_{z in O} min_{y in I} ||z - y||_inf.

  • halfspaces_of_hull –

    Halfspace form (A, b) of the convex hull of points, or None if the hull is flat.

  • hit_and_run –

    Approximately uniform samples from {z : A z <= b} with the hit-and-run random walk.

  • hull_vertex_indices –

    Indices of the points that are vertices of their convex hull, also when the hull is flat.

  • polytope_vertices –

    All vertices of the bounded polytope {z : A z <= b}.

  • support_point –

    Point of {z : A z <= b} that goes furthest in direction (maximises direction @ z).

Attributes:

VERTEX_METHOD_FALLBACK_MAX_DIMENSIONS module-attribute ¤

VERTEX_METHOD_FALLBACK_MAX_DIMENSIONS = 8

VERTEX_METHOD_MAX_DIMENSIONS module-attribute ¤

VERTEX_METHOD_MAX_DIMENSIONS = 6

FurthestPoint dataclass ¤

FurthestPoint(
    point: ndarray,
    distance: float,
    upper_bound: float,
    method: str,
)

Solution of the ORACLE metric: the point of the outer approximation that is furthest from the inner one.

Attributes:

  • point (ndarray) –

    The furthest point of the outer approximation (the next "trial point" to explore).

  • distance (float) –

    Its L-infinity distance to the inner approximation (the ORACLE metric).

  • upper_bound (float) –

    A certified upper bound on the metric. Equals distance for the exact vertex method; for the MILP it is the solver's dual bound, which is larger when the MILP stops at its optimality gap or time limit (distance is then only a lower bound on the metric).

  • method (str) –

    'vertex' or 'milp'.

distance instance-attribute ¤

distance: float

method instance-attribute ¤

method: str

point instance-attribute ¤

point: ndarray

upper_bound instance-attribute ¤

upper_bound: float

bounding_box ¤

bounding_box(
    A: ndarray, b: ndarray
) -> tuple[ndarray, ndarray]

Smallest axis-aligned box containing {z : A z <= b} (two LPs per dimension).

Source code in src/energyscope/oracle/geometry.py
73
74
75
76
77
78
79
80
81
82
def bounding_box(A: np.ndarray, b: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """Smallest axis-aligned box containing ``{z : A z <= b}`` (two LPs per dimension)."""
    n = A.shape[1]
    lower, upper = np.empty(n), np.empty(n)
    for i in range(n):
        c = np.zeros(n)
        c[i] = 1.0
        lower[i] = _linprog(c, A_ub=A, b_ub=b, bounds=[(None, None)] * n).fun
        upper[i] = -_linprog(-c, A_ub=A, b_ub=b, bounds=[(None, None)] * n).fun
    return lower, upper

chebyshev_center ¤

chebyshev_center(
    A: ndarray, b: ndarray
) -> tuple[ndarray, float]

Centre and radius of the largest ball inside {z : A z <= b}.

Parameters:

  • A ¤

    (ndarray) –

    Halfspace normals, shape (n_halfspaces, n_dims).

  • b ¤

    (ndarray) –

    Right-hand sides, shape (n_halfspaces,).

Returns:

  • tuple[ndarray, float] –

    The centre and the radius of the ball. A radius of (almost) zero means the polytope has no interior.

Source code in src/energyscope/oracle/geometry.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def chebyshev_center(A: np.ndarray, b: np.ndarray) -> tuple[np.ndarray, float]:
    """Centre and radius of the largest ball inside ``{z : A z <= b}``.

    Args:
        A: Halfspace normals, shape ``(n_halfspaces, n_dims)``.
        b: Right-hand sides, shape ``(n_halfspaces,)``.

    Returns:
        The centre and the radius of the ball. A radius of (almost) zero means the polytope has no interior.
    """
    A = np.asarray(A, dtype=float)
    norms = np.linalg.norm(A, axis=1)
    n = A.shape[1]
    # max r  s.t.  A z + r ||a_i|| <= b
    c = np.zeros(n + 1)
    c[-1] = -1.0
    res = _linprog(c, A_ub=np.hstack([A, norms[:, None]]), b_ub=b, bounds=[(None, None)] * n + [(0, None)])
    return res.x[:n], float(res.x[-1])

distance_to_hull ¤

distance_to_hull(
    z: ndarray, points: ndarray
) -> tuple[float, ndarray]

L-infinity distance from z to the convex hull of points (one LP).

Parameters:

  • z ¤

    (ndarray) –

    The point, shape (n_dims,).

  • points ¤

    (ndarray) –

    The points spanning the hull, shape (n_points, n_dims).

Returns:

  • tuple[float, ndarray] –

    The distance and the weights of the closest convex combination of points.

Source code in src/energyscope/oracle/geometry.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def distance_to_hull(z: np.ndarray, points: np.ndarray) -> tuple[float, np.ndarray]:
    """L-infinity distance from ``z`` to the convex hull of ``points`` (one LP).

    Args:
        z: The point, shape ``(n_dims,)``.
        points: The points spanning the hull, shape ``(n_points, n_dims)``.

    Returns:
        The distance and the weights of the closest convex combination of ``points``.
    """
    points = np.atleast_2d(np.asarray(points, dtype=float))
    m, n = points.shape
    # variables: weights s (m), t ;  min t  s.t.  -t <= z - points^T s <= t,  sum s = 1,  s >= 0
    c = np.zeros(m + 1)
    c[-1] = 1.0
    ones = np.ones((n, 1))
    A_ub = np.vstack([np.hstack([points.T, -ones]), np.hstack([-points.T, -ones])])
    b_ub = np.concatenate([z, -z])
    A_eq = np.hstack([np.ones((1, m)), np.zeros((1, 1))])
    res = _linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=[1.0], bounds=[(0, None)] * (m + 1))
    return max(float(res.x[-1]), 0.0), res.x[:m]

furthest_point ¤

furthest_point(
    A: ndarray,
    b: ndarray,
    points: ndarray,
    method: str = "auto",
    upper_bound: Optional[float] = None,
    time_limit: Optional[float] = None,
    mip_rel_gap: float = 1e-06,
    mip_abs_gap: float = 0.0,
) -> FurthestPoint

The ORACLE metric: max_{z in O} min_{y in I} ||z - y||_inf.

O = {z : A z <= b} is the outer approximation and I = conv(points) the inner approximation. The value is the largest error made by using either approximation in place of the (unknown) near-optimal space, and the point reaching it is where the approximations disagree the most - which is where ORACLE explores next.

Parameters:

  • A ¤

    (ndarray) –

    Halfspace normals of the outer approximation, shape (n_halfspaces, n_dims). Must describe a bounded set.

  • b ¤

    (ndarray) –

    Right-hand sides, shape (n_halfspaces,).

  • points ¤

    (ndarray) –

    Points spanning the inner approximation, shape (n_points, n_dims).

  • method ¤

    (str, default: 'auto' ) –

    'vertex' enumerates the vertices of O and evaluates the distance at each of them. This is exact because the distance to a convex set is a convex function, so its maximum over a polytope is reached at a vertex. 'milp' solves the bilevel problem of the paper as a single-level MILP (KKT conditions with big-M constraints), which scales better with the number of dimensions. 'auto' (default) picks 'vertex' up to VERTEX_METHOD_MAX_DIMENSIONS (6) dimensions.

  • upper_bound ¤

    (Optional[float], default: None ) –

    Known upper bound on the metric (e.g. its previous value), used to speed up the MILP.

  • time_limit ¤

    (Optional[float], default: None ) –

    Time limit in seconds for the MILP. When it is reached, the best point found is returned with the solver's upper bound on the metric.

  • mip_rel_gap ¤

    (float, default: 1e-06 ) –

    Relative optimality gap for the MILP.

  • mip_abs_gap ¤

    (float, default: 0.0 ) –

    Absolute optimality gap for the MILP.

Returns:

Source code in src/energyscope/oracle/geometry.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def furthest_point(A: np.ndarray, b: np.ndarray, points: np.ndarray, method: str = 'auto',
                   upper_bound: Optional[float] = None, time_limit: Optional[float] = None,
                   mip_rel_gap: float = 1e-6, mip_abs_gap: float = 0.0) -> FurthestPoint:
    """The ORACLE metric: ``max_{z in O} min_{y in I} ||z - y||_inf``.

    ``O = {z : A z <= b}`` is the outer approximation and ``I = conv(points)`` the inner approximation. The value is
    the largest error made by using either approximation in place of the (unknown) near-optimal space, and the point
    reaching it is where the approximations disagree the most - which is where ORACLE explores next.

    Args:
        A: Halfspace normals of the outer approximation, shape ``(n_halfspaces, n_dims)``. Must describe a bounded set.
        b: Right-hand sides, shape ``(n_halfspaces,)``.
        points: Points spanning the inner approximation, shape ``(n_points, n_dims)``.
        method: ``'vertex'`` enumerates the vertices of ``O`` and evaluates the distance at each of them. This is exact
            because the distance to a convex set is a convex function, so its maximum over a polytope is reached at a
            vertex. ``'milp'`` solves the bilevel problem of the paper as a single-level MILP (KKT conditions with
            big-M constraints), which scales better with the number of dimensions. ``'auto'`` (default) picks
            ``'vertex'`` up to ``VERTEX_METHOD_MAX_DIMENSIONS`` (6) dimensions.
        upper_bound: Known upper bound on the metric (e.g. its previous value), used to speed up the MILP.
        time_limit: Time limit in seconds for the MILP. When it is reached, the best point found is returned with
            the solver's upper bound on the metric.
        mip_rel_gap: Relative optimality gap for the MILP.
        mip_abs_gap: Absolute optimality gap for the MILP.

    Returns:
        The furthest point and its distance.
    """
    A = np.asarray(A, dtype=float)
    b = np.asarray(b, dtype=float)
    points = np.atleast_2d(np.asarray(points, dtype=float))
    n = A.shape[1]
    if method == 'auto':
        method = 'vertex' if n <= VERTEX_METHOD_MAX_DIMENSIONS else 'milp'
    if method == 'vertex':
        try:
            return _furthest_point_vertex(A, b, points)
        except (ValueError, QhullError):
            # O is flat (no interior): Qhull cannot enumerate it, the MILP still works.
            method = 'milp'
    if method == 'milp':
        try:
            return _furthest_point_milp(A, b, points, upper_bound=upper_bound, time_limit=time_limit,
                                        mip_rel_gap=mip_rel_gap, mip_abs_gap=mip_abs_gap)
        except RuntimeError:
            if n > VERTEX_METHOD_FALLBACK_MAX_DIMENSIONS:
                raise
            return _furthest_point_vertex(A, b, points)  # numerical trouble in the MILP: use the exact method
    raise ValueError(f"Unknown method '{method}', use 'auto', 'vertex' or 'milp'.")

halfspaces_of_hull ¤

halfspaces_of_hull(
    points: ndarray,
) -> Optional[tuple[ndarray, ndarray]]

Halfspace form (A, b) of the convex hull of points, or None if the hull is flat.

Source code in src/energyscope/oracle/geometry.py
395
396
397
398
399
400
401
402
403
404
405
406
407
def halfspaces_of_hull(points: np.ndarray) -> Optional[tuple[np.ndarray, np.ndarray]]:
    """Halfspace form ``(A, b)`` of the convex hull of ``points``, or ``None`` if the hull is flat."""
    points = np.atleast_2d(np.asarray(points, dtype=float))
    m, n = points.shape
    if m <= n:
        return None
    if n == 1:
        return np.array([[1.0], [-1.0]]), np.array([points.max(), -points.min()])
    try:
        hull = ConvexHull(points)
    except QhullError:
        return None
    return hull.equations[:, :-1], -hull.equations[:, -1]

hit_and_run ¤

hit_and_run(
    A: ndarray,
    b: ndarray,
    n_samples: int,
    start: Optional[ndarray] = None,
    thinning: Optional[int] = None,
    rng: Optional[Generator] = None,
) -> ndarray

Approximately uniform samples from {z : A z <= b} with the hit-and-run random walk.

Parameters:

  • A ¤

    (ndarray) –

    Halfspace normals.

  • b ¤

    (ndarray) –

    Right-hand sides.

  • n_samples ¤

    (int) –

    Number of samples to return.

  • start ¤

    (Optional[ndarray], default: None ) –

    Interior starting point (default: the Chebyshev centre).

  • thinning ¤

    (Optional[int], default: None ) –

    Number of walk steps between two returned samples (default: 10 * n_dims).

  • rng ¤

    (Optional[Generator], default: None ) –

    Random generator, for reproducibility.

Returns:

  • ndarray –

    Array of shape (n_samples, n_dims).

Source code in src/energyscope/oracle/geometry.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
def hit_and_run(A: np.ndarray, b: np.ndarray, n_samples: int, start: Optional[np.ndarray] = None,
                thinning: Optional[int] = None, rng: Optional[np.random.Generator] = None) -> np.ndarray:
    """Approximately uniform samples from ``{z : A z <= b}`` with the hit-and-run random walk.

    Args:
        A: Halfspace normals.
        b: Right-hand sides.
        n_samples: Number of samples to return.
        start: Interior starting point (default: the Chebyshev centre).
        thinning: Number of walk steps between two returned samples (default: ``10 * n_dims``).
        rng: Random generator, for reproducibility.

    Returns:
        Array of shape ``(n_samples, n_dims)``.
    """
    rng = np.random.default_rng() if rng is None else rng
    A = np.asarray(A, dtype=float)
    b = np.asarray(b, dtype=float)
    n = A.shape[1]
    x = chebyshev_center(A, b)[0] if start is None else np.asarray(start, dtype=float)
    thinning = 10 * n if thinning is None else thinning
    samples = np.empty((n_samples, n))
    for k in range(n_samples * thinning):
        d = rng.normal(size=n)
        d /= np.linalg.norm(d)
        Ad = A @ d
        slack = b - A @ x
        with np.errstate(divide='ignore', invalid='ignore'):
            ratios = slack / Ad
        t_max = np.min(ratios[Ad > 1e-12], initial=np.inf)
        t_min = np.max(ratios[Ad < -1e-12], initial=-np.inf)
        if np.isfinite(t_min) and np.isfinite(t_max) and t_max > t_min:
            x = x + rng.uniform(t_min, t_max) * d
        if (k + 1) % thinning == 0:
            samples[(k + 1) // thinning - 1] = x
    return samples

hull_vertex_indices ¤

hull_vertex_indices(points: ndarray) -> ndarray

Indices of the points that are vertices of their convex hull, also when the hull is flat.

A flat hull (e.g. collinear points in 2-D) is handled in the affine subspace spanned by the points.

Source code in src/energyscope/oracle/geometry.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
def hull_vertex_indices(points: np.ndarray) -> np.ndarray:
    """Indices of the points that are vertices of their convex hull, also when the hull is flat.

    A flat hull (e.g. collinear points in 2-D) is handled in the affine subspace spanned by the points.
    """
    points = np.atleast_2d(np.asarray(points, dtype=float))
    centered = points - points.mean(axis=0)
    _, singular, axes = np.linalg.svd(centered, full_matrices=False)
    rank = int(np.sum(singular > 1e-9 * max(1.0, float(singular[0]) if len(singular) else 1.0)))
    if rank == 0:
        return np.array([0])
    coordinates = centered @ axes[:rank].T
    if rank == 1:
        return np.unique([int(np.argmin(coordinates[:, 0])), int(np.argmax(coordinates[:, 0]))])
    return np.sort(ConvexHull(coordinates).vertices)

polytope_vertices ¤

polytope_vertices(A: ndarray, b: ndarray) -> ndarray

All vertices of the bounded polytope {z : A z <= b}.

Uses Qhull's halfspace intersection, so it is exact but its cost grows quickly with the number of dimensions.

Raises:

  • ValueError –

    If the polytope has no interior (it is flat or empty), or if Qhull can only enumerate its vertices approximately (nearly degenerate input).

Source code in src/energyscope/oracle/geometry.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def polytope_vertices(A: np.ndarray, b: np.ndarray) -> np.ndarray:
    """All vertices of the bounded polytope ``{z : A z <= b}``.

    Uses Qhull's halfspace intersection, so it is exact but its cost grows quickly with the number of dimensions.

    Raises:
        ValueError: If the polytope has no interior (it is flat or empty), or if Qhull can only enumerate its vertices
            approximately (nearly degenerate input).
    """
    A = np.asarray(A, dtype=float)
    b = np.asarray(b, dtype=float)
    n = A.shape[1]
    if n == 1:
        lower, upper = bounding_box(A, b)
        return np.array([lower, upper])
    lower, upper = bounding_box(A, b)
    span = upper - lower
    size = max(float(np.max(span)), 1e-12)
    if np.min(span) <= 1e-9 * size:
        raise ValueError('The polytope has no interior; its vertices cannot be enumerated with Qhull.')
    # Work in the unit bounding box: Qhull's precision (and the joggle of 'QJ') is relative to the largest
    # coordinate, so very different extents per dimension would otherwise cost accuracy.
    A_box, b_box = A * span, b - A @ lower
    center, radius = chebyshev_center(A_box, b_box)
    if radius <= 1e-9:
        raise ValueError('The polytope has no interior; its vertices cannot be enumerated with Qhull.')
    A_unit, b_unit = _distinct_halfspaces(A_box, b_box)
    halfspaces = np.hstack([A_unit, -b_unit[:, None]])
    try:
        vertices = HalfspaceIntersection(halfspaces, center).intersections
        joggled = False
    except QhullError:
        # Nearly degenerate input (e.g. almost parallel cuts): retry with a joggled input, whose vertices are only
        # off by round-off. ('Q12' would also run, but can return wrong points.)
        vertices = HalfspaceIntersection(halfspaces, center, qhull_options='QJ').intersections
        joggled = True
    feasible = np.all(A_unit @ vertices.T <= b_unit[:, None] + 1e-7, axis=0)
    if joggled and not np.all(feasible):
        # Some joggled vertices are off: the enumeration may be incomplete, and the vertex metric too small.
        raise ValueError('Qhull could only enumerate the vertices approximately.')
    return _unique_rows(lower + vertices[feasible] * span, tol=1e-9 * size)

support_point ¤

support_point(
    A: ndarray, b: ndarray, direction: ndarray
) -> ndarray

Point of {z : A z <= b} that goes furthest in direction (maximises direction @ z).

Source code in src/energyscope/oracle/geometry.py
85
86
87
88
def support_point(A: np.ndarray, b: np.ndarray, direction: np.ndarray) -> np.ndarray:
    """Point of ``{z : A z <= b}`` that goes furthest in ``direction`` (maximises ``direction @ z``)."""
    n = A.shape[1]
    return _linprog(-np.asarray(direction, dtype=float), A_ub=A, b_ub=b, bounds=[(None, None)] * n).x