Skip to content

Commit 933f2e4

Browse files
authored
Merge upstream master into empty-indexing branch
Sync upstream 7b4d837 as requested for Unidata#1499. Preserve the existing contribution and history; no unrelated feature changes.
2 parents a0a3271 + 7b4d837 commit 933f2e4

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,5 +1,8 @@
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).
4+
* Fix command-line usage error exit codes and --help handling, honour nc4tonc3 --chunk,
5+
and fix ncinfo group dimension selection (issue #1500).
36
* Change default encoding for stringtochar/chartostring functions from 'utf-8' to 'utf-8'/'ascii' for dtype.kind='U'/'S'
47
(issue #1464).
58
* 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
@@ -557,14 +557,14 @@ def ncinfo():
557557

558558
try:
559559
opts, pargs = getopt.getopt(sys.argv[1:],'hv:g:d:',
560-
['group=',
560+
['help',
561+
'group=',
561562
'variable=',
562563
'dimension='])
563-
except:
564-
(type, value, traceback) = sys.exc_info()
565-
sys.stdout.write("Error parsing the options. The error was: %s\n" % value)
564+
except getopt.GetoptError as error:
565+
sys.stdout.write("Error parsing the options. The error was: %s\n" % error)
566566
sys.stderr.write(usage)
567-
sys.exit(0)
567+
sys.exit(2)
568568

569569
# Get the options
570570
group = None; var = None; dim=None
@@ -581,15 +581,15 @@ def ncinfo():
581581
else:
582582
sys.stdout.write("%s: Unrecognized option\n" % option[0])
583583
sys.stderr.write(usage)
584-
sys.exit(0)
584+
sys.exit(2)
585585

586586
# filename passed as last argument
587587
try:
588588
filename = pargs[-1]
589589
except IndexError:
590590
sys.stdout.write("You need to pass netcdf filename!\n.")
591591
sys.stderr.write(usage)
592-
sys.exit(0)
592+
sys.exit(2)
593593

594594
f = Dataset(filename)
595595
if group is None:
@@ -608,7 +608,7 @@ def ncinfo():
608608
if var is not None:
609609
print(g.variables[var])
610610
if dim is not None:
611-
print(g.dimensions[var])
611+
print(g.dimensions[dim])
612612
f.close()
613613

614614
def _nc4tonc3(filename4,filename3,clobber=False,nchunk=10,quiet=False,format='NETCDF3_64BIT'):
@@ -696,16 +696,15 @@ def nc4tonc3():
696696

697697
try:
698698
opts, pargs = getopt.getopt(sys.argv[1:], 'ho',
699-
['format=','chunk=','quiet='])
700-
except:
701-
(type, value, traceback) = sys.exc_info()
702-
sys.stdout.write("Error parsing the options. The error was: %s\n" % value)
699+
['help','format=','chunk=','quiet='])
700+
except getopt.GetoptError as error:
701+
sys.stdout.write("Error parsing the options. The error was: %s\n" % error)
703702
sys.stderr.write(usage)
704-
sys.exit(0)
703+
sys.exit(2)
705704

706705
# default options
707706
quiet = 0
708-
chunk = 1000
707+
chunk = 10
709708
format = 'NETCDF3_64BIT'
710709
overwritefile = 0
711710

@@ -723,22 +722,22 @@ def nc4tonc3():
723722
elif option[0] == '--chunk':
724723
chunk = int(option[1])
725724
else:
726-
sys.stdout.write("%s : Unrecognized option\n" % options[0])
725+
sys.stdout.write("%s : Unrecognized option\n" % option[0])
727726
sys.stderr.write(usage)
728-
sys.exit(0)
727+
sys.exit(2)
729728

730729
# if we pass a number of files different from 2, abort
731730
if len(pargs) < 2 or len(pargs) > 2:
732731
sys.stdout.write("You need to pass both source and destination!\n.")
733732
sys.stderr.write(usage)
734-
sys.exit(0)
733+
sys.exit(2)
735734

736735
# Catch the files passed as the last arguments
737736
filename4 = pargs[0]
738737
filename3 = pargs[1]
739738

740739
# copy the data from filename4 to filename3.
741-
_nc4tonc3(filename4,filename3,clobber=overwritefile,quiet=quiet,format=format)
740+
_nc4tonc3(filename4,filename3,clobber=overwritefile,nchunk=chunk,quiet=quiet,format=format)
742741

743742

744743
def _nc3tonc4(filename3,filename4,unpackshort=True,
@@ -899,7 +898,8 @@ def nc3tonc4():
899898

900899
try:
901900
opts, pargs = getopt.getopt(sys.argv[1:], 'ho',
902-
['classic=',
901+
['help',
902+
'classic=',
903903
'vars=',
904904
'zlib=',
905905
'quiet=',
@@ -911,11 +911,10 @@ def nc3tonc4():
911911
'chunk=',
912912
'istart=',
913913
'istop='])
914-
except:
915-
(type, value, traceback) = sys.exc_info()
916-
sys.stdout.write("Error parsing the options. The error was: %s\n" % value)
914+
except getopt.GetoptError as error:
915+
sys.stdout.write("Error parsing the options. The error was: %s\n" % error)
917916
sys.stderr.write(usage)
918-
sys.exit(0)
917+
sys.exit(2)
919918

920919
# default options
921920
overwritefile = 0
@@ -966,13 +965,13 @@ def nc3tonc4():
966965
else:
967966
sys.stdout.write("%s: Unrecognized option\n" % option[0])
968967
sys.stderr.write(usage)
969-
sys.exit(0)
968+
sys.exit(2)
970969

971970
# if we pass a number of files different from 2, abort
972971
if len(pargs) < 2 or len(pargs) > 2:
973972
sys.stdout.write("You need to pass both source and destination!.\n")
974973
sys.stderr.write(usage)
975-
sys.exit(0)
974+
sys.exit(2)
976975

977976
# Catch the files passed as the last arguments
978977
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()

‎test/test_cli.py‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import sys
2+
from unittest.mock import patch
3+
4+
import numpy as np
5+
import pytest
6+
7+
from netCDF4 import Dataset, utils
8+
9+
10+
@pytest.mark.parametrize("command", [utils.ncinfo, utils.nc3tonc4, utils.nc4tonc3])
11+
@pytest.mark.parametrize("args", [[], ["--unknown"]])
12+
def test_usage_error(command, args, monkeypatch, capsys):
13+
monkeypatch.setattr(sys, "argv", [command.__name__, *args])
14+
with pytest.raises(SystemExit) as exc:
15+
command()
16+
assert exc.value.code == 2
17+
assert "usage:" in capsys.readouterr().err
18+
19+
20+
@pytest.mark.parametrize("command, option", [
21+
(utils.ncinfo, "--group"),
22+
(utils.nc3tonc4, "--chunk"),
23+
(utils.nc4tonc3, "--chunk"),
24+
])
25+
def test_missing_option_value(command, option, monkeypatch, capsys):
26+
monkeypatch.setattr(sys, "argv", [command.__name__, option])
27+
with pytest.raises(SystemExit) as exc:
28+
command()
29+
assert exc.value.code == 2
30+
assert "usage:" in capsys.readouterr().err
31+
32+
33+
@pytest.mark.parametrize("command", [utils.nc3tonc4, utils.nc4tonc3])
34+
@pytest.mark.parametrize("args", [["source.nc"], ["source.nc", "dest.nc", "extra.nc"]])
35+
def test_converter_file_count(command, args, monkeypatch, capsys):
36+
monkeypatch.setattr(sys, "argv", [command.__name__, *args])
37+
with pytest.raises(SystemExit) as exc:
38+
command()
39+
assert exc.value.code == 2
40+
assert "usage:" in capsys.readouterr().err
41+
42+
43+
@pytest.mark.parametrize("command", [utils.ncinfo, utils.nc3tonc4, utils.nc4tonc3])
44+
@pytest.mark.parametrize("option", ["-h", "--help"])
45+
def test_help(command, option, monkeypatch, capsys):
46+
monkeypatch.setattr(sys, "argv", [command.__name__, option])
47+
with pytest.raises(SystemExit) as exc:
48+
command()
49+
assert exc.value.code == 0
50+
output = capsys.readouterr()
51+
assert "usage:" in output.err
52+
assert "Error" not in output.out
53+
54+
55+
def test_ncinfo_group_dimension(tmp_path, monkeypatch, capsys):
56+
filename = str(tmp_path / "groups.nc")
57+
with Dataset(filename, "w") as dataset:
58+
dataset.createGroup("g1").createDimension("x", 7)
59+
monkeypatch.setattr(sys, "argv", ["ncinfo", "-g", "g1", "-d", "x", filename])
60+
utils.ncinfo()
61+
assert "name = 'x', size = 7" in capsys.readouterr().out
62+
63+
64+
@pytest.mark.parametrize("chunk", [None, 0, 5])
65+
def test_nc4tonc3_chunk(tmp_path, chunk, monkeypatch):
66+
source = str(tmp_path / "source.nc")
67+
destination = str(tmp_path / "destination.nc")
68+
values = np.arange(25, dtype="i4")
69+
with Dataset(source, "w", format="NETCDF4_CLASSIC") as dataset:
70+
dataset.createDimension("record", None)
71+
dataset.createVariable("values", "i4", ("record",))[:] = values
72+
args = ["nc4tonc3", "--quiet=1"]
73+
if chunk is not None:
74+
args.append("--chunk=%s" % chunk)
75+
monkeypatch.setattr(sys, "argv", [*args, source, destination])
76+
with patch.object(utils, "_nc4tonc3", wraps=utils._nc4tonc3) as convert:
77+
utils.nc4tonc3()
78+
assert convert.call_args.kwargs["nchunk"] == (10 if chunk is None else chunk)
79+
with Dataset(destination) as dataset:
80+
assert dataset.file_format == "NETCDF3_64BIT_OFFSET"
81+
np.testing.assert_array_equal(dataset.variables["values"][:], values)

0 commit comments

Comments
 (0)