Skip to content

Commit b3ab51b

Browse files
0.31.8
new Spot plot contour
1 parent 2a43204 commit b3ab51b

4 files changed

Lines changed: 230 additions & 121 deletions

File tree

notebooks/00_spotPython_tests.ipynb

Lines changed: 91 additions & 29 deletions
Large diffs are not rendered by default.

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
77

88
[project]
99
name = "spotpython"
10-
version = "0.31.7"
10+
version = "0.31.8"
1111
authors = [
1212
{ name="T. Bartz-Beielstein", email="tbb@bartzundbartz.de" }
1313
]

src/spotpython/spot/spot.py

Lines changed: 103 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@
5151
from typing import Callable
5252
from spotpython.utils.numpy2json import NumpyEncoder
5353
from spotpython.utils.file import load_result
54-
from spotpython.surrogate.plot import plot_3d_contour
54+
from spotpython.surrogate.plot import plot_3d_contour, plotkd
5555

5656
# Setting up the backend to use QtAgg
5757
# matplotlib.use("TkAgg")
@@ -2432,77 +2432,6 @@ def process_z00(self, z00, use_min=True) -> list:
24322432
result.append(max_value)
24332433
return result
24342434

2435-
def plot_contour(
2436-
self,
2437-
i=0,
2438-
j=1,
2439-
min_z=None,
2440-
max_z=None,
2441-
show=True,
2442-
title=None,
2443-
filename=None,
2444-
n_grid=50,
2445-
contour_levels=10,
2446-
dpi=200,
2447-
figsize=(12, 5),
2448-
use_min=False,
2449-
use_max=True,
2450-
tkagg=False,
2451-
cmap="jet",
2452-
) -> None:
2453-
"""
2454-
Plot the contour and 3D surface for any pair of dimensions of the surrogate model.
2455-
This method visualizes the surrogate model's predictions over a grid for two selected dimensions.
2456-
It creates both a filled contour plot and a 3D surface plot, allowing users to inspect the surrogate's
2457-
response surface. The remaining dimensions are fixed to either their minimum or maximum values, depending
2458-
on the `use_min` and `use_max` flags.
2459-
2460-
Args:
2461-
i (int, optional): Index of the first dimension to plot. Default is 0.
2462-
j (int, optional): Index of the second dimension to plot. Default is 1.
2463-
min_z (float, optional): Minimum value for the color scale (z-axis). If None, determined automatically.
2464-
max_z (float, optional): Maximum value for the color scale (z-axis). If None, determined automatically.
2465-
show (bool, optional): Whether to display the plot interactively. Default is True.
2466-
filename (str, optional): If provided, saves the plot to this file. Default is None.
2467-
n_grid (int, optional): Number of grid points per dimension. Default is 50.
2468-
contour_levels (int, optional): Number of contour levels. Default is 10.
2469-
dpi (int, optional): Dots per inch for saved figure. Default is 200.
2470-
title (str, optional): Title for the plot. Default is None.
2471-
figsize (tuple, optional): Figure size in inches (width, height). Default is (12, 6).
2472-
use_min (bool, optional): If True, fix hidden dimensions to their minimum values. Default is False.
2473-
use_max (bool, optional): If True, fix hidden dimensions to their maximum values. Default is True.
2474-
tkagg (bool, optional): If True, use TkAgg backend for matplotlib. Default is False.
2475-
cmap (str, optional): Colormap to use for the contour plot. Default is "jet".
2476-
2477-
Returns:
2478-
None
2479-
"""
2480-
X, Y, Z = self.prepare_plot(
2481-
i=i,
2482-
j=j,
2483-
n_grid=n_grid,
2484-
use_min=use_min,
2485-
use_max=use_max,
2486-
)
2487-
plot_3d_contour(
2488-
X=X,
2489-
Y=Y,
2490-
Z=Z,
2491-
vmin=min_z if min_z is not None else np.min(Z),
2492-
vmax=max_z if max_z is not None else np.max(Z),
2493-
var_name=self.var_name,
2494-
i=i,
2495-
j=j,
2496-
show=show,
2497-
filename=filename,
2498-
contour_levels=contour_levels,
2499-
dpi=dpi,
2500-
title=title,
2501-
figsize=figsize,
2502-
tkagg=tkagg,
2503-
cmap=cmap,
2504-
)
2505-
25062435
def prepare_plot(
25072436
self,
25082437
i=0,
@@ -2522,7 +2451,10 @@ def prepare_plot(
25222451
use_max (bool, optional): If True, fix hidden dimensions to their maximum values. Default is True.
25232452
25242453
Returns:
2525-
dict: Dictionary containing X_combined, Y_combined, Z_combined, min_z, max_z.
2454+
(tuple): A tuple containing:
2455+
- X (numpy.ndarray): Mesh grid for the first dimension.
2456+
- Y (numpy.ndarray): Mesh grid for the second dimension.
2457+
- Z (numpy.ndarray): Surrogate predictions over the grid.
25262458
25272459
Examples:
25282460
>>> plot_data = S.prepare_plot(i=0, j=1)
@@ -2577,6 +2509,104 @@ def predict_contour_values(X, Y, z0):
25772509

25782510
return X_combined, Y_combined, Z_combined
25792511

2512+
def plot_contour(
2513+
self,
2514+
i=0,
2515+
j=1,
2516+
min_z=None,
2517+
max_z=None,
2518+
show=True,
2519+
title=None,
2520+
filename=None,
2521+
n_grid=50,
2522+
contour_levels=10,
2523+
dpi=200,
2524+
figsize=(12, 5),
2525+
use_min=False,
2526+
use_max=True,
2527+
tkagg=False,
2528+
cmap="jet",
2529+
) -> None:
2530+
"""
2531+
Plot the contour and 3D surface for any pair of dimensions of the surrogate model.
2532+
This method visualizes the surrogate model's predictions over a grid for two selected dimensions.
2533+
It creates both a filled contour plot and a 3D surface plot, allowing users to inspect the surrogate's
2534+
response surface. The remaining dimensions are fixed to either their minimum or maximum values, depending
2535+
on the `use_min` and `use_max` flags.
2536+
"""
2537+
plotkd(model=self.surrogate, X=self.X, y=self.y, i=i, j=j, num=n_grid)
2538+
2539+
def plot_contour_old(
2540+
self,
2541+
i=0,
2542+
j=1,
2543+
min_z=None,
2544+
max_z=None,
2545+
show=True,
2546+
title=None,
2547+
filename=None,
2548+
n_grid=50,
2549+
contour_levels=10,
2550+
dpi=200,
2551+
figsize=(12, 5),
2552+
use_min=False,
2553+
use_max=True,
2554+
tkagg=False,
2555+
cmap="jet",
2556+
) -> None:
2557+
"""
2558+
Plot the contour and 3D surface for any pair of dimensions of the surrogate model.
2559+
This method visualizes the surrogate model's predictions over a grid for two selected dimensions.
2560+
It creates both a filled contour plot and a 3D surface plot, allowing users to inspect the surrogate's
2561+
response surface. The remaining dimensions are fixed to either their minimum or maximum values, depending
2562+
on the `use_min` and `use_max` flags.
2563+
2564+
Args:
2565+
i (int, optional): Index of the first dimension to plot. Default is 0.
2566+
j (int, optional): Index of the second dimension to plot. Default is 1.
2567+
min_z (float, optional): Minimum value for the color scale (z-axis). If None, determined automatically.
2568+
max_z (float, optional): Maximum value for the color scale (z-axis). If None, determined automatically.
2569+
show (bool, optional): Whether to display the plot interactively. Default is True.
2570+
filename (str, optional): If provided, saves the plot to this file. Default is None.
2571+
n_grid (int, optional): Number of grid points per dimension. Default is 50.
2572+
contour_levels (int, optional): Number of contour levels. Default is 10.
2573+
dpi (int, optional): Dots per inch for saved figure. Default is 200.
2574+
title (str, optional): Title for the plot. Default is None.
2575+
figsize (tuple, optional): Figure size in inches (width, height). Default is (12, 6).
2576+
use_min (bool, optional): If True, fix hidden dimensions to their minimum values. Default is False.
2577+
use_max (bool, optional): If True, fix hidden dimensions to their maximum values. Default is True.
2578+
tkagg (bool, optional): If True, use TkAgg backend for matplotlib. Default is False.
2579+
cmap (str, optional): Colormap to use for the contour plot. Default is "jet".
2580+
2581+
Returns:
2582+
None
2583+
"""
2584+
X, Y, Z = self.prepare_plot(
2585+
i=i,
2586+
j=j,
2587+
n_grid=n_grid,
2588+
use_min=use_min,
2589+
use_max=use_max,
2590+
)
2591+
plot_3d_contour(
2592+
X=X,
2593+
Y=Y,
2594+
Z=Z,
2595+
vmin=min_z if min_z is not None else np.min(Z),
2596+
vmax=max_z if max_z is not None else np.max(Z),
2597+
var_name=self.var_name,
2598+
i=i,
2599+
j=j,
2600+
show=show,
2601+
filename=filename,
2602+
contour_levels=contour_levels,
2603+
dpi=dpi,
2604+
title=title,
2605+
figsize=figsize,
2606+
tkagg=tkagg,
2607+
cmap=cmap,
2608+
)
2609+
25802610
def plot_important_hyperparameter_contour(
25812611
self,
25822612
threshold=0.0,

src/spotpython/surrogate/plot.py

Lines changed: 35 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ def plot1d(model, X: np.ndarray, y: np.ndarray, show: Optional[bool] = True) ->
3434
raise ValueError("plot1d is only supported for 1D input data.")
3535

3636
_ = plt.figure(figsize=(9, 6))
37-
n_grid = 100
38-
x = linspace(X[:, 0].min(), X[:, 0].max(), num=n_grid).reshape(-1, 1)
37+
num = 100
38+
x = linspace(X[:, 0].min(), X[:, 0].max(), num=num).reshape(-1, 1)
3939
y_pred, y_std = model.predict(x, return_std=True)
4040

4141
plt.plot(x, y_pred, "k", label="Prediction")
@@ -55,30 +55,47 @@ def plot1d(model, X: np.ndarray, y: np.ndarray, show: Optional[bool] = True) ->
5555
plt.show()
5656

5757

58-
def generate_mesh_grid(X: np.ndarray, i: int, j: int, n_grid: int = 100):
58+
def generate_mesh_grid(
59+
X: Optional[np.ndarray] = None,
60+
i: int = 0,
61+
j: int = 1,
62+
num: int = 100,
63+
lower: Optional[np.ndarray] = None,
64+
upper: Optional[np.ndarray] = None,
65+
):
5966
"""
60-
Generate a mesh grid for two selected dimensions of X, and fill the remaining dimensions with their mean values.
67+
Generate a mesh grid for two selected dimensions, filling remaining dimensions with their mean values
68+
(if X is given) or the mean of the lower and upper bound (if lower and upper are given).
6169
6270
Args:
63-
X (np.ndarray): Input data of shape (n_samples, k).
71+
X (np.ndarray, optional): Input data of shape (n_samples, k). Required if lower/upper are not given.
6472
i (int): Index of the first dimension to vary.
6573
j (int): Index of the second dimension to vary.
66-
n_grid (int): Number of grid points per dimension.
74+
num (int): Number of grid points per dimension.
75+
lower (np.ndarray, optional): Lower bounds for each dimension (shape (k,)).
76+
upper (np.ndarray, optional): Upper bounds for each dimension (shape (k,)).
6777
6878
Returns:
6979
X_i (np.ndarray): Meshgrid for the i-th dimension.
7080
X_j (np.ndarray): Meshgrid for the j-th dimension.
71-
grid_points (np.ndarray): Grid points of shape (n_grid*n_grid, k) for prediction.
81+
grid_points (np.ndarray): Grid points of shape (num*num, k) for prediction.
7282
"""
73-
k = X.shape[1]
74-
mean_values = X.mean(axis=0)
83+
# Check that exactly one of (X) or (lower and upper) is provided
84+
if (X is not None and (lower is not None or upper is not None)) or (X is None and (lower is None or upper is None)):
85+
raise ValueError("Provide either X or both lower and upper, but not both or neither.")
86+
87+
if X is not None:
88+
k = X.shape[1]
89+
mean_values = X.mean(axis=0)
90+
x_i = linspace(X[:, i].min(), X[:, i].max(), num=num)
91+
x_j = linspace(X[:, j].min(), X[:, j].max(), num=num)
92+
else:
93+
k = len(lower)
94+
mean_values = (np.array(lower) + np.array(upper)) / 2.0
95+
x_i = linspace(lower[i], upper[i], num=num)
96+
x_j = linspace(lower[j], upper[j], num=num)
7597

76-
# Create a grid for the two varied dimensions
77-
x_i = linspace(X[:, i].min(), X[:, i].max(), num=n_grid)
78-
x_j = linspace(X[:, j].min(), X[:, j].max(), num=n_grid)
7998
X_i, X_j = meshgrid(x_i, x_j)
80-
81-
# Prepare the grid points for prediction
8299
grid_points = np.zeros((X_i.size, k))
83100
grid_points[:, i] = X_i.ravel()
84101
grid_points[:, j] = X_j.ravel()
@@ -318,7 +335,7 @@ def plotkd(
318335
max_error: float = 1e-3,
319336
var_names: Optional[List[str]] = None,
320337
cmap: str = "jet",
321-
n_grid: int = 100,
338+
num: int = 100,
322339
vmin: Optional[float] = None,
323340
vmax: Optional[float] = None,
324341
add_points: bool = False,
@@ -338,7 +355,7 @@ def plotkd(
338355
max_error (float): Maximum error for color scaling. Default is 1e-3.
339356
var_names (list of str, optional): List of variable names for axis labeling. If None, generic labels are used.
340357
cmap (str): Colormap for the surface and contour plots. Default is "jet".
341-
n_grid (int): Number of grid points per dimension for the mesh grid. Default is 100.
358+
num (int): Number of grid points per dimension for the mesh grid. Default is 100.
342359
vmin (float, optional): Minimum value for the color scale. If None, determined from predictions.
343360
vmax (float, optional): Maximum value for the color scale. If None, determined from predictions.
344361
add_points (bool): If True, adds scatter points to the surface and contour plots. Default is False.
@@ -358,7 +375,7 @@ def plotkd(
358375
"""
359376
k = X.shape[1]
360377
check_ij(i, j, k)
361-
X_i, X_j, grid_points = generate_mesh_grid(X, i, j, n_grid)
378+
X_i, X_j, grid_points = generate_mesh_grid(X, i, j, num)
362379

363380
# Predict the values and standard deviations
364381
y_pred, y_std = model.predict(grid_points, return_std=True)
@@ -491,7 +508,7 @@ def plot_3d_contour(X, Y, Z, vmin, vmax, var_name=None, i=0, j=1, show=True, fil
491508
Examples:
492509
>>> # Example 1: Using output from Spot
493510
>>> # Assume S is a Spot object with a fitted surrogate
494-
>>> plot_data = S.prepare_plot(i=0, j=1, n_grid=100)
511+
>>> plot_data = S.prepare_plot(i=0, j=1, num=100)
495512
>>> from spotpython.surrogate.plot import plot_3d_contour
496513
>>> plot_3d_contour(
497514
... plot_data,

0 commit comments

Comments
 (0)