|
5 | 5 | import warnings |
6 | 6 | from copy import deepcopy |
7 | 7 |
|
| 8 | +import esmvalcore.dataset |
| 9 | + |
| 10 | +if typing.TYPE_CHECKING: |
| 11 | + import esmvalcore |
| 12 | + from esmvalcore.dataset import Dataset |
| 13 | + from esmvalcore.typing import FacetValue |
| 14 | + |
8 | 15 | import dask |
9 | 16 | import packaging.version |
10 | 17 | import xarray as xr |
|
22 | 29 | from fastprogress.fastprogress import progress_bar |
23 | 30 | from intake.catalog import Catalog |
24 | 31 |
|
| 32 | +from ._imports import _ESMVALCORE_AVAILABLE |
25 | 33 | from .cat import ESMCatalogModel |
26 | 34 | from .derived import DerivedVariableRegistry, default_registry |
27 | 35 | from .source import ESMDataSource |
@@ -839,6 +847,53 @@ def to_dask(self, **kwargs) -> xr.Dataset: |
839 | 847 | _, ds = res.popitem() |
840 | 848 | return ds |
841 | 849 |
|
| 850 | + def to_iris( |
| 851 | + self, |
| 852 | + facets: dict[FacetValue, str], |
| 853 | + cmorizer: typing.Any | None = None, |
| 854 | + **kwargs, |
| 855 | + ) -> esmvalcore.dataset.Dataset: |
| 856 | + """ |
| 857 | + Convert result to an ESMValCore Dataset. |
| 858 | +
|
| 859 | + This is only possible if the search returned exactly one result. |
| 860 | +
|
| 861 | + Parameters |
| 862 | + ---------- |
| 863 | + facets: dict[FacetValue, str] |
| 864 | + Mapping of ESMValCore Dataset facets to their corresponding esm_datastore |
| 865 | + attributes. For example, the mapping for a dataset containing keys |
| 866 | + 'activity_id', 'source_id', 'member_id', 'experiment_id' would look like: |
| 867 | + ```python |
| 868 | + facets = { |
| 869 | + "activity": "activity_id", |
| 870 | + "dataset": "source_id", |
| 871 | + "ensemble": "member_id", |
| 872 | + "exp": "experiment_id", |
| 873 | + "grid": "grid_label", |
| 874 | + }, |
| 875 | + ``` |
| 876 | + cmorize: Any, optional |
| 877 | + CMORizer to use in order to CMORize the datastore search results for |
| 878 | + the ESMValCore Dataset. Presumably this will be a callable? If not set, |
| 879 | + no CMORization will be done. |
| 880 | + kwargs: dict |
| 881 | + TBC. |
| 882 | + """ |
| 883 | + if not _ESMVALCORE_AVAILABLE: |
| 884 | + raise ImportError( |
| 885 | + '`to_iris()` requires the esmvalcore package to be installed. ' |
| 886 | + 'To proceed please install esmvalcore using: ' |
| 887 | + ' `python -m pip install esmvalcore` or `conda install -c conda-forge esmvalcore`.' |
| 888 | + ) |
| 889 | + |
| 890 | + if len(self) != 1: # quick check to fail more quickly if there are many results |
| 891 | + raise ValueError( |
| 892 | + f'Expected exactly one dataset. Received {len(self)} datasets. Please refine your search.' |
| 893 | + ) |
| 894 | + |
| 895 | + ds = Dataset(**facets) |
| 896 | + |
842 | 897 | def _create_derived_variables(self, datasets, skip_on_error): |
843 | 898 | if len(self.derivedcat) > 0: |
844 | 899 | datasets = self.derivedcat.update_datasets( |
|
0 commit comments