Skip to content

algorithm ¤

The ORACLE algorithm (Turan, Moret & Bardow, 2026).

ORACLE sandwiches the unknown near-optimal space Z between two polytopes:

  • the inner approximation I: the convex hull of near-optimal designs found so far. I is inside Z because Z is convex, so every point of I is a guaranteed near-optimal design;
  • the outer approximation O: the intersection of halfspaces ("cuts") that are known to contain Z.

and repeats until the two meet:

  1. Initialise I with the cost optimum and O with the bounds of the design variables and a cost cut.
  2. Measure: find the point of O furthest from I. Its distance (the ORACLE metric) bounds the error of both approximations; stop when it is below the tolerance.
  3. Explore: find the near-optimal design closest to that point (one solve of the full model).
  4. Refine: add that design to I and, if the point was not near-optimal, cut it off O with a hyperplane that separates it from Z (built from the dual variables of step 3).

Classes:

  • Oracle –

    Explore the whole near-optimal space of a model with ORACLE.

  • OracleResult –

    Snapshot of ORACLE's approximations of the near-optimal space.

Oracle ¤

Oracle(
    problem: NearOptimalProblem,
    eps: float = 0.05,
    tol: Optional[float] = None,
    scale: Union[None, str, Sequence[float]] = None,
    metric: str = "auto",
    cost_cut: bool = True,
    verbose: bool = True,
    mip_rel_gap: float = 0.01,
    mip_time_limit: Optional[float] = None,
)

Explore the whole near-optimal space of a model with ORACLE.

Example
from energyscope.oracle import Oracle, PyomoProblem

problem = PyomoProblem.from_energyscope(technologies=['PV', 'WIND', 'NUCLEAR', 'CCGT'])
oracle = Oracle(problem, eps=0.03)
result = oracle.run(max_iter=50)
result.ranges()

Use run for the full algorithm, or initialise followed by step (or by furthest_point, nearest_point and refine) to follow it step by step.

Parameters:

  • problem ¤

    (NearOptimalProblem) –

    The model to explore, e.g. a PyomoProblem.

  • eps ¤

    (float, default: 0.05 ) –

    Allowed relative cost increase over the optimum: designs costing at most (1 + eps) times the optimal cost are near-optimal (more precisely optimal cost + eps * |optimal cost|, also valid for negative costs).

  • tol ¤

    (Optional[float], default: None ) –

    Stop when the ORACLE metric (the largest distance between the two approximations) is below tol. Default: 1 % of the largest (scaled) bound range.

  • scale ¤

    (Union[None, str, Sequence[float]], default: None ) –

    How distances are measured. None (default, as in the paper) uses the units of the design variables. When units or magnitudes differ (e.g. GW and GWh), use 'extent', which divides each dimension by its extent in the near-optimal space (two extra solves per dimension, which also tighten the initial bounds), or 'range', which divides it by its bound range. Or give one positive number per dimension.

  • metric ¤

    (str, default: 'auto' ) –

    How the ORACLE metric is computed: 'vertex' (exact, up to about 6 dimensions), 'milp' (the bilevel problem of the paper, solved as a MILP) or 'auto' (default), see furthest_point.

  • cost_cut ¤

    (bool, default: True ) –

    Also add the cost cut of the paper (one extra solve per iteration, usually fewer iterations).

  • verbose ¤

    (bool, default: True ) –

    Print one line per iteration.

  • mip_rel_gap ¤

    (float, default: 0.01 ) –

    Relative optimality gap of the metric MILP (the paper uses 10 %). Convergence is always judged on the MILP's proven upper bound, so a gap only makes some trial points less than the furthest.

  • mip_time_limit ¤

    (Optional[float], default: None ) –

    Time limit in seconds for each metric MILP.

