Skip to main content

ctrecon

An interface and some tools for computed tomography reconstruction.

This software aims to provide a stable interface to the conceptual ideas of CT scanning rather than attempting to maximize performance.

This is still currently under active development. If you use it, you will encounter bugs. Stable interfaces are discovered not designed, so while development continues there may be tweaks and changes that occur. Your patience and feedback are appreciated.

We currently are only attempting 2D scanning and reconstruction. The interfaces should scale, however we'll address that as time allows and need requires.

The Mental Model

ctrecon aims to describe the CT pipeline: phantom → scanner → sinogram → reconstruction → image.

It is organized into four modules mirroring the physical computed tomography process:

Module Role
phantoms Objects to scan — prebuilt or custom
scanners Scanner geometries, scan protocols, and basic ray-casting engines
recon Reconstruction algorithms and a workspace for managing results
points Spatial descriptions of where reconstructed values live (grids, profiles, …)

Think of it as describing your experiment in code. The same interface should feel whether you're testing a quick idea or running a research-grade simulation.

Installation

pip install ctrecon

Requires Python ≥ 3.9. Dependencies: numpy, matplotlib, pandas, fctpd, smcore.

Quick Start

The minimum code to go from phantom to reconstructed image:

from ctrecon import phantoms, scanners, recon, points

# 1. Create a phantom
ph = phantoms.Debug()

# 2. Configure a scanner
scanner = scanners.ParallelBeam(
    r_si_cm=59.5, r_sd_cm=109.5,
    n_channels=512, det_size_cm=30/512
)

# 3. Scan it (defaults suffice)
scan_result = scanner.scan(ph)

# 4. Open a reconstruction workspace
wksp = recon.Workspace(scan_result)

# 5. Define where to reconstruct
grid = points.IsoGrid2D(cx=0, cy=0, fov=30, N=256)

# 6. Run filtered backprojection
result = wksp.recon(grid, recon.FBPEngine(), id="fbp")

# 7. Format and display
X, Y, img = result.points.format(result.recon)
import matplotlib.pyplot as plt
plt.pcolormesh(X, Y, img, cmap="gray", vmin=0)
plt.show()

Every step above can be configured in detail. The rest of this README shows how.


The Scan Pipeline in Detail

Phantoms

A phantom is a collection of geometric primitives, each with an attenuation coefficient. During scanning, we ray march through these shapes to compute line integrals.

Prebuilt Phantoms

Phantom Description
phantoms.Debug() Simple test phantom with a background circle and two inserts
phantoms.SheppLogan(mu_water=None) Standard Shepp-Logan head phantom (renderable; scanning support pending)
phantoms.ForbildHead(mu_water=None, mu_bone=None) FORBILD Head phantom (PMB 2012) with clipped ellipses (renderable; scanning support pending)
phantoms.HD() The HD phantom with a ring of inserts (known bug: does not set internal object list)
phantoms.WanderingLinePair(cx, cy, spatial_frequency, orientation, ...) Line-pair phantom for MTF/resolution testing
phantoms.BinaryCode(bits, obj_size, ...) Encodes a bit sequence as circles for decoding experiments (known bug: does not set internal object list)

All phantoms support:

  • .render(cx, cy, fov, dim) — render the phantom as a 2D image tuple (X, Y, img)
  • .sample(points) — sample exact attenuation values at arbitrary Points locations
  • .label() — return a human-readable identifier

Building Your Own Phantom

from ctrecon import phantoms
from ctrecon.primitives import Circle

class MyPhantom(phantoms.Phantom):
    def __init__(self):
        elements = [
            Circle(0, 0, 10.0, 0.0192),   # background
            Circle(0, 5, 3.0, 0.04),       # insert 1
            Circle(5, 0, 1.5, 0.04),       # insert 2
        ]
        # Order matters: list is processed last-to-first (foreground overwrites background)
        elements.reverse()
        self.objects = elements

    def label(self):
        return "my-phantom"

Available Primitives

