Skip to content

oracle ¤

Oracle

explore all near-optimal designs of an energy system model.

ORACLE (Optimization for the Rigorous Analysis of the Complete Landscape of alternatives in Energy systems), a method by E. M. Turan, S. Moret and A. Bardow, maps the near-optimal space of a linear model - every design whose cost is at most (1 + eps) times the optimal cost - and measures how well it has been mapped, so you know when to stop.

ORACLE is general: it applies to any energy system model that is a linear (more generally, convex) optimisation problem. This subpackage implements it for the EnergyScope models and for any linear Pyomo or AMPL model; it is adapted from the authors' reference implementation. If you use ORACLE, please cite their paper:

Reference

E. M. Turan, S. Moret, A. Bardow. ORACLE: A rigorous metric and method to explore all near-optimal designs for energy systems. Computers & Chemical Engineering 210 (2026) 109630. doi:10.1016/j.compchemeng.2026.109630 ⧉

Example
from energyscope.oracle import Oracle, PyomoProblem

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

See the tutorial Explore near-optimal designs with ORACLE for a step-by-step introduction.

Modules:

  • algorithm –

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

  • geometry –

    Polytope geometry used by ORACLE.

  • plots –

    Plots of ORACLE results (plotly).

  • problem –

    Models that ORACLE can explore.

Classes:

  • AmplProblem –

    A linear AMPL model, e.g. the EnergyScope core or infrastructure_ch_2050 model.

  • CostAtPoint –

    Answer to "what does it cost, at least, to build exactly point?".

  • FurthestPoint –

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

  • NearOptimalProblem –

    Interface between ORACLE and an optimisation model.

  • NearestPoint –

    Answer to "which near-optimal design is closest to target?".

  • Oracle –

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

  • OracleResult –

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

  • PyomoProblem –

    A linear Pyomo model, solved with HiGHS (no license needed).

Functions:

  • 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.

  • polytope_vertices –

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

AmplProblem ¤

AmplProblem(
    ampl: AMPL,
    dimensions: Sequence[str],
    design: str = "F",
    cost: str = "TotalCost",
    lower: Optional[Sequence[float]] = None,
    upper: Optional[Sequence[float]] = None,
    cost_coefficients: Optional[Sequence[float]] = None,
    parser: Optional[Callable] = None,
    relax_integers: bool = True,
)

Bases: NearOptimalProblem

A linear AMPL model, e.g. the EnergyScope core or infrastructure_ch_2050 model.

ORACLE declares a few extra AMPL entities, all prefixed with oracle_, and re-solves the model in the same AMPL session with the solver selected in it (option solver). After each of its solves it drops its constraints and objectives again and re-selects the session's objective, so the session (e.g. the one of an Energyscope object) still solves the original model afterwards; its variables hold the last ORACLE solution.