Methods:

  • design –

    Cheapest full system with the design point, e.g. an EnergyScope

  • furthest_point –

    Step 2: the ORACLE metric - the point of the outer approximation furthest from the inner one.

  • initialise –

    Step 1: solve the cost optimum and build the first inner and outer approximations.

  • nearest_point –

    Step 3: the near-optimal design closest to target (one solve of the full model).

  • refine –

    Step 4: add the design found to the inner approximation and cut target off the outer one.

  • run –

    Run ORACLE until the metric is below the tolerance or max_iter iterations are done.

  • step –

    One ORACLE iteration (steps 2 to 4). Returns the iteration record (also appended to the history).

Attributes:

Source code in src/energyscope/oracle/algorithm.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def __init__(self, problem: NearOptimalProblem, eps: float = 0.05, tol: Optional[float] = None,
             scale: Union[None, str, Sequence[float]] = None, metric: str = 'auto', cost_cut: bool = True,
             verbose: bool = True, mip_rel_gap: float = 0.01, mip_time_limit: Optional[float] = None):
    if eps < 0:
        raise ValueError('eps must be non-negative.')
    if metric not in ('auto', 'vertex', 'milp'):
        raise ValueError(f"Unknown metric '{metric}', use 'auto', 'vertex' or 'milp'.")
    if isinstance(scale, str):
        if scale not in ('range', 'extent'):
            raise ValueError(f"Unknown scale '{scale}', use None, 'range', 'extent' or one number per dimension.")
    elif scale is not None:
        scale = np.asarray(scale, dtype=float)
        if scale.shape != (len(problem.dimensions),) or np.any(scale <= 0):
            raise ValueError('scale must be None, "range", "extent" or one positive number per dimension.')
    self.problem = problem
    self.eps = eps
    self.metric = metric
    self.cost_cut = cost_cut
    self.verbose = verbose
    self.mip_rel_gap = mip_rel_gap
    self.mip_time_limit = mip_time_limit
    self.dimensions = list(problem.dimensions)
    self._tol = tol
    self._scale_option = scale
    self.scale: Optional[np.ndarray] = None
    self.tol: Optional[float] = None
    self.optimal_cost: Optional[float] = None
    self.budget: Optional[float] = None
    self.optimum: Optional[np.ndarray] = None
    self.lower: Optional[np.ndarray] = None
    self.upper: Optional[np.ndarray] = None
    self._points: list[np.ndarray] = []
    self._point_costs: list[float] = []
    self._halfspaces: list[_Halfspace] = []
    self._history: list[dict] = []
    self._bound: Optional[float] = None
    self._converged = False

A property ¤

A: ndarray

Normals of the outer approximation {z : A z <= b}.

b property ¤

b: ndarray

Right-hand sides of the outer approximation {z : A z <= b}.

budget instance-attribute ¤

budget: Optional[float] = None

cost_cut instance-attribute ¤

cost_cut = cost_cut

dimensions instance-attribute ¤

dimensions = list(problem.dimensions)

eps instance-attribute ¤

eps = eps

inner_points property ¤

inner_points: ndarray

Near-optimal designs found so far, one per row (they span the inner approximation).

lower instance-attribute ¤

lower: Optional[ndarray] = None

metric instance-attribute ¤

metric = metric

mip_rel_gap instance-attribute ¤

mip_rel_gap = mip_rel_gap

mip_time_limit instance-attribute ¤

mip_time_limit = mip_time_limit

n_dims property ¤

n_dims: int

optimal_cost instance-attribute ¤

optimal_cost: Optional[float] = None

optimum instance-attribute ¤

optimum: Optional[ndarray] = None

problem instance-attribute ¤

problem = problem

result property ¤

result: OracleResult

The current approximations, as an OracleResult.

scale instance-attribute ¤

scale: Optional[ndarray] = None

tol instance-attribute ¤

tol: Optional[float] = None

upper instance-attribute ¤

upper: Optional[ndarray] = None

verbose instance-attribute ¤

verbose = verbose

design ¤

design(point: Union[Sequence[float], dict, Series])

Cheapest full system with the design point, e.g. an EnergyScope Result.

Its cost is within the budget if point is in the near-optimal space (always true inside the inner approximation).

