Skip to content

plots ¤

Plots of ORACLE results (plotly).

Functions:

  • plot_convergence –

    The ORACLE metric (largest distance between the inner and outer approximations) at each iteration.

  • plot_projection –

    Both approximations of the near-optimal space, projected on two dimensions.

  • plot_ranges –

    Near-optimal range of each dimension: guaranteed (inner approximation) and possible (outer approximation).

  • projected_outer –

    Outline of the projection of {z : A z <= b} on dimensions ix and iy.

Attributes:

INNER_COLOR module-attribute ¤

INNER_COLOR = '#08519c'

OPTIMUM_COLOR module-attribute ¤

OPTIMUM_COLOR = '#d62728'

OUTER_COLOR module-attribute ¤

OUTER_COLOR = '#9ecae1'

TRIAL_COLOR module-attribute ¤

TRIAL_COLOR = '#ff7f0e'

plot_convergence ¤

plot_convergence(
    result: OracleResult,
    log_y: bool = True,
    title: Optional[str] = None,
) -> Figure

The ORACLE metric (largest distance between the inner and outer approximations) at each iteration.

The line is the certified upper bound on the metric. When the metric MILP stops at its optimality gap, the distance of the trial point actually explored (a lower bound) is shown as well.

Parameters:

  • result ¤

    (OracleResult) –

    An OracleResult with at least one iteration.

  • log_y ¤

    (bool, default: True ) –

    Logarithmic vertical axis (switched off automatically if the metric reaches 0).

  • title ¤

    (Optional[str], default: None ) –

    Figure title.

Source code in src/energyscope/oracle/plots.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def plot_convergence(result: 'OracleResult', log_y: bool = True, title: Optional[str] = None) -> go.Figure:
    """The ORACLE metric (largest distance between the inner and outer approximations) at each iteration.

    The line is the certified upper bound on the metric. When the metric MILP stops at its optimality gap, the
    distance of the trial point actually explored (a lower bound) is shown as well.

    Args:
        result: An [`OracleResult`][energyscope.oracle.algorithm.OracleResult] with at least one iteration.
        log_y: Logarithmic vertical axis (switched off automatically if the metric reaches 0).
        title: Figure title.
    """
    history = result.history
    if history.empty:
        raise ValueError('No iteration to plot yet: call Oracle.step() or Oracle.run() first.')
    fig = go.Figure(go.Scatter(x=history['iteration'], y=history['distance_bound'], mode='lines+markers',
                               name='ORACLE metric', line=dict(color=INNER_COLOR)))
    if np.any(history['distance_bound'] > history['distance'] * (1 + 1e-6) + 1e-9):
        fig.add_trace(go.Scatter(x=history['iteration'], y=history['distance'], mode='markers',
                                 name='Distance of the trial point', marker=dict(color=TRIAL_COLOR, size=6)))
    fig.add_hline(y=result.tol, line=dict(color=OPTIMUM_COLOR, dash='dot'), annotation_text='tolerance',
                  annotation_position='top right')
    log_y = log_y and bool(np.all(history['distance'] > 0))
    fig.update_layout(template='plotly_white', title=title or 'Convergence of ORACLE', xaxis_title='Iteration',
                      yaxis_title='Max. distance between approximations', yaxis_type='log' if log_y else 'linear')
    return fig

plot_projection ¤

plot_projection(
    result: OracleResult,
    x: str,
    y: str,
    show_points: bool = True,
    show_outer: bool = True,
    trial_point: Optional[dict] = None,
    n_directions: int = 120,
    title: Optional[str] = None,
) -> Figure

Both approximations of the near-optimal space, projected on two dimensions.

The true near-optimal space lies between the dark (inner) and the light (outer) region.

Parameters:

  • result ¤

    (OracleResult) –
  • x ¤

    (str) –

    Dimension on the horizontal axis.

  • y ¤

    (str) –

    Dimension on the vertical axis.

  • show_points ¤

    (bool, default: True ) –

    Show the near-optimal designs found.

  • show_outer ¤

    (bool, default: True ) –

    Show the outer approximation.

  • trial_point ¤

    (Optional[dict], default: None ) –

    Optional design to highlight, as a dict, a pandas Series or an array with one value per dimension (e.g. the point returned by Oracle.furthest_point).

  • n_directions ¤

    (int, default: 120 ) –

    Number of directions used to trace the outer projection in more than 2 dimensions.

  • title ¤

    (Optional[str], default: None ) –

    Figure title.

