Skip to content

Commit 63ad784

Browse files
authored
Merge branch 'master' into fix/win-arm64-py310-numpy
2 parents d99748d + ba22b9c commit 63ad784

4 files changed

Lines changed: 562 additions & 18 deletions

File tree

‎Changelog‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
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+
* Preserve surviving dimensions and decoded types for empty orthogonal selections,
5+
including empty integer indices and all-false masks (PR #1499).
46
* Convert non-native-endian numeric attributes to native byte order before writing (issue #1502).
57
* Fix command-line usage error exit codes and --help handling, honour nc4tonc3 --chunk,
68
and fix ncinfo group dimension selection (issue #1500).

‎src/netCDF4/_netCDF4.pyx‎

Lines changed: 52 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5103,6 +5103,8 @@ rename a `Variable` attribute named `oldname` to `newname`."""
51035103

51045104
# Fill output array with data chunks.
51055105
for (a,b,c,i) in zip(start, count, stride, put_ind):
5106+
if 0 in b:
5107+
continue # retain the empty shape without issuing native I/O
51065108
datout = self._get(a,b,c)
51075109
if not hasattr(datout,'shape') or data.shape == datout.shape:
51085110
data = datout
@@ -5185,8 +5187,8 @@ rename a `Variable` attribute named `oldname` to `newname`."""
51855187
if len(data.shape) > 0 and data.shape[-1] == self.shape[-1]:
51865188
# also make sure slice is along last dimension
51875189
matchdim = True
5188-
for cnt in count:
5189-
if cnt[-1] != self.shape[-1]:
5190+
for cnt, ind in zip(count, put_ind):
5191+
if cnt[-1] != self.shape[-1] or (0 in cnt and ind[-1] != slice(None)):
51905192
matchdim = False
51915193
break
51925194
if matchdim:
@@ -5625,7 +5627,7 @@ cannot be safely cast to variable data type""" % attname
56255627
data = numpy.tile(data,datashape)
56265628
# reshape data array if needed to conform with start,count,stride.
56275629
if data.ndim != len(datashape) or\
5628-
(data.shape != datashape and data.ndim > 1): # issue #1083
5630+
(data.shape != datashape and (data.ndim > 1 or 0 in datashape)): # issue #1083
56295631
# create a view so shape in caller is not modified (issue 90)
56305632
try: # if extra singleton dims, just reshape
56315633
data = data.view()
@@ -7243,8 +7245,8 @@ class _Variable:
72437245
# is a perfect match for the "start", "count" and "stride"
72447246
# arguments to the nc_get_var() function, and is much more easy
72457247
# to use.
7246-
start, count, stride, put_ind =\
7247-
_StartCountStride(elem, self.shape)
7248+
start, count, stride, put_ind, selection =\
7249+
_StartCountStride(elem, self.shape, return_selection=True)
72487250
datashape = _out_array_shape(count)
72497251
data = ma.empty(datashape, dtype=self.dtype)
72507252

@@ -7271,6 +7273,51 @@ class _Variable:
72717273
count = [abs(cnt) for cnt in count]
72727274
if (numpy.array(stride) < 0).any():
72737275
raise IndexError('negative strides not allowed when slicing MFVariable Variable instance')
7276+
if 0 in count:
7277+
# An empty underlying read retains automatic unpacking and
7278+
# unsigned conversion without reading or concatenating records.
7279+
empty = (slice(0, 0),) + (slice(None),) * (self.ndim - 1)
7280+
if self.dtype.kind == 'S' and (count[-1] != self.shape[-1] or ind[-1] != slice(None)):
7281+
# A partial, scalar or fancy character selection is not
7282+
# eligible for automatic conversion of the full width.
7283+
empty = empty[:-1] + (slice(0, 0),)
7284+
records = selection[0]
7285+
selected = []
7286+
offset = 0
7287+
if isinstance(records, slice):
7288+
beg, end, inc = records.indices(self.shape[0])
7289+
for n, length in enumerate(self._recLen):
7290+
# Intersect an arithmetic progression with each file's
7291+
# record interval without materializing all records.
7292+
lower = max(beg, offset)
7293+
first = beg + ((lower - beg + inc - 1) // inc) * inc
7294+
if first < min(end, offset + length):
7295+
selected.append(n)
7296+
offset += length
7297+
else:
7298+
# Non-slice fancy indexing processes one record chunk at a
7299+
# time; preserve the final chunk's dtype, as for nonempty
7300+
# reads. Scalars select their own file by the same rule.
7301+
record = records[-1] if numpy.iterable(records) else records
7302+
if record < 0:
7303+
record += self.shape[0]
7304+
for n, length in enumerate(self._recLen):
7305+
if offset <= record < offset + length:
7306+
selected.append(n)
7307+
break
7308+
offset += length
7309+
# With no selected records there is no contributing file;
7310+
# retain the first file's empty-decoding convention.
7311+
if not selected:
7312+
selected = [0]
7313+
decoded = [Variable.__getitem__(self._recVar[n], empty) for n in selected]
7314+
if any(part.ndim != decoded[0].ndim for part in decoded):
7315+
raise ValueError('all the input arrays must have same number of dimensions')
7316+
data = data.astype(numpy.result_type(*(part.dtype for part in decoded)))
7317+
if decoded[0].ndim < self.ndim:
7318+
data = data.reshape(datashape[:-1])
7319+
squeeze = squeeze[:-1]
7320+
continue
72747321
# Start, stop and step along 1st dimension, eg the unlimited
72757322
# dimension.
72767323
sta = start[0]

‎src/netCDF4/utils.py‎

Lines changed: 56 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def _quantize(data,least_significant_digit):
7979
return datout
8080

8181
def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\
82-
put=False, use_get_vars = True):
82+
put=False, use_get_vars = True, return_selection=False):
8383
"""Return start, count, stride and indices needed to store/extract data
8484
into/from a netCDF variable.
8585
@@ -134,6 +134,9 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\
134134
datashape : sequence
135135
The shape of the data that is being stored. Only needed by __setitem__
136136
put : True|False (default False). If called from __setitem__, put is True.
137+
return_selection : bool (default False)
138+
Also return the normalized selectors, for callers that need their exact
139+
indices after an empty selection has been represented by compact chunks.
137140
138141
Returns
139142
-------
@@ -148,6 +151,8 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\
148151
indices : ndarray (..., n)
149152
An array storing the indices describing the location of the
150153
data chunk in the target/source array (__getitem__/__setitem__).
154+
selection : list, optional
155+
Normalized selectors, included only when return_selection is True.
151156
152157
Notes:
153158
@@ -322,6 +327,10 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\
322327
newElem.append(e)
323328
elif np.iterable(e) and len(e) == 1:
324329
newElem.append(slice(e[0], e[0] + 1, 1))
330+
elif np.iterable(e) and len(e) == 0:
331+
# Retain counts and scalar squeeze markers for the other axes.
332+
# A zero-length chunk axis would discard all of that metadata.
333+
newElem.append(slice(0, 0, 1))
325334
else:
326335
newElem.append(e)
327336
elem = newElem
@@ -358,8 +367,23 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\
358367

359368
# pad datashape with zeros for dimensions not being sliced (issue #906)
360369
# only used when data covers slice over subset of dimensions
370+
padding_dims = sum(1 for e in elem if type(e) == slice)
371+
if datashape and len(datashape) != len(elem):
372+
for i, e in enumerate(elem):
373+
if type(e) != slice:
374+
continue
375+
length = shape[i]
376+
if hasunlim and unlimd[dimensions[i]]:
377+
if e.stop is None:
378+
continue # an open-ended write may extend this dimension
379+
length = max(length, e.stop)
380+
if not range(*e.indices(length)):
381+
# Empty writes retain fancy axes too. Keep the historical
382+
# padding rules for nonempty writes outside this correction.
383+
padding_dims = sum(1 for index in elem if type(index) == slice or np.iterable(index))
384+
break
361385
if datashape and len(datashape) != len(elem) and\
362-
len(datashape) == sum(1 for e in elem if type(e) == slice):
386+
len(datashape) == padding_dims:
363387
datashapenew = (); i=0
364388
for e in elem:
365389
if type(e) != slice and not np.iterable(e): # scalar integer slice
@@ -369,13 +393,14 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\
369393
i+=1
370394
datashape = datashapenew
371395

372-
# Create the start, count, stride and indices arrays.
373-
396+
# First describe one chunk with the complete selected shape. Only expand
397+
# integer index arrays into their Cartesian chunk grid if it is nonempty.
374398
sdim.append(max(nDims, 1))
375-
start = np.empty(sdim, dtype=np.intp)
376-
count = np.empty(sdim, dtype=np.intp)
377-
stride = np.empty(sdim, dtype=np.intp)
378-
indices = np.empty(sdim, dtype=object)
399+
compact = [1] * nDims + [nDims]
400+
start = np.empty(compact, dtype=np.intp)
401+
count = np.empty(compact, dtype=np.intp)
402+
stride = np.empty(compact, dtype=np.intp)
403+
indices = np.empty(compact, dtype=object)
379404

380405
for i, e in enumerate(elem):
381406

@@ -426,11 +451,10 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\
426451

427452
# ITERABLE #
428453
elif np.iterable(e) and np.array(e).dtype.kind in 'i': # Sequence of integers
429-
if start[...,i].size:
430-
start[...,i] = np.apply_along_axis(lambda x: e*x, i, np.ones(sdim[:-1]))
431-
indices[...,i] = np.apply_along_axis(lambda x: np.arange(sdim[i])*x, i, np.ones(sdim[:-1], int))
432-
count[...,i] = 1
433-
stride[...,i] = 1
454+
start[...,i] = e[0]
455+
count[...,i] = len(e)
456+
stride[...,i] = 1
457+
indices[...,i] = 0 # preserve the distinction from a full slice
434458

435459
# all that's left is SCALAR INTEGER #
436460
else:
@@ -446,6 +470,25 @@ def _StartCountStride(elem, shape, dimensions=None, grp=None, datashape=None,\
446470
indices[...,i] = -1 # Use -1 instead of 0 to indicate that
447471
# this dimension shall be squeezed.
448472

473+
if 0 in count and not put:
474+
# Empty reads bypass native bounds checks, including those for vlens.
475+
for i, e in enumerate(elem):
476+
if type(e) != slice and not np.iterable(e) and e >= shape[i]:
477+
raise IndexError("integer index exceeds dimension size")
478+
479+
if 0 not in count and sdim != compact:
480+
start = np.broadcast_to(start, sdim).copy()
481+
count = np.broadcast_to(count, sdim).copy()
482+
stride = np.broadcast_to(stride, sdim).copy()
483+
indices = np.broadcast_to(indices, sdim).copy()
484+
for i, e in enumerate(elem):
485+
if np.iterable(e):
486+
start[...,i] = np.apply_along_axis(lambda x: e*x, i, np.ones(sdim[:-1]))
487+
indices[...,i] = np.apply_along_axis(lambda x: np.arange(sdim[i])*x, i, np.ones(sdim[:-1], int))
488+
count[...,i] = 1
489+
490+
if return_selection:
491+
return start, count, stride, indices, elem
449492
return start, count, stride, indices#, out_shape
450493

451494
def _out_array_shape(count):

0 commit comments

Comments
 (0)