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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ Python/devtest.py
Python/dist/
Python/tigre/utilities/cuda_interface/*.cpp
Python/tigre/plugins/*/*.cpp
Python/tigre/plugins/dual_energy/data/
.ipynb_checkpoints
# Object files
*.o
Expand Down
2 changes: 2 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ graft Python/tests
graft Python/demos
# Plugin CUDA sources: built only with TIGRE_PLUGINS, so not added by setup.py otherwise.
graft Common/CUDA/plugins
# Dual-energy plugin data, copied into the package by setup.py.
include Common/data/*.json
global-exclude *.py[cod]
prune Python/tests/__pycache__
prune Python/demos/__pycache__
2 changes: 2 additions & 0 deletions MATLAB/Utilities/TIGRE.bib
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,8 @@ @article{https://doi.org/10.1002/mp.17002
doi = {https://doi.org/10.1002/mp.17002},
url = {https://aapm.onlinelibrary.wiley.com/doi/abs/10.1002/mp.17002},
eprint = {https://aapm.onlinelibrary.wiley.com/doi/pdf/10.1002/mp.17002},
year = {2024}
}

pCTCubicSpline

Expand Down
50 changes: 50 additions & 0 deletions Python/demos/d23_DualEnergy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""Dual-energy CBCT (dual-energy plugin).

Decomposes two scans taken at different tube voltages into equivalent thicknesses of two
basis materials, makes virtual monoenergetic (VM) projections and reconstructs a VM image.
Needs two Varian scans of the same object; set the data paths below.
Same as MATLAB/Plugins/DualEnergy/Demos/d23_DualEnergy.m.

Coded by: Andrew Keeler. Contact: akeeler@luc.edu. Date: February 28, 2024.
"""

# %% Data loading (see d21_ScannerDataLoader.py)
# We'll use VarianDataLoader as an example. Load two sets of scan data at different kV
# settings. geo should be the same for both scans, so it only needs to be loaded once.
# Beam hardening correction is not needed.
import tigre
import tigre.algorithms as algs
from tigre.plugins.dual_energy import DeDecompose, MakeVMproj
from tigre.utilities.io import VarianDataLoader

datafolder_low = "~/your_data_path/varian/low_kV/2020-01-01_123456/"
datafolder_high = "~/your_data_path/varian/high_kV/2020-01-01_123456/"
proj_h, geo, angles_h = VarianDataLoader(datafolder_high, bh=False)
proj_l, _, angles_l = VarianDataLoader(datafolder_low, bh=False)

# %% Material decomposition
# DE-CBCT decomposes the two scans into equivalent thicknesses of two basis materials.
# Generally, either Al and PMMA or iodine and water are used. The calibration in TIGRE uses
# Al and PMMA; other materials are supported if the calibration file
# (Common/data/dual_energy_calibrations.json) is updated with their data (contact the
# developers or make a PR to add it).
#
# The decomposition defaults to scans at 80 and 140 kV. Other energies can be given with
# kVl and kVh.
Al_proj, PMMA_proj, angles = DeDecompose(
proj_l, angles_l, proj_h, angles_h,
# the following are the defaults
scanner="VarianTrueBeam", material1="Al", material2="PMMA", kVl=80, kVh=140,
)

# %% Image construction
# Equivalent thickness projections can now be used to synthesize various DE-derived image
# types. The most common of these are virtual monoenergetic (VM) images.
energy = 60 # keV
VM_proj = MakeVMproj(Al_proj, PMMA_proj, energy, material1="Al", material2="PMMA")

VMimg = algs.fdk(VM_proj, geo, angles)
VMimg = algs.ossart(VM_proj, geo, angles, 100)

# %% Plot image
tigre.plotimg(VMimg, dim="z")
52 changes: 52 additions & 0 deletions Python/tests/test_dual_energy_plugin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Dual-energy plugin (tigre.plugins.dual_energy) on tiny synthetic data, CPU only. Same
numbers as MATLAB's test_DualEnergy_plugin.m:
- DeDecompose maps each pixel pair (L, H) with the calibration polynomial, matches low-kV
projections by angle ('nearest', 'linear', 'skip') and uses the kV pair it is given.
- MakeVMproj at 100 keV, a tabulated energy, gives exactly the NIST values.
"""


import numpy as np
from tigre.plugins.dual_energy import DeDecompose, MakeVMproj
from tigre.plugins.dual_energy._data import load_data

ARGS = {"scanner": "VarianTrueBeam", "material1": "Al", "material2": "PMMA"}


def poly(c, L, H):
return (c[0] * L + c[1] * H + c[2] * L**2 + c[3] * L * H + c[4] * H**2
+ c[5] * L**3 + c[6] * H * L**2 + c[7] * L * H**2 + c[8] * H**3)


def test_dual_energy_plugin():
cal = load_data("dual_energy_calibrations.json")
# (angle, v, u); MATLAB's L(:,:,k) is L[k] here
L = np.array([[[0.1, 0.2], [0.3, 0.4]], [[0.5, 0.6], [0.7, 0.8]], [[0.9, 1.0], [1.1, 1.2]]])
H = 0.6 * L + 0.05
angles_l = np.array([0.02, 1.02, 2.02])
angles_h = np.array([0.0, 1.0, 2.0])

# nearest, 80/140 kV (default)
m1, m2, ang = DeDecompose(L, angles_l, H, angles_h, **ARGS)
c, d = cal["VarianTrueBeam"]["V_80_140"]["Al"], cal["VarianTrueBeam"]["V_80_140"]["PMMA"]
np.testing.assert_array_equal(ang, angles_h)
np.testing.assert_allclose(m1, poly(c, L, H), rtol=0, atol=1e-12)
np.testing.assert_allclose(m2, poly(d, L, H), rtol=0, atol=1e-12)

# the kV pair given is used
m1_90, _, _ = DeDecompose(L, angles_l, H, angles_h, kVl=90, kVh=140, **ARGS)
np.testing.assert_allclose(m1_90[0], poly(cal["VarianTrueBeam"]["V_90_140"]["Al"], L[0], H[0]), rtol=0, atol=1e-12)

# linear: halfway between two low-kV projections
m1_lin, _, _ = DeDecompose(L, [0, 1, 2], H[:1], [0.5], interpolation="linear", **ARGS)
np.testing.assert_allclose(m1_lin[0], poly(c, (L[0] + L[1]) / 2, H[0]), rtol=0, atol=1e-12)

# skip: nothing within 0.01 rad, everything within 0.05 rad
m1_skip, _, ang_skip = DeDecompose(L, angles_l, H, angles_h, interpolation="skip", tolerance=0.01, **ARGS)
assert m1_skip.shape[0] == 0 and ang_skip.size == 0
_, _, ang_skip = DeDecompose(L, angles_l, H, angles_h, interpolation="skip", tolerance=0.05, **ARGS)
np.testing.assert_array_equal(ang_skip, angles_h)

# virtual monoenergetic projection at a tabulated energy
vm = MakeVMproj(m1, m2, 100, material1="Al", material2="PMMA")
np.testing.assert_allclose(vm, 0.046 * m1 + 0.0194 * m2, rtol=0, atol=1e-9)
166 changes: 166 additions & 0 deletions Python/tigre/plugins/dual_energy/DeDecompose.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import warnings

import numpy as np

from ._data import load_data


def DeDecompose(
proj_l,
angles_l,
proj_h,
angles_h,
scanner=None,
kVl=80,
kVh=140,
material1=None,
material2=None,
interpolation="nearest",
tolerance=None,
):
"""Map CBCT projections taken at two kV settings to equivalent thicknesses of two materials.

For each high-kV projection, the low-kV projection at the same angle is found (see
``interpolation``), and every pixel pair (L, H) is mapped to two thicknesses with
third-degree transfer functions whose coefficients come from the scanner's calibration
(``Common/data/dual_energy_calibrations.json``). Other scanners, kV pairs or basis
materials need calibration data added there.

Method: Keeler A. et al., Technical note: TIGRE-DE for the creation of virtual
monoenergetic images from dual-energy cone-beam CT, Med Phys 2024,
https://doi.org/10.1002/mp.17002 (BibTeX: entry ``TIGRE-DE`` in
``tigre/utilities/TIGRE.bib``).

Args:
proj_l, angles_l: projections ``(angle, v, u)`` and angles (radians) of the low-kV scan.
proj_h, angles_h: the same for the high-kV scan. Both scans must have the same
detector size.
scanner (str): calibration to use. Default ``"VarianTrueBeam"``, with a warning:
results are only quantitative with your own scanner's calibration.
kVl, kVh (float): kV of the low- and high-kV scans. Default 80 and 140.
material1 (str): default ``"Al"``.
material2 (str): default ``"PMMA"``.
interpolation (str): how to get the low-kV projection at a high-kV angle:
``"nearest"`` (default) the low-kV projection with the closest angle;
``"linear"`` linear interpolation between the low-kV projections either side;
``"skip"`` like ``"nearest"``, but high-kV projections with no low-kV projection
within ``tolerance`` are skipped.
tolerance (float): for ``"skip"``, the largest angle difference in radians.
Default: half the low-kV angular step.

Returns:
tuple: ``(material1_proj, material2_proj, angles)``: the thicknesses of material1 and
material2, ``(angle, v, u)``, at ``angles`` (the high-kV angles, minus any skipped).
"""
proj_l = np.asarray(proj_l)
proj_h = np.asarray(proj_h)
angles_l = np.asarray(angles_l, dtype=np.float64).ravel()
angles_h = np.asarray(angles_h).ravel()

interpolation = str(interpolation).lower()
if interpolation not in ("nearest", "linear", "skip"):
raise ValueError("interpolation must be 'nearest', 'linear' or 'skip'.")
if tolerance is not None and not (np.isscalar(tolerance) and tolerance >= 0):
raise ValueError("tolerance must be a non-negative number (radians).")
if scanner is None:
warnings.warn(
"You have not given a scanner for DE calibration. Dual Energy Calibration is strictly "
"dependant on scanner calibration, so do not use the results here for quantitative "
"analysis. Assuming VarianTrueBeam"
)
scanner = "VarianTrueBeam"
if material1 is None:
warnings.warn("Assuming Al for material1")
material1 = "Al"
if material2 is None:
warnings.warn("Assuming PMMA for material2")
material2 = "PMMA"

calibration_data = load_data("dual_energy_calibrations.json")
if scanner not in calibration_data:
raise ValueError(
f"Scanner {scanner} has no calibration data. "
f"Scanners with calibration data: {', '.join(calibration_data)}"
)
scanner_data = calibration_data[scanner]
kVl, kVh = round(kVl), round(kVh)
pair = f"V_{kVl}_{kVh}"
if pair not in scanner_data:
raise ValueError(
f"No calibration for {kVl} and {kVh} kV for scanner {scanner}. "
f"Calibrated kV pairs: {', '.join(k.replace('V_', '') for k in scanner_data)}"
)
pair_data = scanner_data[pair]
for material in (material1, material2):
if material not in pair_data:
raise ValueError(
f"{material} is not (yet) a supported material for scanner {scanner} at {kVl} and "
f"{kVh} kV. Supported materials: {', '.join(pair_data)}"
)
c = [float(x) for x in pair_data[material1]]
d = [float(x) for x in pair_data[material2]]

if proj_l.ndim != 3 or proj_h.ndim != 3 or proj_l.shape[1:] != proj_h.shape[1:]:
raise ValueError(
"High- and low-kV projections must be (angle, v, u) with the same detector size "
f"(got {proj_h.shape} and {proj_l.shape})."
)
if angles_h.size != proj_h.shape[0] or angles_l.size != proj_l.shape[0]:
raise ValueError("There must be one angle per projection in each scan.")
if tolerance is None:
tolerance = _angular_step(angles_l) / 2

material1_proj = np.zeros_like(proj_h)
material2_proj = np.zeros_like(proj_h)
angles_out = np.zeros_like(angles_h)
kept = 0
for k in range(proj_h.shape[0]):
L = _proj_interp(proj_l, angles_l, angles_h[k], interpolation, tolerance)
if L is None:
print(f"No low-kV projection within {tolerance:g} rad of high-kV projection {k}. Skipping.")
continue
H = proj_h[k]
# map each pixel pair (L, H) to equivalent thicknesses
material1_proj[kept] = _transfer(c, L, H)
material2_proj[kept] = _transfer(d, L, H)
angles_out[kept] = angles_h[k]
kept += 1
return material1_proj[:kept], material2_proj[:kept], angles_out[:kept]


def _transfer(c, L, H):
return (
c[0] * L + c[1] * H + c[2] * L**2 + c[3] * L * H + c[4] * H**2
+ c[5] * L**3 + c[6] * H * L**2 + c[7] * L * H**2 + c[8] * H**3
)


def _angular_step(angles):
a = np.sort(np.mod(angles, 2 * np.pi))
if a.size < 2:
return 2 * np.pi
return float(np.median(np.diff(a)))


def _proj_interp(proj_in, angles_in, target_angle, model, tolerance):
"""Low-kV projection at target_angle (None if 'skip' finds none within tolerance).

Angles are compared modulo 2*pi, so 0 and 2*pi are the same angle.
"""
# signed angle differences, wrapped to [-pi, pi)
delta = np.mod(angles_in - target_angle + np.pi, 2 * np.pi) - np.pi
idx = int(np.argmin(np.abs(delta)))
dmin = abs(delta[idx])
if model == "skip" and dmin > tolerance:
return None
if model != "linear" or dmin == 0:
return proj_in[idx]
other = np.flatnonzero(np.sign(delta) == -np.sign(delta[idx]))
if other.size == 0:
return proj_in[idx]
j = other[np.argmin(np.abs(delta[other]))]
dother = abs(delta[j])
if angles_in.size > 1 and dmin + dother <= 2 * _angular_step(angles_in):
w = dmin / (dmin + dother) # weight of the projection on the other side
return (1 - w) * proj_in[idx] + w * proj_in[j]
return proj_in[idx]
57 changes: 57 additions & 0 deletions Python/tigre/plugins/dual_energy/MakeVMproj.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import warnings

import numpy as np
from scipy.interpolate import CubicSpline

from ._data import load_data


def MakeVMproj(material1_proj, material2_proj, energy, material1=None, material2=None):
"""Virtual monoenergetic (VM) projections from basis material thickness projections.

``VM_proj = mu1(energy) * material1_proj + mu2(energy) * material2_proj``, with the
attenuation coefficients mu from ``Common/data/NIST_material_attenuation.json``,
interpolated with a cubic spline (as MATLAB's ``spline``). Reconstruct ``VM_proj`` with any
TIGRE algorithm to get a VM image.

Method: Keeler A. et al., Technical note: TIGRE-DE for the creation of virtual
monoenergetic images from dual-energy cone-beam CT, Med Phys 2024,
https://doi.org/10.1002/mp.17002.

Args:
material1_proj, material2_proj: thickness projections from :func:`DeDecompose`.
energy (float): energy in keV.
material1 (str): default ``"Al"``.
material2 (str): default ``"PMMA"``.

Returns:
The VM projections, the same shape as ``material1_proj``.
"""
if material1 is None:
warnings.warn("Assuming Al for material1")
material1 = "Al"
if material2 is None:
warnings.warn("Assuming PMMA for material2")
material2 = "PMMA"
nist = load_data("NIST_material_attenuation.json")
for material in (material1, material2):
if material not in nist:
raise ValueError(
f"{material} is not (yet) a supported material in the NIST data. "
f"Supported materials: {', '.join(nist)}"
)
if not np.isscalar(energy) or isinstance(energy, (str, bool)):
raise ValueError("energy must be a number (keV).")
e1, e2 = nist[material1]["energy"], nist[material2]["energy"]
if energy < max(min(e1), min(e2)) or energy > min(max(e1), max(e2)):
warnings.warn("Requested energy is outside of expected range. Results may be unreliable.")

# attenuation coefficients of the basis materials at the selected energy
mu1 = float(_spline(e1, nist[material1]["mu"], energy))
mu2 = float(_spline(e2, nist[material2]["mu"], energy))
return mu1 * np.asarray(material1_proj) + mu2 * np.asarray(material2_proj)


def _spline(x, y, xi):
order = np.argsort(x) # MATLAB's spline sorts x too
return CubicSpline(np.asarray(x, dtype=float)[order], np.asarray(y, dtype=float)[order])(xi)
12 changes: 12 additions & 0 deletions Python/tigre/plugins/dual_energy/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"""Dual-energy CBCT plugin: material decomposition and virtual monoenergetic projections
(MATLAB/Plugins/DualEnergy in MATLAB).

Pure Python, always installed. Method: Keeler A. et al., Technical note: TIGRE-DE for the
creation of virtual monoenergetic images from dual-energy cone-beam CT, Med Phys 2024,
https://doi.org/10.1002/mp.17002.
"""

from .DeDecompose import DeDecompose
from .MakeVMproj import MakeVMproj

__all__ = ["DeDecompose", "MakeVMproj"]
21 changes: 21 additions & 0 deletions Python/tigre/plugins/dual_energy/_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import json
import os

_HERE = os.path.dirname(os.path.abspath(__file__))


def load_data(name):
"""Read one of the plugin's JSON data files.

The single copy is in TIGRE's Common/data; setup.py copies it into the package's data
folder. Running from a source folder that was not built, Common/data is read directly.
"""
candidates = [
os.path.join(_HERE, "data", name),
os.path.join(_HERE, "..", "..", "..", "..", "Common", "data", name),
]
for file in candidates:
if os.path.isfile(file):
with open(file, encoding="utf-8") as f:
return json.load(f)
raise FileNotFoundError("Dual-energy data not found: " + name + " (looked in " + ", ".join(candidates) + ")")
Loading
Loading