forked from IMAP-Science-Operations-Center/imap_processing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
280 lines (242 loc) · 10.6 KB
/
Copy pathutils.py
File metadata and controls
280 lines (242 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
"""Various utility functions to support creation of CDF files."""
from __future__ import annotations
import datetime
import logging
import re
import warnings
from pathlib import Path
import imap_data_access
import numpy as np
import pandas as pd
import xarray as xr
from cdflib.logging import logger as cdflib_logger
from cdflib.xarray import cdf_to_xarray, xarray_to_cdf
from cdflib.xarray.cdf_to_xarray import ISTP_TO_XARRAY_ATTRS
from imap_data_access.file_validation import Version
import imap_processing
from imap_processing._version import __version__, __version_tuple__ # noqa: F401
from imap_processing.spice.time import TTJ2000_EPOCH
logger = logging.getLogger(__name__)
def _cdf_compatible_dataset(dataset: xr.Dataset) -> xr.Dataset:
"""Return a shallow copy whose extension arrays are NumPy-backed.
``cdflib`` expects array-valued variables to be backed by NumPy arrays. In
particular, it cannot serialize the string extension arrays that pandas 3
uses by default. Converting at the CDF boundary keeps the in-memory dataset
unchanged and also supports explicitly created extension arrays on pandas 2.
Parameters
----------
dataset : xarray.Dataset
Dataset to prepare for serialization by ``cdflib``.
Returns
-------
xarray.Dataset
Shallow copy with extension-array variables converted to NumPy arrays.
"""
converted = dataset.copy(deep=False)
for name, variable in dataset.variables.items():
if not isinstance(variable.data, pd.api.extensions.ExtensionArray):
continue
numpy_variable = xr.Variable(
variable.dims,
variable.data.to_numpy(copy=True),
attrs=variable.attrs,
)
numpy_variable.encoding = variable.encoding.copy()
if name in dataset.coords:
converted = converted.assign_coords({name: numpy_variable})
else:
converted[name] = numpy_variable
return converted
def load_cdf(
file_path: Path | str, remove_xarray_attrs: bool = True, **kwargs: dict
) -> xr.Dataset:
"""
Load the contents of a CDF file into an ``xarray`` dataset.
Parameters
----------
file_path : pathlib.Path or ImapFilePath or str
The path to the CDF file or ImapFilePath object.
remove_xarray_attrs : bool
Whether to remove the xarray attributes that get injected by the
cdf_to_xarray function from the output xarray.Dataset. Default is True.
**kwargs : dict, optional
Keyword arguments for ``cdf_to_xarray``.
Returns
-------
dataset : xarray.Dataset
The ``xarray`` dataset for the CDF file.
"""
if isinstance(file_path, imap_data_access.ImapFilePath):
file_path = file_path.construct_path()
# By default, do not convert epoch to datetime64. This ensures that the
# round-trip of writing and then loading a cdf keeps the dataset the same.
if "to_datetime" not in kwargs:
kwargs["to_datetime"] = False # type: ignore
# By default, load fillvalues as nan
if "fillval_to_nan" not in kwargs:
kwargs["fillval_to_nan"] = True # type: ignore
dataset = cdf_to_xarray(file_path, **kwargs)
# cdf_to_xarray converts single-value attributes to lists
# convert these back to single values where applicable
for attribute in dataset.attrs:
value = dataset.attrs[attribute]
if isinstance(value, list) and len(value) == 1:
dataset.attrs[attribute] = value[0]
# Remove attributes specific to xarray plotting from vars and coords
# TODO: This can be removed if/when feature is added to cdf_to_xarray to
# make adding these attributes optional
if remove_xarray_attrs:
for key in dataset.variables.keys():
for xarray_key in ISTP_TO_XARRAY_ATTRS.values():
dataset[key].attrs.pop(xarray_key, None)
return dataset
def write_cdf(
dataset: xr.Dataset,
**extra_cdf_kwargs: dict,
) -> Path:
"""
Write the contents of "data" to a CDF file using cdflib.xarray_to_cdf.
This function determines the file name to use from the global attributes,
fills in the final attributes, and converts the whole dataset to a CDF.
The date in the file name is determined by the time of the first epoch in the
xarray Dataset. The first 3 file name fields (mission, instrument, level) are
determined by the "Logical_source" attribute. The version is determined from
"Data_version".
The start_date and repointing attributes in the dataset are used to override the
computed values.
If these are not included, start_date is generated from the first epoch in the
dataset and repointing is not included if the attribute is not present or None.
Parameters
----------
dataset : xarray.Dataset
The dataset object to convert to a CDF.
**extra_cdf_kwargs : dict
Additional keyword arguments to pass to the ``xarray_to_cdf`` function.
Returns
-------
file_path : pathlib.Path
Path to the file created.
"""
# Create the filename from the global attributes
# Logical_source looks like "imap_swe_l2_counts-1min"
instrument, data_level, descriptor = dataset.attrs["Logical_source"].split("_")[1:]
# Convert J2000 epoch referenced data to datetime64
# TODO: This implementation of epoch to time string results in an error of
# 5 seconds due to 5 leap-second occurrences since the J2000 epoch.
# TODO: Create a ttj2000_to_datetime function to handle this conversion
start_date = dataset.attrs.get("Start_date", None)
if start_date is None:
# If no start time is included, then use the first epoch in the dataset
dt64 = TTJ2000_EPOCH + dataset["epoch"].values[0].astype("timedelta64[ns]")
start_date = np.datetime_as_string(dt64, unit="D").replace("-", "")
version = dataset.attrs.get("Data_version", None)
if version is None:
warnings.warn(
"No Data_version attribute found in dataset. Using default 001.0001",
stacklevel=2,
)
version = "001.0001"
dataset.attrs["Data_version"] = version
# Data_version may be stored without the leading 'v'; add it before validating.
version_string = version if str(version).startswith("v") else f"v{version}"
try:
version_obj = Version.from_version(version_string)
except ValueError as e:
raise ValueError(
f"The Data_version attribute {version} is not a valid version string. "
f"Please use the format matching the pattern "
f"'{Version.science_version_pattern}' instead."
) from e
repointing = dataset.attrs.get("Repointing", None)
repointing_int = int(repointing[-5:]) if repointing else None
science_file = imap_data_access.ScienceFilePath.generate_from_inputs(
instrument=instrument,
data_level=data_level,
descriptor=descriptor,
start_time=start_date,
major_version=version_obj.major,
minor_version=version_obj.minor,
repointing=repointing_int,
)
file_path = Path(science_file.construct_path())
if not file_path.parent.exists():
logger.info(
"The directory does not exist, creating directory %s", file_path.parent
)
file_path.parent.mkdir(parents=True)
# Insert the final attribute:
# The Logical_file_id is always the name of the file without the extension
dataset.attrs["Logical_file_id"] = file_path.stem
# Add the processing version to the dataset attributes
dataset.attrs["ground_software_version"] = imap_processing._version.__version__
dataset.attrs["Generation_date"] = datetime.datetime.now(
datetime.timezone.utc
).strftime("%Y%m%d")
dataset.attrs["Generated_by"] = "IMAP Science Data Center"
# Convert the xarray object to a CDF
if "l1" in data_level:
if "terminate_on_warning" not in extra_cdf_kwargs:
extra_cdf_kwargs["terminate_on_warning"] = False # type: ignore
else:
if "terminate_on_warning" not in extra_cdf_kwargs:
extra_cdf_kwargs["terminate_on_warning"] = True # type: ignore
if "istp" not in extra_cdf_kwargs:
extra_cdf_kwargs["istp"] = True # type: ignore
if "compression" not in extra_cdf_kwargs:
extra_cdf_kwargs["compression"] = 6 # type: ignore
prev_cdflib_level = cdflib_logger.level
try:
if not extra_cdf_kwargs.get("istp", False):
# Suppress cdflib logging messages for data levels that don't need
# strict ISTP compliance
logger.info("Disabling cdflib ISTP logging for level 1 data products")
cdflib_logger.setLevel(logging.ERROR)
xarray_to_cdf(
_cdf_compatible_dataset(dataset),
str(file_path),
**extra_cdf_kwargs,
)
finally:
# Set back to the previous logging level
cdflib_logger.setLevel(prev_cdflib_level)
return file_path
def parse_filename_like(filename_like: str) -> re.Match:
"""
Parse a filename like string.
This function is based off of the more strict regex parsing of IMAP science
product filenames found in the `imap_data_access` package `ScienceFilePath`
class. This function implements a more relaxed regex that can be used on
`Logical_source` or `Logical_file_id` found in the CDF file. The required
components in the input string are `mission`, `instrument`, `data_level`,
and `descriptor`.
Parameters
----------
filename_like : str
A filename like string. This includes `Logical_source` or `Logical_file_id`
strings.
Returns
-------
match : re.Match
A dictionary like re.Match object resulting from parsing the input string.
Raises
------
ValueError if the regex fails to match the input string.
"""
regex_str = (
r"^(?P<mission>imap)_" # Required mission
r"(?P<instrument>[^_]+)_" # Required instrument
r"(?P<data_level>[^_]+)_" # Required data level
r"((?P<sensor>\d{2}sensor)?-)?" # Optional sensor number
r"(?P<descriptor>[^_]+)" # Required descriptor
r"(_(?P<start_date>\d{8}))?" # Optional start date
r"(-repoint(?P<repointing>\d{5}))?" # Optional repointing field
rf"(?:_(?P<version>{Version.version_regex()}))?" # Optional version
r"(?:\.(?P<extension>cdf|pkts))?$" # Optional extension
)
match = re.match(regex_str, filename_like)
if match is None:
raise ValueError(
"Filename like string did not contain required fields"
"including mission, instrument, data_level, and descriptor."
)
return match