diff --git a/.gitignore b/.gitignore index e861c2d4..906256ec 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/MANIFEST.in b/MANIFEST.in index 10fd4769..c63af49e 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -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__ diff --git a/MATLAB/Utilities/TIGRE.bib b/MATLAB/Utilities/TIGRE.bib index 26895b80..1a0be598 100644 --- a/MATLAB/Utilities/TIGRE.bib +++ b/MATLAB/Utilities/TIGRE.bib @@ -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 diff --git a/Python/demos/d23_DualEnergy.py b/Python/demos/d23_DualEnergy.py new file mode 100644 index 00000000..971bb1be --- /dev/null +++ b/Python/demos/d23_DualEnergy.py @@ -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") diff --git a/Python/tests/test_dual_energy_plugin.py b/Python/tests/test_dual_energy_plugin.py new file mode 100644 index 00000000..20a899e6 --- /dev/null +++ b/Python/tests/test_dual_energy_plugin.py @@ -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) diff --git a/Python/tigre/plugins/dual_energy/DeDecompose.py b/Python/tigre/plugins/dual_energy/DeDecompose.py new file mode 100644 index 00000000..acf55b07 --- /dev/null +++ b/Python/tigre/plugins/dual_energy/DeDecompose.py @@ -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] diff --git a/Python/tigre/plugins/dual_energy/MakeVMproj.py b/Python/tigre/plugins/dual_energy/MakeVMproj.py new file mode 100644 index 00000000..fa966e27 --- /dev/null +++ b/Python/tigre/plugins/dual_energy/MakeVMproj.py @@ -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) diff --git a/Python/tigre/plugins/dual_energy/__init__.py b/Python/tigre/plugins/dual_energy/__init__.py new file mode 100644 index 00000000..8cd5b819 --- /dev/null +++ b/Python/tigre/plugins/dual_energy/__init__.py @@ -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"] diff --git a/Python/tigre/plugins/dual_energy/_data.py b/Python/tigre/plugins/dual_energy/_data.py new file mode 100644 index 00000000..3b6a4a23 --- /dev/null +++ b/Python/tigre/plugins/dual_energy/_data.py @@ -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) + ")") diff --git a/Python/tigre/utilities/TIGRE.bib b/Python/tigre/utilities/TIGRE.bib index 0201fa3b..6b5ce420 100644 --- a/Python/tigre/utilities/TIGRE.bib +++ b/Python/tigre/utilities/TIGRE.bib @@ -430,4 +430,19 @@ @article{pCT_cubic_spline doi={10.1088/0031-9155/61/23/8232} } +TIGRE-DE + +Keeler A, Lehmann M, Luce J, Kaur M, Roeske J, Kang H. Technical note: TIGRE-DE for the creation of virtual monoenergetic images from dual-energy cone-beam CT. Med Phys. 2024; 1-8. https://doi.org/10.1002/mp.17002 + +@article{https://doi.org/10.1002/mp.17002, +author = {Keeler, Andrew and Lehmann, Mathias and Luce, Jason and Kaur, Mandeep and Roeske, John and Kang, Hyejoo}, +title = {Technical note: TIGRE-DE for the creation of virtual monoenergetic images from dual-energy cone-beam CT}, +journal = {Medical Physics}, +keywords = {cone beam CT, dual-energy, spectral imaging}, +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} +} + End of Bib (leave this here) diff --git a/changelog.md b/changelog.md index 9a01afe8..66c8061f 100644 --- a/changelog.md +++ b/changelog.md @@ -9,7 +9,7 @@ thank you. ### Changed - MATLAB dual energy (`DeDecompose`, `MakeVMproj`, demo `d23_DualEnergy`) is now a plugin in - `MATLAB/Plugins/DualEnergy`, always on the path after `InitTIGRE` (nothing to compile). Python version to follow (#522). + `MATLAB/Plugins/DualEnergy`, always on the path after `InitTIGRE` (nothing to compile). - MATLAB proton CT is now a plugin in `MATLAB/Plugins/pCT` (CUDA code in `Common/CUDA/plugins/pCT`). Compile it with `Compile pCT` (or `Compile all` for TIGRE and every plugin); plain `Compile` still builds core TIGRE only. The intercept vector lengths are set with `Compile('pCT','-pct_pixel',0.5)` or `-pct_intercepts`, instead of @@ -41,6 +41,10 @@ thank you. them directly, e.g. `from _minTV import minTV`, now needs `from tigre.utilities.cuda_interface._minTV import minTV`. ### Added +- Python dual energy: `tigre.plugins.dual_energy.DeDecompose` and `MakeVMproj`, the same functions and options as in + MATLAB, with demo `d23_DualEnergy.py`, and a user-guide page for the plugin (#522). Always installed (pure Python); + the calibration and NIST tables stay in `Common/data` and are copied into the package when it is built. Its paper is + in the Python `TIGRE.bib` too (`TIGRE-DE`; the MATLAB entry was missing its closing brace). - Docs: a Plugins section in the user guide (what plugins are, how to build them, how to add one) and the proton CT plugin in the Python and MATLAB API reference. Its papers are in `TIGRE.bib` (`citeme('pCTCubicSpline')` in MATLAB). - Python proton CT: `tigre.plugins.pct.pCTCubicSpline`, the optimised proton radiographies MATLAB already had. diff --git a/docs/_ext/tigre_demos.py b/docs/_ext/tigre_demos.py index f6e721e6..80430fa3 100644 --- a/docs/_ext/tigre_demos.py +++ b/docs/_ext/tigre_demos.py @@ -38,7 +38,7 @@ def _m_path(m: str) -> str: # Demos that need data, hardware or packages a website build does not have # (d24 is a template: it needs your own curved-detector projections; pRad_demo # needs the proton CT plugin, which is not built by default). -NOT_RUN = {"d21_ScannerDataLoader.py", "d24_CurvedDetector.py", "d25_Pytorch.py", "pRad_demo.py"} +NOT_RUN = {"d21_ScannerDataLoader.py", "d23_DualEnergy.py", "d24_CurvedDetector.py", "d25_Pytorch.py", "pRad_demo.py"} # (folder, heading, intro, [(python file or None, MATLAB file or None, title, description)]) CATALOGUE = [ @@ -130,8 +130,9 @@ def _m_path(m: str) -> str: "See :doc:`/user-guide/gpus`."), ("d25_Pytorch.py", None, "Use TIGRE from PyTorch", "Differentiable TIGRE operators inside a learned reconstruction network."), - (None, "Plugins/DualEnergy/Demos/d23_DualEnergy.m", "Dual-energy CBCT", - "Material decomposition from two scans at different tube voltages."), + ("d23_DualEnergy.py", "Plugins/DualEnergy/Demos/d23_DualEnergy.m", "Dual-energy CBCT", + "Material decomposition from two scans at different tube voltages. " + "See :doc:`/user-guide/dual-energy`."), (None, "SophiaBeads_demo.m", "Real micro-CT data: SophiaBeads", "Reconstruct the SophiaBeads dataset, a tube of glass beads."), ("pRad_demo.py", "Plugins/pCT/Demos/pRad_demo.m", "Proton radiography", diff --git a/docs/api/matlab/plugins.md b/docs/api/matlab/plugins.md index 4c82edfd..181e4950 100644 --- a/docs/api/matlab/plugins.md +++ b/docs/api/matlab/plugins.md @@ -1,15 +1,16 @@ --- -og:description: "MATLAB reference for TIGRE's plugins: the proton CT plugin's optimised proton radiographies." +og:description: "MATLAB reference for TIGRE's plugins: the proton CT plugin's optimised proton radiographies and the dual-energy plugin's material decomposition." myst: html_meta: - description: "MATLAB reference for TIGRE's plugins: the proton CT plugin's optimised proton radiographies." + description: "MATLAB reference for TIGRE's plugins: the proton CT plugin's optimised proton radiographies and the dual-energy plugin's material decomposition." --- # MATLAB plugins Optional parts of TIGRE in `MATLAB/Plugins`; compiled plugins must be built first (see {doc}`/user-guide/plugins`). Proton CT: `Compile pCT`, see -{doc}`/user-guide/proton-ct`. +{doc}`/user-guide/proton-ct`. Dual energy: nothing to compile, see +{doc}`/user-guide/dual-energy`. ```{include} ../../_generated/matlab/plugins.md ``` diff --git a/docs/api/python/plugins.md b/docs/api/python/plugins.md index 41888f3e..3803d530 100644 --- a/docs/api/python/plugins.md +++ b/docs/api/python/plugins.md @@ -1,8 +1,8 @@ --- -og:description: "Python reference for TIGRE's plugins: the proton CT plugin's optimised proton radiographies." +og:description: "Python reference for TIGRE's plugins: the proton CT plugin's optimised proton radiographies and the dual-energy plugin's material decomposition." myst: html_meta: - description: "Python reference for TIGRE's plugins: the proton CT plugin's optimised proton radiographies." + description: "Python reference for TIGRE's plugins: the proton CT plugin's optimised proton radiographies and the dual-energy plugin's material decomposition." --- # Python plugins @@ -17,4 +17,13 @@ Proton CT Built with ``TIGRE_PLUGINS=pct``. See :doc:`/user-guide/proton-ct`. .. autofunction:: tigre.plugins.pct.pCTCubicSpline + +Dual energy +----------- + +Always installed. See :doc:`/user-guide/dual-energy`. + +.. autofunction:: tigre.plugins.dual_energy.DeDecompose + +.. autofunction:: tigre.plugins.dual_energy.MakeVMproj ``` diff --git a/docs/user-guide/dual-energy.md b/docs/user-guide/dual-energy.md new file mode 100644 index 00000000..14f296cd --- /dev/null +++ b/docs/user-guide/dual-energy.md @@ -0,0 +1,97 @@ +--- +og:description: "Dual-energy CBCT with TIGRE: decompose two scans into basis materials and reconstruct virtual monoenergetic images, in Python and MATLAB." +myst: + html_meta: + description: "Dual-energy CBCT with TIGRE: decompose two scans into basis materials and reconstruct virtual monoenergetic images, in Python and MATLAB." +--- + +# Dual-energy CBCT + +TIGRE includes a dual-energy plugin for Python and MATLAB. It takes two scans +of the same object at different tube voltages (for example 80 and 140 kV) and +makes **virtual monoenergetic (VM) images**: images as if the object had been +scanned with a single X-ray energy. The method is +[Keeler et al. (2024)](https://doi.org/10.1002/mp.17002); cite it if you use +the plugin. + +It works in three steps: + +1. `DeDecompose` pairs each high-kV projection with the low-kV projection at + the same angle, and maps every pixel pair to the thicknesses of two basis + materials (Al and PMMA by default) with calibrated third-degree + polynomials. +2. `MakeVMproj` combines the two thicknesses into the projection at one + energy, `mu1(E)·t1 + mu2(E)·t2`, with attenuation coefficients from NIST. +3. Any TIGRE algorithm reconstructs the VM projections. + +The plugin is plain Python and MATLAB code, so it needs no build and is always +there. It lives in `Python/tigre/plugins/dual_energy` and +`MATLAB/Plugins/DualEnergy`; its data (calibration and attenuation tables) is +in `Common/data`. The function reference is in the API pages +([Python](../api/python/plugins.md), [MATLAB](../api/matlab/plugins.md)). + +## Example + +::::{tab-set} +:sync-group: lang + +:::{tab-item} Python +:sync: python +```python +from tigre.plugins.dual_energy import DeDecompose, MakeVMproj +import tigre.algorithms as algs + +# proj_l, angles_l: low-kV scan; proj_h, angles_h: high-kV scan; same geo +Al_proj, PMMA_proj, angles = DeDecompose( + proj_l, angles_l, proj_h, angles_h, + scanner="VarianTrueBeam", kVl=80, kVh=140, material1="Al", material2="PMMA", +) +VM_proj = MakeVMproj(Al_proj, PMMA_proj, 60, material1="Al", material2="PMMA") # 60 keV +img = algs.fdk(VM_proj, geo, angles) +``` +::: + +:::{tab-item} MATLAB +:sync: matlab +```matlab +% proj_l, angles_l: low-kV scan; proj_h, angles_h: high-kV scan; same geo +[Al_proj, PMMA_proj, angles] = DeDecompose(proj_l, angles_l, proj_h, angles_h, ... + 'scanner', 'VarianTrueBeam', 'kVl', 80, 'kVh', 140, 'material1', 'Al', 'material2', 'PMMA'); +VM_proj = MakeVMproj(Al_proj, PMMA_proj, 60, 'material1', 'Al', 'material2', 'PMMA'); % 60 keV +img = FDK(VM_proj, geo, angles); +``` +::: +:::: + +The full demo is `d23_DualEnergy` (Python: `Python/demos/d23_DualEnergy.py`; +MATLAB: `MATLAB/Plugins/DualEnergy/Demos/d23_DualEnergy.m`). It loads two +Varian scans with `VarianDataLoader`; set its data paths to your own scans. + +## Matching the two scans + +The two scans rarely have projections at exactly the same angles. The +`interpolation` option sets how the low-kV projection at each high-kV angle is +found: + +| `interpolation` | Low-kV projection used | +|---|---| +| `'nearest'` (default) | The one with the closest angle. | +| `'linear'` | Linear interpolation between the closest ones on each side. | +| `'skip'` | Like `'nearest'`, but high-kV projections with no low-kV projection within `tolerance` radians (default: half the low-kV angular step) are left out. | + +Angles are compared modulo 2π. The returned angles are the high-kV angles +that were kept; reconstruct with those. + +## Calibration + +The thickness polynomials depend on the scanner and its spectra, so results +are only quantitative with a calibration for **your** scanner. TIGRE has +calibrations for one scanner, `VarianTrueBeam`, at 80/140 kV and 90/140 kV, +for Al and PMMA. Without `scanner`, `material1` or `material2`, the plugin +warns and uses these. + +To add a scanner, kV pair or material, add its nine coefficients per material +to `Common/data/dual_energy_calibrations.json` (the order of the terms is in +`DeDecompose`), and for a new material its attenuation coefficients to +`Common/data/NIST_material_attenuation.json`. Python and MATLAB both read these +files. Contributions are welcome: open a pull request. diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index 6ffc8dc3..4b59c385 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -132,6 +132,9 @@ Optional parts of TIGRE, outside the core toolbox. [](proton-ct.md) : The proton CT plugin: optimised proton radiographies. +[](dual-energy.md) +: The dual-energy plugin: virtual monoenergetic images from two scans. + ## Background [](further-reading.md) @@ -169,6 +172,7 @@ performance-tuning plugins proton-ct +dual-energy ``` ```{toctree} diff --git a/docs/user-guide/plugins.md b/docs/user-guide/plugins.md index 002c34ef..62ff54cf 100644 --- a/docs/user-guide/plugins.md +++ b/docs/user-guide/plugins.md @@ -15,6 +15,7 @@ both Python and MATLAB, with the same function names, like the rest of TIGRE. | Plugin | What it does | Compiled | Page | |---|---|---|---| | `pct` (Python), `pCT` (MATLAB) | Optimised proton radiographies from single-proton data | Yes (CUDA, NVIDIA GPUs) | [](proton-ct.md) | +| `dual_energy` (Python), `DualEnergy` (MATLAB) | Virtual monoenergetic images from dual-energy CBCT | No | [](dual-energy.md) | ## Building plugins @@ -75,6 +76,9 @@ A plugin can have its own build options; see its page. Data a plugin's demos need stays in the source folder (for proton CT, `MATLAB/Plugins/pCT/data/`) and is not installed. +Data the plugin itself needs at run time goes in `Common/data/`, read by +both languages; `setup.py` copies it into the Python package (as for the +dual-energy plugin's calibration tables). ## Adding a plugin diff --git a/pyproject.toml b/pyproject.toml index 3e6728d0..e8d8036b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -60,6 +60,7 @@ include = ["tigre*"] "tigre" = ["data/*.mat"] "tigre.utilities.cuda_interface" = ["*.pyx", "*.pxd", "*.pxi", "*.cpp"] "tigre.plugins.pct" = ["*.pyx"] +"tigre.plugins.dual_energy" = ["data/*.json"] [tool.cibuildwheel] build-frontend = "build[uv]" diff --git a/setup.py b/setup.py index e051c2d8..d22c01c4 100644 --- a/setup.py +++ b/setup.py @@ -696,6 +696,13 @@ def pct_intercepts(): ) ) +# Dual-energy plugin data: the single copy is in Common/data (MATLAB reads it there); copy it into +# the package so it is installed. The copies are git-ignored. From an sdist, Common/data is there too. +DUAL_ENERGY_DATA = ("dual_energy_calibrations.json", "NIST_material_attenuation.json") +os.makedirs(pjoin("Python", "tigre", "plugins", "dual_energy", "data"), exist_ok=True) +for name in DUAL_ENERGY_DATA: + shutil.copyfile(pjoin("Common", "data", name), pjoin("Python", "tigre", "plugins", "dual_energy", "data", name)) + setup( # Packages and package data are listed in pyproject.toml. include_package_data=True,