Badly scaled models such as infrastructure_ch_2050 (coefficients from 1e-7 to 1e7) can make an LP solver stop at a design that is not optimal and still report it as optimal, because the error is below its default tolerance. ORACLE would then get wrong distances and invalid cuts. To prevent this, ORACLE's solves:

  • put the options in solver_defaults (for Gurobi: deterministic dual simplex with the tightest optimality tolerance) before the session's <solver>_options, which therefore take precedence; the session's options are restored afterwards;
  • minimise distance_weight times the distance in the nearest-design problem, so that its dual values (which give ORACLE's cuts) are not tolerance-sized;
  • re-solve once when the solver fails (solve_result_num 500 to 599), e.g. on "unrecoverable numerical issues".

For infrastructure_ch_2050, use Gurobi: CPLEX and HiGHS (through AMPL) do not solve its ORACLE problems reliably (CPLEX reports numerical issues, HiGHS may not finish). A warning of ORACLE that a cut "would remove known near-optimal designs" means that the solver's answers are inaccurate.

Parameters:

  • ampl ¤

    (AMPL) –

    An amplpy.AMPL object with the model and data already loaded.

  • dimensions ¤

    (Sequence[str]) –

    Indices of design to explore, e.g. technology names.

  • design ¤

    (str, default: 'F' ) –

    Name of the indexed design variable (default 'F', the installed capacities).

  • cost ¤

    (str, default: 'TotalCost' ) –

    Name of the total cost variable (default 'TotalCost').

  • lower ¤

    (Optional[Sequence[float]], default: None ) –

    Lower bounds of the explored variables (default: unbounded). They are imposed in ORACLE's solves, so bounds tighter than the model's restrict the explored space to this box.

  • upper ¤

    (Optional[Sequence[float]], default: None ) –

    Upper bounds of the explored variables (default: unbounded), see lower.

  • cost_coefficients ¤

    (Optional[Sequence[float]], default: None ) –

    Under-estimator of the cost, see cost_coefficients.

  • parser ¤

    (Optional[Callable], default: None ) –

    Function turning the solved AMPL object into a result object, used by design_at.

  • relax_integers ¤

    (bool, default: True ) –

    ORACLE needs a convex model. If the model has integer or binary variables, relax them to continuous ones in ORACLE's solves (default, AMPL option relax_integrality) or raise an error (False).

Methods:

Attributes:

  • ampl –
  • dimensions –
  • distance_weight (float) –

    The nearest-design problem minimises distance_weight * distance; distances and duals are scaled back.

  • n_dims (int) –
  • parser –
  • solver_defaults (dict[str, dict[str, str]]) –

    Solver options used in ORACLE's solves, per solver (matched in the solver option).

Source code in src/energyscope/oracle/problem.py
408
409
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
def __init__(self, ampl: 'AMPL', dimensions: Sequence[str], design: str = 'F', cost: str = 'TotalCost',
             lower: Optional[Sequence[float]] = None, upper: Optional[Sequence[float]] = None,
             cost_coefficients: Optional[Sequence[float]] = None, parser: Optional[Callable] = None,
             relax_integers: bool = True):
    super().__init__(dimensions)
    self.ampl = ampl
    self.parser = parser
    self.solver_defaults = {solver: dict(options) for solver, options in type(self).solver_defaults.items()}
    n_integer = int(ampl.get_value('_snbvars + _snivars'))  # binary and integer variables of the model
    if n_integer:
        if not relax_integers:
            raise ValueError(f'The model has {n_integer} integer/binary variables; ORACLE needs a convex model. '
                             'Use relax_integers=True to relax them.')
        warnings.warn(f'ORACLE needs a convex model: {n_integer} integer/binary variables are relaxed to '
                      "continuous variables in ORACLE's solves.", stacklevel=2)
    self._relax_integers = bool(n_integer)
    self._design_name = design
    self._cost_name = cost
    self._lower = _as_array(lower, self.n_dims, -np.inf)
    self._upper = _as_array(upper, self.n_dims, np.inf)
    self._cost_coefficients = None if cost_coefficients is None \
        else _as_array(cost_coefficients, self.n_dims, 0.0)

    available = set(ampl.get_variable(design).to_pandas().index)
    missing = [d for d in self.dimensions if d not in available]
    if missing:
        raise ValueError(f"Unknown dimension(s) {missing} for '{design}'. Available: {sorted(available)}")
    if 'oracle_DIMS' in [name for name, _ in ampl.get_sets()]:
        raise ValueError('ORACLE entities are already declared in this AMPL session; load the model in a fresh '
                         'one.')
    self._user_objective = self._current_objective()
    ampl.eval(f"""
        set oracle_DIMS;
        param oracle_target{{oracle_DIMS}} default 0;
        param oracle_scale{{oracle_DIMS}} default 1;
        param oracle_direction{{oracle_DIMS}} default 0;
        param oracle_budget default Infinity;
        param oracle_delta_bound default Infinity;
        param oracle_lower{{oracle_DIMS}} default -Infinity;
        param oracle_upper{{oracle_DIMS}} default Infinity;
        var oracle_delta{{oracle_DIMS}} >= -oracle_delta_bound, <= oracle_delta_bound;
        var oracle_t >= 0;
        s.t. oracle_box{{i in oracle_DIMS}}: oracle_lower[i] <= {design}[i] <= oracle_upper[i];
        s.t. oracle_link{{i in oracle_DIMS}}: {design}[i] + oracle_delta[i] = oracle_target[i];
        s.t. oracle_deviation_up{{i in oracle_DIMS}}: oracle_delta[i] <= oracle_scale[i] * oracle_t;
        s.t. oracle_deviation_down{{i in oracle_DIMS}}: -oracle_delta[i] <= oracle_scale[i] * oracle_t;
        s.t. oracle_budget_limit: {cost} <= oracle_budget;
        minimize oracle_cost: {cost};
        minimize oracle_distance: oracle_t;
        minimize oracle_linear: sum{{i in oracle_DIMS}} oracle_direction[i] * {design}[i];
    """)
    ampl.set['oracle_DIMS'] = self.dimensions
    self._set_indexed('oracle_lower', self._lower)
    self._set_indexed('oracle_upper', self._upper)
    self._restore_session()

ampl instance-attribute ¤

ampl = ampl

dimensions instance-attribute ¤

dimensions = list(dimensions)

distance_weight class-attribute instance-attribute ¤

distance_weight: float = 1000.0

The nearest-design problem minimises distance_weight * distance; distances and duals are scaled back.

n_dims property ¤

n_dims: int

parser instance-attribute ¤

parser = parser

solver_defaults class-attribute instance-attribute ¤

solver_defaults: dict[str, dict[str, str]] = {
    solver: dict(options)
    for solver, options in type(
        self
    ).solver_defaults.items()
}

Solver options used in ORACLE's solves, per solver (matched in the solver option).

Default: {'gurobi': {'method': '1', 'opttol': '1e-9'}} (Gurobi's dual simplex with the tightest optimality tolerance). They are put before the session's <solver>_options, so the session's own options take precedence. Each instance has its own copy: set it to {} on an instance to use the session's options only.

bounds ¤

bounds() -> tuple[ndarray, ndarray]
Source code in src/energyscope/oracle/problem.py
609
610
def bounds(self) -> tuple[np.ndarray, np.ndarray]:
    return self._lower.copy(), self._upper.copy()

cost_at ¤

cost_at(point: ndarray) -> CostAtPoint
Source code in src/energyscope/oracle/problem.py
631
632
633
634
635
def cost_at(self, point: np.ndarray) -> CostAtPoint:
    self._set_indexed('oracle_target', point)
    self._set_mode('cost_at')
    return self._solve('fixed-design cost', lambda: CostAtPoint(
        cost=self._cost(), gradient=self._indexed('oracle_link[i].dual')), presolve=False)

cost_coefficients ¤

cost_coefficients() -> Optional[ndarray]
Source code in src/energyscope/oracle/problem.py
612
613
def cost_coefficients(self) -> Optional[np.ndarray]:
    return None if self._cost_coefficients is None else self._cost_coefficients.copy()

design_at ¤

design_at(point: ndarray) -> Any

Cheapest full system with the design point: a Result for EnergyScope models (via parser), otherwise the AMPL object holding the solution.

Source code in src/energyscope/oracle/problem.py
642
643
644
645
646
647
648
def design_at(self, point: np.ndarray) -> Any:
    """Cheapest full system with the design ``point``: a [`Result`][energyscope.result.Result] for EnergyScope
    models (via ``parser``), otherwise the AMPL object holding the solution."""
    self._set_indexed('oracle_target', point)
    self._set_mode('cost_at')
    return self._solve('fixed-design cost', lambda: self.parser(self.ampl) if self.parser is not None
                       else self.ampl, presolve=False)

extreme ¤

extreme(direction: ndarray) -> ndarray
Source code in src/energyscope/oracle/problem.py
637
638
639
640
def extreme(self, direction: np.ndarray) -> np.ndarray:
    self._set_indexed('oracle_direction', direction)
    self._set_mode('extreme')
    return self._solve('extreme design', self._design_values)

from_energyscope classmethod ¤

from_energyscope(
    es: Energyscope,
    technologies: Sequence[str],
    ds: Optional[Dataset] = None,
    design: Optional[str] = None,
) -> AmplProblem

Explore the installed capacities of some technologies of an EnergyScope AMPL model.

Parameters:

  • es ¤

    (Energyscope) –

    An Energyscope object, e.g. Energyscope(model=infrastructure_ch_2050). Its model files are loaded if they are not yet.

  • technologies ¤

    (Sequence[str]) –

    Technologies whose capacity spans the explored space. Prefer technologies with a finite f_max; infinite bounds are replaced by the extent of the near-optimal space (one extra solve each).

  • ds ¤

    (Optional[Dataset], default: None ) –

    Optional Dataset passed to the model when it is loaded.

  • design ¤

    (Optional[str], default: None ) –

    Name of the capacity variable (default: F in the typical-day models such as core, F_Mult in the monthly models).

Returns:

  • AmplProblem –

    The problem, with the technology bounds f_min/f_max and the annualised investment costs tau * c_inv as cost under-estimator. Integer variables of the model are relaxed.

Source code in src/energyscope/oracle/problem.py
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
494
495
496
497
498
499
500
@classmethod
def from_energyscope(cls, es: 'Energyscope', technologies: Sequence[str], ds: Optional['Dataset'] = None,
                     design: Optional[str] = None) -> 'AmplProblem':
    """Explore the installed capacities of some technologies of an EnergyScope AMPL model.

    Args:
        es: An [`Energyscope`][energyscope.energyscope.Energyscope] object, e.g.
            ``Energyscope(model=infrastructure_ch_2050)``. Its model files are loaded if they are not yet.
        technologies: Technologies whose capacity spans the explored space. Prefer technologies with a finite
            ``f_max``; infinite bounds are replaced by the extent of the near-optimal space (one extra solve
            each).
        ds: Optional [`Dataset`][energyscope.datasets.Dataset] passed to the model when it is loaded.
        design: Name of the capacity variable (default: ``F`` in the typical-day models such as ``core``,
            ``F_Mult`` in the monthly models).

    Returns:
        The problem, with the technology bounds ``f_min``/``f_max`` and the annualised investment costs
            ``tau * c_inv`` as cost under-estimator. Integer variables of the model are relaxed.
    """
    from energyscope.result import parse_result

    ampl = es.es_model
    if ampl.getSets().__len__() == 0:
        es._initial_run(ds=ds)
    technologies = list(technologies)
    if design is None:
        design = 'F' if 'F' in [name for name, _ in ampl.get_variables()] else 'F_Mult'
    available = set(ampl.get_variable(design).to_pandas().index)
    unknown = [t for t in technologies if t not in available]
    if unknown:
        raise ValueError(f'Unknown technologies {unknown}. Available: {sorted(available)}')

    def values(parameter):  # evaluated by AMPL, so that default values count
        return np.array([float(ampl.get_value(f"{parameter}['{t}']")) for t in technologies])

    return cls(ampl, technologies, design=design, cost='TotalCost', lower=values('f_min'), upper=values('f_max'),
               cost_coefficients=values('tau') * values('c_inv'), parser=lambda a: parse_result(a, id_run=0))

nearest ¤

nearest(target: ndarray, scale: ndarray) -> NearestPoint
Source code in src/energyscope/oracle/problem.py
622
623
624
625
626
627
628
629
def nearest(self, target: np.ndarray, scale: np.ndarray) -> NearestPoint:
    weight = self.distance_weight
    self._set_indexed('oracle_target', target)
    self._set_indexed('oracle_scale', np.asarray(scale, dtype=float) / weight)  # oracle_t = weight * distance
    self._set_mode('nearest')
    return self._solve('nearest near-optimal design', lambda: NearestPoint(
        point=self._design_values(), distance=float(self.ampl.get_value('oracle_t')) / weight,
        normal=self._indexed('oracle_link[i].dual') / weight, cost=self._cost()), presolve=False)

set_budget ¤

set_budget(budget: Optional[float]) -> None
Source code in src/energyscope/oracle/problem.py
604
605
606
607
def set_budget(self, budget: Optional[float]) -> None:
    super().set_budget(budget)
    if budget is not None:
        self.ampl.param['oracle_budget'] = budget

solve_optimum ¤

solve_optimum() -> tuple[float, ndarray]
Source code in src/energyscope/oracle/problem.py
618
619
620
def solve_optimum(self) -> tuple[float, np.ndarray]:
    self._set_mode('optimum')
    return self._solve('cost optimum', lambda: (self._cost(), self._design_values()))

CostAtPoint dataclass ¤

CostAtPoint(cost: float, gradient: ndarray)

Answer to "what does it cost, at least, to build exactly point?".

Attributes:

  • cost (float) –

    Minimum total cost when the design variables are fixed to point.

  • gradient (ndarray) –

    Sensitivity of that cost to point (dual variables), used to build the cost cut.

cost instance-attribute ¤

cost: float

gradient instance-attribute ¤

gradient: ndarray

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

NearOptimalProblem ¤

NearOptimalProblem(dimensions: Sequence[Any])

Bases: ABC

Interface between ORACLE and an optimisation model.

The model must be linear (more generally, convex): ORACLE's approximations are only valid if the near-optimal space is convex. Implement the abstract methods to plug in another modelling framework.

Parameters:

  • dimensions ¤

    (Sequence[Any]) –

    Names of the design variables that span the explored space (e.g. technology names).

Methods:

  • bounds –

    Lower and upper bounds of the design variables (-inf/inf when unknown).

  • cost_at –

    Minimise the total cost with the design fixed to point (ignoring the budget).

  • cost_coefficients –

    Coefficients c such that c @ z never exceeds the total cost (e.g. annualised investment costs).

  • design_at –

    Full model solution of the cheapest system that has the design point.

  • extreme –

    Near-optimal design minimising direction @ z.

  • nearest –

    Find the near-optimal design closest to target in the norm max_i |z_i - target_i| / scale_i.

  • set_budget –

    Set the cost budget (1 + eps) * optimal cost that defines the near-optimal space.

  • solve_optimum –

    Minimise the total cost (ignoring the budget). Returns the optimal cost and design.

Attributes:

Source code in src/energyscope/oracle/problem.py
76
77
78
79
80
def __init__(self, dimensions: Sequence[Any]):
    self.dimensions = list(dimensions)
    if len(set(self.dimensions)) != len(self.dimensions):
        raise ValueError('The dimensions must be unique.')
    self._budget: Optional[float] = None

dimensions instance-attribute ¤

dimensions = list(dimensions)

n_dims property ¤

n_dims: int

bounds ¤

bounds() -> tuple[ndarray, ndarray]

Lower and upper bounds of the design variables (-inf/inf when unknown).

Source code in src/energyscope/oracle/problem.py
106
107
108
def bounds(self) -> tuple[np.ndarray, np.ndarray]:
    """Lower and upper bounds of the design variables (``-inf``/``inf`` when unknown)."""
    return np.full(self.n_dims, -np.inf), np.full(self.n_dims, np.inf)

cost_at abstractmethod ¤

cost_at(point: ndarray) -> CostAtPoint

Minimise the total cost with the design fixed to point (ignoring the budget).

Source code in src/energyscope/oracle/problem.py
 98
 99
100
@abc.abstractmethod
def cost_at(self, point: np.ndarray) -> CostAtPoint:
    """Minimise the total cost with the design fixed to ``point`` (ignoring the budget)."""

cost_coefficients ¤

cost_coefficients() -> Optional[ndarray]

Coefficients c such that c @ z never exceeds the total cost (e.g. annualised investment costs).

They give ORACLE's initial "cost cut" c @ z <= budget. Return None if no such under-estimator is known.

Source code in src/energyscope/oracle/problem.py
110
111
112
113
114
115
def cost_coefficients(self) -> Optional[np.ndarray]:
    """Coefficients ``c`` such that ``c @ z`` never exceeds the total cost (e.g. annualised investment costs).

    They give ORACLE's initial "cost cut" ``c @ z <= budget``. Return ``None`` if no such under-estimator is known.
    """
    return None

design_at ¤

design_at(point: ndarray) -> Any

Full model solution of the cheapest system that has the design point.

Source code in src/energyscope/oracle/problem.py
117
118
119
def design_at(self, point: np.ndarray) -> Any:
    """Full model solution of the cheapest system that has the design ``point``."""
    raise NotImplementedError

extreme abstractmethod ¤

extreme(direction: ndarray) -> ndarray

Near-optimal design minimising direction @ z.

Source code in src/energyscope/oracle/problem.py
102
103
104
@abc.abstractmethod
def extreme(self, direction: np.ndarray) -> np.ndarray:
    """Near-optimal design minimising ``direction @ z``."""

nearest abstractmethod ¤

nearest(target: ndarray, scale: ndarray) -> NearestPoint

Find the near-optimal design closest to target in the norm max_i |z_i - target_i| / scale_i.

Source code in src/energyscope/oracle/problem.py
94
95
96
@abc.abstractmethod
def nearest(self, target: np.ndarray, scale: np.ndarray) -> NearestPoint:
    """Find the near-optimal design closest to ``target`` in the norm ``max_i |z_i - target_i| / scale_i``."""

set_budget ¤

set_budget(budget: Optional[float]) -> None

Set the cost budget (1 + eps) * optimal cost that defines the near-optimal space.

Source code in src/energyscope/oracle/problem.py
86
87
88
def set_budget(self, budget: Optional[float]) -> None:
    """Set the cost budget ``(1 + eps) * optimal cost`` that defines the near-optimal space."""
    self._budget = budget

solve_optimum abstractmethod ¤

solve_optimum() -> tuple[float, ndarray]

Minimise the total cost (ignoring the budget). Returns the optimal cost and design.

Source code in src/energyscope/oracle/problem.py
90
91
92
@abc.abstractmethod
def solve_optimum(self) -> tuple[float, np.ndarray]:
    """Minimise the total cost (ignoring the budget). Returns the optimal cost and design."""

NearestPoint dataclass ¤

NearestPoint(
    point: ndarray,
    distance: float,
    normal: ndarray,
    cost: float,
)

Answer to "which near-optimal design is closest to target?".

Attributes:

  • point (ndarray) –

    The closest near-optimal design z_f (in the units of the design variables).

  • distance (float) –

    Its (scaled) L-infinity distance to the target. Zero means the target itself is near-optimal.

  • normal (ndarray) –

    Sensitivity of distance to the target (the dual variables of the problem). It is the normal of a hyperplane that separates the target from the whole near-optimal space.

  • cost (float) –

    Total cost of the design found.

cost instance-attribute ¤

cost: float

distance instance-attribute ¤

distance: float

normal instance-attribute ¤

normal: ndarray

point instance-attribute ¤

point: ndarray

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))

