Skip to content

Commit

Permalink
feat: Allow Sequence as space= in ConfigurationSpace
Browse files Browse the repository at this point in the history
  • Loading branch information
eddiebergman committed Jul 30, 2024
1 parent 34734ee commit 8a928d5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/ConfigSpace/configuration_space.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ def __init__(
| str
| Hyperparameter,
]
| Sequence[Hyperparameter]
) = None,
) -> None:
"""Initialize a configuration space.
Expand Down Expand Up @@ -174,9 +175,20 @@ def __init__(
)
```
You can also use a sequence of hyperparameters:
```python exec="true" result="python" source="material-block"
from ConfigSpace import ConfigurationSpace, Float, Integer
ConfigurationSpace(
name="myspace",
space=[Float("a", (1.0, 10.0)), Integer("b", (1, 10))]
)
```
"""
# If first arg is a dict, we assume this to be `space`
if isinstance(name, Mapping):
if isinstance(name, (Mapping, Sequence)) and not isinstance(name, str):
space = name
_name = None
else:
Expand All @@ -189,7 +201,10 @@ def __init__(
self._len = 0

if space is not None:
hyperparameters = list(_parse_hyperparameters_from_dict(space))
if isinstance(space, Mapping):
hyperparameters = list(_parse_hyperparameters_from_dict(space))
elif isinstance(space, Sequence):
hyperparameters = list(space)
self.add(hyperparameters)

@property
Expand Down
12 changes: 12 additions & 0 deletions test/test_configuration_space.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@
OrConjunction,
UniformIntegerHyperparameter,
)
from ConfigSpace.api.types.float import Float
from ConfigSpace.api.types.integer import Integer
from ConfigSpace.exceptions import (
AmbiguousConditionError,
ChildNotFoundError,
Expand Down Expand Up @@ -1326,3 +1328,13 @@ def test_repr_roundtrip():
repr = repr.replace("})", "}, configuration_space=cs)")
config = eval(repr) # noqa: S307
assert default == config


def test_configuration_space_can_be_made_with_sequence_of_hyperparameters() -> None:
cs = ConfigurationSpace(
name="myspace",
space=[Float("a", (1.0, 10.0)), Integer("b", (1, 10))],
)
assert len(cs) == 2
assert "a" in cs
assert "b" in cs

0 comments on commit 8a928d5

Please sign in to comment.