anemoi.utils package
Anemoi Utils package.
Subpackages
- anemoi.utils.commands package
- anemoi.utils.mars package
- anemoi.utils.mlflow package
- anemoi.utils.remote package
robust()LoaderBaseDownloadBaseUploadTransferMethodNotImplementedErrorTransfertransfer()- Submodules
- anemoi.utils.remote.s3 module
- anemoi.utils.remote.ssh module
- anemoi.utils.schemas package
Submodules
anemoi.utils.caching module
- anemoi.utils.caching.clean_cache(collection: str = 'default') None
Clean the cache for a collection.
This removes all cached data files and their associated lock files.
- Parameters:
collection (str, optional) – The name of the collection, by default “default”
- class anemoi.utils.caching.Cacher(collection: str, expires: int | None)
Bases:
objectThis class implements a simple caching mechanism. Private class, do not use directly.
- class anemoi.utils.caching.JsonCacher(collection: str, expires: int | None)
Bases:
CacherCacher that uses JSON files.
- ext = ''
- class anemoi.utils.caching.NpzCacher(collection: str, expires: int | None)
Bases:
CacherCacher that uses NPZ files.
- ext = '.npz'
- anemoi.utils.caching.cached(collection: str = 'default', expires: int | None = None, encoding: str = 'json') Callable
Decorator to cache the result of a function.
Default is to use a json file to store the cache, but you can also use npz files to cache dict of numpy arrays.
- Parameters:
- Returns:
The decorated function
- Return type:
Callable
anemoi.utils.checkpoints module
Read and write extra metadata in PyTorch checkpoints files. These files are zip archives containing the model weights.
- anemoi.utils.checkpoints.has_metadata(path: str, *, name: str = 'anemoi.json') bool
Check if a checkpoint file has a metadata file.
- anemoi.utils.checkpoints.get_metadata_path(path: str, *, name: str = 'anemoi.json') str
Get the full path of the metadata file in the checkpoint.
- Parameters:
- Returns:
The full path of the metadata file in the zip archive
- Return type:
- Raises:
FileNotFoundError – If the metadata file is not found
ValueError – If multiple metadata files are found
- anemoi.utils.checkpoints.load_metadata(path: str, *, supporting_arrays: Literal[False] = False, name: str = DEFAULT_NAME) dict
- anemoi.utils.checkpoints.load_metadata(path: str, *, supporting_arrays: Literal[True] = True, name: str = DEFAULT_NAME) tuple[dict, dict]
Load metadata from a checkpoint file.
- Parameters:
- Returns:
The content of the metadata file from JSON
- Return type:
- Raises:
ValueError – If the metadata file is not found
- anemoi.utils.checkpoints.load_supporting_arrays(zipf: ZipFile, entries: dict) dict
Load supporting arrays from a zip file.
- Parameters:
zipf (zipfile.ZipFile) – The zip file
entries (dict) – A dictionary of entries with paths, shapes, and dtypes
- Returns:
A dictionary of supporting arrays
- Return type:
- anemoi.utils.checkpoints.save_metadata(path: str, metadata: dict, *, supporting_arrays: dict | None = None, name: str = 'anemoi.json', folder: str = 'anemoi-metadata') None
Save metadata to a checkpoint file.
- Parameters:
path (str) – The path to the checkpoint file
metadata (dict) – A JSON serializable object
supporting_arrays (dict | None, optional) – A dictionary of supporting NumPy arrays
name (str, optional) – The name of the metadata file in the zip archive
folder (str, optional) – The folder where the metadata file will be saved
anemoi.utils.cli module
- class anemoi.utils.cli.Command
Bases:
objectBase class for commands.
- accept_unknown_args = False
- check(parser: ArgumentParser, args: Namespace) None
Check the command arguments.
- run(args: Namespace) None
Run the command.
- Parameters:
args (argparse.Namespace) – The arguments for the command
- anemoi.utils.cli.make_parser(description: str, commands: dict[str, Command]) ArgumentParser
Create an argument parser for the CLI.
- Parameters:
- Returns:
The argument parser
- Return type:
- class anemoi.utils.cli.Failed(name: str, error: ImportError)
Bases:
CommandCommand not available.
- add_arguments(command_parser: ArgumentParser) None
Add arguments to the command parser.
- Parameters:
command_parser (argparse.ArgumentParser) – The command parser
- run(args: Namespace) None
Run the command.
- Parameters:
args (argparse.Namespace) – The arguments for the command
- anemoi.utils.cli.register_commands(here: str, package: str, select: Callable, fail: Callable = None) dict[str, Command]
Register commands from a package.
- Parameters:
- Returns:
A dictionary of command names to Command instances
- Return type:
anemoi.utils.compatibility module
- anemoi.utils.compatibility.aliases(aliases: dict[str, str | list[str]] | None = None, **kwargs: Any) Callable[[Callable], Callable]
Alias keyword arguments in a function call.
Allows for dynamically renaming keyword arguments in a function call.
- Parameters:
- Returns:
Decorator function that renames keyword arguments in a function call.
- Return type:
Callable
- Raises:
ValueError – If the aliasing would result in duplicate keys.
Examples
```python @aliases(a=”b”, c=[“d”, “e”]) def func(a, c):
return a, c
anemoi.utils.config module
- class anemoi.utils.config.DotDict(*args, **kwargs)
Bases:
dictA dictionary that allows access to its keys as attributes.
>>> d = DotDict({"a": 1, "b": {"c": 2}}) >>> d.a 1 >>> d.b.c 2 >>> d.b = 3 >>> d.b 3
The class is recursive, so nested dictionaries are also DotDicts.
The DotDict class has the same constructor as the dict class.
>>> d = DotDict(a=1, b=2)
- static convert_to_nested_dot_dict(value: Any) Any
Convert nested dicts to DotDict recursively.
- Parameters:
value (Any) – The value to convert
- Returns:
Converted value with nested dicts as DotDict
- Return type:
Any
- anemoi.utils.config.is_omegaconf_dict(value: Any) bool
Check if a value is an OmegaConf DictConfig.
- Parameters:
value (Any) – The value to check.
- Returns:
True if the value is a DictConfig, False otherwise.
- Return type:
- anemoi.utils.config.is_omegaconf_list(value: Any) bool
Check if a value is an OmegaConf ListConfig.
- Parameters:
value (Any) – The value to check.
- Returns:
True if the value is a ListConfig, False otherwise.
- Return type:
- anemoi.utils.config.config_path(name: str = 'settings.toml') str
Get the path to a configuration file.
- anemoi.utils.config.load_any_dict_format(path: str) dict
Load a configuration file in any supported format: JSON, YAML and TOML.
- anemoi.utils.config.save_config(name: str, data: Any) None
Save a configuration file.
- Parameters:
name (str) – The name of the configuration file to save.
data (Any) – The data to save.
- anemoi.utils.config.load_config(name: str = 'settings.toml', secrets: str | list[str] | None = None, defaults: str | dict | None = None) DotDict | str
Read a configuration file.
- Parameters:
- Returns:
Return DotDict if it is a dictionary, otherwise the raw data
- Return type:
- anemoi.utils.config.load_raw_config(name: str, default: Any = None) DotDict | str
Load a raw configuration file.
- anemoi.utils.config.check_config_mode(name: str = 'settings.toml', secrets_name: str = None, secrets: list[str] = None) None
Check that a configuration file is secure.
- Parameters:
- Raises:
SystemError – If the configuration file is not secure.
- anemoi.utils.config.find(metadata: dict | list, what: str, result: list = None, *, select: callable = None) list
Find all occurrences of a key in a nested dictionary or list with an optional selector.
- Parameters:
- Returns:
The list of found values.
- Return type:
anemoi.utils.dates module
- anemoi.utils.dates.as_datetime(date: date | datetime | str, keep_time_zone: bool = False) datetime
Convert a date to a datetime object, removing any time zone information.
- Parameters:
date (datetime.date or datetime.datetime or str) – The date to convert.
keep_time_zone (bool, optional) – If True, the time zone information is kept, by default False.
- Returns:
The datetime object.
- Return type:
- anemoi.utils.dates.as_datetime_list(date: date | datetime | str, default_increment: int = 1) list[datetime]
Convert a date to a list of datetime objects.
- Parameters:
date (datetime.date or datetime.datetime or str) – The date to convert.
default_increment (int, optional) – The default increment in hours, by default 1.
- Returns:
A list of datetime objects.
- Return type:
- anemoi.utils.dates.as_timedelta(frequency: int | str | timedelta) timedelta
Convert anything to a timedelta object.
- Parameters:
frequency (int or str or datetime.timedelta) –
The frequency to convert. If an integer, it is assumed to be in hours. If a string, it can be in the format:
”1h” for 1 hour
”1d” for 1 day
”1m” for 1 minute
”1s” for 1 second
”1:30” for 1 hour and 30 minutes
”1:30:10” for 1 hour, 30 minutes and 10 seconds
”PT10M” for 10 minutes (ISO8601)
If a timedelta object is provided, it is returned as is.
- Returns:
The timedelta object.
- Return type:
- Raises:
ValueError – Exception raised if the frequency cannot be converted to a timedelta.
- anemoi.utils.dates.frequency_to_timedelta(frequency: int | str | timedelta) timedelta
Convert a frequency to a timedelta object.
- Parameters:
frequency (int or str or datetime.timedelta) – The frequency to convert.
- Returns:
The timedelta object.
- Return type:
- anemoi.utils.dates.frequency_to_string(frequency: timedelta) str
Convert a frequency (i.e. a datetime.timedelta) to a string.
- Parameters:
frequency (datetime.timedelta) – The frequency to convert.
- Returns:
A string representation of the frequency.
- Return type:
- anemoi.utils.dates.frequency_to_seconds(frequency: int | str | timedelta) int
Convert a frequency to seconds.
- Parameters:
frequency (int or str or datetime.timedelta) – The frequency to convert.
- Returns:
Number of seconds.
- Return type:
- class anemoi.utils.dates.DateTimes(start: date | datetime | str, end: date | datetime | str, increment: int = 24, *, day_of_month: tuple[int, list[int]] | None = None, day_of_week: tuple[str, list[str]] | None = None, calendar_months: int | str | list[int | str] | None = None)
Bases:
objectThe DateTimes class is an iterator that generates datetime objects within a given range.
- class anemoi.utils.dates.Year(year: int, **kwargs)
Bases:
DateTimesYear is defined as the months of January to December.
- class anemoi.utils.dates.Winter(year: int, **kwargs)
Bases:
DateTimesWinter is defined as the months of December, January and February.
- class anemoi.utils.dates.Spring(year: int, **kwargs)
Bases:
DateTimesSpring is defined as the months of March, April and May.
- class anemoi.utils.dates.Summer(year: int, **kwargs)
Bases:
DateTimesSummer is defined as the months of June, July and August.
- class anemoi.utils.dates.Autumn(year: int, **kwargs)
Bases:
DateTimesAutumn is defined as the months of September, October and November.
- class anemoi.utils.dates.ConcatDateTimes(*dates: DateTimes)
Bases:
objectConcatDateTimes is an iterator that generates datetime objects from a list of dates.
- class anemoi.utils.dates.EnumDateTimes(dates: list[date | datetime | str])
Bases:
objectEnumDateTimes is an iterator that generates datetime objects from a list of dates.
- anemoi.utils.dates.datetimes_factory(*args: Any, **kwargs: Any) DateTimes | ConcatDateTimes | EnumDateTimes
Create a DateTimes, ConcatDateTimes, or EnumDateTimes object.
- Parameters:
*args (Any) – Positional arguments.
**kwargs (Any) – Keyword arguments.
- Returns:
The created object.
- Return type:
anemoi.utils.devtools module
anemoi.utils.grib module
Utilities for working with GRIB parameters.
See https://codes.ecmwf.int/grib/param-db/ for more information.
- class anemoi.utils.grib.LazyConfig
Bases:
object
- anemoi.utils.grib.shortname_to_paramid(shortname: str, **filters) int
Return the GRIB parameter id given its shortname.
- Parameters:
shortname (str) – Parameter shortname.
filters (Any) – Additional filters to disambiguate parameters with the same shortname (e.g. origin, encoding, table, discipline, category).
- Returns:
int – Parameter id.
>>> shortname_to_paramid(“2t”)
167
- anemoi.utils.grib.paramid_to_shortname(paramid: int, **filters) str
Return the shortname of a GRIB parameter given its id.
- Parameters:
paramid (int) – Parameter id.
filters (Any) – Additional filters to disambiguate parameters with the same shortname (e.g. origin, encoding, table, discipline, category).
- Returns:
str – Parameter shortname.
>>> paramid_to_shortname(167)
’2t’
anemoi.utils.grids module
Utilities for working with grids.
- anemoi.utils.grids.xyz_to_latlon(x: ndarray, y: ndarray, z: ndarray) tuple[ndarray, ndarray]
Convert Cartesian coordinates to latitude and longitude.
- Parameters:
x (np.ndarray) – The x coordinates
y (np.ndarray) – The y coordinates
z (np.ndarray) – The z coordinates
- Returns:
The latitude and longitude
- Return type:
tuple[np.ndarray, np.ndarray]
Deprecated since version 0.4.25: This will be removed in 0.5.0. Use anemoi.transform.spatial.xyz_to_latlon instead.
- anemoi.utils.grids.latlon_to_xyz(lat: ndarray, lon: ndarray, radius: float = 1.0) tuple[ndarray, ndarray, ndarray]
Convert latitude and longitude to Cartesian coordinates.
- Parameters:
lat (np.ndarray) – The latitudes
lon (np.ndarray) – The longitudes
radius (float, optional) – The radius of the sphere, by default 1.0
- Returns:
The x, y, and z coordinates
- Return type:
tuple[np.ndarray, np.ndarray, np.ndarray]
Deprecated since version 0.4.25: This will be removed in 0.5.0. Use anemoi.transform.spatial.xyz_to_latlon instead.
- anemoi.utils.grids.nearest_grid_points(source_latitudes: ndarray, source_longitudes: ndarray, target_latitudes: ndarray, target_longitudes: ndarray) ndarray
Find the nearest grid points.
- Parameters:
source_latitudes (np.ndarray) – The source latitudes
source_longitudes (np.ndarray) – The source longitudes
target_latitudes (np.ndarray) – The target latitudes
target_longitudes (np.ndarray) – The target longitudes
- Returns:
The indices of the nearest grid points
- Return type:
np.ndarray
Deprecated since version 0.4.25: This will be removed in 0.5.0. Use anemoi.transform.spatial.nearest_grid_points instead.
anemoi.utils.hindcasts module
anemoi.utils.humanize module
Generate human readable strings.
- anemoi.utils.humanize.bytes_to_human(n: float) str
Convert a number of bytes to a human readable string.
>>> bytes_to_human(4096) '4 KiB'
>>> bytes_to_human(4000) '3.9 KiB'
- anemoi.utils.humanize.bytes(n: float) str
Deprecated function to convert bytes to a human readable string.
- anemoi.utils.humanize.base2_to_human(n: float) str
Convert a number to a human readable string using base 2 units.
- anemoi.utils.humanize.base2(n: float) str
Deprecated function to convert a number to a human readable string using base 2 units.
- anemoi.utils.humanize.seconds_to_human(seconds: float | timedelta) str
Convert a number of seconds to a human readable string.
>>> seconds_to_human(4000) '1 hour 6 minutes 40 seconds'
- anemoi.utils.humanize.seconds(seconds: float) str
Deprecated function to convert seconds to a human readable string.
- anemoi.utils.humanize.plural(value: int, what: str) str
Return a string with the value and the pluralized form of what.
- anemoi.utils.humanize.when(then: datetime, now: datetime | None = None, short: bool = True, use_utc: bool = False) str
Generate a human readable string for a date, relative to now.
>>> when(datetime.datetime.now() - datetime.timedelta(hours=2)) '2 hours ago'
>>> when(datetime.datetime.now() - datetime.timedelta(days=1)) 'yesterday at 08:46'
>>> when(datetime.datetime.now() - datetime.timedelta(days=5)) 'last Sunday'
>>> when(datetime.datetime.now() - datetime.timedelta(days=365)) 'last year'
>>> when(datetime.datetime.now() + datetime.timedelta(days=365)) 'next year'
- Parameters:
then (datetime.datetime) – A datetime
now (datetime.datetime, optional) – The reference date, by default NOW
short (bool, optional) – Generate shorter strings, by default True
use_utc (bool, optional) – Use UTC time, by default False
- Returns:
A human readable string
- Return type:
- anemoi.utils.humanize.string_distance(s: str, t: str) int
Calculate the Levenshtein distance between two strings.
- anemoi.utils.humanize.did_you_mean(word: str, vocabulary: list[str]) str
Pick the closest word in a vocabulary.
>>> did_you_mean("aple", ["banana", "lemon", "apple", "orange"]) 'apple'
- anemoi.utils.humanize.dict_to_human(query: dict[str, Any]) str
Convert a dictionary to a human readable string.
- anemoi.utils.humanize.list_to_human(lst: list[str], conjunction: str = 'and') str
Convert a list of strings to a human readable string.
>>> list_to_human(["banana", "lemon", "apple", "orange"]) 'banana, lemon, apple and orange'
- anemoi.utils.humanize.human_to_number(value: str | int, name: str, units: dict[str, int], none_ok: bool) int | None
Convert a human readable string to a number.
- anemoi.utils.humanize.as_number(value: str | int, name: str | None = None, units: dict[str, int] | None = None, none_ok: bool = False) int | None
Deprecated function to convert a human readable string to a number.
- anemoi.utils.humanize.human_seconds(value: str | int, name: str | None = None, none_ok: bool = False) int | None
Convert a human readable string to seconds.
- anemoi.utils.humanize.as_seconds(value: str | int, name: str | None = None, none_ok: bool = False) int | None
Deprecated function to convert a human readable string to seconds.
- anemoi.utils.humanize.human_to_percent(value: str | int, name: str | None = None, none_ok: bool = False) int | None
Convert a human readable string to a percentage.
- anemoi.utils.humanize.as_percent(value: str | int, name: str | None = None, none_ok: bool = False) int | None
Deprecated function to convert a human readable string to a percentage.
- anemoi.utils.humanize.human_to_bytes(value: str | int, name: str | None = None, none_ok: bool = False) int | None
Convert a human readable string to bytes.
- anemoi.utils.humanize.as_bytes(value: str | int, name: str | None = None, none_ok: bool = False) int | None
Deprecated function to convert a human readable string to bytes.
- anemoi.utils.humanize.human_to_timedelta(value: str, name: str | None = None, none_ok: bool = False) timedelta
Convert a human readable string to a timedelta.
- Parameters:
- Returns:
The converted value as a timedelta
- Return type:
- anemoi.utils.humanize.as_timedelta(value: str, name: str | None = None, none_ok: bool = False) timedelta
Deprecated function to convert a human readable string to a timedelta.
- Parameters:
- Returns:
The converted value as a timedelta
- Return type:
- anemoi.utils.humanize.rounded_datetime(d: datetime) datetime
Round a datetime to the nearest second.
- Parameters:
d (datetime.datetime) – The datetime to round
- Returns:
The rounded datetime
- Return type:
- anemoi.utils.humanize.json_pretty_dump(obj: Any, max_line_length: int = 120, default: Callable = <class 'str'>) str
Custom JSON dump function that keeps dicts and lists on one line if they are short enough.
- anemoi.utils.humanize.shorten_list(lst: list[Any] | tuple[Any], max_length: int = 5) list[Any] | tuple[Any]
Shorten a list to a maximum length.
- anemoi.utils.humanize.compress_dates(dates: list[datetime | str]) str
Compress a list of dates into a human-readable format.
- anemoi.utils.humanize.print_dates(dates: list[datetime | str]) None
Print a list of dates in a human-readable format.
- Parameters:
dates (list) – A list of dates, as datetime objects or strings.
- anemoi.utils.humanize.make_list_int(value: str | list[int] | tuple[int] | int) list[int]
Convert a value to a list of integers.
Handles slash-separated strings including MARS-style range notation:
"1/2/3","1/to/3", and"1/to/10/by/2".- Parameters:
value (str, list, tuple, or int) – The value to convert to a list of integers.
- Returns:
A list of integers.
- Return type:
- Raises:
ValueError – If the value cannot be converted to a list of integers.
Examples
>>> make_list_int("1/2/3") [1, 2, 3] >>> make_list_int("0/to/6") [0, 1, 2, 3, 4, 5, 6] >>> make_list_int("0/to/12/by/6") [0, 6, 12]
anemoi.utils.logs module
Logging utilities.
- anemoi.utils.logs.set_logging_name(name: str) None
Set the logging name for the current thread.
- Parameters:
name (str) – The name to set for logging.
- class anemoi.utils.logs.ThreadCustomFormatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)
Bases:
FormatterCustom logging formatter that includes thread-specific logging names.
- format(record: LogRecord) str
Format the log record to include the thread-specific logging name.
- Parameters:
record (logging.LogRecord) – The log record to format.
- Returns:
The formatted log record.
- Return type:
anemoi.utils.provenance module
Collect information about the current environment, like:
The Python version
The versions of the modules which are currently loaded
The git information for the modules which are currently loaded from a git repository
…
- anemoi.utils.provenance.editable_installs() dict[str, Path]
Return a dictionary of editable installs.
The check relies on how editable installs are handled based on PEP610. A <path-to-venv>/lib/site-packages/<package>.dist-info/direct_url.json file should be present.
- anemoi.utils.provenance.is_editable_install(init_path: str | Path) bool
Determine if the given path corresponds to an editable install.
- anemoi.utils.provenance.lookup_git_repo(path: str) Any | None
Lookup the git repository for a given path.
- Parameters:
path (str) – The path to lookup.
- Returns:
The git repository if found, otherwise None.
- Return type:
Repo, optional
- anemoi.utils.provenance.package_distributions() dict[str, list[str]]
Get the package distributions.
- Returns:
The package distributions.
- Return type:
- anemoi.utils.provenance.import_name_to_distribution_name(packages: list[str]) dict[str, str]
Convert import names to distribution names.
- anemoi.utils.provenance.module_versions(full: bool) tuple[dict[str, Any], dict[str, Any]]
Collect version information for all loaded modules and their git information.
- anemoi.utils.provenance.git_check(*args: Any) dict[str, Any]
Return the git information for the given arguments.
- Arguments can be:
an empty list, in that case all loaded modules are checked
a module name
a module object
an object or a class
a path to a directory
- Parameters:
args (list) – The list of arguments to check
- Returns:
An object with the git information for the given arguments.
>>> { "anemoi.utils": { "sha1": "c999d83ae283bcbb99f68d92c42d24315922129f", "remotes": [ "git@github.com:ecmwf/anemoi-utils.git" ], "modified_files": [ "anemoi/utils/checkpoints.py" ], "untracked_files": [] } }
- Return type:
- anemoi.utils.provenance.platform_info() dict[str, Any]
Get the platform information.
- Returns:
The platform information.
- Return type:
- anemoi.utils.provenance.assets_info(paths: list[str]) dict[str, Any]
Get information about the given assets.
anemoi.utils.registry module
- class anemoi.utils.registry.Wrapper(name: str, registry: Registry)
Bases:
Generic[T]A wrapper for the registry.
- class anemoi.utils.registry.Error(error: Exception)
Bases:
objectAn error class. Used in place of a plugin that failed to load.
- Parameters:
error (Exception) – The error.
- class anemoi.utils.registry.Registry(package: str, key: str = '_type', api_version: str = '1.0.0')
Bases:
Generic[T]A registry of factories.
- Parameters:
- register(name: str, factory: Callable[[...], T], source: Any | None = None, aliases: list[str] | None = None) None
- register(name: str, factory: None = None, source: Any | None = None, aliases: list[str] | None = None) Wrapper
Register a factory with the registry.
- Parameters:
- Returns:
A wrapper if the factory is None, otherwise None.
- Return type:
Wrapper, optional
- create(name: str, *args: Any, **kwargs: Any) T
Create an instance using a factory.
- Parameters:
name (str) – The name of the factory.
*args (Any) – Positional arguments for the factory.
**kwargs (Any) – Keyword arguments for the factory.
- Returns:
The created instance.
- Return type:
Any
- from_config(config: str | dict[str, Any], *args: Any, **kwargs: Any) T
Create an instance from a configuration.
- aliases()
Get the aliases.
anemoi.utils.rules module
- class anemoi.utils.rules.Rule(match: dict[str, Any], result: Any)
Bases:
object
- class anemoi.utils.rules.RuleSet(rules: list[Rule | dict[str, Any] | list[Any]])
Bases:
object- classmethod from_list(rules: list[Any]) RuleSet
Create a RuleSet from a list of rules.
- Parameters:
rules (List[Any]) – A list of rules to initialize the RuleSet.
- Returns:
A new RuleSet object.
- Return type:
- classmethod from_files(path: str) RuleSet
Create a RuleSet from a file.
- Parameters:
path (str) – The path to the file containing the rules. Supported formats are .json and .yaml/.yml.
- Returns:
A new RuleSet object.
- Return type:
- Raises:
ValueError – If the file format is unsupported.
- classmethod from_any(rules: str | list[Any]) RuleSet
Create a RuleSet from a list or a file path.
- Parameters:
rules (Union[str, List[Any]]) – The rules to initialize the RuleSet, either as a list or a file path.
- Returns:
A new RuleSet object.
- Return type:
- Raises:
ValueError – If the rules format is unsupported.
anemoi.utils.s3 module
- anemoi.utils.s3.s3_client(*args: Any, **kwargs: Any) Any
Create an S3 client.
- Parameters:
*args (Any) – Positional arguments for the S3 client.
**kwargs (Any) – Keyword arguments for the S3 client.
- Returns:
The S3 client.
- Return type:
Any
- anemoi.utils.s3.upload(source: str, target: str, *, overwrite: bool = False, resume: bool = False, verbosity: int = 1, progress: Callable | None = None, threads: int = 1) None
Upload a file to S3.
- Parameters:
source (str) – The source file path.
target (str) – The target S3 path.
overwrite (bool, optional) – Whether to overwrite the target file, by default False.
resume (bool, optional) – Whether to resume a previous upload, by default False.
verbosity (int, optional) – The verbosity level, by default 1.
progress (Callable, optional) – A callback function for progress updates, by default None.
threads (int, optional) – The number of threads to use, by default 1.
anemoi.utils.sanitise module
- anemoi.utils.sanitise.sanitise(obj: Any, level=1) Any
Sanitise an object by replacing all full paths with shortened versions and URL credentials with ‘***’.
- Parameters:
obj (Any) – The object to sanitise.
level (int, optional) – The level of sanitation. The higher levels will also apply the levels below it. - 1: Shorten file paths to file name and hide credentials in URLs (default). - 2: Hide hostnames in URLs. - 3: Hide full file paths and URLs.
- Returns:
The sanitised object.
- Return type:
Any
anemoi.utils.sanitize module
- anemoi.utils.sanitize.sanitize(obj: Any, level=1) Any
Sanitise an object by replacing all full paths with shortened versions and URL credentials with ‘***’.
- Parameters:
obj (Any) – The object to sanitise.
level (int, optional) – The level of sanitation. The higher levels will also apply the levels below it. - 1: Shorten file paths to file name and hide credentials in URLs (default). - 2: Hide hostnames in URLs. - 3: Hide full file paths and URLs.
- Returns:
The sanitised object.
- Return type:
Any
anemoi.utils.testing module
anemoi.utils.text module
Text utilities.
- anemoi.utils.text.dotted_line(width: int = 84) str
Return a dotted line using ‘┈’.
>>> dotted_line(40) ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
- anemoi.utils.text.visual_len(s: str | list[tuple[str, int]]) int
Compute the length of a string as it appears on the terminal.
- anemoi.utils.text.boxed(text: str, min_width: int = 80, max_width: int = 80) str
Put a box around a text.
>>> boxed("Hello,\nWorld!", max_width=40) ┌──────────────────────────────────────────┐ │ Hello, │ │ World! │ └──────────────────────────────────────────┘
- class anemoi.utils.text.Tree(actor: Any, parent: Tree | None = None)
Bases:
objectTree data structure.
- Parameters:
actor (Any) – The actor associated with the tree node.
parent (Tree, optional) – The parent tree node, by default None.
- adopt(kid: Tree) None
Adopt a child tree node.
- Parameters:
kid (Tree) – The child tree node to adopt.
- as_dict() dict
Convert the tree node to a dictionary.
- Returns:
The dictionary representation of the tree node.
- Return type:
- anemoi.utils.text.table(rows: list[list[Any]], header: list[str], align: list[str], margin: int = 0) str
Format a table.
>>> table([['Aa', 12, 5], ['B', 120, 1], ['C', 9, 123]], ['C1', 'C2', 'C3'], ['<', '>', '>']) C1 │ C2 │ C3 ───┼─────┼──── Aa │ 12 │ 5 B │ 120 │ 1 C │ 9 │ 123 ───┴─────┴────
- Parameters:
- Returns:
A table as a string
- Return type:
anemoi.utils.timer module
Logging utilities.
- class anemoi.utils.timer.Timer(title: str, logger: Logger = <Logger anemoi.utils.timer (WARNING)>)
Bases:
objectContext manager to measure elapsed time.
- Parameters:
title (str) – The title of the timer.
logger (logging.Logger, optional) – The logger to use for logging the elapsed time, by default LOGGER.
anemoi.utils.window module
- class anemoi.utils.window.Window(window: str)
Bases:
objectRepresents a time window for selecting data, with before/after offsets and inclusivity.
Parses a window string to determine the time offsets before and after a central point, and whether the window is inclusive or exclusive at each end. Used by WindowView to select data slices.