Skip to content

Commit d4d6777

Browse files
committed
Add suggestions from code review
* Rename 'true' parameter to 'data' in 'target_func' method. * Remove setting random_state in run function during tests. * Add explicit haz_type to tests to avoid warnings.
1 parent 6fa9315 commit d4d6777

File tree

6 files changed

+25
-20
lines changed

6 files changed

+25
-20
lines changed

climada/test/test_util_calibrate.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ def setUp(self) -> None:
6363
mdd=np.array([0, 10 * slope]),
6464
paa=np.ones(2),
6565
id=1,
66+
haz_type="TEST",
6667
)
6768
]
6869
)
@@ -106,6 +107,7 @@ def test_multiple_constrained(self):
106107
mdd=np.array([0, 1, 3]),
107108
paa=np.ones(3),
108109
id=1,
110+
haz_type="TEST",
109111
)
110112
]
111113
)
@@ -155,6 +157,7 @@ def setUp(self) -> None:
155157
mdd=np.array([0, 10 * slope]),
156158
paa=np.ones(2),
157159
id=1,
160+
haz_type="TEST",
158161
)
159162
]
160163
)
@@ -170,8 +173,8 @@ def setUp(self) -> None:
170173
def test_single(self):
171174
"""Test with single parameter"""
172175
self.input.bounds = {"slope": (-1, 3)}
173-
optimizer = BayesianOptimizer(self.input)
174-
output = optimizer.run(init_points=10, n_iter=20, random_state=1)
176+
optimizer = BayesianOptimizer(self.input, random_state=1)
177+
output = optimizer.run(init_points=10, n_iter=20)
175178

176179
# Check result (low accuracy)
177180
self.assertAlmostEqual(output.params["slope"], 1.0, places=2)
@@ -189,6 +192,7 @@ def test_multiple_constrained(self):
189192
mdd=np.array([0, 1, 3]),
190193
paa=np.ones(3),
191194
id=1,
195+
haz_type="TEST",
192196
)
193197
]
194198
)
@@ -199,8 +203,8 @@ def test_multiple_constrained(self):
199203
)
200204
self.input.bounds = {"intensity_1": (-1, 4), "intensity_2": (-1, 4)}
201205
# Run optimizer
202-
optimizer = BayesianOptimizer(self.input)
203-
output = optimizer.run(n_iter=200, random_state=1)
206+
optimizer = BayesianOptimizer(self.input, random_state=1)
207+
output = optimizer.run(n_iter=200)
204208

205209
# Check results (low accuracy)
206210
self.assertEqual(output.p_space.dim, 2)
@@ -230,8 +234,8 @@ def test_multiple_constrained(self):
230234
def test_plots(self):
231235
"""Check if executing the default plots works"""
232236
self.input.bounds = {"slope": (-1, 3)}
233-
optimizer = BayesianOptimizer(self.input)
234-
output = optimizer.run(init_points=10, n_iter=20, random_state=1)
237+
optimizer = BayesianOptimizer(self.input, random_state=1)
238+
output = optimizer.run(init_points=10, n_iter=20)
235239

236240
output_eval = OutputEvaluator(self.input, output)
237241
output_eval.impf_set.plot()

climada/util/calibrate/base.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -379,16 +379,16 @@ class Optimizer(ABC):
379379

380380
input: Input
381381

382-
def _target_func(self, true: pd.DataFrame, predicted: pd.DataFrame) -> Number:
382+
def _target_func(self, data: pd.DataFrame, predicted: pd.DataFrame) -> Number:
383383
"""Target function for the optimizer
384384
385385
The default version of this function simply returns the value of the cost
386386
function evaluated on the arguments.
387387
388388
Parameters
389389
----------
390-
true : pandas.DataFrame
391-
The "true" data used for calibration. By default, this is
390+
data : pandas.DataFrame
391+
The reference data used for calibration. By default, this is
392392
:py:attr:`Input.data`.
393393
predicted : pandas.DataFrame
394394
The impact predicted by the data calibration after it has been transformed
@@ -398,7 +398,7 @@ def _target_func(self, true: pd.DataFrame, predicted: pd.DataFrame) -> Number:
398398
-------
399399
The value of the target function for the optimizer.
400400
"""
401-
return self.input.cost_func(true, predicted)
401+
return self.input.cost_func(data, predicted)
402402

