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

Detect _param_names from __init__ signature #867

Merged
merged 2 commits into from
Mar 31, 2022
Merged
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: 11 additions & 1 deletion src/orion/algo/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"""
import copy
import hashlib
import inspect
import logging
from abc import ABCMeta, abstractmethod

Expand Down Expand Up @@ -108,7 +109,16 @@ def __init__(self, space, **kwargs):
)
self._trials_info = {} # Stores Unique Trial -> Result
self._space = space
self._param_names = list(kwargs.keys())
if kwargs:
param_names = list(kwargs)
else:
init_signature = inspect.signature(type(self))
param_names = [
name
for name, param in init_signature.parameters.items()
if name != "space" and param.kind != param.VAR_KEYWORD
]
self._param_names = param_names
# Instantiate tunable parameters of an algorithm
for varname, param in kwargs.items():
setattr(self, varname, param)
Expand Down
35 changes: 35 additions & 0 deletions tests/unittests/algo/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
# -*- coding: utf-8 -*-
"""Example usage and tests for :mod:`orion.algo.base`."""

import pytest

from orion.algo.base import BaseAlgorithm
from orion.algo.space import Integer, Real, Space
from orion.core.utils import backward, format_trials

Expand Down Expand Up @@ -108,3 +111,35 @@ def test_is_done_max_trials(monkeypatch, dumbalgo):

dumbalgo.max_trials = 4
assert algo.is_done


@pytest.mark.parametrize("pass_to_super", [True, False])
def test_arg_names(pass_to_super: bool):
"""Test that the `_arg_names` can be determined programmatically when the args aren't passed to
`super().__init__(space, **kwargs)`.

Also checks that the auto-generated configuration dict acts the same way.
"""

class SomeAlgo(BaseAlgorithm):
def __init__(self, space, foo: int = 123, bar: str = "heyo"):
if pass_to_super:
super().__init__(space, foo=foo, bar=bar)
else:
super().__init__(space)
self.foo = foo
self.bar = bar
# Param names should be correct, either way.
assert self._param_names == ["foo", "bar"]
# Attributes should be set correctly either way:
assert self.foo == foo
assert self.bar == bar

space = Space(x=Real("yolo1", "uniform", 1, 4))
algo = SomeAlgo(space, foo=111, bar="barry")
assert algo.configuration == {
"somealgo": {
"bar": "barry",
"foo": 111,
}
}