55
66
77def alias (dataset : xr .Dataset , old_name : str , new_name : str ) -> PandasIndex :
8- """Alias a dimension coordinate to a coordinate with a different name."""
8+ """
9+ Alias a dimension coordinate to a coordinate with a different name.
10+ Suggested by Benoit Bovy https://github.com/pydata/xarray/pull/10076#issuecomment-2809041994.
11+ """
912 try :
1013 size = dataset .sizes [old_name ]
1114 except KeyError :
12- try :
13- size = dataset .dims [old_name ]
14- except KeyError :
15- size = dataset .attrs [old_name ]
15+ size = dataset .attrs [old_name ]
1616 return PandasIndex (pd .RangeIndex (size , name = new_name ), dim = old_name )
1717
1818
19- class GridIndex (Index ):
19+ class MetaIndex (Index ):
20+ """
21+ Combine multiple indexes into a single index.
22+ Adapted from https://docs.xarray.dev/en/stable/internals/how-to-create-custom-index.html#meta-indexes.
23+ """
24+
2025 def __init__ (self , indices ):
2126 self ._indices = indices
2227
@@ -39,13 +44,29 @@ def sel(self, labels):
3944 results .append (index .sel ({k : labels [k ]}))
4045 return merge_sel_results (results )
4146
47+ def to_pandas_index (self ) -> pd .Index :
48+ # from https://github.com/corteva/rioxarray/pull/846/files#diff-917105823f61e63ef4afde8bed408a6c249e375690e56bc800406676f02551d8R418
49+ if len (self ._indices ) == 1 :
50+ index = next (iter (self ._indices .values ()))
51+ if isinstance (index , PandasIndex ):
52+ return index .to_pandas_index ()
53+
54+ raise ValueError ("Cannot convert MetaIndex to pandas.Index" )
55+
4256
43- def grid_index (dataset : xr .Dataset ) -> GridIndex :
44- return GridIndex (
57+ def grid_index (dataset : xr .Dataset ) -> MetaIndex :
58+ return MetaIndex (
4559 {
46- # k collides with npf.k so use "lay"
60+ # TODO add 'per' (stress period)
4761 "lay" : alias (dataset , "nlay" , "lay" ),
4862 "col" : alias (dataset , "ncol" , "col" ),
4963 "row" : alias (dataset , "nrow" , "row" ),
64+ # "node": alias(dataset, "nnodes", "node"),
65+ # TODO: adding node breaks the other three.
66+ # and just having node by itself works. why?
5067 }
5168 )
69+
70+
71+ def time_index (dataset : xr .Dataset ) -> PandasIndex :
72+ return alias (dataset , "nper" , "per" )
0 commit comments