Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve prior build error message #889

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions src/orion/algo/space.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,17 +130,17 @@ def __init__(self, name, prior, *args, **kwargs):
def validate(self):
"""Validate dimension arguments"""
if "random_state" in self._kwargs or "seed" in self._kwargs:
raise ValueError(
raise TypeError(
"random_state/seed cannot be set in a "
"parameter's definition! Set seed globally!"
)
if "discrete" in self._kwargs:
raise ValueError(
raise TypeError(
"Do not use kwarg 'discrete' on `Dimension`, "
"use pure `_Discrete` class instead!"
)
if "size" in self._kwargs:
raise ValueError("Use 'shape' keyword only instead of 'size'.")
raise TypeError("Use 'shape' keyword only instead of 'size'.")

if (
self.default_value is not self.NO_DEFAULT_VALUE
Expand Down Expand Up @@ -884,13 +884,13 @@ class Fidelity(Dimension):
# pylint:disable=super-init-not-called
def __init__(self, name, low, high, base=2):
if low <= 0:
raise AttributeError("Minimum resources must be a positive number.")
raise ValueError("Minimum resources must be a positive number.")
elif low > high:
raise AttributeError(
raise ValueError(
"Minimum resources must be smaller than maximum resources."
)
if base < 1:
raise AttributeError("Base should be greater than or equal to 1")
raise ValueError("Base should be greater than or equal to 1")
self.name = name
self.low = int(low)
self.high = int(high)
Expand Down
24 changes: 17 additions & 7 deletions src/orion/core/io/space_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,16 @@ def loguniform(self, *args, **kwargs):
klass = _real_or_int(kwargs)
return klass(name, "reciprocal", *args, **kwargs)

def _build_custom(self, expression, globals_, locals_):
name = expression.split("(")[0]
if not hasattr(self, name):
return None
try:
dimension = eval("self." + expression, globals_, locals_)
return dimension
except AttributeError as error:
raise AttributeError(f"Parameter '{name}': {error}") from error

def _build(self, name, expression):
"""Build a `Dimension` object using a string as its `name` and another
string, `expression`, from configuration as a "function" to create it.
Expand All @@ -205,12 +215,10 @@ def _build(self, name, expression):
import numpy as np

globals_["np"] = np
try:
dimension = eval("self." + expression, globals_, {"self": self})

locals_ = {"self": self}
dimension = self._build_custom(expression, globals_, locals_)
if dimension is not None:
return dimension
except AttributeError:
pass

# If not found in the methods of `DimensionBuilder`.
# try to see if it is legit scipy stuff and call a `Dimension`
Expand Down Expand Up @@ -242,8 +250,10 @@ def build(self, name, expression):
"""
try:
dimension = self._build(name, expression)
except ValueError as exc:
raise TypeError(f"Parameter '{name}': Incorrect arguments.") from exc
except (TypeError, ValueError) as exc:
raise type(exc)(
f"Parameter '{name}' has incorrect arguments: {str(exc)}"
) from exc
except IndexError as exc:
error_msg = (
f"Parameter '{name}': Please provide a valid form for prior:\n"
Expand Down
14 changes: 7 additions & 7 deletions tests/unittests/algo/test_space.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,17 +96,17 @@ def test_shaped_instance(self, seed):

def test_ban_size_kwarg(self):
"""Should not be able to use 'size' kwarg."""
with pytest.raises(ValueError):
with pytest.raises(TypeError):
Dimension("yolo", "norm", 0.9, size=(3, 2))

def test_ban_seed_kwarg(self):
"""Should not be able to use 'seed' kwarg."""
with pytest.raises(ValueError):
with pytest.raises(TypeError):
Dimension("yolo", "norm", 0.9, seed=8)

def test_ban_rng_kwarg(self):
"""Should not be able to use 'random_state' kwarg."""
with pytest.raises(ValueError):
with pytest.raises(TypeError):
Dimension("yolo", "norm", 0.9, random_state=8)

def test_with_predefined_dist(self, seed):
Expand All @@ -118,7 +118,7 @@ def test_with_predefined_dist(self, seed):

def test_ban_discrete_kwarg(self):
"""Do not allow use for 'discrete' kwarg, because now there's `_Discrete`."""
with pytest.raises(ValueError) as exc:
with pytest.raises(TypeError) as exc:
Dimension("yolo", "uniform", -3, 4, shape=(4, 4), discrete=True)
assert "pure `_Discrete`" in str(exc.value)

Expand Down Expand Up @@ -699,21 +699,21 @@ def test_fidelity_set_base(self):

def test_min_resources(self):
"""Test that an error is raised if min is smaller than 1"""
with pytest.raises(AttributeError) as exc:
with pytest.raises(ValueError) as exc:
Fidelity("epoch", 0, 2)
assert "Minimum resources must be a positive number." == str(exc.value)

def test_min_max_resources(self):
"""Test that an error is raised if min is larger than max"""
with pytest.raises(AttributeError) as exc:
with pytest.raises(ValueError) as exc:
Fidelity("epoch", 3, 2)
assert "Minimum resources must be smaller than maximum resources." == str(
exc.value
)

def test_base(self):
"""Test that an error is raised if base is smaller than 1"""
with pytest.raises(AttributeError) as exc:
with pytest.raises(ValueError) as exc:
Fidelity("epoch", 1, 2, 0)
assert "Base should be greater than or equal to 1" == str(exc.value)

Expand Down
13 changes: 12 additions & 1 deletion tests/unittests/core/io/test_space_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,17 @@ def test_build_fails_because_of_ValueError_on_init(self, dimbuilder):
assert "Parameter" in str(exc.value)
assert "size" in str(exc.value.__cause__)

def test_build_fails_because_of_invalid_arguments_for_custom_prior(
self, dimbuilder
):
"""Build fails because ValueError happens on init of builtin prior."""
with pytest.raises(ValueError) as exc:
Copy link
Collaborator

@lebrice lebrice May 17, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could use the match argument of raises instead of checking if the value is in the exception message, I think.
(That might be only true for pytest.warns though, not 100% sure).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed. This test is looking at two different parts of exc.value however.

dimbuilder.build("yolo2", "fidelity(0, 10, base=1)")
assert "Parameter" in str(exc.value)
assert "Minimum resources must be a positive number." in str(
exc.value.__cause__
)

def test_build_gaussian(self, dimbuilder):
"""Check that gaussian/normal/norm is built into reciprocal correctly."""
dim = dimbuilder.build("yolo", "gaussian(3, 5)")
Expand Down Expand Up @@ -175,7 +186,7 @@ def test_build_choices(self, dimbuilder):
assert dim._prior_name == "Distribution"
assert isinstance(dim.prior, dists.rv_discrete)

with pytest.raises(TypeError) as exc:
with pytest.raises(ValueError) as exc:
dimbuilder.build("yolo2", "choices({'adfa': 0.1, 3: 0.4})")
assert "Parameter" in str(exc.value)
assert "sum" in str(exc.value.__cause__)
Expand Down
4 changes: 2 additions & 2 deletions tests/unittests/core/test_branch_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -772,9 +772,9 @@ def test_add_bad_default(self, parent_config, new_config_with_w):
-1
] = "-w_d~+normal(0,1,default_value='a')"
backward.populate_space(new_config_with_w)
with pytest.raises(TypeError) as exc:
with pytest.raises(ValueError) as exc:
detect_conflicts(parent_config, new_config_with_w)
assert "Parameter '/w_d': Incorrect arguments." in str(exc.value)
assert "Parameter '/w_d' has incorrect arguments: a is not" in str(exc.value)

def test_add_changed(self, parent_config, changed_config):
"""Test if changed dimension conflict is automatically resolved"""
Expand Down
2 changes: 1 addition & 1 deletion tests/unittests/core/test_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,7 +825,7 @@ def test_validate(self, tdim, tdim2):
tdim2.original_dimension._default_value = "bad-default"

# It does not pass
with pytest.raises(ValueError) as exc:
with pytest.raises(TypeError) as exc:
tdim.validate()
assert "Use 'shape' keyword only instead of 'size'." in str(exc.value)

Expand Down