Skip to content

Commit f9ca033

Browse files
committed
Add Convention.get_depth_coordinate_for_data_array()
Partial fix for #138
1 parent c301cb1 commit f9ca033

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

src/emsarray/conventions/_base.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,57 @@ def get_all_depth_names(self) -> list[Hashable]:
478478
"""
479479
return [c.name for c in self.depth_coordinates]
480480

481+
def get_depth_coordinate_for_data_array(
482+
self,
483+
data_array: DataArrayOrName,
484+
) -> xarray.DataArray:
485+
"""
486+
Find the depth coordinate for a particular data array.
487+
Some conventions will contain multiple depth coordinates,
488+
meaning that a default :attr:`depth_coordinate` value can be misleading.
489+
490+
Parameters
491+
----------
492+
data_array : xarray.DataArray or Hashable
493+
A data array or the name of a data array in the dataset.
494+
495+
Returns
496+
-------
497+
xarray.DataArray
498+
The depth coordinate variable for the data array.
499+
500+
Raises
501+
------
502+
NoSuchCoordinateError
503+
If data array does not have an associated depth coordinate
504+
ValueError
505+
If multiple depth coordinates matched the data array.
506+
507+
See also
508+
--------
509+
:attr:`depth_coordinate`
510+
The default or main depth coordinate for this dataset,
511+
but not necessarily the correct depth coordinate for all variables.
512+
:attr:`depth_coordinates`
513+
All the depth coordinates in this dataset.
514+
"""
515+
data_array = utils.name_to_data_array(self.dataset, data_array)
516+
name = repr(data_array.name) if data_array.name is not None else 'data array'
517+
518+
candidates = [
519+
coordinate
520+
for coordinate in self.depth_coordinates
521+
if coordinate.dims[0] in data_array.dims
522+
]
523+
if len(candidates) == 0:
524+
raise NoSuchCoordinateError(f"No depth coordinate found for {name}")
525+
if len(candidates) > 1:
526+
raise ValueError(
527+
f"Multiple possible depth coordinates found for {name}: "
528+
", ".join(repr(c.name) for c in candidates)
529+
)
530+
return candidates[0]
531+
481532
@abc.abstractmethod
482533
def ravel_index(self, index: Index) -> int:
483534
"""Convert a convention native index to a linear index.

src/emsarray/transect.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,8 @@ def plot(
5757
Passed to :meth:`Transect.plot_on_figure()`.
5858
"""
5959
figure = pyplot.figure(layout="constrained", figsize=figsize)
60-
transect = Transect(dataset, line)
60+
depth_coordinate = dataset.ems.get_depth_coordinate_for_data_array(data_array)
61+
transect = Transect(dataset, line, depth=depth_coordinate)
6162
transect.plot_on_figure(figure, data_array, **kwargs)
6263
pyplot.show()
6364
return figure

0 commit comments

Comments
 (0)