Skip to content
Open
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
5 changes: 3 additions & 2 deletions docs/source/Math/f_intensity_3d.rst
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@ bounding box outside the mask.
``3COVERED_IMAGE_INTENSITY_RANGE`` through its slope, variances through the square of its slope,
and the ratios ``3COV``, ``3QCOD`` and ``3UNIFORMITY_PIU`` are recomputed from the mapped parts.
A signed integer volume is therefore reported in its own signed values. A floating-point volume
is reported in its own range, to the resolution of its grey levels (``--fpimgdr``, 10000 steps
over the volume's range by default).
with fractional values is reported in its own range, to the resolution of its grey levels
(``--fpimgdr``, 10000 steps over the volume's range by default); a floating-point NIfTI volume
that holds only whole values is reported exactly, as an integer volume is.
- **Files only:** ``Nyxus3D`` reads volumes from files (``featurize_files`` or
``featurize_directory``); there is no in-memory path.
- **IBSI mode:** ``--ibsi=true`` does not change any 3D intensity feature.
Expand Down
7 changes: 5 additions & 2 deletions docs/source/supported_formats.rst
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,11 @@ they are reported in the image's own units:
``0 .. --fpimgdr`` grey levels (10000 by default). ``--fpimgmin`` and ``--fpimgmax`` replace the
image's own range with a fixed one; giving any of the three options switches every
floating-point image to that fixed range, which is 0 to 1 unless set.
* A floating-point NIfTI volume is not rescaled: its values are truncated to whole units (after
the shift, when it has negative values), so fractional values are lost.
* A floating-point NIfTI volume with fractional values (after its ``scl_slope`` and ``scl_inter``
rescale) is rescaled the same way, so a volume normalised to 0 .. 1 keeps its fraction. One that
holds only whole values, such as a CT saved as float, is not rescaled: it is shifted like an
integer image, so one grey level is one intensity unit and texture features are binned in its own
units.
* A DICOM image, or an integer NIfTI volume, keeps its stored integers as grey levels and applies
its rescale slope and intercept when converting back, so a fractional rescaled value is reported
exactly.
Expand Down
7 changes: 5 additions & 2 deletions src/nyx/image_loader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,11 @@ bool ImageLoader::open (SlideProps & p, const FpImageOptions & fpopts)
if (fmt == Nyxus::ContainerKind::Nifti)
{
// Same as DICOM for an integer volume. A real-valued one never takes the stored
// map, so it rescales and shifts by the offset the scan recorded.
intFL = new NiftiLoader<uint32_t> (int_fpath, medical_shift, medical_rescale, round_offset);
// map: one holding fractional values takes the quantization a real-valued TIFF
// or Zarr takes, and one of whole values the offset map, as does either under
// preserve_hu -- every map after the header rescale. On the quantized map
// medical_shift is fpmin.
intFL = new NiftiLoader<uint32_t> (int_fpath, medical_shift, medical_rescale, round_offset, quantize, fpmax, dr);
}
else
{
Expand Down
97 changes: 76 additions & 21 deletions src/nyx/raw_nifti.h
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,12 @@ class RawNiftiLoader : public RawFormatLoader
case 16: // NIFTI_TYPE_FLOAT32
get_uint32_pixel_typeresolved = get_uint32_pixel_imp <float>;
get_dpequiv_pixel_typeresolved = get_dp_pixel_imp <float>;
fp_pixels_ = holds_fraction();
break;
case 64: // NIFTI_TYPE_FLOAT64
get_uint32_pixel_typeresolved = get_uint32_pixel_imp <double>;
get_dpequiv_pixel_typeresolved = get_dp_pixel_imp <double>;
fp_pixels_ = holds_fraction();
break;
default:
std::string erm = "error: unrecognized NIFTI data type " + std::to_string(nii_->datatype) + " in " + slide_path_;
Expand Down Expand Up @@ -193,6 +195,24 @@ class RawNiftiLoader : public RawFormatLoader
int bitsPerSample_ = 1;

std::string slide_path_;

// Whether a real-valued volume carries a fraction anywhere: a finite voxel whose header-rescaled
// value is not a whole number. Such a volume reports itself as real-valued, so the scan records
// the quantized map a real-valued TIFF or OME-Zarr takes and a volume normalised to [0, 1]
// keeps its fraction. A FLOAT32/FLOAT64 volume holding whole values only -- a CT stored as
// float, a label-like phantom -- reports itself as integer and keeps 1 grey level == 1
// intensity unit, so its texture features are binned in its own units. Non-finite voxels say
// nothing about the volume's values and are skipped, as the scan skips them.
bool holds_fraction() const
{
for (size_t i = 0; i < nii_->nvox; i++)
{
double v = get_dpequiv_pixel (i);
if (std::isfinite (v) && v != std::floor (v))
return true;
}
return false;
}
};

template<class DataType>
Expand All @@ -204,9 +224,13 @@ class NiftiLoader : public AbstractTileLoader<DataType>
std::string const& slide_path,
double inten_offset = 0.0, // the shift the scan recorded: physical units, or stored units with the rescale off
bool rescale_to_physical = true, // off for a mask volume, whose voxels are labels, and on the stored map
bool round_offset = false) // offset map: round to nearest instead of truncating
bool round_offset = false, // offset map: round to nearest instead of truncating
bool quantize = false, // min-max rescale a real-valued volume, instead of the offset map
double inten_max = 1.0, // upper end of the clamp, used only when quantize is set
double target_dyn_range = 1e4) // grey levels the rescale spans, used only when quantize is set
: AbstractTileLoader<DataType>("NiftiLoader", 1/*numberThreads*/, slide_path),
inten_offset_(inten_offset), rescale_(rescale_to_physical), round_offset_(round_offset)
inten_offset_(inten_offset), rescale_(rescale_to_physical), round_offset_(round_offset),
quantize_(quantize), inten_max_(inten_max), target_dyn_range_(target_dyn_range)
{
slide_path_ = slide_path;

Expand Down Expand Up @@ -341,36 +365,67 @@ class NiftiLoader : public AbstractTileLoader<DataType>

// The shift this volume's grey levels carry. On the offset map voxels are rescaled to physical
// units and shifted by SlideProps::inten_offset (0 unless the volume's own minimum is
// negative). On the stored map rescale_ is off, so the stored integers are shifted by
// SlideProps::inten_stored_shift and the rescale lives in the recorded inverse instead. The
// intensity families apply that inverse, so reported statistics are in the volume's own domain
// either way. cur_scl_* hold the current read's header rescale, shared with rescale_offset().
// negative). On the quantized map, which a volume holding fractional values takes when read
// without --preserve-hu, inten_offset_ is the low end of the [fpmin, fpmax] window the physical values are
// clamped to and rescaled from. On the stored map rescale_ is off, so the stored integers are
// shifted by SlideProps::inten_stored_shift and the rescale lives in the recorded inverse
// instead. The intensity families apply that inverse, so reported statistics are in the
// volume's own domain on every map. cur_scl_* hold the current read's header rescale, shared
// with rescale_offset().
double inten_offset_ = 0.0;
bool rescale_ = true;
bool round_offset_ = false; // offset map: round to nearest (--preserve-hu) instead of truncating
double cur_scl_slope_ = 1.0, cur_scl_inter_ = 0.0;

// Whether this volume is min-max rescaled into [0, target_dyn_range_] (a real-valued volume
// left in its default mode) or carried on the offset map. SlideProps::inten_map is where the
// choice is made and recorded; ImageLoader::open passes it here, exactly as it does for TIFF
// and OME-Zarr.
bool quantize_ = false;
double inten_max_ = 1.0,
target_dyn_range_ = 1e4;

template <class til, class fra>
void rescale_offset (std::vector<til>& nyxbuf, const fra* houbuf, size_t n)
{
// Rescale stored -> physical (slope*stored + intercept) unless the rescale is off, then shift
// by the recorded offset so sub-minimum voxels (negative CT values among them) clamp to 0
// instead of wrapping on the unsigned cast. With the rescale off the stored integers are
// shifted as they are, and the narrowing below is exact. Reading the volume's own minimum
// here instead would produce a shift nothing downstream could undo.
//
// Nyxus::grey_level() carries the narrowing every load-time map shares. A non-finite voxel
// takes grey level 0 -- a float volume is free to hold NaN, a masked-out background most
// often -- and one above the grey type's maximum saturates, which a 64-bit volume or a
// large scl_slope can reach. round_offset_ rounds to nearest under --preserve-hu, where
// scl_slope is routinely fractional on a PET-derived volume and the scale-1 inverse could
// not recover a truncated fraction; a volume read without the flag truncates, which is what
// a real-valued NIfTI has always done. An integer volume read without the flag takes the
// stored map, where there is no fraction to narrow.
// Rescale stored -> physical (slope*stored + intercept) unless the rescale is off, then map
// the physical value the way the scan recorded. The scan measured its range on the same
// rescaled values (RawNiftiLoader::get_dpequiv_pixel), so the quantized window and the
// offset are both in physical units. With the rescale off the stored integers are shifted
// as they are, and the narrowing is exact.
for (size_t i = 0; i < n; ++i)
{
double v = cur_scl_slope_ * (double)houbuf[i] + cur_scl_inter_;
nyxbuf[i] = Nyxus::grey_level<til> (v - inten_offset_, round_offset_);
nyxbuf[i] = map_intensity<til> (v);
}
}

// One physical value -> the grey level stored for it. Both branches narrow through the
// Nyxus::grey_level* calls the TIFF and OME-Zarr loaders use, so no backend can drift from
// another. A non-finite voxel takes grey level 0 on either -- a float volume is free to hold
// NaN, a masked-out background most often -- and one above the grey type's maximum saturates,
// which a 64-bit volume or a large scl_slope can reach on the offset map.
//
// The offset map shifts by the recorded offset so sub-minimum voxels (negative CT values among
// them) clamp to 0 instead of wrapping on the unsigned cast. round_offset_ rounds to nearest
// under --preserve-hu, where scl_slope is routinely fractional on a PET-derived volume and the
// scale-1 inverse could not recover a truncated fraction; otherwise it truncates. Without the
// flag the volumes that reach it hold no fraction to lose: a FLOAT32/FLOAT64 volume of whole
// values (RawNiftiLoader::holds_fraction), an integer one whose header rescale the stored map
// cannot carry (a zero, negative or non-finite slope), or a constant real-valued volume, which
// has no window to quantize into.
//
// The quantized map hard-clamps to [inten_offset_, inten_max_] and spreads that window over
// target_dyn_range_ grey levels, so a volume normalised to [0, 1] keeps its fraction.
template <class til>
til map_intensity (double v) const
{
if (! quantize_)
return Nyxus::grey_level<til> (v - inten_offset_, round_offset_);
// Ahead of the clamp, as in the TIFF loaders: the clamp would store +Inf as the top level.
if (! std::isfinite (v)) return (til) 0;
double t = v < inten_offset_ ? inten_offset_ : v;
t = t > inten_max_ ? inten_max_ : t;
return Nyxus::grey_level_truncated<til> (target_dyn_range_ * (t - inten_offset_) / (inten_max_ - inten_offset_));
}
};
36 changes: 30 additions & 6 deletions tests/data/hounsfield/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ loader path (`RawNiftiLoader`/`NiftiLoader`). `ct3d_int16.nii` is also the overs
| `ct3d_int16.nii` | 8×8×8 signed int16, `scl_slope=2`, `scl_inter=-1024` | stored `idx-200` (−200..311, crosses 0); true HU = 2·stored−1024 |
| `ct3d_frac.nii` | 8×8×8 signed int16, `scl_slope=0.5`, `scl_inter=-1024` | stored `idx` (0..511); physical = 0.5·idx−1024 over −1024..−768.5, half the voxels fractional |
| `ct3d_nan.nii` | 8×8×8 float32, no rescale | `v(idx) = idx`, with NaN at 3, +Inf at 5, −Inf at 7 |
| `mask3d.nii` | 8×8×8 uint8, all ones | single ROI over the whole volume, shared by all three |
| `ct3d_unit.nii` | 8×8×8 float32, no rescale (`scl_slope=0`) | `v(idx) = idx/511` over 0..1, every voxel but the two ends fractional |
| `ct3d_float_slope.nii` | 8×8×8 float32, `scl_slope=2`, `scl_inter=-1024` | stored `idx + 0.25`; physical = 2·idx − 1023.5 over −1023.5..−1.5 |
| `mask3d.nii` | 8×8×8 uint8, all ones | single ROI over the whole volume, shared by all five |

