Metadata-Version: 2.4
Name: spectarf
Version: 0.1.0
Summary: Monte Carlo angular response functions (ARFs) and point-spread functions for parallel-hole SPECT, for PyTomography
License: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: scipy>=1.10
Requires-Dist: torch>=2.1
Requires-Dist: numba>=0.60
Provides-Extra: cuda
Requires-Dist: numba-cuda[cu12]>=0.30; extra == "cuda"
Provides-Extra: pytomography
Requires-Dist: pytomography>=3.4; extra == "pytomography"
Requires-Dist: pandas; extra == "pytomography"
Provides-Extra: test
Requires-Dist: pytest>=7; extra == "test"
Dynamic: license-file

# spectarf

Monte Carlo angular response functions (ARFs) and point-spread functions
(PSFs) for parallel-hole SPECT, for reconstruction in
[PyTomography](https://github.com/PyTomography/PyTomography).

> **Status: pre-release (0.0.1.dev0).** The package is being built; the API
> shown below is under construction and will change. It is a research tool,
> not a medical device.

## What it is

PyTomography's default model of the collimator and detector blur is a
Gaussian whose width grows linearly with distance. That model has no septal
penetration, no collimator scatter, no lead X-rays and no downscatter from
higher-energy lines, all of which shape the response at medium and high
photon energies: Lu-177 at 208 keV, In-111, I-131, and the Pb-212 and Ac-225
decay chains.

spectarf computes the response instead, by photon transport through the
collimator and detector. For one photon energy and one energy window, the ARF
is the probability that a photon arriving at the collimator face in direction
(θ, φ), at a uniformly random point of the hole lattice, is detected in the
window with its energy-weighted Anger centroid displaced by (dx, dy) from
where it entered. The package then turns the ARFs of an isotope's emission
lines into a 2D kernel at every plane distance of a reconstruction.

* **One dense ARF per emission line and energy window**, over (θ, φ, dx, dy).
  Every window a reconstruction uses (the photopeak and its TEW side windows)
  is scored from the same photon histories in one pass, with the window's
  exact bounds; the energy resolution enters as each event's exact acceptance
  in each window.
* **User-set bins**, non-uniform where the response is sharp. `suggest_grid`
  proposes a grid and a validator checks it.
* **A cache keyed on every input that changes the transport or the
  scoring.** An ARF is reused only when all of them match; a window that
  differs by 0.1 keV is a new ARF. The lattice orientation and the intrinsic
  blur act after scoring, so they are written into the returned ARF rather
  than keyed.
* **`psf_from_arf`**: ARFs and line yields in, one kernel per plane distance
  out, at the reconstruction's own pixel size, in counts per decay. No
  Gaussian assumption, no separability, no symmetrisation: the six-fold
  septal-penetration star is kept. It needs only numpy and torch.
* **TEW-consistent kernels.** `tew_combine` forms the combination of
  photopeak and side-window ARFs that matches what triple-energy-window
  scatter correction subtracts from the data.
* **The intrinsic blur is counted once.** A vendor's NEMA intrinsic
  resolution already contains the crystal's own positional spread, which the
  transport models; the package solves for the remaining light-centroid
  width and applies only that.
* **Geometry in SIMIND's parameterisation**: a collimator from SIMIND's
  collimator database by exact code, from a scanner preset that cites the
  vendor's datasheet, or from explicit numbers; an aluminium cover; a NaI(Tl)
  crystal; a homogeneous backscatter slab.
* **Isotopes as line lists** of (energy, photons per decay). `Nuclide.from_ddep`
  builds one from the evaluated data of DDEP, the Decay Data Evaluation
  Project, including X-rays and decay chains.
* **Transport engines behind one interface**: `fused-cuda` on NVIDIA GPUs
  `fused-cpu` (the same kernel compiled for CPU cores) and `torch` on any
  device torch supports. See [docs/hardware.md](docs/hardware.md).
* **Checks**: `simulate_point_source` runs the same transport from a point
  source, and `compare_psf` overlays the result with `psf_from_arf`'s kernel,
  tails included.

## What it is not

* **Not a Monte Carlo forward projector or a Monte Carlo reconstruction.**
  The kernels describe photons that were not scattered in the patient; the
  ARFs have no continuous energy axis, which a model of patient scatter would
  need. Patient scatter remains the job of TEW, estimated from the
  measurement.
* **Not for fan-beam, cone-beam, slant-hole or pinhole collimators.**
* **Not for pixelated CZT cameras**, whose response needs a model of pixel
  collection and charge sharing rather than an Anger centroid.
* **Not for bremsstrahlung imaging** (Y-90, P-32): DDEP lists no continuous
  photon spectrum.
* **Not an extension of SPECTPSFToolbox.** It is independent of it.
* **No graphical interface.**

## Installation

spectarf is not on PyPI yet. Until the first release, install it from a
clone of this repository with `pip install -e .`. Once released:

```bash
pip install spectarf                    # the fused-cpu and torch engines, any platform
pip install "spectarf[cuda]"            # adds the fused-cuda engine for NVIDIA GPUs
pip install "spectarf[pytomography]"    # adds PyTomography, for ArbitraryKernelPSFTransform
```

* Python 3.10 or later.
* The `[cuda]` extra installs numba-cuda with NVIDIA's pip CUDA wheels, so no
  CUDA toolkit or `nvcc` is needed; an NVIDIA driver is.
* For any GPU, install torch first by
  [PyTorch's own instructions](https://pytorch.org/get-started/locally/)
  (CUDA, ROCm, Apple MPS or Intel XPU), then install spectarf.

## Quick start

**API under construction.** The names follow the package's current interface
contract and may change before the first release.

```python
import numpy as np

from spectarf import DetectorStack
from spectarf.generate import generate_arf
from spectarf.geometry.presets import response_from_preset
from spectarf.nuclides import Nuclide
from spectarf.psf import psf_from_arf, tew_combine

# A scanner preset: collimator, crystal and NEMA resolutions from the vendor's
# datasheet (each value cited), in SIMIND's stack: 1 mm aluminium cover,
# NaI(Tl) crystal, homogeneous backscatter slab. Any field can be overridden,
# and a stack can also be built from a SIMIND database code or explicit numbers.
stack = DetectorStack.from_preset("NM670Pro-MEGP-3/8")
response = response_from_preset("NM670Pro-MEGP-3/8")

# Lu-177: photopeak window and its TEW side windows, in keV, as declared.
windows = {"P": (187.2, 228.8), "L": (166.4, 187.2), "U": (228.8, 249.6)}
lines = Nuclide.from_ddep("Lu-177").lines_for(windows, response.energy)

# One ARF per line and window. All windows are scored in one transport pass per
# line; the grid is suggested per line (or pass your own ArfGrid); every result
# is cached under a key built from all of these inputs.
arfs = generate_arf(stack, response, lines, windows)
# arfs["P"] is a list of (Arf, yield per decay) terms, one per emission line.

distances_mm = np.arange(2.4, 400.0, 4.8)             # plane distances to the face
k_peak = psf_from_arf(arfs["P"], distances_mm, pixel_mm=4.8, kernel_shape=(63, 63))
k_tew = psf_from_arf(tew_combine(arfs, windows), distances_mm,
                     pixel_mm=4.8, kernel_shape=(63, 63))
# k_*: torch tensors (n_distances, n_u, n_v) in counts per decay of the parent
# per pixel; u is the projection's transaxial axis, v its axial axis.
```

The kernels go into PyTomography's system matrix through an arbitrary-kernel
PSF transform, which applies one 2D kernel per plane by FFT and the true back
projection in `backward`. It computes the kernels itself, at the plane
distances of every view of the acquisition, from the same terms:

```python
from pytomography.projectors.SPECT import SPECTSystemMatrix
from spectarf.psf import ArbitraryKernelPSFTransform

psf = ArbitraryKernelPSFTransform(tew_combine(arfs, windows))   # or arfs["P"]
system_matrix = SPECTSystemMatrix(
    obj2obj_transforms=[attenuation_transform, psf],  # attenuation as usual
    proj2proj_transforms=[],
    object_meta=object_meta, proj_meta=proj_meta)
# psf.clipped_fraction: per distance, the share of a TEW kernel's tail clipped
# at zero (OSEM needs a non-negative system matrix).
```

This is a reference implementation tested against PyTomography 3.4.0; how
PyTomography v4 takes it over is being agreed with its maintainers.

## Limits

The full list is in [docs/limitations.md](docs/limitations.md). In short:

* The PSF is for photons not scattered in the patient; TEW's own errors in
  the patient remain.
* Window bounds are taken as declared, as true deposited energy. A DICOM
  window is on the camera's console energy axis; where that axis is offset or
  scaled from true energy, the modelled window is misplaced by the same
  amount. Enter corrected bounds if you know the offset.
* The rear of the camera is a homogeneous slab, as in SIMIND. Above about
  500 keV, where backscatter from the photomultipliers and the rear shielding
  forms peaks in the window, this is the model's weakest part.
* The intrinsic blur and the energy resolution are modelled as Gaussian.
* PyTomography applies attenuation along the ray normal to the detector,
  separately from the PSF, so oblique paths through the patient are
  approximated. That is a property of the analytic system matrix, not of the
  kernel.

## Data sources and their licensing

| Data | Source | Status |
|---|---|---|
| Collimator records | spectarf's own specification table, `collimators.csv`: the dimensions listed in SIMIND 9.0's collimator database `collim.col` (M. Ljungberg, Lund University), converted to mm | Bundled. The SIMIND file itself is not copied; a user's own `collim.col` (`$SMC_DIR`) or PyTomography's bundled copy can be read instead. |
| Collimator cross-check | OpenGATE's public SPECT head models (LGPL-3.0) | Published dimensions, with their source, are used only to audit the database records; no OpenGATE code or file is redistributed. |
| Scanner presets | Vendors' public datasheets | Each preset cites its source. |
| The backscatter slab's `pmt` material | SIMIND 9.0's `pmt.cr5`: a borosilicate glass, composition by weight and density as the file states them | Used as stated, with the source recorded. |
| Emission lines | DDEP recommended data, published by LNHB (CEA, France) through Nucléide-Lara | Freely available. The package ships DDEP's values, transcribed unmodified, for Lu-177, Tc-99m, In-111, I-131, Pb-203, Pb-212 and Ac-225 with their chains (`src/spectarf/data/ddep/`), each with its evaluation reference. Any other line list can be given by hand. See [docs/nuclides.md](docs/nuclides.md). |
| Photon cross sections | Up to 350 keV, Elam, Ravel and Sieber (2002) through xraydb; above, NIST XCOM 3.1; coherent form factors (Hubbell et al. 1975) and anomalous scattering factors from EPDL97 | Public data. The bundled table is generated by `tools/gen_xs_stack.py`, and its provenance is stored with it. |

## Validation

Every check uses analytic results, our own runs of public codes, or public
data. They are being built with the package, and their results will be
reported in the documentation as they pass.

* **Transport**: engines against each other, bin by bin, as a statistical
  test; narrow-beam transmission through lead and tungsten against
  Beer-Lambert; the geometric efficiency of a hexagonal collimator against
  the analytic formula.
* **Generation**: invariance to where the lattice cell is anchored, and
  robustness to the binning, from one set of photon histories scored into
  different grids.
* **`psf_from_arf`**: sensitivity preserved through interpolation and area
  rebinning; the low-energy FWHM against the geometric resolution.
* **End to end**: a point source simulated directly through the same
  transport against `psf_from_arf`'s kernel, out to the tails (Ac-225's
  440 keV line on medium- and high-energy collimators, Tc-99m on a LEHR
  collimator).
* **Other codes**: SIMIND 9.0 point sources in air, compared per collimator
  component (geometric and septal penetration) in
  [validation/simind/](validation/simind/README.md); GATE for the full response,
  collimator scatter included.
* **Reconstruction**: a public phantom with the Gaussian PSF and with the ARF
  PSF, both with TEW (tutorial 3).

## Documentation

The documentation is in [docs/](docs/index.md) and will be published on Read
the Docs. Tutorial outlines are in [tutorials/](tutorials/README.md). Where
development stands, and the open work: [docs/STATUS.md](docs/STATUS.md).

## Citation

spectarf has not been released or published yet. A citation, and a
`CITATION.cff` file, will come with the first release. In the meantime,
please cite this repository and PyTomography:

> L. A. Polson et al., PyTomography: A python library for medical image
> reconstruction, *SoftwareX* 29 (2025) 102020.

## Contributing and licence

See [CONTRIBUTING.md](CONTRIBUTING.md). spectarf is released under the MIT
licence ([LICENSE](LICENSE)). Data from external sources keep their own
terms, listed above.
