{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2d61e430",
   "metadata": {},
   "source": [
    "# Explore near-optimal designs with ORACLE\n",
    "\n",
    "The cost-optimal solution of an energy system model is only **one** answer. Models simplify reality, costs are uncertain, and decision-makers care about things a model does not capture: public acceptance, land use, security of supply, and so on. Often, many **very different** energy systems cost only a few percent more than the optimum. Together they form the **near-optimal space**:\n",
    "\n",
    "$$\n",
    "\\mathcal{Z}_\\varepsilon = \\left\\{\\, z \\;\\middle|\\; \\exists\\, x \\text{ feasible with design } z,\\; \\text{cost}(x) \\le (1+\\varepsilon)\\, C^* \\,\\right\\}\n",
    "$$\n",
    "\n",
    "where $x$ is a complete energy system (all the variables of the model), $z$ the design decisions you care about (e.g. the installed capacities of wind, PV, nuclear and gas power plants), $C^*$ the optimal cost, and $\\varepsilon$ the cost slack you accept (e.g. 5 %).\n",
    "\n",
    "*Modelling to Generate Alternatives* (MGA) methods find alternatives in this space, but they **cannot tell you how much of it they have missed**. **ORACLE** (*Optimization for the Rigorous Analysis of the Complete Landscape of alternatives in Energy systems*), a method developed by **Evren M. Turan, Stefano Moret and André Bardow** at ETH Zurich [1], solves this problem. It sandwiches the near-optimal space between an **inner** and an **outer** approximation and measures the gap between the two. Once the gap is small, you have mapped **all** near-optimal designs, with a known accuracy.\n",
    "\n",
    "> **ORACLE is a general method; this tutorial shows one possible application of it.** ORACLE works with **any energy system model** that is a linear (more generally, convex) optimisation problem, whatever the modelling framework. The authors demonstrate it on an hourly EnergyScope model of Switzerland with typical days [1]. Here we apply it to a simpler, monthly EnergyScope model of Switzerland shipped with this library, with the implementation in `energyscope.oracle`, which is adapted from the authors' reference code [2].\n",
    ">\n",
    "> The method, its metric and its guarantees are the work of Turan, Moret and Bardow. **If you use ORACLE, please cite their paper** [1] (see *How to cite* at the end of this tutorial).\n",
    ">\n",
    "> [1] 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](https://doi.org/10.1016/j.compchemeng.2026.109630) (open access; preprint: [arXiv:2509.26452](https://arxiv.org/abs/2509.26452)).\n",
    ">\n",
    "> [2] Reference implementation of ORACLE, ETH Zurich (MIT license): [gitlab.ethz.ch/epse/systems-design-public/oracle-metric-and-method](https://gitlab.ethz.ch/epse/systems-design-public/oracle-metric-and-method).\n",
    "\n",
    "**In this tutorial**\n",
    "\n",
    "1. **How ORACLE works**, step by step, on a toy model with two design variables, where everything can be drawn. It uses Pyomo and the open-source HiGHS solver: no license needed.\n",
    "2. **One application, plug and play:** the EnergyScope model of Switzerland in 2050, solved with AMPL and Gurobi. This needs an AMPL license that includes Gurobi (free for academics, see [Getting started](../../getting-started/)). Without one, a one-line change runs the same steps with Pyomo and the open-source HiGHS solver (see the note just before the first code cell of part 2).\n",
    "3. **How to use the result:** ranges, trade-offs, sampling alternatives, and rebuilding a full energy system from a chosen design."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "bd7e413a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T17:42:29.672029Z",
     "iopub.status.busy": "2026-11-05T17:42:29.671809Z",
     "iopub.status.idle": "2026-11-05T17:42:31.626269Z",
     "shell.execute_reply": "2026-11-05T17:42:31.625753Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import plotly.express as px\n",
    "import plotly.graph_objects as go\n",
    "import plotly.io as pio\n",
    "import pyomo.environ as pyo\n",
    "from scipy.spatial import ConvexHull\n",
    "\n",
    "from energyscope.oracle import Oracle, PyomoProblem, polytope_vertices\n",
    "\n",
    "pio.renderers.default = 'notebook_connected'  # figures load plotly.js from the web: keeps the notebook light"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3b542bb5",
   "metadata": {},
   "source": [
    "---\n",
    "## 1. How ORACLE works, on a toy model\n",
    "\n",
    "A small country splits its year into two halves, **day** and **night**:\n",
    "\n",
    "| | day | night |\n",
    "|---|---|---|\n",
    "| Average electricity demand [GW] | 8 | 5 |\n",
    "| PV capacity factor | 0.40 | 0 |\n",
    "| Wind capacity factor | 0.25 | 0.35 |\n",
    "\n",
    "It decides how much **PV** and **wind** capacity to build (0 to 30 GW each): these two capacities are the **design variables** we want to explore. A gas power plant covers whatever is missing. Annualised costs, in arbitrary money units: PV 1.0 and wind 1.5 per GW installed; the gas plant 1.0 per GW installed plus 6 per GW of average production (fuel).\n",
    "\n",
    "This is a **linear program** (LP), hence convex, which is what ORACLE needs: convexity is what makes its approximations provably valid. To connect a model, ORACLE needs:\n",
    "\n",
    "1. `design`: the variables that span the space to explore, here the capacities `F['PV']` and `F['WIND']` (their bounds are read from the model);\n",
    "2. `cost`: the total cost that defines what \"near-optimal\" means;\n",
    "3. `cost_coefficients` (optional): a cheap **under-estimate** of the cost as a function of the design. Here it is the investment in PV and wind: whatever else happens, the system costs at least $1.0\\,F_{PV} + 1.5\\,F_{WIND}$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "10cdabb4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T17:42:31.627562Z",
     "iopub.status.busy": "2026-11-05T17:42:31.627500Z",
     "iopub.status.idle": "2026-11-05T17:42:31.630857Z",
     "shell.execute_reply": "2026-11-05T17:42:31.630518Z"
    }
   },
   "outputs": [],
   "source": [
    "def toy_model():\n",
    "    m = pyo.ConcreteModel()\n",
    "    m.TECH = pyo.Set(initialize=['PV', 'WIND'])\n",
    "    m.HALF = pyo.Set(initialize=['day', 'night'])\n",
    "    demand = {'day': 8.0, 'night': 5.0}                                  # GW\n",
    "    cf = {('PV', 'day'): 0.40, ('PV', 'night'): 0.0, ('WIND', 'day'): 0.25, ('WIND', 'night'): 0.35}\n",
    "    capex = {'PV': 1.0, 'WIND': 1.5}                                      # per GW installed\n",
    "\n",
    "    m.F = pyo.Var(m.TECH, bounds=(0, 30))                                # PV and wind capacity [GW]: the design\n",
    "    m.GAS = pyo.Var(bounds=(0, None))                                     # gas plant capacity [GW]\n",
    "    m.gas_use = pyo.Var(m.HALF, bounds=(0, None))                         # gas plant production [GW]\n",
    "\n",
    "    m.balance = pyo.Constraint(m.HALF, rule=lambda m, h:\n",
    "                               sum(cf[t, h] * m.F[t] for t in m.TECH) + m.gas_use[h] >= demand[h])\n",
    "    m.gas_capacity = pyo.Constraint(m.HALF, rule=lambda m, h: m.gas_use[h] <= m.GAS)\n",
    "    m.TotalCost = pyo.Expression(expr=sum(capex[t] * m.F[t] for t in m.TECH) + 1.0 * m.GAS\n",
    "                                 + sum(0.5 * 6.0 * m.gas_use[h] for h in m.HALF))  # day and night: half a year each\n",
    "    return m\n",
    "\n",
    "\n",
    "problem = PyomoProblem(toy_model(), design='F', cost='TotalCost', cost_coefficients=[1.0, 1.5])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0ef1a54d",
   "metadata": {},
   "source": [
    "To check ORACLE against the truth, we first compute the exact near-optimal space by brute force, which is only possible in two dimensions: solve the cost optimum $C^*$, impose the budget $\\text{cost} \\le (1+\\varepsilon)\\,C^*$ with $\\varepsilon = 10\\,\\%$, and push the design as far as possible in 360 directions (one LP each). ORACLE avoids exactly this brute force, which is impossible with more dimensions.\n",
    "\n",
    "The helper `draw` (you can skip reading it) draws the true near-optimal space (black outline), ORACLE's **outer approximation** (light blue) and **inner approximation** (dark blue), both explained below, and the cost optimum (red star)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "02fb7ba2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T17:42:31.631910Z",
     "iopub.status.busy": "2026-11-05T17:42:31.631864Z",
     "iopub.status.idle": "2026-11-05T17:42:31.822814Z",
     "shell.execute_reply": "2026-11-05T17:42:31.822376Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Optimal cost: 32.50 -> budget with eps = 10%: 35.75\n",
      "Cost-optimal design: PV = 11.07 GW, wind = 14.29 GW\n"
     ]
    }
   ],
   "source": [
    "EPS = 0.10  # accept designs that cost at most 10 % more than the optimum\n",
    "\n",
    "optimal_cost, optimal_design = problem.solve_optimum()\n",
    "problem.set_budget((1 + EPS) * optimal_cost)\n",
    "print(f'Optimal cost: {optimal_cost:.2f} -> budget with eps = {EPS:.0%}: {(1 + EPS) * optimal_cost:.2f}')\n",
    "print(f'Cost-optimal design: PV = {optimal_design[0]:.2f} GW, wind = {optimal_design[1]:.2f} GW')\n",
    "true_points = np.array([problem.extreme(np.array([np.cos(a), np.sin(a)]))\n",
    "                        for a in np.linspace(0, 2 * np.pi, 360, endpoint=False)])\n",
    "\n",
    "\n",
    "def outline(points):\n",
    "    # Closed outline of a convex 2-D point set (its convex hull).\n",
    "    points = np.unique(np.round(np.atleast_2d(points), 9), axis=0)\n",
    "    if len(points) < 3:\n",
    "        return points\n",
    "    loop = points[ConvexHull(points).vertices]\n",
    "    return np.vstack([loop, loop[:1]])\n",
    "\n",
    "\n",
    "def draw(oracle, title, trial=None, found=None):\n",
    "    fig = go.Figure()\n",
    "    areas = [(polytope_vertices(oracle.A, oracle.b), 'Outer approximation O',\n",
    "              dict(fill='toself', fillcolor='rgba(158,202,225,0.35)', line=dict(color='#6baed6', dash='dash'))),\n",
    "             (true_points, 'True near-optimal space', dict(mode='lines', line=dict(color='black', width=2))),\n",
    "             (oracle.inner_points, 'Inner approximation I',\n",
    "              dict(fill='toself', fillcolor='rgba(8,81,156,0.45)', line=dict(color='#08519c')))]\n",
    "    for points, name, style in areas:\n",
    "        loop = outline(points)\n",
    "        fig.add_trace(go.Scatter(x=loop[:, 0], y=loop[:, 1], name=name, **style))\n",
    "    points = [(oracle.optimum, 'Cost optimum', dict(symbol='star', size=14, color='#d62728')),\n",
    "              (trial, 'Trial point', dict(symbol='x', size=12, color='#ff7f0e')),\n",
    "              (found, 'Closest near-optimal design', dict(size=10, color='#2ca02c'))]\n",
    "    for point, name, marker in points:\n",
    "        if point is not None:\n",
    "            fig.add_trace(go.Scatter(x=[point[0]], y=[point[1]], mode='markers', marker=marker, name=name))\n",
    "    fig.update_layout(template='plotly_white', title=title, height=520, legend=dict(orientation='h', y=-0.15),\n",
    "                      xaxis=dict(title='PV capacity [GW]', range=[-1, 31]),\n",
    "                      yaxis=dict(title='Wind capacity [GW]', range=[-1, 31]))\n",
    "    return fig"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71fcbf8e",
   "metadata": {},
   "source": [
    "The cost optimum is fully renewable (about 11 GW of PV and 14 GW of wind, no gas), but for only 10 % more, very different designs are possible: much less PV and more wind, or fewer renewables backed up by gas. You will see the true space in the figures below. Now let us pretend we do not know it, and let ORACLE find it.\n",
    "\n",
    "### The idea\n",
    "\n",
    "Following Turan, Moret and Bardow [1], ORACLE maintains two approximations of the unknown near-optimal space $\\mathcal{Z}_\\varepsilon$:\n",
    "\n",
    "- the **inner approximation** $I$: the convex hull of the near-optimal designs found so far. Because $\\mathcal{Z}_\\varepsilon$ is convex, **every point of $I$ is a guaranteed near-optimal design**;\n",
    "- the **outer approximation** $O$: a polytope made of halfspaces (\"cuts\") that are **guaranteed to contain all near-optimal designs**.\n",
    "\n",
    "The truth is always sandwiched, $I \\subseteq \\mathcal{Z}_\\varepsilon \\subseteq O$, and ORACLE measures the gap with its metric, the largest distance from a point of $O$ to $I$:\n",
    "\n",
    "$$\n",
    "d = \\max_{z \\in O}\\; \\min_{y \\in I}\\; \\lVert z - y \\rVert_\\infty\n",
    "$$\n",
    "\n",
    "$d$ is the **largest error** you can make by using $I$ (or $O$) instead of the true near-optimal space, in the units of the design variables (GW here; the $\\infty$-norm is the largest deviation of any single technology). This metric is the key contribution of the paper [1]. As in the paper, ORACLE proceeds in steps:\n",
    "\n",
    "- **Step 1, initialise:** $I$ is the cost optimum, and $O$ the box of the variable bounds cut by the investment budget, $1.0\\,F_{PV} + 1.5\\,F_{WIND} \\le (1+\\varepsilon)\\,C^*$.\n",
    "\n",
    "Then it repeats steps 2 to 4 until $d$ is below a tolerance:\n",
    "\n",
    "- **Step 2, measure the gap:** compute $d$ and the point of $O$ that reaches it, the **trial point**, where the two approximations disagree most. (The paper [1] computes it by solving a bilevel problem, reformulated as a mixed-integer linear program. This implementation does the same above 6 dimensions; in up to 6 dimensions it simply checks the vertices of $O$, where the maximum lies.)\n",
    "- **Step 3, explore:** solve one LP on the full model for the near-optimal design **closest to the trial point**. Its dual variables $\\mu$ tell how this distance changes when the trial point moves.\n",
    "- **Step 4, refine:** add the design found to $I$, and cut the trial point off $O$ with the hyperplane $\\mu^\\top z \\le \\mu^\\top z_\\text{found}$. This cut is **valid**, it never removes a near-optimal design: the distance to $\\mathcal{Z}_\\varepsilon$ is a convex function of the trial point, $\\mu$ is its slope, and it is zero on $\\mathcal{Z}_\\varepsilon$. A second LP (the cheapest system with the design found) gives a second, **cost** cut.\n",
    "\n",
    "Let us run the first iteration by hand, with a tolerance of 0.05 GW."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5d7f76bf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T17:42:31.823932Z",
     "iopub.status.busy": "2026-11-05T17:42:31.823863Z",
     "iopub.status.idle": "2026-11-05T17:42:31.998034Z",
     "shell.execute_reply": "2026-11-05T17:42:31.997605Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ORACLE: 2 dimensions, optimal cost 32.5, budget 35.75 (eps = 10.00%), tolerance 0.05\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ORACLE metric d = 18.93 GW, reached at the trial point [30.    3.83]\n",
      "Closest near-optimal design: [14.94  8.1 ], at 15.06 GW from the trial point\n",
      "Dual variables mu: [1. 0.]\n"
     ]
    },
    {
     "data": {
      "text/html": "<div style=\"height:520px; width:100%;\">            <script>if (window.MathJax && window.MathJax.Hub && window.MathJax.Hub.Config) {window.MathJax.Hub.Config({SVG: {font: \"STIX-Web\"}});}</script>                <script>window.PlotlyConfig = {MathJaxConfig: 'local'};</script>\n        <script charset=\"utf-8\" src=\"https://cdn.plot.ly/plotly-3.7.0.min.js\" integrity=\"sha256-jvTGqxNp8AGWEcvNLVuKr+8j5dGe9Yw51LQkmDH+IYA=\" crossorigin=\"anonymous\"></script>                <div id=\"3d17a866-1c86-48fd-9a4b-d59b69fad5a2\" class=\"plotly-graph-div\" style=\"height:100%; width:100%;\"></div>            <script>                window.PLOTLYENV=window.PLOTLYENV || {};                                if (document.getElementById(\"3d17a866-1c86-48fd-9a4b-d59b69fad5a2\")) {                    Plotly.newPlot(                        \"3d17a866-1c86-48fd-9a4b-d59b69fad5a2\",                        [{\"fill\":\"toself\",\"fillcolor\":\"rgba(158,202,225,0.35)\",\"line\":{\"color\":\"#6baed6\",\"dash\":\"dash\"},\"name\":\"Outer approximation O\",\"x\":{\"dtype\":\"f8\",\"bdata\":\"AAAAAAAAAAAAAAAAAAA+QAAAAAAAAD5AAAAAAAAAAAAAAAAAAAAAAA==\"},\"y\":{\"dtype\":\"f8\",\"bdata\":\"AAAAAAAAAAAAAAAAAAAAAKM2n6qqqg5A1OZTVVXVN0AAAAAAAAAAAA==\"},\"type\":\"scatter\"},{\"line\":{\"color\":\"black\",\"width\":2},\"mode\":\"lines\",\"name\":\"True near-optimal space\",\"x\":{\"dtype\":\"f8\",\"bdata\":\"AAAAAACAIUAPkaLneZ4WQG+9lCRJ0iNA8W5dGIbhLUDZ4yBJkqQsQAAAAAAAgCFA\"},\"y\":{\"dtype\":\"f8\",\"bdata\":\"AAAAAAAAMkBvvZQkSZIsQLheSpIkSSNAeLcuDMMwIEBvvZQkSZIsQAAAAAAAADJA\"},\"type\":\"scatter\"},{\"fill\":\"toself\",\"fillcolor\":\"rgba(8,81,156,0.45)\",\"line\":{\"color\":\"#08519c\"},\"name\":\"Inner approximation I\",\"x\":{\"dtype\":\"f8\",\"bdata\":\"2eMgSZIkJkA=\"},\"y\":{\"dtype\":\"f8\",\"bdata\":\"b72UJEmSLEA=\"},\"type\":\"scatter\"},{\"marker\":{\"color\":\"#d62728\",\"size\":14,\"symbol\":\"star\"},\"mode\":\"markers\",\"name\":\"Cost optimum\",\"x\":[11.071428571428571],\"y\":[14.285714285714286],\"type\":\"scatter\"},{\"marker\":{\"color\":\"#ff7f0e\",\"size\":12,\"symbol\":\"x\"},\"mode\":\"markers\",\"name\":\"Trial point\",\"x\":[30.0],\"y\":[3.8333333333333335],\"type\":\"scatter\"},{\"marker\":{\"color\":\"#2ca02c\",\"size\":10},\"mode\":\"markers\",\"name\":\"Closest near-optimal design\",\"x\":[14.940476190476195],\"y\":[8.095238095238086],\"type\":\"scatter\"}],                        {\"template\":{\"data\":{\"barpolar\":[{\"marker\":{\"line\":{\"color\":\"white\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"barpolar\"}],\"bar\":[{\"error_x\":{\"color\":\"#2a3f5f\"},\"error_y\":{\"color\":\"#2a3f5f\"},\"marker\":{\"line\":{\"color\":\"white\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"bar\"}],\"carpet\":[{\"aaxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"#C8D4E3\",\"linecolor\":\"#C8D4E3\",\"minorgridcolor\":\"#C8D4E3\",\"startlinecolor\":\"#2a3f5f\"},\"baxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"#C8D4E3\",\"linecolor\":\"#C8D4E3\",\"minorgridcolor\":\"#C8D4E3\",\"startlinecolor\":\"#2a3f5f\"},\"type\":\"carpet\"}],\"choropleth\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"choropleth\"}],\"contourcarpet\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"contourcarpet\"}],\"contour\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"contour\"}],\"heatmap\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"heatmap\"}],\"histogram2dcontour\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"histogram2dcontour\"}],\"histogram2d\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"histogram2d\"}],\"histogram\":[{\"marker\":{\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"histogram\"}],\"mesh3d\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"mesh3d\"}],\"parcoords\":[{\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"parcoords\"}],\"pie\":[{\"automargin\":true,\"type\":\"pie\"}],\"scatter3d\":[{\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatter3d\"}],\"scattercarpet\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattercarpet\"}],\"scattergeo\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattergeo\"}],\"scattergl\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattergl\"}],\"scattermapbox\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattermapbox\"}],\"scattermap\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattermap\"}],\"scatterpolargl\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterpolargl\"}],\"scatterpolar\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterpolar\"}],\"scatter\":[{\"fillpattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2},\"type\":\"scatter\"}],\"scatterternary\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterternary\"}],\"surface\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"surface\"}],\"table\":[{\"cells\":{\"fill\":{\"color\":\"#EBF0F8\"},\"line\":{\"color\":\"white\"}},\"header\":{\"fill\":{\"color\":\"#C8D4E3\"},\"line\":{\"color\":\"white\"}},\"type\":\"table\"}]},\"layout\":{\"annotationdefaults\":{\"arrowcolor\":\"#2a3f5f\",\"arrowhead\":0,\"arrowwidth\":1},\"autotypenumbers\":\"strict\",\"coloraxis\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"colorscale\":{\"diverging\":[[0,\"#8e0152\"],[0.1,\"#c51b7d\"],[0.2,\"#de77ae\"],[0.3,\"#f1b6da\"],[0.4,\"#fde0ef\"],[0.5,\"#f7f7f7\"],[0.6,\"#e6f5d0\"],[0.7,\"#b8e186\"],[0.8,\"#7fbc41\"],[0.9,\"#4d9221\"],[1,\"#276419\"]],\"sequential\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"sequentialminus\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]},\"colorway\":[\"#636efa\",\"#EF553B\",\"#00cc96\",\"#ab63fa\",\"#FFA15A\",\"#19d3f3\",\"#FF6692\",\"#B6E880\",\"#FF97FF\",\"#FECB52\"],\"font\":{\"color\":\"#2a3f5f\"},\"geo\":{\"bgcolor\":\"white\",\"lakecolor\":\"white\",\"landcolor\":\"white\",\"showlakes\":true,\"showland\":true,\"subunitcolor\":\"#C8D4E3\"},\"hoverlabel\":{\"align\":\"left\"},\"hovermode\":\"closest\",\"mapbox\":{\"style\":\"light\"},\"paper_bgcolor\":\"white\",\"plot_bgcolor\":\"white\",\"polar\":{\"angularaxis\":{\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\"},\"bgcolor\":\"white\",\"radialaxis\":{\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\"}},\"scene\":{\"xaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"},\"yaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"},\"zaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"}},\"shapedefaults\":{\"line\":{\"color\":\"#2a3f5f\"}},\"ternary\":{\"aaxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"},\"baxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"},\"bgcolor\":\"white\",\"caxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"}},\"title\":{\"x\":0.05},\"xaxis\":{\"automargin\":true,\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"#EBF0F8\",\"zerolinewidth\":2},\"yaxis\":{\"automargin\":true,\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"#EBF0F8\",\"zerolinewidth\":2}}},\"legend\":{\"orientation\":\"h\",\"y\":-0.15},\"xaxis\":{\"title\":{\"text\":\"PV capacity [GW]\"},\"range\":[-1,31]},\"yaxis\":{\"title\":{\"text\":\"Wind capacity [GW]\"},\"range\":[-1,31]},\"title\":{\"text\":\"Steps 2-3: trial point and closest design\"},\"height\":520},                        {\"responsive\": true}                    ).then(function(){\n                            \nvar gd = document.getElementById('3d17a866-1c86-48fd-9a4b-d59b69fad5a2');\nvar x = new MutationObserver(function (mutations, observer) {{\n        var display = window.getComputedStyle(gd).display;\n        if (!display || display === 'none') {{\n            console.log([gd, 'removed!']);\n            Plotly.purge(gd);\n            observer.disconnect();\n        }}\n}});\n\n// Listen for the removal of the full notebook cells\nvar notebookContainer = gd.closest('#notebook-container');\nif (notebookContainer) {{\n    x.observe(notebookContainer, {childList: true});\n}}\n\n// Listen for the clearing of the current output cell\nvar outputEl = gd.closest('.output');\nif (outputEl) {{\n    x.observe(outputEl, {childList: true});\n}}\n\n                        })                };            </script>        </div>"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "oracle = Oracle(problem, eps=EPS, tol=0.05)\n",
    "oracle.initialise()                           # step 1: initialise\n",
    "trial = oracle.furthest_point()               # step 2: measure the gap\n",
    "explored = oracle.nearest_point(trial.point)  # step 3: explore\n",
    "print(f'ORACLE metric d = {trial.distance:.2f} GW, reached at the trial point {trial.point.round(2)}')\n",
    "print(f'Closest near-optimal design: {explored.point.round(2)}, at {explored.distance:.2f} GW from the trial point')\n",
    "print(f'Dual variables mu: {explored.normal.round(3) + 0.0}')\n",
    "draw(oracle, 'Steps 2-3: trial point and closest design', trial.point, explored.point).show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "33962ebf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T17:42:31.998916Z",
     "iopub.status.busy": "2026-11-05T17:42:31.998855Z",
     "iopub.status.idle": "2026-11-05T17:42:32.020281Z",
     "shell.execute_reply": "2026-11-05T17:42:32.019912Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": "<div style=\"height:520px; width:100%;\">            <script>if (window.MathJax && window.MathJax.Hub && window.MathJax.Hub.Config) {window.MathJax.Hub.Config({SVG: {font: \"STIX-Web\"}});}</script>                <script>window.PlotlyConfig = {MathJaxConfig: 'local'};</script>\n        <script charset=\"utf-8\" src=\"https://cdn.plot.ly/plotly-3.7.0.min.js\" integrity=\"sha256-jvTGqxNp8AGWEcvNLVuKr+8j5dGe9Yw51LQkmDH+IYA=\" crossorigin=\"anonymous\"></script>                <div id=\"d22f6ae4-0032-4935-9983-7506c6055ed0\" class=\"plotly-graph-div\" style=\"height:100%; width:100%;\"></div>            <script>                window.PLOTLYENV=window.PLOTLYENV || {};                                if (document.getElementById(\"d22f6ae4-0032-4935-9983-7506c6055ed0\")) {                    Plotly.newPlot(                        \"d22f6ae4-0032-4935-9983-7506c6055ed0\",                        [{\"fill\":\"toself\",\"fillcolor\":\"rgba(158,202,225,0.35)\",\"line\":{\"color\":\"#6baed6\",\"dash\":\"dash\"},\"name\":\"Outer approximation O\",\"x\":{\"dtype\":\"f8\",\"bdata\":\"AAAAAAAAAABKSN4YhuEtQEpI3hiG4S1AAAAAAAAAAIAAAAAAAAAAAA==\"},\"y\":{\"dtype\":\"f8\",\"bdata\":\"Sf\\u002fpC8MwIEBJ\\u002f+kLwzAgQMzyaO\\u002f7vitA1OZTVVXVN0BJ\\u002f+kLwzAgQA==\"},\"type\":\"scatter\"},{\"line\":{\"color\":\"black\",\"width\":2},\"mode\":\"lines\",\"name\":\"True near-optimal space\",\"x\":{\"dtype\":\"f8\",\"bdata\":\"AAAAAACAIUAPkaLneZ4WQG+9lCRJ0iNA8W5dGIbhLUDZ4yBJkqQsQAAAAAAAgCFA\"},\"y\":{\"dtype\":\"f8\",\"bdata\":\"AAAAAAAAMkBvvZQkSZIsQLheSpIkSSNAeLcuDMMwIEBvvZQkSZIsQAAAAAAAADJA\"},\"type\":\"scatter\"},{\"fill\":\"toself\",\"fillcolor\":\"rgba(8,81,156,0.45)\",\"line\":{\"color\":\"#08519c\"},\"name\":\"Inner approximation I\",\"x\":{\"dtype\":\"f8\",\"bdata\":\"2eMgSZIkJkDxbl0YhuEtQA==\"},\"y\":{\"dtype\":\"f8\",\"bdata\":\"b72UJEmSLEB4ty4MwzAgQA==\"},\"type\":\"scatter\"},{\"marker\":{\"color\":\"#d62728\",\"size\":14,\"symbol\":\"star\"},\"mode\":\"markers\",\"name\":\"Cost optimum\",\"x\":[11.071428571428571],\"y\":[14.285714285714286],\"type\":\"scatter\"},{\"marker\":{\"color\":\"#ff7f0e\",\"size\":12,\"symbol\":\"x\"},\"mode\":\"markers\",\"name\":\"Trial point\",\"x\":[30.0],\"y\":[3.8333333333333335],\"type\":\"scatter\"}],                        {\"template\":{\"data\":{\"barpolar\":[{\"marker\":{\"line\":{\"color\":\"white\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"barpolar\"}],\"bar\":[{\"error_x\":{\"color\":\"#2a3f5f\"},\"error_y\":{\"color\":\"#2a3f5f\"},\"marker\":{\"line\":{\"color\":\"white\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"bar\"}],\"carpet\":[{\"aaxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"#C8D4E3\",\"linecolor\":\"#C8D4E3\",\"minorgridcolor\":\"#C8D4E3\",\"startlinecolor\":\"#2a3f5f\"},\"baxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"#C8D4E3\",\"linecolor\":\"#C8D4E3\",\"minorgridcolor\":\"#C8D4E3\",\"startlinecolor\":\"#2a3f5f\"},\"type\":\"carpet\"}],\"choropleth\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"choropleth\"}],\"contourcarpet\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"contourcarpet\"}],\"contour\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"contour\"}],\"heatmap\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"heatmap\"}],\"histogram2dcontour\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"histogram2dcontour\"}],\"histogram2d\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"histogram2d\"}],\"histogram\":[{\"marker\":{\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"histogram\"}],\"mesh3d\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"mesh3d\"}],\"parcoords\":[{\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"parcoords\"}],\"pie\":[{\"automargin\":true,\"type\":\"pie\"}],\"scatter3d\":[{\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatter3d\"}],\"scattercarpet\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattercarpet\"}],\"scattergeo\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattergeo\"}],\"scattergl\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattergl\"}],\"scattermapbox\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattermapbox\"}],\"scattermap\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattermap\"}],\"scatterpolargl\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterpolargl\"}],\"scatterpolar\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterpolar\"}],\"scatter\":[{\"fillpattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2},\"type\":\"scatter\"}],\"scatterternary\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterternary\"}],\"surface\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"surface\"}],\"table\":[{\"cells\":{\"fill\":{\"color\":\"#EBF0F8\"},\"line\":{\"color\":\"white\"}},\"header\":{\"fill\":{\"color\":\"#C8D4E3\"},\"line\":{\"color\":\"white\"}},\"type\":\"table\"}]},\"layout\":{\"annotationdefaults\":{\"arrowcolor\":\"#2a3f5f\",\"arrowhead\":0,\"arrowwidth\":1},\"autotypenumbers\":\"strict\",\"coloraxis\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"colorscale\":{\"diverging\":[[0,\"#8e0152\"],[0.1,\"#c51b7d\"],[0.2,\"#de77ae\"],[0.3,\"#f1b6da\"],[0.4,\"#fde0ef\"],[0.5,\"#f7f7f7\"],[0.6,\"#e6f5d0\"],[0.7,\"#b8e186\"],[0.8,\"#7fbc41\"],[0.9,\"#4d9221\"],[1,\"#276419\"]],\"sequential\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"sequentialminus\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]},\"colorway\":[\"#636efa\",\"#EF553B\",\"#00cc96\",\"#ab63fa\",\"#FFA15A\",\"#19d3f3\",\"#FF6692\",\"#B6E880\",\"#FF97FF\",\"#FECB52\"],\"font\":{\"color\":\"#2a3f5f\"},\"geo\":{\"bgcolor\":\"white\",\"lakecolor\":\"white\",\"landcolor\":\"white\",\"showlakes\":true,\"showland\":true,\"subunitcolor\":\"#C8D4E3\"},\"hoverlabel\":{\"align\":\"left\"},\"hovermode\":\"closest\",\"mapbox\":{\"style\":\"light\"},\"paper_bgcolor\":\"white\",\"plot_bgcolor\":\"white\",\"polar\":{\"angularaxis\":{\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\"},\"bgcolor\":\"white\",\"radialaxis\":{\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\"}},\"scene\":{\"xaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"},\"yaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"},\"zaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"}},\"shapedefaults\":{\"line\":{\"color\":\"#2a3f5f\"}},\"ternary\":{\"aaxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"},\"baxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"},\"bgcolor\":\"white\",\"caxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"}},\"title\":{\"x\":0.05},\"xaxis\":{\"automargin\":true,\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"#EBF0F8\",\"zerolinewidth\":2},\"yaxis\":{\"automargin\":true,\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"#EBF0F8\",\"zerolinewidth\":2}}},\"legend\":{\"orientation\":\"h\",\"y\":-0.15},\"xaxis\":{\"title\":{\"text\":\"PV capacity [GW]\"},\"range\":[-1,31]},\"yaxis\":{\"title\":{\"text\":\"Wind capacity [GW]\"},\"range\":[-1,31]},\"title\":{\"text\":\"Step 4: refined approximations\"},\"height\":520},                        {\"responsive\": true}                    ).then(function(){\n                            \nvar gd = document.getElementById('d22f6ae4-0032-4935-9983-7506c6055ed0');\nvar x = new MutationObserver(function (mutations, observer) {{\n        var display = window.getComputedStyle(gd).display;\n        if (!display || display === 'none') {{\n            console.log([gd, 'removed!']);\n            Plotly.purge(gd);\n            observer.disconnect();\n        }}\n}});\n\n// Listen for the removal of the full notebook cells\nvar notebookContainer = gd.closest('#notebook-container');\nif (notebookContainer) {{\n    x.observe(notebookContainer, {childList: true});\n}}\n\n// Listen for the clearing of the current output cell\nvar outputEl = gd.closest('.output');\nif (outputEl) {{\n    x.observe(outputEl, {childList: true});\n}}\n\n                        })                };            </script>        </div>"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>PV</th>\n",
       "      <th>WIND</th>\n",
       "      <th>rhs</th>\n",
       "      <th>kind</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>1.0</td>\n",
       "      <td>-0.0</td>\n",
       "      <td>14.940476</td>\n",
       "      <td>cut</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>-0.0</td>\n",
       "      <td>-1.0</td>\n",
       "      <td>-8.095238</td>\n",
       "      <td>cost cut</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    PV  WIND        rhs      kind\n",
       "5  1.0  -0.0  14.940476       cut\n",
       "6 -0.0  -1.0  -8.095238  cost cut"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "oracle.refine(trial.point, explored)          # step 4: refine (I grows, O gets two cuts)\n",
    "draw(oracle, 'Step 4: refined approximations', trial.point).show()\n",
    "oracle.result.outer.tail(2)                   # the two new cuts: sum(coefficient * z) <= rhs"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a6dc58c5",
   "metadata": {},
   "source": [
    "The trial point is now outside $O$, and $I$ has grown from a point to a segment. Here $\\mu = (1, 0)$, so the cut is $F_{PV} \\le 14.94$ GW: no near-optimal design has more PV than the design found. The cost cut adds $F_{WIND} \\ge 8.10$ GW. Both are new edges of $O$ in the figure.\n",
    "\n",
    "`oracle.step()` runs one such iteration, and `oracle.run()` iterates until the metric is below the tolerance (its counter does not include the iteration done by hand). Each line of its log is one iteration: the metric $d$ (\"distance\"), how far the trial point was from the near-optimal space (0 means that it is near-optimal, so no cut is needed), and which cuts were added. All distances are in GW:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c2893692",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T17:42:32.021449Z",
     "iopub.status.busy": "2026-11-05T17:42:32.021390Z",
     "iopub.status.idle": "2026-11-05T17:42:32.070504Z",
     "shell.execute_reply": "2026-11-05T17:42:32.070189Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   1: distance 11.07 | trial point is 5.911 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   2: distance 9.626 | trial point is 7.424 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   3: distance 2.222 | trial point is 0.5253 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   4: distance 1.591 | trial point is 0 away from the near-optimal space | no cut (trial point is near-optimal)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   5: distance 1.429 | trial point is 0.8497 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   6: distance 0.6272 | trial point is 0 away from the near-optimal space | no cut (trial point is near-optimal)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   7: distance 0.4727 | trial point is 0 away from the near-optimal space | no cut (trial point is near-optimal)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   8: distance 0.2652 | trial point is 0 away from the near-optimal space | no cut (trial point is near-optimal)\n",
      "  iteration   9: distance 0 <= tolerance 0.05: converged\n"
     ]
    },
    {
     "data": {
      "text/html": "<div style=\"height:520px; width:100%;\">            <script>if (window.MathJax && window.MathJax.Hub && window.MathJax.Hub.Config) {window.MathJax.Hub.Config({SVG: {font: \"STIX-Web\"}});}</script>                <script>window.PlotlyConfig = {MathJaxConfig: 'local'};</script>\n        <script charset=\"utf-8\" src=\"https://cdn.plot.ly/plotly-3.7.0.min.js\" integrity=\"sha256-jvTGqxNp8AGWEcvNLVuKr+8j5dGe9Yw51LQkmDH+IYA=\" crossorigin=\"anonymous\"></script>                <div id=\"a05b6dd6-99de-405a-92ef-284928a3630e\" class=\"plotly-graph-div\" style=\"height:100%; width:100%;\"></div>            <script>                window.PLOTLYENV=window.PLOTLYENV || {};                                if (document.getElementById(\"a05b6dd6-99de-405a-92ef-284928a3630e\")) {                    Plotly.newPlot(                        \"a05b6dd6-99de-405a-92ef-284928a3630e\",                        [{\"fill\":\"toself\",\"fillcolor\":\"rgba(158,202,225,0.35)\",\"line\":{\"color\":\"#6baed6\",\"dash\":\"dash\"},\"name\":\"Outer approximation O\",\"x\":{\"dtype\":\"f8\",\"bdata\":\"6KPd\\u002f\\u002f9\\u002fIUCAaNTmeZ4WQDTXPiRJ0iNAnizlF4bhLUBKSN4YhuEtQEpI3hiG4S1APuuySZKkLEDoo93\\u002f\\u002f38hQA==\"},\"y\":{\"dtype\":\"f8\",\"bdata\":\"ieIMAAAAMkBGnFgkSZIsQHx49JEkSSNASf\\u002fpC8MwIEBJ\\u002f+kLwzAgQKhvcwzDMCBAKKktJEmSLECJ4gwAAAAyQA==\"},\"type\":\"scatter\"},{\"line\":{\"color\":\"black\",\"width\":2},\"mode\":\"lines\",\"name\":\"True near-optimal space\",\"x\":{\"dtype\":\"f8\",\"bdata\":\"AAAAAACAIUAPkaLneZ4WQG+9lCRJ0iNA8W5dGIbhLUDZ4yBJkqQsQAAAAAAAgCFA\"},\"y\":{\"dtype\":\"f8\",\"bdata\":\"AAAAAAAAMkBvvZQkSZIsQLheSpIkSSNAeLcuDMMwIEBvvZQkSZIsQAAAAAAAADJA\"},\"type\":\"scatter\"},{\"fill\":\"toself\",\"fillcolor\":\"rgba(8,81,156,0.45)\",\"line\":{\"color\":\"#08519c\"},\"name\":\"Inner approximation I\",\"x\":{\"dtype\":\"f8\",\"bdata\":\"6KPd\\u002f\\u002f9\\u002fIUCAaNTmeZ4WQDTXPiRJ0iNA8W5dGIbhLUA+67JJkqQsQOij3f\\u002f\\u002ffyFA\"},\"y\":{\"dtype\":\"f8\",\"bdata\":\"ieIMAAAAMkBGnFgkSZIsQHx49JEkSSNAeLcuDMMwIEAoqS0kSZIsQIniDAAAADJA\"},\"type\":\"scatter\"},{\"marker\":{\"color\":\"#d62728\",\"size\":14,\"symbol\":\"star\"},\"mode\":\"markers\",\"name\":\"Cost optimum\",\"x\":[11.071428571428571],\"y\":[14.285714285714286],\"type\":\"scatter\"}],                        {\"template\":{\"data\":{\"barpolar\":[{\"marker\":{\"line\":{\"color\":\"white\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"barpolar\"}],\"bar\":[{\"error_x\":{\"color\":\"#2a3f5f\"},\"error_y\":{\"color\":\"#2a3f5f\"},\"marker\":{\"line\":{\"color\":\"white\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"bar\"}],\"carpet\":[{\"aaxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"#C8D4E3\",\"linecolor\":\"#C8D4E3\",\"minorgridcolor\":\"#C8D4E3\",\"startlinecolor\":\"#2a3f5f\"},\"baxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"#C8D4E3\",\"linecolor\":\"#C8D4E3\",\"minorgridcolor\":\"#C8D4E3\",\"startlinecolor\":\"#2a3f5f\"},\"type\":\"carpet\"}],\"choropleth\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"choropleth\"}],\"contourcarpet\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"contourcarpet\"}],\"contour\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"contour\"}],\"heatmap\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"heatmap\"}],\"histogram2dcontour\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"histogram2dcontour\"}],\"histogram2d\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"histogram2d\"}],\"histogram\":[{\"marker\":{\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"histogram\"}],\"mesh3d\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"mesh3d\"}],\"parcoords\":[{\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"parcoords\"}],\"pie\":[{\"automargin\":true,\"type\":\"pie\"}],\"scatter3d\":[{\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatter3d\"}],\"scattercarpet\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattercarpet\"}],\"scattergeo\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattergeo\"}],\"scattergl\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattergl\"}],\"scattermapbox\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattermapbox\"}],\"scattermap\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattermap\"}],\"scatterpolargl\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterpolargl\"}],\"scatterpolar\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterpolar\"}],\"scatter\":[{\"fillpattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2},\"type\":\"scatter\"}],\"scatterternary\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterternary\"}],\"surface\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"surface\"}],\"table\":[{\"cells\":{\"fill\":{\"color\":\"#EBF0F8\"},\"line\":{\"color\":\"white\"}},\"header\":{\"fill\":{\"color\":\"#C8D4E3\"},\"line\":{\"color\":\"white\"}},\"type\":\"table\"}]},\"layout\":{\"annotationdefaults\":{\"arrowcolor\":\"#2a3f5f\",\"arrowhead\":0,\"arrowwidth\":1},\"autotypenumbers\":\"strict\",\"coloraxis\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"colorscale\":{\"diverging\":[[0,\"#8e0152\"],[0.1,\"#c51b7d\"],[0.2,\"#de77ae\"],[0.3,\"#f1b6da\"],[0.4,\"#fde0ef\"],[0.5,\"#f7f7f7\"],[0.6,\"#e6f5d0\"],[0.7,\"#b8e186\"],[0.8,\"#7fbc41\"],[0.9,\"#4d9221\"],[1,\"#276419\"]],\"sequential\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"sequentialminus\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]},\"colorway\":[\"#636efa\",\"#EF553B\",\"#00cc96\",\"#ab63fa\",\"#FFA15A\",\"#19d3f3\",\"#FF6692\",\"#B6E880\",\"#FF97FF\",\"#FECB52\"],\"font\":{\"color\":\"#2a3f5f\"},\"geo\":{\"bgcolor\":\"white\",\"lakecolor\":\"white\",\"landcolor\":\"white\",\"showlakes\":true,\"showland\":true,\"subunitcolor\":\"#C8D4E3\"},\"hoverlabel\":{\"align\":\"left\"},\"hovermode\":\"closest\",\"mapbox\":{\"style\":\"light\"},\"paper_bgcolor\":\"white\",\"plot_bgcolor\":\"white\",\"polar\":{\"angularaxis\":{\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\"},\"bgcolor\":\"white\",\"radialaxis\":{\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\"}},\"scene\":{\"xaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"},\"yaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"},\"zaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"}},\"shapedefaults\":{\"line\":{\"color\":\"#2a3f5f\"}},\"ternary\":{\"aaxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"},\"baxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"},\"bgcolor\":\"white\",\"caxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"}},\"title\":{\"x\":0.05},\"xaxis\":{\"automargin\":true,\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"#EBF0F8\",\"zerolinewidth\":2},\"yaxis\":{\"automargin\":true,\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"#EBF0F8\",\"zerolinewidth\":2}}},\"legend\":{\"orientation\":\"h\",\"y\":-0.15},\"xaxis\":{\"title\":{\"text\":\"PV capacity [GW]\"},\"range\":[-1,31]},\"yaxis\":{\"title\":{\"text\":\"Wind capacity [GW]\"},\"range\":[-1,31]},\"title\":{\"text\":\"Converged after 9 iterations: d = 0.000 GW\"},\"height\":520},                        {\"responsive\": true}                    ).then(function(){\n                            \nvar gd = document.getElementById('a05b6dd6-99de-405a-92ef-284928a3630e');\nvar x = new MutationObserver(function (mutations, observer) {{\n        var display = window.getComputedStyle(gd).display;\n        if (!display || display === 'none') {{\n            console.log([gd, 'removed!']);\n            Plotly.purge(gd);\n            observer.disconnect();\n        }}\n}});\n\n// Listen for the removal of the full notebook cells\nvar notebookContainer = gd.closest('#notebook-container');\nif (notebookContainer) {{\n    x.observe(notebookContainer, {childList: true});\n}}\n\n// Listen for the clearing of the current output cell\nvar outputEl = gd.closest('.output');\nif (outputEl) {{\n    x.observe(outputEl, {childList: true});\n}}\n\n                        })                };            </script>        </div>"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "toy_result = oracle.run(max_iter=50)\n",
    "draw(oracle, f'Converged after {len(toy_result.history)} iterations: d = {toy_result.distance:.3f} GW').show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aad27939",
   "metadata": {},
   "source": [
    "The inner and outer approximations now coincide with the true near-optimal space, and ORACLE **knows** it: the metric certifies that no near-optimal design is further than `tol` from the inner approximation.\n",
    "\n",
    "> **Key ideas**\n",
    ">\n",
    "> - **Inner approximation:** convex hull of the designs found. Everything inside is guaranteed near-optimal.\n",
    "> - **Outer approximation:** intersection of valid cuts. Nothing outside is near-optimal.\n",
    "> - **ORACLE metric:** the largest distance between the two. It bounds the error, says when to stop, and points to where to explore next.\n",
    "\n",
    "---\n",
    "## 2. One application: EnergyScope Switzerland 2050, plug and play\n",
    "\n",
    "ORACLE is not tied to a particular model. As one possible application, and as in the paper [1] but with a simpler monthly model, we now run it in a few lines on the EnergyScope model of Switzerland in 2050 shipped with the library (`infrastructure_ch_2050`: monthly resolution, net-zero CO$_2$ emissions, about 14 000 variables and 17 000 constraints), solved with AMPL and Gurobi.\n",
    "\n",
    "`AmplProblem.from_energyscope(es, technologies=[...])` connects an `Energyscope` object to ORACLE:\n",
    "\n",
    "- the design variables are the installed capacities `F_Mult` of the technologies you list, between their bounds `f_min` and `f_max` from the data;\n",
    "- the cost under-estimator is the annualised investment cost $\\tau \\cdot c_{inv}$ of each technology ($c_{inv}$: investment cost per GW; $\\tau$: annuity factor that turns it into a yearly cost);\n",
    "- the model's integer variables (e.g. the charging or discharging mode of storage) are **relaxed** to continuous variables, because ORACLE needs a convex model, and a warning tells you so. The near-optimal space explored is that of this linear relaxation.\n",
    "\n",
    "We explore four electricity technologies, rooftop PV (`PV_LV`, connected to the low-voltage grid), wind, nuclear and gas combined-cycle plants (`CCGT`); we accept 5 % of extra cost and ask for an accuracy of 0.1 GW. The cell below is self-contained: you can copy it into your own script.\n",
    "\n",
    "> **AMPL license.** If AMPL and Gurobi are not installed and activated yet, pass your license to `Energyscope`, as in [Getting started](../../getting-started/): `Energyscope(model=infrastructure_ch_2050, license_uuid='<your license UUID>', modules=['gurobi'])`.\n",
    ">\n",
    "> **No AMPL or Gurobi license?** Replace the `swiss = ...` line with\n",
    "> ```python\n",
    "> swiss = PyomoProblem.from_energyscope(\n",
    ">     technologies=['PV', 'WIND', 'NUCLEAR', 'CCGT'])\n",
    "> ```\n",
    "> It explores `pyomo_ch`, a monthly Pyomo model of Switzerland solved with the open-source HiGHS solver (about 20 s). **It is a different scenario**, without CO$_2$ limit and with other data (e.g. a single PV technology, `PV`, and at most 5.3 GW of wind). Its cost optimum builds 3.7 GW of nuclear and none of the three others, so the comments below, which describe the AMPL model, do not apply to it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "6f3d33c9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T17:42:32.071550Z",
     "iopub.status.busy": "2026-11-05T17:42:32.071497Z",
     "iopub.status.idle": "2026-11-05T17:43:03.906935Z",
     "shell.execute_reply": "2026-11-05T17:43:03.906479Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Warning: ORACLE needs a convex model: 445 integer/binary variables are relaxed to continuous variables in ORACLE's solves.\n",
      "ORACLE: 4 dimensions, optimal cost 9229.74, budget 9691.23 (eps = 5.00%), tolerance 0.1\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   1: distance 51 | trial point is 42.69 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   2: distance 20 | trial point is 12.63 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   3: distance 7.576 | trial point is 1.006 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   4: distance 6.386 | trial point is 4.034 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   5: distance 2.508 | trial point is 1.935 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   6: distance 2.132 | trial point is 2.018 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   7: distance 1.421 | trial point is 1.117 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   8: distance 1.309 | trial point is 1.028 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration   9: distance 1.131 | trial point is 0.3909 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  10: distance 1.129 | trial point is 0.3493 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  11: distance 0.9113 | trial point is 0.1259 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  12: distance 0.8149 | trial point is 0.7485 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  13: distance 0.5966 | trial point is 0.5898 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  14: distance 0.5761 | trial point is 5.79e-05 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  15: distance 0.499 | trial point is 0.2473 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  16: distance 0.2731 | trial point is 0.2128 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  17: distance 0.2699 | trial point is 0.1132 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  18: distance 0.2552 | trial point is 0.07074 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  19: distance 0.2297 | trial point is 0.1169 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  20: distance 0.2144 | trial point is 0.1483 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  21: distance 0.2035 | trial point is 0.196 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  22: distance 0.1722 | trial point is 0.158 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  23: distance 0.149 | trial point is 0.06854 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  24: distance 0.1261 | trial point is 0.0617 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  25: distance 0.1198 | trial point is 0.08968 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  26: distance 0.1116 | trial point is 0.09558 away from the near-optimal space | cut + cost_cut\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  iteration  27: distance 0.1017 | trial point is 0.003171 away from the near-optimal space | cut + cost_cut\n",
      "  iteration  28: distance 0.09889 <= tolerance 0.1: converged\n"
     ]
    }
   ],
   "source": [
    "import warnings\n",
    "\n",
    "from energyscope.energyscope import Energyscope\n",
    "from energyscope.models import infrastructure_ch_2050\n",
    "from energyscope.oracle import AmplProblem, Oracle, PyomoProblem\n",
    "\n",
    "es = Energyscope(model=infrastructure_ch_2050)  # AMPL, with Gurobi (the default solver)\n",
    "with warnings.catch_warnings(record=True) as caught:  # print ORACLE's warnings as plain lines\n",
    "    warnings.simplefilter('always')\n",
    "    swiss = AmplProblem.from_energyscope(es, technologies=['PV_LV', 'WIND', 'NUCLEAR', 'CCGT'])\n",
    "for warning in caught:\n",
    "    print('Warning:', warning.message)\n",
    "\n",
    "swiss_oracle = Oracle(swiss, eps=0.05, tol=0.1)\n",
    "swiss_result = swiss_oracle.run(max_iter=100)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dda88830",
   "metadata": {},
   "source": [
    "ORACLE converged: the last line of the log shows that the metric fell below the tolerance.\n",
    "\n",
    "> **Solver accuracy matters.** `infrastructure_ch_2050` is badly scaled (its coefficients range from $10^{-7}$ to $10^{7}$), so an LP solver can return a slightly non-optimal solution and still report it as optimal. `AmplProblem` therefore asks Gurobi for its dual simplex method with a tight optimality tolerance; CPLEX and HiGHS through AMPL solve the model itself, but fail on ORACLE's problems for it (CPLEX stops with a numerical error, HiGHS does not finish). If ORACLE warns that a cut \"would remove known near-optimal designs\", the solver's answers are inaccurate. `pyomo_ch` is much better scaled, and HiGHS solves it accurately.\n",
    "\n",
    "### How much can each technology vary?\n",
    "\n",
    "`ranges()` gives, for each technology, the range covered by the inner approximation (**guaranteed** near-optimal) and by the outer approximation (**possibly** near-optimal). The true near-optimal range is in between."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "76b1edb3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T17:43:03.908062Z",
     "iopub.status.busy": "2026-11-05T17:43:03.907991Z",
     "iopub.status.idle": "2026-11-05T17:43:03.916483Z",
     "shell.execute_reply": "2026-11-05T17:43:03.916182Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>optimum</th>\n",
       "      <th>inner_min</th>\n",
       "      <th>inner_max</th>\n",
       "      <th>outer_min</th>\n",
       "      <th>outer_max</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>dimension</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>PV_LV</th>\n",
       "      <td>0.0</td>\n",
       "      <td>0.00</td>\n",
       "      <td>8.31</td>\n",
       "      <td>0.00</td>\n",
       "      <td>8.31</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>WIND</th>\n",
       "      <td>20.0</td>\n",
       "      <td>12.63</td>\n",
       "      <td>20.00</td>\n",
       "      <td>12.63</td>\n",
       "      <td>20.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>NUCLEAR</th>\n",
       "      <td>0.0</td>\n",
       "      <td>0.00</td>\n",
       "      <td>2.35</td>\n",
       "      <td>0.00</td>\n",
       "      <td>2.35</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>CCGT</th>\n",
       "      <td>0.0</td>\n",
       "      <td>0.00</td>\n",
       "      <td>6.57</td>\n",
       "      <td>0.00</td>\n",
       "      <td>6.57</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "           optimum  inner_min  inner_max  outer_min  outer_max\n",
       "dimension                                                     \n",
       "PV_LV          0.0       0.00       8.31       0.00       8.31\n",
       "WIND          20.0      12.63      20.00      12.63      20.00\n",
       "NUCLEAR        0.0       0.00       2.35       0.00       2.35\n",
       "CCGT           0.0       0.00       6.57       0.00       6.57"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "swiss_result.ranges().round(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "d98c4659",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T17:43:03.917560Z",
     "iopub.status.busy": "2026-11-05T17:43:03.917511Z",
     "iopub.status.idle": "2026-11-05T17:43:03.956721Z",
     "shell.execute_reply": "2026-11-05T17:43:03.956245Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": "<div style=\"height:525px; width:100%;\">            <script>if (window.MathJax && window.MathJax.Hub && window.MathJax.Hub.Config) {window.MathJax.Hub.Config({SVG: {font: \"STIX-Web\"}});}</script>                <script>window.PlotlyConfig = {MathJaxConfig: 'local'};</script>\n        <script charset=\"utf-8\" src=\"https://cdn.plot.ly/plotly-3.7.0.min.js\" integrity=\"sha256-jvTGqxNp8AGWEcvNLVuKr+8j5dGe9Yw51LQkmDH+IYA=\" crossorigin=\"anonymous\"></script>                <div id=\"77d70d00-fb02-4a5b-b1b6-b2c0e79a7bdd\" class=\"plotly-graph-div\" style=\"height:100%; width:100%;\"></div>            <script>                window.PLOTLYENV=window.PLOTLYENV || {};                                if (document.getElementById(\"77d70d00-fb02-4a5b-b1b6-b2c0e79a7bdd\")) {                    Plotly.newPlot(                        \"77d70d00-fb02-4a5b-b1b6-b2c0e79a7bdd\",                        [{\"base\":[0.0,12.629995106044417,0.0,0.0],\"marker\":{\"color\":\"#9ecae1\"},\"name\":\"Outer approximation (possible)\",\"orientation\":\"h\",\"x\":{\"dtype\":\"f8\",\"bdata\":\"2vVWowmhIEDCmBuQ4nodQLeHeSML0gJA+ju\\u002fbvRHGkA=\"},\"y\":[\"PV_LV\",\"WIND\",\"NUCLEAR\",\"CCGT\"],\"type\":\"bar\"},{\"base\":[0.0,12.62999511867442,0.0,0.0],\"marker\":{\"color\":\"#08519c\"},\"name\":\"Inner approximation (guaranteed)\",\"orientation\":\"h\",\"width\":0.4,\"x\":{\"dtype\":\"f8\",\"bdata\":\"AYoPowmhIEBqnUKP4nodQGCyKCML0gJAoVtObvRHGkA=\"},\"y\":[\"PV_LV\",\"WIND\",\"NUCLEAR\",\"CCGT\"],\"type\":\"bar\"},{\"marker\":{\"color\":\"#d62728\",\"size\":12,\"symbol\":\"star\"},\"mode\":\"markers\",\"name\":\"Cost optimum\",\"x\":{\"dtype\":\"f8\",\"bdata\":\"AAAAAAAAAAAAAAAAAAA0QAAAAAAAAAAAAAAAAAAAAAA=\"},\"y\":[\"PV_LV\",\"WIND\",\"NUCLEAR\",\"CCGT\"],\"type\":\"scatter\"}],                        {\"template\":{\"data\":{\"barpolar\":[{\"marker\":{\"line\":{\"color\":\"white\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"barpolar\"}],\"bar\":[{\"error_x\":{\"color\":\"#2a3f5f\"},\"error_y\":{\"color\":\"#2a3f5f\"},\"marker\":{\"line\":{\"color\":\"white\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"bar\"}],\"carpet\":[{\"aaxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"#C8D4E3\",\"linecolor\":\"#C8D4E3\",\"minorgridcolor\":\"#C8D4E3\",\"startlinecolor\":\"#2a3f5f\"},\"baxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"#C8D4E3\",\"linecolor\":\"#C8D4E3\",\"minorgridcolor\":\"#C8D4E3\",\"startlinecolor\":\"#2a3f5f\"},\"type\":\"carpet\"}],\"choropleth\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"choropleth\"}],\"contourcarpet\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"contourcarpet\"}],\"contour\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"contour\"}],\"heatmap\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"heatmap\"}],\"histogram2dcontour\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"histogram2dcontour\"}],\"histogram2d\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"histogram2d\"}],\"histogram\":[{\"marker\":{\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"histogram\"}],\"mesh3d\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"mesh3d\"}],\"parcoords\":[{\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"parcoords\"}],\"pie\":[{\"automargin\":true,\"type\":\"pie\"}],\"scatter3d\":[{\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatter3d\"}],\"scattercarpet\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattercarpet\"}],\"scattergeo\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattergeo\"}],\"scattergl\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattergl\"}],\"scattermapbox\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattermapbox\"}],\"scattermap\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattermap\"}],\"scatterpolargl\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterpolargl\"}],\"scatterpolar\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterpolar\"}],\"scatter\":[{\"fillpattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2},\"type\":\"scatter\"}],\"scatterternary\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterternary\"}],\"surface\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"surface\"}],\"table\":[{\"cells\":{\"fill\":{\"color\":\"#EBF0F8\"},\"line\":{\"color\":\"white\"}},\"header\":{\"fill\":{\"color\":\"#C8D4E3\"},\"line\":{\"color\":\"white\"}},\"type\":\"table\"}]},\"layout\":{\"annotationdefaults\":{\"arrowcolor\":\"#2a3f5f\",\"arrowhead\":0,\"arrowwidth\":1},\"autotypenumbers\":\"strict\",\"coloraxis\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"colorscale\":{\"diverging\":[[0,\"#8e0152\"],[0.1,\"#c51b7d\"],[0.2,\"#de77ae\"],[0.3,\"#f1b6da\"],[0.4,\"#fde0ef\"],[0.5,\"#f7f7f7\"],[0.6,\"#e6f5d0\"],[0.7,\"#b8e186\"],[0.8,\"#7fbc41\"],[0.9,\"#4d9221\"],[1,\"#276419\"]],\"sequential\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"sequentialminus\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]},\"colorway\":[\"#636efa\",\"#EF553B\",\"#00cc96\",\"#ab63fa\",\"#FFA15A\",\"#19d3f3\",\"#FF6692\",\"#B6E880\",\"#FF97FF\",\"#FECB52\"],\"font\":{\"color\":\"#2a3f5f\"},\"geo\":{\"bgcolor\":\"white\",\"lakecolor\":\"white\",\"landcolor\":\"white\",\"showlakes\":true,\"showland\":true,\"subunitcolor\":\"#C8D4E3\"},\"hoverlabel\":{\"align\":\"left\"},\"hovermode\":\"closest\",\"mapbox\":{\"style\":\"light\"},\"paper_bgcolor\":\"white\",\"plot_bgcolor\":\"white\",\"polar\":{\"angularaxis\":{\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\"},\"bgcolor\":\"white\",\"radialaxis\":{\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\"}},\"scene\":{\"xaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"},\"yaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"},\"zaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"}},\"shapedefaults\":{\"line\":{\"color\":\"#2a3f5f\"}},\"ternary\":{\"aaxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"},\"baxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"},\"bgcolor\":\"white\",\"caxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"}},\"title\":{\"x\":0.05},\"xaxis\":{\"automargin\":true,\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"#EBF0F8\",\"zerolinewidth\":2},\"yaxis\":{\"automargin\":true,\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"#EBF0F8\",\"zerolinewidth\":2}}},\"legend\":{\"orientation\":\"h\",\"y\":-0.2},\"barmode\":\"overlay\",\"title\":{\"text\":\"Range of each dimension within 5.0% of the optimal cost\"},\"xaxis\":{\"title\":{\"text\":\"Value\"}}},                        {\"responsive\": true}                    ).then(function(){\n                            \nvar gd = document.getElementById('77d70d00-fb02-4a5b-b1b6-b2c0e79a7bdd');\nvar x = new MutationObserver(function (mutations, observer) {{\n        var display = window.getComputedStyle(gd).display;\n        if (!display || display === 'none') {{\n            console.log([gd, 'removed!']);\n            Plotly.purge(gd);\n            observer.disconnect();\n        }}\n}});\n\n// Listen for the removal of the full notebook cells\nvar notebookContainer = gd.closest('#notebook-container');\nif (notebookContainer) {{\n    x.observe(notebookContainer, {childList: true});\n}}\n\n// Listen for the clearing of the current output cell\nvar outputEl = gd.closest('.output');\nif (outputEl) {{\n    x.observe(outputEl, {childList: true});\n}}\n\n                        })                };            </script>        </div>"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "swiss_result.plot_ranges().show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a266844",
   "metadata": {},
   "source": [
    "Within 5 % of the optimal cost:\n",
    "\n",
    "- The cost optimum builds **wind** up to its full potential (20 GW, its upper bound `f_max`) and none of the three other technologies.\n",
    "- **Wind** can nevertheless drop to 12.6 GW.\n",
    "- **Rooftop PV**, **nuclear** and **CCGT**, absent from the optimum, can reach 8.3 GW, 2.4 GW and 6.6 GW respectively.\n",
    "\n",
    "The inner and outer ranges agree within the tolerance, as they must once ORACLE has converged. The converse is not true: matching ranges only show that the bounding box of the near-optimal space is found, which can happen long before the whole space is mapped. Only the ORACLE metric (the last line of the log, or `swiss_result.converged`) certifies that.\n",
    "\n",
    "### Trade-offs between technologies\n",
    "\n",
    "Ranges hide the interactions between technologies: a value that is near-optimal on its own may only be near-optimal in combination with specific values of the others. Two-dimensional projections of the near-optimal space show these trade-offs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "87cddba5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T17:43:03.957761Z",
     "iopub.status.busy": "2026-11-05T17:43:03.957704Z",
     "iopub.status.idle": "2026-11-05T17:43:04.014034Z",
     "shell.execute_reply": "2026-11-05T17:43:04.013691Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": "<div style=\"height:525px; width:100%;\">            <script>if (window.MathJax && window.MathJax.Hub && window.MathJax.Hub.Config) {window.MathJax.Hub.Config({SVG: {font: \"STIX-Web\"}});}</script>                <script>window.PlotlyConfig = {MathJaxConfig: 'local'};</script>\n        <script charset=\"utf-8\" src=\"https://cdn.plot.ly/plotly-3.7.0.min.js\" integrity=\"sha256-jvTGqxNp8AGWEcvNLVuKr+8j5dGe9Yw51LQkmDH+IYA=\" crossorigin=\"anonymous\"></script>                <div id=\"2c1c3fd5-5576-4dcd-af3f-1ad92b8605b4\" class=\"plotly-graph-div\" style=\"height:100%; width:100%;\"></div>            <script>                window.PLOTLYENV=window.PLOTLYENV || {};                                if (document.getElementById(\"2c1c3fd5-5576-4dcd-af3f-1ad92b8605b4\")) {                    Plotly.newPlot(                        \"2c1c3fd5-5576-4dcd-af3f-1ad92b8605b4\",                        [{\"fill\":\"toself\",\"fillcolor\":\"rgba(158,202,225,0.35)\",\"line\":{\"color\":\"#9ecae1\",\"dash\":\"dash\"},\"mode\":\"lines\",\"name\":\"Outer approximation\",\"x\":{\"dtype\":\"f8\",\"bdata\":\"tDLyt45CKUAAAAAAAAA0QAAAAAAAADRAeZOZkK\\u002fzM0AMcPqhGgIxQLQy8reOQilAtDLyt45CKUA=\"},\"y\":{\"dtype\":\"f8\",\"bdata\":\"AAAAAAAAAIAAAAAAAAAAgKk8v270RxpAqTy\\u002fbvRHGkB3xExicOAPQA9CZP\\u002fXRlQ\\u002fAAAAAAAAAIA=\"},\"type\":\"scatter\"},{\"fill\":\"toself\",\"fillcolor\":\"rgba(8,81,156,0.45)\",\"line\":{\"color\":\"#08519c\"},\"mode\":\"lines\",\"name\":\"Inner approximation\",\"x\":{\"dtype\":\"f8\",\"bdata\":\"XrBeuI5CKUAAAAAAAAA0QAAAAAAAADRAXrBeuI5CKUA=\"},\"y\":{\"dtype\":\"f8\",\"bdata\":\"AAAAAAAAAAAAAAAAAAAAAH9dTm70RxpAAAAAAAAAAAA=\"},\"type\":\"scatter\"},{\"marker\":{\"color\":\"#08519c\",\"line\":{\"color\":\"white\",\"width\":1},\"size\":6},\"mode\":\"markers\",\"name\":\"Near-optimal designs found\",\"x\":{\"dtype\":\"f8\",\"bdata\":\"AAAAAAAANEAAAAAAAAA0QEuxXriOQilAAAAAAAAANED1Lg5KkHYwQFeOQYZkIS1A79\\u002fJINlnL0BZPJU8vX8wQAAAAAAAADRApX2znEuKMUDi9\\u002fJflaYzQEhom+Iz2ytAu1dRdSyPMEAl3W4bLDQzQJdEnDT8\\u002fzNAAAAAAAAANECsurGdiMkzQAAAAAAAADRAhxieLtDWMECYYytVi9QyQGroJsZUtitAoI\\u002f6FCNDM0DhDn4MkNczQAAAAAAAADRAAAAAAAAANECH3LuUFtEuQI9sGHygbSxAJmY2TYYnK0A=\"},\"y\":{\"dtype\":\"f8\",\"bdata\":\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAoVtObvRHGkAAAAAAAAAAAAAAAAAAAAAA8C3r\\u002focSBUAAAAAAAAAAALuOEJzuyxFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFuih9skq+j8Lp1gXk5EEQAAAAAAAAAAAhuWVSulKEkAGbNq6mlb6P6YlA0PbLRlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAz7lxqGuhB0DwGW+2Dif2P9QrWjUB3gFAt1nDWCP1FkAAAAAAAAAAAMKg8Mr2PdQ\\u002fAAAAAAAAAAA=\"},\"type\":\"scatter\"},{\"marker\":{\"color\":\"#d62728\",\"size\":14,\"symbol\":\"star\"},\"mode\":\"markers\",\"name\":\"Cost optimum\",\"x\":[20.0],\"y\":[0.0],\"type\":\"scatter\"}],                        {\"template\":{\"data\":{\"barpolar\":[{\"marker\":{\"line\":{\"color\":\"white\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"barpolar\"}],\"bar\":[{\"error_x\":{\"color\":\"#2a3f5f\"},\"error_y\":{\"color\":\"#2a3f5f\"},\"marker\":{\"line\":{\"color\":\"white\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"bar\"}],\"carpet\":[{\"aaxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"#C8D4E3\",\"linecolor\":\"#C8D4E3\",\"minorgridcolor\":\"#C8D4E3\",\"startlinecolor\":\"#2a3f5f\"},\"baxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"#C8D4E3\",\"linecolor\":\"#C8D4E3\",\"minorgridcolor\":\"#C8D4E3\",\"startlinecolor\":\"#2a3f5f\"},\"type\":\"carpet\"}],\"choropleth\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"choropleth\"}],\"contourcarpet\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"contourcarpet\"}],\"contour\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"contour\"}],\"heatmap\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"heatmap\"}],\"histogram2dcontour\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"histogram2dcontour\"}],\"histogram2d\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"histogram2d\"}],\"histogram\":[{\"marker\":{\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"histogram\"}],\"mesh3d\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"mesh3d\"}],\"parcoords\":[{\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"parcoords\"}],\"pie\":[{\"automargin\":true,\"type\":\"pie\"}],\"scatter3d\":[{\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatter3d\"}],\"scattercarpet\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattercarpet\"}],\"scattergeo\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattergeo\"}],\"scattergl\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattergl\"}],\"scattermapbox\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattermapbox\"}],\"scattermap\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattermap\"}],\"scatterpolargl\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterpolargl\"}],\"scatterpolar\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterpolar\"}],\"scatter\":[{\"fillpattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2},\"type\":\"scatter\"}],\"scatterternary\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterternary\"}],\"surface\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"surface\"}],\"table\":[{\"cells\":{\"fill\":{\"color\":\"#EBF0F8\"},\"line\":{\"color\":\"white\"}},\"header\":{\"fill\":{\"color\":\"#C8D4E3\"},\"line\":{\"color\":\"white\"}},\"type\":\"table\"}]},\"layout\":{\"annotationdefaults\":{\"arrowcolor\":\"#2a3f5f\",\"arrowhead\":0,\"arrowwidth\":1},\"autotypenumbers\":\"strict\",\"coloraxis\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"colorscale\":{\"diverging\":[[0,\"#8e0152\"],[0.1,\"#c51b7d\"],[0.2,\"#de77ae\"],[0.3,\"#f1b6da\"],[0.4,\"#fde0ef\"],[0.5,\"#f7f7f7\"],[0.6,\"#e6f5d0\"],[0.7,\"#b8e186\"],[0.8,\"#7fbc41\"],[0.9,\"#4d9221\"],[1,\"#276419\"]],\"sequential\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"sequentialminus\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]},\"colorway\":[\"#636efa\",\"#EF553B\",\"#00cc96\",\"#ab63fa\",\"#FFA15A\",\"#19d3f3\",\"#FF6692\",\"#B6E880\",\"#FF97FF\",\"#FECB52\"],\"font\":{\"color\":\"#2a3f5f\"},\"geo\":{\"bgcolor\":\"white\",\"lakecolor\":\"white\",\"landcolor\":\"white\",\"showlakes\":true,\"showland\":true,\"subunitcolor\":\"#C8D4E3\"},\"hoverlabel\":{\"align\":\"left\"},\"hovermode\":\"closest\",\"mapbox\":{\"style\":\"light\"},\"paper_bgcolor\":\"white\",\"plot_bgcolor\":\"white\",\"polar\":{\"angularaxis\":{\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\"},\"bgcolor\":\"white\",\"radialaxis\":{\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\"}},\"scene\":{\"xaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"},\"yaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"},\"zaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"}},\"shapedefaults\":{\"line\":{\"color\":\"#2a3f5f\"}},\"ternary\":{\"aaxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"},\"baxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"},\"bgcolor\":\"white\",\"caxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"}},\"title\":{\"x\":0.05},\"xaxis\":{\"automargin\":true,\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"#EBF0F8\",\"zerolinewidth\":2},\"yaxis\":{\"automargin\":true,\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"#EBF0F8\",\"zerolinewidth\":2}}},\"legend\":{\"orientation\":\"h\",\"y\":-0.2},\"title\":{\"text\":\"Near-optimal space (eps = 5.0%): CCGT vs WIND\"},\"xaxis\":{\"title\":{\"text\":\"WIND\"}},\"yaxis\":{\"title\":{\"text\":\"CCGT\"}}},                        {\"responsive\": true}                    ).then(function(){\n                            \nvar gd = document.getElementById('2c1c3fd5-5576-4dcd-af3f-1ad92b8605b4');\nvar x = new MutationObserver(function (mutations, observer) {{\n        var display = window.getComputedStyle(gd).display;\n        if (!display || display === 'none') {{\n            console.log([gd, 'removed!']);\n            Plotly.purge(gd);\n            observer.disconnect();\n        }}\n}});\n\n// Listen for the removal of the full notebook cells\nvar notebookContainer = gd.closest('#notebook-container');\nif (notebookContainer) {{\n    x.observe(notebookContainer, {childList: true});\n}}\n\n// Listen for the clearing of the current output cell\nvar outputEl = gd.closest('.output');\nif (outputEl) {{\n    x.observe(outputEl, {childList: true});\n}}\n\n                        })                };            </script>        </div>"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "swiss_result.plot_projection('WIND', 'CCGT').show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cdc5cc1a",
   "metadata": {},
   "source": [
    "The projection is almost a triangle. The full 6.6 GW of CCGT are near-optimal only when wind is fully built (20 GW), and no CCGT at all fits when wind is at its minimum (12.6 GW): giving up wind and building gas plants use up the same 5 % budget, so you can do one, the other, or a bit of both. This picture is the \"shadow\" of the 4-dimensional near-optimal space: a point inside it is near-optimal for *some* values of the two other technologies, not for all of them.\n",
    "\n",
    "---\n",
    "## 3. Use the near-optimal space\n",
    "\n",
    "Once ORACLE has converged, the near-optimal space is known, and using it needs no further model solve:\n",
    "\n",
    "- `swiss_result.contains(design, 'inner')` tells whether a design is **guaranteed** near-optimal; outside the outer approximation (`'outer'`), it is **certainly not** near-optimal;\n",
    "- `swiss_result.sample(n)` draws designs approximately uniformly from the inner approximation (with a hit-and-run random walk): thousands of guaranteed near-optimal alternatives, for free.\n",
    "\n",
    "`swiss_oracle.design(z)` then solves the full model with the capacities $z$ pinned, at minimum cost, and returns a regular EnergyScope `Result`, so all the usual post-processing and plotting functions work on it.\n",
    "\n",
    "Let us first check a design that the ranges alone would accept: the least wind together with the most CCGT. Then we draw 1000 alternatives, pick the one with the least wind, and rebuild its full energy system."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "cd568a0b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T17:43:04.015147Z",
     "iopub.status.busy": "2026-11-05T17:43:04.015091Z",
     "iopub.status.idle": "2026-11-05T17:43:04.658231Z",
     "shell.execute_reply": "2026-11-05T17:43:04.657767Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Least wind and most CCGT possibly near-optimal: False\n",
      "Distance to the inner approximation: 3.47 GW\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Design with the least wind [GW]: {'PV_LV': 0.36, 'WIND': 13.46, 'NUCLEAR': 0.01, 'CCGT': 0.37}\n",
      "Total cost: 9678 MCHF/year vs. 9230 MCHF/year at the optimum (+4.9%, budget +5%)\n"
     ]
    }
   ],
   "source": [
    "# Ranges hide interactions: the least wind and the most CCGT are each near-optimal, but not together\n",
    "ranges = swiss_result.ranges()\n",
    "both = swiss_result.optimum.copy()\n",
    "both['WIND'], both['CCGT'] = ranges.loc['WIND', 'inner_min'], ranges.loc['CCGT', 'inner_max']\n",
    "print('Least wind and most CCGT possibly near-optimal:', swiss_result.contains(both, 'outer'))\n",
    "print(f'Distance to the inner approximation: {swiss_result.distance_to_inner(both):.2f} GW')\n",
    "\n",
    "samples = swiss_result.sample(1000, seed=42)\n",
    "low_wind = samples.loc[samples['WIND'].idxmin()]\n",
    "print('Design with the least wind [GW]:', low_wind.round(2).to_dict())\n",
    "\n",
    "alternative = swiss_oracle.design(low_wind)\n",
    "optimum = swiss_oracle.design(swiss_result.optimum)\n",
    "cost = alternative.variables['TotalCost']['TotalCost'].iloc[0]\n",
    "print(f'Total cost: {cost:.0f} MCHF/year vs. {swiss_result.optimal_cost:.0f} MCHF/year at the optimum '\n",
    "      f'(+{cost / swiss_result.optimal_cost - 1:.1%}, budget +{swiss_result.eps:.0%})')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "48fd83d3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-05T17:43:04.659363Z",
     "iopub.status.busy": "2026-11-05T17:43:04.659307Z",
     "iopub.status.idle": "2026-11-05T17:43:04.710306Z",
     "shell.execute_reply": "2026-11-05T17:43:04.709963Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": "<div style=\"height:525px; width:100%;\">            <script>if (window.MathJax && window.MathJax.Hub && window.MathJax.Hub.Config) {window.MathJax.Hub.Config({SVG: {font: \"STIX-Web\"}});}</script>                <script>window.PlotlyConfig = {MathJaxConfig: 'local'};</script>\n        <script charset=\"utf-8\" src=\"https://cdn.plot.ly/plotly-3.7.0.min.js\" integrity=\"sha256-jvTGqxNp8AGWEcvNLVuKr+8j5dGe9Yw51LQkmDH+IYA=\" crossorigin=\"anonymous\"></script>                <div id=\"67f1e962-9272-4687-81bb-9d8a11c754e8\" class=\"plotly-graph-div\" style=\"height:100%; width:100%;\"></div>            <script>                window.PLOTLYENV=window.PLOTLYENV || {};                                if (document.getElementById(\"67f1e962-9272-4687-81bb-9d8a11c754e8\")) {                    Plotly.newPlot(                        \"67f1e962-9272-4687-81bb-9d8a11c754e8\",                        [{\"alignmentgroup\":\"True\",\"hovertemplate\":\"=Cost optimum\\u003cbr\\u003eTechnology=%{x}\\u003cbr\\u003eTWh\\u002fyear=%{y}\\u003cextra\\u003e\\u003c\\u002fextra\\u003e\",\"legendgroup\":\"Cost optimum\",\"marker\":{\"color\":\"#636efa\",\"pattern\":{\"shape\":\"\"}},\"name\":\"Cost optimum\",\"offsetgroup\":\"Cost optimum\",\"orientation\":\"v\",\"showlegend\":true,\"textposition\":\"auto\",\"x\":[\"CCGT_CC\",\"HYDRO_DAM\",\"HYDRO_GAS\",\"HYDRO_RIVER\",\"IND_COGEN_WASTE\",\"NEW_HYDRO_DAM\",\"NEW_HYDRO_RIVER\",\"NUCLEAR\",\"PV_EHV\",\"PV_LV\",\"WIND\"],\"xaxis\":\"x\",\"y\":{\"dtype\":\"f8\",\"bdata\":\"j8L1KFyPFUAUrkfhepQwQOF6FK5H4co\\u002fH4XrUbgeMEA9CtejcD32P83MzMzMzOw\\u002f4XoUrkfhDEAAAAAAAAAAAJqZmZmZmQFAAAAAAAAAAABmZmZmZiZEQA==\"},\"yaxis\":\"y\",\"type\":\"bar\"},{\"alignmentgroup\":\"True\",\"hovertemplate\":\"=Least-wind alternative\\u003cbr\\u003eTechnology=%{x}\\u003cbr\\u003eTWh\\u002fyear=%{y}\\u003cextra\\u003e\\u003c\\u002fextra\\u003e\",\"legendgroup\":\"Least-wind alternative\",\"marker\":{\"color\":\"#EF553B\",\"pattern\":{\"shape\":\"\"}},\"name\":\"Least-wind alternative\",\"offsetgroup\":\"Least-wind alternative\",\"orientation\":\"v\",\"showlegend\":true,\"textposition\":\"auto\",\"x\":[\"CCGT_CC\",\"HYDRO_DAM\",\"HYDRO_GAS\",\"HYDRO_RIVER\",\"IND_COGEN_WASTE\",\"NEW_HYDRO_DAM\",\"NEW_HYDRO_RIVER\",\"NUCLEAR\",\"PV_EHV\",\"PV_LV\",\"WIND\"],\"xaxis\":\"x\",\"y\":{\"dtype\":\"f8\",\"bdata\":\"9ihcj8L1GkAUrkfhepQwQOF6FK5H4co\\u002fH4XrUbgeMEBmZmZmZmb2P83MzMzMzOw\\u002f4XoUrkfhDEAK16NwPQq3P83MzMzMTCdACtejcD0K1z\\u002fhehSuRyE7QA==\"},\"yaxis\":\"y\",\"type\":\"bar\"}],                        {\"template\":{\"data\":{\"barpolar\":[{\"marker\":{\"line\":{\"color\":\"white\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"barpolar\"}],\"bar\":[{\"error_x\":{\"color\":\"#2a3f5f\"},\"error_y\":{\"color\":\"#2a3f5f\"},\"marker\":{\"line\":{\"color\":\"white\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"bar\"}],\"carpet\":[{\"aaxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"#C8D4E3\",\"linecolor\":\"#C8D4E3\",\"minorgridcolor\":\"#C8D4E3\",\"startlinecolor\":\"#2a3f5f\"},\"baxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"#C8D4E3\",\"linecolor\":\"#C8D4E3\",\"minorgridcolor\":\"#C8D4E3\",\"startlinecolor\":\"#2a3f5f\"},\"type\":\"carpet\"}],\"choropleth\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"choropleth\"}],\"contourcarpet\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"contourcarpet\"}],\"contour\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"contour\"}],\"heatmap\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"heatmap\"}],\"histogram2dcontour\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"histogram2dcontour\"}],\"histogram2d\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"histogram2d\"}],\"histogram\":[{\"marker\":{\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"histogram\"}],\"mesh3d\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"type\":\"mesh3d\"}],\"parcoords\":[{\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"parcoords\"}],\"pie\":[{\"automargin\":true,\"type\":\"pie\"}],\"scatter3d\":[{\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatter3d\"}],\"scattercarpet\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattercarpet\"}],\"scattergeo\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattergeo\"}],\"scattergl\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattergl\"}],\"scattermapbox\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattermapbox\"}],\"scattermap\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scattermap\"}],\"scatterpolargl\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterpolargl\"}],\"scatterpolar\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterpolar\"}],\"scatter\":[{\"fillpattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2},\"type\":\"scatter\"}],\"scatterternary\":[{\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"type\":\"scatterternary\"}],\"surface\":[{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"type\":\"surface\"}],\"table\":[{\"cells\":{\"fill\":{\"color\":\"#EBF0F8\"},\"line\":{\"color\":\"white\"}},\"header\":{\"fill\":{\"color\":\"#C8D4E3\"},\"line\":{\"color\":\"white\"}},\"type\":\"table\"}]},\"layout\":{\"annotationdefaults\":{\"arrowcolor\":\"#2a3f5f\",\"arrowhead\":0,\"arrowwidth\":1},\"autotypenumbers\":\"strict\",\"coloraxis\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"colorscale\":{\"diverging\":[[0,\"#8e0152\"],[0.1,\"#c51b7d\"],[0.2,\"#de77ae\"],[0.3,\"#f1b6da\"],[0.4,\"#fde0ef\"],[0.5,\"#f7f7f7\"],[0.6,\"#e6f5d0\"],[0.7,\"#b8e186\"],[0.8,\"#7fbc41\"],[0.9,\"#4d9221\"],[1,\"#276419\"]],\"sequential\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"sequentialminus\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]},\"colorway\":[\"#636efa\",\"#EF553B\",\"#00cc96\",\"#ab63fa\",\"#FFA15A\",\"#19d3f3\",\"#FF6692\",\"#B6E880\",\"#FF97FF\",\"#FECB52\"],\"font\":{\"color\":\"#2a3f5f\"},\"geo\":{\"bgcolor\":\"white\",\"lakecolor\":\"white\",\"landcolor\":\"white\",\"showlakes\":true,\"showland\":true,\"subunitcolor\":\"#C8D4E3\"},\"hoverlabel\":{\"align\":\"left\"},\"hovermode\":\"closest\",\"mapbox\":{\"style\":\"light\"},\"paper_bgcolor\":\"white\",\"plot_bgcolor\":\"white\",\"polar\":{\"angularaxis\":{\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\"},\"bgcolor\":\"white\",\"radialaxis\":{\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\"}},\"scene\":{\"xaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"},\"yaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"},\"zaxis\":{\"backgroundcolor\":\"white\",\"gridcolor\":\"#DFE8F3\",\"gridwidth\":2,\"linecolor\":\"#EBF0F8\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"#EBF0F8\"}},\"shapedefaults\":{\"line\":{\"color\":\"#2a3f5f\"}},\"ternary\":{\"aaxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"},\"baxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"},\"bgcolor\":\"white\",\"caxis\":{\"gridcolor\":\"#DFE8F3\",\"linecolor\":\"#A2B1C6\",\"ticks\":\"\"}},\"title\":{\"x\":0.05},\"xaxis\":{\"automargin\":true,\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"#EBF0F8\",\"zerolinewidth\":2},\"yaxis\":{\"automargin\":true,\"gridcolor\":\"#EBF0F8\",\"linecolor\":\"#EBF0F8\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"#EBF0F8\",\"zerolinewidth\":2}}},\"xaxis\":{\"anchor\":\"y\",\"domain\":[0.0,1.0],\"title\":{\"text\":\"Technology\"}},\"yaxis\":{\"anchor\":\"x\",\"domain\":[0.0,1.0],\"title\":{\"text\":\"TWh\\u002fyear\"}},\"legend\":{\"title\":{\"text\":\"\"},\"tracegroupgap\":0,\"orientation\":\"h\",\"yanchor\":\"bottom\",\"y\":1.02},\"title\":{\"text\":\"Annual electricity production [TWh\\u002fyear]\"},\"barmode\":\"group\"},                        {\"responsive\": true}                    ).then(function(){\n                            \nvar gd = document.getElementById('67f1e962-9272-4687-81bb-9d8a11c754e8');\nvar x = new MutationObserver(function (mutations, observer) {{\n        var display = window.getComputedStyle(gd).display;\n        if (!display || display === 'none') {{\n            console.log([gd, 'removed!']);\n            Plotly.purge(gd);\n            observer.disconnect();\n        }}\n}});\n\n// Listen for the removal of the full notebook cells\nvar notebookContainer = gd.closest('#notebook-container');\nif (notebookContainer) {{\n    x.observe(notebookContainer, {childList: true});\n}}\n\n// Listen for the clearing of the current output cell\nvar outputEl = gd.closest('.output');\nif (outputEl) {{\n    x.observe(outputEl, {childList: true});\n}}\n\n                        })                };            </script>        </div>"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Change in production [TWh/year]: {'WIND': -13.2, 'NUCLEAR': 0.1, 'PV_LV': 0.4, 'CCGT_CC': 1.4, 'PV_EHV': 9.4}\n",
      "Electricity used by the rest of the system: 41.1 -> 39.3 TWh/year\n"
     ]
    }
   ],
   "source": [
    "def electricity_production(result):\n",
    "    # Annual electricity produced (+) or consumed (-) by each technology [TWh/year], all voltage levels together\n",
    "    production = result.variables['Annual_Prod']['Annual_Prod']  # GWh/year of each technology's main output\n",
    "    layers = result.parameters['layers_in_out']['layers_in_out'].unstack()\n",
    "    to_electricity = layers.filter(like='ELECTRICITY').sum(axis=1)\n",
    "    return production.mul(to_electricity.reindex(production.index).fillna(0)) / 1000\n",
    "\n",
    "\n",
    "electricity = pd.DataFrame({'Cost optimum': electricity_production(optimum),\n",
    "                            'Least-wind alternative': electricity_production(alternative)})\n",
    "producers = electricity[(electricity > 0.05).any(axis=1)].round(2)\n",
    "fig = px.bar(producers, barmode='group', title='Annual electricity production [TWh/year]',\n",
    "             labels={'index': 'Technology', 'value': 'TWh/year', 'variable': ''})\n",
    "fig.update_layout(template='plotly_white', legend=dict(orientation='h', yanchor='bottom', y=1.02))\n",
    "fig.show()\n",
    "\n",
    "change = (producers['Least-wind alternative'] - producers['Cost optimum']).round(1)\n",
    "print('Change in production [TWh/year]:', change[change.abs() >= 0.1].sort_values().to_dict())\n",
    "used = -electricity.clip(upper=0).sum()  # electricity used by heat pumps, electric mobility, industry...\n",
    "print(f\"Electricity used by the rest of the system: {used['Cost optimum']:.1f} -> \"\n",
    "      f\"{used['Least-wind alternative']:.1f} TWh/year\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "724d820b",
   "metadata": {},
   "source": [
    "The whole energy system has been re-optimised around the chosen capacities, and its cost stays within the 5 % budget. With 6.5 GW less wind, about 13 TWh/year of wind power are missing. They are replaced mostly by **alpine PV** (`PV_EHV`: large PV parks in the Swiss Alps, connected to the extra-high-voltage grid), a technology we did not explore, and partly by gas plants with carbon capture (`CCGT_CC`). The rest of the system also uses less electricity, mainly in the heat pumps of district heating networks. Emissions are the same: this scenario is net zero by constraint.\n",
    "\n",
    "Two lessons:\n",
    "\n",
    "- This is what ORACLE is made for. Once the near-optimal space is mapped, you can screen thousands of alternatives for criteria the model does not optimise (land use, acceptance, ...) and pick the ones you prefer, knowing that they cost at most 5 % more than the optimum.\n",
    "- The choice of design variables matters. Alpine PV turned out to be the main substitute for wind, so it deserves to be explored as a dimension of its own.\n",
    "\n",
    "---\n",
    "## Going further\n",
    "\n",
    "- **More dimensions:** just list more technologies. Above 6 dimensions, this implementation computes the metric by solving the bilevel problem of the paper [1] as a mixed-integer linear program (`metric='milp'`) instead of enumerating vertices. This MILP becomes the expensive part of ORACLE as the number of dimensions and of designs found grows; `mip_rel_gap` and `mip_time_limit` trade accuracy for speed (convergence is always judged on the certified bound).\n",
    "- **Units:** the metric measures the largest deviation of any single design variable, in its own units. If your dimensions have different units or magnitudes (e.g. GW of generation and GWh of storage), use `Oracle(..., scale='extent')`. ORACLE warns you when the bound ranges differ by more than a factor 10.\n",
    "- **Options:** `tol` sets the accuracy, `max_iter` the iteration budget (`run()` can be called again to continue), and `cost_cut=False` uses only the separating cut.\n",
    "- **Any other energy system model:** ORACLE is not specific to EnergyScope. Any linear Pyomo model works as in part 1, with `PyomoProblem(model, design=..., cost=...)`; any linear AMPL model with `AmplProblem(ampl, dimensions, design=..., cost=...)`. For other modelling frameworks, implement the four methods of `NearOptimalProblem` (cost optimum, nearest near-optimal design, minimum cost of a design, extreme design), or start from the authors' reference code [2].\n",
    "\n",
    "**Limitations.** ORACLE needs a convex model: integer decisions are relaxed, and the near-optimal space of a mixed-integer model is not convex. Each iteration solves the full model once or twice, plus the metric, whose cost grows with the number of dimensions. And the space is explored in the chosen design variables only: two systems with the same design can still differ in their operation.\n",
    "\n",
    "### References\n",
    "\n",
    "[1] E. M. Turan, S. Moret, A. Bardow (2026). *ORACLE: A rigorous metric and method to explore all near-optimal designs for energy systems*. Computers & Chemical Engineering 210, 109630. [doi:10.1016/j.compchemeng.2026.109630](https://doi.org/10.1016/j.compchemeng.2026.109630). Open access (CC BY-NC-ND 4.0); preprint: [arXiv:2509.26452](https://arxiv.org/abs/2509.26452).\n",
    "\n",
    "[2] Reference implementation of ORACLE, © 2026 ETH Zurich, MIT license: [gitlab.ethz.ch/epse/systems-design-public/oracle-metric-and-method](https://gitlab.ethz.ch/epse/systems-design-public/oracle-metric-and-method).\n",
    "\n",
    "API reference of the implementation used in this tutorial: [`energyscope.oracle`](../../reference/oracle/).\n",
    "\n",
    "### How to cite\n",
    "\n",
    "ORACLE is the work of Evren M. Turan, Stefano Moret and André Bardow. If you use it, in EnergyScope or in any other model, please cite their paper [1]:\n",
    "\n",
    "```bibtex\n",
    "@article{turan2026oracle,\n",
    "  author  = {Turan, Evren M. and Moret, Stefano\n",
    "             and Bardow, Andr{\\'e}},\n",
    "  title   = {{ORACLE}: A rigorous metric and method\n",
    "             to explore all near-optimal designs\n",
    "             for energy systems},\n",
    "  journal = {Computers \\& Chemical Engineering},\n",
    "  volume  = {210},\n",
    "  pages   = {109630},\n",
    "  year    = {2026},\n",
    "  doi     = {10.1016/j.compchemeng.2026.109630}\n",
    "}\n",
    "```\n",
    "\n",
    "The implementation in `energyscope.oracle` used in this tutorial is adapted from the authors' reference code [2]."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}