Skip to content

Commit 39319c8

Browse files
authored
Merge pull request #1525 from FFspiky/fix/1404-auto-complex-write
Keep explicit real variable shapes with auto_complex=True
2 parents 0a79d16 + 56ca59b commit 39319c8

3 files changed

Lines changed: 130 additions & 5 deletions

File tree

‎Changelog‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
version 1.7.6 (not yet released)
22
================================
3+
* Preserve explicit real variable dimensions and I/O with auto_complex=True,
4+
while retaining complex decoding on reopen (issue #1404, PR #1525).
35
* Speed up index setup in _StartCountStride (used when indexing variables) by
46
skipping numpy conversion for plain ints and slices and classifying each index once (PR #1524).
57

‎src/netCDF4/_netCDF4.pyx‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1254,6 +1254,14 @@ When writing files using `auto_complex=True`, `netCDF4` will use:
12541254
- or a dimension of length 2 named `_pfnc_complex` for netCDF3 or classic
12551255
formats.
12561256
1257+
Variables created with a real or compound datatype retain that datatype and
1258+
all of their dimensions, even when `auto_complex=True`. For example, a real
1259+
variable with dimensions `("x", "complex")` accepts separate real and imaginary
1260+
components along its last axis. Reopening that file with `auto_complex=True`
1261+
interprets the stored convention as a complex variable with dimensions `("x",)`.
1262+
To write complex arrays directly, create the variable with datatype `"c8"` or
1263+
`"c16"` instead.
1264+
12571265
Support for complex numbers is handled via the
12581266
[`nc-complex`](https://github.com/PlasmaFAIR/nc-complex) library. See there for
12591267
further details.
@@ -4481,7 +4489,10 @@ does not do anything."""
44814489
if dim.isunlimited(): self._nunlimdim = self._nunlimdim + 1
44824490

44834491
# set ndim attribute (number of dimensions).
4484-
self.ndim = _inq_varndims(self._grpid, self._varid, self._grp.auto_complex)
4492+
# A newly created real variable may happen to use a complex-looking
4493+
# dimension. Only hide its component axis when its Python dtype is
4494+
# complex; otherwise its shape and I/O buffers must stay real.
4495+
self.ndim = _inq_varndims(self._grpid, self._varid, is_complex)
44854496
self._name = name
44864497
# default for automatically applying scale_factor and
44874498
# add_offset, and converting to/from masked arrays is True.
@@ -4609,7 +4620,7 @@ does not do anything."""
46094620
cdef int ierr, dimid
46104621
cdef char namstring[NC_MAX_NAME+1]
46114622

4612-
dimids = _inq_vardimid(self._grpid, self._varid, self._grp.auto_complex)
4623+
dimids = _inq_vardimid(self._grpid, self._varid, dtype_is_complex(self.dtype))
46134624

46144625
# loop over dimensions, retrieve names.
46154626
dimensions = ()
@@ -5937,7 +5948,7 @@ NC_CHAR).
59375948
if not data.dtype.isnative:
59385949
data = data.byteswap()
59395950
# strides all 1 or scalar variable, use put_vara (faster)
5940-
if self._grp.auto_complex:
5951+
if dtype_is_complex(self.dtype):
59415952
with nogil:
59425953
ierr = pfnc_put_vars(self._grpid, self._varid,
59435954
startp, countp, stridep, PyArray_DATA(data))
@@ -6062,7 +6073,7 @@ NC_CHAR).
60626073
# strides all 1 or scalar variable, use get_vara (faster)
60636074
# if count contains a zero element, no data is being read
60646075
if 0 not in count:
6065-
if self._grp.auto_complex:
6076+
if dtype_is_complex(self.dtype):
60666077
with nogil:
60676078
ierr = pfnc_get_vars(self._grpid, self._varid,
60686079
startp, countp, stridep,

‎test/test_complex.py‎

Lines changed: 113 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414

1515
class ComplexNumbersTestCase(unittest.TestCase):
1616
def setUp(self):
17-
self.tmp_path = pathlib.Path(tempfile.mkdtemp())
17+
tmp_dir = tempfile.TemporaryDirectory()
18+
self.addCleanup(tmp_dir.cleanup)
19+
self.tmp_path = pathlib.Path(tmp_dir.name)
1820

1921
def test_read_dim(self):
2022
filename = self.tmp_path / "test_read_dim.nc"
@@ -34,6 +36,116 @@ def test_read_dim(self):
3436

3537
assert np.array_equal(data, complex_array)
3638

39+
def test_write_real_with_complex_dimension(self):
40+
# A new variable must retain its requested dtype and dimensions, even
41+
# when its on-disk layout matches a complex-number convention (#1404).
42+
for format in ("NETCDF4", "NETCDF4_CLASSIC", "NETCDF3_CLASSIC"):
43+
for dim_name in ("complex", "ri", "_pfnc_complex"):
44+
for dtype in ("f4", "f8", "i4"):
45+
with self.subTest(format=format, dim_name=dim_name, dtype=dtype):
46+
filename = self.tmp_path / "test_write_real.nc"
47+
values = np.arange(12, dtype=dtype).reshape(6, 2)
48+
with netCDF4.Dataset(
49+
filename, "w", format=format, auto_complex=True
50+
) as f:
51+
f.createDimension("x", 6)
52+
f.createDimension(dim_name, 2)
53+
var = f.createVariable("data", dtype, ("x", dim_name))
54+
self.assertEqual(var.dtype, np.dtype(dtype))
55+
self.assertEqual(var.dimensions, ("x", dim_name))
56+
self.assertEqual(var.ndim, 2)
57+
self.assertEqual(var.shape, values.shape)
58+
var[:] = values
59+
var[::2, 1] = -1
60+
values[::2, 1] = -1
61+
np.testing.assert_array_equal(var[:], values)
62+
np.testing.assert_array_equal(var[::-2, ::-1], values[::-2, ::-1])
63+
64+
with netCDF4.Dataset(filename) as f:
65+
self.assertEqual(f["data"].dimensions, ("x", dim_name))
66+
np.testing.assert_array_equal(f["data"][:], values)
67+
68+
# Existing floating-point layouts must still decode
69+
# as complex when reopening with auto_complex=True.
70+
if dtype != "i4":
71+
with netCDF4.Dataset(filename, auto_complex=True) as f:
72+
var = f["data"]
73+
self.assertEqual(var.dimensions, ("x",))
74+
self.assertEqual(var.ndim, 1)
75+
self.assertEqual(var.dtype, np.dtype("c8" if dtype == "f4" else "c16"))
76+
np.testing.assert_array_equal(
77+
var[:], values[:, 0] + 1j * values[:, 1]
78+
)
79+
80+
def test_write_real_component_axis(self):
81+
# A component-like dimension can also be an ordinary leading axis,
82+
# or the only axis of a real variable.
83+
for dimensions in (("complex", "x"), ("complex",)):
84+
with self.subTest(dimensions=dimensions):
85+
filename = self.tmp_path / "test_write_real_axis.nc"
86+
shape = (2, 3) if len(dimensions) == 2 else (2,)
87+
values = np.arange(np.prod(shape), dtype="f8").reshape(shape)
88+
with netCDF4.Dataset(filename, "w", auto_complex=True) as f:
89+
f.createDimension("complex", 2)
90+
f.createDimension("x", 3)
91+
var = f.createVariable("data", "f8", dimensions)
92+
self.assertEqual(var.dimensions, dimensions)
93+
self.assertEqual(var.ndim, len(dimensions))
94+
var[:] = values
95+
np.testing.assert_array_equal(var[:], values)
96+
with netCDF4.Dataset(filename) as f:
97+
np.testing.assert_array_equal(f["data"][:], values)
98+
99+
def test_write_complex_casts_real_values(self):
100+
# Both compound and dimension storage must cast real input to complex,
101+
# and reopened variables must keep the same complex I/O behavior.
102+
for format in ("NETCDF4", "NETCDF3_CLASSIC"):
103+
for dtype in ("c8", "c16"):
104+
with self.subTest(format=format, dtype=dtype):
105+
filename = self.tmp_path / "test_write_complex_cast.nc"
106+
values = complex_array.astype(dtype)
107+
with netCDF4.Dataset(
108+
filename, "w", format=format, auto_complex=True
109+
) as f:
110+
f.createDimension("x", len(values))
111+
var = f.createVariable("data", dtype, ("x",))
112+
self.assertEqual(var.dimensions, ("x",))
113+
var[:] = values.real
114+
np.testing.assert_array_equal(var[:], values.real)
115+
var[::2] = values[::2]
116+
expected = values.real.astype(dtype)
117+
expected[::2] = values[::2]
118+
np.testing.assert_array_equal(var[:], expected)
119+
with netCDF4.Dataset(filename, "r+", auto_complex=True) as f:
120+
var = f["data"]
121+
self.assertEqual(var.dtype, np.dtype(dtype))
122+
np.testing.assert_array_equal(var[:], expected)
123+
var[:] = values
124+
with netCDF4.Dataset(filename) as f:
125+
raw = f["data"]
126+
if format == "NETCDF4":
127+
self.assertEqual(raw.dimensions, ("x",))
128+
np.testing.assert_array_equal(raw[:]["r"], values.real)
129+
np.testing.assert_array_equal(raw[:]["i"], values.imag)
130+
else:
131+
self.assertEqual(len(raw.dimensions), 2)
132+
self.assertEqual(raw.shape, (len(values), 2))
133+
np.testing.assert_array_equal(raw[:, 0], values.real)
134+
np.testing.assert_array_equal(raw[:, 1], values.imag)
135+
with netCDF4.Dataset(filename, auto_complex=True) as f:
136+
np.testing.assert_array_equal(f["data"][:], values)
137+
138+
def test_write_explicit_complex_struct(self):
139+
filename = self.tmp_path / "test_write_explicit_struct.nc"
140+
with netCDF4.Dataset(filename, "w", auto_complex=True) as f:
141+
f.createDimension("x", len(complex_array))
142+
datatype = f.createCompoundType(np_dt, "nc_complex")
143+
var = f.createVariable("data", datatype, ("x",))
144+
var[:] = complex_struct_array
145+
np.testing.assert_array_equal(var[:], complex_struct_array)
146+
with netCDF4.Dataset(filename, auto_complex=True) as f:
147+
np.testing.assert_array_equal(f["data"][:], complex_array)
148+
37149
def test_read_struct(self):
38150
filename = self.tmp_path / "test_read_struct.nc"
39151

0 commit comments

Comments
 (0)