rompy 0.6.4__tar.gz → 0.7.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. {rompy-0.6.4 → rompy-0.7.2}/HISTORY.rst +25 -0
  2. {rompy-0.6.4 → rompy-0.7.2}/PKG-INFO +2 -7
  3. {rompy-0.6.4 → rompy-0.7.2}/pyproject.toml +1 -6
  4. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/__init__.py +1 -1
  5. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/backends/config.py +1 -1
  6. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/core/boundary.py +8 -1
  7. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/core/config.py +1 -4
  8. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/core/data.py +16 -19
  9. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/core/filters.py +219 -212
  10. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/core/render.py +12 -7
  11. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/core/spectrum.py +8 -11
  12. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/core/types.py +33 -0
  13. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/core/yaml_loader.py +3 -3
  14. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/formatting.py +12 -4
  15. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/model.py +10 -3
  16. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/pipeline/__init__.py +3 -2
  17. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/postprocess/__init__.py +6 -3
  18. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/postprocess/config.py +4 -2
  19. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/run/__init__.py +5 -1
  20. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/run/docker.py +5 -1
  21. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/run/slurm.py +6 -2
  22. {rompy-0.6.4 → rompy-0.7.2}/src/rompy.egg-info/PKG-INFO +2 -7
  23. {rompy-0.6.4 → rompy-0.7.2}/src/rompy.egg-info/SOURCES.txt +0 -2
  24. {rompy-0.6.4 → rompy-0.7.2}/src/rompy.egg-info/requires.txt +1 -6
  25. {rompy-0.6.4 → rompy-0.7.2}/tests/test_basemodel.py +19 -0
  26. {rompy-0.6.4 → rompy-0.7.2}/tests/test_data.py +16 -0
  27. {rompy-0.6.4 → rompy-0.7.2}/tests/test_datablob_http.py +5 -1
  28. rompy-0.6.4/docs/Makefile +0 -20
  29. rompy-0.6.4/docs/make.bat +0 -35
  30. {rompy-0.6.4 → rompy-0.7.2}/AUTHORS.rst +0 -0
  31. {rompy-0.6.4 → rompy-0.7.2}/LICENSE +0 -0
  32. {rompy-0.6.4 → rompy-0.7.2}/MANIFEST.in +0 -0
  33. {rompy-0.6.4 → rompy-0.7.2}/NOTICE +0 -0
  34. {rompy-0.6.4 → rompy-0.7.2}/README.md +0 -0
  35. {rompy-0.6.4 → rompy-0.7.2}/setup.cfg +0 -0
  36. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/_version.py +0 -0
  37. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/backends/__init__.py +0 -0
  38. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/cli.py +0 -0
  39. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/core/__init__.py +0 -0
  40. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/core/grid.py +0 -0
  41. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/core/http_handler.py +0 -0
  42. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/core/source.py +0 -0
  43. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/core/time.py +0 -0
  44. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/logging/__init__.py +0 -0
  45. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/logging/config.py +0 -0
  46. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/logging/formatter.py +0 -0
  47. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/logging/logger.py +0 -0
  48. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/plotting.py +0 -0
  49. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/templates/base/__init__.py +0 -0
  50. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/templates/base/{{runtime.staging_dir}}/INPUT +0 -0
  51. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/templates/base/{{runtime.staging_dir}}/datasets/readme.md +0 -0
  52. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/templates/base/{{runtime.staging_dir}}/outputs/readme.md +0 -0
  53. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/templating.py +0 -0
  54. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/transfer/__init__.py +0 -0
  55. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/transfer/base.py +0 -0
  56. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/transfer/cloud.py +0 -0
  57. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/transfer/exceptions.py +0 -0
  58. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/transfer/file.py +0 -0
  59. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/transfer/http.py +0 -0
  60. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/transfer/manager.py +0 -0
  61. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/transfer/oceanum.py +0 -0
  62. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/transfer/registry.py +0 -0
  63. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/transfer/utils.py +0 -0
  64. {rompy-0.6.4 → rompy-0.7.2}/src/rompy/utils.py +0 -0
  65. {rompy-0.6.4 → rompy-0.7.2}/src/rompy.egg-info/dependency_links.txt +0 -0
  66. {rompy-0.6.4 → rompy-0.7.2}/src/rompy.egg-info/entry_points.txt +0 -0
  67. {rompy-0.6.4 → rompy-0.7.2}/src/rompy.egg-info/top_level.txt +0 -0
  68. {rompy-0.6.4 → rompy-0.7.2}/tests/__init__.py +0 -0
  69. {rompy-0.6.4 → rompy-0.7.2}/tests/backends/test_enhanced_backends.py +0 -0
  70. {rompy-0.6.4 → rompy-0.7.2}/tests/backends/test_modelrun_pydantic_integration.py +0 -0
  71. {rompy-0.6.4 → rompy-0.7.2}/tests/backends/test_pydantic_backends.py +0 -0
  72. {rompy-0.6.4 → rompy-0.7.2}/tests/backends/test_slurm_backend.py +0 -0
  73. {rompy-0.6.4 → rompy-0.7.2}/tests/conftest.py +0 -0
  74. {rompy-0.6.4 → rompy-0.7.2}/tests/core/test_logging.py +0 -0
  75. {rompy-0.6.4 → rompy-0.7.2}/tests/example_configs/make_full_yaml.py +0 -0
  76. {rompy-0.6.4 → rompy-0.7.2}/tests/integration/test_docker_backend.py +0 -0
  77. {rompy-0.6.4 → rompy-0.7.2}/tests/test_basegrid.py +0 -0
  78. {rompy-0.6.4 → rompy-0.7.2}/tests/test_cloud_transfer.py +0 -0
  79. {rompy-0.6.4 → rompy-0.7.2}/tests/test_config_render_delegation.py +0 -0
  80. {rompy-0.6.4 → rompy-0.7.2}/tests/test_helpers.py +0 -0
  81. {rompy-0.6.4 → rompy-0.7.2}/tests/test_intake_driver.py +0 -0
  82. {rompy-0.6.4 → rompy-0.7.2}/tests/test_join_prefix.py +0 -0
  83. {rompy-0.6.4 → rompy-0.7.2}/tests/test_pipeline_config.py +0 -0
  84. {rompy-0.6.4 → rompy-0.7.2}/tests/test_postprocess_config.py +0 -0
  85. {rompy-0.6.4 → rompy-0.7.2}/tests/test_serilization.py +0 -0
  86. {rompy-0.6.4 → rompy-0.7.2}/tests/test_templates.py +0 -0
  87. {rompy-0.6.4 → rompy-0.7.2}/tests/test_templating.py +0 -0
  88. {rompy-0.6.4 → rompy-0.7.2}/tests/test_time.py +0 -0
  89. {rompy-0.6.4 → rompy-0.7.2}/tests/test_transfer_file.py +0 -0
  90. {rompy-0.6.4 → rompy-0.7.2}/tests/test_transfer_http.py +0 -0
  91. {rompy-0.6.4 → rompy-0.7.2}/tests/test_transfer_manager.py +0 -0
  92. {rompy-0.6.4 → rompy-0.7.2}/tests/test_transfer_oceanum.py +0 -0
  93. {rompy-0.6.4 → rompy-0.7.2}/tests/test_transfer_registry.py +0 -0
  94. {rompy-0.6.4 → rompy-0.7.2}/tests/test_utils/__init__.py +0 -0
  95. {rompy-0.6.4 → rompy-0.7.2}/tests/test_utils/logging.py +0 -0
  96. {rompy-0.6.4 → rompy-0.7.2}/tests/test_yaml_loader.py +0 -0
  97. {rompy-0.6.4 → rompy-0.7.2}/tests/utils/__init__.py +0 -0
  98. {rompy-0.6.4 → rompy-0.7.2}/tests/utils/compare.py +0 -0
