Skip to content

Commit 1e3eb0a

Browse files
authored
More doc updates (#281)
1 parent 44ef351 commit 1e3eb0a

File tree

10 files changed

+144
-67
lines changed

10 files changed

+144
-67
lines changed

cf_xarray/accessor.py

Lines changed: 12 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -232,11 +232,6 @@ def _get_axis_coord(obj: Union[DataArray, Dataset], key: str) -> List[str]:
232232
DataArray belonging to the coordinate to be checked
233233
key : str, ["X", "Y", "Z", "T", "longitude", "latitude", "vertical", "time"]
234234
key to check for.
235-
error : bool
236-
raise errors when key is not found or interpretable. Use False and provide default
237-
to replicate dict.get(k, None).
238-
default : Any
239-
default value to return when error is False.
240235
241236
Returns
242237
-------
@@ -1011,7 +1006,6 @@ def isin(self, test_elements):
10111006
to the corresponding value in "flag_values" before passing
10121007
that on to DataArray.isin.
10131008
1014-
10151009
Returns
10161010
-------
10171011
isin : DataArray
@@ -1409,11 +1403,6 @@ def standard_names(self) -> Dict[str, List[str]]:
14091403
"""
14101404
Returns a dictionary mapping standard names to variable names.
14111405
1412-
Parameters
1413-
----------
1414-
obj : DataArray, Dataset
1415-
Xarray object to process
1416-
14171406
Returns
14181407
-------
14191408
Dictionary mapping standard names to variable names.
@@ -1446,12 +1435,13 @@ def get_associated_variable_names(
14461435
----------
14471436
name : Hashable
14481437
skip_bounds : bool, optional
1449-
error: bool, optional
1438+
error : bool, optional
14501439
Raise or ignore errors.
14511440
14521441
Returns
1453-
------
1454-
Dict with keys "ancillary_variables", "cell_measures", "coordinates", "bounds"
1442+
-------
1443+
names : dict
1444+
Dictionary with keys "ancillary_variables", "cell_measures", "coordinates", "bounds"
14551445
"""
14561446
keys = ["ancillary_variables", "cell_measures", "coordinates", "bounds"]
14571447
coords: Dict[str, List[str]] = {k: [] for k in keys}
@@ -1542,7 +1532,7 @@ def rename_like(
15421532
----------
15431533
other : DataArray, Dataset
15441534
Variables will be renamed to match variable names in this xarray object
1545-
skip: str, Iterable[str], optional
1535+
skip : str, Iterable[str], optional
15461536
Limit the renaming excluding
15471537
("axes", "bounds", cell_measures", "coordinates", "standard_names")
15481538
or a subset thereof.
@@ -1706,7 +1696,7 @@ def differentiate(
17061696
17071697
Parameters
17081698
----------
1709-
positive_upward: optional, bool
1699+
positive_upward : optional, bool
17101700
Change sign of the derivative based on the ``"positive"`` attribute of ``coord``
17111701
so that positive values indicate increasing upward.
17121702
If ``positive=="down"``, then multiplied by -1.
@@ -1719,8 +1709,8 @@ def differentiate(
17191709
--------
17201710
DataArray.cf.differentiate
17211711
Dataset.cf.differentiate
1722-
xarray.DataArray.differentiate: underlying xarray function
1723-
xarray.Dataset.differentiate: underlying xarray function
1712+
xarray.DataArray.differentiate : underlying xarray function
1713+
xarray.Dataset.differentiate : underlying xarray function
17241714
"""
17251715
coord = apply_mapper(
17261716
(_single(_get_coords),), self._obj, coord, error=False, default=[coord]
@@ -1755,13 +1745,13 @@ def add_canonical_attributes(
17551745
17561746
Parameters
17571747
----------
1758-
override: bool
1748+
override : bool
17591749
Override existing attributes.
1760-
skip: str, iterable, optional
1750+
skip : str, iterable, optional
17611751
Attribute(s) to skip: ``{"units", "grib", "amip", "description"}``.
1762-
verbose: bool
1752+
verbose : bool
17631753
Print added attributes to screen.
1764-
source: optional
1754+
source : optional
17651755
Path of `cf-standard-name-table.xml` or file object containing XML data.
17661756
If ``None``, use the default version associated with ``cf-xarray``.
17671757

cf_xarray/geometry.py

Lines changed: 34 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,18 @@ def reshape_unique_geometries(
1919
Parameters
2020
----------
2121
ds : xr.Dataset
22-
A Dataset.
22+
A Dataset.
2323
geom_var : string
24-
Name of the variable in `ds` that contains the geometry objects of type shapely.geometry.
25-
The variable must be 1D.
24+
Name of the variable in `ds` that contains the geometry objects of type shapely.geometry.
25+
The variable must be 1D.
2626
new_dim : string
27-
Name of the new dimension in the returned object.
27+
Name of the new dimension in the returned object.
2828
2929
Returns
3030
-------
3131
Dataset
32-
All variables sharing the dimension of `ds[geom_var]` are reshaped so that `new_dim`
33-
as a length equal to the number of unique geometries.
32+
All variables sharing the dimension of `ds[geom_var]` are reshaped so that `new_dim`
33+
as a length equal to the number of unique geometries.
3434
"""
3535
if ds[geom_var].ndim > 1:
3636
raise ValueError(
@@ -78,24 +78,25 @@ def shapely_to_cf(geometries: Union[xr.DataArray, Sequence], grid_mapping: str =
7878
Parameters
7979
----------
8080
geometries : sequence of shapely geometries or xarray.DataArray
81-
A sequence of geometry objects or a Dataset with a "geometry" variable storing such geometries.
82-
All geometries must be of the same base type : Point, Line or Polygon, but multipart geometries are accepted.
81+
A sequence of geometry objects or a Dataset with a "geometry" variable storing such geometries.
82+
All geometries must be of the same base type : Point, Line or Polygon, but multipart geometries are accepted.
83+
8384
grid_mapping : str, optional
84-
A CF grid mapping name. When given, coordinates and attributes are named and set accordingly.
85-
Defaults to None, in which case the coordinates are simply names "crd_x" and "crd_y".
85+
A CF grid mapping name. When given, coordinates and attributes are named and set accordingly.
86+
Defaults to None, in which case the coordinates are simply names "crd_x" and "crd_y".
8687
87-
.. warning::
88-
Only the `longitude_latitude` grid mapping is currently implemented.
88+
.. warning::
89+
Only the `longitude_latitude` grid mapping is currently implemented.
8990
9091
Returns
9192
-------
9293
xr.Dataset
93-
A dataset with shapely geometry objects translated into CF-compliant variables :
94-
- 'x', 'y' : the node coordinates
95-
- 'crd_x', 'crd_y' : the feature coordinates (might have different names if `grid_mapping` is available).
96-
- 'node_count' : The number of nodes per feature. Absent if all instances are Points.
97-
- 'geometry_container' : Empty variable with attributes describing the geometry type.
98-
- Other variables are not implemented as only Points are currently understood.
94+
A dataset with shapely geometry objects translated into CF-compliant variables :
95+
- 'x', 'y' : the node coordinates
96+
- 'crd_x', 'crd_y' : the feature coordinates (might have different names if `grid_mapping` is available).
97+
- 'node_count' : The number of nodes per feature. Absent if all instances are Points.
98+
- 'geometry_container' : Empty variable with attributes describing the geometry type.
99+
- Other variables are not implemented as only Points are currently understood.
99100
"""
100101
# Get all types to call the appropriate translation function.
101102
types = {
@@ -139,15 +140,15 @@ def cf_to_shapely(ds: xr.Dataset):
139140
Parameters
140141
----------
141142
ds : xr.Dataset
142-
Must contain a `geometry_container` variable with attributes giving the geometry specifications.
143-
Must contain all variables needed to reconstruct the geometries listed in these specifications.
143+
Must contain a ``geometry_container`` variable with attributes giving the geometry specifications.
144+
Must contain all variables needed to reconstruct the geometries listed in these specifications.
144145
145146
Returns
146147
-------
147-
xr.DataArray
148-
A 1D DataArray of shapely objects.
149-
It has the same dimension as the `node_count` or the coordinates variables, or
150-
'features' if those were not present in `ds `.
148+
da: xr.DataArray
149+
A 1D DataArray of shapely objects.
150+
It has the same dimension as the ``node_count`` or the coordinates variables, or
151+
``features`` if those were not present in ``ds``.
151152
"""
152153
geom_type = ds.geometry_container.attrs["geometry_type"]
153154
if geom_type == "point":
@@ -168,13 +169,13 @@ def points_to_cf(pts: Union[xr.DataArray, Sequence]):
168169
Parameters
169170
----------
170171
pts : sequence of shapely.geometry.Point or MultiPoint
171-
The sequence of [multi]points to translate to a CF dataset.
172+
The sequence of [multi]points to translate to a CF dataset.
172173
173174
Returns
174175
-------
175176
xr.Dataset
176-
A Dataset with variables 'x', 'y', 'crd_x', 'crd_y', 'node_count' and 'geometry_container'.
177-
The coordinates of MultiPoint instances are their first point.
177+
A Dataset with variables 'x', 'y', 'crd_x', 'crd_y', 'node_count' and 'geometry_container'.
178+
The coordinates of MultiPoint instances are their first point.
178179
"""
179180
if isinstance(pts, xr.DataArray):
180181
dim = pts.dims[0]
@@ -229,16 +230,16 @@ def cf_to_points(ds: xr.Dataset):
229230
Parameters
230231
----------
231232
ds : xr.Dataset
232-
A dataset with CF-compliant point geometries.
233-
Must have a "geometry_container" variable with at least a 'node_coordinates' attribute.
234-
Must also have the two 1D variables listed by this attribute.
233+
A dataset with CF-compliant point geometries.
234+
Must have a "geometry_container" variable with at least a 'node_coordinates' attribute.
235+
Must also have the two 1D variables listed by this attribute.
235236
236237
Returns
237238
-------
238239
geometry : xr.DataArray
239-
A 1D array of shapely.geometry.[Multi]Point objects.
240-
It has the same dimension as the `node_count` or the coordinates variables, or
241-
'features' if those were not present in `ds `.
240+
A 1D array of shapely.geometry.[Multi]Point objects.
241+
It has the same dimension as the ``node_count`` or the coordinates variables, or
242+
``'features'`` if those were not present in ``ds``.
242243
"""
243244
from shapely.geometry import MultiPoint, Point
244245

cf_xarray/options.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,29 @@
1414

1515
class set_options:
1616
"""Set options for cf-xarray in a controlled context.
17-
Currently supported options:
18-
- ``custom_critera``: Translate from axis, coord, or custom name to
19-
variable name optionally using ``custom_criteria``. Default: [].
17+
18+
Parameters
19+
----------
20+
custom_criteria : dict
21+
Translate from axis, coord, or custom name to
22+
variable name optionally using ``custom_criteria``. Default: [].
23+
24+
Examples
25+
--------
2026
2127
You can use ``set_options`` either as a context manager:
28+
29+
>>> import numpy as np
30+
>>> import xarray as xr
2231
>>> my_custom_criteria = { 'ssh': {'name': 'elev$'} }
2332
>>> ds = xr.Dataset({"elev": np.arange(1000)})
2433
>>> with cf_xarray.set_options(custom_criteria=my_custom_criteria):
25-
... assert (ds['elev'] == ds.cf['ssh']).all()
34+
... xr.testing.assert_identical(ds['elev'], ds.cf['ssh'])
2635
2736
Or to set global options:
37+
2838
>>> cf_xarray.set_options(custom_criteria=my_custom_criteria)
29-
>>> assert (ds['elev'] == ds.cf['ssh']).all()
39+
>>> xr.testing.assert_identical(ds['elev'], ds.cf['ssh'])
3040
"""
3141

3242
def __init__(self, **kwargs):

ci/doc.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ dependencies:
99
- pooch
1010
- xarray
1111
- sphinx
12-
- nbsphinx
12+
- sphinx-copybutton
1313
- numpydoc
1414
- sphinx-autosummary-accessors
1515
- ipython

doc/api.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ Top-level API
1313
vertices_to_bounds
1414
shapely_to_cf
1515
cf_to_shapely
16+
set_options
1617

1718
.. currentmodule:: xarray
1819

doc/conf.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
"sphinx_autosummary_accessors",
5151
"IPython.sphinxext.ipython_directive",
5252
"myst_nb",
53+
"sphinx_copybutton",
5354
]
5455

5556
extlinks = {
@@ -252,7 +253,7 @@
252253

253254
intersphinx_mapping = {
254255
"python": ("https://docs.python.org/3/", None),
255-
"xarray": ("http://xarray.pydata.org/en/stable/", None),
256+
"xarray": ("https://xarray.pydata.org/en/stable/", None),
256257
}
257258

258259
autosummary_generate = True

doc/custom-criteria.md

Lines changed: 76 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,88 @@
11
---
22
jupytext:
33
text_representation:
4-
format_name: myst
4+
format_name: myst
55
kernelspec:
66
display_name: Python 3
77
name: python3
88
---
99
```{eval-rst}
10-
.. currentmodule:: xarray
10+
.. currentmodule:: cf_xarray
1111
```
1212

1313
(custom_criteria)=
1414
# Custom Criteria
15+
16+
Fundamentally, cf_xarray uses rules or "criteria" to interpret user input using the
17+
attributes of an Xarray object (`.attrs`). These criteria are simple dictionaries. For example, here are the criteria used for identifying a "latitude" variable:
18+
```python
19+
coordinate_criteria = {
20+
"latitude": {
21+
"standard_name": ("latitude",),
22+
"units": (
23+
"degree_north",
24+
"degree_N",
25+
"degreeN",
26+
"degrees_north",
27+
"degrees_N",
28+
"degreesN",
29+
),
30+
"_CoordinateAxisType": ("Lat",),
31+
},
32+
}
33+
```
34+
35+
This dictionary maps the user input (`"latitude"`) to another dictionary which in turn maps an attribute name to a tuple of acceptable values for that attribute. So any variable with either `standard_name: latitude` or `_CoordinateAxisType: Lat_` or any of the `unit`s listed above will match the user-input `"latitude"`.
36+
37+
cf_xarray lets you provide your own custom criteria in addition to those built-in. Here's an example:
38+
```{code-cell}
39+
import cf_xarray as cfxr
40+
import numpy as np
41+
import xarray as xr
42+
43+
ds = xr.Dataset({
44+
"salt1": ("x", np.arange(10), {"standard_name": "sea_water_salinity"}),
45+
"salt2": ("x", np.arange(10), {"standard_name": "sea_water_practical_salinity"}),
46+
})
47+
48+
# first define our criteria
49+
salt_criteria = {
50+
"sea_water_salinity": {
51+
"standard_name": "sea_water_salinity|sea_water_practical_salinity"
52+
}
53+
}
54+
```
55+
56+
Now we apply our custom criteria temporarily using {py:func}`set_options` as a context manager. The following sets `"sea_water_salinity"` as an alias for variables that have either `"sea_water_salinity"` or `"sea_water_practical_salinity"` (note the use of regular expressions as a value). Here's how that works in practice
57+
```{code-cell}
58+
with cfxr.set_options(custom_criteria=salt_criteria):
59+
salty = ds.cf[["sea_water_salinity"]]
60+
salty
61+
```
62+
63+
Note that `salty` contains both `salt1` and `salt2`. Without setting these criteria, we would only get `salt1` by default
64+
```{code-cell}
65+
ds.cf[["sea_water_salinity"]]
66+
```
67+
68+
We can also use {py:func}`set_options` to set the criteria globally.
69+
```{code-cell}
70+
cfxr.set_options(custom_criteria=salt_criteria)
71+
ds.cf[["sea_water_salinity"]]
72+
```
73+
74+
Again we get back both `salt1` and `salt2`. To limit side effects of setting criteria globally, we recommend that you use `set_options` as a context manager.
75+
76+
```{tip}
77+
To reset your custom criteria use `cfxr.set_options(custom_criteria=())`
78+
```
79+
80+
You can also match on the variable name, though be careful!
81+
```{code-cell}
82+
salt_criteria = {
83+
"salinity": {"name": "salt*"}
84+
}
85+
cfxr.set_options(custom_criteria=salt_criteria)
86+
87+
ds.cf[["salinity"]]
88+
```

doc/flags.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ Similarly with membership tests using {py:meth}`DataArray.cf.isin`
4444
da.cf.isin(["indian_ocean", "pacific_ocean"])
4545
```
4646

47-
You can also check whether a DataArray has the appropriate attributes to be recognized as a flag variable.
47+
You can also check whether a DataArray has the appropriate attributes to be recognized as a flag variable using {py:meth}`DataArray.cf.is_flag_variable`
4848
```{code-cell}
4949
da.cf.is_flag_variable
5050
```

doc/units.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
jupytext:
33
text_representation:
4-
format_name: myst
4+
format_name: myst
55
kernelspec:
66
display_name: Python 3
77
name: python3

0 commit comments

Comments
 (0)