|
| 1 | +import pandas as pd |
| 2 | +import xarray as xr |
| 3 | +from xarray.core.indexes import Index, PandasIndex |
| 4 | +from xarray.core.indexing import merge_sel_results |
| 5 | + |
| 6 | + |
| 7 | +def alias(dataset: xr.Dataset, old_name: str, new_name: str) -> PandasIndex: |
| 8 | + """Alias a dimension coordinate to a coordinate with a different name.""" |
| 9 | + try: |
| 10 | + size = dataset.sizes[old_name] |
| 11 | + except KeyError: |
| 12 | + try: |
| 13 | + size = dataset.dims[old_name] |
| 14 | + except KeyError: |
| 15 | + size = dataset.attrs[old_name] |
| 16 | + return PandasIndex(pd.RangeIndex(size, name=new_name), dim=old_name) |
| 17 | + |
| 18 | + |
| 19 | +class GridIndex(Index): |
| 20 | + def __init__(self, indices): |
| 21 | + self._indices = indices |
| 22 | + |
| 23 | + @classmethod |
| 24 | + def from_variables(cls, variables): |
| 25 | + return { |
| 26 | + k: PandasIndex.from_variables({k: v}) for k, v in variables.items() |
| 27 | + } |
| 28 | + |
| 29 | + def create_variables(self, variables=None): |
| 30 | + idx_vars = {} |
| 31 | + for index in self._indices.values(): |
| 32 | + idx_vars.update(index.create_variables(variables)) |
| 33 | + return idx_vars |
| 34 | + |
| 35 | + def sel(self, labels): |
| 36 | + results = [] |
| 37 | + for k, index in self._indices.items(): |
| 38 | + if k in labels: |
| 39 | + results.append(index.sel({k: labels[k]})) |
| 40 | + return merge_sel_results(results) |
| 41 | + |
| 42 | + |
| 43 | +def grid_index(dataset: xr.Dataset) -> GridIndex: |
| 44 | + return GridIndex( |
| 45 | + { |
| 46 | + # k collides with npf.k so use "lay" |
| 47 | + "lay": alias(dataset, "nlay", "lay"), |
| 48 | + "col": alias(dataset, "ncol", "col"), |
| 49 | + "row": alias(dataset, "nrow", "row"), |
| 50 | + } |
| 51 | + ) |
0 commit comments