Skip to content

problem ¤

Models that ORACLE can explore.

ORACLE only talks to a model through four questions (the "oracle" calls):

  1. What is the cost optimum? (solve_optimum)
  2. Which near-optimal design is closest to this trial point? (nearest)
  3. What does it cost, at least, to build exactly this design? (cost_at)
  4. How far can the near-optimal space go in this direction? (extreme)

PyomoProblem answers them for any linear Pyomo model (e.g. the EnergyScope pyomo_ch model, license-free with HiGHS) and AmplProblem for any linear AMPL model (e.g. the EnergyScope core model).

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?".

  • NearOptimalProblem –

    Interface between ORACLE and an optimisation model.

  • NearestPoint –

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

  • PyomoProblem –

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

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

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

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