diff --git a/CHANGELOG b/CHANGELOG index 52ec2b2..1f4e386 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -41,6 +41,13 @@ size equaled the number of images - fix: sparse median background computation failed for input data with a duration of zero (e.g. a single image) + - fix: "index_mapping" values beyond the dataset size (e.g. `1000` + or `slice(30, 1000)`) resulted in a wrong dataset size and an + `IndexError`, and open-ended slices (e.g. `slice(30, None)`) were + not supported; they are now limited to the dataset size (the + pipeline identifier still contains the user-specified value) + - fix: negative "index_mapping" values and mappings that do not + select any events now raise a `ValueError` - docs: comment on intended behavior of `fill_holes` (mask post-processing), Haralick texture features, and the sparsemed background assignment after cleansing diff --git a/dcnum/logic/ctrl.py b/dcnum/logic/ctrl.py index 6611296..b4bf84f 100644 --- a/dcnum/logic/ctrl.py +++ b/dcnum/logic/ctrl.py @@ -25,7 +25,7 @@ from ..segm.segmenter_mpo import MPOSegmenter from ..segm.segmenter_sto import STOSegmenter from ..meta import ppid -from ..read import HDF5Data, get_measurement_identifier, get_mapping_indices +from ..read import HDF5Data, get_measurement_identifier from .._version import version, version_tuple from ..write import ( HDF5Writer, QueueWriterProcess, QueueWriterThread, copy_features, @@ -652,7 +652,7 @@ def task_enforce_basin_strategy(self): basinmap0 = idx_um else: self.logger.info("Converting input mapping") - basinmap0 = get_mapping_indices(raw_im)[idx_um] + basinmap0 = self.draw.index_mapping_indices[idx_um] # Store the mapped basin data in the output file. hw.store_feature_chunk("basinmap0", basinmap0) self.logger.info("Input mapped to output with basinmap0") diff --git a/dcnum/read/hdf5_data.py b/dcnum/read/hdf5_data.py index e9d953b..3118e8b 100644 --- a/dcnum/read/hdf5_data.py +++ b/dcnum/read/hdf5_data.py @@ -17,7 +17,9 @@ from .cache import HDF5ImageCache, ImageCorrCache, md5sum from .const import PROTECTED_FEATURES -from .mapped import get_mapped_object, get_mapping_indices +from .mapped import ( + check_index_mapping, get_mapped_object, get_mapping_indices +) class BasinIdentifierMismatchError(BaseException): @@ -113,7 +115,9 @@ def __init__(self, - slice: use the events defined by a slice - list: list of integers specifying the event indices to use Numpy indexing rules apply. E.g. to only process the first - 100 events, set this to `100` or `slice(0, 100)`. + 100 events, set this to `100` or `slice(0, 100)`. Negative + values are not allowed. Integers and slices are limited to + the size of the dataset (e.g. `slice(30, None)`). """ # Init is in __setstate__ so we can pickle this class # and use it for multiprocessing. @@ -125,6 +129,7 @@ def __init__(self, # Optimize image chunk size with h5py.File(path, "r") as h5: + size = h5.attrs.get("experiment:event count") if "events/image" in h5: h5ds = h5["events/image"] if isinstance(h5ds, h5py.Dataset) and h5ds.chunks is not None: @@ -159,6 +164,14 @@ def __init__(self, "index_mapping": index_mapping, }) + if index_mapping is not None: + # Make sure the index mapping is valid + self._index_mapping_indices = get_mapping_indices( + index_mapping, size=size) + if self._index_mapping_indices.size == 0: + raise ValueError(f"The `index_mapping` {index_mapping} does " + f"not select any events in {path}") + def __contains__(self, item): return item in self.keys() @@ -183,8 +196,9 @@ def __getitem__(self, feat): # no mapping indices, just slice dat_sc = self.h5["events"][feat][:] else: - dat_sc = get_mapped_object(self.h5["events"][feat], - index_mapping=self.index_mapping)[:] + dat_sc = get_mapped_object( + self.h5["events"][feat], + index_mapping=self.index_mapping_indices)[:] self._cache_scalar[feat] = dat_sc return self._cache_scalar[feat] else: @@ -193,7 +207,7 @@ def __getitem__(self, feat): warnings.warn(f"Feature {feat} not cached (possibly slow)") return get_mapped_object( obj=self.h5["events"][feat], - index_mapping=self.index_mapping) + index_mapping=self.index_mapping_indices) else: # Check the basins for idx in range(len(self.basins)): @@ -322,15 +336,32 @@ def basin_sort_cmp(a, b): self.image_chunk_size = state["image_chunk_size"] self.index_mapping = state["index_mapping"] + self._index_mapping_indices = None def __len__(self): if self._len is None: if self.index_mapping is not None: - self._len = get_mapping_indices(self.index_mapping).size + self._len = self.index_mapping_indices.size else: self._len = self.h5.attrs["experiment:event count"] return self._len + @property + def index_mapping_indices(self) -> np.ndarray | None: + """Event indices selected by :attr:`index_mapping` + + In contrast to :attr:`index_mapping` (which is used in the + pipeline identifier), integers and slices are limited to the + size of the dataset. + """ + if self.index_mapping is None: + return None + if self._index_mapping_indices is None: + self._index_mapping_indices = get_mapping_indices( + self.index_mapping, + size=self.h5.attrs.get("experiment:event count")) + return self._index_mapping_indices + @property def h5(self) -> h5py.File: """The underlying HDF5 file, opened lazily in read-only mode""" @@ -504,6 +535,7 @@ def get_ppid_from_ppkw(cls, kwargs): def get_ppid_index_mapping(index_mapping): """Return the pipeline identifier part for index mapping""" im = index_mapping + check_index_mapping(im) if im is None: dim = "0" elif isinstance(im, numbers.Integral): @@ -611,7 +643,7 @@ def get_basin_data(self, index: int) -> tuple[ feat_basinmap = bn_dict.get("mapping", None) if feat_basinmap is None: # This is NOT a mapped basin. - index_mapping = self.index_mapping + index_mapping = self.index_mapping_indices else: # This is a mapped basin. Create an indexing list. if self.index_mapping is None: @@ -619,7 +651,7 @@ def get_basin_data(self, index: int) -> tuple[ basinmap_idx = slice(None) else: # The current dataset is also mapped. - basinmap_idx = get_mapping_indices(self.index_mapping) + basinmap_idx = self.index_mapping_indices basinmap = self.h5[f"events/{feat_basinmap}"] index_mapping = basinmap[basinmap_idx] @@ -719,7 +751,7 @@ def get_image_cache(self, feat): if feat not in self._image_cache: if f"events/{feat}" in self.h5: ds = self.h5[f"events/{feat}"] - idx_map = self.index_mapping + idx_map = self.index_mapping_indices else: idx_map = None # search all basins (internal basins are always first) diff --git a/dcnum/read/mapped.py b/dcnum/read/mapped.py index 61fa8db..2cbbb27 100644 --- a/dcnum/read/mapped.py +++ b/dcnum/read/mapped.py @@ -52,8 +52,32 @@ def __len__(self): return self.shape[0] +def check_index_mapping( + index_mapping: numbers.Integral | slice | list | np.ndarray | None + ): + """Raise a ValueError if `index_mapping` contains negative values""" + if index_mapping is None: + return + elif isinstance(index_mapping, numbers.Integral): + values = [index_mapping] + elif isinstance(index_mapping, slice): + values = [index_mapping.start, index_mapping.stop, + index_mapping.step] + elif isinstance(index_mapping, (np.ndarray, list)): + indices = np.asarray(index_mapping) + values = [np.min(indices)] if indices.size else [] + else: + # Type is checked elsewhere + values = [] + for val in values: + if val is not None and val < 0: + raise ValueError(f"Negative values in `index_mapping` are not " + f"allowed: {index_mapping}") + + def get_mapping_indices( - index_mapping: numbers.Integral | slice | list | np.ndarray + index_mapping: numbers.Integral | slice | list | np.ndarray, + size: int | None = None, ): """Return integer numpy array with mapping indices for a range @@ -64,14 +88,38 @@ def get_mapping_indices( - integer: results in np.arange(integer) - slice: results in np.arange(slice.start, slice.stop, slice.step) - list or np.ndarray: returns the input as uint32 array + Negative values are not allowed. + size: int + Size of the dataset to which the mapping is applied. If given, + integers and slices are limited to the dataset size (e.g. + `slice(30, None)` or `slice(30, 1000)` for a dataset of size + 40 results in `np.arange(30, 40)`), and a `ValueError` is + raised if a list or array contains indices beyond the dataset. + Slices without start or stop require `size`. + + Raises + ------ + ValueError + If `index_mapping` contains negative values or if it contains + indices beyond `size` """ + check_index_mapping(index_mapping) if isinstance(index_mapping, numbers.Integral): - return _get_mapping_indices_cached(index_mapping) + if size is not None: + index_mapping = min(index_mapping, size) + return _get_mapping_indices_cached(int(index_mapping)) elif isinstance(index_mapping, slice): + if size is not None: + # Limit slice to the dataset size + return _get_mapping_indices_cached(index_mapping.indices(size)) return _get_mapping_indices_cached( (index_mapping.start, index_mapping.stop, index_mapping.step)) elif isinstance(index_mapping, (np.ndarray, list)): - return np.asarray(index_mapping, dtype=np.uint32) + indices = np.asarray(index_mapping) + if indices.size and size is not None and np.max(indices) >= size: + raise ValueError(f"`index_mapping` contains indices beyond " + f"the dataset size {size}") + return np.asarray(indices, dtype=np.uint32) else: raise ValueError(f"Invalid type for `index_mapping`: " f"{type(index_mapping)} ({index_mapping})") diff --git a/tests/test_logic_pipeline.py b/tests/test_logic_pipeline.py index c714e47..18cb5f5 100644 --- a/tests/test_logic_pipeline.py +++ b/tests/test_logic_pipeline.py @@ -773,6 +773,51 @@ def test_index_mapping_pipeline(index_mapping, size, mapping_out): assert h5.attrs["pipeline:dcnum mapping"] == mapping_out +@pytest.mark.parametrize("index_mapping,mapping_out", [ + (slice(190, None), "190-n-n"), + (slice(190, 1000), "190-1000-n"), +]) +def test_index_mapping_pipeline_beyond_dataset(index_mapping, mapping_out): + """Open-ended slices are limited to the dataset size internally + + The pipeline identifier contains the mapping specified by the user. + """ + path_orig = retrieve_data("fmt-hdf5_cytoshot_full-features_2023.zip") + path = path_orig.with_name("input.rtdc") + with read.concatenated_hdf5_data(5 * [path_orig], path_out=path): + pass + + results = [] + for im in [index_mapping, slice(190, 200)]: + job = logic.DCNumPipelineJob( + path_in=path, + path_out=path.with_name(f"out_{len(results)}.rtdc"), + data_kwargs={"index_mapping": im}, + background_code="copy", + segmenter_code="thresh", + segmenter_kwargs={"thresh": -6, + "kwargs_mask": {"closing_disk": 0}}, + debug=True) + with logic.DCNumJobRunner(job=job) as runner: + runner.run() + with h5py.File(job["path_out"]) as h5: + results.append({ + "mapping": h5.attrs["pipeline:dcnum mapping"], + "data": h5.attrs["pipeline:dcnum data"], + "basinmap0": h5["events/basinmap0"][:], + "deform": h5["events/deform"][:], + }) + + res, ref = results + assert res["mapping"] == mapping_out + assert res["data"].endswith(f"i={mapping_out}") + assert ref["mapping"] == "190-200-n" + assert len(ref["deform"]) + assert np.all(res["basinmap0"] == ref["basinmap0"]) + assert np.all(res["basinmap0"] >= 190) + assert np.all(res["deform"] == ref["deform"]) + + def test_duplicate_transfer_basin_data(): """task_transfer_basin_data should not copy basin data from input""" path_orig = retrieve_data("fmt-hdf5_cytoshot_full-features_2023.zip") diff --git a/tests/test_meta_ppid_data.py b/tests/test_meta_ppid_data.py index b5916db..0bb2bc2 100644 --- a/tests/test_meta_ppid_data.py +++ b/tests/test_meta_ppid_data.py @@ -43,3 +43,10 @@ def test_ppid_required_method_definitions(): assert hasattr(dat_class, "get_ppid_from_ppkw") assert hasattr(dat_class, "get_ppkw_from_ppid") assert dat_class.get_ppid_code() == dat_code + + +@pytest.mark.parametrize("index_mapping", [-5, slice(-5, None), [3, -1]]) +def test_ppid_encoding_dat_negative_index_mapping(index_mapping): + with pytest.raises(ValueError, match="Negative values"): + HDF5Data.get_ppid_from_ppkw({"pixel_size": 0.34, + "index_mapping": index_mapping}) diff --git a/tests/test_read_hdf5.py b/tests/test_read_hdf5.py index adb5caa..770245b 100644 --- a/tests/test_read_hdf5.py +++ b/tests/test_read_hdf5.py @@ -260,6 +260,12 @@ def test_image_cache_iter_chunks(size, chunks, tmp_path): [slice(1, 11, 3), [1, 4, 7, 10]], [slice(10, 11), [10]], [slice(1, 3, None), [1, 2]], + # open-ended slices and bounds beyond the dataset (dcnum 0.31.3) + [slice(8, None), [8, 9, 10]], + [slice(None, 3), [0, 1, 2]], + [slice(None, None, 4), [0, 4, 8]], + [slice(8, 1000), [8, 9, 10]], + [1000, list(range(11))], ]) def test_index_mapping(index_mapping, result_data): path = retrieve_data( @@ -270,7 +276,33 @@ def test_index_mapping(index_mapping, result_data): h5["events/temp"] = np.arange(size, dtype=np.float64) with read.HDF5Data(path, index_mapping=index_mapping) as hd: + assert len(hd) == len(result_data) assert np.allclose(hd["temp"], result_data) + assert len(hd.image) == len(result_data) + assert np.all(hd.image[-1] == hd.h5["events/image"][result_data[-1]]) + # The pipeline identifier contains the value specified by the user + assert hd.get_ppid().endswith( + "i=" + read.HDF5Data.get_ppid_index_mapping(index_mapping)) + + +@pytest.mark.parametrize("index_mapping,error", [ + [-1, "Negative values"], + [slice(-3, None), "Negative values"], + [slice(0, -1), "Negative values"], + [slice(None, None, -1), "Negative values"], + [[1, -2], "Negative values"], + [np.array([1, -2]), "Negative values"], + [[1, 11], "beyond the dataset size 11"], + [0, "does not select any events"], + [slice(5, 5), "does not select any events"], + [slice(20, 30), "does not select any events"], + [[], "does not select any events"], +]) +def test_index_mapping_invalid(index_mapping, error): + path = retrieve_data( + "fmt-hdf5_cytoshot_full-features_legacy_allev_2023.zip") + with pytest.raises(ValueError, match=error): + read.HDF5Data(path, index_mapping=index_mapping) def test_keyerror_when_image_is_none(tmp_path):