PyomoProblem ¤

PyomoProblem(
    model: ConcreteModel,
    design: Union[str, Any],
    cost: Union[str, Any],
    dimensions: Optional[Sequence[Any]] = None,
    lower: Optional[Sequence[float]] = None,
    upper: Optional[Sequence[float]] = None,
    cost_coefficients: Optional[Sequence[float]] = None,
    parser: Optional[Callable] = None,
    relax_integers: bool = True,
    solver_options: Optional[dict] = None,
)

Bases: NearOptimalProblem

A linear Pyomo model, solved with HiGHS (no license needed).

ORACLE adds a block model.oracle to the model with the extra variables, constraints and objectives it needs, deactivates the model's own objectives, and re-solves the model with a persistent HiGHS instance, so each query only takes a fraction of a full solve. The model is therefore dedicated to ORACLE (from_energyscope builds a fresh one).

Parameters:

  • model ¤

    (ConcreteModel) –

    The Pyomo ConcreteModel. Its objectives are deactivated; the cost to minimise is given by cost.

  • design ¤

    (Union[str, Any]) –

    The indexed design variable (or its name), e.g. 'F_Mult'.

  • cost ¤

    (Union[str, Any]) –

    The total cost variable or expression (or its name), e.g. 'TotalCost'.

  • dimensions ¤

    (Optional[Sequence[Any]], default: None ) –

    Indices of design to explore (default: all of them).

  • lower ¤

    (Optional[Sequence[float]], default: None ) –

    Lower bounds of the explored variables (default: the variable bounds). Given bounds are added to the model as constraints, so bounds tighter than the model's restrict the explored space to this box.

  • upper ¤

    (Optional[Sequence[float]], default: None ) –

    Upper bounds of the explored variables (default: the variable bounds), see lower.

  • cost_coefficients ¤

    (Optional[Sequence[float]], default: None ) –

    Under-estimator of the cost, see cost_coefficients.

  • parser ¤

    (Optional[Callable], default: None ) –

    Function turning the solved model into a result object, used by design_at.

  • relax_integers ¤

    (bool, default: True ) –

    ORACLE needs a convex model. If the model has integer or binary variables, relax them to continuous ones (default) or raise an error (False).

  • solver_options ¤

    (Optional[dict], default: None ) –

    Extra HiGHS options.