Primitive Description
Circle(cx, cy, r, attenuation) Circle with uniform attenuation
Rectangle(cx, cy, w, h, angle, attenuation) Rotated rectangle
Ellipse(cx, cy, wx, wy, angle, attenuation) Rotated ellipse (wx, wy are full widths)
ForbildShape(cx, cy, a, b, phi_deg, rho, clips) Ellipse with optional clipping planes; supports additive (not overwriting) density

Scanners

A scanner defines the geometry between X-ray source and detector. It translates a Protocol (scan intent) into concrete rays and produces a ScanResult.

Available Scanners

Scanner Description
scanners.ParallelBeam(r_si_cm, r_sd_cm, n_channels, det_size_cm, offset=0.0) Parallel (pencil) beam — 1st-gen CT geometry
scanners.ClinicalPencilBeam() Preconfigured with UCLA-like clinical geometry (50 cm FOV, 736 detectors) (available via from ctrecon.scanners.clinical_pencil_beam import ClinicalPencilBeam)

Circular fan-beam geometry is defined in the spec (specs.CircularFanBeam) but not yet implemented as a scanner.

Protocols

A protocol describes how the scanner is used: how many projections, at what angles.

from ctrecon.scanners import Protocol
import numpy as np

# Uniform 360° scan with 360 projections
prot = Protocol.uniform(0, 2 * np.pi, proj_per_rotation=360)

Scanners should provide a default_protocol(), so you can usually just call:

scan_result = scanner.scan(ph)

and get reasonable defaults.

ScanResult

Although the projection data/sinogram is the core essence of a CT scan, the metadata associated with it is equally as important. To capture and hold this data, we use a class called a ScanResult. This is analogous to what would be exported from a clinical CT system.

scanner.scan() returns a ScanResult dataclass containing:

  • sinogram — the raw projection data (2D ndarray: views × detectors)
  • scanner — the scanner that produced the data
  • protocol — the protocol that was used
  • telemetry — per-view metadata (e.g. photon counts, timing)
  • id, tags — user-defined identifiers

Accessors like scan_result.must_get_sinogram() raise clear errors if data is missing.

Persistence: ScanResults can be saved and loaded via the FPB (FreeCT Projection Binary) format:

scan_result.save("my_scan.fpb")
loaded = scanners.ScanResult.from_fpb("my_scan.fpb")

Reconstruction

Reconstruction is managed through a Workspace, which ties a ScanResult to one or more reconstruction attempts and caches the results.

Workspace

wksp = recon.Workspace(scan_result)

# Perform a reconstruction
result = wksp.recon(grid, recon.FBPEngine(), id="my-fbp")

# List all reconstructions in the workspace
wksp.ls()

# Retrieve a specific reconstruction by ID
rec = wksp.get("my-fbp")

# Access as a timeline (oldest first)
rec = wksp[-1]

# Export to pandas DataFrame
df = wksp.to_df()

Reconstruction Engines

Engine Description
recon.BackprojectionEngine() Basic (unfiltered) backprojection — useful for understanding the blur
recon.FBPEngine() Filtered backprojection with ramp filtering and 2× sinogram upsampling

Both engines only support ParallelBeam scanner geometry at this time. They are designed to be independent and swappable — adding a new algorithm means implementing ReconEngine.compute().

Points — Where Values Live

The points module describes where reconstructed attenuation values live in space. Reconstruction engines return a flat array of values; Points knows how to reshape them into an "image". Although most folks will be concerned with simple, standard isotropic grids (see IsoGrid2D below), images can be much richer than that basic description.

Class Description
points.IsoGrid2D(cx, cy, fov, N) Standard isotropic 2D pixel grid
points.Profile(points) 1D line of sample locations (for line profiles / MTF analysis)
points.Profile.uniform(pt1, pt2, num) Uniformly spaced profile between two points
grid = points.IsoGrid2D(cx=0, cy=0, fov=30, N=256)

# After reconstruction:
X, Y, img = grid.format(result.recon)

# Sample an existing reconstruction at arbitrary locations:
profile = points.Profile.uniform((-5, 0), (5, 0), num=200)
line_values = grid.sample(result.recon, profile)

Noise Simulation

I'd like to work on extending our simulation to also provide a basic description of dose and a richer, more physically-accurate Monte Carlo simulation, however for now ctrecon only includes a crude Monte Carlo photon-counting noise model:

