Miscellaneous utilities.

ebcc.util.misc.InheritedType

Type for an inherited variable.

ebcc.util.misc.ModelNotImplemented

Bases: NotImplementedError

Error for unsupported models.

ebcc.util.misc.Namespace(**kwargs)

Bases: MutableMapping[str, T], Generic[T]

Namespace class.

Replacement for SimpleNamespace, which does not trivially allow conversion to a dict for heterogenously nested objects.

Attributes can be added and removed, using either string indexing or accessing the attribute directly.

Initialise the namespace.

Source code in ebcc/util/misc.py
def __init__(self, **kwargs: T):
    """Initialise the namespace."""
    self.__dict__["_members"] = {}
    for key, val in kwargs.items():
        self.__dict__["_members"][key] = val

ebcc.util.misc.Namespace.__setitem__(key, val)

Set an item.

Source code in ebcc/util/misc.py
def __setitem__(self, key: str, val: T) -> None:
    """Set an item."""
    self.__dict__["_members"][key] = val

ebcc.util.misc.Namespace.__setattr__(key, val)

Set an attribute.

Source code in ebcc/util/misc.py
def __setattr__(self, key: str, val: T) -> None:
    """Set an attribute."""
    return self.__setitem__(key, val)

ebcc.util.misc.Namespace.__getitem__(key)

Get an item.

Source code in ebcc/util/misc.py
def __getitem__(self, key: str) -> T:
    """Get an item."""
    value: T = self.__dict__["_members"][key]
    return value

ebcc.util.misc.Namespace.__getattr__(key)

Get an attribute.

Source code in ebcc/util/misc.py
def __getattr__(self, key: str) -> T:
    """Get an attribute."""
    if key in self.__dict__:
        return self.__dict__[key]  # type: ignore[no-any-return]
    try:
        return self.__getitem__(key)
    except KeyError:
        raise AttributeError(f"Namespace object has no attribute {key}")

ebcc.util.misc.Namespace.__delitem__(key)

Delete an item.

Source code in ebcc/util/misc.py
def __delitem__(self, key: str) -> None:
    """Delete an item."""
    self._members.pop(key)

ebcc.util.misc.Namespace.__delattr__(key)

Delete an attribute.

Source code in ebcc/util/misc.py
def __delattr__(self, key: str) -> None:
    """Delete an attribute."""
    return self.__delitem__(key)

ebcc.util.misc.Namespace.__iter__()

Iterate over the namespace as a dictionary.

Source code in ebcc/util/misc.py
def __iter__(self) -> Iterator[str]:
    """Iterate over the namespace as a dictionary."""
    yield from self._members

ebcc.util.misc.Namespace.__eq__(other)

Check equality.

Source code in ebcc/util/misc.py
def __eq__(self, other: Any) -> bool:
    """Check equality."""
    if not isinstance(other, Namespace):
        return False
    return dict(self) == dict(other)

ebcc.util.misc.Namespace.__ne__(other)

Check inequality.

Source code in ebcc/util/misc.py
def __ne__(self, other: Any) -> bool:
    """Check inequality."""
    return not self == other

ebcc.util.misc.Namespace.__contains__(key)

Check if an attribute exists.

Source code in ebcc/util/misc.py
def __contains__(self, key: Any) -> bool:
    """Check if an attribute exists."""
    return key in self._members

ebcc.util.misc.Namespace.__len__()

Get the number of attributes.

Source code in ebcc/util/misc.py
def __len__(self) -> int:
    """Get the number of attributes."""
    return len(self._members)

ebcc.util.misc.Namespace.keys()

Get keys of the namespace as a dictionary.

Source code in ebcc/util/misc.py
def keys(self) -> KeysView[str]:
    """Get keys of the namespace as a dictionary."""
    return self._members.keys()

ebcc.util.misc.Namespace.values()

Get values of the namespace as a dictionary.

Source code in ebcc/util/misc.py
def values(self) -> ValuesView[T]:
    """Get values of the namespace as a dictionary."""
    return self._members.values()

ebcc.util.misc.Namespace.items()

Get items of the namespace as a dictionary.

Source code in ebcc/util/misc.py
def items(self) -> ItemsView[str, T]:
    """Get items of the namespace as a dictionary."""
    return self._members.items()

ebcc.util.misc.Namespace.__repr__()

Return a string representation.

Source code in ebcc/util/misc.py
def __repr__(self) -> str:
    """Return a string representation."""
    return f"Namespace({self._members})"

ebcc.util.misc.Timer()

Timer class.

Initialise the timer.

Source code in ebcc/util/misc.py
def __init__(self) -> None:
    """Initialise the timer."""
    self.t_init = time.perf_counter()
    self.t_prev = time.perf_counter()
    self.t_curr = time.perf_counter()

ebcc.util.misc.Timer.lap()

Return the time since the last call to lap.

Source code in ebcc/util/misc.py
def lap(self) -> float:
    """Return the time since the last call to `lap`."""
    self.t_prev, self.t_curr = self.t_curr, time.perf_counter()
    return self.t_curr - self.t_prev

ebcc.util.misc.Timer.total()

Return the total time since initialization.

Source code in ebcc/util/misc.py
def total(self) -> float:
    """Return the total time since initialization."""
    return time.perf_counter() - self.t_init

ebcc.util.misc.Timer.format_time(seconds, precision=2) staticmethod

Return a formatted time.

Source code in ebcc/util/misc.py
@staticmethod
def format_time(seconds: float, precision: int = 2) -> str:
    """Return a formatted time."""

    seconds, milliseconds = divmod(seconds, 1)
    milliseconds *= 1000
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)

    out = []
    if hours:
        out.append("%d h" % hours)
    if minutes:
        out.append("%d m" % minutes)
    if seconds:
        out.append("%d s" % seconds)
    if milliseconds:
        out.append("%d ms" % milliseconds)

    return " ".join(out[-max(precision, len(out)) :])

ebcc.util.misc.prod(values)

Return the product of values.

Source code in ebcc/util/misc.py
def prod(values: Union[list[int], tuple[int, ...]]) -> int:
    """Return the product of values."""
    out = 1
    for value in values:
        out *= value
    return out

ebcc.util.misc.regularise_tuple(*_items)

Regularise the input tuples.

Allows input of the forms - func((a, b, c)) - func([a, b, c]) - func(a, b, c) - func(a)

Parameters:
  • _items (Union[Any, tuple[Any, ...], list[Any]], default: () ) –

    The input tuples.

Returns:
  • tuple[Any, ...]

    The regularised tuple.

Source code in ebcc/util/misc.py
def regularise_tuple(*_items: Union[Any, tuple[Any, ...], list[Any]]) -> tuple[Any, ...]:
    """Regularise the input tuples.

    Allows input of the forms
    - `func((a, b, c))`
    - `func([a, b, c])`
    - `func(a, b, c)`
    - `func(a)`

    Args:
        _items: The input tuples.

    Returns:
        The regularised tuple.
    """
    if isinstance(_items[0], (tuple, list)):
        if len(_items) > 1:
            raise ValueError("Only one tuple can be passed.")
        items = _items[0]
    else:
        items = _items
    return tuple(items)