Skip to content

Commit d99748d

Browse files
authored
Merge branch 'master' into fix/win-arm64-py310-numpy
2 parents c49876d + 7b4d837 commit d99748d

5 files changed

Lines changed: 230 additions & 30 deletions

File tree

‎Changelog‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
version 1.7.4.1 (tag v1.7.4.1rel)
22
=================================
33
* Keep a numpy pin for Windows ARM64 on Python 3.10 so lockers can resolve that environment (issue #1491).
4+
* Convert non-native-endian numeric attributes to native byte order before writing (issue #1502).
5+
* Fix command-line usage error exit codes and --help handling, honour nc4tonc3 --chunk,
6+
and fix ncinfo group dimension selection (issue #1500).
47
* Change default encoding for stringtochar/chartostring functions from 'utf-8' to 'utf-8'/'ascii' for dtype.kind='U'/'S'
58
(issue #1464).
69
* Fix DeprecationWarning for assigning to numpy.ndarray.shape for numpy >= 2.5.0 (issue #1468).

‎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

‎src/netCDF4/utils.py‎

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -514,14 +514,14 @@ def ncinfo():
514514

515515
try:
516516
opts, pargs = getopt.getopt(sys.argv[1:],'hv:g:d:',
517-
['group=',
517+
['help',
518+
'group=',
518519
'variable=',
519520
'dimension='])
520-
except:
521-
(type, value, traceback) = sys.exc_info()
522-
sys.stdout.write("Error parsing the options. The error was: %s\n" % value)
521+
except getopt.GetoptError as error:
522+
sys.stdout.write("Error parsing the options. The error was: %s\n" % error)
523523
sys.stderr.write(usage)
524-
sys.exit(0)
524+
sys.exit(2)
525525

526526
# Get the options
527527
group = None; var = None; dim=None
@@ -538,15 +538,15 @@ def ncinfo():
538538
else:
539539
sys.stdout.write("%s: Unrecognized option\n" % option[0])
540540
sys.stderr.write(usage)
541-
sys.exit(0)
541+
sys.exit(2)
542542

543543
# filename passed as last argument
544544
try:
545545
filename = pargs[-1]
546546
except IndexError:
547547
sys.stdout.write("You need to pass netcdf filename!\n.")
548548
sys.stderr.write(usage)
549-
sys.exit(0)
549+
sys.exit(2)
550550

551551
f = Dataset(filename)
552552
if group is None:
@@ -565,7 +565,7 @@ def ncinfo():
565565
if var is not None:
566566
print(g.variables[var])
567567
if dim is not None:
568-
print(g.dimensions[var])
568+
print(g.dimensions[dim])
569569
f.close()
570570

571571
def _nc4tonc3(filename4,filename3,clobber=False,nchunk=10,quiet=False,format='NETCDF3_64BIT'):
@@ -653,16 +653,15 @@ def nc4tonc3():
653653

654654
try:
655655
opts, pargs = getopt.getopt(sys.argv[1:], 'ho',
656-
['format=','chunk=','quiet='])
657-
except:
658-
(type, value, traceback) = sys.exc_info()
659-
sys.stdout.write("Error parsing the options. The error was: %s\n" % value)
656+
['help','format=','chunk=','quiet='])
657+
except getopt.GetoptError as error:
658+
sys.stdout.write("Error parsing the options. The error was: %s\n" % error)
660659
sys.stderr.write(usage)
661-
sys.exit(0)
660+
sys.exit(2)
662661

663662
# default options
664663
quiet = 0
665-
chunk = 1000
664+
chunk = 10
666665
format = 'NETCDF3_64BIT'
667666
overwritefile = 0
668667

@@ -680,22 +679,22 @@ def nc4tonc3():
680679
elif option[0] == '--chunk':
681680
chunk = int(option[1])
682681
else:
683-
sys.stdout.write("%s : Unrecognized option\n" % options[0])
682+
sys.stdout.write("%s : Unrecognized option\n" % option[0])
684683
sys.stderr.write(usage)
685-
sys.exit(0)
684+
sys.exit(2)
686685

687686
# if we pass a number of files different from 2, abort
688687
if len(pargs) < 2 or len(pargs) > 2:
689688
sys.stdout.write("You need to pass both source and destination!\n.")
690689
sys.stderr.write(usage)
691-
sys.exit(0)
690+
sys.exit(2)
692691

693692
# Catch the files passed as the last arguments
694693
filename4 = pargs[0]
695694
filename3 = pargs[1]
696695

697696
# copy the data from filename4 to filename3.
698-
_nc4tonc3(filename4,filename3,clobber=overwritefile,quiet=quiet,format=format)
697+
_nc4tonc3(filename4,filename3,clobber=overwritefile,nchunk=chunk,quiet=quiet,format=format)
699698

700699

701700
def _nc3tonc4(filename3,filename4,unpackshort=True,
@@ -856,7 +855,8 @@ def nc3tonc4():
856855

857856
try:
858857
opts, pargs = getopt.getopt(sys.argv[1:], 'ho',
859-
['classic=',
858+
['help',
859+
'classic=',
860860
'vars=',
861861
'zlib=',
862862
'quiet=',
@@ -868,11 +868,10 @@ def nc3tonc4():
868868
'chunk=',
869869
'istart=',
870870
'istop='])
871-
except:
872-
(type, value, traceback) = sys.exc_info()
873-
sys.stdout.write("Error parsing the options. The error was: %s\n" % value)
871+
except getopt.GetoptError as error:
872+
sys.stdout.write("Error parsing the options. The error was: %s\n" % error)
874873
sys.stderr.write(usage)
875-
sys.exit(0)
874+
sys.exit(2)
876875

877876
# default options
878877
overwritefile = 0
@@ -923,13 +922,13 @@ def nc3tonc4():
923922
else:
924923
sys.stdout.write("%s: Unrecognized option\n" % option[0])
925924
sys.stderr.write(usage)
926-
sys.exit(0)
925+
sys.exit(2)
927926

928927
# if we pass a number of files different from 2, abort
929928
if len(pargs) < 2 or len(pargs) > 2:
930929
sys.stdout.write("You need to pass both source and destination!.\n")
931930
sys.stderr.write(usage)
932-
sys.exit(0)
931+
sys.exit(2)
933932

934933
# Catch the files passed as the last arguments
935934
filename3 = pargs[0]

‎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)