@@ -33,6 +33,31 @@ are continually evolving. Contributions and feedback are welcome!
33
33
  Releases
34
34
  ********
35
35
 
36
+ 0.7.2 (2026-12-01)
37
+ ___________________
38
+
39
+ Internal Changes
40
+ ----------------
41
+ * The ``docs`` extra installs ``rompy-docs`` from PyPI. It depended on the GitHub repository, which PyPI does not accept in a package, so 0.7.0 and 0.7.1 were tagged but not published.
42
+
43
+ 0.7.0 (2026-12-01)
44
+ ___________________
45
+
46
+ New Features
47
+ ------------
48
+ * Misspelled field names are reported instead of silently ignored: a model given an unknown field that resembles one of its fields raises an error that suggests the field, e.g. ``Unknown field 'tmie'. Did you mean 'time'?``. By `@tomdurrant <https://github.com/tomdurrant>`_ (`#27 <https://github.com/rom-py/rompy/pull/27>`_).
49
+ * ``DataBlob.copied_path`` gives the destination written by the last ``get()``, as a ``Path``. By `@tomdurrant <https://github.com/tomdurrant>`_ (`#36 <https://github.com/rom-py/rompy/pull/36>`_).
50
+
51
+ Bug Fixes
52
+ ---------
53
+ * The check for misspelled fields accepts field aliases. Models could not be created with an alias, e.g. the ``break`` parameter of rompy-xbeach's wave models (`#40 <https://github.com/rom-py/rompy/pull/40>`_).
54
+ * ``DataBlob`` keeps the path it copied to as a ``Path``, the type ``get()`` returns, instead of a string (`#35 <https://github.com/rom-py/rompy/issues/35>`_).
55
+
56
+ Internal Changes
57
+ ----------------
58
+ * The documentation is restructured as the hub of the rompy sites: concept, how-to and plugin pages, a models page and a per-module reference, built in strict mode with the shared ``rompy-docs`` configuration. The notebooks are rendered on the `rompy-notebooks site <https://rom-py.github.io/rompy-notebooks/>`_ (`#39 <https://github.com/rom-py/rompy/pull/39>`_).
59
+ * Docstrings and annotations shown in the API reference are corrected, including those of ``RompyBaseModel``, ``Filter`` and ``DataBoundary``.
60
+
36
61
  0.6.0 (2026-02-18)