Methods:

Attributes:

Source code in src/energyscope/oracle/problem.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
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
226
227
228
def __init__(self, model: 'ConcreteModel', design: Union[str, Any], cost: Union[str, Any],
             dimensions: Optional[Sequence[Any]] = None, lower: Optional[Sequence[float]] = None,
             upper: Optional[Sequence[float]] = None,
             cost_coefficients: Optional[Sequence[float]] = None, parser: Optional[Callable] = None,
             relax_integers: bool = True, solver_options: Optional[dict] = None):
    import pyomo.environ as pyo
    from pyomo.contrib.appsi.solvers import Highs

    design = getattr(model, design) if isinstance(design, str) else design
    cost = getattr(model, cost) if isinstance(cost, str) else cost
    keys = list(design.keys()) if dimensions is None else list(dimensions)
    missing = [k for k in keys if k not in design]
    if missing:
        raise ValueError(f"Unknown dimension(s) {missing} for '{design.name}'. Available: {list(design.keys())}")
    super().__init__(keys)
    self.model = model
    self.parser = parser
    self._design = [design[k] for k in keys]

    integer_vars = [v for v in model.component_data_objects(pyo.Var, active=True) if v.is_integer()]
    if integer_vars:
        if not relax_integers:
            raise ValueError(f'The model has {len(integer_vars)} integer/binary variables; ORACLE needs a convex '
                             'model. Use relax_integers=True to relax them.')
        pyo.TransformationFactory('core.relax_integer_vars').apply_to(model)
        warnings.warn(f'ORACLE needs a convex model: {len(integer_vars)} integer/binary variables were relaxed '
                      'to continuous variables.', stacklevel=2)

    self._lower = np.array([v.lb if v.lb is not None else -np.inf for v in self._design]) if lower is None \
        else _as_array(lower, self.n_dims, -np.inf)
    self._upper = np.array([v.ub if v.ub is not None else np.inf for v in self._design]) if upper is None \
        else _as_array(upper, self.n_dims, np.inf)
    self._cost_coefficients = None if cost_coefficients is None \
        else _as_array(cost_coefficients, self.n_dims, 0.0)

    for objective in model.component_data_objects(pyo.Objective, active=True):
        objective.deactivate()

    if hasattr(model, 'oracle'):
        raise ValueError("The model already has a component named 'oracle'; build a fresh model for each problem.")
    b = model.oracle = pyo.Block()
    b.dims = pyo.RangeSet(0, self.n_dims - 1)
    b.target = pyo.Param(b.dims, mutable=True, initialize=0.0)
    b.scale = pyo.Param(b.dims, mutable=True, initialize=1.0)
    b.direction = pyo.Param(b.dims, mutable=True, initialize=0.0)
    b.budget = pyo.Param(mutable=True, initialize=0.0)
    b.delta = pyo.Var(b.dims)
    b.t = pyo.Var(bounds=(0, None))
    # z + delta = target, |delta_i| <= scale_i * t: t is the scaled L-infinity distance between z and the target
    b.link = pyo.Constraint(b.dims, rule=lambda _, i: self._design[i] + b.delta[i] == b.target[i])
    b.deviation_up = pyo.Constraint(b.dims, rule=lambda _, i: b.delta[i] <= b.scale[i] * b.t)
    b.deviation_down = pyo.Constraint(b.dims, rule=lambda _, i: -b.delta[i] <= b.scale[i] * b.t)
    b.budget_limit = pyo.Constraint(expr=cost <= b.budget)
    # Bounds given by the user are part of the explored model (always active).
    given_lower = np.full(self.n_dims, -np.inf) if lower is None else self._lower
    given_upper = np.full(self.n_dims, np.inf) if upper is None else self._upper

    def box(_, i):
        lo = float(given_lower[i]) if np.isfinite(given_lower[i]) else None
        up = float(given_upper[i]) if np.isfinite(given_upper[i]) else None
        return pyo.Constraint.Skip if lo is None and up is None else (lo, self._design[i], up)
    b.box = pyo.Constraint(b.dims, rule=box)
    b.cost_objective = pyo.Objective(expr=cost)
    b.distance_objective = pyo.Objective(expr=b.t)
    b.linear_objective = pyo.Objective(expr=sum(b.direction[i] * self._design[i] for i in b.dims))
    self._block = b
    self._cost = cost

    self._solver = Highs()
    self._solver.config.stream_solver = False
    self._solver.config.load_solution = False
    if solver_options:
        self._solver.highs_options.update(solver_options)

