Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@
of the "dcnum-job" and "dcnum-log" logs if necessary
- fix: brightness features failed with a `ZeroDivisionError` for
empty masks; they are NaN now
- fix: the cached arrays returned by `get_mapping_indices` could be
modified by callers, changing the result of later calls; they are
read-only now
- docs: comment on intended behavior of `fill_holes` (mask
post-processing), Haralick texture features, and the sparsemed
background assignment after cleansing
Expand Down
17 changes: 14 additions & 3 deletions dcnum/read/mapped.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,13 @@ def get_mapping_indices(
raised if a list or array contains indices beyond the dataset.
Slices without start or stop require `size`.

Returns
-------
indices: np.ndarray
Integer array with the mapping indices. For integers and slices,
this array is cached and shared with other callers, so it is
read-only (make a copy if you need to modify it).

Raises
------
ValueError
Expand Down Expand Up @@ -130,18 +137,22 @@ def _get_mapping_indices_cached(
index_mapping: numbers.Integral | tuple
):
if isinstance(index_mapping, numbers.Integral):
return np.arange(index_mapping)
indices = np.arange(index_mapping)
elif isinstance(index_mapping, tuple):
im_slice = slice(*index_mapping)
if im_slice.stop is None or im_slice.start is None:
raise NotImplementedError(
"Slices must have start and stop defined")
return np.arange(im_slice.start, im_slice.stop, im_slice.step)
indices = np.arange(im_slice.start, im_slice.stop, im_slice.step)
elif isinstance(index_mapping, list):
return np.asarray(index_mapping, dtype=np.uint32)
indices = np.asarray(index_mapping, dtype=np.uint32)
else:
raise ValueError(f"Invalid type for cached `index_mapping`: "
f"{type(index_mapping)} ({index_mapping})")
# The returned array is shared by all callers (cache), so it must
# not be modified.
indices.setflags(write=False)
return indices


def get_mapped_object(obj, index_mapping=None):
Expand Down
18 changes: 17 additions & 1 deletion tests/test_read_mapped.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
import numpy as np
import pytest

from dcnum.read.mapped import MappedHDF5Dataset, get_mapped_object
from dcnum.read.mapped import (
MappedHDF5Dataset, get_mapped_object, get_mapping_indices
)


@pytest.mark.parametrize("idx", [
Expand All @@ -23,3 +25,17 @@ def test_mapped_dataset_getitem(tmp_path, idx):
assert isinstance(mds, MappedHDF5Dataset)
assert mds.shape == (4, 3, 4)
assert np.array_equal(mds[idx], data[mapping][idx])


@pytest.mark.parametrize("index_mapping", [10, slice(2, 8), slice(1, 9, 2)])
def test_mapping_indices_cache_not_modifiable(index_mapping):
"""Cached mapping indices are shared and must not be modified

In dcnum 0.31.2, modifying the returned array changed the result
of all later calls with the same mapping.
"""
indices = get_mapping_indices(index_mapping)
reference = indices.copy()
with pytest.raises(ValueError, match="read-only"):
indices[0] = 99
assert np.all(get_mapping_indices(index_mapping) == reference)
Loading