37
62
  ___________________
38
63
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rompy
3
- Version: 0.6.4
3
+ Version: 0.7.2
4
4
  Summary: Core rompy library for ocean wave modeling with plugin system
5
5
  Author-email: CSIRO <paul.branson@csiro.au>
6
6
  Maintainer-email: Rompy Contributors <developers@rompy.com>
@@ -237,12 +237,7 @@ Requires-Dist: gcsfs; extra == "extra"
237
237
  Requires-Dist: zarr; extra == "extra"
238
238
  Requires-Dist: cloudpathlib[azure,gs,s3]; extra == "extra"
239
239
  Provides-Extra: docs
240
- Requires-Dist: mkdocs; extra == "docs"
241
- Requires-Dist: mkdocs-material; extra == "docs"
242
- Requires-Dist: mkdocstrings[python]; extra == "docs"
243
- Requires-Dist: mkdocs-gallery; extra == "docs"
244
- Requires-Dist: mkdocs-execute-plugin; extra == "docs"
245
- Requires-Dist: mkdocs-jupyter; extra == "docs"
240
+ Requires-Dist: rompy-docs>=0.1; extra == "docs"
246
241
  Provides-Extra: dev
247
242
  Requires-Dist: pytest; extra == "dev"
248
243
  Requires-Dist: envyaml; extra == "dev"
@@ -105,12 +105,7 @@ az = "rompy.transfer.cloud:CloudTransfer"
105
105
  test = ["pytest", "envyaml", "coverage"]
106
106
  extra = ["gcsfs", "zarr", "cloudpathlib[s3,gs,azure]"]
107
107
  docs = [
108
- "mkdocs",
109
- "mkdocs-material",
110
- "mkdocstrings[python]",
111
- "mkdocs-gallery",
112
- "mkdocs-execute-plugin",
113
- "mkdocs-jupyter",
108
+ "rompy-docs>=0.1",
114
109
  ]
115
110
  dev = ["pytest", "envyaml", "coverage", "ruff", "black", "respx"]
116
111
 
