Skip to content

Commit 9d53560

Browse files
authored
docs (#48)
* docs * update isort call. * update pre-commit * fix isort
1 parent a562c57 commit 9d53560

File tree

7 files changed

+162
-24
lines changed

7 files changed

+162
-24
lines changed

.github/workflows/linting.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,4 +59,4 @@ jobs:
5959
python -m pip install isort
6060
- name: isort check
6161
run: |
62-
isort --recursive --check-only .
62+
isort --check-only .

.pre-commit-config.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
repos:
33
# isort should run before black as black sometimes tweaks the isort output
44
- repo: https://github.com/timothycrosley/isort
5-
rev: 4.3.21-2
5+
rev: 5.0.4
66
hooks:
77
- id: isort
88
files: .+\.py$
@@ -16,7 +16,7 @@ repos:
1616
hooks:
1717
- id: flake8
1818
- repo: https://github.com/pre-commit/mirrors-mypy
19-
rev: v0.781 # Must match ci/requirements/*.yml
19+
rev: v0.782 # Must match ci/requirements/*.yml
2020
hooks:
2121
- id: mypy
2222
# run this occasionally, ref discussion https://github.com/pydata/xarray/pull/3194

cf_xarray/accessor.py

Lines changed: 89 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -149,11 +149,11 @@ def _get_axis_coord(
149149
150150
Parameters
151151
----------
152-
var : DataArray, Dataset
152+
var: DataArray, Dataset
153153
DataArray belonging to the coordinate to be checked
154-
key : str, ["X", "Y", "Z", "T", "longitude", "latitude", "vertical", "time"]
154+
key: str, ["X", "Y", "Z", "T", "longitude", "latitude", "vertical", "time"]
155155
key to check for.
156-
error : bool
156+
error: bool
157157
raise errors when key is not found or interpretable. Use False and provide default
158158
to replicate dict.get(k, None).
159159
default: Any
@@ -217,7 +217,24 @@ def _get_measure(
217217
da: xr.DataArray, key: str, error: bool = True, default: str = None
218218
) -> Optional[str]:
219219
"""
220-
Interprets 'cell_measures'.
220+
Translate from cell measures ("area" or "volume") to appropriate variable name.
221+
This function interprets the ``cell_measures`` attribute on DataArrays.
222+
223+
Parameters
224+
----------
225+
da: DataArray
226+
DataArray belonging to the coordinate to be checked
227+
key: str, ["area", "volume"]
228+
key to check for.
229+
error: bool
230+
raise errors when key is not found or interpretable. Use False and provide default
231+
to replicate dict.get(k, None).
232+
default: Any
233+
default value to return when error is False.
234+
235+
Returns
236+
-------
237+
List[str], Variable name(s) in parent xarray object that matches axis or coordinate `key`
221238
"""
222239
if not isinstance(da, DataArray):
223240
raise NotImplementedError("Measures not implemented for Datasets yet.")
@@ -254,6 +271,9 @@ def _get_measure(
254271

255272

256273
#: Default mappers for common keys.
274+
# TODO: Make the values of this a tuple,
275+
# so that multiple mappers can be used for a single key
276+
# We need this for groupby("T.month") and groupby("latitude") for example.
257277
_DEFAULT_KEY_MAPPERS: Mapping[str, Mapper] = {
258278
"dim": _get_axis_coord,
259279
"dims_or_levels": _get_axis_coord, # reset_index
@@ -280,7 +300,19 @@ def _filter_by_standard_names(ds: xr.Dataset, name: Union[str, List[str]]) -> Li
280300

281301

282302
def _get_list_standard_names(obj: xr.Dataset) -> List[str]:
283-
""" Returns a sorted list of standard names in Dataset. """
303+
"""
304+
Returns a sorted list of standard names in Dataset.
305+
306+
Parameters
307+
----------
308+
309+
obj: DataArray, Dataset
310+
Xarray objec to process
311+
312+
Returns
313+
-------
314+
list of standard names in dataset
315+
"""
284316
names = []
285317
for k, v in obj.variables.items():
286318
if "standard_name" in v.attrs:
@@ -332,15 +364,18 @@ def wrapper(*args, **kwargs):
332364

333365

334366
class _CFWrappedClass:
367+
"""
368+
This class is used to wrap any class in _WRAPPED_CLASSES.
369+
"""
370+
335371
def __init__(self, towrap, accessor: "CFAccessor"):
336372
"""
337-
This class is used to wrap any class in _WRAPPED_CLASSES.
338-
339373
Parameters
340374
----------
341375
towrap : Resample, GroupBy, Coarsen, Rolling, Weighted
342376
Instance of xarray class that is being wrapped.
343377
accessor : CFAccessor
378+
Parent accessor object
344379
"""
345380
self.wrapped = towrap
346381
self.accessor = accessor
@@ -369,7 +404,10 @@ def __init__(self, obj, accessor):
369404

370405
def _plot_decorator(self, func):
371406
"""
372-
This decorator is used to set kwargs on plotting functions.
407+
This decorator is used to set default kwargs on plotting functions.
408+
409+
For now, this is setting ``xincrease`` and ``yincrease``. It could set
410+
other arguments in the future.
373411
"""
374412
valid_keys = self.accessor.get_valid_keys()
375413

@@ -402,6 +440,9 @@ def _plot_wrapper(*args, **kwargs):
402440
return _plot_wrapper
403441

404442
def __call__(self, *args, **kwargs):
443+
"""
444+
Allows .plot()
445+
"""
405446
plot = _getattr(
406447
obj=self._obj,
407448
attr="plot",
@@ -411,6 +452,9 @@ def __call__(self, *args, **kwargs):
411452
return self._plot_decorator(plot)(*args, **kwargs)
412453

413454
def __getattr__(self, attr):
455+
"""
456+
Wraps .plot.contour() for example.
457+
"""
414458
return _getattr(
415459
obj=self._obj.plot,
416460
attr=attr,
@@ -423,10 +467,21 @@ def __getattr__(self, attr):
423467

424468

425469
class CFAccessor:
470+
"""
471+
Common Dataset and DataArray accessor functionality.
472+
"""
473+
426474
def __init__(self, da):
427475
self._obj = da
428476

429-
def _process_signature(self, func, args, kwargs, key_mappers):
477+
def _process_signature(self, func: Callable, args, kwargs, key_mappers):
478+
"""
479+
Processes a function's signature, args, kwargs:
480+
1. Binds *args so that everthing is a Mapping from kwarg name to values
481+
2. Calls _rewrite_values to rewrite any special CF names to normal xarray names.
482+
This uses key_mappers
483+
3. Unpacks arguments if necessary before returning them.
484+
"""
430485
sig = inspect.signature(func, follow_wrapped=False)
431486

432487
# Catch things like .isel(T=5).
@@ -456,7 +511,24 @@ def _process_signature(self, func, args, kwargs, key_mappers):
456511
return arguments
457512

458513
def _rewrite_values(self, kwargs, key_mappers: dict, var_kws):
459-
""" rewrites 'dim' for example using 'mapper' """
514+
"""
515+
Rewrites the values in a Mapping from kwarg to value.
516+
517+
Parameters
518+
----------
519+
kwargs: Mapping
520+
Mapping from kwarg name to value
521+
key_mappers: Mapping
522+
Mapping from kwarg name to a Mapper function that will convert a
523+
given CF "special" name to an xarray name.
524+
var_kws: List[str]
525+
List of variable kwargs that need special treatment.
526+
e.g. **indexers_kwargs in isel
527+
528+
Returns
529+
-------
530+
dict of kwargs with fully rewritten values.
531+
"""
460532
updates: dict = {}
461533

462534
# allow multiple return values here.
@@ -558,11 +630,17 @@ def _describe(self):
558630
return text
559631

560632
def describe(self):
633+
"""
634+
Print a string repr to screen.
635+
"""
561636
print(self._describe())
562637

563638
def get_valid_keys(self) -> Set[str]:
564639
"""
565-
Returns valid keys for .cf[]
640+
Utility function that returns valid keys for .cf[].
641+
642+
This is useful for checking whether a key is valid for indexing, i.e.
643+
that the attributes necessary to allow indexing by that key exist.
566644
567645
Returns
568646
-------

cf_xarray/tests/test_accessor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import matplotlib as mpl
2-
import matplotlib.pyplot as plt
32
import pytest
43
import xarray as xr
4+
from matplotlib import pyplot as plt
55
from xarray.testing import assert_identical
66

77
import cf_xarray # noqa

cf_xarray/utils.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,21 @@ def either_dict_or_kwargs(
2929

3030
def is_dict_like(value: Any) -> bool:
3131
return hasattr(value, "keys") and hasattr(value, "__getitem__")
32+
33+
34+
# copied from xarray
35+
class UncachedAccessor:
36+
""" Acts like a property, but on both classes and class instances
37+
This class is necessary because some tools (e.g. pydoc and sphinx)
38+
inspect classes for which property returns itself and not the
39+
accessor.
40+
"""
41+
42+
def __init__(self, accessor):
43+
self._accessor = accessor
44+
45+
def __get__(self, obj, cls):
46+
if obj is None:
47+
return self._accessor
48+
49+
return self._accessor(obj)

doc/api.rst

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ DataArray
1010
:toctree: generated/
1111
:template: autosummary/accessor_attribute.rst
1212

13-
13+
DataArray.cf.plot
1414

1515
.. autosummary::
1616
:toctree: generated/
@@ -26,8 +26,6 @@ Dataset
2626
:toctree: generated/
2727
:template: autosummary/accessor_attribute.rst
2828

29-
30-
3129
.. autosummary::
3230
:toctree: generated/
3331
:template: autosummary/accessor_method.rst

doc/contributing.rst

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,59 @@
11
.. currentmodule:: cf_xarray
22

3+
.. ipython:: python
4+
:suppress:
5+
6+
import cf_xarray.accessor
7+
38
Contributing
49
--------------
510

6-
This section will be expanded later.
7-
8-
.. autodata:: cf_xarray.accessor.coordinate_criteria
9-
.. autodata:: cf_xarray.accessor._WRAPPED_CLASSES
11+
This section will be expanded later. For now it lists docstrings for a number of internal variables, classes and functions.
1012

11-
The following names are "special"
13+
Variables
14+
~~~~~~~~~
1215

1316
.. autodata:: cf_xarray.accessor._AXIS_NAMES
14-
.. autodata:: cf_xarray.accessor._COORD_NAMES
1517
.. autodata:: cf_xarray.accessor._CELL_MEASURES
18+
.. autodata:: cf_xarray.accessor._COORD_NAMES
19+
.. autodata:: cf_xarray.accessor._WRAPPED_CLASSES
20+
21+
22+
Attribute parsing
23+
+++++++++++++++++
24+
25+
This dictionary contains criteria for identifying axis and coords using CF attributes. It was copied from MetPy
26+
27+
.. autosummary::
28+
:toctree: generated/
29+
30+
~accessor.coordinate_criteria
31+
32+
Classes
33+
~~~~~~~
34+
35+
.. autosummary::
36+
:toctree: generated/
37+
:template: autosummary/accessor_class.rst
38+
39+
40+
~accessor.CFAccessor
41+
~accessor._CFWrappedClass
42+
~accessor._CFWrappedPlotMethods
43+
44+
Functions
45+
~~~~~~~~~
46+
47+
48+
Primarily for developer reference. Some of these could become public API if necessary.
49+
50+
.. autosummary::
51+
:toctree: generated/
52+
53+
~accessor._getattr
54+
~accessor._get_axis_coord
55+
~accessor._get_axis_coord_single
56+
~accessor._get_list_standard_names
57+
~accessor._get_measure
58+
~accessor._get_measure_variable
59+
accessor._CFWrappedPlotMethods._plot_decorator

0 commit comments

Comments
 (0)