dimensions instance-attribute ¤

dimensions = list(dimensions)

model instance-attribute ¤

model = model

n_dims property ¤

n_dims: int

parser instance-attribute ¤

parser = parser

bounds ¤

bounds() -> tuple[ndarray, ndarray]
Source code in src/energyscope/oracle/problem.py
311
312
def bounds(self) -> tuple[np.ndarray, np.ndarray]:
    return self._lower.copy(), self._upper.copy()

cost_at ¤

cost_at(point: ndarray) -> CostAtPoint
Source code in src/energyscope/oracle/problem.py
334
335
336
337
338
339
340
341
def cost_at(self, point: np.ndarray) -> CostAtPoint:
    import pyomo.environ as pyo
    b = self._block
    for i in b.dims:
        b.target[i].set_value(float(point[i]))
    self._set_mode('cost_at')
    self._solve('fixed-design cost')
    return CostAtPoint(cost=float(pyo.value(self._cost)), gradient=self._link_duals())

cost_coefficients ¤

cost_coefficients() -> Optional[ndarray]
Source code in src/energyscope/oracle/problem.py
314
315
def cost_coefficients(self) -> Optional[np.ndarray]:
    return None if self._cost_coefficients is None else self._cost_coefficients.copy()

design_at ¤

design_at(point: ndarray) -> Any

