topobench.utils.rich_utils module#

This module contains utility functions for printing and saving Hydra configs.

class DictConfig(content, key=None, parent=None, ref_type=typing.Any, key_type=typing.Any, element_type=typing.Any, is_optional=True, flags=None)#

Bases: BaseContainer, MutableMapping[Any, Any]

__init__(content, key=None, parent=None, ref_type=typing.Any, key_type=typing.Any, element_type=typing.Any, is_optional=True, flags=None)#
copy()#
get(key, default_value=None)#

Return the value for key if key is in the dictionary, else default_value (defaulting to None).

items() a set-like object providing a view on D's items#
items_ex(resolve=True, keys=None)#
keys() a set-like object providing a view on D's keys#
pop(k[, d]) v, remove specified key and return the corresponding value.#

If key is not found, d is returned if given, otherwise KeyError is raised.

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D#
class HydraConfig(*args, **kwargs)#

Bases: object

__init__()#
static get()#
static initialized()#
static instance(*args, **kwargs)#
set_config(cfg)#
class OmegaConf#

Bases: object

OmegaConf primary class

__init__()#
static clear_cache(conf)#
classmethod clear_resolver(name)#

Clear(remove) any resolver only if it exists.

Returns a bool: True if resolver is removed and False if not removed.

Parameters:

name (str) – Name of the resolver.

Returns:

A bool (True if resolver is removed, False if not found before removing).

Return type:

bool

static clear_resolvers()#

Clear(remove) all OmegaConf resolvers, then re-register OmegaConf’s default resolvers.

static copy_cache(from_config, to_config)#
static create(obj: str, parent: BaseContainer | None = None, flags: Dict[str, bool] | None = None) DictConfig | ListConfig#
static create(obj: List[Any] | Tuple[Any, ...], parent: BaseContainer | None = None, flags: Dict[str, bool] | None = None) ListConfig
static create(obj: DictConfig, parent: BaseContainer | None = None, flags: Dict[str, bool] | None = None) DictConfig
static create(obj: ListConfig, parent: BaseContainer | None = None, flags: Dict[str, bool] | None = None) ListConfig
static create(obj: Dict[Any, Any] | None = None, parent: BaseContainer | None = None, flags: Dict[str, bool] | None = None) DictConfig
static from_cli(args_list=None)#
static from_dotlist(dotlist)#

Creates config from the content sys.argv or from the specified args list of not None

Parameters:

dotlist (List[str]) – A list of dotlist-style strings, e.g. ["foo.bar=1", "baz=qux"].

Returns:

A DictConfig object created from the dotlist.

Return type:

DictConfig

static get_cache(conf)#
static get_type(obj, key=None)#
classmethod has_resolver(name)#
static is_config(obj)#
static is_dict(obj)#
static is_interpolation(node, key=None)#
static is_list(obj)#
static is_missing(cfg, key)#
static is_readonly(conf)#
static is_struct(conf)#
static legacy_register_resolver(name, resolver)#
static load(file_)#
static masked_copy(conf, keys)#

Create a masked copy of of this config that contains a subset of the keys

Parameters:
Returns:

The masked DictConfig object.

Return type:

DictConfig

static merge(*configs)#

Merge a list of previously created configs into a single one

Parameters:

configs (DictConfig | ListConfig | Dict[str | bytes | int | Enum | float | bool, Any] | List[Any] | Tuple[Any, ...] | Any) – Input configs

Returns:

the merged config object.

Return type:

ListConfig | DictConfig

static missing_keys(cfg)#

Returns a set of missing keys in a dotlist style.

Parameters:

cfg (Any) – An OmegaConf.Container, or a convertible object via OmegaConf.create (dict, list, …).

Returns:

set of strings of the missing keys.

Raises:

ValueError – On input not representing a config.

Return type:

Set[str]

static register_new_resolver(name, resolver, *, replace=False, use_cache=False)#

Register a resolver.

Parameters:
  • name (str) – Name of the resolver.

  • resolver (Callable[[...], Any]) – Callable whose arguments are provided in the interpolation, e.g., with ${foo:x,0,${y.z}} these arguments are respectively “x” (str), 0 (int) and the value of y.z.

  • replace (bool) – If set to False (default), then a ValueError is raised if an existing resolver has already been registered with the same name. If set to True, then the new resolver replaces the previous one. NOTE: The cache on existing config objects is not affected, use OmegaConf.clear_cache(cfg) to clear it.

  • use_cache (bool) – Whether the resolver’s outputs should be cached. The cache is based only on the string literals representing the resolver arguments, e.g., ${foo:${bar}} will always return the same value regardless of the value of bar if the cache is enabled for foo.