Source code in src/energyscope/oracle/algorithm.py
511
512
513
514
515
516
517
518
def design(self, point: Union[Sequence[float], dict, pd.Series]):
    """Cheapest full system with the design ``point``, e.g. an EnergyScope
    [`Result`][energyscope.result.Result].

    Its cost is within the budget if ``point`` is in the near-optimal space (always true inside the inner
    approximation).
    """
    return self.problem.design_at(_as_point(point, self.dimensions))

furthest_point ¤

furthest_point() -> FurthestPoint

Step 2: the ORACLE metric - the point of the outer approximation furthest from the inner one.

Returns:

  • FurthestPoint –

    The point (in the units of the design variables), its scaled distance to the inner approximation, and a

  • FurthestPoint –

    certified upper bound on the metric (equal to the distance, unless the MILP stopped at its gap or time

  • FurthestPoint –

    limit).

Source code in src/energyscope/oracle/algorithm.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def furthest_point(self) -> FurthestPoint:
    """Step 2: the ORACLE metric - the point of the outer approximation furthest from the inner one.

    Returns:
        The point (in the units of the design variables), its scaled distance to the inner approximation, and a
        certified upper bound on the metric (equal to the distance, unless the MILP stopped at its gap or time
        limit).
    """
    self._require_initialised()
    A_scaled = self.A * self.scale
    found = geometry.furthest_point(A_scaled, self.b, self.inner_points / self.scale, method=self.metric,
                                    upper_bound=self._bound, time_limit=self.mip_time_limit,
                                    mip_rel_gap=self.mip_rel_gap, mip_abs_gap=0.1 * self.tol)
    found.point = found.point * self.scale
    # The metric can only decrease (O shrinks, I grows), so the bound is reused to speed up the next MILP.
    self._bound = found.upper_bound if self._bound is None else min(self._bound, found.upper_bound)
    return found

initialise ¤

initialise() -> Oracle

Step 1: solve the cost optimum and build the first inner and outer approximations.

  • inner approximation: the cost-optimal design;
  • outer approximation: the bounds of the design variables, plus the cost cut c @ z <= budget when the problem knows an under-estimator c of the cost. Infinite bounds (and all bounds with scale='extent') are replaced by the extent of the near-optimal space in that dimension (one extra solve each); the designs reaching these extents are added to the inner approximation.
