Skip to content

Commit 12d7730

Browse files
committed
✨plot created and added to ModelEvaluator
1 parent 7c6ee38 commit 12d7730

1 file changed

Lines changed: 337 additions & 0 deletions

File tree

corrai/optimize.py

Lines changed: 337 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
import numpy as np
55
import pandas as pd
6+
import plotly.graph_objects as go
67
from pymoo.core.problem import ElementwiseProblem
78
from pymoo.core.variable import Binary, Choice, Integer, Real
89
from scipy.optimize import differential_evolution, minimize_scalar, minimize, curve_fit
@@ -279,6 +280,37 @@ def scipy_obj_function(self, x: np.ndarray, *args) -> float:
279280
def scipy_scalar_obj_function(self, x: float, *args):
280281
return self.scipy_obj_function(np.array([x]), *args)
281282

283+
def plot_parameter_forest(
284+
self,
285+
optimal_values: "dict[str, float] | list[float] | pd.Series",
286+
mode: str = "normalized",
287+
title: str = None,
288+
**plot_kwargs,
289+
) -> go.Figure:
290+
"""
291+
Forest plot of this evaluator's parameters with bounds and optimal values.
292+
293+
Delegates to the module-level :func:`plot_parameter_forest`.
294+
See that function for full documentation.
295+
296+
Parameters
297+
----------
298+
optimal_values : dict, list, or pd.Series
299+
Optimal value per parameter. When a list, order must match
300+
``self.parameters``.
301+
mode : {"normalized", "absolute", "relative"}, default "normalized"
302+
title : str, optional
303+
**plot_kwargs
304+
Forwarded to ``fig.update_layout`` / ``fig.update_traces``.
305+
"""
306+
return plot_parameter_forest(
307+
self.parameters,
308+
optimal_values,
309+
mode=mode,
310+
title=title,
311+
**plot_kwargs,
312+
)
313+
282314

