33"""Tensorization logic to convert IDSs to netCDF files and/or xarray Datasets."""
44
55from collections import deque
6- from typing import List
6+ from typing import List , Tuple , Dict
77
88import numpy
99
@@ -47,13 +47,26 @@ def __init__(self, ids: IDSToplevel, paths_to_tensorize: List[str]) -> None:
4747 """Map of IDS paths to filled data nodes."""
4848 self .filled_variables = set ()
4949 """Set of filled IDS variables"""
50- self .homogeneous_time = (
50+ self .homogeneous_time = bool (
5151 ids .ids_properties .homogeneous_time == IDS_TIME_MODE_HOMOGENEOUS
5252 )
5353 """True iff the IDS time mode is homogeneous."""
5454 self .shapes = {}
5555 """Map of IDS paths to data shape arrays."""
5656
57+ def get_dimensions (self , path : str ) -> Tuple [str , ...]:
58+ """Get the dimensions for a netCDF variable.
59+
60+ Args:
61+ path: Data Dictionary path to the variable, e.g. ``ids_properties/comment``.
62+ """
63+ return self .ncmeta .get_dimensions (path , self .homogeneous_time )
64+
65+ def get_shape_dimensions (self , path : str ) -> Tuple [str , ...]:
66+ """Get dimensions names for shape array of the tensorized variable"""
67+ ndim = self .ids .metadata [path ].ndim
68+ return self .get_dimensions (self .ncmeta .aos .get (path , "" )) + (f"{ ndim } D" ,)
69+
5770 def include_coordinate_paths (self ) -> None :
5871 """Append all paths that are coordinates of self.paths_to_tensorize"""
5972 # Use a queue so we can also take coordinates of coordinates into account
@@ -62,7 +75,7 @@ def include_coordinate_paths(self) -> None:
6275 for path in self .paths_to_tensorize :
6376 while path :
6477 path , _ , _ = path .rpartition ("/" )
65- if self .ncmeta . get_dimensions (path , self . homogeneous_time ):
78+ if self .get_dimensions (path ):
6679 queue .append (path )
6780
6881 self .paths_to_tensorize = []
@@ -82,7 +95,6 @@ def collect_filled_data(self) -> None:
8295 # Initialize dictionary with all paths that could exist in this IDS
8396 filled_data = {path : {} for path in self .ncmeta .paths }
8497 dimension_size = {}
85- get_dimensions = self .ncmeta .get_dimensions
8698
8799 if self .paths_to_tensorize :
88100 # Restrict tensorization to provided paths
@@ -102,7 +114,7 @@ def collect_filled_data(self) -> None:
102114 ndim = node .metadata .ndim
103115 if not ndim :
104116 continue
105- dimensions = get_dimensions (path , self . homogeneous_time )
117+ dimensions = self . get_dimensions (path )
106118 # We're only interested in the non-tensorized dimensions: [-ndim:]
107119 for dim_name , size in zip (dimensions [- ndim :], node .shape ):
108120 dimension_size [dim_name ] = max (dimension_size .get (dim_name , 0 ), size )
@@ -115,15 +127,13 @@ def collect_filled_data(self) -> None:
115127
116128 def determine_data_shapes (self ) -> None :
117129 """Determine tensorized data shapes and sparsity, save in :attr:`shapes`."""
118- get_dimensions = self .ncmeta .get_dimensions
119-
120130 for path , nodes_dict in self .filled_data .items ():
121131 metadata = self .ids .metadata [path ]
122132 # Structures don't have a size
123133 if metadata .data_type is IDSDataType .STRUCTURE :
124134 continue
125135 ndim = metadata .ndim
126- dimensions = get_dimensions (path , self . homogeneous_time )
136+ dimensions = self . get_dimensions (path )
127137
128138 # node shape if it is completely filled
129139 full_shape = tuple (self .dimension_size [dim ] for dim in dimensions [- ndim :])
@@ -137,7 +147,7 @@ def determine_data_shapes(self) -> None:
137147
138148 else :
139149 # Data is tensorized, determine if it is homogeneously shaped
140- aos_dims = get_dimensions (self .ncmeta .aos [path ], self . homogeneous_time )
150+ aos_dims = self . get_dimensions (self .ncmeta .aos [path ])
141151 shapes_shape = [self .dimension_size [dim ] for dim in aos_dims ]
142152 if ndim :
143153 shapes_shape .append (ndim )
@@ -168,6 +178,55 @@ def filter_coordinates(self, path: str) -> str:
168178 if coordinate in self .filled_variables
169179 )
170180
181+ def get_attributes (self , path : str , fillvals : dict ) -> Dict [str , str ]:
182+ """Get metadata attributes of the tensorized variable"""
183+ metadata = self .ids .metadata [path ]
184+ var_name = path .replace ("/" , "." )
185+
186+ assert metadata .documentation is not None
187+ attrs = {"documentation" : metadata .documentation }
188+ if metadata .units :
189+ attrs ["units" ] = metadata .units
190+
191+ ancillary_variables = " " .join (
192+ error_var
193+ for error_var in [f"{ var_name } _error_upper" , f"{ var_name } _error_lower" ]
194+ if error_var in self .filled_variables
195+ )
196+ if ancillary_variables :
197+ attrs ["ancillary_variables" ] = ancillary_variables
198+
199+ if metadata .data_type is not IDSDataType .STRUCT_ARRAY :
200+ coordinates = self .filter_coordinates (path )
201+ if coordinates :
202+ attrs ["coordinates" ] = coordinates
203+
204+ # Sparsity
205+ if path in self .shapes :
206+ if not metadata .ndim :
207+ # Doesn't need a :shape array
208+ attrs ["sparse" ] = (
209+ "Sparse data, missing data is filled with _FillValue"
210+ f" ({ fillvals [metadata .data_type ]} )"
211+ )
212+ else :
213+ attrs ["sparse" ] = (
214+ f"Sparse data, data shapes are stored in { var_name } :shape"
215+ )
216+
217+ return attrs
218+
219+ def get_shape_attributes (self , var_name : str ) -> Dict [str , str ]:
220+ """Get attributes of the :shape variable corresponding to var_name"""
221+ doc_indices = "," .join (chr (ord ("i" ) + i ) for i in range (3 ))
222+ documentation = (
223+ f"Shape information for { var_name } .\n "
224+ f"{ var_name } :shape[{ doc_indices } ,:] describes the shape of filled "
225+ f"data of { var_name } [{ doc_indices } ,...]. Data outside this "
226+ "shape is unset (i.e. filled with _Fillvalue)."
227+ )
228+ return {"documentation" : documentation }
229+
171230 def tensorize (self , path , fillvalue ):
172231 """
173232 Tensorizes the data at the given path with the specified fill value.
@@ -180,7 +239,7 @@ def tensorize(self, path, fillvalue):
180239 Returns:
181240 A tensor filled with the data from the specified path.
182241 """
183- dimensions = self .ncmeta . get_dimensions (path , self . homogeneous_time )
242+ dimensions = self .get_dimensions (path )
184243 shape = tuple (self .dimension_size [dim ] for dim in dimensions )
185244
186245 # TODO: depending on the data, tmp_var may be HUGE, we may need a more
0 commit comments