Skip to content

Commit 0394ee6

Browse files
0.29.3
Kriging does not accept noise argument, use method
1 parent ed24d1b commit 0394ee6

7 files changed

Lines changed: 97 additions & 40 deletions

File tree

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.29.2"
10+
version = "0.29.3"
1111
authors = [
1212
{ name="T. Bartz-Beielstein", email="tbb@bartzundbartz.de" }
1313
]

src/spotpython/spot/spot.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -374,12 +374,12 @@ def _optimizer_setup(self, optimizer) -> None:
374374
def _surrogate_control_setup(self) -> None:
375375
self.surrogate_control.update({"var_type": self.var_type})
376376
# Surrogate control updates:
377-
# The default value for `noise` from the surrogate_control dictionary
377+
# The default value for `method` from the surrogate_control dictionary
378378
# based on surrogate_control.init() is None. This value is updated
379-
# to the value of the key "noise" from the fun_control dictionary.
379+
# to the value of the key "method" from the fun_control dictionary.
380380
# If the value is set (i.e., not None), it is not updated.
381-
if self.surrogate_control["noise"] is None:
382-
self.surrogate_control.update({"noise": self.fun_control.noise})
381+
if self.surrogate_control["method"] is None:
382+
self.surrogate_control.update({"method": self.fun_control.method})
383383
if self.surrogate_control["model_fun_evals"] is None:
384384
self.surrogate_control.update({"model_fun_evals": self.optimizer_control["max_iter"]})
385385
# self.optimizer is not None here. If 1) the key "model_optimizer"
@@ -407,7 +407,7 @@ def _surrogate_setup(self, surrogate) -> None:
407407
if self.surrogate is None:
408408
# Call kriging with surrogate_control parameters:
409409
self.surrogate = Kriging(
410-
noise=self.surrogate_control["noise"],
410+
method=self.surrogate_control["method"],
411411
var_type=self.surrogate_control["var_type"],
412412
seed=self.surrogate_control["seed"],
413413
model_optimizer=self.surrogate_control["model_optimizer"],
@@ -485,7 +485,7 @@ def get_spot_attributes_as_df(self) -> pd.DataFrame:
485485
23 min_mean_y None
486486
24 min_y 0.0
487487
25 n_points 1
488-
26 noise False
488+
26 noise True
489489
27 ocba_delta 0
490490
28 optimizer_control {'max_iter': 1000, 'seed': 125}
491491
29 red_dim False
@@ -495,7 +495,7 @@ def get_spot_attributes_as_df(self) -> pd.DataFrame:
495495
33 show_progress True
496496
34 spot_writer None
497497
35 surrogate <spotpython.build.kriging.Kriging object at 0x...
498-
36 surrogate_control {'noise': False, 'model_optimizer': <function ...
498+
36 surrogate_control {'method': "regession", 'model_optimizer': <function ...
499499
37 tolerance_x 0
500500
38 upper [1]
501501
39 var_name [x0]
@@ -2193,7 +2193,7 @@ def get_tuned_hyperparameters(self, fun_control=None) -> dict:
21932193
] )
21942194
from spotpython.utils.init import design_control_init, surrogate_control_init
21952195
design_control = design_control_init(init_size=INIT_SIZE)
2196-
surrogate_control = surrogate_control_init(noise=True,
2196+
surrogate_control = surrogate_control_init(method="regression",
21972197
n_theta=2)
21982198
from spotpython.fun.hyperlight import HyperLight
21992199
fun = HyperLight(log_level=50).fun

src/spotpython/surrogate/kriging.py

Lines changed: 64 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,20 @@
55
from sklearn.base import BaseEstimator, RegressorMixin
66
from scipy.special import erf
77
import matplotlib.pyplot as plt
8-
from numpy import linspace, meshgrid, array
8+
from numpy import linspace, meshgrid, array, append
99
import pylab
1010
from numpy import ravel
1111
from spotpython.utils.aggregate import aggregate_mean_var
12+
import logging
13+
14+
logger = logging.getLogger(__name__)
15+
# configure the handler and formatter as needed
16+
py_handler = logging.FileHandler(f"{__name__}.log", mode="w")
17+
py_formatter = logging.Formatter("%(name)s %(asctime)s %(levelname)s %(message)s")
18+
# add formatter to the handler
19+
py_handler.setFormatter(py_formatter)
20+
# add handler to the logger
21+
logger.addHandler(py_handler)
1222

1323

1424
class Kriging(BaseEstimator, RegressorMixin):
@@ -99,11 +109,18 @@ def __init__(
99109
if self.model_fun_evals is None:
100110
self.model_fun_evals = 100
101111

112+
# Logging information
113+
self.log = {}
114+
self.log["negLnLike"] = []
115+
self.log["theta"] = []
116+
self.log["p"] = []
117+
self.log["Lambda"] = []
118+
102119
self.logtheta_lambda_ = None
103120
self.U_ = None
104121
self.X_ = None
105122
self.y_ = None
106-
self.NegLnLike_ = None
123+
self.negLnLike = None
107124
self.Psi_ = None
108125
if method not in ["interpolation", "regression", "reinterpolation"]:
109126
raise ValueError("method must be one of 'interpolation', 'regression', or 'reinterpolation']")
@@ -127,7 +144,43 @@ def get_model_params(self) -> Dict[str, float]:
127144
Returns:
128145
dict: Parameter names not included in get_params() mapped to their values.
129146
"""
130-
return {"log_theta_lambda": self.logtheta_lambda_, "U": self.U_, "X": self.X_, "y": self.y_, "NegLnLike": self.NegLnLike_}
147+
return {"log_theta_lambda": self.logtheta_lambda_, "U": self.U_, "X": self.X_, "y": self.y_, "negLnLike": self.negLnLike}
148+
149+
def _update_log(self) -> None:
150+
"""
151+
If spot_writer is not None, this method writes the current values of
152+
negLnLike, theta, p (if optim_p is True),
153+
and Lambda (if method is not "interpolation") to the spot_writer object.
154+
155+
Args:
156+
self (object): The Kriging object.
157+
158+
Returns:
159+
None
160+
161+
"""
162+
self.log["negLnLike"] = append(self.log["negLnLike"], self.negLnLike)
163+
self.log["theta"] = append(self.log["theta"], self.theta)
164+
if self.optim_p:
165+
self.log["p"] = append(self.log["p"], self.p)
166+
if (self.method == "regression") or (self.method == "reinterpolation"):
167+
self.log["Lambda"] = append(self.log["Lambda"], self.Lambda)
168+
# get the length of the log
169+
self.log_length = len(self.log["negLnLike"])
170+
if self.spot_writer is not None:
171+
negLnLike = self.negLnLike.copy()
172+
self.spot_writer.add_scalar("spot_negLnLike", negLnLike, self.counter + self.log_length)
173+
# add the self.n_theta theta values to the writer with one key "theta",
174+
# i.e, the same key for all theta values
175+
theta = self.theta.copy()
176+
self.spot_writer.add_scalars("spot_theta", {f"theta_{i}": theta[i] for i in range(self.n_theta)}, self.counter + self.log_length)
177+
if (self.method == "regression") or (self.method == "reinterpolation"):
178+
Lambda = self.Lambda.copy()
179+
self.spot_writer.add_scalar("spot_Lambda", Lambda, self.counter + self.log_length)
180+
if self.optim_p:
181+
p = self.p.copy()
182+
self.spot_writer.add_scalars("spot_p", {f"p_{i}": p[i] for i in range(self.n_p)}, self.counter + self.log_length)
183+
self.spot_writer.flush()
131184

132185
def fit(self, X: np.ndarray, y: np.ndarray, bounds: Optional[List[Tuple[float, float]]] = None) -> "Kriging":
133186
"""
@@ -190,7 +243,10 @@ def fit(self, X: np.ndarray, y: np.ndarray, bounds: Optional[List[Tuple[float, f
190243
self.p = 2
191244

192245
# Once logtheta_lambda is found, compute the final correlation matrix
193-
self.NegLnLike_, self.Psi_, self.U_ = self.likelihood(self.logtheta_lambda_)
246+
self.negLnLike, self.Psi_, self.U_ = self.likelihood(self.logtheta_lambda_)
247+
248+
# Update log with the current values
249+
self._update_log()
194250
return self
195251

196252
def predict(self, X: np.ndarray, return_std=False, return_val: str = "y") -> np.ndarray:
@@ -273,8 +329,8 @@ def likelihood(self, x: np.ndarray) -> Tuple[float, np.ndarray, np.ndarray]:
273329
274330
Returns:
275331
(float, np.ndarray, np.ndarray):
276-
(NegLnLike, Psi, U) where:
277-
- NegLnLike (float): The negative concentrated log-likelihood.
332+
(negLnLike, Psi, U) where:
333+
- negLnLike (float): The negative concentrated log-likelihood.
278334
- Psi (np.ndarray): The correlation matrix.
279335
- U (np.ndarray): The Cholesky factor (or None if ill-conditioned).
280336
"""
@@ -329,8 +385,8 @@ def likelihood(self, x: np.ndarray) -> Tuple[float, np.ndarray, np.ndarray]:
329385
tresid = np.linalg.solve(U.T, tresid)
330386
SigmaSqr = (resid @ tresid) / n
331387

332-
NegLnLike = (n / 2.0) * np.log(SigmaSqr) + 0.5 * LnDetPsi
333-
return NegLnLike, Psi, U
388+
negLnLike = (n / 2.0) * np.log(SigmaSqr) + 0.5 * LnDetPsi
389+
return negLnLike, Psi, U
334390

335391
def _pred(self, x: np.ndarray) -> float:
336392
"""

src/spotpython/utils/init.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -718,7 +718,7 @@ def design_control_init(init_size=10, repeats=1) -> dict:
718718

719719
def surrogate_control_init(
720720
log_level: int = 50,
721-
noise=False,
721+
method="regression",
722722
model_optimizer=differential_evolution,
723723
model_fun_evals=10000,
724724
min_theta=-3.0,
@@ -748,9 +748,10 @@ def surrogate_control_init(
748748
Default is -3.
749749
max_theta (float): The maximum value of theta. Note that the base10-logarithm is used.
750750
Default is 3.
751-
noise (bool):
752-
Whether the objective function is noisy or not. If Kriging, then a nugget is added.
753-
Default is False. Note: Will be set in the Spot class.
751+
method (str):
752+
The method to be used for the surrogate model. Default is "regression".
753+
Can be one of ["regression", "interpolation", "reinterpolation"].
754+
Note: Will also be set in the Spot class, if None.
754755
n_theta (int):
755756
The number of theta values. If larger than 1 or set to the string "anisotropic",
756757
then the k theta values are used, where k is the problem dimension.
@@ -783,9 +784,9 @@ def surrogate_control_init(
783784
Note:
784785
* The surrogate_control dictionary is used in the Spot class. The following values
785786
are updated in the Spot class if they are None in the surrogate_control dictionary:
786-
* `noise`: If the surrogate model dictionary is passed to the Spot class,
787-
and the `noise` value is `None`, then the noise value is set in the
788-
Spot class based on the value of `noise` in the Spot class fun_control dictionary.
787+
* `method`: If the surrogate model dictionary is passed to the Spot class,
788+
and the `method` value is `None`, then the method value is set in the
789+
Spot class based on the value of `method` in the Spot class fun_control dictionary.
789790
* `var_type`: The `var_type` value is set in the Spot class based on the value
790791
of `var_type` in the Spot class fun_control dictionary and the dimension of the problem.
791792
If the Kriging model is used as a surrogate in the Spot class, the setting from
@@ -804,7 +805,7 @@ def surrogate_control_init(
804805
"""
805806
surrogate_control = {
806807
"log_level": log_level,
807-
"noise": noise,
808+
"method": method,
808809
"model_optimizer": model_optimizer,
809810
"model_fun_evals": model_fun_evals,
810811
"min_theta": min_theta,

test/test_mo_repeats.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def test_repeats_1_1_0():
1212
"""
1313

1414
fun = MultiAnalytical(m=4).fun_mo_linear
15-
surrogate_control = surrogate_control_init(noise=True)
15+
surrogate_control = surrogate_control_init(method="regression")
1616
design_control = design_control_init(init_size=3, repeats=1)
1717
fun_control = fun_control_init(
1818
lower=np.array([-1]),
@@ -40,7 +40,7 @@ def test_repeats_1_1_1():
4040
"""
4141

4242
fun = MultiAnalytical(m=2).fun_mo_linear
43-
surrogate_control = surrogate_control_init(noise=True)
43+
surrogate_control = surrogate_control_init(method="regression")
4444
design_control = design_control_init(init_size=3, repeats=1)
4545
fun_control = fun_control_init(
4646
lower=np.array([-1]),
@@ -68,7 +68,7 @@ def test_repeats_2_1_0():
6868
"""
6969

7070
fun = MultiAnalytical(m=2).fun_mo_linear
71-
surrogate_control = surrogate_control_init(noise=True)
71+
surrogate_control = surrogate_control_init(method="regression")
7272
design_control = design_control_init(init_size=3, repeats=2)
7373
fun_control = fun_control_init(
7474
lower=np.array([-1]),
@@ -97,7 +97,7 @@ def test_repeats_1_2_0():
9797
"""
9898

9999
fun = MultiAnalytical(m=2).fun_mo_linear
100-
surrogate_control = surrogate_control_init(noise=True)
100+
surrogate_control = surrogate_control_init(method="regression")
101101
design_control = design_control_init(init_size=3, repeats=1)
102102
fun_control = fun_control_init(
103103
lower=np.array([-1]),
@@ -126,7 +126,7 @@ def test_repeats_1_2_1():
126126
"""
127127

128128
fun = MultiAnalytical(m=2).fun_mo_linear
129-
surrogate_control = surrogate_control_init(noise=True)
129+
surrogate_control = surrogate_control_init(method="regression")
130130
design_control = design_control_init(init_size=3, repeats=1)
131131
fun_control = fun_control_init(
132132
lower=np.array([-1]),
@@ -156,7 +156,7 @@ def test_repeats_2_2_1():
156156
"""
157157

158158
fun = MultiAnalytical(m=2).fun_mo_linear
159-
surrogate_control = surrogate_control_init(noise=True)
159+
surrogate_control = surrogate_control_init(method="regression")
160160
design_control = design_control_init(init_size=3, repeats=2)
161161
fun_control = fun_control_init(
162162
lower=np.array([-1]),
@@ -184,7 +184,7 @@ def test_repeats_2_2_2():
184184
"""
185185

186186
fun = MultiAnalytical(m=2).fun_mo_linear
187-
surrogate_control = surrogate_control_init(noise=True)
187+
surrogate_control = surrogate_control_init(method="regression")
188188
design_control = design_control_init(init_size=3, repeats=2)
189189
fun_control = fun_control_init(
190190
lower=np.array([-1]),

test/test_ocba.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def test_ocba():
2525
# [11 9 19 9 2]
2626

2727
fun = Analytical().fun_linear
28-
surrogate_control = surrogate_control_init(noise=True)
28+
surrogate_control = surrogate_control_init(method="regression")
2929
design_control = design_control_init(init_size=3, repeats=2)
3030
fun_control = fun_control_init(
3131
lower=np.array([-1]),

test/test_repeats.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ def test_repeats_1_1_0():
1414
"""
1515

1616
fun = Analytical().fun_linear
17-
surrogate_control = surrogate_control_init(noise=True)
17+
surrogate_control = surrogate_control_init(method="regression")
1818
design_control = design_control_init(init_size=3, repeats=1)
1919
fun_control = fun_control_init(
2020
lower=np.array([-1]),
@@ -42,7 +42,7 @@ def test_repeats_1_1_1():
4242
"""
4343

4444
fun = Analytical().fun_linear
45-
surrogate_control = surrogate_control_init(noise=True)
45+
surrogate_control = surrogate_control_init(method="regression")
4646
design_control = design_control_init(init_size=3, repeats=1)
4747
fun_control = fun_control_init(
4848
lower=np.array([-1]),
@@ -70,7 +70,7 @@ def test_repeats_2_1_0():
7070
"""
7171

7272
fun = Analytical().fun_linear
73-
surrogate_control = surrogate_control_init(noise=True)
73+
surrogate_control = surrogate_control_init(method="regression")
7474
design_control = design_control_init(init_size=3, repeats=2)
7575
fun_control = fun_control_init(
7676
lower=np.array([-1]),
@@ -99,7 +99,7 @@ def test_repeats_1_2_0():
9999
"""
100100

101101
fun = Analytical().fun_linear
102-
surrogate_control = surrogate_control_init(noise=True)
102+
surrogate_control = surrogate_control_init(method="regression")
103103
design_control = design_control_init(init_size=3, repeats=1)
104104
fun_control = fun_control_init(
105105
lower=np.array([-1]),
@@ -128,7 +128,7 @@ def test_repeats_1_2_1():
128128
"""
129129

130130
fun = Analytical().fun_linear
131-
surrogate_control = surrogate_control_init(noise=True)
131+
surrogate_control = surrogate_control_init(method="regression")
132132
design_control = design_control_init(init_size=3, repeats=1)
133133
fun_control = fun_control_init(
134134
lower=np.array([-1]),
@@ -158,7 +158,7 @@ def test_repeats_2_2_1():
158158
"""
159159

160160
fun = Analytical().fun_linear
161-
surrogate_control = surrogate_control_init(noise=True)
161+
surrogate_control = surrogate_control_init(method="regression")
162162
design_control = design_control_init(init_size=3, repeats=2)
163163
fun_control = fun_control_init(
164164
lower=np.array([-1]),
@@ -186,7 +186,7 @@ def test_repeats_2_2_2():
186186
"""
187187

188188
fun = Analytical().fun_linear
189-
surrogate_control = surrogate_control_init(noise=True)
189+
surrogate_control = surrogate_control_init(method="regression")
190190
design_control = design_control_init(init_size=3, repeats=2)
191191
fun_control = fun_control_init(
192192
lower=np.array([-1]),

0 commit comments

Comments
 (0)