From 210917db8e751d4057b1cedeb200d915c26d9abc Mon Sep 17 00:00:00 2001 From: Demian Vladi Date: Mon, 16 Nov 2026 16:22:05 -0800 Subject: [PATCH] fix(glszm): grow 2D zones through all eight neighbours A GLSZM zone is 8-connected, as IBSI, PyRadiomics and MIRP define it. The 2D zone walk stepped only east, south-east, south and south-west from a pixel already in the zone, so a zone that turned back west or north was split into several smaller zones and every 2D GLSZM feature moved. On the 5 x 5 example of the PyRadiomics GLSZM documentation it found 13 zones where PyRadiomics finds 11. The walk now steps to all eight neighbours. The out-of-core path calls the same calculate(), and 3D GLSZM was already 26-connected. test_2d_glszm_pyradiomics.h checks all sixteen features against PyRadiomics 3.0.1 on four fixtures: three whose zones turn back west, north or north-east (they fail on the old walk) and a negative one whose same-level pixels touch only across a gap or through a pixel outside the mask, which must stay separate zones. gen_glszm_pyradiomics.py regenerates and re-verifies the pins. Docs: the GLSZM page describes 8-connectivity, drops the split-zone known issue, and its background-as-grey-level-1 example quotes the recomputed values (one of its zones was split as well). Conventions, validation, the 3D GLSZM page and the feature list follow. --- docs/examples/glszm_worked_example.py | 29 +-- docs/feature_descriptions.toml | 2 +- docs/source/Math/f_glszm.rst | 69 +++--- docs/source/Math/f_glszm_3d.rst | 4 +- docs/source/conventions.rst | 3 +- docs/source/featurelist.rst | 2 +- docs/source/validation.rst | 1 - src/nyx/features/glszm.cpp | 60 ++--- tests/test_2d_glszm_pyradiomics.h | 214 ++++++++++++++++++ tests/test_all.cc | 19 ++ .../audit/gldzm_2d_mirp_vetting_report.md | 6 +- tests/vetting/audit/scan_glszm_coverage.py | 3 +- tests/vetting/config_recipes.md | 16 ++ tests/vetting/matrix/glszm.md | 1 + .../vetting/oracles/gen_glszm_pyradiomics.py | 197 ++++++++++++++++ 15 files changed, 519 insertions(+), 107 deletions(-) create mode 100644 tests/test_2d_glszm_pyradiomics.h create mode 100644 tests/vetting/oracles/gen_glszm_pyradiomics.py diff --git a/docs/examples/glszm_worked_example.py b/docs/examples/glszm_worked_example.py index 4a71b5ca0..eac8fb3e4 100644 --- a/docs/examples/glszm_worked_example.py +++ b/docs/examples/glszm_worked_example.py @@ -51,25 +51,20 @@ def glszm(image, roi, **kw): assert math.isclose(got, 341.05, rel_tol=5e-4), f"default GLSZM_GLV = {got}, page says 341.05" -# Zone growth: images whose zones are split by the east/south-east/south/south-west walk -split = np.array([[2, 2, 1], - [1, 1, 1]], dtype=np.uint32) -f = glszm(split, np.ones_like(split), ibsi=True) -quoted = {"ZP": 0.5, "SAE": 0.4537} -for name, expected in quoted.items(): - got = f[f"GLSZM_{name}"][0] - assert math.isclose(got, expected, rel_tol=5e-4), f"2x3 GLSZM_{name} = {got}, page says {expected}" +# Connectivity: the four 1s of the 2 x 3 image are one zone, reached from the top right by stepping west +west = np.array([[2, 2, 1], + [1, 1, 1]], dtype=np.uint32) +f = glszm(west, np.ones_like(west), ibsi=True) +assert math.isclose(f["GLSZM_ZP"][0], 2 / 6), f"2x3 GLSZM_ZP = {f['GLSZM_ZP'][0]}, expected 2 zones over 6 pixels" +# The 5 x 5 example of the PyRadiomics GLSZM documentation: 11 zones over 25 pixels pyrad = np.array([[5, 2, 5, 4, 4], [3, 3, 3, 1, 3], [2, 1, 1, 1, 3], [4, 2, 2, 2, 3], [3, 5, 3, 3, 2]], dtype=np.uint32) f = glszm(pyrad, np.ones_like(pyrad), ibsi=True) -quoted = {"ZP": 0.52, "SAE": 0.6596} -for name, expected in quoted.items(): - got = f[f"GLSZM_{name}"][0] - assert math.isclose(got, expected, rel_tol=5e-4), f"PyRadiomics image GLSZM_{name} = {got}, page says {expected}" +assert math.isclose(f["GLSZM_ZP"][0], 0.44), f"PyRadiomics image GLSZM_ZP = {f['GLSZM_ZP'][0]}, page says 0.44" # Background as grey level 1: a 6x5 ROI whose four corners are outside the mask roi_img = np.array([[3, 3, 7, 7, 7, 2], @@ -83,26 +78,22 @@ def glszm(image, roi, **kw): [1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 0]], dtype=np.uint32) default = glszm(roi_img, roi_mask) -quoted = {"ZP": 0.4, "SAE": 0.4144, "LGLZE": 0.3342} +quoted = {"ZP": 0.3667, "SAE": 0.4261, "LGLZE": 0.3645} for name, expected in quoted.items(): got = default[f"GLSZM_{name}"][0] assert math.isclose(got, expected, rel_tol=5e-4), f"default GLSZM_{name} = {got}, page says {expected}" ibsi = glszm(roi_img, roi_mask, ibsi=True) -assert math.isclose(ibsi["GLSZM_ZP"][0], 8 / 26, rel_tol=5e-4), f"IBSI GLSZM_ZP = {ibsi['GLSZM_ZP'][0]}" +assert math.isclose(ibsi["GLSZM_ZP"][0], 7 / 26, rel_tol=5e-4), f"IBSI GLSZM_ZP = {ibsi['GLSZM_ZP'][0]}" # Constant ROI: every feature is the missing-value substitute (0 by default) const = np.full((4, 4), 7, dtype=np.uint32) f = glszm(const, np.ones_like(const), ibsi=True) assert all(f[f"GLSZM_{c}"][0] == 0 for c in ("SAE", "ZE", "GLV", "ZP")), "constant ROI is not the substitute" -# The 8-connected values for the 2 x 3 image: one zone of 4 pixels and one of 2 -assert math.isclose(2 / 6, 0.3333, rel_tol=5e-4), "8-connected zone percentage" -assert math.isclose((1 / 16 + 1 / 4) / 2, 0.1563, rel_tol=5e-4), "8-connected small area emphasis" - # The 6 x 5 ROI without its corners: IBSI mode on the image binned the default way, corners set to 0 binned = np.minimum(np.floor(64 * roi_img.astype(int) / 9) + 1, 64).astype(np.uint32) * roi_mask f = glszm(binned, roi_mask, ibsi=True) -quoted = {"ZP": 0.3077, "SAE": 0.1215, "LGLZE": 0.001356} +quoted = {"ZP": 0.2692, "SAE": 0.09821, "LGLZE": 0.001379} for name, expected in quoted.items(): got = f[f"GLSZM_{name}"][0] assert math.isclose(got, expected, rel_tol=5e-4), f"corners excluded GLSZM_{name} = {got}, page says {expected}" diff --git a/docs/feature_descriptions.toml b/docs/feature_descriptions.toml index 3f5cce072..023902b56 100644 --- a/docs/feature_descriptions.toml +++ b/docs/feature_descriptions.toml @@ -9,7 +9,7 @@ intensity_histogram = "Available only in IBSI mode (--ibsi=true). All features c neighbors = "Two ROIs are neighbours when their contours come within --pixelDistance pixels of each other (5 by default), measured between contour pixels, not centroids." glcm = "The grey-level co-occurrence matrix counts pairs of ROI pixels one pixel apart, built separately for each angle in --glcmAngles (default 0, 45, 90 and 135 degrees); pairs with a pixel of stored intensity 0 are skipped, which covers every pixel outside the ROI and any ROI pixel whose value is 0. Each plain code is output as one column per angle, named with the angle as a suffix (for example GLCM_ASM_45), and its _AVE code is the mean of those columns. Grey levels come from --coarseGrayDepth binning or are the raw intensities under --ibsi; each ordered pair is counted once with a positive grey depth, and the matrix is made symmetric with a negative or zero grey depth and under --ibsi." glrlm = "A run is a straight line of consecutive pixels with the same grey level; runs are collected separately along 0, 45, 90 and 135 degrees into a grey level by run length matrix. Each plain code is output as one column per angle (suffixes _0, _45, _90 and _135), and its _AVE code is the mean of the four. Grey levels come from --coarseGrayDepth binning, or are the raw intensities under --ibsi. With a positive --coarseGrayDepth (the default), pixels of stored intensity 0, including every bounding-box pixel outside the ROI, are binned to grey level 1 and form runs; under --ibsi or a negative --coarseGrayDepth they are skipped." -glszm = "A zone is a group of connected pixels sharing one grey level, grown from each unvisited pixel in scan order through same-level neighbours to its east, south-east, south and south-west; the matrix counts zones by grey level and size. The family has no directions, so each code is one value per ROI. Grey levels come from --coarseGrayDepth binning, or are the raw intensities under --ibsi. With a positive --coarseGrayDepth (the default), pixels of stored intensity 0, including every bounding-box pixel outside the ROI, are binned to grey level 1 and form zones; under --ibsi or a negative --coarseGrayDepth they are skipped." +glszm = "A zone is an 8-connected group of pixels sharing one grey level, pixels touching by an edge or a corner, as IBSI defines it; the matrix counts zones by grey level and size. The family has no directions, so each code is one value per ROI. Grey levels come from --coarseGrayDepth binning, or are the raw intensities under --ibsi. With a positive --coarseGrayDepth (the default), pixels of stored intensity 0, including every bounding-box pixel outside the ROI, are binned to grey level 1 and form zones; under --ibsi or a negative --coarseGrayDepth they are skipped." gldm = "A pixel's dependence is one plus the number of its 8 neighbours of nonzero stored intensity that have exactly the same grey level, and the matrix counts the ROI pixels of nonzero stored intensity by grey level and dependence. The family has no directions, so each code is one value per ROI. Grey levels come from --coarseGrayDepth binning, or are the raw intensities under --ibsi." gldzm = "A zone is an 8-connected group of pixels sharing one grey level. Its distance is the smallest, over its pixels, of the steps along a row or column to the nearest pixel of stored intensity 0 plus one, or to the bounding-box edge, where a pixel on the bounding-box edge is at distance 1. With a positive --coarseGrayDepth (the default) the pixels outside the ROI are binned to grey level 1 and form zones like ROI pixels, so only the bounding-box edge counts; under --ibsi pixels of stored intensity 0 are skipped. The matrix counts zones by grey level and distance; each code is one value per ROI. Grey levels come from --coarseGrayDepth binning, or are the raw intensities under --ibsi." ngldm = "Every ROI pixel is a neighbourhood centre whose dependence count is one plus the number of its 8 neighbours inside the ROI with the same grey level; the matrix counts centres by grey level and dependence count. Each code is one value per ROI. With a positive --coarseGrayDepth, grey levels come from scaling the range 0 to the ROI maximum by it and truncating (levels 0 to --coarseGrayDepth); 0 and --ibsi keep the raw intensities, and a negative value gives PyRadiomics-style bins over the ROI's range." diff --git a/docs/source/Math/f_glszm.rst b/docs/source/Math/f_glszm.rst index 3cca2508c..95e920ca2 100644 --- a/docs/source/Math/f_glszm.rst +++ b/docs/source/Math/f_glszm.rst @@ -39,14 +39,21 @@ How the matrix is built ----------------------- Nyxus scans the ROI's bounding box row by row, from the top left. Each pixel that is not yet in a -zone and has a non-zero grey level starts a new zone. The zone grows through pixels of the same grey -level, one step at a time, to the east, south-east, south or south-west of a pixel already in the -zone. :math:`\textbf{P}(i,j)` counts the zones of grey level :math:`i` and size :math:`j` pixels. - -- **Connectivity:** the steps cover half of the 8-neighbourhood. A zone whose pixels can all be - reached this way from its first pixel is the 8-connected zone that IBSI defines. A zone that needs - a step to the west, north-west, north or north-east is split into several zones (see - :ref:`glszm-possible-issues`). +zone and has a non-zero grey level starts a new zone. The zone grows through every pixel of the same +grey level that touches a pixel already in it, by an edge or a corner. +:math:`\textbf{P}(i,j)` counts the zones of grey level :math:`i` and size :math:`j` pixels. + +- **Connectivity:** 8-connected, as IBSI, PyRadiomics and MIRP define it. A zone is the full + 8-connected component, whatever the scan order, including one that turns back up or to the left. + In the image below the four pixels of level 1 are one zone, though the zone starts at the top + right and reaches the bottom left only by stepping west: + + .. math:: + + \begin{bmatrix} 2 & 2 & 1\\ 1 & 1 & 1 \end{bmatrix} + + On the 5 × 5 example of the PyRadiomics GLSZM documentation Nyxus finds the same 11 zones as + PyRadiomics, and a zone percentage of 0.44. - **Directions:** none. One matrix is built per ROI, and each feature has one value. - **Grey levels:** intensities are first binned into :math:`N` grey levels, as set by ``--coarseGrayDepth`` (64 by default). A pixel of intensity :math:`x` gets level @@ -75,8 +82,7 @@ Take a 5 × 5 ROI that already has five grey levels: In IBSI mode (no binning) the matrix is below; rows are grey levels 1 to 5 and columns are zone sizes 1 to 6. The six pixels of level 1 in the lower left form one zone; the 3 at the start of row -2 joins the 3 below it to the south-east, a zone of size 2. Every zone of this image is the same -under Nyxus' scan and under full 8-connectivity. +2 joins the 3 below it to the south-east, a zone of size 2. .. math:: @@ -332,8 +338,8 @@ The mean over all zones of one over the squared grey level. High when dark zones \mathrm{LGLZE} = \frac{1}{N_z}\sum_{i=1}^{N_g} \frac{s_i}{g_i^{\,2}} **Possible issues.** With the default binning the background zones have level 1 and weight 1, far -above any binned ROI level. On the ROI in :ref:`glszm-possible-issues` the value is 0.3342 with -them and 0.001356 without them. +above any binned ROI level. On the ROI in :ref:`glszm-possible-issues` the value is 0.3645 with +them and 0.001379 without them. .. _feature-glszm-sae: @@ -351,9 +357,6 @@ fine texture. IBSI calls it *small zone emphasis*. \mathrm{SAE} = \frac{1}{N_z}\sum_{j=1}^{N_s} \frac{s_j}{j^2} -**Possible issues.** A zone split by the scan adds smaller zones and changes the value: 0.4537 -instead of 0.1563 on the 2 × 3 image in :ref:`glszm-possible-issues`. - .. _feature-glszm-sahgle: @@ -478,23 +481,6 @@ The variance of the zone size over all zones. IBSI calls it *zone size variance* Possible issues --------------- -Zones are not fully 8-connected - A zone grows only by steps to the east, south-east, south and south-west. A same-level pixel that - can be reached only by a step to the west, north-west, north or north-east starts a zone of its - own. In the image below, the 1 at the lower left touches the 1 to its right, but the zone starts - at the top-right 1 and never steps west, so Nyxus finds zones of size 3 and 1 where IBSI has one - zone of size 4. - - .. math:: - - \begin{bmatrix} 2 & 2 & 1\\ 1 & 1 & 1 \end{bmatrix} - - Every feature can change. On this image zone percentage is 0.5 instead of 0.3333, and small area - emphasis 0.4537 instead of 0.1563. On the 5 × 5 example of the PyRadiomics GLSZM documentation - Nyxus finds 13 zones instead of 11, zone percentage is 0.52 instead of 0.44 and small area - emphasis 0.6596 instead of 0.5912. Of the 512 ways to fill a 3 × 3 image with two grey levels, - 152 give a different set of zones. IBSI mode does not change the scan. - Background as grey level 1 with the default binning With a positive ``--coarseGrayDepth``, intensity 0 bins to level 1. The bounding-box pixels outside the mask then form zones of level 1, and :math:`N_p` is the size of the bounding box. ROI @@ -510,10 +496,10 @@ Background as grey level 1 with the default binning 6 & 6 & 4 & 9 & 4 & 4\\ \cdot & 6 & 4 & 4 & 4 & \cdot \end{bmatrix} - With the default settings the four corners add four zones of size 1. Nyxus counts 12 zones over - 30 pixels, so zone percentage is 0.4; without the corners the same binning gives 8 zones over 26 - pixels, 0.3077. Small area emphasis is 0.4144 instead of 0.1215, and low grey level zone - emphasis 0.3342 instead of 0.001356. IBSI mode excludes the corners and gives 8 zones over 26 + With the default settings the four corners add four zones of size 1. Nyxus counts 11 zones over + 30 pixels, so zone percentage is 0.3667; without the corners the same binning gives 7 zones over + 26 pixels, 0.2692. Small area emphasis is 0.4261 instead of 0.09821, and low grey level zone + emphasis 0.3645 instead of 0.001379. IBSI mode excludes the corners and gives 7 zones over 26 pixels. Pixels of intensity 0 inside the mask @@ -539,9 +525,14 @@ phantom in IBSI mode. Fifteen features agree to an absolute 10\ :sup:`-9`; zone relative 4 × 10\ :sup:`-3`, which allows for the approximate logarithm. The four-slice means are also compared with IBSI's published consensus values at a relative 10\ :sup:`-2`, the precision those values are published to; that comparison is a consistency check, not one of the validations -in the index. The phantom's zones are the same under Nyxus' scan and under -8-connectivity, so these comparisons do not cover the split zones described above. The default -mode is covered by regression tests only. +in the index. + +The phantom has no zone that turns back up or to the left, so the zone connectivity is checked +against PyRadiomics on four more images in IBSI mode: the 2 × 3 image above, the 5 × 5 example of +the PyRadiomics documentation, a zone that turns north-east and climbs north, and an image whose +same-level pixels touch only across a gap or through a pixel outside the mask, which must stay +separate zones. Fifteen features agree to an absolute 10\ :sup:`-9` and zone entropy to a relative +4 × 10\ :sup:`-3`. The default mode is covered by regression tests only. References diff --git a/docs/source/Math/f_glszm_3d.rst b/docs/source/Math/f_glszm_3d.rst index 33a69982f..a1af607df 100644 --- a/docs/source/Math/f_glszm_3d.rst +++ b/docs/source/Math/f_glszm_3d.rst @@ -44,8 +44,8 @@ grey level that touches a voxel already in it, by a face, an edge or a corner. :math:`\textbf{P}(i,j)` counts the zones of grey level :math:`i` and size :math:`j` voxels. - **Connectivity:** 26-connected. All 26 neighbours of a voxel are searched: 8 in its own slice and - 9 in each adjacent slice. A zone is the full 26-connected component, whatever the scan order. This - differs from the 2D family, whose zones grow only to the east, south-east, south and south-west. + 9 in each adjacent slice. A zone is the full 26-connected component, whatever the scan order, the + 3D counterpart of the 2D family's 8-connected zones. - **Directions:** none. One matrix is built per ROI, and each feature has one value. - **Grey levels:** set by ``--coarseGrayDepth`` (``coarse_gray_depth``, 64 by default), or by the ``3glszm/greydepth`` metaparameter, which overrides it for this family. diff --git a/docs/source/conventions.rst b/docs/source/conventions.rst index 0bec0e65b..1371e9514 100644 --- a/docs/source/conventions.rst +++ b/docs/source/conventions.rst @@ -245,8 +245,7 @@ they differ in these ways: - ``3GLCM_*`` and ``3GLRLM_*`` are one column: the direction :math:`(1,1,1)` only. ``_AVE`` averages the 13 directions. * - Zones - - GLSZM zones grow only east, south-east, south and south-west, so some 8-connected zones - split (see :ref:`glszm-possible-issues`). GLDZM zones are 8-connected. + - GLSZM and GLDZM zones are 8-connected. - GLSZM and GLDZM zones are 26-connected. * - GLDZM distance - A walk along the pixel's row and column to the first pixel of grey level 0 or the box diff --git a/docs/source/featurelist.rst b/docs/source/featurelist.rst index b6ee652d5..b335a234e 100644 --- a/docs/source/featurelist.rst +++ b/docs/source/featurelist.rst @@ -1181,7 +1181,7 @@ Definitions, formulas and settings: :doc:`/Math/f_glrlm`. Grey-level size-zone matrix (GLSZM) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -A zone is a group of connected pixels sharing one grey level, grown from each unvisited pixel in scan order through same-level neighbours to its east, south-east, south and south-west; the matrix counts zones by grey level and size. The family has no directions, so each code is one value per ROI. Grey levels come from ``--coarseGrayDepth`` binning, or are the raw intensities under ``--ibsi``. With a positive ``--coarseGrayDepth`` (the default), pixels of stored intensity 0, including every bounding-box pixel outside the ROI, are binned to grey level 1 and form zones; under ``--ibsi`` or a negative ``--coarseGrayDepth`` they are skipped. +A zone is an 8-connected group of pixels sharing one grey level, pixels touching by an edge or a corner, as IBSI defines it; the matrix counts zones by grey level and size. The family has no directions, so each code is one value per ROI. Grey levels come from ``--coarseGrayDepth`` binning, or are the raw intensities under ``--ibsi``. With a positive ``--coarseGrayDepth`` (the default), pixels of stored intensity 0, including every bounding-box pixel outside the ROI, are binned to grey level 1 and form zones; under ``--ibsi`` or a negative ``--coarseGrayDepth`` they are skipped. Definitions, formulas and settings: :doc:`/Math/f_glszm`. diff --git a/docs/source/validation.rst b/docs/source/validation.rst index 38753a397..ac59b1bba 100644 --- a/docs/source/validation.rst +++ b/docs/source/validation.rst @@ -139,7 +139,6 @@ ones are: * Background pixels: with the default binning some families count background as grey level 1. See :ref:`glrlm-possible-issues`, :ref:`glszm-possible-issues`, :ref:`gldzm-possible-issues` and :ref:`ngtdm-possible-issues`. -* GLSZM: 2D zones are not fully 8-connected. See :ref:`glszm-possible-issues`. * GLDZM: the distance next to background is one too large. See :ref:`gldzm-possible-issues`. * NGLDM: grey levels are converted differently from the other texture families. See :ref:`ngldm-possible-issues`. diff --git a/src/nyx/features/glszm.cpp b/src/nyx/features/glszm.cpp index 0848faa17..6371558eb 100644 --- a/src/nyx/features/glszm.cpp +++ b/src/nyx/features/glszm.cpp @@ -121,49 +121,33 @@ void GLSZMFeature::calculate (LR& r, const Fsettings& s) int zoneArea = 1; D.yx(y, x) = VISITED; + // A zone is 8-connected, the connectivity IBSI defines for GLSZM and the one PyRadiomics and + // MIRP implement: the walk steps to all eight neighbours, so a zone that turns back up or + // to the left stays one zone. + static const int dxs[] = { 1, 1, 0, -1, -1, -1, 0, 1 }, + dys[] = { 0, 1, 1, 1, 0, -1, -1, -1 }; for (;;) { - if (D.safe(y, x + 1) && D.yx(y, x + 1) != VISITED && D.yx(y, x + 1) == pi) + bool advanced = false; + for (int k = 0; k < 8; k++) { - D.yx(y, x + 1) = VISITED; - zoneArea++; - - // Remember this pixel - history.push_back({ x,y }); - // Advance - x = x + 1; - // Proceed - continue; - } - if (D.safe(y + 1, x + 1) && D.yx(y + 1, x + 1) != VISITED && D.yx(y + 1, x + 1) == pi) - { - D.yx(y + 1, x + 1) = VISITED; - zoneArea++; - - history.push_back({ x,y }); - x = x + 1; - y = y + 1; - continue; - } - if (D.safe(y + 1, x) && D.yx(y + 1, x) != VISITED && D.yx(y + 1, x) == pi) - { - D.yx(y + 1, x) = VISITED; - zoneArea++; - - history.push_back({ x,y }); - y = y + 1; - continue; + int nx = x + dxs[k], + ny = y + dys[k]; + if (D.safe(ny, nx) && D.yx(ny, nx) != VISITED && D.yx(ny, nx) == pi) + { + D.yx(ny, nx) = VISITED; + zoneArea++; + + // Remember this pixel and advance to the neighbour + history.push_back({ x,y }); + x = nx; + y = ny; + advanced = true; + break; + } } - if (D.safe(y + 1, x - 1) && D.yx(y + 1, x - 1) != VISITED && D.yx(y + 1, x - 1) == pi) - { - D.yx(y + 1, x - 1) = VISITED; - zoneArea++; - - history.push_back({ x,y }); - x = x - 1; - y = y + 1; + if (advanced) continue; - } // Return from the branch if (history.size() > 0) diff --git a/tests/test_2d_glszm_pyradiomics.h b/tests/test_2d_glszm_pyradiomics.h new file mode 100644 index 000000000..2603d562c --- /dev/null +++ b/tests/test_2d_glszm_pyradiomics.h @@ -0,0 +1,214 @@ +#pragma once + +#include "test_2d_glszm_common.h" // gtest, , , GLSZMFeature, the settings recipe and the ROI loader +#include "test_ref_vals.h" // ref_vals_map + +// PyRadiomics goldens for the 2D GLSZM zone connectivity (SPEC 6.4 provenance). +// tool=pyradiomics 3.0.1 (SimpleITK 2.3.1); env=nyxus_oracle (conda); +// recipe=glszm.pyradiomics_connectivity_2d, i.e. each fixture below read as one 2D ROI at binWidth=1 +// with force2D=True. Every fixture's smallest ROI intensity is 1, so PyRadiomics' grey levels are the +// intensities themselves, which is what Nyxus computes in IBSI mode; +// generator=tests/vetting/oracles/gen_glszm_pyradiomics.py, which also re-verifies every table here. +// +// A GLSZM zone is an 8-connected set of same-level pixels. The first three fixtures hold zones whose +// pixels can be reached from the zone's first pixel in raster order only through a step to the west, +// north or north-east, so a walk that steps only east, south-east, south and south-west splits them +// into more, smaller zones and every feature moves. The fourth is the negative case: same-level pixels +// that touch only across a gap or through a pixel outside the mask, which must stay separate zones. +// +// Fifteen features assert at SPEC 7's exact tier, an ABSOLUTE 1e-9 band. GLSZM_ZE goes through +// Nyxus::fast_log10 where PyRadiomics takes a double log2, and asserts at the same rel=4e-3 band +// test_2d_glszm_mirp.h gives it for the same reason. + +struct Glszm2dFixture +{ + std::vector> intensity; + std::vector> mask; // empty: every pixel is in the ROI +}; + +// glszm_2d_docs_2x3 -- the image of the GLSZM page. The level-1 zone starts at the top-right pixel and +// needs two steps west to reach the bottom-left one: one zone of 4 and one of 2, not 3 + 1 + 2. +static const Glszm2dFixture glszm_2d_docs_2x3 +{ + {{2, 2, 1}, + {1, 1, 1}}, + {} +}; +static const ref_vals_map glszm_2d_pyradiomics_docs_2x3_ref_vals +{ + {"GLSZM_SAE", 0.15625}, + {"GLSZM_LAE", 10.0}, + {"GLSZM_GLN", 1.0}, + {"GLSZM_GLNN", 0.5}, + {"GLSZM_SZN", 1.0}, + {"GLSZM_SZNN", 0.5}, + {"GLSZM_ZP", 0.3333333333333333}, + {"GLSZM_GLV", 0.25}, + {"GLSZM_ZV", 1.0}, + {"GLSZM_ZE", 0.9999999999999993}, + {"GLSZM_LGLZE", 0.625}, + {"GLSZM_HGLZE", 2.5}, + {"GLSZM_SALGLE", 0.0625}, + {"GLSZM_SAHGLE", 0.53125}, + {"GLSZM_LALGLE", 8.5}, + {"GLSZM_LAHGLE", 16.0} +}; + +// glszm_2d_pyrad_5x5 -- the example of the PyRadiomics GLSZM documentation: 11 zones, where an +// east/south-east/south/south-west walk finds 13. +static const Glszm2dFixture glszm_2d_pyrad_5x5 +{ + {{5, 2, 5, 4, 4}, + {3, 3, 3, 1, 3}, + {2, 1, 1, 1, 3}, + {4, 2, 2, 2, 3}, + {3, 5, 3, 3, 2}}, + {} +}; +static const ref_vals_map glszm_2d_pyradiomics_pyrad_5x5_ref_vals +{ + {"GLSZM_SAE", 0.5912373737373737}, + {"GLSZM_LAE", 7.7272727272727275}, + {"GLSZM_GLN", 2.4545454545454546}, + {"GLSZM_GLNN", 0.2231404958677686}, + {"GLSZM_SZN", 3.909090909090909}, + {"GLSZM_SZNN", 0.35537190082644626}, + {"GLSZM_ZP", 0.44}, + {"GLSZM_GLV", 1.6859504132231407}, + {"GLSZM_ZV", 2.56198347107438}, + {"GLSZM_ZE", 3.0271691184406153}, + {"GLSZM_LGLZE", 0.18893939393939393}, + {"GLSZM_HGLZE", 13.0}, + {"GLSZM_SALGLE", 0.05895693041526375}, + {"GLSZM_SAHGLE", 9.962045454545454}, + {"GLSZM_LALGLE", 2.438308080808081}, + {"GLSZM_LAHGLE", 53.63636363636363} +}; + +// glszm_2d_hook_6x6 -- the outer level-1 zone runs down the left edge and along the bottom row, then +// turns north-east into the right edge and climbs it. 5 zones, where the forward walk finds 6. +static const Glszm2dFixture glszm_2d_hook_6x6 +{ + {{1, 2, 2, 2, 2, 1}, + {1, 2, 1, 1, 2, 1}, + {1, 2, 1, 3, 2, 1}, + {1, 2, 3, 3, 2, 1}, + {1, 2, 2, 2, 2, 1}, + {1, 1, 1, 1, 1, 3}}, + {} +}; +static const ref_vals_map glszm_2d_pyradiomics_hook_6x6_ref_vals +{ + {"GLSZM_SAE", 0.24635374149659867}, + {"GLSZM_LAE", 88.0}, + {"GLSZM_GLN", 1.8}, + {"GLSZM_GLNN", 0.36}, + {"GLSZM_SZN", 1.4}, + {"GLSZM_SZNN", 0.28}, + {"GLSZM_ZP", 0.1388888888888889}, + {"GLSZM_GLV", 0.8}, + {"GLSZM_ZV", 36.160000000000004}, + {"GLSZM_ZE", 2.321928094887361}, + {"GLSZM_LGLZE", 0.49444444444444446}, + {"GLSZM_HGLZE", 4.8}, + {"GLSZM_SALGLE", 0.048057571176618796}, + {"GLSZM_SAHGLE", 2.0271927437641724}, + {"GLSZM_LALGLE", 56.822222222222216}, + {"GLSZM_LAHGLE", 221.6} +}; + +// glszm_2d_apart_3x7 -- the negative case. The four level-1 corners of the left 3 x 3 block are two +// steps apart and stay four zones. The right 3 x 3 block is all 4, but its middle column is outside +// the mask, so the two level-4 columns stay two zones. 8 zones over 18 pixels: a walk that reached +// further than the 8-neighbourhood, or through pixels outside the ROI, would find fewer. +static const Glszm2dFixture glszm_2d_apart_3x7 +{ + {{1, 3, 1, 2, 4, 4, 4}, + {3, 3, 3, 2, 4, 4, 4}, + {1, 3, 1, 2, 4, 4, 4}}, + {{1, 1, 1, 1, 1, 0, 1}, + {1, 1, 1, 1, 1, 0, 1}, + {1, 1, 1, 1, 1, 0, 1}} +}; +static const ref_vals_map glszm_2d_pyradiomics_apart_3x7_ref_vals +{ + {"GLSZM_SAE", 0.5466666666666666}, + {"GLSZM_LAE", 7.0}, + {"GLSZM_GLN", 2.75}, + {"GLSZM_GLNN", 0.34375}, + {"GLSZM_SZN", 3.25}, + {"GLSZM_SZNN", 0.40625}, + {"GLSZM_ZP", 0.4444444444444444}, + {"GLSZM_GLV", 1.609375}, + {"GLSZM_ZV", 1.9375}, + {"GLSZM_ZE", 1.7499999999999987}, + {"GLSZM_LGLZE", 0.5607638888888888}, + {"GLSZM_HGLZE", 6.125}, + {"GLSZM_SALGLE", 0.5057638888888889}, + {"GLSZM_SAHGLE", 1.045}, + {"GLSZM_LALGLE", 1.2690972222222223}, + {"GLSZM_LAHGLE", 69.125} +}; + +static const double glszm_2d_pyradiomics_abs_tolerance = 1e-9; +static const double glszm_2d_pyradiomics_ze_frac_tolerance = 250.; + +/// @brief Featurises a fixture in IBSI mode and checks all sixteen features against PyRadiomics +static void assert_glszm_2d_pyradiomics (const Glszm2dFixture& fx, const ref_vals_map& gt) +{ + std::vector intensity, mask; + for (size_t y = 0; y < fx.intensity.size(); y++) + for (size_t x = 0; x < fx.intensity[y].size(); x++) + { + intensity.push_back ({ x, y, fx.intensity[y][x] }); + mask.push_back ({ x, y, fx.mask.empty() ? 1u : fx.mask[y][x] }); + } + + LR roidata; + Nyxus::load_masked_test_roi_data (roidata, intensity.data(), mask.data(), intensity.size()); + + GLSZMFeature f; + f.calculate (roidata, make_glszm2d_settings (true/*ibsi*/, 0)); + roidata.initialize_fvals(); + f.save_value (roidata.fvals); + + const std::pair features[] = + { + {Feature2D::GLSZM_SAE, "GLSZM_SAE"}, {Feature2D::GLSZM_LAE, "GLSZM_LAE"}, + {Feature2D::GLSZM_GLN, "GLSZM_GLN"}, {Feature2D::GLSZM_GLNN, "GLSZM_GLNN"}, + {Feature2D::GLSZM_SZN, "GLSZM_SZN"}, {Feature2D::GLSZM_SZNN, "GLSZM_SZNN"}, + {Feature2D::GLSZM_ZP, "GLSZM_ZP"}, {Feature2D::GLSZM_GLV, "GLSZM_GLV"}, + {Feature2D::GLSZM_ZV, "GLSZM_ZV"}, {Feature2D::GLSZM_ZE, "GLSZM_ZE"}, + {Feature2D::GLSZM_LGLZE, "GLSZM_LGLZE"}, {Feature2D::GLSZM_HGLZE, "GLSZM_HGLZE"}, + {Feature2D::GLSZM_SALGLE, "GLSZM_SALGLE"}, {Feature2D::GLSZM_SAHGLE, "GLSZM_SAHGLE"}, + {Feature2D::GLSZM_LALGLE, "GLSZM_LALGLE"}, {Feature2D::GLSZM_LAHGLE, "GLSZM_LAHGLE"} + }; + for (const auto& [id, name] : features) + { + const double got = roidata.fvals[(int)id][0]; + if (std::string(name) == "GLSZM_ZE") + ASSERT_TRUE (agrees_gt (got, gt.at(name), glszm_2d_pyradiomics_ze_frac_tolerance)) << name << " = " << got; + else + ASSERT_NEAR (got, gt.at(name), glszm_2d_pyradiomics_abs_tolerance) << name; + } +} + +void test_2d_glszm_docs_2x3_pyradiomics() +{ + assert_glszm_2d_pyradiomics (glszm_2d_docs_2x3, glszm_2d_pyradiomics_docs_2x3_ref_vals); +} + +void test_2d_glszm_pyrad_5x5_pyradiomics() +{ + assert_glszm_2d_pyradiomics (glszm_2d_pyrad_5x5, glszm_2d_pyradiomics_pyrad_5x5_ref_vals); +} + +void test_2d_glszm_hook_6x6_pyradiomics() +{ + assert_glszm_2d_pyradiomics (glszm_2d_hook_6x6, glszm_2d_pyradiomics_hook_6x6_ref_vals); +} + +void test_2d_glszm_apart_3x7_pyradiomics() +{ + assert_glszm_2d_pyradiomics (glszm_2d_apart_3x7, glszm_2d_pyradiomics_apart_3x7_ref_vals); +} diff --git a/tests/test_all.cc b/tests/test_all.cc index e433c07d1..b67a6d2bf 100644 --- a/tests/test_all.cc +++ b/tests/test_all.cc @@ -78,6 +78,7 @@ #include "test_2d_glszm_ibsi.h" #include "test_2d_glszm_mirp.h" #include "test_2d_glszm_analytic.h" +#include "test_2d_glszm_pyradiomics.h" #include "test_2d_firstorder_ibsi.h" #include "test_2d_firstorder_pyradiomics.h" #include "test_2d_ngldm_ibsi.h" @@ -3864,6 +3865,24 @@ TEST(TEST_NYXUS, TEST_2D_GLSZM_ZE_MIRP) { ASSERT_NO_THROW(test_2d_glszm_ze_mirp()); } +//***** 2D GLSZM zone connectivity vs PyRadiomics ***** + +TEST(TEST_NYXUS, TEST_2D_GLSZM_DOCS_2X3_PYRADIOMICS) { + ASSERT_NO_THROW(test_2d_glszm_docs_2x3_pyradiomics()); +} + +TEST(TEST_NYXUS, TEST_2D_GLSZM_PYRAD_5X5_PYRADIOMICS) { + ASSERT_NO_THROW(test_2d_glszm_pyrad_5x5_pyradiomics()); +} + +TEST(TEST_NYXUS, TEST_2D_GLSZM_HOOK_6X6_PYRADIOMICS) { + ASSERT_NO_THROW(test_2d_glszm_hook_6x6_pyradiomics()); +} + +TEST(TEST_NYXUS, TEST_2D_GLSZM_APART_3X7_PYRADIOMICS) { + ASSERT_NO_THROW(test_2d_glszm_apart_3x7_pyradiomics()); +} + //***** IBSI tests of NGLDM ***** TEST(TEST_NYXUS, TEST_2D_NGLDM_MATRIX_CORRECTNESS_IBSI) diff --git a/tests/vetting/audit/gldzm_2d_mirp_vetting_report.md b/tests/vetting/audit/gldzm_2d_mirp_vetting_report.md index 6041ede1e..fa1678c9d 100644 --- a/tests/vetting/audit/gldzm_2d_mirp_vetting_report.md +++ b/tests/vetting/audit/gldzm_2d_mirp_vetting_report.md @@ -77,9 +77,9 @@ table is therefore doing work no averaged assertion in this family can do. `GLDZMFeature::calculate` grew a zone by testing four neighbours — East, South, West, North. A GLDZM zone is 8-connected: two same-level pixels touching only at a corner are one zone. That is the -connectivity IBSI defines, the one mirp implements, and the one **Nyxus' own GLSZM already used** -(`glszm.cpp` tests E/SE/S/SW, the forward half of the 8-neighbourhood). The two families disagreed -with each other inside the same codebase about what a zone is. +connectivity IBSI defines, the one mirp implements, and the one **Nyxus' own GLSZM uses** +(`glszm.cpp` walks all eight neighbours). The two families disagreed with each other inside the same +codebase about what a zone is. On phantom slice z1 the difference is two diagonal links, which split five true zones into seven: diff --git a/tests/vetting/audit/scan_glszm_coverage.py b/tests/vetting/audit/scan_glszm_coverage.py index b56439126..8e7a7624d 100644 --- a/tests/vetting/audit/scan_glszm_coverage.py +++ b/tests/vetting/audit/scan_glszm_coverage.py @@ -15,6 +15,7 @@ "test_2d_glszm_analytic.h", "test_2d_glszm_ibsi.h", "test_2d_glszm_mirp.h", + "test_2d_glszm_pyradiomics.h", "test_2d_glszm_regression.h", ] @@ -35,7 +36,7 @@ FAMILY = scanlib.Family( dim="2D", family="glszm", sources=SOURCES, - oracle_suffix={"mirp": "mirp", "ibsi": "ibsi", "analytic": "analytic"}, + oracle_suffix={"mirp": "mirp", "ibsi": "ibsi", "analytic": "analytic", "pyradiomics": "pyradiomics"}, notes=scanlib.dual_oracle_notes(NOTE, DUAL_ORACLE), ) diff --git a/tests/vetting/config_recipes.md b/tests/vetting/config_recipes.md index 8c582b8b1..75ae6b5ce 100644 --- a/tests/vetting/config_recipes.md +++ b/tests/vetting/config_recipes.md @@ -554,6 +554,22 @@ oracle for the Nyxus-original features); it is not built in this tree, and the g - The band is `rel=1e-12` rather than SPEC 7's absolute exact tier, because `LAE` is 4.3e9 and an absolute 1e-9 is below its last bit. +## glszm.pyradiomics_connectivity_2d +- Four small literal ROIs in `test_2d_glszm_pyradiomics.h`, each featurised with `IBSI=true` and + `GREYDEPTH=0`. Oracle: `pyradiomics` 3.0.1 at `binWidth=1`, `force2D=True`; every fixture's + smallest ROI intensity is 1, so PyRadiomics' grey levels are the intensities. Generator: + `oracles/gen_glszm_pyradiomics.py`, which re-verifies every pin in the header. Config matrix: + `matrix/glszm.md`. +- **What it is for.** The IBSI phantom has no zone that turns back up or to the left, so it cannot + tell 8-connectivity from a walk that steps only east, south-east, south and south-west. Three + fixtures can: `glszm_2d_docs_2x3` (a zone reached by stepping west), `glszm_2d_pyrad_5x5` (the + PyRadiomics documentation example, 11 zones) and `glszm_2d_hook_6x6` (a zone that turns north-east + and climbs north). The generator fails unless each has fewer 8-connected zones than forward-walk + zones. `glszm_2d_apart_3x7` is the negative case: same-level pixels two steps apart, and two + level-4 columns joined only through a column outside the mask, must stay separate zones. +- Fifteen features at SPEC 7's exact tier (absolute 1e-9), `GLSZM_ZE` at `rel=4e-3` for + `Nyxus::fast_log10`, as in `glszm.ibsi_phantom_2d`. + ## glrlm.ibsi_ng128 - The four IBSI digital-phantom slices (`ibsi_phantom_z1..z4`, `test_data.h`), each featurised on its own with `IBSI=true` and `GREYDEPTH=128`, the four in-slice directions averaged, then the four diff --git a/tests/vetting/matrix/glszm.md b/tests/vetting/matrix/glszm.md index 94ad897f0..f6e02dbdb 100644 --- a/tests/vetting/matrix/glszm.md +++ b/tests/vetting/matrix/glszm.md @@ -20,6 +20,7 @@ configure once the discretisation is fixed. |---|---|---|---|---| | True | none (identity on an already-discrete fixture) | phantom's own 1..6 | VALID, 15 features | `glszm.ibsi_phantom_2d` — mirp + ibsi, at SPEC §7's exact tier | | True | none | phantom's own 1..6 | VALID, 1 feature at a wider band | `GLSZM_ZE` — same oracles, `rel=4e-3`, the `fast_log10` residual | +| True | none | four literal ROIs, levels 1..5 | VALID, all 16 (ZE at `rel=4e-3`) | `glszm.pyradiomics_connectivity_2d` — PyRadiomics on zones that turn back west, north or north-east, plus a negative fixture, `test_2d_glszm_pyradiomics.h` | | True | none | 1 and 2, zones of 65,536 | VALID, 2 features | `GLSZM_SAE`, `GLSZM_LAE` on zones whose squared size, 2^32, wraps to 0 in 32 bits — analytic, `rel=1e-12`, `test_2d_glszm_analytic.h` | | False | MATLAB (`GREYDEPTH > 0`) | 64 | VALID-prod-only, all 16 | no oracle reproduces it → `test_2d_glszm_regression.h` | | False | radiomics (`GREYDEPTH < 0`) | any | NOT MEASURED | see below | diff --git a/tests/vetting/oracles/gen_glszm_pyradiomics.py b/tests/vetting/oracles/gen_glszm_pyradiomics.py new file mode 100644 index 000000000..7a2b0921c --- /dev/null +++ b/tests/vetting/oracles/gen_glszm_pyradiomics.py @@ -0,0 +1,197 @@ +"""OFFLINE PyRadiomics oracle for the 2D GLSZM features on four small zone-connectivity fixtures. + + python tests/vetting/oracles/gen_glszm_pyradiomics.py (from the repository root) + +Prints the paste-ready goldens AND re-verifies every golden pinned in test_2d_glszm_pyradiomics.h, +exiting non-zero on any mismatch, on a fixture the header and this script disagree about, or on a +feature in scope that the header does not pin. + +RECIPE `glszm.pyradiomics_connectivity_2d`: each fixture is one 2D ROI read at binWidth=1 with +force2D=True, no resampling. Every fixture's smallest ROI intensity is 1, so PyRadiomics' bin of an +intensity x is floor(x) - floor(1) + 1 = x and its grey levels are the intensities themselves. That is +what Nyxus computes in IBSI mode, where the intensities are not binned. A pixel whose mask is 0 is +outside the ROI on both sides. + +WHAT THE FIXTURES ARE FOR. A GLSZM zone is an 8-connected set of same-level pixels. Three fixtures +hold zones that can be reached from their first pixel in raster order only by stepping west, north +or north-east, so a walk that steps only east, south-east, south and south-west splits +them; `forward_zone_count()` below counts that split, and the script fails unless each of the three +fixtures has fewer 8-connected zones than forward-walk zones. The fourth fixture is the negative +case: same-level pixels two steps apart, and two same-level columns joined only through a pixel +outside the mask, which must stay separate zones under any correct connectivity. + + glszm_2d_docs_2x3 the 2 x 3 image of the Nyxus GLSZM page; the bottom row needs a west step + glszm_2d_pyrad_5x5 the 5 x 5 example of the PyRadiomics GLSZM documentation (11 zones) + glszm_2d_hook_6x6 a zone that turns north-east and climbs north + glszm_2d_apart_3x7 the negative case: zones that touch only through a gap or a masked pixel + +Each fixture's own 8-connected zone count is checked against `zone_count_8()` (scipy-free flood +fill), so PyRadiomics, the flood fill and the header agree on the zones before any feature is read. + +Provenance: tool=pyradiomics 3.0.1 (SimpleITK 2.3.1, Python 3.8); env=nyxus_oracle (conda, needs +Python <= 3.9); generator=tests/vetting/oracles/gen_glszm_pyradiomics.py. Run offline; CI never +invokes it. +""" +import math +import os +import re +import sys + +import numpy +import SimpleITK as sitk +import radiomics +from radiomics import featureextractor + +HERE = os.path.dirname(os.path.abspath(__file__)) +TESTS = os.path.dirname(os.path.dirname(HERE)) +TEST_H = os.path.join(TESTS, "test_2d_glszm_pyradiomics.h") + +RELTOL = 1e-12 # the pins are PyRadiomics' own output at repr() precision +SCOPE_LOG = ("GLSZM_ZE",) # carries Nyxus' fast_log10 approximation; pinned, asserted in its own band + +PYRAD = { + "GLSZM_SAE": "SmallAreaEmphasis", + "GLSZM_LAE": "LargeAreaEmphasis", + "GLSZM_GLN": "GrayLevelNonUniformity", + "GLSZM_GLNN": "GrayLevelNonUniformityNormalized", + "GLSZM_SZN": "SizeZoneNonUniformity", + "GLSZM_SZNN": "SizeZoneNonUniformityNormalized", + "GLSZM_ZP": "ZonePercentage", + "GLSZM_GLV": "GrayLevelVariance", + "GLSZM_ZV": "ZoneVariance", + "GLSZM_ZE": "ZoneEntropy", + "GLSZM_LGLZE": "LowGrayLevelZoneEmphasis", + "GLSZM_HGLZE": "HighGrayLevelZoneEmphasis", + "GLSZM_SALGLE": "SmallAreaLowGrayLevelEmphasis", + "GLSZM_SAHGLE": "SmallAreaHighGrayLevelEmphasis", + "GLSZM_LALGLE": "LargeAreaLowGrayLevelEmphasis", + "GLSZM_LAHGLE": "LargeAreaHighGrayLevelEmphasis", +} + +# name -> (intensity rows, mask rows or None for an all-ones mask). Must match the header byte for byte. +FIXTURES = { + "glszm_2d_docs_2x3": ( + [[2, 2, 1], + [1, 1, 1]], None), + "glszm_2d_pyrad_5x5": ( + [[5, 2, 5, 4, 4], + [3, 3, 3, 1, 3], + [2, 1, 1, 1, 3], + [4, 2, 2, 2, 3], + [3, 5, 3, 3, 2]], None), + "glszm_2d_hook_6x6": ( + [[1, 2, 2, 2, 2, 1], + [1, 2, 1, 1, 2, 1], + [1, 2, 1, 3, 2, 1], + [1, 2, 3, 3, 2, 1], + [1, 2, 2, 2, 2, 1], + [1, 1, 1, 1, 1, 3]], None), + "glszm_2d_apart_3x7": ( + [[1, 3, 1, 2, 4, 4, 4], + [3, 3, 3, 2, 4, 4, 4], + [1, 3, 1, 2, 4, 4, 4]], + [[1, 1, 1, 1, 1, 0, 1], + [1, 1, 1, 1, 1, 0, 1], + [1, 1, 1, 1, 1, 0, 1]]), +} +SPLIT_BY_FORWARD_WALK = ("glszm_2d_docs_2x3", "glszm_2d_pyrad_5x5", "glszm_2d_hook_6x6") + +FORWARD = ((0, 1), (1, 1), (1, 0), (1, -1)) +EIGHT = ((0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1)) + + +def _zones(img, mask, steps): + """Zone sizes per grey level, growing each zone from its first raster pixel through `steps`.""" + h, w = img.shape + seen = numpy.zeros_like(img, dtype=bool) + zones = [] + for r in range(h): + for c in range(w): + if not mask[r, c] or seen[r, c]: + continue + g = img[r, c] + seen[r, c] = True + stack, size = [(r, c)], 1 + while stack: + y, x = stack.pop() + for dy, dx in steps: + ny, nx = y + dy, x + dx + if 0 <= ny < h and 0 <= nx < w and mask[ny, nx] and not seen[ny, nx] and img[ny, nx] == g: + seen[ny, nx] = True + size += 1 + stack.append((ny, nx)) + zones.append((int(g), size)) + return zones + + +def zone_count_8(img, mask): + return len(_zones(img, mask, EIGHT)) + + +def forward_zone_count(img, mask): + return len(_zones(img, mask, FORWARD)) + + +def pyradiomics_values(img, mask): + radiomics.setVerbosity(40) + ext = featureextractor.RadiomicsFeatureExtractor( + binWidth=1, force2D=True, force2Ddimension=0, label=1, resampledPixelSpacing=None) + ext.disableAllFeatures() + ext.enableFeatureClassByName("glszm") + # PyRadiomics refuses a mask with no 0 in it, so each fixture gets a one-pixel border outside the + # mask; it crops to the ROI's bounding box before building the matrix, so the border adds nothing. + img, mask = numpy.pad(img, 1), numpy.pad(mask, 1) + im = sitk.GetImageFromArray(img[numpy.newaxis].astype(numpy.float64)) + ma = sitk.GetImageFromArray(mask[numpy.newaxis].astype(numpy.uint8)) + res = ext.execute(im, ma) + return {code: float(res["original_glszm_" + name]) for code, name in PYRAD.items()} + + +def header_pins(): + """{fixture: {feature: value}} parsed from the header's glszm_2d_pyradiomics__ref_vals tables.""" + text = open(TEST_H, encoding="utf-8").read() + pins = {} + for m in re.finditer(r"static const ref_vals_map glszm_2d_pyradiomics_(\w+?)_ref_vals\s*\{(.*?)\};", text, re.S): + pins["glszm_2d_" + m.group(1)] = {k: float(v) for k, v in re.findall(r'\{"(GLSZM_\w+)",\s*([-0-9.eE+]+)\}', m.group(2))} + return pins + + +def main(): + failures = [] + pins = header_pins() if os.path.exists(TEST_H) else {} + for name, (rows, mrows) in FIXTURES.items(): + img = numpy.array(rows, dtype=numpy.int64) + mask = numpy.ones_like(img) if mrows is None else numpy.array(mrows, dtype=numpy.int64) + assert img[mask > 0].min() == 1, f"{name}: smallest ROI intensity must be 1 for binWidth=1 to keep the levels" + n8, nf = zone_count_8(img, mask), forward_zone_count(img, mask) + if name in SPLIT_BY_FORWARD_WALK and not nf > n8: + failures.append(f"{name}: the forward walk finds {nf} zones, no more than the {n8} 8-connected ones") + if name not in SPLIT_BY_FORWARD_WALK and nf != n8: + failures.append(f"{name}: the negative fixture must not discriminate the walk ({nf} vs {n8})") + vals = pyradiomics_values(img, mask) + npix = int((mask > 0).sum()) + if not math.isclose(vals["GLSZM_ZP"], n8 / npix, rel_tol=1e-12): + failures.append(f"{name}: PyRadiomics ZP {vals['GLSZM_ZP']} is not {n8} zones / {npix} pixels") + print(f"// {name}: {n8} zones (8-connected), {nf} under an E/SE/S/SW walk, {npix} pixels") + table = name.replace("glszm_2d_", "glszm_2d_pyradiomics_") + "_ref_vals" + print(f"static const ref_vals_map {table}") + print("{") + print(",\n".join(f' {{"{k}", {v!r}}}' for k, v in vals.items())) + print("};\n") + got = pins.get(name) + if got is None: + failures.append(f"{name}: no table in {os.path.basename(TEST_H)}") + continue + for k, v in vals.items(): + if k not in got: + failures.append(f"{name}: {k} not pinned") + elif not math.isclose(got[k], v, rel_tol=RELTOL): + failures.append(f"{name}: {k} pinned {got[k]!r}, PyRadiomics gives {v!r}") + if failures: + print("\n".join("FAIL " + f for f in failures), file=sys.stderr) + sys.exit(1) + print("OK: every pin reproduces") + + +if __name__ == "__main__": + main()