Source code in src/energyscope/oracle/algorithm.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
def initialise(self) -> 'Oracle':
    """Step 1: solve the cost optimum and build the first inner and outer approximations.

    * inner approximation: the cost-optimal design;
    * outer approximation: the bounds of the design variables, plus the cost cut ``c @ z <= budget`` when the
      problem knows an under-estimator ``c`` of the cost. Infinite bounds (and all bounds with
      ``scale='extent'``) are replaced by the extent of the near-optimal space in that dimension (one extra solve
      each); the designs reaching these extents are added to the inner approximation.
    """
    n = self.n_dims
    self.optimal_cost, self.optimum = self.problem.solve_optimum()
    self.budget = self.optimal_cost + self.eps * abs(self.optimal_cost)
    self.problem.set_budget(self.budget)
    self._points, self._halfspaces, self._history = [self.optimum], [], []
    self._point_costs = [self.optimal_cost]  # upper bounds on the minimum cost of each inner point
    self._bound, self._converged = None, False

    lower, upper = self.problem.bounds()
    extent = isinstance(self._scale_option, str) and self._scale_option == 'extent'
    for i in range(n):
        unit = np.eye(n)[i]
        if extent or not np.isfinite(upper[i]):
            point = self.problem.extreme(-unit)
            upper[i] = point[i]
            self._add_point(point)
        if extent or not np.isfinite(lower[i]):
            point = self.problem.extreme(unit)
            lower[i] = point[i]
            self._add_point(point)
    fixed = [d for d, lo, up in zip(self.dimensions, lower, upper) if up - lo <= 1e-7 * max(1.0, abs(up))]
    if fixed:
        raise ValueError(f'Dimension(s) {fixed} cannot vary in the near-optimal space; remove them.')
    self.lower, self.upper = lower, upper
    self.optimum = self._clip(self.optimum)
    self._points = [self._clip(p) for p in self._points]
    for i in range(n):
        unit = np.eye(n)[i]
        self._halfspaces.append(_Halfspace(unit, upper[i], 'upper bound'))
        self._halfspaces.append(_Halfspace(-unit, -lower[i], 'lower bound'))
    coefficients = self.problem.cost_coefficients()
    if coefficients is not None and np.any(coefficients > 0):
        coefficients = np.asarray(coefficients, dtype=float)
        if coefficients @ self.optimum > self.optimal_cost + 1e-6 * max(1.0, abs(self.optimal_cost)):
            warnings.warn('The cost coefficients over-estimate the cost of the optimal design, so they are not an '
                          'under-estimator of the cost: the initial cost cut is skipped.', stacklevel=2)
        else:
            self._halfspaces.append(_Halfspace(coefficients, self.budget, 'cost'))

    if self._scale_option is None:
        self.scale = np.ones(n)
        ranges = upper - lower
        if np.max(ranges) > 10 * np.min(ranges):
            warnings.warn(f'The bound ranges of the dimensions differ by more than a factor 10 '
                          f'({dict(zip(self.dimensions, np.round(ranges, 4).tolist()))}), so distances, and the '
                          "tolerance, are dominated by the largest ones. Use scale='extent' (or 'range') unless "
                          'this is intended.', stacklevel=2)
    elif isinstance(self._scale_option, str):
        self.scale = upper - lower  # 'range', or 'extent' (the bounds are then the extents)
    else:
        self.scale = self._scale_option
    self.tol = 0.01 * float(np.max((upper - lower) / self.scale)) if self._tol is None else float(self._tol)
    if self.verbose:
        print(f'ORACLE: {n} dimensions, optimal cost {self.optimal_cost:.6g}, budget {self.budget:.6g} '
              f'(eps = {self.eps:.2%}), tolerance {self.tol:.4g}')
    return self

nearest_point ¤

nearest_point(target: ndarray) -> NearestPoint

Step 3: the near-optimal design closest to target (one solve of the full model).

The dual variables give the normal of a hyperplane that separates target from the near-optimal space; they are checked against the distance found and re-oriented if the solver uses the opposite sign convention.

Source code in src/energyscope/oracle/algorithm.py
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
def nearest_point(self, target: np.ndarray) -> NearestPoint:
    """Step 3: the near-optimal design closest to ``target`` (one solve of the full model).

    The dual variables give the normal of a hyperplane that separates ``target`` from the near-optimal space;
    they are checked against the distance found and re-oriented if the solver uses the opposite sign convention.
    """
    self._require_initialised()
    target = np.asarray(target, dtype=float)
    nearest = self.problem.nearest(target, self.scale)
    gap = target - nearest.point
    if nearest.distance > self._feasibility_tol():
        mu = np.asarray(nearest.normal, dtype=float)
        if mu @ gap < 0:
            mu = -mu
        # Strong duality: mu @ (target - z_f) = distance and sum(scale * |mu|) = 1. Otherwise the duals are not
        # trustworthy, and neither would be the cut: drop it (refine() then only adds the design found).
        if abs(mu @ gap - nearest.distance) > 1e-4 * nearest.distance + 1e-9:
            warnings.warn(f'Inconsistent dual variables (mu @ gap = {mu @ gap:.6g}, distance = '
                          f'{nearest.distance:.6g}): no separating cut is added.', stacklevel=2)
            mu = np.zeros_like(mu)
        nearest.normal = mu
    return nearest

refine ¤

refine(target: ndarray, nearest: NearestPoint) -> dict

Step 4: add the design found to the inner approximation and cut target off the outer one.