Cheapest full system with the design point: a Result for EnergyScope models (via parser), otherwise the solved Pyomo model.

Source code in src/energyscope/oracle/problem.py
351
352
353
354
355
def design_at(self, point: np.ndarray) -> Any:
    """Cheapest full system with the design ``point``: a [`Result`][energyscope.result.Result] for EnergyScope
    models (via ``parser``), otherwise the solved Pyomo model."""
    self.cost_at(point)
    return self.parser(self.model) if self.parser is not None else self.model

extreme ¤

extreme(direction: ndarray) -> ndarray
Source code in src/energyscope/oracle/problem.py
343
344
345
346
347
348
349
def extreme(self, direction: np.ndarray) -> np.ndarray:
    b = self._block
    for i in b.dims:
        b.direction[i].set_value(float(direction[i]))
    self._set_mode('extreme')
    self._solve('extreme design')
    return self._design_values()

from_energyscope classmethod ¤

from_energyscope(
    technologies: Sequence[str],
    model: Optional[PyomoModel] = None,
    solver_options: Optional[dict] = None,
) -> PyomoProblem

Explore the installed capacities of some technologies of an EnergyScope Pyomo model.

Parameters:

  • technologies ¤

    (Sequence[str]) –

    Technologies whose capacity (F_Mult) spans the explored space, e.g. ['PV', 'WIND', 'NUCLEAR', 'CCGT'].

  • model ¤

    (Optional[PyomoModel], default: None ) –

    An EnergyScope PyomoModel (default: energyscope.models.pyomo_ch).

  • solver_options ¤

    (Optional[dict], default: None ) –

    Extra HiGHS options.