Source code in src/energyscope/oracle/plots.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def plot_projection(result: 'OracleResult', x: str, y: str, show_points: bool = True, show_outer: bool = True,
                    trial_point: Optional[dict] = None, n_directions: int = 120, title: Optional[str] = None
                    ) -> go.Figure:
    """Both approximations of the near-optimal space, projected on two dimensions.

    The true near-optimal space lies between the dark (inner) and the light (outer) region.

    Args:
        result: An [`OracleResult`][energyscope.oracle.algorithm.OracleResult].
        x: Dimension on the horizontal axis.
        y: Dimension on the vertical axis.
        show_points: Show the near-optimal designs found.
        show_outer: Show the outer approximation.
        trial_point: Optional design to highlight, as a dict, a pandas Series or an array with one value per
            dimension (e.g. the point returned by `Oracle.furthest_point`).
        n_directions: Number of directions used to trace the outer projection in more than 2 dimensions.
        title: Figure title.
    """
    ix, iy = result.dimensions.index(x), result.dimensions.index(y)
    fig = go.Figure()
    if show_outer:
        outline = projected_outer(result.outer_A, result.outer_b, ix, iy, n_directions)
        fig.add_trace(go.Scatter(x=outline[:, 0], y=outline[:, 1], fill='toself', mode='lines',
                                 line=dict(color=OUTER_COLOR, dash='dash'), fillcolor='rgba(158,202,225,0.35)',
                                 name='Outer approximation'))
    points = result.inner_points.to_numpy()[:, [ix, iy]]
    outline = _polygon(points)
    fig.add_trace(go.Scatter(x=outline[:, 0], y=outline[:, 1], fill='toself' if len(outline) > 3 else None,
                             mode='lines', line=dict(color=INNER_COLOR), fillcolor='rgba(8,81,156,0.45)',
                             name='Inner approximation'))
    if show_points:
        fig.add_trace(go.Scatter(x=points[:, 0], y=points[:, 1], mode='markers', name='Near-optimal designs found',
                                 marker=dict(color=INNER_COLOR, size=6, line=dict(color='white', width=1))))
    fig.add_trace(go.Scatter(x=[result.optimum[x]], y=[result.optimum[y]], mode='markers', name='Cost optimum',
                             marker=dict(color=OPTIMUM_COLOR, size=14, symbol='star')))
    if trial_point is not None:
        trial = result._as_point(trial_point)
        fig.add_trace(go.Scatter(x=[trial[ix]], y=[trial[iy]], mode='markers', name='Trial point',
                                 marker=dict(color=TRIAL_COLOR, size=12, symbol='x')))
    fig.update_layout(template='plotly_white', title=title or f'Near-optimal space (eps = {result.eps:.1%}): '
                      f'{y} vs {x}', xaxis_title=str(x), yaxis_title=str(y), legend=dict(orientation='h', y=-0.2))
    return fig

plot_ranges ¤

plot_ranges(
    result: OracleResult, title: Optional[str] = None
) -> Figure

Near-optimal range of each dimension: guaranteed (inner approximation) and possible (outer approximation).

Source code in src/energyscope/oracle/plots.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def plot_ranges(result: 'OracleResult', title: Optional[str] = None) -> go.Figure:
    """Near-optimal range of each dimension: guaranteed (inner approximation) and possible (outer approximation)."""
    ranges = result.ranges()
    names = [str(name) for name in ranges.index]
    fig = go.Figure()
    fig.add_trace(go.Bar(y=names, x=ranges['outer_max'] - ranges['outer_min'], base=ranges['outer_min'],
                         orientation='h', marker_color=OUTER_COLOR, name='Outer approximation (possible)'))
    fig.add_trace(go.Bar(y=names, x=ranges['inner_max'] - ranges['inner_min'], base=ranges['inner_min'],
                         orientation='h', marker_color=INNER_COLOR, name='Inner approximation (guaranteed)',
                         width=0.4))
    fig.add_trace(go.Scatter(y=names, x=ranges['optimum'], mode='markers', name='Cost optimum',
                             marker=dict(color=OPTIMUM_COLOR, size=12, symbol='star')))
    fig.update_layout(template='plotly_white', barmode='overlay', title=title or
                      f'Range of each dimension within {result.eps:.1%} of the optimal cost',
                      xaxis_title='Value', legend=dict(orientation='h', y=-0.2))
    return fig

projected_outer ¤

projected_outer(
    A: ndarray,
    b: ndarray,
    ix: int,
    iy: int,
    n_directions: int = 120,
) -> ndarray

Outline of the projection of {z : A z <= b} on dimensions ix and iy.

In 2-D the vertices are exact. In more dimensions the projection is traced with one LP per direction, which finds every vertex of the projected polygon whose normal cone contains one of the n_directions directions.

Source code in src/energyscope/oracle/plots.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def projected_outer(A: np.ndarray, b: np.ndarray, ix: int, iy: int, n_directions: int = 120) -> np.ndarray:
    """Outline of the projection of ``{z : A z <= b}`` on dimensions ``ix`` and ``iy``.

    In 2-D the vertices are exact. In more dimensions the projection is traced with one LP per direction, which
    finds every vertex of the projected polygon whose normal cone contains one of the ``n_directions`` directions.
    """
    if A.shape[1] == 2:
        try:
            return _polygon(geometry.polytope_vertices(A, b)[:, [ix, iy]])
        except ValueError:
            pass
    points = []
    for angle in np.linspace(0, 2 * np.pi, n_directions, endpoint=False):
        direction = np.zeros(A.shape[1])
        direction[ix], direction[iy] = np.cos(angle), np.sin(angle)
        points.append(geometry.support_point(A, b, direction)[[ix, iy]])
    return _polygon(np.array(points))