Skip to content

Commit abd7b6c

Browse files
authored
Include metadata variables for (arrays of) structures in to_xarray (#112)
1 parent 062c2ca commit abd7b6c

6 files changed

Lines changed: 175 additions & 85 deletions

File tree

‎docs/source/netcdf.rst‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,3 +183,39 @@ specific paths inside the IDS. The latter variant can also be combined with
183183
# profiles_1d.grid.rho_tor
184184
# profiles_1d.grid.rho_tor_norm
185185
# profiles_1d.grid.psi
186+
187+
188+
Store Xarray Datasets in IMAS-compatible netCDF file
189+
''''''''''''''''''''''''''''''''''''''''''''''''''''
190+
191+
.. versionadded:: 2.3.0 :py:meth:`~imas.util.to_xarray` now includes the required
192+
metadata to load the IDS from a netCDF file.
193+
194+
The following snippet shows how to store an IMAS Xarray dataset in an IMAS-compatible
195+
netCDF file. The group name in the netCDF file must correspond to ``<IDS
196+
Name>/<occurrence>`` (``core_profiles/0`` in the snippet).
197+
198+
.. code-block:: python
199+
:caption: Store IMAS Xarray dataset in an IMAS-compatible netCDF file
200+
201+
import imas.training
202+
import netCDF4
203+
204+
with imas.training.get_training_db_entry() as training_entry:
205+
core_profiles = training_entry.get("core_profiles")
206+
xrds = imas.util.to_xarray(core_profiles)
207+
208+
# Store the xarray dataset in an IMAS-compatible netCDF dataset
209+
filename = "data.nc"
210+
xrds.to_netcdf(
211+
filename,
212+
group="core_profiles/0", # Update to the correct IDS name and occurrence
213+
# auto_complex=True, # Uncomment if the dataset contains complex data
214+
)
215+
# Set global DD version metadata
216+
with netCDF4.Dataset(filename, "a") as ds:
217+
ds.data_dictionary_version = imas.util.get_data_dictionary_version(ids)
218+
219+
# Test that we can get the IDS from the netCDF file
220+
with imas.DBEntry(filename, "r") as entry:
221+
ids2 = entry.get("core_profiles")

‎imas/_to_xarray.py‎

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from imas.ids_data_type import IDSDataType
99

1010
fillvals = {
11-
IDSDataType.INT: -(2**31) + 1,
11+
IDSDataType.INT: numpy.int32(-(2**31) + 1),
1212
IDSDataType.STR: "",
1313
IDSDataType.FLT: numpy.nan,
1414
IDSDataType.CPX: numpy.nan * (1 + 1j),
@@ -50,21 +50,28 @@ def to_xarray(ids: IDSToplevel, *paths: str) -> xarray.Dataset:
5050
var_name = path.replace("/", ".")
5151
metadata = ids.metadata[path]
5252
if metadata.data_type in (IDSDataType.STRUCTURE, IDSDataType.STRUCT_ARRAY):
53-
continue # We don't store these in xarray
54-
55-
dimensions = tensorizer.ncmeta.get_dimensions(path, tensorizer.homogeneous_time)
56-
data = tensorizer.tensorize(path, fillvals[metadata.data_type])
57-
58-
attrs = dict(documentation=metadata.documentation)
59-
if metadata.units:
60-
attrs["units"] = metadata.units
61-
coordinates = tensorizer.filter_coordinates(path)
62-
if coordinates:
63-
coordinate_names.update(coordinates.split(" "))
64-
attrs["coordinates"] = coordinates
53+
# Metadata variables for (arrays of) structures
54+
if paths and path not in paths:
55+
continue
56+
dimensions = ()
57+
data = b""
58+
else:
59+
dimensions = tensorizer.get_dimensions(path)
60+
data = tensorizer.tensorize(path, fillvals[metadata.data_type])
6561

62+
attrs = tensorizer.get_attributes(path, fillvals)
63+
if "coordinates" in attrs:
64+
coordinate_names.update(attrs["coordinates"].split(" "))
6665
data_vars[var_name] = (dimensions, data, attrs)
6766

67+
# :shape array for sparse data
68+
if path in tensorizer.shapes and metadata.ndim:
69+
shape_name = f"{var_name}:shape"
70+
dimensions = tensorizer.get_shape_dimensions(path)
71+
data = tensorizer.shapes[path]
72+
attrs = tensorizer.get_shape_attributes(var_name)
73+
data_vars[shape_name] = (dimensions, data, attrs)
74+
6875
# Remove coordinates from data_vars and put in coordinates mapping:
6976
coordinates = {}
7077
for coordinate_name in coordinate_names:

‎imas/backends/netcdf/ids2nc.py‎

Lines changed: 12 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@ def create_dimensions(self) -> None:
4747

4848
def create_variables(self) -> None:
4949
"""Create netCDF variables."""
50-
get_dimensions = self.ncmeta.get_dimensions
5150
for path in self.filled_data:
5251
metadata = self.ids.metadata[path]
5352
var_name = path.replace("/", ".")
@@ -75,54 +74,21 @@ def create_variables(self) -> None:
7574
if dtype is not dtypes[IDSDataType.CPX]: # Set fillvalue
7675
kwargs.update(fill_value=default_fillvals[metadata.data_type])
7776
# Create variable
78-
dimensions = get_dimensions(path, self.homogeneous_time)
77+
dimensions = self.get_dimensions(path)
7978
var = self.group.createVariable(var_name, dtype, dimensions, **kwargs)
8079

8180
# Fill metadata attributes
82-
var.documentation = metadata.documentation
83-
if metadata.units:
84-
var.units = metadata.units
85-
86-
ancillary_variables = " ".join(
87-
error_var
88-
for error_var in [f"{var_name}_error_upper", f"{var_name}_error_lower"]
89-
if error_var in self.filled_variables
90-
)
91-
if ancillary_variables:
92-
var.ancillary_variables = ancillary_variables
93-
94-
if metadata.data_type is not IDSDataType.STRUCT_ARRAY:
95-
coordinates = self.filter_coordinates(path)
96-
if coordinates:
97-
var.coordinates = coordinates
98-
99-
# Sparsity and :shape array
100-
if path in self.shapes:
101-
if not metadata.ndim:
102-
# Doesn't need a :shape array:
103-
var.sparse = "Sparse data, missing data is filled with _FillValue"
104-
var.sparse += f" ({default_fillvals[metadata.data_type]})"
105-
106-
else:
107-
shape_name = f"{var_name}:shape"
108-
var.sparse = f"Sparse data, data shapes are stored in {shape_name}"
109-
110-
# Create variable to store data shape
111-
dimensions = get_dimensions(
112-
self.ncmeta.aos.get(path), self.homogeneous_time
113-
) + (f"{metadata.ndim}D",)
114-
shape_var = self.group.createVariable(
115-
shape_name,
116-
SHAPE_DTYPE,
117-
dimensions,
118-
)
119-
doc_indices = ",".join(chr(ord("i") + i) for i in range(3))
120-
shape_var.documentation = (
121-
f"Shape information for {var_name}.\n"
122-
f"{shape_name}[{doc_indices},:] describes the shape of filled "
123-
f"data of {var_name}[{doc_indices},...]. Data outside this "
124-
"shape is unset (i.e. filled with _Fillvalue)."
125-
)
81+
var.setncatts(self.get_attributes(path, default_fillvals))
82+
83+
# :shape array for sparse data
84+
if path in self.shapes and metadata.ndim:
85+
shape_name = f"{var_name}:shape"
86+
# Create variable to store data shape
87+
dimensions = self.get_shape_dimensions(path)
88+
shape_var = self.group.createVariable(
89+
shape_name, SHAPE_DTYPE, dimensions
90+
)
91+
shape_var.setncatts(self.get_shape_attributes(var_name))
12692

12793
def store_data(self) -> None:
12894
"""Store data in the netCDF variables"""

‎imas/backends/netcdf/ids_tensorizer.py‎

Lines changed: 69 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"""Tensorization logic to convert IDSs to netCDF files and/or xarray Datasets."""
44

55
from collections import deque
6-
from typing import List
6+
from typing import List, Tuple, Dict
77

88
import 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

‎imas/backends/netcdf/nc2ids.py‎

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import logging
22
import os
3-
from typing import Optional
3+
from typing import Optional, Tuple
44

55
import netCDF4
66
import numpy as np
@@ -80,6 +80,14 @@ def __init__(
8080
)
8181
self.homogeneous_time = var[()] == IDS_TIME_MODE_HOMOGENEOUS
8282

83+
def get_dimensions(self, path: str) -> Tuple[str, ...]:
84+
"""Get the dimensions for a netCDF variable.
85+
86+
Args:
87+
path: Data Dictionary path to the variable, e.g. ``ids_properties/comment``.
88+
"""
89+
return self.ncmeta.get_dimensions(path, self.homogeneous_time)
90+
8391
def run(self, lazy: bool) -> None:
8492
"""Load the data from the netCDF group into the IDS."""
8593
self.variables.sort()
@@ -130,9 +138,7 @@ def run(self, lazy: bool) -> None:
130138

131139
else:
132140
# FIXME: extract dimension name from nc file?
133-
dim = self.ncmeta.get_dimensions(
134-
metadata.path_string, self.homogeneous_time
135-
)[-1]
141+
dim = self.get_dimensions(metadata.path_string)[-1]
136142
size = self.group.dimensions[dim].size
137143
for _, node in indexed_tree_iter(self.ids, target_metadata):
138144
node.resize(size)
@@ -235,9 +241,7 @@ def _validate_variable(self, var: netCDF4.Variable, metadata: IDSMetadata) -> No
235241
raise variable_error(var, "data type", var.dtype, expected_dtype)
236242

237243
# Dimensions
238-
expected_dims = self.ncmeta.get_dimensions(
239-
metadata.path_string, self.homogeneous_time
240-
)
244+
expected_dims = self.get_dimensions(metadata.path_string)
241245
if var.dimensions != expected_dims:
242246
raise variable_error(var, "dimensions", var.dimensions, expected_dims)
243247

@@ -298,9 +302,7 @@ def _validate_sparsity(
298302
return # Sparsity is stored with _Fillvalue, nothing to validate
299303

300304
# Dimensions
301-
aos_dimensions = self.ncmeta.get_dimensions(
302-
self.ncmeta.aos.get(metadata.path_string), self.homogeneous_time
303-
)
305+
aos_dimensions = self.get_dimensions(self.ncmeta.aos.get(metadata.path_string))
304306
shape_dimensions = shape_var.dimensions
305307
if (
306308
len(shape_dimensions) != len(aos_dimensions) + 1
@@ -331,7 +333,6 @@ def get_child(self, child):
331333
332334
Args:
333335
child: The child IDS node which should be lazy loaded.
334-
335336
"""
336337
metadata = child.metadata
337338
path = metadata.path_string
@@ -347,9 +348,7 @@ def get_child(self, child):
347348
size = nc2ids.group[var.name + ":shape"][self.index][0]
348349
else:
349350
# FIXME: extract dimension name from nc file?
350-
dim = nc2ids.ncmeta.get_dimensions(
351-
metadata.path_string, nc2ids.homogeneous_time
352-
)[-1]
351+
dim = nc2ids.get_dimensions(metadata.path_string)[-1]
353352
size = nc2ids.group.dimensions[dim].size
354353

355354
child._set_lazy_context(LazyArrayStructContext(nc2ids, self.index, size))

0 commit comments

Comments
 (0)