Returns:

  • PyomoProblem –

    The problem, with the technology bounds f_min/f_max and the annualised investment costs tau * c_inv as cost under-estimator.

Source code in src/energyscope/oracle/problem.py
230
231
232
233
234
235
236
237
238
239
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
@classmethod
def from_energyscope(cls, technologies: Sequence[str], model: Optional['PyomoModel'] = None,
                     solver_options: Optional[dict] = None) -> 'PyomoProblem':
    """Explore the installed capacities of some technologies of an EnergyScope Pyomo model.

    Args:
        technologies: Technologies whose capacity (``F_Mult``) spans the explored space, e.g.
            ``['PV', 'WIND', 'NUCLEAR', 'CCGT']``.
        model: An EnergyScope [`PyomoModel`][energyscope.models.PyomoModel] (default:
            ``energyscope.models.pyomo_ch``).
        solver_options: Extra HiGHS options.

    Returns:
        The problem, with the technology bounds ``f_min``/``f_max`` and the annualised investment costs
            ``tau * c_inv`` as cost under-estimator.
    """
    import pyomo.environ as pyo
    from energyscope.models import pyomo_ch
    from energyscope.result import parse_pyomo_result

    model = pyomo_ch if model is None else model
    spec = importlib.util.spec_from_file_location('ses_pyomo', model.model_path)
    ses_pyomo = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(ses_pyomo)
    with open(str(model.data_path), 'r') as f:
        data = json.load(f)
    m = ses_pyomo.build_model(data, objective='cost')

    technologies = list(technologies)
    unknown = [t for t in technologies if t not in m.TECHNOLOGIES]
    if unknown:
        raise ValueError(f'Unknown technologies {unknown}. Available: {sorted(m.TECHNOLOGIES)}')
    return cls(m, design=m.F_Mult, cost=m.TotalCost, dimensions=technologies,
               lower=[pyo.value(m.f_min[t]) for t in technologies],
               upper=[pyo.value(m.f_max[t]) for t in technologies],
               cost_coefficients=[pyo.value(m.tau[t] * m.c_inv[t]) for t in technologies],
               parser=parse_pyomo_result, solver_options=solver_options)

