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
8 changes: 8 additions & 0 deletions docs/source/Math/f_glcm.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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``,
Expand Down
9 changes: 5 additions & 4 deletions docs/source/ibsi_mode.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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::
Expand Down
123 changes: 79 additions & 44 deletions src/nyx/features/glcm.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
#include <iostream>
#include <new>
#include <numeric>
#include <stdexcept>
#include <string>
#include "glcm.h"
#include "../helpers/helpers.h"
#include "../environment.h"
Expand Down Expand Up @@ -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<double>().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()
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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<double>& 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<double>& GLCM,
Expand Down Expand Up @@ -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);

Expand Down
9 changes: 9 additions & 0 deletions src/nyx/features/glcm.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<double>& 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<double>& P_matrix, std::vector<double>& px, std::vector<double>& py);
double f_info_meas_corr1(const SimpleMatrix<double>& P_matrix, double softnan);
Expand Down
114 changes: 114 additions & 0 deletions tests/python/test_2d_glcm_mechanics.py
Original file line number Diff line number Diff line change
@@ -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()
51 changes: 51 additions & 0 deletions tests/test_2d_glcm_mechanics.h
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,55 @@ 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<std::vector<double>> extract_2d_glcm_ibsi (unsigned int top_level, double noval)
{
std::vector<NyxusPixel> 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 (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);
}
}
Loading
Loading