Two cuts can be added, both valid for the whole near-optimal space:

  • the separating cut mu @ z <= mu @ z_f (always, when target is not near-optimal), where mu are the dual variables of step 3: since the distance to the near-optimal space is a convex function of the target and mu its slope, no near-optimal design can be on the far side of this hyperplane;
  • the cost cut cost(z_f) + lam @ (z - z_f) <= budget (if cost_cut), where lam is the slope of the minimum cost as a function of the design: it linearises the cost from below, so it is also valid.

Returns:

  • dict –

    Which cuts were added and whether target was cut off.

Source code in src/energyscope/oracle/algorithm.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def refine(self, target: np.ndarray, nearest: NearestPoint) -> dict:
    """Step 4: add the design found to the inner approximation and cut ``target`` off the outer one.

    Two cuts can be added, both valid for the whole near-optimal space:

    * the **separating cut** ``mu @ z <= mu @ z_f`` (always, when ``target`` is not near-optimal), where ``mu`` are
      the dual variables of step 3: since the distance to the near-optimal space is a convex function of the
      target and ``mu`` its slope, no near-optimal design can be on the far side of this hyperplane;
    * the **cost cut** ``cost(z_f) + lam @ (z - z_f) <= budget`` (if ``cost_cut``), where ``lam`` is the slope of
      the minimum cost as a function of the design: it linearises the cost from below, so it is also valid.

    Returns:
        Which cuts were added and whether ``target`` was cut off.
    """
    self._require_initialised()
    target = np.asarray(target, dtype=float)
    info = {'new_point': self._add_point(nearest.point, nearest.cost), 'cut': False, 'cost_cut': False,
            'separated': False}
    if nearest.distance <= self._feasibility_tol():
        return info  # The target is near-optimal: nothing to cut.
    mu = nearest.normal
    cut = self._add_halfspace(mu, max(mu @ target - nearest.distance, mu @ nearest.point), 'cut')
    cost_cut = self._add_cost_cut(nearest.point) if self.cost_cut else None
    info['cut'], info['cost_cut'] = cut is not None, cost_cut is not None
    info['separated'] = any(h is not None and h.normal @ target > h.rhs for h in (cut, cost_cut))
    return info

run ¤

run(max_iter: int = 100) -> OracleResult

Run ORACLE until the metric is below the tolerance or max_iter iterations are done.

Can be called again to continue a previous run.

Source code in src/energyscope/oracle/algorithm.py
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
def run(self, max_iter: int = 100) -> OracleResult:
    """Run ORACLE until the metric is below the tolerance or ``max_iter`` iterations are done.

    Can be called again to continue a previous run.
    """
    if self.optimum is None:
        self.initialise()
    for _ in range(max_iter):
        record = self.step()
        if record['converged'] or record.get('stalled', False):
            break
    else:
        if self.verbose:
            print(f'  stopped after {max_iter} iterations without reaching the tolerance.')
    return self.result

step ¤

step() -> dict

One ORACLE iteration (steps 2 to 4). Returns the iteration record (also appended to the history).

