Skip to content

Commit

Permalink
Replace deprecated configpsace methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Sarah Krebs committed Aug 26, 2024
1 parent 275c5b7 commit b345cac
Show file tree
Hide file tree
Showing 33 changed files with 79 additions and 76 deletions.
5 changes: 4 additions & 1 deletion smac/acquisition/maximizer/local_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,10 @@ def _get_initial_points(
init_points = []
n_init_points = n_points
if len(previous_configs) < n_points:
sampled_points = self._configspace.sample_configuration(size=n_points - len(previous_configs))
if n_points - len(previous_configs) == 1:
sampled_points = [self._configspace.sample_configuration()]
else:
sampled_points = self._configspace.sample_configuration(size=n_points - len(previous_configs))
n_init_points = len(previous_configs)
if not isinstance(sampled_points, list):
sampled_points = [sampled_points]
Expand Down
2 changes: 1 addition & 1 deletion smac/acquisition/maximizer/random_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def _maximize(
if n_points > 1:
rand_configs = self._configspace.sample_configuration(size=n_points)
else:
rand_configs = [self._configspace.sample_configuration(size=1)]
rand_configs = [self._configspace.sample_configuration()]

if _sorted:
for i in range(len(rand_configs)):
Expand Down
4 changes: 2 additions & 2 deletions smac/facade/blackbox_facade.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,11 @@ def get_kernel(scenario: Scenario) -> kernels.Kernel:
cont_dims = np.where(np.array(types) == 0)[0]
cat_dims = np.where(np.array(types) != 0)[0]

if (len(cont_dims) + len(cat_dims)) != len(scenario.configspace.get_hyperparameters()):
if (len(cont_dims) + len(cat_dims)) != len(list(scenario.configspace.values())):
raise ValueError(
"The inferred number of continuous and categorical hyperparameters "
"must equal the total number of hyperparameters. Got "
f"{(len(cont_dims) + len(cat_dims))} != {len(scenario.configspace.get_hyperparameters())}."
f"{(len(cont_dims) + len(cat_dims))} != {len(list(scenario.configspace.values()))}."
)

# Constant Kernel
Expand Down
6 changes: 3 additions & 3 deletions smac/initial_design/abstract_initial_design.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def __init__(

self._additional_configs = additional_configs

n_params = len(self._configspace.get_hyperparameters())
n_params = len(list(self._configspace.values()))
if n_configs is not None:
logger.info("Using `n_configs` and ignoring `n_configs_per_hyperparameter`.")
self._n_configs = n_configs
Expand Down Expand Up @@ -174,10 +174,10 @@ def _transform_continuous_designs(
configs : list[Configuration]
Continuous transformed configs.
"""
params = configspace.get_hyperparameters()
params = list(configspace.values())
for idx, param in enumerate(params):
if isinstance(param, IntegerHyperparameter):
design[:, idx] = param._inverse_transform(param._transform(design[:, idx]))
design[:, idx] = param.to_vector(param.to_value(design[:, idx]))
elif isinstance(param, NumericalHyperparameter):
continue
elif isinstance(param, Constant):
Expand Down
2 changes: 1 addition & 1 deletion smac/initial_design/factorial_design.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class FactorialInitialDesign(AbstractInitialDesign):
"""Factorial initial design to select corner and middle configurations."""

def _select_configurations(self) -> list[Configuration]:
params = self._configspace.get_hyperparameters()
params = list(self._configspace.values())

values = []
mid = []
Expand Down
2 changes: 1 addition & 1 deletion smac/initial_design/latin_hypercube_design.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class LatinHypercubeInitialDesign(AbstractInitialDesign):
"""

def _select_configurations(self) -> list[Configuration]:
params = self._configspace.get_hyperparameters()
params = list(self._configspace.values())

constants = 0
for p in params:
Expand Down
5 changes: 3 additions & 2 deletions smac/initial_design/random_design.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ class RandomInitialDesign(AbstractInitialDesign):
"""Initial design that evaluates random configurations."""

def _select_configurations(self) -> list[Configuration]:
configs = self._configspace.sample_configuration(size=self._n_configs)
if self._n_configs == 1:
configs = [configs]
configs = [self._configspace.sample_configuration()]
else:
configs = self._configspace.sample_configuration(size=self._n_configs)
for config in configs:
config.origin = "Initial Design: Random"
return configs
4 changes: 2 additions & 2 deletions smac/initial_design/sobol_design.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ class SobolInitialDesign(AbstractInitialDesign):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)

if len(self._configspace.get_hyperparameters()) > 21201:
if len(list(self._configspace.values())) > 21201:
raise ValueError(
"The default initial design Sobol sequence can only handle up to 21201 dimensions. "
"Please use a different initial design, such as the Latin Hypercube design."
)

def _select_configurations(self) -> list[Configuration]:
params = self._configspace.get_hyperparameters()
params = list(self._configspace.values())

constants = 0
for p in params:
Expand Down
2 changes: 1 addition & 1 deletion smac/intensifier/successive_halving.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def get_state(self) -> dict[str, Any]: # noqa: D102
for seed, configs in self._tracker[key]:
# We have to make key serializable
new_key = f"{key[0]},{key[1]}"
tracker[new_key].append((seed, [config.get_dictionary() for config in configs]))
tracker[new_key].append((seed, [dict(config) for config in configs]))

return {"tracker": tracker}

Expand Down
2 changes: 1 addition & 1 deletion smac/main/config_selector.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ def __iter__(self) -> Iterator[Configuration]:
# the configspace.
logger.debug("No data available to train the model. Sample a random configuration.")

config = self._scenario.configspace.sample_configuration(1)
config = self._scenario.configspace.sample_configuration()
self._call_callbacks_on_end(config)
yield config
self._call_callbacks_on_start()
Expand Down
2 changes: 1 addition & 1 deletion smac/model/abstract_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def __init__(
raise RuntimeError("Instances must have the same number of features.")

self._n_features = n_features
self._n_hps = len(self._configspace.get_hyperparameters())
self._n_hps = len(list(self._configspace.values()))

self._pca = PCA(n_components=self._pca_components)
self._scaler = MinMaxScaler()
Expand Down
2 changes: 1 addition & 1 deletion smac/model/gaussian_process/abstract_gaussian_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def _get_all_priors(

def _set_has_conditions(self) -> None:
"""Sets `has_conditions` on `current_param`."""
has_conditions = len(self._configspace.get_conditions()) > 0
has_conditions = len(self._configspace.conditions) > 0
to_visit = []
to_visit.append(self._kernel)

Expand Down
4 changes: 2 additions & 2 deletions smac/model/random_forest/abstract_random_forest.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:

def _impute_inactive(self, X: np.ndarray) -> np.ndarray:
X = X.copy()
for idx, hp in enumerate(self._configspace.get_hyperparameters()):
for idx, hp in enumerate(list(self._configspace.values())):
if idx not in self._conditional:
parents = self._configspace.get_parents_of(hp.name)
parents = self._configspace.parents_of[hp.name]
if len(parents) == 0:
self._conditional[idx] = False
else:
Expand Down
2 changes: 1 addition & 1 deletion smac/runhistory/encoder/abstract_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def __init__(
self._instances = scenario.instances
self._instance_features = scenario.instance_features
self._n_features = scenario.count_instance_features()
self._n_params = len(scenario.configspace.get_hyperparameters())
self._n_params = len(list(scenario.configspace.values()))

if self._instances is not None and self._n_features == 0:
logger.warning(
Expand Down
4 changes: 2 additions & 2 deletions smac/runhistory/runhistory.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ def add(

# Construct keys and values for the data dictionary
for key, value in (
("config", config.get_dictionary()),
("config", dict(config)),
("config_id", config_id),
("instance", instance),
("seed", seed),
Expand Down Expand Up @@ -783,7 +783,7 @@ def save(self, filename: str | Path = "runhistory.json") -> None:
config_origins = {}
for id_, config in self._ids_config.items():
if id_ in config_ids_to_serialize:
configs[id_] = config.get_dictionary()
configs[id_] = dict(config)

config_origins[id_] = config.origin

Expand Down
2 changes: 1 addition & 1 deletion smac/runner/target_function_script_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def run(
status = StatusType.SUCCESS

# Add config arguments to the kwargs
for k, v in config.get_dictionary().items():
for k, v in dict(config).items():
if k in kwargs:
raise RuntimeError(f"The key {k} is already in use. Please use a different one.")
kwargs[k] = v
Expand Down
6 changes: 3 additions & 3 deletions smac/utils/configspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,11 @@ def get_types(
The bounds for the instance features are *not* added in this function.
"""
# Extract types vector for rf from config space and the bounds
types = [0] * len(configspace.get_hyperparameters())
types = [0] * len(list(configspace.values()))
bounds = [(np.nan, np.nan)] * len(types)

for i, param in enumerate(configspace.get_hyperparameters()):
parents = configspace.get_parents_of(param.name)
for i, param in enumerate(list(configspace.values())):
parents = configspace.parents_of[param.name]
if len(parents) == 0:
can_be_inactive = False
else:
Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures/config_selector.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def __iter__(self):
yield config

while True:
config = self._scenario.configspace.sample_configuration(1)
config = self._scenario.configspace.sample_configuration()
if config not in self._processed_configs:
self._processed_configs.append(config)
yield config
Expand Down
4 changes: 2 additions & 2 deletions tests/test_acquisition/test_maximizers.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,8 +205,8 @@ def model(configspace: ConfigurationSpace):
model = RandomForest(configspace)

np.random.seed(0)
X = np.random.rand(100, len(configspace.get_hyperparameters()))
y = 1 - (np.sum(X, axis=1) / len(configspace.get_hyperparameters()))
X = np.random.rand(100, len(list(configspace.values())))
y = 1 - (np.sum(X, axis=1) / len(list(configspace.values())))
model.train(X, y)

return model
Expand Down
2 changes: 1 addition & 1 deletion tests/test_initial_design/test_factorical_design.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def get_ordinal_param(name: str):
for i in range(n_dim):
for j, get_param in enumerate(get_params):
param_name = f"x{i+1}_{j}"
cs.add_hyperparameter(get_param(param_name))
cs.add(get_param(param_name))

design = FactorialInitialDesign(
make_scenario(configspace=cs),
Expand Down
2 changes: 1 addition & 1 deletion tests/test_initial_design/test_initial_design.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def test_config_numbers(make_scenario, configspace_small):
scenario = make_scenario(configspace_small)
configs = configspace_small.sample_configuration(n_configs)

n_hps = len(configspace_small.get_hyperparameters())
n_hps = len(list(configspace_small.values()))

dc = AbstractInitialDesign(
scenario=scenario,
Expand Down
20 changes: 10 additions & 10 deletions tests/test_intensifier/test_abstract_intensifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def test_setting_runhistory(make_scenario, configspace_small, make_config_select
intensifier.config_selector = make_config_selector(scenario, runhistory, n_initial_configs=1)

config = configspace_small.get_default_configuration()
config2 = configspace_small.sample_configuration(1)
config2 = configspace_small.sample_configuration()

# Add some entries to the runhistory
runhistory.add(
Expand Down Expand Up @@ -55,7 +55,7 @@ def test_incumbent_selection_single_objective(make_scenario, configspace_small,
intensifier.runhistory = runhistory

config = configspace_small.get_default_configuration()
config2 = configspace_small.sample_configuration(1)
config2 = configspace_small.sample_configuration()

runhistory.add(config=config, cost=50, time=0.0, instance=scenario.instances[0], seed=999)
intensifier.update_incumbents(config)
Expand Down Expand Up @@ -88,7 +88,7 @@ def test_incumbent_selection_multi_objective(make_scenario, configspace_small, m
intensifier.runhistory = runhistory

config = configspace_small.get_default_configuration()
config2 = configspace_small.sample_configuration(1)
config2 = configspace_small.sample_configuration()

runhistory.add(config=config, cost=[50, 10], time=0.0, instance=scenario.instances[0], seed=999)
intensifier.update_incumbents(config)
Expand Down Expand Up @@ -182,8 +182,8 @@ def test_pareto_front1(make_scenario, configspace_small):
runhistory = RunHistory()
intensifier = AbstractIntensifier(scenario=scenario, max_config_calls=3, seed=0)
intensifier.runhistory = runhistory
config1 = configspace_small.sample_configuration(1)
config2 = configspace_small.sample_configuration(1)
config1 = configspace_small.sample_configuration()
config2 = configspace_small.sample_configuration()

runhistory.add(
config=config1,
Expand Down Expand Up @@ -211,8 +211,8 @@ def test_pareto_front2(make_scenario, configspace_small):
runhistory = RunHistory()
intensifier = AbstractIntensifier(scenario=scenario, max_config_calls=3, seed=0)
intensifier.runhistory = runhistory
config1 = configspace_small.sample_configuration(1)
config2 = configspace_small.sample_configuration(1)
config1 = configspace_small.sample_configuration()
config2 = configspace_small.sample_configuration()

runhistory.add(
config=config1,
Expand Down Expand Up @@ -240,9 +240,9 @@ def test_pareto_front3(make_scenario, configspace_small):
runhistory = RunHistory()
intensifier = AbstractIntensifier(scenario=scenario, max_config_calls=3, seed=0)
intensifier.runhistory = runhistory
config1 = configspace_small.sample_configuration(1)
config2 = configspace_small.sample_configuration(1)
config3 = configspace_small.sample_configuration(1)
config1 = configspace_small.sample_configuration()
config2 = configspace_small.sample_configuration()
config3 = configspace_small.sample_configuration()

runhistory.add(
config=config1,
Expand Down
2 changes: 1 addition & 1 deletion tests/test_intensifier/test_intensifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ def test_intensifier_with_filled_runhistory(make_scenario, configspace_small, ma
intensifier.config_selector = make_config_selector(scenario, runhistory, n_initial_configs=1)
intensifier.runhistory = runhistory
config = configspace_small.get_default_configuration()
config2 = configspace_small.sample_configuration(1)
config2 = configspace_small.sample_configuration()

# Add some entries to the runhistory
runhistory.add(
Expand Down
6 changes: 3 additions & 3 deletions tests/test_intensifier/test_successive_halving.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def test_incumbents_any_budget(make_scenario, configspace_small, make_config_sel
intensifier.config_selector = make_config_selector(scenario, runhistory, n_initial_configs=1)
intensifier.runhistory = runhistory
config = configspace_small.get_default_configuration()
config2 = configspace_small.sample_configuration(1)
config2 = configspace_small.sample_configuration()

# Add some entries to the runhistory
runhistory.add(config=config, cost=0.5, time=0.0, seed=8, budget=1, status=StatusType.SUCCESS)
Expand Down Expand Up @@ -176,7 +176,7 @@ def test_incumbents_highest_observed_budget(make_scenario, configspace_small, ma
intensifier.runhistory = runhistory
intensifier.__post_init__()
config = configspace_small.get_default_configuration()
config2 = configspace_small.sample_configuration(1)
config2 = configspace_small.sample_configuration()

# Add some entries to the runhistory
runhistory.add(config=config, cost=0.5, time=0.0, seed=8, budget=1, status=StatusType.SUCCESS)
Expand Down Expand Up @@ -217,7 +217,7 @@ def test_incumbents_highest_budget(make_scenario, configspace_small, make_config
intensifier.runhistory = runhistory
intensifier.__post_init__()
config = configspace_small.get_default_configuration()
config2 = configspace_small.sample_configuration(1)
config2 = configspace_small.sample_configuration()

# Add some entries to the runhistory
runhistory.add(config=config, cost=0.5, time=0.0, seed=8, budget=1, status=StatusType.SUCCESS)
Expand Down
4 changes: 2 additions & 2 deletions tests/test_main/_test_boing.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,8 @@ def test_do_switching(make_scenario):

def test_subspace_extraction():
cs = ConfigurationSpace(0)
cs.add_hyperparameter(UniformFloatHyperparameter("x0", 0.0, 1.0))
cs.add_hyperparameter(CategoricalHyperparameter("x1", [0, 1, 2, 3, 4, 5]))
cs.add(UniformFloatHyperparameter("x0", 0.0, 1.0))
cs.add(CategoricalHyperparameter("x1", [0, 1, 2, 3, 4, 5]))

rf = RandomForest(
cs,
Expand Down
6 changes: 3 additions & 3 deletions tests/test_model/_test_gp_gpytorch.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def get_gp(n_dimensions, rs, noise=None, normalize_y=True) -> GPyTorchGaussianPr

configspace = ConfigurationSpace()
for i in range(n_dimensions):
configspace.add_hyperparameter(UniformFloatHyperparameter("x%d" % i, 0, 1))
configspace.add(UniformFloatHyperparameter("x%d" % i, 0, 1))

model = GPyTorchGaussianProcess(
configspace=configspace,
Expand Down Expand Up @@ -122,9 +122,9 @@ def get_mixed_gp(cat_dims, cont_dims, rs, normalize_y=True):

cs = ConfigurationSpace()
for c in cont_dims:
cs.add_hyperparameter(UniformFloatHyperparameter("X%d" % c, 0, 1))
cs.add(UniformFloatHyperparameter("X%d" % c, 0, 1))
for c in cat_dims:
cs.add_hyperparameter(CategoricalHyperparameter("X%d" % c, [0, 1, 2, 3]))
cs.add(CategoricalHyperparameter("X%d" % c, [0, 1, 2, 3]))

model = GPyTorchGaussianProcess(
configspace=cs,
Expand Down
2 changes: 1 addition & 1 deletion tests/test_model/_test_lgpga.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def setUp(self) -> None:
self.gp_model, self.cs = generate_lgpga(self.kernel, n_dimensions=num_dims, rs=rs)

def test_init(self):
np.testing.assert_equal(self.gp_model.cont_dims, np.arange(len(self.cs.get_hyperparameters())))
np.testing.assert_equal(self.gp_model.cont_dims, np.arange(len(list(self.cs.values()))))
np.testing.assert_equal(self.gp_model.cat_dims, np.array([]))

def test_update_attribute(self):
Expand Down
Loading

0 comments on commit b345cac

Please sign in to comment.