from ctrecon.tools import add_noise

noisy_sino = add_noise(scan_result.sinogram, n_photons=10000)

Higher n_photons → less noise. The model treats exp(-μ) as the per-photon transmission probability and computes measured attenuation from photon counts. It is approximate but sufficient for exploring noise effects on reconstruction quality.

For large sinograms, a multiprocessing version (add_noise_mp) is used automatically when n_photons > 1000.


Spec Objects

Scanner geometries are described by frozen specs dataclasses that act as a standardized contract between scanning and reconstruction:

Spec Description
specs.ParallelBeam Source-detector distances, channel count, channel width, offset
specs.CircularFanBeam Same base fields + fan angle increment

These are exposed via scanner.spec and used internally by reconstruction engines.


Extending the Package

Adding a New Scanner

Inherit from Scanner and implement:

  • generate_views(protocol) → Generator[View, None, None]
  • default_protocol() → Protocol
  • default_engine() → ScanEngine
  • Set self.spec to an appropriate specs dataclass

Adding a New Reconstruction Algorithm

Inherit from recon.ReconEngine and implement:

  • supports(scan) → bool — can this engine handle this scan's geometry?
  • compute(scan, points, cache) → (np.ndarray, dict) — return attenuation values and a log dict

Adding a New Scan Engine

A richer simulation engine beyond simple ray marching would be very desirable! Alas, time has not permitted this just yet.

To add a new engine though the gist is to inherit from scanners.ScanEngine and implement:

  • compute_transit(phantom, ray_origins, ray_directions) → (np.ndarray, dict)

The default engine (NaiveEngine) marches rays with a configurable step size. Swap it out for GPU acceleration, analytical ray-shape intersection, etc.

eng = scanners.NaiveEngine()
eng.configure(step_size=0.01, max_dist=109.5)
scan_result = scanner.scan(ph, engine=eng)

Adding a New Points Layout

Inherit from points.Points and implement:

  • points() → np.ndarray of shape (N, 2) or (N, 3)
  • logical_shape() → tuple describing the output array shape
  • format(values, uv) → reshape flat values into a displayable structure
  • sample(values, points) → interpolate values at new locations

Interactive Examples

The companion repository ctrecon-examples contains a Marimo notebook that walks through the full pipeline with inline explanations.

The test/ directory in this repository also contains runnable scripts for each phantom type and reconstruction path. These are not unit tests per say, but rather interactive sanity checks for human users. I'm really bad about ensuring tests are running and stay in perfect sync with the rest of the code, so please anticipate occasional bugs.


License

UNLICENSE — public domain. Software must be free. Use it, modify it, extend it. If you find it useful, please let me know.

If people could put rainbows in zoos, they would.


Metadata

Release files for ctrecon 0.2.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ctrecon 0.2.4
File Size Uploaded Provenance Actions
ctrecon-0.2.4.tar.gz 50.0 kB Without provenance Details for ctrecon-0.2.4.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ctrecon 0.2.4
File Interpreter ABI Platform Actions
ctrecon-0.2.4-py3-none-any.whl Python 3 none any Details for ctrecon-0.2.4-py3-none-any.whl

Total release size: 100.2 kB

Release files / ctrecon-0.2.4.tar.gz

Download URL ctrecon-0.2.4.tar.gz
Size 50.0 kB
Tags Source
SHA-256 checksum
How to use checksums
235a55270089fdc56e51da1d410d7704a2083c7f4c207eae9db4e1eaab55eff7
BLAKE2b-256 checksum
How to use checksums
166ffe54d25e8b50a2b85dcc2787451b5a594403c05a00b550285ba7bb407b65
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.7

Release files / ctrecon-0.2.4-py3-none-any.whl

Download URL ctrecon-0.2.4-py3-none-any.whl
Size 50.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ae153c290219b81cf9aa7a36b3ab59b326f99ed42d88d99eae8e08267c52b4b9
BLAKE2b-256 checksum
How to use checksums
185ae08827795918fecc65dfb7d74a15feada061d94cdeb786a109b2d76f83af
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.7

Security for ctrecon 0.2.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page