Source code in src/energyscope/oracle/algorithm.py
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
def step(self) -> dict:
    """One ORACLE iteration (steps 2 to 4). Returns the iteration record (also appended to the history)."""
    self._require_initialised()
    record = {'iteration': len(self._history) + 1}
    start = time.perf_counter()
    found = self.furthest_point()
    record.update({'distance': found.distance, 'distance_bound': found.upper_bound, 'metric': found.method,
                   'time_metric': time.perf_counter() - start})
    record.update({f'trial {d}': v for d, v in zip(self.dimensions, found.point)})
    self._converged = bool(found.upper_bound <= self.tol)  # also re-evaluated if tol was changed
    if self._converged:
        record['converged'] = True
        self._history.append(record)
        if self.verbose:
            print(f"  iteration {record['iteration']:3d}: distance {found.upper_bound:.4g} <= tolerance "
                  f"{self.tol:.4g}: converged")
        return record
    start = time.perf_counter()
    nearest = self.nearest_point(found.point)
    record['time_nearest'] = time.perf_counter() - start
    record['distance_to_space'] = nearest.distance
    record.update({f'nearest {d}': v for d, v in zip(self.dimensions, nearest.point)})
    start = time.perf_counter()
    info = self.refine(found.point, nearest)
    record['time_refine'] = time.perf_counter() - start
    record.update(info)
    record['n_points'] = len(self._points)
    record['n_halfspaces'] = len(self._halfspaces)
    record['converged'] = False
    self._history.append(record)
    if self.verbose:
        added = ' + '.join(k for k in ('cut', 'cost_cut') if info[k]) or 'no cut (trial point is near-optimal)'
        bound = f' (<= {found.upper_bound:.4g})' if found.upper_bound > found.distance * (1 + 1e-6) + 1e-9 else ''
        away = max(nearest.distance, 0.0) + 0.0  # + 0.0 turns -0.0 into 0.0
        print(f"  iteration {record['iteration']:3d}: distance {found.distance:.4g}{bound} | trial point is "
              f"{away:.4g} away from the near-optimal space | {added}")
    if not info['new_point'] and not info['separated']:
        # Should not happen; it would mean the solver returned inaccurate duals or designs.
        record['stalled'] = True
        warnings.warn('ORACLE made no progress (no new design and the trial point was not cut off), probably '
                      'because of numerical trouble in the solver. Stopping.', stacklevel=2)
    return record

OracleResult dataclass ¤

OracleResult(
    dimensions: list,
    eps: float,
    optimal_cost: float,
    budget: float,
    optimum: Series,
    inner_points: DataFrame,
    outer: DataFrame,
    history: DataFrame,
    scale: Series,
    tol: float,
    distance: float,
    converged: bool,
)

Snapshot of ORACLE's approximations of the near-optimal space.

Attributes:

  • dimensions (list) –

    Names of the explored design variables.

  • eps (float) –

    Allowed relative cost increase over the optimum (e.g. 0.05 for 5 %).

  • optimal_cost (float) –

    Cost of the optimal design.

  • budget (float) –

    Cost budget optimal_cost + eps * |optimal_cost| defining the near-optimal space.

  • optimum (Series) –

    The cost-optimal design.

  • inner_points (DataFrame) –

    Near-optimal designs found (one row each); their convex hull is the inner approximation.

  • outer (DataFrame) –

    Halfspaces sum(row[d] * z[d]) <= rhs of the outer approximation, with their origin in kind.

  • history (DataFrame) –

    One row per iteration: ORACLE metric, trial point, nearest near-optimal design, cuts added, timings.

  • scale (Series) –

    Scale of each dimension used to measure distances (distances are in units of z / scale).

  • tol (float) –

    Convergence tolerance on the ORACLE metric.

  • distance (float) –

    Certified upper bound on the ORACLE metric, i.e. on the largest distance between the two approximations (and so on the error made by using either of them).

  • converged (bool) –

    Whether the metric reached the tolerance.

Methods:

  • contains –

    Whether point lies in the inner (guaranteed near-optimal) or outer (possibly near-optimal) region.

  • distance_to_inner –

    Scaled L-infinity distance from point to the inner approximation (0 if it is inside).

  • flat_dimensions –

    Dimensions that do not vary in the outer approximation (and so in the near-optimal space).

  • plot_convergence –

    Plot the ORACLE metric against the iterations, see

  • plot_projection –

    Plot both approximations projected on two dimensions, see

  • plot_ranges –

    Plot the near-optimal range of each dimension, see plot_ranges.

  • ranges –

    Smallest and largest value of each dimension over both approximations.

  • sample –

    Random designs from the inner (guaranteed near-optimal) or outer approximation.

  • vertices –

    Vertices of the inner or outer approximation (exact, practical up to about 6 dimensions).

budget instance-attribute ¤

budget: float

converged instance-attribute ¤

converged: bool

dimensions instance-attribute ¤

dimensions: list

distance instance-attribute ¤

distance: float