The non-unit `scl_slope` makes the HU rescale observable: in HU mode the loader maps each voxel to
`u = round((2·stored − 1024) − floor(HU min)) = 2·stored + 400` (offset domain 0..1022, mean 511),
Expand All @@ -83,11 +85,25 @@ maps that `ct3d_int16.nii` cannot show:
level is `round(0.5·idx)` (MAX −768, MEAN −896): `inten_scale` is 1 on the offset map, so a
fraction dropped there is unrecoverable. Without the flag the stored map keeps `idx` as the grey
level and reports the fractions exactly (MAX −768.5, MEAN −896.25). Both are pinned.
- **Non-finite voxels.** `ct3d_nan.nii` is float32, so it takes the offset map either way. They are
left out of the scanned extrema and stored as grey level 0, so the finite range stays `[0, 511]`
and the mean is `(130816 − 3 − 5 − 7)/512 = 255.470703125`.

Both were produced by patching `ct3d_int16.nii`'s own 352-byte header block — its `datatype`
- **Non-finite voxels.** `ct3d_nan.nii` is float32 holding whole values only, so it takes the offset
map either way. They are left out of the scanned extrema and stored as grey level 0, so the finite
range stays `[0, 511]` and the mean is `(130816 − 3 − 5 − 7)/512 = 255.470703125`.

