-
Notifications
You must be signed in to change notification settings - Fork 0
/
_single_namespace.py
67 lines (56 loc) · 2.14 KB
/
_single_namespace.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""Common utilities for classes that manage hyperparameters."""
from typing import Any, Mapping, Optional, Type, Union
from scalarstop.hyperparams import HyperparamsType, hash_hyperparams, init_hyperparams
class SingleNamespace:
"""
A common base class for classes with hyperparameters.
Subclasses of this class takes hyperparameters of
:py:class:`~scalarstop.hyperparams.HyperparamsType` and calculates
hash-based names of the hyperparameters.
"""
Hyperparams: Type[HyperparamsType] = HyperparamsType
hyperparams: HyperparamsType
_group_name: str = ""
_name: str = ""
def __init__(
self,
*,
hyperparams: Optional[Union[Mapping[str, Any], HyperparamsType]] = None,
**kwargs, # pylint: disable=unused-argument
):
"""
Args:
hyperparams: The hyperparameters to initialize this class with.
"""
self.hyperparams = init_hyperparams(
class_name=self.__class__.__name__,
hyperparams=hyperparams,
hyperparams_class=self.Hyperparams,
)
@classmethod
def calculate_name(
cls, *, hyperparams: Optional[Union[Mapping[str, Any], HyperparamsType]] = None
) -> str:
"""
Calculate the hashed name of this object, given the hyperparameters.
This classmethod can be used to calculate what an object would
be without actually having to call ``__init__()``.
"""
hp = init_hyperparams(
class_name=cls.__name__,
hyperparams=hyperparams,
hyperparams_class=cls.Hyperparams,
)
return "-".join((cls.__name__, hash_hyperparams(hp)))
@property
def group_name(self) -> str:
"""The "group" name is this object's Python class name."""
if not self._group_name:
self._group_name = self.__class__.__name__
return self._group_name
@property
def name(self) -> str:
"""The group (class) name and a calculated hash of the hyperparameters."""
if not self._name:
self._name = self.calculate_name(hyperparams=self.hyperparams)
return self._name