Skip to content

Commit a7e43ad

Browse files
authored
Better docstrings + small theme tweaks (#283)
1 parent f337e63 commit a7e43ad

18 files changed

+354
-41
lines changed

cf_xarray/accessor.py

Lines changed: 160 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -137,12 +137,12 @@ def _apply_single_mapper(mapper):
137137

138138

139139
def _get_groupby_time_accessor(var: DataArray | Dataset, key: str) -> list[str]:
140+
# This first docstring is used by _build_docstring. Do not remove.
140141
"""
141142
Time variable accessor e.g. 'T.month'
142143
"""
143144
"""
144-
Helper method for when our key name is of the nature "T.month" and we want to
145-
isolate the "T" for coordinate mapping
145+
Helper method for decoding datetime components "T.month".
146146
147147
Parameters
148148
----------
@@ -193,7 +193,6 @@ def _get_custom_criteria(
193193
Returns
194194
-------
195195
List[str], Variable name(s) in parent xarray object that matches axis, coordinate, or custom `key`
196-
197196
"""
198197

199198
if isinstance(obj, DataArray):
@@ -1305,7 +1304,8 @@ def keys(self) -> set[str]:
13051304
13061305
Returns
13071306
-------
1308-
Set of valid key names that can be used with __getitem__ or .cf[key].
1307+
set
1308+
Set of valid key names that can be used with __getitem__ or .cf[key].
13091309
"""
13101310

13111311
varnames = list(self.axes) + list(self.coordinates)
@@ -1322,12 +1322,15 @@ def axes(self) -> dict[str, list[str]]:
13221322
13231323
This is useful for checking whether a key is valid for indexing, i.e.
13241324
that the attributes necessary to allow indexing by that key exist.
1325-
However, it will only return the Axis names present in ``.coords``, not Coordinate names.
1325+
However, it will only return the Axis names ``("X", "Y", "Z", "T")``
1326+
present in ``.coords``, not in ``.data_vars``.
13261327
13271328
Returns
13281329
-------
1329-
Dictionary of valid Axis names that can be used with ``__getitem__`` or ``.cf[key]``.
1330-
Will be ("X", "Y", "Z", "T") or a subset thereof.
1330+
dict
1331+
Dictionary with keys that can be used with ``__getitem__`` or as ``.cf[key]``.
1332+
Keys will be the appropriate subset of ("X", "Y", "Z", "T").
1333+
Values are lists of variable names that match that particular key.
13311334
"""
13321335
vardict = {key: _get_coords(self._obj, key) for key in _AXIS_NAMES}
13331336

@@ -1341,12 +1344,16 @@ def coordinates(self) -> dict[str, list[str]]:
13411344
13421345
This is useful for checking whether a key is valid for indexing, i.e.
13431346
that the attributes necessary to allow indexing by that key exist.
1344-
However, it will only return the Coordinate names present in ``.coords``, not Axis names.
1347+
However, it will only return the Coordinate names ``("latitude", "longitude", "vertical", "time")``
1348+
present in ``.coords``, not in ``.data_vars``.
13451349
13461350
Returns
13471351
-------
1348-
Dictionary of valid Coordinate names that can be used with ``__getitem__`` or ``.cf[key]``.
1349-
Will be ("longitude", "latitude", "vertical", "time") or a subset thereof.
1352+
dict
1353+
Dictionary of valid Coordinate names that can be used with ``__getitem__`` or ``.cf[key]``.
1354+
Keys will be the appropriate subset of ``("latitude", "longitude", "vertical", "time")``.
1355+
Values are lists of variable names that match that particular key.
1356+
13501357
"""
13511358
vardict = {key: _get_coords(self._obj, key) for key in _COORD_NAMES}
13521359

@@ -1363,7 +1370,8 @@ def cell_measures(self) -> dict[str, list[str]]:
13631370
13641371
Returns
13651372
-------
1366-
Dictionary of valid cell measure names that can be used with __getitem__ or .cf[key].
1373+
dict
1374+
Dictionary of valid cell measure names that can be used with ``__getitem__`` or ``.cf[key]``.
13671375
"""
13681376

13691377
obj = self._obj
@@ -1404,7 +1412,8 @@ def standard_names(self) -> dict[str, list[str]]:
14041412
14051413
Returns
14061414
-------
1407-
Dictionary mapping standard names to variable names.
1415+
dict
1416+
Dictionary mapping standard names to variable names.
14081417
"""
14091418
if isinstance(self._obj, Dataset):
14101419
variables = self._obj.variables
@@ -1440,7 +1449,7 @@ def get_associated_variable_names(
14401449
Returns
14411450
-------
14421451
names : dict
1443-
Dictionary with keys "ancillary_variables", "cell_measures", "coordinates", "bounds"
1452+
Dictionary with keys "ancillary_variables", "cell_measures", "coordinates", "bounds".
14441453
"""
14451454
keys = ["ancillary_variables", "cell_measures", "coordinates", "bounds"]
14461455
coords: dict[str, list[str]] = {k: [] for k in keys}
@@ -1538,7 +1547,8 @@ def rename_like(
15381547
15391548
Returns
15401549
-------
1541-
DataArray or Dataset with renamed variables
1550+
DataArray or Dataset
1551+
with renamed variables
15421552
"""
15431553
skip = [skip] if isinstance(skip, str) else skip or []
15441554

@@ -1642,7 +1652,8 @@ def guess_coord_axis(self, verbose: bool = False) -> DataArray | Dataset:
16421652
16431653
Returns
16441654
-------
1645-
DataArray or Dataset with appropriate attributes added
1655+
DataArray or Dataset
1656+
with appropriate attributes added
16461657
"""
16471658
obj = self._obj.copy(deep=True)
16481659
for var in obj.coords.variables:
@@ -1843,7 +1854,6 @@ def __getitem__(self, key: str | list[str]) -> DataArray | Dataset:
18431854
18441855
Parameters
18451856
----------
1846-
18471857
key: str, Iterable[str], optional
18481858
One of
18491859
- axes names: "X", "Y", "Z", "T"
@@ -1865,14 +1875,60 @@ def __getitem__(self, key: str | list[str]) -> DataArray | Dataset:
18651875
18661876
``bounds`` variables will not be attached when a DataArray is returned. This
18671877
is a limitation of the xarray data model.
1878+
1879+
Add additional keys by specifying "custom criteria". See :ref:`custom_criteria` for more.
18681880
"""
18691881
return _getitem(self, key)
18701882

18711883
@property
18721884
def formula_terms(self) -> dict[str, dict[str, str]]:
18731885
"""
1874-
Property that returns a dictionary
1875-
{parametric_coord_name: {standard_term_name: variable_name}}
1886+
Property that returns a dictionary mapping the parametric coordinate's name
1887+
to a dictionary that maps "standard term names" to actual variable names.
1888+
1889+
Returns
1890+
-------
1891+
dict
1892+
Dictionary of the form ``{parametric_coord_name: {standard_term_name: variable_name}}``
1893+
1894+
References
1895+
----------
1896+
Please refer to the CF conventions document :
1897+
1. http://cfconventions.org/Data/cf-conventions/cf-conventions-1.8/cf-conventions.html#parametric-vertical-coordinate
1898+
2. http://cfconventions.org/Data/cf-conventions/cf-conventions-1.8/cf-conventions.html#parametric-v-coord.
1899+
1900+
Examples
1901+
--------
1902+
>>> import cf_xarray
1903+
>>> from cf_xarray.datasets import romsds
1904+
1905+
The ``s_rho`` DataArray is an example of a parametric vertical coordinate.
1906+
1907+
>>> romsds.s_rho
1908+
<xarray.DataArray 's_rho' (s_rho: 30)>
1909+
array([-0.983333, -0.95 , -0.916667, -0.883333, -0.85 , -0.816667,
1910+
-0.783333, -0.75 , -0.716667, -0.683333, -0.65 , -0.616667,
1911+
-0.583333, -0.55 , -0.516667, -0.483333, -0.45 , -0.416667,
1912+
-0.383333, -0.35 , -0.316667, -0.283333, -0.25 , -0.216667,
1913+
-0.183333, -0.15 , -0.116667, -0.083333, -0.05 , -0.016667])
1914+
Coordinates:
1915+
* s_rho (s_rho) float64 -0.9833 -0.95 -0.9167 ... -0.05 -0.01667
1916+
hc float64 20.0
1917+
h float64 603.9
1918+
Vtransform float64 2.0
1919+
Cs_r (s_rho) float64 -0.933 -0.8092 -0.6988 ... -0.0005206 -5.758e-05
1920+
Attributes:
1921+
long_name: S-coordinate at RHO-points
1922+
valid_min: -1.0
1923+
valid_max: 0.0
1924+
standard_name: ocean_s_coordinate_g2
1925+
formula_terms: s: s_rho C: Cs_r eta: zeta depth: h depth_c: hc
1926+
field: s_rho, scalar
1927+
1928+
Now access the formula terms
1929+
1930+
>>> romsds.cf.formula_terms
1931+
{'s_rho': {'s': 's_rho', 'C': 'Cs_r', 'eta': 'zeta', 'depth': 'h', 'depth_c': 'hc'}}
18761932
"""
18771933
results = {}
18781934
for dim in _get_dims(self._obj, "Z"):
@@ -1887,12 +1943,23 @@ def formula_terms(self) -> dict[str, dict[str, str]]:
18871943
@property
18881944
def bounds(self) -> dict[str, list[str]]:
18891945
"""
1890-
Property that returns a dictionary mapping valid keys
1946+
Property that returns a dictionary mapping keys
18911947
to the variable names of their bounds.
18921948
18931949
Returns
18941950
-------
1895-
Dictionary mapping valid keys to the variable names of their bounds.
1951+
dict
1952+
Dictionary mapping keys to the variable names of their bounds.
1953+
1954+
See Also
1955+
--------
1956+
Dataset.cf.get_bounds_dim_name
1957+
1958+
Examples
1959+
--------
1960+
>>> from cf_xarray.datasets import mollwds
1961+
>>> mollwds.cf.bounds
1962+
{'lat': ['lat_bounds'], 'latitude': ['lat_bounds'], 'lon': ['lon_bounds'], 'longitude': ['lon_bounds']}
18961963
"""
18971964

18981965
obj = self._obj
@@ -1960,16 +2027,26 @@ def add_bounds(self, keys: str | Iterable[str]):
19602027
19612028
Returns
19622029
-------
1963-
DataArray or Dataset with bounds variables added and appropriate "bounds" attribute set.
2030+
DataArray or Dataset
2031+
with bounds variables added and appropriate "bounds" attribute set.
19642032
19652033
Raises
19662034
------
19672035
KeyError
19682036
19692037
Notes
19702038
-----
1971-
The bounds variables are automatically named f"{dim}_bounds" where ``dim``
2039+
The bounds variables are automatically named ``f"{dim}_bounds"`` where ``dim``
19722040
is a dimension name.
2041+
2042+
Examples
2043+
--------
2044+
>>> from cf_xarray.datasets import airds
2045+
>>> airds.cf.bounds
2046+
{}
2047+
>>> updated = airds.cf.add_bounds("time")
2048+
>>> updated.cf.bounds
2049+
{'T': ['time_bounds'], 'time': ['time_bounds']}
19732050
"""
19742051
if isinstance(keys, str):
19752052
keys = [keys]
@@ -2043,6 +2120,8 @@ def bounds_to_vertices(
20432120
tranpose data without raising any warning or error, which make attributes
20442121
unreliable.
20452122
2123+
References
2124+
----------
20462125
Please refer to the CF conventions document : http://cfconventions.org/Data/cf-conventions/cf-conventions-1.8/cf-conventions.html#cell-boundaries.
20472126
"""
20482127
if keys is None:
@@ -2100,6 +2179,10 @@ def decode_vertical_coords(self, prefix="z"):
21002179
21012180
.. warning::
21022181
Very lightly tested. Please double check the results.
2182+
2183+
See Also
2184+
--------
2185+
Dataset.cf.formula_terms
21032186
"""
21042187
ds = self._obj
21052188

@@ -2160,8 +2243,52 @@ class CFDataArrayAccessor(CFAccessor):
21602243
@property
21612244
def formula_terms(self) -> dict[str, str]:
21622245
"""
2163-
Property that returns a dictionary
2164-
{parametric_coord_name: {standard_term_name: variable_name}}
2246+
Property that returns a dictionary mapping the parametric coordinate's name
2247+
to a dictionary that maps "standard term names" to actual variable names.
2248+
2249+
Returns
2250+
-------
2251+
dict
2252+
Dictionary of the form ``{parametric_coord_name: {standard_term_name: variable_name}}``
2253+
2254+
References
2255+
----------
2256+
Please refer to the CF conventions document :
2257+
1. http://cfconventions.org/Data/cf-conventions/cf-conventions-1.8/cf-conventions.html#parametric-vertical-coordinate
2258+
2. http://cfconventions.org/Data/cf-conventions/cf-conventions-1.8/cf-conventions.html#parametric-v-coord.
2259+
2260+
Examples
2261+
--------
2262+
>>> import cf_xarray
2263+
>>> from cf_xarray.datasets import romsds
2264+
2265+
The ``s_rho`` DataArray is an example of a parametric vertical coordinate.
2266+
2267+
>>> romsds.s_rho
2268+
<xarray.DataArray 's_rho' (s_rho: 30)>
2269+
array([-0.983333, -0.95 , -0.916667, -0.883333, -0.85 , -0.816667,
2270+
-0.783333, -0.75 , -0.716667, -0.683333, -0.65 , -0.616667,
2271+
-0.583333, -0.55 , -0.516667, -0.483333, -0.45 , -0.416667,
2272+
-0.383333, -0.35 , -0.316667, -0.283333, -0.25 , -0.216667,
2273+
-0.183333, -0.15 , -0.116667, -0.083333, -0.05 , -0.016667])
2274+
Coordinates:
2275+
* s_rho (s_rho) float64 -0.9833 -0.95 -0.9167 ... -0.05 -0.01667
2276+
hc float64 20.0
2277+
h float64 603.9
2278+
Vtransform float64 2.0
2279+
Cs_r (s_rho) float64 -0.933 -0.8092 -0.6988 ... -0.0005206 -5.758e-05
2280+
Attributes:
2281+
long_name: S-coordinate at RHO-points
2282+
valid_min: -1.0
2283+
valid_max: 0.0
2284+
standard_name: ocean_s_coordinate_g2
2285+
formula_terms: s: s_rho C: Cs_r eta: zeta depth: h depth_c: hc
2286+
field: s_rho, scalar
2287+
2288+
Now access the formula terms
2289+
2290+
>>> romsds.s_rho.cf.formula_terms
2291+
{'s': 's_rho', 'C': 'Cs_r', 'eta': 'zeta', 'depth': 'h', 'depth_c': 'hc'}
21652292
"""
21662293
da = self._obj
21672294
if "formula_terms" not in ChainMap(da.attrs, da.encoding):
@@ -2204,6 +2331,8 @@ def __getitem__(self, key: str | list[str]) -> DataArray:
22042331
-----
22052332
Associated CF variables will be attached as coordinate variables
22062333
by parsing attributes such as ``cell_measures``, ``coordinates`` etc.
2334+
2335+
Add additional keys by specifying "custom criteria". See :ref:`custom_criteria` for more.
22072336
"""
22082337

22092338
if not isinstance(key, str):
@@ -2214,11 +2343,16 @@ def __getitem__(self, key: str | list[str]) -> DataArray:
22142343
return _getitem(self, key)
22152344

22162345
@property
2217-
def is_flag_variable(self):
2346+
def is_flag_variable(self) -> bool:
22182347
"""
22192348
Returns True if the DataArray satisfies CF conventions for flag variables.
22202349
2221-
Flag masks are not supported yet.
2350+
.. warning::
2351+
Flag masks are not supported yet.
2352+
2353+
Returns
2354+
-------
2355+
bool
22222356
"""
22232357
if (
22242358
isinstance(self._obj, DataArray)

cf_xarray/geometry.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,10 @@ def shapely_to_cf(geometries: Union[xr.DataArray, Sequence], grid_mapping: str =
9797
- 'node_count' : The number of nodes per feature. Absent if all instances are Points.
9898
- 'geometry_container' : Empty variable with attributes describing the geometry type.
9999
- Other variables are not implemented as only Points are currently understood.
100+
101+
References
102+
----------
103+
Please refer to the CF conventions document: http://cfconventions.org/Data/cf-conventions/cf-conventions-1.8/cf-conventions.html#geometries
100104
"""
101105
# Get all types to call the appropriate translation function.
102106
types = {
@@ -149,6 +153,10 @@ def cf_to_shapely(ds: xr.Dataset):
149153
A 1D DataArray of shapely objects.
150154
It has the same dimension as the ``node_count`` or the coordinates variables, or
151155
``features`` if those were not present in ``ds``.
156+
157+
References
158+
----------
159+
Please refer to the CF conventions document: http://cfconventions.org/Data/cf-conventions/cf-conventions-1.8/cf-conventions.html#geometries
152160
"""
153161
geom_type = ds.geometry_container.attrs["geometry_type"]
154162
if geom_type == "point":

0 commit comments

Comments
 (0)