static register_resolver(name, resolver)#
static resolve(cfg)#

Resolves all interpolations in the given config object in-place.

Parameters:

cfg (Container) – An OmegaConf container (DictConfig, ListConfig) Raises a ValueError if the input object is not an OmegaConf container.

static save(config, f, resolve=False)#

Save as configuration object to a file

Parameters:
  • config (Any) – omegaconf.Config object (DictConfig or ListConfig).

  • f (str | Path | IO[Any]) – filename or file object

  • resolve (bool) – True to save a resolved config (defaults to False)

static select(cfg, key, *, default=_DEFAULT_MARKER_, throw_on_resolution_failure=True, throw_on_missing=False)#
Parameters:
  • cfg (Container) – Config node to select from

  • key (str) – Key to select

  • default (Any) – Default value to return if key is not found

  • throw_on_resolution_failure (bool) – Raise an exception if an interpolation resolution error occurs, otherwise return None

  • throw_on_missing (bool) – Raise an exception if an attempt to select a missing key (with the value ‘???’) is made, otherwise return None

Returns:

selected value or None if not found.

Return type:

Any

static set_cache(conf, cache)#
static set_readonly(conf, value)#
static set_struct(conf, value)#
static structured(obj, parent=None, flags=None)#
static to_container(cfg, *, resolve=False, throw_on_missing=False, enum_to_str=False, structured_config_mode=SCMode.DICT)#

Resursively converts an OmegaConf config to a primitive container (dict or list).

Parameters:
  • cfg (Any) – the config to convert

  • resolve (bool) – True to resolve all values

  • throw_on_missing (bool) – When True, raise MissingMandatoryValue if any missing values are present. When False (the default), replace missing values with the string “???” in the output container.

  • enum_to_str (bool) – True to convert Enum keys and values to strings

  • structured_config_mode (SCMode) –

    Specify how Structured Configs (DictConfigs backed by a dataclass) are handled.
    • By default (structured_config_mode=SCMode.DICT) structured configs are converted to plain dicts.

    • If structured_config_mode=SCMode.DICT_CONFIG, structured config nodes will remain as DictConfig.

    • If structured_config_mode=SCMode.INSTANTIATE, this function will instantiate structured configs (DictConfigs backed by a dataclass), by creating an instance of the underlying dataclass.

    See also OmegaConf.to_object.

Returns:

A dict or a list representing this config as a primitive container.

Return type:

Dict[str | bytes | int | Enum | float | bool, Any] | List[Any] | None | str | Any

static to_object(cfg)#

Resursively converts an OmegaConf config to a primitive container (dict or list). Any DictConfig objects backed by dataclasses or attrs classes are instantiated as instances of those backing classes.

This is an alias for OmegaConf.to_container(…, resolve=True, throw_on_missing=True,

structured_config_mode=SCMode.INSTANTIATE)

Parameters:

cfg (Any) – the config to convert

Returns:

A dict or a list or dataclass representing this config.

Return type:

Dict[str | bytes | int | Enum | float | bool, Any] | List[Any] | None | str | Any

static to_yaml(cfg, *, resolve=False, sort_keys=False)#

returns a yaml dump of this config object.

Parameters:
  • cfg (Any) – Config object, Structured Config type or instance

  • resolve (bool) – if True, will return a string with the interpolations resolved, otherwise interpolations are preserved

  • sort_keys (bool) – If True, will print dict keys in sorted order. default False.

Returns:

A string containing the yaml representation.

Return type:

str

static unsafe_merge(*configs)#

Merge a list of previously created configs into a single one This is much faster than OmegaConf.merge() as the input configs are not copied. However, the input configs must not be used after this operation as will become inconsistent.

Parameters:

configs (DictConfig | ListConfig | Dict[str | bytes | int | Enum | float | bool, Any] | List[Any] | Tuple[Any, ...] | Any) – Input configs

Returns:

the merged config object.

Return type:

ListConfig | DictConfig

static update(cfg, key, value=None, *, merge=True, force_add=False)#

Updates a dot separated key sequence to a value

Parameters:
  • cfg (Container) – input config to update

  • key (str) – key to update (can be a dot separated path)

  • value (Any) – value to set, if value if a list or a dict it will be merged or set depending on merge_config_values

  • merge (bool) – If value is a dict or a list, True (default) to merge into the destination, False to replace the destination.

  • force_add (bool) – insert the entire path regardless of Struct flag or Structured Config nodes.

class Path(*args, **kwargs)#

Bases: PurePath

PurePath subclass that can make system calls.

Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.

absolute()#

