From f1bac7edbd60787e8577182da0fbf4b717f3a58a Mon Sep 17 00:00:00 2001 From: Demian Vladi Date: Tue, 10 Nov 2026 08:32:49 -0800 Subject: [PATCH 1/2] fix(glcm): refuse a ROI whose 2D co-occurrence matrix cannot be held on its own In IBSI mode the matrix has one row and column per grey level up to the ROI's maximum. Above 46340 levels the size check overflowed int and threw, and the reduce workers drop that exception, so the rest of the batch kept unset values and every GLCM column came out 0. A ROI above that limit, or whose matrix cannot be allocated, now gets the noval substitute for itself and a message naming it on stderr. The other ROIs are calculated as usual, in RAM and out of core. Refs PN-235 --- docs/source/Math/f_glcm.rst | 8 ++ docs/source/ibsi_mode.rst | 9 +- src/nyx/features/glcm.cpp | 123 ++++++++++++++++--------- src/nyx/features/glcm.h | 9 ++ tests/python/test_2d_glcm_mechanics.py | 114 +++++++++++++++++++++++ tests/test_2d_glcm_mechanics.h | 46 +++++++++ tests/test_all.cc | 10 ++ tests/vetting/not_covered.md | 7 +- 8 files changed, 275 insertions(+), 51 deletions(-) create mode 100644 tests/python/test_2d_glcm_mechanics.py diff --git a/docs/source/Math/f_glcm.rst b/docs/source/Math/f_glcm.rst index c9fa469e5..e433b56f9 100644 --- a/docs/source/Math/f_glcm.rst +++ b/docs/source/Math/f_glcm.rst @@ -799,6 +799,14 @@ Constant ROI :math:`N`, a ROI of intensities 1000 and 1001 returns 0 in every column, while one of 10 and 11 does not. With a zero or negative ``--coarseGrayDepth`` only a constant ROI does. +ROI with too many grey levels + In IBSI mode the matrix has one row and one column per integer level up to the ROI's maximum. + A ROI whose maximum is above 46340, or whose matrix cannot be allocated, is not calculated: + every GLCM feature of that ROI returns the ``--noval`` substitute (0 from Python) and a message + on standard error names the ROI. The other ROIs of the image are not affected. The same limit + applies to a ``--coarseGrayDepth`` above 46340. A ROI covered by "Constant ROI" above returns + before any matrix is sized, so it gets neither the substitute nor the message. + Grey-level values and indices With PyRadiomics-style binning (negative ``--coarseGrayDepth``) the grey levels are the distinct binned values present in the ROI. Most features use those values, but ``DIS``, ``HOM1``, diff --git a/docs/source/ibsi_mode.rst b/docs/source/ibsi_mode.rst index b9b9ae77a..eb73ddaaa 100644 --- a/docs/source/ibsi_mode.rst +++ b/docs/source/ibsi_mode.rst @@ -115,10 +115,11 @@ Edge cases .. warning:: **Images with large intensities.** Without binning, the 2D GLCM matrix has one row and one - column per grey value up to the ROI's largest intensity. A ROI whose largest value is 50 000 - needs a 50 000 × 50 000 matrix of doubles, about 20 GB. When that allocation fails, Nyxus - prints ``cannot allocate a ... matrix`` and reports 0 for every GLCM feature of the image. On a - 16-bit image whose ROI maxima ran from 19 552 to 65 519, every GLCM value of all 66 ROIs was 0. + column per grey value up to the ROI's largest intensity. A ROI whose largest value is 40 000 + needs a 40 000 × 40 000 matrix of doubles, about 13 GB. A ROI whose largest value is above + 46 340, or whose matrix cannot be allocated, is not calculated: every GLCM feature of that + ROI returns the ``--noval`` substitute (0 from Python), a message on standard error names the + ROI, and the other ROIs of the image are calculated as usual. Rescale such images to a small integer range before using IBSI mode, or leave it off. .. warning:: diff --git a/src/nyx/features/glcm.cpp b/src/nyx/features/glcm.cpp index d6c426406..c9623e526 100644 --- a/src/nyx/features/glcm.cpp +++ b/src/nyx/features/glcm.cpp @@ -1,4 +1,8 @@ +#include +#include #include +#include +#include #include "glcm.h" #include "../helpers/helpers.h" #include "../environment.h" @@ -94,9 +98,66 @@ void GLCMFeature::calculate (LR& r, const Fsettings& s) return; } - // Calculate features for all the directions - for (auto a : angles) - Extract_Texture_Features2 (s, a, r.aux_image_matrix, offset, r.aux_min, r.aux_max); + // Calculate features for all the directions. A ROI whose matrix cannot be held is reported on + // its own, so the caller goes on to the next ROI + try + { + for (auto a : angles) + Extract_Texture_Features2 (s, a, r.aux_image_matrix, offset, r.aux_min, r.aux_max); + } + catch (const std::length_error& e) + { + refuse_roi (r.label, softNAN, e.what()); + } + catch (const std::bad_alloc& e) + { + refuse_roi (r.label, softNAN, e.what()); + } +} + +void GLCMFeature::refuse_roi (int label, double w, const char* reason) +{ + SimpleMatrix().swap (P_matrix); // frees the matrix before anything else is allocated + + clear_result_buffers(); + for (size_t i = 0; i < angles.size(); i++) + push_angle_value (w); + + std::cerr << "Error: ROI " + std::to_string(label) + ": GLCM features not calculated, set to the no-value substitute: " + reason + "\n"; +} + +void GLCMFeature::push_angle_value (double w) +{ + fvals_ASM.push_back(w); + fvals_acor.push_back(w); + fvals_cluprom.push_back(w); + fvals_clushade.push_back(w); + fvals_clutend.push_back(w); + fvals_contrast.push_back(w); + fvals_correlation.push_back(w); + fvals_diff_avg.push_back(w); + fvals_diff_var.push_back(w); + fvals_diff_entropy.push_back(w); + fvals_dis.push_back(w); + fvals_energy.push_back(w); + fvals_entropy.push_back(w); + fvals_homo.push_back(w); + fvals_hom2.push_back(w); + fvals_id.push_back(w); + fvals_idn.push_back(w); + fvals_IDM.push_back(w); + fvals_idmn.push_back(w); + fvals_meas_corr1.push_back(w); + fvals_meas_corr2.push_back(w); + fvals_iv.push_back(w); + fvals_jave.push_back(w); + fvals_je.push_back(w); + fvals_jmax.push_back(w); + fvals_jvar.push_back(w); + fvals_sum_avg.push_back(w); + fvals_sum_var.push_back(w); + fvals_sum_entropy.push_back(w); + fvals_variance.push_back(w); } void GLCMFeature::clear_result_buffers() @@ -259,37 +320,7 @@ void GLCMFeature::Extract_Texture_Features2 (const Fsettings& s, int angle, cons // Blank cooc-matrix? -- no point to use it, assign each feature value '0' and return. if (sum_p == 0) { - double _ = s[(int)NyxSetting::SOFTNAN].rval; - fvals_ASM.push_back(_); - fvals_acor.push_back(_); - fvals_cluprom.push_back(_); - fvals_clushade.push_back(_); - fvals_clutend.push_back(_); - fvals_contrast.push_back(_); - fvals_correlation.push_back(_); - fvals_diff_avg.push_back(_); - fvals_diff_var.push_back(_); - fvals_diff_entropy.push_back(_); - fvals_dis.push_back(_); - fvals_energy.push_back(_); - fvals_entropy.push_back(_); - fvals_homo.push_back(_); - fvals_hom2.push_back(_); - fvals_id.push_back(_); - fvals_idn.push_back(_); - fvals_IDM.push_back(_); - fvals_idmn.push_back(_); - fvals_meas_corr1.push_back(_); - fvals_meas_corr2.push_back(_); - fvals_iv.push_back(_); - fvals_jave.push_back(_); - fvals_je.push_back(_); - fvals_jmax.push_back(_); - fvals_jvar.push_back(_); - fvals_sum_avg.push_back(_); - fvals_sum_var.push_back(_); - fvals_sum_entropy.push_back(_); - fvals_variance.push_back(_); + push_angle_value (s[(int)NyxSetting::SOFTNAN].rval); return; } @@ -340,6 +371,16 @@ void GLCMFeature::Extract_Texture_Features2 (const Fsettings& s, int angle, cons fvals_jvar.push_back (f_GLCM_JVAR(P_matrix, jave)); } +void GLCMFeature::allocate_cooc (SimpleMatrix& GLCM, size_t n_levels) +{ + // SimpleMatrix addresses a cell as W*y+x in an int, which bounds the side of a square matrix + const size_t max_levels = 46340; + if (n_levels > max_levels) + throw std::length_error ("a co-occurrence matrix of " + std::to_string(n_levels) + " grey levels exceeds the limit of " + std::to_string(max_levels)); + + GLCM.allocate ((int)n_levels, (int)n_levels); +} + void GLCMFeature::calculateCoocMatAtAngle( // out SimpleMatrix& GLCM, @@ -392,35 +433,29 @@ void GLCMFeature::calculateCoocMatAtAngle( I.assign(U.begin(), U.end()); std::sort(I.begin(), I.end()); - GLCM.allocate((int)I.size(), (int)I.size()); + allocate_cooc (GLCM, I.size()); } else if (matlab_grey_binning(greyInfo)) { auto n_matlab_levels = greyInfo; + allocate_cooc (GLCM, n_matlab_levels); + I.resize (n_matlab_levels); for (int i=0; i< n_matlab_levels; i++) I[i] = i+1; - - GLCM.allocate (n_matlab_levels, n_matlab_levels); } else { // IBSI auto ibsi_levels_it = std::max_element (D.begin(), D.end()); auto n_ibsi_levels = *ibsi_levels_it; + allocate_cooc (GLCM, n_ibsi_levels); I.resize (n_ibsi_levels); for (int i = 0; i < n_ibsi_levels; i++) I[i] = i + 1; - - GLCM.allocate (n_ibsi_levels, n_ibsi_levels); } - if (GLCM.capacity() < GLCM.width()*GLCM.height()) - { - std::cerr << "Error: cannot allocate a " << GLCM.width() << "x" << GLCM.height() << " matrix \n"; - throw std::runtime_error ("Allocation error in GLCMFeature::calculateCoocMatAtAngle(): requested " + std::to_string(GLCM.width()*GLCM.height()) + " but received " + std::to_string(GLCM.capacity())); - } std::fill (GLCM.begin(), GLCM.end(), 0.0); diff --git a/src/nyx/features/glcm.h b/src/nyx/features/glcm.h index e113e8892..7e4a7988c 100644 --- a/src/nyx/features/glcm.h +++ b/src/nyx/features/glcm.h @@ -228,6 +228,15 @@ class GLCMFeature : public FeatureMethod, public TextureFeature void clear_result_buffers(); + // Appends 'w' to the per-angle buffer of every GLCM feature + void push_angle_value (double w); + + // Replaces the ROI's results with 'w' for every angle and reports the ROI on stderr + void refuse_roi (int label, double w, const char* reason); + + // Sizes a square co-occurrence matrix; throws std::length_error when SimpleMatrix cannot index it + static void allocate_cooc (SimpleMatrix& GLCM, size_t n_levels); + double hx = -1, hy = -1, hxy = -1, hxy1 = -1, hxy2 = -1; // Entropies for f12/f13_icorr calculation void calcH(const SimpleMatrix& P_matrix, std::vector& px, std::vector& py); double f_info_meas_corr1(const SimpleMatrix& P_matrix, double softnan); diff --git a/tests/python/test_2d_glcm_mechanics.py b/tests/python/test_2d_glcm_mechanics.py new file mode 100644 index 000000000..00e53139b --- /dev/null +++ b/tests/python/test_2d_glcm_mechanics.py @@ -0,0 +1,114 @@ +"""IBSI-mode 2D GLCM sizes its matrix by the ROI's maximum grey level. A ROI whose matrix cannot be +held gets the noval substitute for itself and a message naming it; the other ROIs of the image are +computed as if it were not there, in RAM and out of core alike. +""" +import numpy as np +import pytest +import nyxus + +# the Python API has no noval option, so the substitute is the default +NOVAL = 0.0 + +# the largest level count whose matrix SimpleMatrix can index, plus one +FIRST_REFUSED_MAX = 46341 + +COMPUTED_PATCH = np.array([[10, 20, 30, 40], + [40, 10, 20, 30], + [30, 40, 10, 20], + [20, 30, 40, 200]], np.uint32) + + +def _refused_patch(roi_max): + patch = np.full((4, 4), 1, np.uint32) + patch[::2, ::2] = roi_max + patch[1::2, 1::2] = roi_max + return patch + + +def _featurize(inten, label): + nyx = nyxus.Nyxus(["*ALL_GLCM*"], n_feature_calc_threads=1, ibsi=True) + df = nyx.featurize(inten, label, intensity_names=["i"], label_names=["l"]) + return df.sort_values("ROI_label").reset_index(drop=True) + + +def _glcm_values(row): + return row[[c for c in row.index if c.startswith("GLCM_")]].astype(float) + + +def _image(patches): + """Patches side by side on background, labelled 1, 2, ... from the left.""" + inten = np.zeros((6, 6 * len(patches)), np.uint32) + label = np.zeros_like(inten) + for i, patch in enumerate(patches): + inten[1:5, 1 + 6 * i:5 + 6 * i] = patch + label[1:5, 1 + 6 * i:5 + 6 * i] = i + 1 + return inten, label + + +@pytest.mark.parametrize("refused_label", [1, 2]) +@pytest.mark.parametrize("roi_max", [FIRST_REFUSED_MAX, 65535]) +def test_2d_glcm_ibsi_refused_roi_is_isolated_mechanics(roi_max, refused_label, capfd): + patches = [COMPUTED_PATCH, COMPUTED_PATCH] + patches[refused_label - 1] = _refused_patch(roi_max) + computed_label = 3 - refused_label + + df = _featurize(*_image(patches)) + err = capfd.readouterr().err + + solo = _glcm_values(_featurize(*_image([COMPUTED_PATCH])).iloc[0]) + computed = _glcm_values(df[df["ROI_label"] == computed_label].iloc[0]) + assert (solo != NOVAL).any() + assert computed.to_numpy() == pytest.approx(solo.to_numpy(), rel=1e-12, abs=1e-12) + + refused = _glcm_values(df[df["ROI_label"] == refused_label].iloc[0]) + assert (refused == NOVAL).all(), refused[refused != NOVAL].to_dict() + assert f"ROI {refused_label}" in err and "GLCM" in err, err + + +def _tile(patch, side=500): + return np.tile(patch, (side // patch.shape[0], side // patch.shape[1])) + + +@pytest.mark.parametrize("refused_label", [1, 2]) +def test_2d_glcm_ibsi_refused_oversized_roi_is_isolated_mechanics(tmp_path, refused_label, capfd): + tifffile = pytest.importorskip("tifffile") + + # each 500x500 ROI is well above the 1 MB limit, so ram_limit=1 takes the out-of-core path + tiles = [_tile(COMPUTED_PATCH), _tile(COMPUTED_PATCH)] + tiles[refused_label - 1] = _tile(_refused_patch(65535)) + inten = np.hstack(tiles).astype(np.uint16) + label = np.hstack([np.full(t.shape, i + 1, np.uint16) for i, t in enumerate(tiles)]) + + intdir, segdir = tmp_path / "int", tmp_path / "seg" + intdir.mkdir() + segdir.mkdir() + tifffile.imwrite(str(intdir / "img.tif"), inten) + tifffile.imwrite(str(segdir / "img.tif"), label) + + def run(ram_limit): + nyx = nyxus.Nyxus(["*ALL_GLCM*"], n_feature_calc_threads=1, ibsi=True) + nyx.set_params(ram_limit=ram_limit) + df = nyx.featurize_directory(str(intdir) + "/", str(segdir) + "/") + return df.sort_values("ROI_label").reset_index(drop=True) + + in_ram = run(1000) + capfd.readouterr() + ooc = run(1) + err = capfd.readouterr().err + + assert f"ROI {refused_label}" in err and "GLCM" in err, err + computed_label = 3 - refused_label + computed_ooc = _glcm_values(ooc[ooc["ROI_label"] == computed_label].iloc[0]) + computed_ram = _glcm_values(in_ram[in_ram["ROI_label"] == computed_label].iloc[0]) + assert (computed_ram != NOVAL).any() + assert computed_ooc.to_numpy() == pytest.approx(computed_ram.to_numpy(), rel=1e-12, abs=1e-12) + assert (_glcm_values(ooc[ooc["ROI_label"] == refused_label].iloc[0]) == NOVAL).all() + + +def test_2d_glcm_ibsi_8bit_rois_not_refused_mechanics(capfd): + df = _featurize(*_image([COMPUTED_PATCH, _refused_patch(255)])) + assert "GLCM" not in capfd.readouterr().err + + for label in (1, 2): + values = _glcm_values(df[df["ROI_label"] == label].iloc[0]) + assert (values != NOVAL).any() diff --git a/tests/test_2d_glcm_mechanics.h b/tests/test_2d_glcm_mechanics.h index d8dfd9167..1ca306e1f 100644 --- a/tests/test_2d_glcm_mechanics.h +++ b/tests/test_2d_glcm_mechanics.h @@ -69,4 +69,50 @@ inline void test_2d_glcm_own_greydepth_bins_the_matrix_mechanics() any_differs = any_differs || a != both64[(int)fc]; } ASSERT_TRUE (any_differs); +} + +static std::vector> extract_2d_glcm_ibsi (unsigned int top_level, double noval) +{ + std::vector intensity, mask; + make_2d_glcm_dense_phantom (intensity, mask); + for (auto& px : intensity) + if (px.intensity == 8) + px.intensity = top_level; + + Fsettings s = make_2d_glcm_dense_settings(); + s[(int)NyxSetting::SOFTNAN].rval = noval; + + LR roidata; + GLCMFeature::angles = {0, 45, 90, 135}; + Nyxus::load_masked_test_roi_data (roidata, intensity.data(), mask.data(), intensity.size()); + roidata.initialize_fvals(); + GLCMFeature::extract (roidata, s); + return roidata.fvals; +} + +// 46340 levels is the largest square matrix SimpleMatrix can index, so 46341 is refused before anything +// is allocated, and every value of the ROI carries the caller's no-value substitute. +inline void test_2d_glcm_ibsi_refused_roi_gets_noval_mechanics() +{ + const double noval = -7.5; + const auto fvals = extract_2d_glcm_ibsi (46341, noval); + + for (auto fc : GLCMFeature::featureset) + { + SCOPED_TRACE ("2D feature code " + std::to_string ((int)fc)); + const auto& v = fvals[(int)fc]; + ASSERT_FALSE (v.empty()); + for (double x : v) + ASSERT_EQ (x, noval); + } +} + +inline void test_2d_glcm_ibsi_small_roi_not_refused_mechanics() +{ + const double noval = -7.5; + const auto fvals = extract_2d_glcm_ibsi (8, noval); + + for (double x : fvals[(int)Feature2D::GLCM_ASM]) + ASSERT_NE (x, noval); + ASSERT_NE (fvals[(int)Feature2D::GLCM_ASM_AVE][0], noval); } \ No newline at end of file diff --git a/tests/test_all.cc b/tests/test_all.cc index e433c07d1..53b1ea522 100644 --- a/tests/test_all.cc +++ b/tests/test_all.cc @@ -3393,6 +3393,16 @@ TEST(TEST_NYXUS, TEST_2D_GLCM_BUG_OFFSET_DEFAULT_IS_ONE_MECHANICS) ASSERT_NO_THROW(test_2d_glcm_bug_offset_default_is_one_mechanics()); } +TEST(TEST_NYXUS, TEST_2D_GLCM_IBSI_REFUSED_ROI_GETS_NOVAL_MECHANICS) +{ + ASSERT_NO_THROW(test_2d_glcm_ibsi_refused_roi_gets_noval_mechanics()); +} + +TEST(TEST_NYXUS, TEST_2D_GLCM_IBSI_SMALL_ROI_NOT_REFUSED_MECHANICS) +{ + ASSERT_NO_THROW(test_2d_glcm_ibsi_small_roi_not_refused_mechanics()); +} + TEST(TEST_NYXUS, TEST_2D_GLCM_OWN_GREYDEPTH_BINS_THE_MATRIX_MECHANICS) { ASSERT_NO_THROW(test_2d_glcm_own_greydepth_bins_the_matrix_mechanics()); diff --git a/tests/vetting/not_covered.md b/tests/vetting/not_covered.md index 3ba8d4b08..bb7a27a7d 100644 --- a/tests/vetting/not_covered.md +++ b/tests/vetting/not_covered.md @@ -17,12 +17,12 @@ Regenerate by re-deriving both sets; keep this file in step with each reorg wave --- -## A. Test files no registry row references — 31 files, 113 test functions +## A. Test files no registry row references — 34 files, 124 test functions Both totals are the sum of the two tables below, counting each distinct file once and skipping any row struck through as closed, so they can be recomputed from the tables. -### A.1 Correctly absent — plumbing, fixtures and framework self-tests (26 files) +### A.1 Correctly absent — plumbing, fixtures and framework self-tests (27 files) These assert no feature value, so they have no `(feature × config × oracle)` row by construction (SPEC §1). Recording them here so their absence is a documented decision, not an oversight. @@ -32,7 +32,8 @@ These assert no feature value, so they have no `(feature × config × oracle)` r | `test_3d_nifti_mechanics.h` | 2 | NIfTI loader geometry / data access | | `test_arrow_mechanics.h` | 4 | Arrow + Parquet writer plumbing, including an output path that cannot be opened | | `test_arrow_file_name_mechanics.h` | 1 | output-file naming rules | -| `test_2d_glcm_mechanics.h` | 1 | guards the `GLCM_OFFSET` default (a setting, not a value) | +| `test_2d_glcm_mechanics.h` | 4 | guards the `GLCM_OFFSET` default and own grey depth (settings, not values) and the substitute for a ROI whose matrix cannot be held | +| `test_2d_glcm_mechanics.py` | 3 | a ROI whose IBSI matrix cannot be held is refused on its own, in RAM and out of core | | `test_2d_radial_mechanics.h` | 6 | contour frame, centre pixel and normalising radius — the wiring the radial goldens depend on — and the one-pixel, two-pixel and two-fragment ROIs. **Uncredited by decision, not by construction:** see the note below the table | | `test_initialization_mechanics.h` | 1 | environment init | | `test_2d_omezarr_mechanics.h` | 14 | OME-Zarr tile/raw loader, including the load-time intensity map on signed and real-valued stores, and the unsigned accessor on every sample class it cannot convert | From d085aab892e164b1cb1f15caea4b3731d87cc119 Mon Sep 17 00:00:00 2001 From: Demian Vladi Date: Tue, 10 Nov 2026 08:55:39 -0800 Subject: [PATCH 2/2] test(glcm): check every feature of a small IBSI ROI without naming one The mechanics header is a scanned source of the GLCM registry, so asserting on GLCM_ASM_AVE there counted as coverage the registry row does not list, and the registry check failed. The test now walks GLCMFeature::featureset and requires every value of every feature to differ from the substitute. Refs PN-235 --- tests/test_2d_glcm_mechanics.h | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/test_2d_glcm_mechanics.h b/tests/test_2d_glcm_mechanics.h index 1ca306e1f..c025997ea 100644 --- a/tests/test_2d_glcm_mechanics.h +++ b/tests/test_2d_glcm_mechanics.h @@ -112,7 +112,12 @@ inline void test_2d_glcm_ibsi_small_roi_not_refused_mechanics() const double noval = -7.5; const auto fvals = extract_2d_glcm_ibsi (8, noval); - for (double x : fvals[(int)Feature2D::GLCM_ASM]) - ASSERT_NE (x, noval); - ASSERT_NE (fvals[(int)Feature2D::GLCM_ASM_AVE][0], noval); + for (auto fc : GLCMFeature::featureset) + { + SCOPED_TRACE ("2D feature code " + std::to_string ((int)fc)); + const auto& v = fvals[(int)fc]; + ASSERT_FALSE (v.empty()); + for (double x : v) + ASSERT_NE (x, noval); + } } \ No newline at end of file