Skip to content

Commit

Permalink
Merge branch 'development' into fix/1179
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamc authored Jan 13, 2025
2 parents 75f7e70 + 08d3bd7 commit f8c35d6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

## Bugfixes
- Fix bug with HyperBand setup given a total budget (#1179)
- Fix kwargs for DifferentialEvolution (#1187)

# 2.2.1

Expand Down
33 changes: 32 additions & 1 deletion smac/acquisition/maximizer/differential_evolution.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

import inspect

import numpy as np
from ConfigSpace import Configuration, ConfigurationSpace
from scipy.optimize._differentialevolution import DifferentialEvolutionSolver
Expand All @@ -14,6 +16,30 @@
__license__ = "3-clause BSD"


def check_kwarg(cls: type, kwarg_name: str) -> bool:
"""
Checks if a given class accepts a specific keyword argument in its __init__ method.
Parameters
----------
cls (type): The class to inspect.
kwarg_name (str): The name of the keyword argument to check.
Returns
-------
bool: True if the class's __init__ method accepts the keyword argument,
otherwise False.
"""
# Get the signature of the class's __init__ method
init_signature = inspect.signature(cls.__init__) # type: ignore[misc]

# Check if the kwarg_name is present in the signature as a parameter
for param in init_signature.parameters.values():
if param.name == kwarg_name and param.default != inspect.Parameter.empty:
return True # It accepts the kwarg
return False # It does not accept the kwarg


class DifferentialEvolution(AbstractAcquisitionMaximizer):
"""Get candidate solutions via `DifferentialEvolutionSolvers` from scipy.
Expand Down Expand Up @@ -92,6 +118,11 @@ def func(x: np.ndarray) -> np.ndarray:
transform_continuous_designs(design=x.T, origin="Diffrential Evolution", configspace=self._configspace)
)

accepts_seed = check_kwarg(DifferentialEvolutionSolver, "seed")
if accepts_seed:
kwargs = {"seed": self._rng.randint(1000)}
else:
kwargs = {"rng": self._rng.randint(1000)}
ds = DifferentialEvolutionSolver(
func,
bounds=[[0, 1] for _ in range(len(self._configspace))],
Expand All @@ -102,13 +133,13 @@ def func(x: np.ndarray) -> np.ndarray:
tol=0.01,
mutation=self.mutation,
recombination=self.recombination,
seed=self._rng.randint(1000),
polish=self.polish,
callback=None,
disp=False,
init="latinhypercube",
atol=0,
vectorized=True,
**kwargs,
)

_ = ds.solve()
Expand Down

0 comments on commit f8c35d6

Please sign in to comment.