`ct3d_unit.nii` and `ct3d_float_slope.nii` are consumed by `tests/test_3d_nifti_mechanics.h`
(`TEST_3D_NIFTI_FLOAT_*`). A float NIfTI whose header-rescaled values carry a fraction takes the
quantized map a float TIFF takes, and these pin it:

- **A volume normalised to 0..1.** `ct3d_unit.nii` spreads over grey levels 0..10000, its 512 values
on 512 distinct levels, each reading back to within 1e-4. Narrowed to whole units it would read
back as 0 everywhere but its last voxel.
- **The rescale comes first.** `ct3d_float_slope.nii` is quantized over the physical window
`[−1023.5, −1.5]` the scan measures on rescaled values, so each voxel reads back to within
1022/10000. Narrowed to whole units, every voxel lands half a unit off.
- **Not quantized.** Under `--preserve-hu`, `ct3d_unit.nii` takes the offset map and rounds (0.499 →
0, 0.501 → 1). `ct3d_nan.nii`, float32 of whole values, keeps one grey level per unit.
`ct3d_frac.nii` keeps the stored map.

All four were produced by patching `ct3d_int16.nii`'s own 352-byte header block — its `datatype`
(offset 70), `bitpix` (72), `scl_slope` (112), `scl_inter` (116), `cal_max` (124) and `cal_min`
(128) — and appending new little-endian payload, so every field the loader does not read stays
byte-identical to the fixture already in the tree:
Expand All @@ -109,8 +125,16 @@ write("ct3d_frac.nii", 4, 16, 0.5, -1024.0,
v = [float(i) for i in range(512)]
v[3], v[5], v[7] = math.nan, math.inf, -math.inf
write("ct3d_nan.nii", 16, 32, 1.0, 0.0, struct.pack("<512f", *v), 0.0, 511.0)

write("ct3d_unit.nii", 16, 32, 0.0, 0.0,
struct.pack("<512f", *[i / 511.0 for i in range(512)]), 0.0, 1.0)
write("ct3d_float_slope.nii", 16, 32, 2.0, -1024.0,
struct.pack("<512f", *[i + 0.25 for i in range(512)]), -1023.5, -1.5)
```

`tests/python/test_3d_nifti_float_mechanics.py` writes its own random float32 and float64 volumes
in the same way at test time.

## Real-scanner fixture

`ct_small.dcm` is pydicom's `CT_small.dcm` test file (128x128 signed int16,
Expand Down
Binary file added tests/data/hounsfield/ct3d_float_slope.nii
Binary file not shown.
Binary file added tests/data/hounsfield/ct3d_unit.nii
Binary file not shown.
Binary file modified tests/data/nifti/phantoms/ut_inten.nii
Binary file not shown.
73 changes: 73 additions & 0 deletions tests/python/test_3d_nifti_float_mechanics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""Mechanics tests for real-valued NIfTI volumes (FLOAT32 / FLOAT64) read end to end.

A real-valued NIfTI takes the quantization a real-valued TIFF or OME-Zarr takes: the volume's range
(or the ``min_intensity`` / ``max_intensity`` window) is spread over ``dynamic_range`` grey levels,
and the intensity family applies the recorded inverse, so MIN / MAX / MEAN come back in the volume's
own units to within one quantization step, ``(max - min) / dynamic_range``. A volume normalised to
[0, 1] keeps its fraction; narrowed to whole units instead it would read back as all zeros, and a
[0, 1000] volume would report its MEAN about half a unit low.

The volumes are random, written at test time with the header of ``ct3d_int16.nii`` (8x8x8) patched
to the float datatype, as tests/data/hounsfield/README.md describes for the committed fixtures, and
paired with ``mask3d.nii`` (all ones). The reference is numpy over the same values.

Kind: *mechanics* per tests/vetting/SPEC.md 2 -- these pin the loader's load-time map rather than
feature values against an independent reference, and establish no vetting.
"""
import os
import pathlib
import struct

import numpy as np
import pytest
import nyxus

DATA = pathlib.Path(__file__).resolve().parent.parent / "data" / "hounsfield"
HEADER_SOURCE = DATA / "ct3d_int16.nii"
MASK = str(DATA / "mask3d.nii")

pytestmark = pytest.mark.skipif(
not (HEADER_SOURCE.exists() and os.path.exists(MASK)),
reason="NIfTI fixtures not present in tests/data/hounsfield",
)

FEATS = ["3MIN", "3MAX", "3MEAN"]
DYNAMIC_RANGE = 10000.0 # the Nyxus3D default

# NIfTI-1 datatype codes and the numpy dtype each stores
FLOAT_TYPES = {16: np.float32, 64: np.float64}


def _write_float_nifti(path, values, datatype):
"""Writes an 8x8x8 real-valued NIfTI with no header rescale."""
h = bytearray(HEADER_SOURCE.read_bytes()[:352]) # 348 header + 4 extender
dtype = FLOAT_TYPES[datatype]
struct.pack_into("<h", h, 70, datatype)
struct.pack_into("<h", h, 72, np.dtype(dtype).itemsize * 8)
struct.pack_into("<f", h, 112, 0.0) # scl_slope 0: no rescale
struct.pack_into("<f", h, 116, 0.0)
path.write_bytes(bytes(h) + np.ascontiguousarray(values, dtype="<" + np.dtype(dtype).char).tobytes())


@pytest.mark.parametrize("datatype", sorted(FLOAT_TYPES))
@pytest.mark.parametrize("hi", [1000.0, 1.0])
def test_3d_nifti_float_keeps_fraction_mechanics(tmp_path, datatype, hi):
"""MIN, MAX and MEAN of a random [0, hi) volume match numpy to within one quantization step.

hi = 1 is the volume that read back as all zeros when narrowed to whole units; hi = 1000 is
the one whose MEAN came out about 0.5 low.
"""
rng = np.random.default_rng(0)
v = rng.uniform(0.0, hi, 512).astype(FLOAT_TYPES[datatype])
inten = tmp_path / "inten.nii"
_write_float_nifti(inten, v, datatype)

df = nyxus.Nyxus3D(FEATS).featurize_files([str(inten)], [MASK], False)
f = {c: float(df[c].iloc[0]) for c in FEATS}

ref = v.astype(np.float64)
step = (ref.max() - ref.min()) / DYNAMIC_RANGE
assert f["3MIN"] == pytest.approx(ref.min(), abs=1e-9 * hi)
assert f["3MAX"] == pytest.approx(ref.max(), abs=step)
assert f["3MEAN"] == pytest.approx(ref.mean(), abs=step)
assert f["3MAX"] > f["3MIN"], "the volume collapsed onto one grey level"
5 changes: 3 additions & 2 deletions tests/python/test_3d_nifti_offset_map_mechanics.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@

*Non-finite voxels.* A float volume is free to hold NaN -- a masked-out background, most often -- and
converting one to an unsigned grey level is undefined. The loader stores grey level 0 for it, the
convention every load-time map uses. ``ct3d_nan.nii`` is float32, which has no stored integers to
keep, so it takes the offset map with or without the flag.
convention every load-time map uses. ``ct3d_nan.nii`` is float32 holding only whole values, so it
is not quantized as a volume with fractional values would be: it takes the offset map with or
without the flag.

Kind: *mechanics* per tests/vetting/SPEC.md 2 -- these pin loader plumbing rather than feature values
against a reference, and establish no vetting.
Expand Down
Loading
Loading