Skip to content

Commit 1bd0195

Browse files
committed
Preserve dimensions for empty orthogonal indexing
Retain selected dimensions and scalar squeeze markers without allocating Cartesian chunk grids for empty results. Preserve broadcastable empty writes and automatic decoding, using the selected multifile components and existing slice/fancy-index dtype rules.
1 parent 6e67576 commit 1bd0195

3 files changed

Lines changed: 560 additions & 18 deletions

File tree

‎src/netCDF4/_netCDF4.pyx‎

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

51065106
# Fill output array with data chunks.
51075107
for (a,b,c,i) in zip(start, count, stride, put_ind):
5108+
if 0 in b:
5109+
continue # retain the empty shape without issuing native I/O
51085110
datout = self._get(a,b,c)
51095111
if not hasattr(datout,'shape') or data.shape == datout.shape:
51105112
data = datout
@@ -5187,8 +5189,8 @@ rename a `Variable` attribute named `oldname` to `newname`."""
51875189
if len(data.shape) > 0 and data.shape[-1] == self.shape[-1]:
51885190
# also make sure slice is along last dimension
51895191
matchdim = True
5190-
for cnt in count:
5191-
if cnt[-1] != self.shape[-1]:
5192+
for cnt, ind in zip(count, put_ind):
5193+
if cnt[-1] != self.shape[-1] or (0 in cnt and ind[-1] != slice(None)):
51925194
matchdim = False
51935195
break
51945196
if matchdim:
@@ -5627,7 +5629,7 @@ cannot be safely cast to variable data type""" % attname
56275629
data = numpy.tile(data,datashape)
56285630
# reshape data array if needed to conform with start,count,stride.
56295631
if data.ndim != len(datashape) or\
5630-
(data.shape != datashape and data.ndim > 1): # issue #1083
5632+
(data.shape != datashape and (data.ndim > 1 or 0 in datashape)): # issue #1083
56315633
# create a view so shape in caller is not modified (issue 90)
56325634
try: # if extra singleton dims, just reshape
56335635
data = data.view()
@@ -7245,8 +7247,8 @@ class _Variable:
72457247
# is a perfect match for the "start", "count" and "stride"
72467248
# arguments to the nc_get_var() function, and is much more easy
72477249
# to use.
7248-
start, count, stride, put_ind =\
7249-
_StartCountStride(elem, self.shape)
7250+
start, count, stride, put_ind, selection =\
7251+
_StartCountStride(elem, self.shape, return_selection=True)
72507252
datashape = _out_array_shape(count)
72517253
data = ma.empty(datashape, dtype=self.dtype)
72527254

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