eps instance-attribute ¤

eps: float

history instance-attribute ¤

history: DataFrame

inner_points instance-attribute ¤

inner_points: DataFrame

optimal_cost instance-attribute ¤

optimal_cost: float

optimum instance-attribute ¤

optimum: Series

outer instance-attribute ¤

outer: DataFrame

outer_A property ¤

outer_A: ndarray

Normals of the outer approximation's halfspaces, one row per halfspace.

outer_b property ¤

outer_b: ndarray

Right-hand sides of the outer approximation's halfspaces.

scale instance-attribute ¤

scale: Series

tol instance-attribute ¤

tol: float

contains ¤

contains(
    point: Union[Sequence[float], dict, Series],
    region: str = "inner",
    tol: float = 1e-06,
) -> bool

Whether point lies in the inner (guaranteed near-optimal) or outer (possibly near-optimal) region.

Source code in src/energyscope/oracle/algorithm.py
87
88
89
90
91
92
93
94
95
def contains(self, point: Union[Sequence[float], dict, pd.Series], region: str = 'inner',
             tol: float = 1e-6) -> bool:
    """Whether ``point`` lies in the inner (guaranteed near-optimal) or outer (possibly near-optimal) region."""
    z = self._as_point(point)
    if region == 'inner':
        return self.distance_to_inner(z) <= tol
    if region == 'outer':
        return bool(np.all(self.outer_A @ z <= self.outer_b + tol))
    raise ValueError("region must be 'inner' or 'outer'.")

distance_to_inner ¤

distance_to_inner(
    point: Union[Sequence[float], dict, Series],
) -> float

Scaled L-infinity distance from point to the inner approximation (0 if it is inside).

Source code in src/energyscope/oracle/algorithm.py
 97
 98
 99
100
101
def distance_to_inner(self, point: Union[Sequence[float], dict, pd.Series]) -> float:
    """Scaled L-infinity distance from ``point`` to the inner approximation (0 if it is inside)."""
    z = self._as_point(point)
    scale = self.scale.to_numpy()
    return geometry.distance_to_hull(z / scale, self.inner_points.to_numpy() / scale)[0]

flat_dimensions ¤

flat_dimensions() -> list

Dimensions that do not vary in the outer approximation (and so in the near-optimal space).

Such a dimension is fixed by the model, e.g. by an equality constraint. It makes the approximations flat, so vertices and sample cannot be used on the outer approximation: explore without it.

Source code in src/energyscope/oracle/algorithm.py
103
104
105
106
107
108
109
110
111
112
113
def flat_dimensions(self) -> list:
    """Dimensions that do not vary in the outer approximation (and so in the near-optimal space).

    Such a dimension is fixed by the model, e.g. by an equality constraint. It makes the approximations flat, so
    [`vertices`][energyscope.oracle.algorithm.OracleResult.vertices] and
    [`sample`][energyscope.oracle.algorithm.OracleResult.sample] cannot be used on the outer approximation:
    explore without it.
    """
    lower, upper = geometry.bounding_box(self.outer_A, self.outer_b)
    span = max(1.0, float(np.max(np.abs(np.concatenate([lower, upper])))))
    return [d for d, lo, up in zip(self.dimensions, lower, upper) if up - lo <= 1e-7 * span]

plot_convergence ¤

plot_convergence(**kwargs)

Plot the ORACLE metric against the iterations, see plot_convergence.

Source code in src/energyscope/oracle/algorithm.py
148
149
150
151
152
def plot_convergence(self, **kwargs):
    """Plot the ORACLE metric against the iterations, see
    [`plot_convergence`][energyscope.oracle.plots.plot_convergence]."""
    from energyscope.oracle.plots import plot_convergence
    return plot_convergence(self, **kwargs)

plot_projection ¤

plot_projection(x: str, y: str, **kwargs)

Plot both approximations projected on two dimensions, see plot_projection.