Return an absolute version of this path by prepending the current working directory. No normalization or symlink resolution is performed.

Use resolve() to get the canonical path to a file.

chmod(mode, *, follow_symlinks=True)#

Change the permissions of the path, like os.chmod().

classmethod cwd()#

Return a new path pointing to the current working directory (as returned by os.getcwd()).

exists()#

Whether this path exists.

expanduser()#

Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)

glob(pattern)#

Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

group()#

Return the group name of the file gid.

Make this path a hard link pointing to the same file as target.

Note the order of arguments (self, target) is the reverse of os.link’s.

classmethod home()#

Return a new path pointing to the user’s home directory (as returned by os.path.expanduser(‘~’)).

is_block_device()#

Whether this path is a block device.

is_char_device()#

Whether this path is a character device.

is_dir()#

Whether this path is a directory.

is_fifo()#

Whether this path is a FIFO.

is_file()#

Whether this path is a regular file (also True for symlinks pointing to regular files).

is_mount()#

Check if this path is a POSIX mount point

is_socket()#

Whether this path is a socket.

Whether this path is a symbolic link.

iterdir()#

Iterate over the files in this directory. Does not yield any result for the special paths ‘.’ and ‘..’.

lchmod(mode)#

Like chmod(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.

Make the target path a hard link pointing to this path.

Note this function does not make this path a hard link to target, despite the implication of the function and argument names. The order of arguments (target, link) is the reverse of Path.symlink_to, but matches that of os.link.

Deprecated since Python 3.10 and scheduled for removal in Python 3.12. Use hardlink_to() instead.

lstat()#

Like stat(), except if the path points to a symlink, the symlink’s status information is returned, rather than its target’s.

mkdir(mode=511, parents=False, exist_ok=False)#

Create a new directory at this given path.

open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)#

Open the file pointed by this path and return a file object, as the built-in open() function does.

owner()#

Return the login name of the file owner.

read_bytes()#

Open the file in bytes mode, read it, and close the file.

read_text(encoding=None, errors=None)#

Open the file in text mode, read it, and close the file.

Return the path to which the symbolic link points.

rename(target)#

Rename this path to the target path.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

replace(target)#

Rename this path to the target path, overwriting if that path exists.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

resolve(strict=False)#

Make the path absolute, resolving all symlinks on the way and also normalizing it.

rglob(pattern)#

Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

rmdir()#

Remove this directory. The directory must be empty.

samefile(other_path)#

Return whether other_path is the same or not as this file (as returned by os.path.samefile()).

stat(*, follow_symlinks=True)#

Return the result of the stat() system call on this path, like os.stat() does.

Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink.

touch(mode=438, exist_ok=True)#

Create this file with the given access mode, if it doesn’t exist.

Remove this file or link. If the path is a directory, use rmdir() instead.

write_bytes(data)#

Open the file in bytes mode, write to it, and close the file.

write_text(data, encoding=None, errors=None, newline=None)#

Open the file in text mode, write to it, and close the file.

class Prompt(prompt='', *, console=None, password=False, choices=None, case_sensitive=True, show_default=True, show_choices=True)#

Bases: PromptBase[str]

A prompt that returns a str.

Example

>>> name = Prompt.ask("Enter your name")
response_type#

alias of str

class Sequence#

Bases: Reversible, Collection

All the operations on a read-only sequence.

Concrete subclasses must override __new__ or __init__, __getitem__, and __len__.

count(value) integer -- return number of occurrences of value#
index(value[, start[, stop]]) integer -- return first index of value.#

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

enforce_tags(cfg, save_to_file=False)#

Prompt user to input tags from terminal if no tags are provided in config.

Parameters:
cfgDictConfig

A DictConfig composed by Hydra.

save_to_filebool, optional

Whether to export tags to the hydra output folder (default: False).

open_dict(config)#
print_config_tree(cfg, print_order=('dataset', 'model', 'transforms', 'callbacks', 'logger', 'trainer', 'paths', 'extras'), resolve=False, save_to_file=False)#

Print the contents of a DictConfig using the Rich library.

Parameters:
cfgDictConfig

A DictConfig object containing the config tree.

print_orderSequence[str], optional

Determines in what order config components are printed, by default (“data”, “model”, “callbacks”, “logger”, “trainer”, “paths”, “extras”).

resolvebool, optional

Whether to resolve reference fields of DictConfig, by default False.

save_to_filebool, optional

Whether to export config to the hydra output folder, by default False.

rank_zero_only(fn, default=None)#

Wrap a function to call internal function only in rank zero.

Function that can be used as a decorator to enable a function/method being called only on global rank 0.