Skip to content

Commit 7b4d837

Browse files
authored
Merge pull request Unidata#1503 from loaff123/fix/numeric-attribute-byte-order
Fix non-native byte order when writing numeric attributes
2 parents f609107 + 1bb285c commit 7b4d837

3 files changed

Lines changed: 123 additions & 5 deletions

File tree

‎Changelog‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
version 1.7.4.1 (tag v1.7.4.1rel)
22
=================================
3+
* Convert non-native-endian numeric attributes to native byte order before writing (issue #1502).
34
* Fix command-line usage error exit codes and --help handling, honour nc4tonc3 --chunk,
45
and fix ncinfo group dimension selection (issue #1500).
56
* Change default encoding for stringtochar/chartostring functions from 'utf-8' to 'utf-8'/'ascii' for dtype.kind='U'/'S'

‎src/netCDF4/_netCDF4.pyx‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1889,6 +1889,9 @@ be raised in the next release."""
18891889
raise TypeError, 'illegal data type for attribute %r, must be one of %s, got %s' % (attname, _supportedtypes, value_arr.dtype.str[1:])
18901890
elif xtype == -99: # if xtype is not passed in as kwarg.
18911891
xtype = _nptonctype[value_arr.dtype.str[1:]]
1892+
# netcdf-c expects native-endian buffers for primitive numeric types.
1893+
if value_arr.dtype.kind in 'iuf' and not value_arr.dtype.isnative:
1894+
value_arr = value_arr.astype(value_arr.dtype.newbyteorder('='))
18921895
lenarr = PyArray_SIZE(value_arr)
18931896
with nogil:
18941897
ierr = nc_put_att(grpid, varid, attname, xtype, lenarr,
@@ -4440,7 +4443,6 @@ behavior is similar to Fortran or Matlab, but different than numpy.
44404443
elif fill_value == 'default':
44414444
if self._isprimitive:
44424445
fillval = numpy.array(default_fillvals[self.dtype.str[1:]])
4443-
if not fillval.dtype.isnative: fillval.byteswap(True)
44444446
_set_att(self._grp, self._varid, '_FillValue',\
44454447
fillval, xtype=xtype)
44464448
else:
@@ -4456,7 +4458,6 @@ does not do anything."""
44564458
_tostr(fill_value), xtype=xtype, force_ncstring=True)
44574459
else:
44584460
fillval = numpy.array(fill_value, self.dtype)
4459-
if not fillval.dtype.isnative: fillval.byteswap(True)
44604461
_set_att(self._grp, self._varid, '_FillValue',\
44614462
fillval, xtype=xtype)
44624463
else:
@@ -5020,13 +5021,10 @@ details."""
50205021
# raise AttributeError(msg)
50215022
elif name in ['valid_min','valid_max','valid_range','missing_value'] and self._isprimitive:
50225023
# make sure these attributes written in same data type as variable.
5023-
# also make sure it is written in native byte order
5024-
# (the same as the data)
50255024
valuea = numpy.array(value, self.dtype)
50265025
# check to see if array cast is safe
50275026
if _safecast(numpy.array(value),valuea):
50285027
value = valuea
5029-
if not value.dtype.isnative: value.byteswap(True)
50305028
else: # otherwise don't do it, but issue a warning
50315029
msg="WARNING: %s cannot be safely cast to variable dtype" \
50325030
% name

‎test/test_atts.py‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import tempfile
77
import warnings
88
import pathlib
9+
import struct
10+
from typing import Literal
911

1012
import numpy as np
1113
from collections import OrderedDict
@@ -223,5 +225,122 @@ def runTest(self):
223225
with netCDF4.Dataset(pathlib.Path(__file__).parent / "test_gold.nc") as f:
224226
assert f['RADIANCE'].VAR_NOTES == ""
225227

228+
class NumericEndianTestCase(unittest.TestCase):
229+
230+
formats: 'tuple[netCDF4.Format, ...]' = (
231+
'NETCDF4', 'NETCDF4_CLASSIC', 'NETCDF3_CLASSIC', 'NETCDF3_64BIT_OFFSET')
232+
if netCDF4.__has_cdf5_format__ and struct.calcsize('P') >= 8:
233+
formats += ('NETCDF3_64BIT_DATA',)
234+
235+
def setUp(self):
236+
directory = tempfile.TemporaryDirectory()
237+
self.addCleanup(directory.cleanup)
238+
self.path = os.path.join(directory.name, 'attributes.nc')
239+
240+
def test_numeric_attribute_byte_order(self):
241+
# Issue #1502: nc_put_att expects native-endian numeric buffers.
242+
for format in self.formats:
243+
extended = format in ('NETCDF4', 'NETCDF3_64BIT_DATA')
244+
dtypes = ['i1', 'i2', 'i4', 'i8', 'f4', 'f8']
245+
if extended:
246+
dtypes += ['u1', 'u2', 'u4', 'u8']
247+
expected = {}
248+
with netCDF4.Dataset(self.path, 'w', format=format) as f:
249+
targets: dict[str, netCDF4.Dataset | netCDF4.Group | netCDF4.Variable] = {
250+
'/': f, '/v': f.createVariable('v', 'f8')}
251+
if format == 'NETCDF4':
252+
group = f.createGroup('g')
253+
targets['/g'] = group
254+
targets['/g/v'] = group.createVariable('v', 'f8')
255+
for dtype in dtypes:
256+
values = [1, 2, 17] if dtype[0] == 'u' else [1, -2, 17]
257+
if dtype[0] == 'f':
258+
values = [1.25, -2.5, 17.75]
259+
for order in ('=', '<', '>'):
260+
array = np.array(values, dtype=np.dtype(dtype).newbyteorder(order))
261+
readonly = array.copy()
262+
readonly.flags.writeable = False
263+
inputs = (array, np.array(values[0], dtype=array.dtype),
264+
np.repeat(array, 2)[::2], array[::-1],
265+
readonly, array[:0])
266+
for layout, value in enumerate(inputs):
267+
original = value.tobytes()
268+
for target_name, target in targets.items():
269+
for setter in ('single', 'bulk', 'syntax'):
270+
name = '%s_%s_%s_%s' % (dtype, order, layout, setter)
271+
with self.subTest(format=format, target=target_name,
272+
attribute=name):
273+
if setter == 'single':
274+
target.setncattr(name, value)
275+
elif setter == 'bulk':
276+
target.setncatts({name: value})
277+
else:
278+
setattr(target, name, value)
279+
self.assertEqual(value.tobytes(), original)
280+
self.assertEqual(value.dtype, array.dtype)
281+
self.assertEqual(value.flags.writeable,
282+
layout != 4)
283+
stored_dtype = 'i4' if dtype == 'i8' and not extended else dtype
284+
expected[target_name, name] = value.astype(stored_dtype)
285+
with netCDF4.Dataset(self.path) as f:
286+
for (target_name, name), value in expected.items():
287+
target = f if target_name == '/' else f[target_name]
288+
with self.subTest(format=format, target=target_name, attribute=name):
289+
actual = np.asarray(target.getncattr(name))
290+
np.testing.assert_array_equal(actual, value)
291+
self.assertEqual(actual.dtype, value.dtype)
292+
293+
def test_valid_range_byte_order(self):
294+
for format in self.formats:
295+
with self.subTest(format=format):
296+
value = np.array([1., 2.], dtype=np.dtype('f8').newbyteorder('S'))
297+
with netCDF4.Dataset(self.path, 'w', format=format) as f:
298+
f.createDimension('x', 4)
299+
v = f.createVariable('v', 'f8', ('x',))
300+
v[:] = [0., 1., 2., 3.]
301+
v.setncattr('valid_range', value)
302+
f.setncattr('levels', value)
303+
with netCDF4.Dataset(self.path) as f:
304+
v = f['v']
305+
np.testing.assert_array_equal(f.levels, [1., 2.])
306+
np.testing.assert_array_equal(v.valid_range, [1., 2.])
307+
np.testing.assert_array_equal(np.ma.getmaskarray(v[:]),
308+
[True, False, False, True])
309+
np.testing.assert_array_equal(v[:].compressed(), [1., 2.])
310+
311+
def test_variable_metadata_byte_order(self):
312+
# Existing fill-value and special-attribute callers must not swap twice.
313+
endians: tuple[Literal['little', 'big'], ...] = ('little', 'big')
314+
for endian in endians:
315+
with self.subTest(endian=endian):
316+
dtype = np.dtype('f8').newbyteorder(endian)
317+
with netCDF4.Dataset(self.path, 'w') as f:
318+
f.createDimension('x', 3)
319+
v = f.createVariable('v', dtype, ('x',), endian=endian,
320+
fill_value=-999.)
321+
v[:2] = [1., 2.]
322+
v.valid_min = np.array(0., dtype=dtype)
323+
v.valid_max = np.array(3., dtype=dtype)
324+
v.valid_range = np.array([0., 3.], dtype=dtype)
325+
v.missing_value = np.array(-999., dtype=dtype)
326+
with netCDF4.Dataset(self.path) as f:
327+
v = f['v']
328+
self.assertEqual(v._FillValue, -999.)
329+
self.assertEqual(v.missing_value, -999.)
330+
self.assertEqual(v.valid_min, 0.)
331+
self.assertEqual(v.valid_max, 3.)
332+
np.testing.assert_array_equal(v.valid_range, [0., 3.])
333+
np.testing.assert_array_equal(np.ma.getmaskarray(v[:]),
334+
[False, False, True])
335+
np.testing.assert_array_equal(v[:].compressed(), [1., 2.])
336+
337+
def test_unsupported_numeric_attributes(self):
338+
with netCDF4.Dataset(self.path, 'w') as f:
339+
for dtype in ('?', '<f2', '>f2', '<c8', '>c8', '<c16', '>c16'):
340+
with self.subTest(dtype=dtype):
341+
with self.assertRaises(TypeError):
342+
f.setncattr('unsupported', np.array([1, 0], dtype=dtype))
343+
344+
226345
if __name__ == '__main__':
227346
unittest.main()

0 commit comments

Comments
 (0)