@@ -49,7 +49,7 @@ warnings.filterwarnings(
49
49
  )
50
50
 
51
51
  # __version__ = _version.get_versions()["version"]
52
- __version__ = "0.6.4"
52
+ __version__ = "0.7.2"
53
53
 
54
54
  # Import and re-export formatting utilities
55
55
  from .formatting import get_formatted_box, get_formatted_header_footer
@@ -74,7 +74,7 @@ class BaseBackendConfig(BaseModel, ABC):
74
74
  return v
75
75
 
76
76
  @abstractmethod
77
- def get_backend_class(self):
77
+ def get_backend_class(self) -> type:
78
78
  """Return the backend class that should handle this configuration.
79
79
 
80
80
  Returns:
@@ -75,6 +75,13 @@ def find_minimum_distance(points: list[tuple[float, float]]) -> float:
75
75
 
76
76
 
77
77
  class DataBoundary(DataGrid):
78
+ """Gridded data along the open boundary of a model grid.
79
+
80
+ Selects data from a gridded source at points along the grid boundary, spaced by
81
+ `spacing` (or at the source grid spacing with `spacing="parent"`), with
82
+ `sel_method` choosing nearest-neighbour selection or interpolation.
83
+ """
84
+
78
85
  model_type: Literal["boundary"] = Field(
79
86
  default="data_boundary",
80
87
  description="Model type discriminator",
@@ -236,7 +243,7 @@ class BoundaryWaveStation(DataBoundary):
236
243
  )
237
244
  buffer: float = Field(
238
245
  default=2.0,
239
- description="Space to buffer the grid bounding box if `filter_grid` is True",
246
+ description="Space to buffer the grid bounding box if `crop_data` is True",
240
247
  )
241
248
 
242
249
  def model_post_init(self, __context):
@@ -45,7 +45,7 @@ class BaseConfig(RompyBaseModel):
45
45
  def __call__(self, *args, **kwargs):
46
46
  return self
47
47
 
48
- def render(self, context: dict, output_dir: Path | str):
48
+ def render(self, context: dict, output_dir: Path | str) -> None:
49
49
  """Render the configuration template to the output directory.
50
50
 
51
51
  This method orchestrates the template rendering process. The default implementation
@@ -56,9 +56,6 @@ class BaseConfig(RompyBaseModel):
56
56
  Args:
57
57
  context: Full context dictionary. Expected to contain at least 'runtime' and 'config' keys.
58
58
  output_dir: Target directory for rendered output.
59
-
60
- Returns:
61
- str: Path to the staging directory (workspace) containing rendered files.
62
59
  """
63
60
  # Import locally to avoid potential circular imports at module import time
64
61
  from rompy.core.render import render as cookiecutter_render
@@ -45,16 +45,8 @@ class DataBlob(DataBase):
45
45
 
46
46
  Generic data source for files that either need to be copied to the model directory
47
47
  or linked if `link` is set to True. Supports local/cloud paths, remote HTTP/HTTPS URLs,
48
- and oceanum:// storage URIs via the transfer registry.
49
-
50
- Parameters
51
- ----------
52
- source : str | Path | AnyPath
53
- URI of the data source: local file path, cloud storage URI (s3://, gs://),
54
- remote HTTP/HTTPS URL, or oceanum:// storage URI.
55
- link : bool
56
- Whether to create a symbolic link instead of copying the file.
57
- Note: Only works with local file paths (file:// scheme).
48
+ and oceanum:// storage URIs via the transfer registry. Linking only works with
49
+ local file paths (file:// scheme).
58
50
 
59
51
  Examples
60
52
  --------
@@ -95,7 +87,12 @@ class DataBlob(DataBase):
95
87
  default=False,
96
88
  description="Whether to create a symbolic link instead of copying the file",
97
89
  )
98
- _copied: Optional[str] = PrivateAttr(default=None)
90
+ _copied: Optional[Path] = PrivateAttr(default=None)
91
+
92
+ @property
93
+ def copied_path(self) -> Optional[Path]:
94
+ """Return the destination created by the most recent successful get()."""
95
+ return self._copied
99
96
 
100
97
  @model_validator(mode="after")
101
98
  def validate_link_scheme_compat(self):
@@ -154,7 +151,7 @@ class DataBlob(DataBase):
154
151
  uri=str(self.source), destdir=destdir, name=name, link=self.link
155
152
  )
156
153
 
157
- self._copied = str(outfile)
154
+ self._copied = outfile
158
155
  return outfile
159
156
 
160
157
 
@@ -203,13 +200,13 @@ class DataPoint(DataBase):
203
200
  )
204
201
  buffer: float = Field(
205
202
  default=0.0,
206
- description="Space to buffer the grid bounding box if `filter_grid` is True",
203
+ description="Space to buffer the grid bounding box if `crop_data` is True",
207
204
  )
208
205
  time_buffer: list[int] = Field(
209
206
  default=[0, 0],
210
207
  description=(
211
208
  "Number of source data timesteps to buffer the time range "
212
- "if `filter_time` is True"
209
+ "if `crop_data` is True"
213
210
  ),
214
211
  )
215
212
 
@@ -279,14 +276,14 @@ class DataPoint(DataBase):
279
276
  class DataGrid(DataPoint):
280
277
  """Data object for gridded source data.