283315
class PymooModelEvaluator(ModelEvaluator):
284316
"""
@@ -993,3 +1025,308 @@ def wrapped_func(x, *params):
9931025
bounds=bounds,
9941026
**kwargs,
9951027
)
1028+
1029+
1030+
_FOREST_MODES = ["normalized", "absolute", "relative"]
1031+
1032+
1033+
def _apply_figure_kwargs(fig: go.Figure, **kwargs) -> None:
1034+
for key, val in kwargs.items():
1035+
try:
1036+
fig.update_layout(**{key: val})
1037+
except ValueError:
1038+
fig.update_traces(**{key: val})
1039+
1040+
1041+
def _forest_label(value: float, relabs: str, mode: str) -> str:
1042+
"""Format a bound or optimal value for forest plot annotation."""
1043+
if mode == "normalized":
1044+
return ""
1045+
if mode == "relative" and relabs == "Relative":
1046+
return f"{value * 100:.4g}%"
1047+
return f"{value:.4g}"
1048+
1049+
1050+
def plot_parameter_forest(
1051+
parameters: list[Parameter],
1052+
optimal_values: dict[str, float] | list[float] | pd.Series,
1053+
mode: str = "normalized",
1054+
title: str = None,
1055+
**plot_kwargs,
1056+
) -> go.Figure:
1057+
"""
1058+
Forest plot of optimization parameters — parameters on the X-axis, normalized
1059+
values on the Y-axis.
1060+
1061+
Each parameter is drawn as a vertical bar spanning [0, 1] (normalized to its
1062+
own bounds) with a diamond marker at the optimal value. Parameters with
1063+
different units are thus comparable on the same scale.
1064+
1065+
How bounds are labelled depends on ``mode``:
1066+
1067+
* ``"normalized"`` — no value annotations; Y-axis ticks read 0 % … 100 %.
1068+
* ``"absolute"`` — actual lower, upper, and optimal values are shown as
1069+
text on each bar.
1070+
* ``"relative"`` — parameters with ``relabs="Relative"`` are annotated in
1071+
percent (e.g. ``interval=(0.2, 1.5)`` → ``"20 %"`` / ``"150 %"``);
1072+
parameters with ``relabs="Absolute"`` fall back to actual values.
1073+
1074+
Parameters without an ``interval`` (e.g. ``Choice``) are silently skipped.
1075+
Hover is disabled on all traces.
1076+
1077+
Parameters
1078+
----------
1079+
parameters : list of Parameter
1080+
Parameters defining the search space.
1081+
optimal_values : dict, list, or pd.Series
1082+
Optimal value per parameter after optimisation. When a list or array,
1083+
order must match ``parameters``.
1084+
mode : {"normalized", "absolute", "relative"}, default "normalized"
1085+
Annotation style (see above).
1086+
title : str, optional
1087+
Plot title.
1088+
**plot_kwargs
1089+
Forwarded to ``fig.update_layout`` or ``fig.update_traces``.
1090+
1091+
Returns
1092+
-------
1093+
plotly.graph_objects.Figure
1094+
1095+
Examples
1096+
--------
1097+
>>> from corrai.base.parameter import Parameter
1098+
>>> from corrai.optimize import plot_parameter_forest
1099+
>>> params = [
1100+
... Parameter("conductivity", interval=(0.03, 0.06), model_property="x"),
1101+
... Parameter("thickness", interval=(0.05, 0.30), model_property="y"),
1102+
... Parameter("temp_setpoint", interval=(18.0, 24.0), model_property="z"),
1103+
... ]
1104+
>>> fig = plot_parameter_forest(
1105+
... params,
1106+
... {"conductivity": 0.04, "thickness": 0.12, "temp_setpoint": 21.0},
1107+
... mode="absolute",
1108+
... )
1109+
"""
1110+
if mode not in _FOREST_MODES:
1111+
raise ValueError(f"mode must be one of {_FOREST_MODES}, got {mode!r}")
1112+
1113+
# Include continuous (interval) and categorical (values/Choice) params; skip Binary
1114+
params = [p for p in parameters if p.interval is not None or p.values is not None]
1115+
if not params:
1116+
raise ValueError("No parameters with interval bounds found.")
1117+
1118+
all_param_names = {p.name for p in params}
1119+
if isinstance(optimal_values, (list, np.ndarray)):
1120+
opt_dict = {
1121+
p.name: v
1122+
for p, v in zip(parameters, optimal_values)
1123+
if p.interval is not None or p.values is not None
1124+
}
1125+
elif isinstance(optimal_values, pd.Series):
1126+
opt_dict = {k: v for k, v in optimal_values.items() if k in all_param_names}
1127+
else:
1128+
opt_dict = {k: v for k, v in optimal_values.items() if k in all_param_names}
1129+
1130+
missing = [p.name for p in params if p.name not in opt_dict]
1131+
if missing:
1132+
raise ValueError(f"Missing optimal values for parameters: {missing}")
1133+
1134+
names = [p.name for p in params]
1135+
interval_params = [p for p in params if p.interval is not None]
1136+
choice_params = [p for p in params if p.values is not None]
1137+
1138+
# --- Normalized optimal positions
1139+
opt_norms: dict[str, float] = {}
1140+
for p in params:
1141+
if p.interval is not None:
1142+
lo, hi = p.interval
1143+
v = float(opt_dict[p.name])
1144+
opt_norms[p.name] = (v - lo) / (hi - lo) if hi != lo else 0.5
1145+
else:
1146+
n = len(p.values)
1147+
positions = [i / (n - 1) for i in range(n)] if n > 1 else [0.5]
1148+
try:
1149+
idx = list(p.values).index(opt_dict[p.name])
1150+
except ValueError:
1151+
raise ValueError(
1152+
f"Optimal value {opt_dict[p.name]!r} not among choices "
1153+
f"{p.values} for parameter {p.name!r}"
1154+
)
1155+
opt_norms[p.name] = positions[idx]
1156+
1157+
# --- Labels
1158+
annotate = mode != "normalized"
1159+
lower_texts = {
1160+
p.name: _forest_label(p.interval[0], p.relabs, mode) for p in interval_params
1161+
}
1162+
upper_texts = {
1163+
p.name: _forest_label(p.interval[1], p.relabs, mode) for p in interval_params
1164+
}
1165+
# Optimal text: mode-aware for interval; empty for choice (tick labels already mark each position)
1166+
all_opt_texts = {
1167+
p.name: (
1168+
_forest_label(float(opt_dict[p.name]), p.relabs, mode)
1169+
if p.interval is not None
1170+
else ""
1171+
)
1172+
for p in params
1173+
}
1174+
annotate_opt = annotate
1175+
1176+
_bar_color = "darkblue"
1177+
fig = go.Figure()
1178+
1179+
# Trace: vertical lines for all params
1180+
x_lines: list[str | None] = []
1181+
y_lines: list[float | None] = []
1182+
for name in names:
1183+
x_lines.extend([name, name, None])
1184+
y_lines.extend([0.0, 1.0, None])
1185+
fig.add_trace(
1186+
go.Scatter(
1187+
x=x_lines,
1188+
y=y_lines,
1189+
mode="lines",
1190+
line=dict(color=_bar_color, width=2),
1191+
showlegend=False,
1192+
hoverinfo="skip",
1193+
)
1194+
)
1195+
1196+
# Trace: interval lower bound ticks (y=0, text below)
1197+
if interval_params:
1198+
inames = [p.name for p in interval_params]
1199+
fig.add_trace(
1200+
go.Scatter(
1201+
x=inames,
1202+
y=[0.0] * len(inames),
1203+
mode="markers+text" if annotate else "markers",
1204+
marker=dict(
1205+
symbol="line-ew-open",
1206+
size=14,
1207+
color=_bar_color,
1208+
line=dict(width=2, color=_bar_color),
1209+
),
1210+
text=[lower_texts[n] for n in inames],
1211+
textposition="bottom center",
1212+
showlegend=False,
1213+
hoverinfo="skip",
1214+
)
1215+
)
1216+
1217+
# Trace: interval upper bound ticks (y=1, text above)
1218+
if interval_params:
1219+
inames = [p.name for p in interval_params]
1220+
fig.add_trace(
1221+
go.Scatter(
1222+
x=inames,
1223+
y=[1.0] * len(inames),
1224+
mode="markers+text" if annotate else "markers",
1225+
marker=dict(
1226+
symbol="line-ew-open",
1227+
size=14,
1228+
color=_bar_color,
1229+
line=dict(width=2, color=_bar_color),
1230+
),
1231+
text=[upper_texts[n] for n in inames],
1232+
textposition="top center",
1233+
showlegend=False,
1234+
hoverinfo="skip",
1235+
)
1236+
)
1237+
1238+
# Trace: choice tick marks — one entry per choice value, always labelled
1239+
if choice_params:
1240+
cx: list[str] = []
1241+
cy: list[float] = []
1242+
ctexts: list[str] = []
1243+
ctextpositions: list[str] = []
1244+
for p in choice_params:
1245+
n = len(p.values)
1246+
positions = [i / (n - 1) for i in range(n)] if n > 1 else [0.5]
1247+
for i, (val, pos) in enumerate(zip(p.values, positions)):
1248+
cx.append(p.name)
1249+
cy.append(pos)
1250+
ctexts.append(str(val))
1251+
if n == 1:
1252+
ctextpositions.append("top center")
1253+
elif i == 0:
1254+
ctextpositions.append("bottom center")
1255+
elif i == n - 1:
1256+
ctextpositions.append("top center")
1257+
else:
1258+
ctextpositions.append("middle right")
1259+
fig.add_trace(
1260+
go.Scatter(
1261+
x=cx,
1262+
y=cy,
1263+
mode="markers+text",
1264+
marker=dict(
1265+
symbol="line-ew-open",
1266+
size=14,
1267+
color=_bar_color,
1268+
line=dict(width=2, color=_bar_color),
1269+
),
1270+
text=ctexts,
1271+
textposition=ctextpositions,
1272+
showlegend=False,
1273+
hoverinfo="skip",
1274+
)
1275+
)
1276+
1277+
# Trace: optimal diamonds — always last
1278+
fig.add_trace(
1279+
go.Scatter(
1280+
x=names,
1281+
y=[opt_norms[n] for n in names],
1282+
mode="markers+text" if annotate_opt else "markers",
1283+
name="Optimal",
1284+
marker=dict(
1285+
symbol="diamond",
1286+
size=13,
1287+
color="orange",
1288+
line=dict(width=1.5, color="darkorange"),
1289+
),
1290+
text=[all_opt_texts[n] for n in names],
1291+
textposition="middle right",
1292+
showlegend=True,
1293+
hoverinfo="skip",
1294+
)
1295+
)
1296+
1297+
# Lower text is "bottom center" → needs a bit of space below 0
1298+
y_range = [-0.05, 1.1] if mode == "normalized" else [-0.18, 1.25]
1299+
if mode == "normalized":
1300+
y_tickvals = [0.0, 0.25, 0.5, 0.75, 1.0]
1301+
y_ticktext = ["Lower (0%)", "25%", "50%", "75%", "Upper (100%)"]
1302+
title_y = "Normalized position with bounds"
1303+
else:
1304+
y_tickvals = [0.0, 1.0]
1305+
y_ticktext = ["Lower bound", "Upper bound"]
1306+
title_y = "Position with bounds"
1307+
1308+
b_margin = 100 if len(names) > 5 else 70
1309+
1310+
fig.update_layout(
1311+
title=title,
1312+
xaxis=dict(
1313+
tickangle=-30 if len(names) > 5 else 0,
1314+
ticklabelstandoff=4,
1315+
),
1316+
yaxis=dict(
1317+
title=title_y,
1318+
range=y_range,
1319+
tickvals=y_tickvals,
1320+
ticktext=y_ticktext,
1321+
showgrid=True,
1322+
gridcolor="#eeeeee",
1323+
zeroline=False,
1324+
),
1325+
plot_bgcolor="white",
1326+
legend=dict(orientation="h", yanchor="bottom", y=1.0, xanchor="right", x=1),
1327+
autosize=True,
1328+
margin=dict(l=70, r=30, t=40, b=b_margin),
1329+
)
1330+
1331+
_apply_figure_kwargs(fig, **plot_kwargs)
1332+
return fig

0 commit comments

Comments
 (0)