Source code in src/energyscope/oracle/algorithm.py
154
155
156
157
158
def plot_projection(self, x: str, y: str, **kwargs):
    """Plot both approximations projected on two dimensions, see
    [`plot_projection`][energyscope.oracle.plots.plot_projection]."""
    from energyscope.oracle.plots import plot_projection
    return plot_projection(self, x, y, **kwargs)

plot_ranges ¤

plot_ranges(**kwargs)

Plot the near-optimal range of each dimension, see plot_ranges.

Source code in src/energyscope/oracle/algorithm.py
160
161
162
163
def plot_ranges(self, **kwargs):
    """Plot the near-optimal range of each dimension, see [`plot_ranges`][energyscope.oracle.plots.plot_ranges]."""
    from energyscope.oracle.plots import plot_ranges
    return plot_ranges(self, **kwargs)

ranges ¤

ranges() -> DataFrame

Smallest and largest value of each dimension over both approximations.

The true near-optimal range of each dimension lies between the inner and the outer one.

Source code in src/energyscope/oracle/algorithm.py
74
75
76
77
78
79
80
81
82
83
84
85
def ranges(self) -> pd.DataFrame:
    """Smallest and largest value of each dimension over both approximations.

    The true near-optimal range of each dimension lies between the inner and the outer one.
    """
    A, b = self.outer_A, self.outer_b
    lower, upper = geometry.bounding_box(A, b)
    return pd.DataFrame({'optimum': self.optimum.to_numpy(),
                         'inner_min': self.inner_points.min().to_numpy(),
                         'inner_max': self.inner_points.max().to_numpy(),
                         'outer_min': lower, 'outer_max': upper},
                        index=_labels(self.dimensions).rename('dimension')) + 0.0  # no -0.0

sample ¤

sample(
    n: int = 100,
    region: str = "inner",
    seed: Optional[int] = None,
) -> DataFrame

Random designs from the inner (guaranteed near-optimal) or outer approximation.

Samples are approximately uniform (hit-and-run random walk). If the inner approximation is flat (fewer than n_dims + 1 independent points), random convex combinations of its points are returned instead.

Source code in src/energyscope/oracle/algorithm.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def sample(self, n: int = 100, region: str = 'inner', seed: Optional[int] = None) -> pd.DataFrame:
    """Random designs from the inner (guaranteed near-optimal) or outer approximation.

    Samples are approximately uniform (hit-and-run random walk). If the inner approximation is flat (fewer
    than ``n_dims + 1`` independent points), random convex combinations of its points are returned instead.
    """
    rng = np.random.default_rng(seed)
    if region == 'outer':
        self._check_not_flat()
        samples = geometry.hit_and_run(self.outer_A, self.outer_b, n, rng=rng)
    elif region == 'inner':
        points = self.inner_points.to_numpy()
        hull = geometry.halfspaces_of_hull(points)
        if hull is None:
            samples = rng.dirichlet(np.ones(len(points)), size=n) @ points
        else:
            samples = geometry.hit_and_run(*hull, n, start=points.mean(axis=0), rng=rng)
    else:
        raise ValueError("region must be 'inner' or 'outer'.")
    return pd.DataFrame(samples, columns=_labels(self.dimensions))

vertices ¤

vertices(region: str = 'outer') -> DataFrame

Vertices of the inner or outer approximation (exact, practical up to about 6 dimensions).

Source code in src/energyscope/oracle/algorithm.py
115
116
117
118
119
120
121
122
123
124
125
def vertices(self, region: str = 'outer') -> pd.DataFrame:
    """Vertices of the inner or outer approximation (exact, practical up to about 6 dimensions)."""
    if region == 'outer':
        self._check_not_flat()
        vertices = geometry.polytope_vertices(self.outer_A, self.outer_b)
    elif region == 'inner':
        points = self.inner_points.to_numpy()
        vertices = points[geometry.hull_vertex_indices(points)]
    else:
        raise ValueError("region must be 'inner' or 'outer'.")
    return pd.DataFrame(vertices, columns=_labels(self.dimensions))