obsarray 1.0.2__py3-none-any.whl

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.
docs/conf.py ADDED
@@ -0,0 +1,181 @@
1
+ #!/usr/bin/env python
2
+ #
3
+ # obsarray documentation build configuration file, created by
4
+ # cookiecutter
5
+ #
6
+ # This file is execfile()d with the current directory set to its
7
+ # containing dir.
8
+ #
9
+ # Note that not all possible configuration values are present in this
10
+ # autogenerated file.
11
+ #
12
+ # All configuration values have a default; values that are commented out
13
+ # serve to show the default.
14
+
15
+
16
+ # If extensions (or modules to document with autodoc) are in another
17
+ # directory, add these directories to sys.path here. If the directory is
18
+ # relative to the documentation root, use os.path.abspath to make it
19
+ # absolute, like shown here.
20
+
21
+ import sphinx_autosummary_accessors
22
+ import obsarray
23
+
24
+ project_title = "obsarray".replace("_", " ").title()
25
+
26
+
27
+ # -- General configuration ---------------------------------------------
28
+
29
+ # If your documentation needs a minimal Sphinx version, state it here.
30
+ #
31
+ # needs_sphinx = '1.0'
32
+
33
+ # Attempt to make links automatially
34
+ default_role = "code"
35
+
36
+ # Add any Sphinx extension module names here, as strings. They can be
37
+ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
38
+ # CFAB added napolean to support google-style docstrings
39
+ extensions = [
40
+ "sphinx.ext.autodoc",
41
+ "sphinx.ext.autosummary",
42
+ "sphinx.ext.intersphinx",
43
+ "sphinx.ext.viewcode",
44
+ "sphinx.ext.napoleon",
45
+ "IPython.sphinxext.ipython_directive",
46
+ "IPython.sphinxext.ipython_console_highlighting",
47
+ "sphinx_design",
48
+ "sphinx_autosummary_accessors",
49
+ ]
50
+
51
+ # Add any paths that contain templates here, relative to this directory.
52
+ templates_path = ["_templates", sphinx_autosummary_accessors.templates_path]
53
+
54
+ # The suffix(es) of source filenames.
55
+ # You can specify multiple suffix as a list of string:
56
+ #
57
+ # source_suffix = ['.rst', '.md']
58
+ source_suffix = ".rst"
59
+
60
+ # The master toctree document.
61
+ master_doc = "index"
62
+
63
+ # General information about the project.
64
+ project = project_title
65
+ copyright = "CoMet Toolkit Team"
66
+ author = "CoMet Toolkit Team"
67
+
68
+ # The version info for the project you're documenting, acts as replacement
69
+ # for |version| and |release|, also used in various other places throughout
70
+ # the built documents.
71
+ #
72
+ # The short X.Y version.
73
+ version = obsarray.__version__
74
+ # The full version, including alpha/beta/rc tags.
75
+ release = obsarray.__version__
76
+
77
+ # The language for content autogenerated by Sphinx. Refer to documentation
78
+ # for a list of supported languages.
79
+ #
80
+ # This is also used if you do content translation via gettext catalogs.
81
+ # Usually you set "language" from the command line for these cases.
82
+ language = None
83
+
84
+ # List of patterns, relative to source directory, that match files and
85
+ # directories to ignore when looking for source files.
86
+ # This patterns also effect to html_static_path and html_extra_path
87
+ exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
88
+
89
+ # The name of the Pygments (syntax highlighting) style to use.
90
+ pygments_style = "sphinx"
91
+
92
+ rst_prolog = """
93
+ .. role:: python(code)
94
+ :language: python
95
+ :class: highlight
96
+ """
97
+
98
+ # If true, `todo` and `todoList` produce output, else they produce nothing.
99
+ todo_include_todos = False
100
+
101
+
102
+ # -- Options for HTML output -------------------------------------------
103
+
104
+ # The theme to use for HTML and HTML Help pages. See the documentation for
105
+ # a list of builtin themes.
106
+ #
107
+ html_theme = "sphinx_book_theme"
108
+
109
+ # Theme options are theme-specific and customize the look and feel of a
110
+ # theme further. For a list of options available for each theme, see the
111
+ # documentation.
112
+ #
113
+ # html_theme_options = {}
114
+
115
+ html_logo = "figs/obsarray.png"
116
+
117
+ # Add any paths that contain custom static files (such as style sheets) here,
118
+ # relative to this directory. They are copied after the builtin static files,
119
+ # so a file named "default.css" will overwrite the builtin "default.css".
120
+ html_static_path = ["_static"]
121
+
122
+ # -- Options for HTMLHelp output ---------------------------------------
123
+
124
+ # Output file base name for HTML help builder.
125
+ htmlhelp_basename = "obsarraydoc"
126
+
127
+
128
+ # -- Options for LaTeX output ------------------------------------------
129
+
130
+ latex_elements = {
131
+ # The paper size ('letterpaper' or 'a4paper').
132
+ #
133
+ # 'papersize': 'letterpaper',
134
+ # The font size ('10pt', '11pt' or '12pt').
135
+ #
136
+ # 'pointsize': '10pt',
137
+ # Additional stuff for the LaTeX preamble.
138
+ #
139
+ # 'preamble': '',
140
+ # Latex figure (float) alignment
141
+ #
142
+ # 'figure_align': 'htbp',
143
+ }
144
+
145
+ # Grouping the document tree into LaTeX files. List of tuples
146
+ # (source start file, target name, title, author, documentclass
147
+ # [howto, manual, or own class]).
148
+ latex_documents = [
149
+ (
150
+ master_doc,
151
+ "user_manual.tex",
152
+ "{} Documentation".format(project_title),
153
+ "CoMet Toolkit Team",
154
+ "manual",
155
+ ),
156
+ ]
157
+
158
+
159
+ # -- Options for manual page output ------------------------------------
160
+
161
+ # One entry per manual page. List of tuples
162
+ # (source start file, name, description, authors, manual section).
163
+ man_pages = [(master_doc, "obsarray", "obsarray Documentation", [author], 1)]
164
+
165
+
166
+ # -- Options for Texinfo output ----------------------------------------
167
+
168
+ # Grouping the document tree into Texinfo files. List of tuples
169
+ # (source start file, target name, title, author,
170
+ # dir menu entry, description, category)
171
+ texinfo_documents = [
172
+ (
173
+ master_doc,
174
+ "obsarray",
175
+ "obsarray Documentation",
176
+ author,
177
+ "obsarray",
178
+ "Extension to xarray for handling uncertainty quantified observation data",
179
+ "Miscellaneous",
180
+ ),
181
+ ]
@@ -0,0 +1,45 @@
1
+ from obsarray.err_corr import register_err_corr_form, BaseErrCorrForm
2
+ import xarray as xr
3
+ import numpy as np
4
+ import obsarray
5
+
6
+
7
+ @register_err_corr_form("new")
8
+ class NewForm(BaseErrCorrForm):
9
+
10
+ form = "new"
11
+ is_systematic = True
12
+
13
+ def build_matrix(self, idx: np.ndarray) -> np.ndarray:
14
+ return "abc"
15
+
16
+
17
+ # ds = xr.open_dataset("obs_example.nc")
18
+ #
19
+ # ds.unc["temperature"]["u_sys_temperature"] = (
20
+ # ["x", "y", "time"],
21
+ # ds.temperature * 0.03,
22
+ # {
23
+ # "err_corr": [
24
+ # {
25
+ # "dim": "x",
26
+ # "form": "new",
27
+ # "params": [],
28
+ # },
29
+ # {
30
+ # "dim": "y",
31
+ # "form": "systematic",
32
+ # "params": [],
33
+ # },
34
+ # {
35
+ # "dim": "time",
36
+ # "form": "systematic",
37
+ # "params": [],
38
+ # },
39
+ # ]
40
+ # },
41
+ # )
42
+ #
43
+ # p = ds.unc["temperature"]["u_sys_temperature"]
44
+ #
45
+ # pass
obsarray/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """obsarray - Extension to xarray for handling uncertainty-quantified observation data"""
2
+
3
+ __author__ = "Sam Hunt <sam.hunt@npl.co.uk>"
4
+ __all__ = []
5
+
6
+ from ._version import get_versions
7
+ from obsarray import unc_accessor, flag_accessor
8
+ from obsarray.err_corr import err_corr_forms
9
+ from obsarray.templater.template_util import create_ds
10
+ from obsarray.templater.dstemplater import DSTemplater
11
+ from obsarray.templater.dswriter import DSWriter
12
+
13
+ __version__ = get_versions()["version"]
14
+ del get_versions
obsarray/_version.py ADDED
@@ -0,0 +1,21 @@
1
+
2
+ # This file was generated by 'versioneer.py' (0.29) from
3
+ # revision-control system data, or from the parent directory name of an
4
+ # unpacked source archive. Distribution tarballs contain a pre-generated copy
5
+ # of this file.
6
+
7
+ import json
8
+
9
+ version_json = '''
10
+ {
11
+ "date": "2025-04-25T14:06:04+0100",
12
+ "dirty": false,
13
+ "error": null,
14
+ "full-revisionid": "b26b43a5d2e41ccb9a5e73c00e6d16a28a8515a9",
15
+ "version": "1.0.2"
16
+ }
17
+ ''' # END VERSION_JSON
18
+
19
+
20
+ def get_versions():
21
+ return json.loads(version_json)
obsarray/err_corr.py ADDED
@@ -0,0 +1,298 @@
1
+ """err_corr_forms - module for the defintion of error-correlation parameterisation forms"""
2
+
3
+ import abc
4
+ from typing import Callable, Type, Union, List
5
+ import numpy as np
6
+ from comet_maths.linear_algebra.matrix_conversion import expand_errcorr_dims
7
+
8
+ __author__ = "Sam Hunt <sam.hunt@npl.co.uk>"
9
+ __all__ = ["err_corr_forms", "register_err_corr_form", "BaseErrCorrForm"]
10
+
11
+
12
+ class ErrCorrForms:
13
+ """
14
+ Container for error-correlation parameterisation form definition objects
15
+ """
16
+
17
+ def __init__(self):
18
+ self._forms = {}
19
+
20
+ def __setitem__(self, form_name, form_cls):
21
+ if not issubclass(form_cls, BaseErrCorrForm):
22
+ raise TypeError(
23
+ "form must be subclass of " + str(BaseErrCorrForm.__class__)
24
+ )
25
+
26
+ self._forms[form_name] = form_cls
27
+
28
+ def __getitem__(self, name):
29
+ return self._forms[name]
30
+
31
+ def __delitem__(self, name):
32
+ del self._forms[name]
33
+
34
+ def keys(self):
35
+ return self._forms.keys()
36
+
37
+
38
+ err_corr_forms = ErrCorrForms()
39
+
40
+
41
+ # placeholder currently
42
+ class BaseErrCorrForm(abc.ABC):
43
+ """
44
+ Base class for error-correlation parameterisation form defintions
45
+ """
46
+
47
+ is_random = False
48
+ is_systematic = False
49
+
50
+ def __init__(self, xarray_obj, unc_var_name, dims, params, units):
51
+ self._obj = xarray_obj
52
+ self._unc_var_name = unc_var_name
53
+ self.dims = dims if isinstance(dims, list) else [dims]
54
+ self.params = params if isinstance(params, list) else [params]
55
+ self.units = units
56
+
57
+ def __str__(self):
58
+ """Custom __str__"""
59
+
60
+ return self.form + " " + str(self.params)
61
+
62
+ def __repr__(self):
63
+ """Custom __repr__"""
64
+ return str(self)
65
+
66
+ @property
67
+ @abc.abstractmethod
68
+ def form(self) -> str:
69
+ """Form name"""
70
+ pass
71
+
72
+ def get_varshape_errcorr(self):
73
+ """
74
+ return shape of uncertainty variable, including only dimensions which are included in the current error correlation form.
75
+
76
+ :return: shape of included dimensions
77
+ """
78
+ all_dims = self._obj[self._unc_var_name].dims
79
+ all_dims_sizes = self._obj.sizes
80
+
81
+ return tuple([all_dims_sizes[dim] for dim in all_dims if dim in self.dims])
82
+
83
+ def get_sliced_dim_sizes_uncvar(self, sli: tuple) -> dict:
84
+ """
85
+ Return dictionary with sizes of sliced dimensions of unc variable, including all dimensions.
86
+
87
+ :param sli: slice (tuple with slice for each dimension)
88
+ :return: dictionary with shape of included sliced dimensions
89
+ """
90
+ uncvar_dims = self._obj[self._unc_var_name][sli].dims
91
+ uncvar_shape = self._obj[self._unc_var_name][sli].shape
92
+ return {
93
+ uncvar_dims[idim]: uncvar_shape[idim] for idim in range(len(uncvar_dims))
94
+ }
95
+
96
+ def get_sliced_dim_sizes_errcorr(self, sli: tuple) -> dict:
97
+ """
98
+ Return dictionary with sizes of sliced dimensions of unc variable, including only dimensions which are
99
+ included in the current error correlation form.
100
+
101
+ :param sli: slice (tuple with slice for each dimension)
102
+ :return: dictionary with shape of included sliced dimensions
103
+ """
104
+ uncvar_sizes = self.get_sliced_dim_sizes_uncvar(sli)
105
+ sliced_dims = self.get_sliced_dims_errcorr(sli)
106
+
107
+ return {dim: uncvar_sizes[dim] for dim in sliced_dims}
108
+
109
+ def get_sliced_dims_errcorr(self, sli: tuple) -> list:
110
+ """
111
+ Return dimensions which are within the slice and included in the current error correlation form.
112
+
113
+ :param sli: slice (tuple with slice for each dimension)
114
+ :return: list with sliced dimensions
115
+ """
116
+ all_dims = self._obj[self._unc_var_name].dims
117
+ return [
118
+ all_dims[idim]
119
+ for idim in range(len(all_dims))
120
+ if (isinstance(sli[idim], slice) and all_dims[idim] in self.dims)
121
+ ]
122
+
123
+ def get_sliced_shape_errcorr(self, sli: tuple) -> tuple:
124
+ """
125
+ return shape of sliced uncertainty variable, including only dimensions which are included in the current error correlation form.
126
+
127
+ :param sli: slice (tuple with slice for each dimension)
128
+ :return: shape of included sliced dimensions
129
+ """
130
+ uncvar_sizes = self.get_sliced_dim_sizes_uncvar(sli)
131
+ sliced_dims = self.get_sliced_dims_errcorr(sli)
132
+
133
+ return tuple([uncvar_sizes[dim] for dim in sliced_dims])
134
+
135
+ def slice_errcorr_matrix(self, err_corr_matrix, variable_shape, sli) -> np.ndarray:
136
+ """
137
+ Slice the provided error correlation matrix (typically the error correlation matrix of the
138
+ BaseErrCorrForm) using the
139
+
140
+ :param err_corr_matrix: error correlation matrix to be sliced
141
+ :param variable_shape: tuple with the length of the dimensions in the error correlation matrix (in correct order for flattening)
142
+ :param sli: slice of observation variable to return error-correlation matrix for
143
+ :return: sliced error correlation matrix
144
+ """
145
+ mask_array = np.ones(variable_shape, dtype=bool)
146
+ mask_array[sli] = False
147
+
148
+ return np.delete(
149
+ np.delete(err_corr_matrix, mask_array.ravel(), 0), mask_array.ravel(), 1
150
+ )
151
+
152
+ @abc.abstractmethod
153
+ def build_matrix(self, sli: Union[np.ndarray, tuple]) -> np.ndarray:
154
+ """
155
+ Returns uncertainty effect error-correlation matrix, populated with error-correlation values defined
156
+ in this parameterisation
157
+
158
+ :param sli: slice of observation variable to return error-correlation matrix for
159
+
160
+ :return: populated error-correlation matrix
161
+ """
162
+ pass
163
+
164
+ def build_dot_matrix(self, sli: Union[np.ndarray, tuple]) -> np.ndarray:
165
+ """
166
+ Returns expanded error correlation matrix for use in dot product with error correlation
167
+ in other dimensions.
168
+
169
+ The (sliced) error correlation matrix for this BaseErrCorrForm is expanded from its current
170
+ (sliced) dimensions (which often don't include all dimensions of the associated uncertainty
171
+ variable) to the dimensions of the full (sliced) error correlation (i.e. all dimensions of
172
+ the uncertainty).
173
+ The returned matrix is not meaningfull unless combined in a dot product with the expanded
174
+ matrices of other error correlation matrices (together spanning all uncertainty dimensions).
175
+
176
+ :param sli: slice of observation variable to return error-correlation matrix for
177
+ :return: expanded matrix for use in dot product with error correlation in other dimensions.
178
+ """
179
+ return expand_errcorr_dims(
180
+ in_corr=self.build_matrix(sli),
181
+ in_dim=self.get_sliced_dims_errcorr(sli),
182
+ out_dim=list(self._obj[self._unc_var_name][sli].dims),
183
+ dim_sizes=self.get_sliced_dim_sizes_uncvar(sli),
184
+ )
185
+
186
+
187
+ def register_err_corr_form(form_name: str) -> Callable:
188
+ """
189
+ Decorator for registering error-correlation parmaterisation form definition to package definition container
190
+
191
+ :param form_name: name of error-correlation parmaterisation form e.g. "random"
192
+ :return: decorator function
193
+ """
194
+
195
+ def decorator(form_cls: Type) -> Type:
196
+ err_corr_forms[form_name] = form_cls
197
+ return form_cls
198
+
199
+ return decorator
200
+
201
+
202
+ @register_err_corr_form("random")
203
+ class RandomCorrelation(BaseErrCorrForm):
204
+
205
+ form = "random"
206
+ is_random = True
207
+
208
+ def build_matrix(self, sli: tuple) -> np.ndarray:
209
+ """
210
+ Returns uncertainty effect error-correlation matrix, populated with error-correlation values defined
211
+ in this parameterisation
212
+
213
+ :param sli: slice of observation variable to return error-correlation matrix for
214
+
215
+ :return: populated error-correlation matrix
216
+ """
217
+
218
+ # evaluate correlation over matrices in form defintion
219
+ dim_lens = self.get_sliced_shape_errcorr(sli)
220
+ n_elems = int(np.prod(dim_lens))
221
+
222
+ submatrix = np.eye(n_elems)
223
+
224
+ return submatrix
225
+
226
+
227
+ @register_err_corr_form("systematic")
228
+ class SystematicCorrelation(BaseErrCorrForm):
229
+
230
+ form = "systematic"
231
+ is_systematic = True
232
+
233
+ def build_matrix(self, sli: tuple) -> np.ndarray:
234
+ """
235
+ Returns uncertainty effect error-correlation matrix, populated with error-correlation values defined
236
+ in this parameterisation
237
+
238
+ :param sli: slice of observation variable to return error-correlation matrix for
239
+
240
+ :return: populated error-correlation matrix
241
+ """
242
+
243
+ # evaluate correlation over matrices in form defintion
244
+ dim_lens = self.get_sliced_shape_errcorr(sli)
245
+ n_elems = int(np.prod(dim_lens))
246
+
247
+ submatrix = np.ones((n_elems, n_elems))
248
+
249
+ return submatrix
250
+
251
+
252
+ @register_err_corr_form("err_corr_matrix")
253
+ class ErrCorrMatrixCorrelation(BaseErrCorrForm):
254
+
255
+ form = "err_corr_matrix"
256
+
257
+ def build_matrix(self, sli: tuple) -> np.ndarray:
258
+ """
259
+ Returns uncertainty effect error-correlation matrix, populated with error-correlation values defined
260
+ in this parameterisation
261
+
262
+ :param sli: slice of observation variable to return error-correlation matrix for
263
+
264
+ :return: populated error-correlation matrix
265
+ """
266
+ all_dims = self._obj[self._unc_var_name].dims
267
+
268
+ sli_submatrix = tuple(
269
+ [sli[i] for i in range(len(all_dims)) if all_dims[i] in self.dims]
270
+ )
271
+
272
+ submatrix = self.slice_errcorr_matrix(
273
+ self._obj[self.params[0]], self.get_varshape_errcorr(), sli_submatrix
274
+ )
275
+
276
+ return submatrix
277
+
278
+
279
+ @register_err_corr_form("ensemble")
280
+ class EnsembleCorrelation(BaseErrCorrForm):
281
+
282
+ form = "ensemble"
283
+
284
+ def build_matrix(self, sli: tuple) -> np.ndarray:
285
+ """
286
+ Returns uncertainty effect error-correlation matrix, populated with error-correlation values defined
287
+ in this parameterisation
288
+
289
+ :param sli: slice of observation variable to return error-correlation matrix for
290
+
291
+ :return: populated error-correlation matrix
292
+ """
293
+
294
+ raise NotImplementedError
295
+
296
+
297
+ if __name__ == "__main__":
298
+ pass