281
278
 
282
- Generic data object for xarray datasets that with gridded spatial dimensions
279
+ Generic data object for xarray datasets with gridded spatial dimensions.
283
280
 
284
281
  Note
285
282
  ----
286
- The fields `filter_grid` and `filter_time` trigger updates to the crop filter from
287
- the grid and time range objects passed to the get method. This is useful for data
288
- sources that are not defined on the same grid as the model grid or the same time
289
- range as the model run.
283
+ When `crop_data` is True, `get` crops the data to the bounding box of the grid
284
+ (plus `buffer`) and to the time range (plus `time_buffer` source time steps)
285
+ passed to it. This is useful for data sources that are not defined on the same
286
+ grid as the model grid or the same time range as the model run.
290
287
 
291
288
  """
292
289
 
@@ -1,212 +1,219 @@
1
- # -----------------------------------------------------------------------------
2
- # Copyright (c) 2020 - 2021, CSIRO
3
- #
4
- # All rights reserved.
5
- #
6
- # The full license is in the LICENSE file, distributed with this software.
7
- # -----------------------------------------------------------------------------
8
-
9
- from typing import Optional
10
-
11
- import xarray as xr
12
- from pydantic import field_validator
13
-
14
- from .types import RompyBaseModel, Slice
15
-
16
-
17
- # pydantic class to apply all the filters to the dataset
18
- class Filter(RompyBaseModel):
19
- sort: Optional[dict] = {}
20
- subset: Optional[dict] = {}
21
- crop: Optional[dict] = {}
22
- timenorm: Optional[dict] = {}
23
- rename: Optional[dict] = {}
24
- derived: Optional[dict] = {}
25
-
26
- @field_validator("crop", mode="before")
27
- def convert_slices(cls, v):
28
- for key, value in v.items():
29
- if isinstance(value, slice):
30
- v[key] = Slice.from_slice(value)
31
- if isinstance(value, dict):
32
- v[key] = Slice.from_dict(value)
33
- return v
34
-
35
- def __call__(self, ds):
36
- filters = get_filter_fns()
37
- for fn in filters:
38
- params = getattr(self, fn)
39
- if params:
40
- ds = filters[fn](ds, **params)
41
- return ds
42
-
43
- def __repr__(self):
44
- return self.__str__()
45
-
46
- def __str__(self):
47
- return f"Filter(sort={self.sort}, subset={self.subset}, crop={self.crop}, timenorm={self.timenorm}, rename={self.rename}, derived={self.derived})"
48
-
49
-
50
- def derived_filter(ds, derived_variables):
51
- """Add derived variable to Dataset.
52
-
53
- Parameters
54
- ----------
55
- ds: xarray.Dataset
56
- Input dataset to add derived variables to.
57
- derived_variables: dict
58
- Mapping {`derived_variable_name`: `derived_variable_definition`} where
59
- `derived_variable_definition` is a string to be evaluated defining some
60
- transformation based on existing variables in the input dataset `ds`.
61
-
62
- Returns
63
- -------
64
- ds: xarray.Dataset
65
- Input dataset with extra derived variables.
66
-
67
- Example
68
- -------
69
- >>> import xarray as xr
70
- >>> ds = xr.DataArray([-10, -11], coords={"x": [0, 1]}).to_dataset(name="elevation")
71
- >>> ds = derived_filter(ds, {"depth": "ds.elevation * -1"})
72
-
73
- """
74
- for var, expr in derived_variables.items():
75
- ds[var] = eval(expr)
76
- return ds
77
-
78
-
79
- def sort_filter(ds, coords: list = []):
80
- coords = list[coords] if isinstance(coords, str) else coords
81
- for c in coords:
82
- if c in ds:
83
- ds = ds.sortby(c)
84
- return ds
85
-
86
-
87
- def subset_filter(ds, data_vars=None) -> xr.Dataset:
88
- """
89
- Subset data variables from dataset.
90
-
91
- parameters
92
- ----------
93
- ds: xr.Dataset
94
- Input dataset to transform.
95
- data_vars: Iterable
96
- Variables to subset from ds.
97
-
98
- Returns
99
- -------
100
- ds: xr.Dataset
101
- """
102
- if data_vars is not None:
103
- ds = ds[data_vars]
104
- return ds
105
-
106
-
107
- def crop_filter(ds, **data_slice) -> xr.Dataset:
108
- """
109
- Crop dataset.
110
-
111
- parameters
112
- ----------
113
- ds: xr.Dataset
114
- Input dataset to transform.
115
- data_slice: Iterable
116
- Data slice to crop
117
-
118
- Returns
119
- -------
120
- ds: xr.Dataset
121
-
122
- """
123
- if data_slice is not None:
124
- this_crop = {
125
- k: data_slice[k].to_slice()
126
- for k in data_slice.keys()
127
- if k in ds.sizes.keys()
128
- }
129
- ds = ds.sel(this_crop)
130
- for k in data_slice.keys():
131
- if (k not in ds.sizes.keys()) and (k in ds.coords.keys()):
132
- ds = ds.where(ds[k] > float(data_slice[k].start), drop=True)
133
- ds = ds.where(ds[k] < float(data_slice[k].stop), drop=True)
134
- return ds
135
-
136
-
137
- def timenorm_filter(ds, interval="hour", reftime=None) -> xr.Dataset:
138
- """Normalize time to lead time in hours
139
-
140
- Parameters
141
- ----------
142
- ds : xr.Dataset
143
- Input dataset to transform.
144
- interval : str, optional
145
- Time interval to normalize to, by default "hour"
146
- reftime : str, optional
147
- Reference time variable, by default None
148
-
149
- Returns
150
- -------
151
- ds : xr.Dataset
152
- """
153
- from pandas import to_datetime, to_timedelta
154
-
155
- dt = to_timedelta("1 " + interval)
156
- if reftime is None:
157
- ds["init"] = (
158
- ("time",),
159
- [
160
- ds["time"].values[0],
161
- ],
162
- )
163
- else:
164
- ds["init"] = (("time",), to_datetime(ds[reftime].values))
165
- ds["lead"] = ((ds["time"] - ds["init"]) / dt).astype("int")
166
- ds["lead"].attrs["units"] = interval
167
- ds = ds.set_coords("init")
168
- ds = ds.swap_dims({"time": "lead"})
169
- return ds
170
-
171
-
172
- def rename_filter(ds, **varmap) -> xr.Dataset:
173
- """Rename variables in dataset
174
-
175
- Parameters
176
- ----------
177
- ds : xr.Dataset
178
- Input dataset to transform.
179
- varmap : dict
180
- Dictionary of variable names to rename
181
-
182
- Returns
183
- -------
184
- ds : xr.Dataset
185
- """
186
- ds = ds.rename(varmap)
187
- return ds
188
-
189
-
190
- def get_filter_fns() -> dict:
191
- """Get dictionary of filter functions"""
192
- return {
193
- "sort": sort_filter,
194
- "subset": subset_filter,
195
- "crop": crop_filter,
196
- "timenorm": timenorm_filter,
197
- "rename": rename_filter,
198
- "derived": derived_filter,
199
- }
200
-
201
-
202
- def _open_preprocess(url, chunks, filters, xarray_kwargs):
203
- import xarray as xr
204
-
205
- ds = xr.open_dataset(url, chunks=chunks, **xarray_kwargs)
206
- filter_fns = get_filter_fns()
207
- for fn, params in filters.items():
208
- if isinstance(fn, str):
209
- fn = filter_fns[fn]
210
- ds = fn(ds, **params)
211
-
212
- return ds
1
+ # -----------------------------------------------------------------------------
2
+ # Copyright (c) 2020 - 2021, CSIRO
3
+ #
4
+ # All rights reserved.
5
+ #
6
+ # The full license is in the LICENSE file, distributed with this software.
7
+ # -----------------------------------------------------------------------------
8
+
9
+ from typing import Optional
10
+
11
+ import xarray as xr
12
+ from pydantic import field_validator
13
+
14
+ from .types import RompyBaseModel, Slice
15
+
16
+
17
+ class Filter(RompyBaseModel):
18
+ """Filters applied to a dataset after a source opens it.
19
+
20
+ Each field holds the keyword arguments of the filter function with the same
21
+ name in this module (`sort_filter`, `subset_filter`, `crop_filter`,
22
+ `timenorm_filter`, `rename_filter`, `derived_filter`). Calling the filter on a
23
+ dataset applies them in that order, skipping those left empty.
24
+ """
25
+
26
+ sort: Optional[dict] = {}
27
+ subset: Optional[dict] = {}
28
+ crop: Optional[dict] = {}
29
+ timenorm: Optional[dict] = {}
30
+ rename: Optional[dict] = {}
31
+ derived: Optional[dict] = {}
32
+
33
+ @field_validator("crop", mode="before")
34
+ def convert_slices(cls, v):
35
+ for key, value in v.items():
36
+ if isinstance(value, slice):
37
+ v[key] = Slice.from_slice(value)
38
+ if isinstance(value, dict):
39
+ v[key] = Slice.from_dict(value)
40
+ return v
41
+
42
+ def __call__(self, ds):
43
+ filters = get_filter_fns()
44
+ for fn in filters:
45
+ params = getattr(self, fn)
46
+ if params:
47
+ ds = filters[fn](ds, **params)
48
+ return ds
49
+
50
+ def __repr__(self):
51
+ return self.__str__()
52
+
53
+ def __str__(self):
54
+ return f"Filter(sort={self.sort}, subset={self.subset}, crop={self.crop}, timenorm={self.timenorm}, rename={self.rename}, derived={self.derived})"
55
+
56
+
57
+ def derived_filter(ds, derived_variables):
58
+ """Add derived variable to Dataset.
59
+
60
+ Parameters
61
+ ----------
62
+ ds: xarray.Dataset
63
+ Input dataset to add derived variables to.
64
+ derived_variables: dict
65
+ Mapping {`derived_variable_name`: `derived_variable_definition`} where
66
+ `derived_variable_definition` is a string to be evaluated defining some
67
+ transformation based on existing variables in the input dataset `ds`.
68
+
69
+ Returns
70
+ -------
71
+ ds: xarray.Dataset
72
+ Input dataset with extra derived variables.
73
+
74
+ Example
75
+ -------
76
+ >>> import xarray as xr
77
+ >>> ds = xr.DataArray([-10, -11], coords={"x": [0, 1]}).to_dataset(name="elevation")
78
+ >>> ds = derived_filter(ds, {"depth": "ds.elevation * -1"})
79
+
80
+ """
81
+ for var, expr in derived_variables.items():
82
+ ds[var] = eval(expr)
83
+ return ds
84
+
85
+
86
+ def sort_filter(ds, coords: list = []):
87
+ coords = list[coords] if isinstance(coords, str) else coords
88
+ for c in coords:
89
+ if c in ds:
90
+ ds = ds.sortby(c)
91
+ return ds
92
+
93
+
94
+ def subset_filter(ds, data_vars=None) -> xr.Dataset:
95
+ """
96
+ Subset data variables from dataset.
97
+
98
+ parameters
99
+ ----------
100
+ ds: xr.Dataset
101
+ Input dataset to transform.
102
+ data_vars: Iterable
103
+ Variables to subset from ds.
104
+
105
+ Returns
106
+ -------
107
+ ds: xr.Dataset
108
+ """
109
+ if data_vars is not None:
110
+ ds = ds[data_vars]
111
+ return ds
112
+
113
+
114
+ def crop_filter(ds, **data_slice) -> xr.Dataset:
115
+ """
116
+ Crop dataset.
117
+
118
+ parameters
119
+ ----------
120
+ ds: xr.Dataset
121
+ Input dataset to transform.
122
+ data_slice: Iterable
123
+ Data slice to crop
124
+
125
+ Returns
126
+ -------
127
+ ds: xr.Dataset
128
+
129
+ """
130
+ if data_slice is not None:
131
+ this_crop = {
132
+ k: data_slice[k].to_slice()
133
+ for k in data_slice.keys()
134
+ if k in ds.sizes.keys()
135
+ }
136
+ ds = ds.sel(this_crop)
137
+ for k in data_slice.keys():
138
+ if (k not in ds.sizes.keys()) and (k in ds.coords.keys()):
139
+ ds = ds.where(ds[k] > float(data_slice[k].start), drop=True)
140
+ ds = ds.where(ds[k] < float(data_slice[k].stop), drop=True)
141
+ return ds
142
+
143
+
144
+ def timenorm_filter(ds, interval="hour", reftime=None) -> xr.Dataset:
145
+ """Normalize time to lead time in hours
146
+
147
+ Parameters
148
+ ----------
149
+ ds : xr.Dataset
150
+ Input dataset to transform.
151
+ interval : str, optional
152
+ Time interval to normalize to, by default "hour"
153
+ reftime : str, optional
154
+ Reference time variable, by default None
155
+
156
+ Returns
157
+ -------
158
+ ds : xr.Dataset
159
+ """
160
+ from pandas import to_datetime, to_timedelta
161
+
162
+ dt = to_timedelta("1 " + interval)
163
+ if reftime is None:
164
+ ds["init"] = (
165
+ ("time",),
166
+ [
167
+ ds["time"].values[0],
168
+ ],
169
+ )
170
+ else:
171
+ ds["init"] = (("time",), to_datetime(ds[reftime].values))
172
+ ds["lead"] = ((ds["time"] - ds["init"]) / dt).astype("int")
173
+ ds["lead"].attrs["units"] = interval
174
+ ds = ds.set_coords("init")
175
+ ds = ds.swap_dims({"time": "lead"})
176
+ return ds
177
+
178
+
179
+ def rename_filter(ds, **varmap) -> xr.Dataset:
180
+ """Rename variables in dataset
181
+
182
+ Parameters
183
+ ----------
184
+ ds : xr.Dataset
185
+ Input dataset to transform.
186
+ varmap : dict
187
+ Dictionary of variable names to rename
188
+
189
+ Returns
190
+ -------
191
+ ds : xr.Dataset
192
+ """
193
+ ds = ds.rename(varmap)
194
+ return ds
195
+
196
+
197
+ def get_filter_fns() -> dict:
198
+ """Get dictionary of filter functions"""
199
+ return {
200
+ "sort": sort_filter,
201
+ "subset": subset_filter,
202
+ "crop": crop_filter,
203
+ "timenorm": timenorm_filter,
204
+ "rename": rename_filter,
205
+ "derived": derived_filter,
206
+ }
207
+
208
+
209
+ def _open_preprocess(url, chunks, filters, xarray_kwargs):
210
+ import xarray as xr
211
+
212
+ ds = xr.open_dataset(url, chunks=chunks, **xarray_kwargs)
213
+ filter_fns = get_filter_fns()
214
+ for fn, params in filters.items():
215
+ if isinstance(fn, str):
216
+ fn = filter_fns[fn]
217
+ ds = fn(ds, **params)
218
+
219
+ return ds