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.az module
- anemoi.utils.remote.s3 module
- anemoi.utils.remote.ssh module
- anemoi.utils.schemas package
- anemoi.utils.settings_schema package
- Submodules
- anemoi.utils.settings_schema.base module
- anemoi.utils.settings_schema.datasets module
- anemoi.utils.settings_schema.object_storage module
ObjectStorageBucketConfigObjectStorageBucketConfig.endpoint_urlObjectStorageBucketConfig.skip_signatureObjectStorageBucketConfig.access_key_idObjectStorageBucketConfig.secret_access_keyObjectStorageBucketConfig.regionObjectStorageBucketConfig.account_nameObjectStorageBucketConfig.account_keyObjectStorageBucketConfig.model_configObjectStorageBucketConfig.sas_tokenObjectStorageBucketConfig.get()
ObjectStorageConfig
- anemoi.utils.settings_schema.paramdb module
- anemoi.utils.settings_schema.registry module
- anemoi.utils.settings_schema.utils module
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.
- class anemoi.utils.caching.NpzCacher(collection: str, expires: int | None)
Bases:
CacherCacher that uses NPZ files.
- 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.checkpoints.replace_metadata(path: str, metadata: dict, supporting_arrays: dict | None = None, *, name: str = 'anemoi.json') None
Replace metadata in a checkpoint file.
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
@aliases(a="b", c=["d", "e"]) def func(a, c): return a, c func(a=1, c=2) # (1, 2) func(b=1, d=2) # (1, 2)
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.
- anemoi.utils.grib.SETTINGS = AnemoiSettings(object_storage=ObjectStorageConfig(endpoint_url=None, skip_signature=False, access_key_id=None, secret_access_key=None, region=None, account_name=None, account_key=None, sas_token=None, type=None), datasets=DatasetsConfig(path=[], use_search_path_not_found=False, ignore_naming_conventions=False, named=DatasetsNamedConfig()), paramdb=ParamDBConfig(default_origin='ecmf', cache_length=30, local_cache=None), registry=RegistryConfig(api_url=None, api_token=None, allow_delete=False, plots_uri_pattern=None, datasets_uri_pattern=None, weights_uri_pattern=None, weights_platform=None), utils=UtilsConfig(grids_path=None, cache_directory=PosixPath('/home/docs/.cache/anemoi'), debug_imports_in_cli=False))
Anemoi settings, loaded on module import.
- 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.settings module
- anemoi.utils.settings.copy_default_settings(dest: Path | None = None, *, overwrite: bool = False) Path
Copy the bundled
settings.defaults.tomlto the user default settings location.- Parameters:
dest (Path, optional) – Custom destination path for the copied defaults file. If None (default), uses the standard user config location (~/.config/anemoi/settings.defaults.toml).
overwrite (bool) – If False (default), skip the copy when the destination file already exists.
- Returns:
The path the file was (or would have been) written to.
- Return type:
Path
- anemoi.utils.settings.convert_to_secret(val: dict[str, str | Any]) dict[str, SecretStr | Any]
- anemoi.utils.settings.convert_to_secret(val: str) SecretStr
- class anemoi.utils.settings.AnemoiConfigFileSource(settings_cls: type[BaseSettings], toml_file: Path, yaml_file: Path)
Bases:
PydanticBaseSettingsSourceLoads settings from a TOML/YAML config file pair.
Secret (
SecretStr) values may live in any settings file, provided that file has mode0600. A file that contains no secrets has no permission requirement. There is therefore no need to partition secret and non-secret keys into separate files: keys may go anywhere as long as any file holding a secret is mode0600.- get_field_value(field: Any, field_name: str) tuple[Any, str, bool]
Gets the value, the key for model creation, and a flag to determine whether value is complex.
This is an abstract method that should be overridden in every settings source classes.
- Parameters:
field – The field.
field_name – The field name.
- Returns:
A tuple that contains the value, key and a flag to determine whether value is complex.
- class anemoi.utils.settings.AnemoiSettings(_case_sensitive: bool | None = None, _nested_model_default_partial_update: bool | None = None, _env_prefix: str | None = None, _env_prefix_target: EnvPrefixTarget | None = None, _env_file: DotenvType | None = PosixPath('.'), _env_file_encoding: str | None = None, _env_ignore_empty: bool | None = None, _env_nested_delimiter: str | None = None, _env_nested_max_split: int | None = None, _env_parse_none_str: str | None = None, _env_parse_enums: bool | None = None, _cli_prog_name: str | None = None, _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None, _cli_settings_source: CliSettingsSource[Any] | None = None, _cli_parse_none_str: str | None = None, _cli_hide_none_type: bool | None = None, _cli_avoid_json: bool | None = None, _cli_enforce_required: bool | None = None, _cli_use_class_docs_for_groups: bool | None = None, _cli_exit_on_error: bool | None = None, _cli_prefix: str | None = None, _cli_flag_prefix_char: str | None = None, _cli_implicit_flags: bool | Literal['dual', 'toggle'] | None = None, _cli_ignore_unknown_args: bool | None = None, _cli_kebab_case: bool | Literal['all', 'no_enums'] | None = None, _cli_shortcuts: Mapping[str, str | list[str]] | None = None, _secrets_dir: PathType | None = None, _build_sources: tuple[tuple[PydanticBaseSettingsSource, ...], dict[str, Any]] | None = None, *, object_storage: ~anemoi.utils.settings_schema.object_storage.ObjectStorageConfig = <factory>, datasets: ~anemoi.utils.settings_schema.datasets.DatasetsConfig = <factory>, paramdb: ~anemoi.utils.settings_schema.paramdb.ParamDBConfig = <factory>, registry: ~anemoi.utils.settings_schema.registry.RegistryConfig = <factory>, utils: ~anemoi.utils.settings_schema.utils.UtilsConfig = <factory>)
Bases:
BaseSettingsSettings for Anemoi.
Use the
ANEMOI_SETTINGS_FILEenvironment variable to specify a custom location for the main settings file (default:~/.config/anemoi/settings.toml).The main settings file can be in either TOML or YAML format; the extension is ignored. Keys may be placed in any settings file, secret or not: there is no requirement to partition secret and non-secret keys into separate files. The only rule is that any file containing a ``SecretStr`` value must have permissions ``0600``; a secret found in a file that is readable by group or others is a fatal error (
PermissionError).An optional secrets file with the same name but suffixed with
.secrets(e.g.settings.secrets.toml) is also read. It is the natural place to keep secrets when the main settings file must stay readable by others.Note: Init kwargs are intentionally disabled as a source of settings.
Settings are loaded with the following priority (highest to lowest):
Environment variables (with prefix
ANEMOI_SETTINGS_and keys in upper case with underscores)Values from the
.secrets.(toml|yaml)fileValues from the
.(toml|yaml)fileDefault values defined in the
AnemoiSettingsclass and its nested models
- model_config = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'cli_avoid_json': False, 'cli_enforce_required': False, 'cli_exit_on_error': True, 'cli_flag_prefix_char': '-', 'cli_hide_none_type': False, 'cli_ignore_unknown_args': False, 'cli_implicit_flags': False, 'cli_kebab_case': False, 'cli_parse_args': None, 'cli_parse_none_str': None, 'cli_prefix': '', 'cli_prog_name': None, 'cli_shortcuts': None, 'cli_use_class_docs_for_groups': False, 'enable_decoding': True, 'env_file': None, 'env_file_encoding': None, 'env_ignore_empty': False, 'env_nested_delimiter': '__', 'env_nested_max_split': None, 'env_parse_enums': None, 'env_parse_none_str': None, 'env_prefix': 'ANEMOI_SETTINGS_', 'env_prefix_target': 'variable', 'extra': 'ignore', 'hide_input_in_errors': True, 'json_file': None, 'json_file_encoding': None, 'nested_model_default_partial_update': False, 'populate_by_name': True, 'protected_namespaces': ('model_validate', 'model_dump', 'settings_customise_sources'), 'secrets_dir': None, 'serialize_by_alias': True, 'toml_file': None, 'validate_by_alias': True, 'validate_by_name': True, 'validate_default': True, 'yaml_config_section': None, 'yaml_file': None, 'yaml_file_encoding': None}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- object_storage: ObjectStorageConfig
Configuration for cloud (S3-compatible and Azure Blob) object storage.
- datasets: DatasetsConfig
Dataset discovery and validation settings.
- paramdb: ParamDBConfig
GRIB parameter database lookup settings.
- registry: RegistryConfig
Configuration for access to the Anemoi registry.
- utils: UtilsConfig
Miscellaneous anemoi-utils settings.
- classmethod settings_customise_sources(settings_cls: type[BaseSettings], init_settings: PydanticBaseSettingsSource, env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource, file_secret_settings: PydanticBaseSettingsSource) tuple[PydanticBaseSettingsSource, ...]
Define the sources and their order for loading the settings values.
- Parameters:
settings_cls – The Settings class.
init_settings – The InitSettingsSource instance.
env_settings – The EnvSettingsSource instance.
dotenv_settings – The DotEnvSettingsSource instance.
file_secret_settings – The SecretsSettingsSource instance.
- Returns:
A tuple containing the sources and their order for loading the settings values.
- anemoi.utils.settings.SETTINGS = AnemoiSettings(object_storage=ObjectStorageConfig(endpoint_url=None, skip_signature=False, access_key_id=None, secret_access_key=None, region=None, account_name=None, account_key=None, sas_token=None, type=None), datasets=DatasetsConfig(path=[], use_search_path_not_found=False, ignore_naming_conventions=False, named=DatasetsNamedConfig()), paramdb=ParamDBConfig(default_origin='ecmf', cache_length=30, local_cache=None), registry=RegistryConfig(api_url=None, api_token=None, allow_delete=False, plots_uri_pattern=None, datasets_uri_pattern=None, weights_uri_pattern=None, weights_platform=None), utils=UtilsConfig(grids_path=None, cache_directory=PosixPath('/home/docs/.cache/anemoi'), debug_imports_in_cli=False))
Global instance of the AnemoiSettings. This will be created on first import of the anemoi.utils.settings module, and can be reloaded with reload_settings().
Use AnemoiSettings() to create separate instances if needed, but these will be runtime specific.
- anemoi.utils.settings.reload_settings()
Reload the Anemoi settings.
Is run in-place on the global SETTINGS instance.
anemoi.utils.testing module
- anemoi.utils.testing.temporary_directory_for_test_data(tmp_path_factory: TempPathFactory) TemporaryDirectoryForTestData
- anemoi.utils.testing.url_for_test_data(path: str) str
Generate the URL for the test data based on the given path.
- class anemoi.utils.testing.GetTestData(temporary_directory_for_test_data: TemporaryDirectoryForTestData)
Bases:
object
- anemoi.utils.testing.get_test_data(temporary_directory_for_test_data: TemporaryDirectoryForTestData) GetTestData
- class anemoi.utils.testing.GetTestArchive(temporary_directory_for_test_data: TemporaryDirectoryForTestData, get_test_data: GetTestData)
Bases:
object
- anemoi.utils.testing.get_test_archive(temporary_directory_for_test_data: TemporaryDirectoryForTestData, get_test_data: GetTestData) GetTestArchive
- anemoi.utils.testing.packages_installed(*names: str) bool
Check if all the given packages are installed.
Use this function to check if the required packages are installed before running tests.
>>> @pytest.mark.skipif(not packages_installed("foo", "bar"), reason="Packages 'foo' and 'bar' are not installed") >>> def test_foo_bar() -> None: >>> ...
- anemoi.utils.testing.skip_missing_packages(*names: str) MarkDecorator
Skip a test if any of the specified packages are missing.
- Parameters:
names (str) – The names of the packages to check.
- Returns:
A decorator that skips the test if any of the specified packages are missing.
- Return type:
Callable
- anemoi.utils.testing.skip_if_missing_command(cmd: str) MarkDecorator
Skip a test if the specified command is not available.
- Parameters:
cmd (str) – The name of the command to check.
- Returns:
A decorator that skips the test if the specified command is not available.
- Return type:
Callable
- anemoi.utils.testing.cli_testing(package: str, cmd: str, *args: str) None
Run a CLI command for testing purposes.
- anemoi.utils.testing.run_tests(globals: dict[str, Callable[[], None]]) None
Run all test functions that start with
test_.- Parameters:
globals (dict[str, Callable[[], None]]) – The global namespace containing the test functions.
Example
Call from a test file to run all tests in that file:
if __name__ == "__main__": from anemoi.utils.testing import run_tests run_tests(globals())
Useful for debugging or running tests in an interactive environment.
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.