Metadata-Version: 2.4
Name: ctrecon
Version: 0.2.4
Summary: an interface and some tools for computed tomography reconstruction
Author-email: "J. Hoffman" <contact@jmh.lol>
Project-URL: Homepage, https://gitlab.com/hoffman-lab/ctrecon
Project-URL: Bug Tracker, https://gitlab.com/hoffman-lab/ctrecon/issues
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: numpy
Requires-Dist: matplotlib
Requires-Dist: pandas
Requires-Dist: fctpd
Requires-Dist: smcore

# 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

```bash
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:

```python
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](https://resources.jmh.lol/jmh-pub/hd-phantom.pdf) 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

```python
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 |

> [!NOTE]
> The default scan engine (`NaiveEngine`) currently only handles `Circle` and
> `Rectangle` primitives during ray-casting. `Ellipse` and `ForbildShape` can be
> rendered (via `phantom.render()`) but will fail during scanning. Support for
> all primitive types in the scan engine is planned.

---

### 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.

```python
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:

```python
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)](https://pypi.org/project/fctpd/) format:

```python
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

```python
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 |

```python
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:

```python
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.

```python
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`](https://gitlab.com/hoffman-lab/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](https://unlicense.org/) — public domain. Software _must_ be free.
Use it, modify it, extend it. If you find it useful, [please let me
know](mailto:ctrecon.filling860@slmail.me).  

If people could put rainbows in zoos, they would.

---

## Links

- [PyPI](https://pypi.org/project/ctrecon/)