nearest ¤

nearest(target: ndarray, scale: ndarray) -> NearestPoint
Source code in src/energyscope/oracle/problem.py
323
324
325
326
327
328
329
330
331
332
def nearest(self, target: np.ndarray, scale: np.ndarray) -> NearestPoint:
    import pyomo.environ as pyo
    b = self._block
    for i in b.dims:
        b.target[i].set_value(float(target[i]))
        b.scale[i].set_value(float(scale[i]))
    self._set_mode('nearest')
    self._solve('nearest near-optimal design')
    return NearestPoint(point=self._design_values(), distance=float(pyo.value(b.t)), normal=self._link_duals(),
                        cost=float(pyo.value(self._cost)))

set_budget ¤

set_budget(budget: Optional[float]) -> None
Source code in src/energyscope/oracle/problem.py
306
307
308
309
def set_budget(self, budget: Optional[float]) -> None:
    super().set_budget(budget)
    if budget is not None:
        self._block.budget.set_value(budget)

solve_optimum ¤

solve_optimum() -> tuple[float, ndarray]
Source code in src/energyscope/oracle/problem.py
317
318
319
320
321
def solve_optimum(self) -> tuple[float, np.ndarray]:
    import pyomo.environ as pyo
    self._set_mode('optimum')
    self._solve('cost optimum')
    return float(pyo.value(self._cost)), self._design_values()

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'.")

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)