403403
def _kwargs_to_impact_func_creator(self, *_, **kwargs) -> Dict[str, Any]:
404404
"""Define how the parameters to :py:meth:`_opt_func` must be transformed

climada/util/calibrate/bayesian_optimizer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -249,9 +249,9 @@ def __post_init__(
249249
**bayes_opt_kwds,
250250
)
251251

252-
def _target_func(self, true: pd.DataFrame, predicted: pd.DataFrame) -> Number:
252+
def _target_func(self, data: pd.DataFrame, predicted: pd.DataFrame) -> Number:
253253
"""Invert the cost function because BayesianOptimization maximizes the target"""
254-
return -self.input.cost_func(true, predicted)
254+
return -self.input.cost_func(data, predicted)
255255

256256
def run(self, **opt_kwargs) -> BayesianOptimizerOutput:
257257
"""Execute the optimization

climada/util/calibrate/test/test_base.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,9 @@ def hazard():
4848
centroids = Centroids.from_lat_lon(lat=lat, lon=lon)
4949
event_id = np.array([1, 3, 10])
5050
intensity = csr_matrix([[1, 0.1], [2, 0.2], [3, 2]])
51-
return Hazard(event_id=event_id, centroids=centroids, intensity=intensity)
51+
return Hazard(
52+
event_id=event_id, centroids=centroids, intensity=intensity, haz_type="TEST"
53+
)
5254

5355

5456
def exposure():
@@ -58,7 +60,7 @@ def exposure():
5860
longitude=[0, 1, 100],
5961
latitude=[1, 2, 50],
6062
value=[1, 0.1, 1e6],
61-
impf_=[1, 1, 1],
63+
impf_TEST=[1, 1, 1],
6264
)
6365
)
6466

@@ -124,9 +126,8 @@ def test_post_init(self):
124126
impact_to_dataframe=self.impact_to_dataframe,
125127
)
126128

127-
# Check hazard and exposure
128-
self.assertIn("centr_", input.exposure.gdf)
129-
npt.assert_array_equal(input.exposure.gdf["centr_"], [0, 1, -1])
129+
# Check centroids assignment
130+
npt.assert_array_equal(input.exposure.gdf["centr_TEST"], [0, 1, -1])
130131

131132
def test_align_impact(self):
132133
"""Check alignment of impact and data"""
@@ -237,9 +238,7 @@ def test_init(self, mock):
237238
self.assertEqual(out_eval._impact_label, "Impact [my_unit]")
238239

239240
self.input.impact_func_creator.assert_called_with(p1=1, p2=2.0)
240-
mock.assert_called_with(
241-
self.input.exposure, "impact_func", self.input.hazard
242-
)
241+
mock.assert_called_with(self.input.exposure, "impact_func", self.input.hazard)
243242

244243

245244
# Execute Tests

climada/util/calibrate/test/test_bayesian_optimizer.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828

2929
from .test_base import hazard, exposure
3030

31+
3132
class TestBayesianOptimizer(unittest.TestCase):
3233
"""Tests for the optimizer based on bayes_opt.BayesianOptimization"""
3334

climada/util/calibrate/test/test_scipy_optimizer.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@ def assert_bounds_in_call(bounds: Optional[List]):
140140
minimize_mock.assert_called_once()
141141
assert_bounds_in_call(bounds=[None, "a", (1, 2)])
142142

143+
143144
# Execute Tests
144145
if __name__ == "__main__":
145146
TESTS = unittest.TestLoader().loadTestsFromTestCase(TestScipyMinimizeOptimizer)

0 commit comments

Comments
 (0)