API Reference

diffct_mlx is the unified, auto-backend API most users should import. diffct_mlx.engine is the Torch/numba-CUDA engine it wraps on the Torch backend, a maintained copy of upstream diffct 2.5.2.

The unified package: diffct_mlx

Backend

diffct_mlx.backend selects the compute engine at import time (torch or mlx; override with DIFFCT_BACKEND). dct.backend is the chosen name. The backend-neutral array namespace diffct_mlx.backend.xp mirrors mlx.core on both engines and is what all shared reconstruction code is written against.

Conventions (diffct_mlx.conventions, re-exported at top level)

Since 3.0 every projector places detector pixel i at det_center + (i - (N-1)/2)·du and returns physical line integrals (µ · length). DETECTOR_CONVENTIONS is ("centered", "legacy") and LINE_INTEGRAL_UNITS is ("physical", "voxel"). The operator factories take detector_convention= and line_integrals=; kernel_detector_center(det_center, det_u_vec, du, det_v_vec, dv, convention="legacy") converts a 2.x detector centre for direct calls and line_integral_scale gives the unit factor. See Migrating from 2.x to 3.0.

Projector object (diffct_mlx.projector, re-exported at top level)

Projector(trajectory, volume_shape, detector_shape, *, beam, detector_spacing, voxel_spacing, projector_mode="siddon", precision="fast", detector_surface=None, view_chunk_size=None, volume_chunk_shape=None, detector_chunk_shape=None, devices=None, backend="auto", detector_convention="centered", line_integrals="physical", **engine_options) is a matched projector and backprojector with P(x) / P.project(x, trajectory=None), P.backproject(y), P.subset(views) and P.as_operator(). beam is one of BEAMS ("parallel", "fan", "cone", "parallel3d"), precision one of PRECISIONS. On the Torch backend the Siddon model runs on diffct_mlx.engine.Projector with all of its options, including float64, per-axis voxel_spacing in tensor order, parallel3d, ParameterizedSurface detectors and chunking. On MLX every option except multi-device execution works too, and in float32 at Metal speed: flat parallel, fan and cone beams with scalar spacing use the frame-based Metal kernels (P.path == "kernel"); per-axis spacing, parallel3d, detector surfaces and precision="float32" use the Metal ray kernels of diffct_mlx.backend.metal.rays ("rays"). Metal has no float64, so MLX works in float32; precision="float64" runs in float32 with a warning. Chunking by views, volume and detector blocks, leading batch dimensions and project_into / backproject_into (NumPy memmaps, zarr) work on both backends. project(x, trajectory=t, surface_parameters=p) gives MLX gradients for the trajectory and surface parameters. circular_trajectory_3d_parallel builds a parallel3d orbit on either backend.

Projectors (diffct_mlx.projectors, re-exported at top level)

Functional operators with identical signatures on both backends: parallel_forward / parallel_backward, fan_forward / fan_backward, cone_forward / cone_backward, and the separable-footprint variants *_forward_footprint / *_backward_footprint (cone_backward_footprint additionally accepts indices= for sparse region-of-interest evaluation). All flow gradients to their data. The Siddon forward projectors also flow exact gradients to the geometry arrays (ray_dir, src_pos, det_origin/det_center, det_u_vec, det_v_vec) on both backends. Footprint geometry gradients use finite differences on Torch; on MLX only the cone src_pos has one.

Geometry (diffct_mlx.geometry, re-exported at top level)

Trajectory generators: circular_trajectory_3d, spiral_trajectory_3d (helical), sinusoidal_trajectory_3d, saddle_trajectory_3d, random_trajectory_3d, custom_trajectory_3d, laminography_trajectory_3d, plus the 2D fan/parallel counterparts and load_arbitrary_cone_geometry_from_json for measured-scan geometry files.

Operator algebra (diffct_mlx.operators)

LinearOperator with A @ x, A.T, composition, sums and scaling; ProjectionOperator with .subset(views) for ordered-subset methods; builders make_parallel_2d_operator, make_fan_2d_operator, make_cone_3d_operator (choose projector_mode="siddon" or "footprint"). IdentityOperator, DiagonalOperator, FunctionOperator compose into pipelines; everything stays differentiable.

Functionals & denoisers (diffct_mlx.functionals, diffct_mlx.filters)

Objectives/regularizers/constraints: SquaredL2, Tikhonov, L1Norm, LpNorm, Huber, TotalVariation, AdaptiveWeightedTV, NonNegativity, Box, soft_threshold; edge-preserving denoisers Bilateral, Guided, Median, HistogramSparsity, Azimuthal, DictionarySparsity and RegularizerSequence for Plug-and-Play priors.

Reconstruction (diffct_mlx.reconstruction_algorithms, re-exported at top level)

Analytic: reconstruct_fbp / reconstruct_fdk (+ FBPParameters / FDKParameters) and reconstruct_case_fdk for a case’s quantitative physical FDK path. Iterative: reconstruct_sart / reconstruct_sirt (+ normalized SART), reconstruct_tv_pocs / reconstruct_asd_pocs / reconstruct_awtv_pocs, reconstruct_dart. Case builders bundling data + matched operators: build_parallel_2d_case, build_fan_2d_case, build_cone_3d_case, build_measured_cone_3d_case, build_npy_cone_3d_case. Solver registry: reconstruct(name, A, b, ...), register_algorithm, list_algorithms with landweber, cgls, pcg, ls / wls / rls / rwls, dls / rdls, mlem / osem, mltr.

Quantitative FDK and units

Cone-beam cases expose fdk_weight, fdk_filter and fdk_back_project when the active backend provides the physical FDK gather path. reconstruct_case_fdk(case) combines cosine weighting, trapezoidal per-view angular weights, a zero-padded physical ramp and the voxel-driven (SID/U)^2 backprojector; its result is attenuation in 1/mm.

Projectors return physical line integrals, so A @ x is already in µ · mm when x is in 1/mm. simulate_scan feeds them straight into the transmission and beam-hardening physics. Iterative reconstruction of a physical sinogram returns attenuation in 1/mm. Operators built with line_integrals="voxel" reproduce the 2.x voxel units; their to_physical attribute is the factor back to physical units.

Physics & simulation (diffct_mlx.physics)

Corrections: flat_field, ring_removal, bad_pixel_correction, beam_hardening_polynomial, detector_deblur, scatter_correction, mar_inpaint and the composable PreprocessingPipeline. Simulation: Spectrum, simulate_scan, apply_beam_hardening, add_poisson_noise; embedded spectrum library physics.spectra (tube_spectrum, material_attenuation, preset, 40–225 kVp).

Sinogram-domain tools (diffct_mlx.rebinning)

apply_parker_weighting (short scans), apply_offset_weighting (extended FOV), extend_truncation, fan_to_parallel, curved_to_flat / flat_to_curved.

Phantoms & calibration (diffct_mlx.phantoms, diffct_mlx.calibration)

shepp_logan_2d / shepp_logan_3d voxel phantoms; the analytic engine Ellipsoid / Phantom / shepp_logan_phantom with exact closed-form cone projections for ground truth. Self-calibration: estimate_center_of_rotation, refine_center_by_sharpness, apply_center_offset.

Out-of-core & multi-GPU (diffct_mlx.orchestration; CUDA only)

chunked_cone_forward / chunked_cone_backward / chunked_cone_fdk, chunked_sirt, chunked_os_sart, mgpu_cone_forward / mgpu_cone_backproject / mgpu_sirt, storage helpers open_memmap / open_zarr / set_out_of_core_dir / set_out_of_core_backend, and the shadow-geometry primitives row_range_for_zslab / slice_range_for_vband.

The Torch engine: diffct_mlx.engine

The engine is upstream diffct 2.5.2, vendored and maintained in DiffCT-MLX. Its modules can be used directly on the Torch backend:

  • diffct_mlx.engine.operators – Projector: chunked, streamed projection for parallel, fan, cone and parallel3d beams, per-axis voxel spacing, detector surfaces, batch dimensions and multiple GPUs

  • diffct_mlx.engine.backends – backend selection ("numba" native CUDA, "torch" portable on CPU, CUDA, ROCm and MPS) and precision="fast" | "float32" | "float64"

  • diffct_mlx.engine.projectors – PyTorch autograd.Function projectors and backprojectors with exact geometry gradients

  • diffct_mlx.engine.footprint – separable-footprint autograd Functions, including the sparse cone backprojection (DiffCT-MLX extension)

  • diffct_mlx.engine.geometry – trajectory generators for 2D and 3D scans

  • diffct_mlx.engine.analytical – ramp filter, cosine and Parker weights, voxel-driven FBP/FDK backprojection

  • diffct_mlx.engine.reconstruction and solvers – differentiable fbp, fdk, helical_fdk and cgls, sirt, tv_reconstruction

  • diffct_mlx.engine.surfaces – ParameterizedSurface for curved detectors

  • diffct_mlx.engine.kernels – numba-CUDA kernels for advanced users

  • diffct_mlx.engine.utils and constants – device helpers and launch constants

The upstream user documentation of the engine ships in docs/engine/ of the repository.

Projector

class diffct_mlx.engine.Projector(trajectory, volume_shape, detector_shape, *, beam='cone', detector_spacing=1.0, voxel_spacing=1.0, devices=None, distributed=False, process_group=None, detector_surface=None, volume_chunk_shape=None, view_chunk_size=None, detector_chunk_shape=None, schedule='auto', partition='views', backend='auto', precision='fast', partition_grid=None, native_volume_layout=False)[source]

Bases: object

Project floating tensors along parallel, fan, cone, or parallel3d trajectories.

A parallel trajectory is (ray_dir, det_origin, det_u) and a fan trajectory is (src_pos, det_center, det_u); each component has shape (views, 2). A cone trajectory is (src_pos, det_center, det_u, det_v) with components shaped (views, 3). A parallel3d trajectory is (ray_dir, det_center, det_u, det_v) with the same 3D component shapes; its infinite ray lines pass through detector pixels. Direction axes are unit vectors; parallel ray_dir and det_u and 3D detector det_u and det_v are orthogonal. Parallel3d rays can be oblique but must not be tangent to the detector plane. If no trajectory tensor requires gradients, the projector clones the geometry. Otherwise it keeps references, reads the current values at every call, and returns gradients for those tensors. Live default frames and overrides are checked on each call. project, backproject, __call__ and their *_into variants accept a keyword-only trajectory replacing all frames for that call. It must retain the constructor’s beam and view count; it is validated and snapshotted independently without replacing the default frames. Rebuild computed trajectories from trainable leaves on each optimization step. Second derivatives are available for volumes and sinograms, not for the geometry.

detector_surface(u, v) optionally supplies local (u, v, n) offsets for every pixel. It receives centred physical float64 grids on CPU and returns a floating-point tensor shaped (*detector_shape, 3) or (views, *detector_shape, 3). 3D normals are cross(det_u, det_v); 2D normals are (det_u_y, -det_u_x) with zero middle offsets. Offsets can be on CPU or CUDA in full-volume and streamed execution. World points expand on each compute device after view sharding. Native execution preserves the composition’s dtype promotion before converting complete coordinates to float32. The PyTorch backend uses the selected precision. The callback is sampled and validated on every call, with first-order gradients for captured PyTorch parameters. Omitting it preserves the flat detector.

ParameterizedSurface(sampler, parameters) instead samples only the selected global view IDs and detector rectangle. Its explicit parameters and trajectory values are snapshotted once per call, with batch-local first-order parameter gradients. detector_chunk_shape bounds pixel rectangles; their physical origins remain those of the full detector.

Volumes use (H, W) for parallel and fan beams and (D, H, W) for cone and parallel3d beams. Sinograms use (views, detectors) or (views, U, V). Any leading batch/channel dimensions are preserved. voxel_spacing is a positive scalar or a tuple in volume tensor order: (y, x) or (z, y, x). Physical coordinates retain the centred global volume frame. Results stay on the input device. precision="fast" and "float32" return float32; "float64" computes geometry, ray lengths and accumulations in float64. The selected backend, precision and dtype are public metadata.

backend="auto" selects the native "numba" backend for NVIDIA CUDA and fast precision with scalar or per-axis voxel spacing, except for hybrid partitions. Other configurations use portable "torch" execution on the input’s CPU or supported PyTorch accelerator. Explicit "numba" requires a compatible native configuration. Data torch.func transforms use portable operations while preserving selected metadata.

Native CPU inputs stream spatial tiles and view batches through CUDA. Native CUDA inputs retain the full-volume path when its additional working set fits every device; otherwise they stream too. volume_chunk_shape sets explicit spatial limits in tensor order; view_chunk_size sets an explicit view limit. Either forces native streaming. Native automatic sizing uses live free memory, reusable allocator cache and the observable per-process fraction ceiling, retaining 25% headroom. Automatic sizing compares fitting first-axis slabs and Cartesian blocks; view batches are at most 32 and shrink if needed. Older PyTorch without a public fraction getter cannot account for that ceiling. Concurrent external allocations can still cause an allocation error.

For the native backend, schedule="auto" selects spatial, view or bounded two-tile window order using estimated full-workload time from short native pilots, with estimated copy bytes breaking ties. The same orders can be requested with "spatial", "views" or "window"; capacity may require a serial spatial fallback. Streaming uses distinct upload, compute and download streams and two reusable host slots capped at 8 MiB each. Store reads and completed output drains are fragmented independently of the resident GPU tile size. last_execution_stats reports actual copy payloads, native launches/layouts, planned capacity and pilot metadata; it is None before execution, after errors, and on the uninstrumented native full-CUDA path. Each thread reads the report of its own last call; backward reports go to the thread that ran the forward call. Portable execution reports actual ray/tile pairs, store I/O, transfers and collective payloads, with conservative automatic chunks targeting 8 MiB work arrays. Explicit chunk hints take priority. Reports and selection caches retain metadata.

native_volume_layout=True makes native full-CUDA cone and parallel3d backprojections of unbatched inputs on a flat detector return (D, H, W) tensors with the kernels’ (W, H, D)-contiguous strides instead of contiguous copies; native projections accept such tensors without a copy. An iterative solver that keeps its volumes in this layout then avoids two whole-volume copies per normal-operator application on one device. The layout does not change the operator. Results from several local devices, curved detectors, batched inputs, streamed execution and the PyTorch backend still involve copies.

Full host volumes/sinograms stay on CPU; streamed native CUDA buffers are bounded by the chosen tile and view batch. Caller-owned CUDA data/results and CUDA work inside a supplied callback are outside this memory bound. Native local devices launch their view batches concurrently, but each device receives every owned volume tile, so host transfers limit the speedup. Local devices split views in list order. partition="views" returns rank-local projections and replicated backprojections. partition="space" assigns balanced first-axis slabs and returns replicated projections and owned backprojections. partition="hybrid" combines both with partition_grid=(view_ranks, space_ranks) and parent-group rank view_rank * space_world_size + space_rank. global_volume_shape is the constructor shape; volume_slice identifies the owned global slab, and volume_shape and local_volume_shape give its required tensor shape. Empty slabs are valid. Physical coordinates retain the global volume frame. For replicated outputs, count the loss once globally or divide each rank’s projection loss by space_world_size or backprojection loss by view_world_size. Geometry gradients already SUM over all parent ranks; do not apply an additional DDP reduction to them. Space ranks participate in backward even when their local input and geometry require no gradients.

backproject(sinogram, *, trajectory=None)[source]

Apply the matched adjoint to a tensor ending in projection_shape.

Cone sinograms use (views, U, V) order after any leading batch/channel dimensions. The result preserves those dimensions, uses selected precision and stays on sinogram.device. View ranks SUM bounded volume contributions; spatial ranks return only the owned volume_slice. Divide replicated losses by view_world_size.

backproject_into(sinogram, output, *, trajectory=None)[source]

Write the numerical adjoint into block output matching self.dtype.

Accepts tensors or stores with read/write/shape/dtype/flush metadata. Returns output after bounded view/pixel contributions complete.

property process_group

Process group of a distributed operator, or None for the default group.

Pass it as group= to collectives that combine per-rank results of this operator, so they use the same ranks as the operator.

project(volume, *, trajectory=None)[source]

Project a floating tensor ending in the owned volume_shape.

Leading batch/channel dimensions are preserved ahead of projection_shape. The result has the selected precision and stays on volume.device. View partitions own contiguous view slices; spatial ranks SUM their ray contributions and replicate the result. Portable execution supports CPU and PyTorch accelerator tensors; native execution uses NVIDIA CUDA and streams CPU data when needed.

project_into(volume, output, *, trajectory=None)[source]

Numerically project into supplied output matching self.dtype.

Returns output; no complete result is allocated. Direct tensors requiring autograd must be detached or used under torch.no_grad(). Known overlapping/read-only outputs are rejected before execution.

Core Projector Functions

class diffct_mlx.engine.ParallelProjectorFunction(*args, **kwargs)[source]

Bases: Function

Summary

PyTorch autograd function for differentiable 2D parallel beam forward projection.

Notes

Provides a differentiable interface to the CUDA-accelerated Siddon ray-tracing method with a cell-constant image basis for parallel beam CT geometry. The forward pass computes the sinogram from a 2D image using parallel beam geometry. The backward pass computes gradients using the adjoint backprojection operation. Requires NVIDIA CUDA hardware. Geometry tensors are moved to the image’s device; execution uses float32.

Examples

>>> import torch
>>> from diffct import ParallelProjectorFunction, circular_trajectory_2d_parallel
>>>
>>> image = torch.randn(128, 128, device='cuda', requires_grad=True)
>>> ray_dir, det_origin, det_u_vec = circular_trajectory_2d_parallel(180, device='cuda')
>>> sinogram = ParallelProjectorFunction.apply(image, ray_dir, det_origin, det_u_vec, 192, 1.0)
>>> sinogram.sum().backward()
>>> image.grad.shape
torch.Size([128, 128])
static backward(ctx, grad_sinogram)[source]

Define a formula for differentiating the operation with backward mode automatic differentiation.

This function is to be overridden by all subclasses. (Defining this function is equivalent to defining the vjp function.)

It must accept a context ctx as the first argument, followed by as many outputs as the forward() returned (None will be passed in for non tensor outputs of the forward function), and it should return as many tensors, as there were inputs to forward(). Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input. If an input is not a Tensor or is a Tensor not requiring grads, you can just pass None as a gradient for that input.

The strides of the gradients passed to backward() are undefined: they are not guaranteed to be contiguous or to match the strides of the corresponding forward outputs, so implementations must not assume a particular memory layout.

The context can be used to retrieve tensors saved during the forward pass. It also has an attribute ctx.needs_input_grad as a tuple of booleans representing whether each input needs gradient. E.g., backward() will have ctx.needs_input_grad[0] = True if the first input to forward() needs gradient computed w.r.t. the output.

static forward(ctx, image, ray_dir, det_origin, det_u_vec, num_detectors, detector_spacing=1.0, voxel_spacing=1.0)[source]

Compute the 2D parallel beam forward projection with arbitrary trajectories using CUDA acceleration.

Parameters:
  • image (torch.Tensor) – Floating-point CUDA image of shape (H, W), converted to float32 for execution.

  • ray_dir (torch.Tensor) – Ray direction unit vectors for each view, shape (n_views, 2).

  • det_origin (torch.Tensor) – Detector origin positions for each view, shape (n_views, 2), in physical units.

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors for each view, shape (n_views, 2).

  • num_detectors (int) – Number of detector elements in the sinogram (columns).

  • detector_spacing (float, optional) – Physical spacing between detector elements (default: 1.0).

  • voxel_spacing (float, optional) – Physical size of one voxel (in same units as detector_spacing, default: 1.0).

Returns:

sinogram – 2D tensor of shape (n_views, num_detectors) containing the forward projection (sinogram) on the same device as image.

Return type:

torch.Tensor

Notes

  • Geometry tensors are moved to the image’s CUDA device and converted to float32.

  • Data derivatives support higher orders; geometry derivatives are first-order only.

  • Supports arbitrary parallel beam geometries.

  • Uses cell-constant Siddon ray tracing.

Examples

>>> image = torch.randn(128, 128, device='cuda', requires_grad=True)
>>> ray_dir, det_origin, det_u_vec = circular_trajectory_2d_parallel(180, device='cuda')
>>> sinogram = ParallelProjectorFunction.apply(
...     image, ray_dir, det_origin, det_u_vec, 128, 1.0
... )
class diffct_mlx.engine.ParallelBackprojectorFunction(*args, **kwargs)[source]

Bases: Function

Summary

PyTorch autograd function for differentiable 2D parallel beam backprojection.

Notes

Provides a differentiable interface to the CUDA-accelerated Siddon ray-tracing method with a cell-constant image basis for parallel beam backprojection. The forward pass computes a 2D reconstruction from sinogram data using parallel beam backprojection, and the backward pass computes gradients via forward projection as the adjoint operation. Requires CUDA-capable hardware and consistent device placements.

Examples

>>> import torch
>>> from diffct import ParallelBackprojectorFunction, circular_trajectory_2d_parallel
>>>
>>> sinogram = torch.randn(180, 192, device='cuda', requires_grad=True)
>>> ray_dir, det_origin, det_u_vec = circular_trajectory_2d_parallel(180, device='cuda')
>>> image = ParallelBackprojectorFunction.apply(sinogram, ray_dir, det_origin, det_u_vec, 1.0, 128, 128)
>>> image.sum().backward()
>>> sinogram.grad.shape
torch.Size([180, 192])
static backward(ctx, grad_output)[source]

Define a formula for differentiating the operation with backward mode automatic differentiation.

This function is to be overridden by all subclasses. (Defining this function is equivalent to defining the vjp function.)

It must accept a context ctx as the first argument, followed by as many outputs as the forward() returned (None will be passed in for non tensor outputs of the forward function), and it should return as many tensors, as there were inputs to forward(). Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input. If an input is not a Tensor or is a Tensor not requiring grads, you can just pass None as a gradient for that input.

The strides of the gradients passed to backward() are undefined: they are not guaranteed to be contiguous or to match the strides of the corresponding forward outputs, so implementations must not assume a particular memory layout.

The context can be used to retrieve tensors saved during the forward pass. It also has an attribute ctx.needs_input_grad as a tuple of booleans representing whether each input needs gradient. E.g., backward() will have ctx.needs_input_grad[0] = True if the first input to forward() needs gradient computed w.r.t. the output.

static forward(ctx, sinogram, ray_dir, det_origin, det_u_vec, detector_spacing=1.0, H=128, W=128, voxel_spacing=1.0)[source]

Compute the 2D parallel beam backprojection with arbitrary trajectories using CUDA acceleration.

Parameters:
  • sinogram (torch.Tensor) – Floating-point CUDA sinogram of shape (n_views, num_detectors), converted to float32 for execution.

  • ray_dir (torch.Tensor) – Ray direction unit vectors for each view, shape (n_views, 2).

  • det_origin (torch.Tensor) – Detector origin positions for each view, shape (n_views, 2), in physical units.

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors for each view, shape (n_views, 2).

  • detector_spacing (float, optional) – Physical spacing between detector elements (default: 1.0).

  • H (int, optional) – Height of the output reconstruction image (default: 128).

  • W (int, optional) – Width of the output reconstruction image (default: 128).

  • voxel_spacing (float, optional) – Physical size of one voxel (in same units as detector_spacing, default: 1.0).

Returns:

reco – 2D tensor of shape (H, W) containing the reconstructed image on the same device as sinogram.

Return type:

torch.Tensor

Notes

  • Geometry tensors are moved to the sinogram’s CUDA device and converted to float32.

  • Data derivatives support higher orders; geometry derivatives are first-order only.

  • Supports arbitrary parallel beam geometries.

  • Uses the adjoint of cell-constant Siddon ray tracing.

Examples

>>> sinogram = torch.randn(180, 128, device='cuda', requires_grad=True)
>>> ray_dir, det_origin, det_u_vec = circular_trajectory_2d_parallel(180, device='cuda')
>>> reco = ParallelBackprojectorFunction.apply(
...     sinogram, ray_dir, det_origin, det_u_vec, 1.0, 128, 128
... )
class diffct_mlx.engine.FanProjectorFunction(*args, **kwargs)[source]

Bases: Function

Summary

PyTorch autograd function for differentiable 2D fan beam forward projection.

Notes

Provides a differentiable interface to the CUDA-accelerated Siddon ray-tracing method with a cell-constant image basis for fan beam geometry, where rays diverge from a point X-ray source to a linear detector array. The forward pass computes sinograms using divergent beam geometry, and the backward pass computes gradients via adjoint backprojection.

Examples

>>> import torch
>>> from diffct import FanProjectorFunction, circular_trajectory_2d_fan
>>>
>>> image = torch.randn(256, 256, device='cuda', requires_grad=True)
>>> src_pos, det_center, det_u_vec = circular_trajectory_2d_fan(360, sid=1000.0, sdd=1500.0, device='cuda')
>>> sinogram = FanProjectorFunction.apply(image, src_pos, det_center, det_u_vec, 512, 1.0)
>>> sinogram.sum().backward()
>>> image.grad.shape
torch.Size([256, 256])
static backward(ctx, grad_sinogram)[source]

Define a formula for differentiating the operation with backward mode automatic differentiation.

This function is to be overridden by all subclasses. (Defining this function is equivalent to defining the vjp function.)

It must accept a context ctx as the first argument, followed by as many outputs as the forward() returned (None will be passed in for non tensor outputs of the forward function), and it should return as many tensors, as there were inputs to forward(). Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input. If an input is not a Tensor or is a Tensor not requiring grads, you can just pass None as a gradient for that input.

The strides of the gradients passed to backward() are undefined: they are not guaranteed to be contiguous or to match the strides of the corresponding forward outputs, so implementations must not assume a particular memory layout.

The context can be used to retrieve tensors saved during the forward pass. It also has an attribute ctx.needs_input_grad as a tuple of booleans representing whether each input needs gradient. E.g., backward() will have ctx.needs_input_grad[0] = True if the first input to forward() needs gradient computed w.r.t. the output.

static forward(ctx, image, src_pos, det_center, det_u_vec, num_detectors, detector_spacing, voxel_spacing=1.0)[source]

Compute the 2D fan beam forward projection with arbitrary trajectories using CUDA acceleration.

Parameters:
  • image (torch.Tensor) – Floating-point CUDA image of shape (H, W), converted to float32 for execution.

  • src_pos (torch.Tensor) – Source positions for each view, shape (n_views, 2), in physical units.

  • det_center (torch.Tensor) – Detector center positions for each view, shape (n_views, 2), in physical units.

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors for each view, shape (n_views, 2).

  • num_detectors (int) – Number of detector elements in the sinogram (columns).

  • detector_spacing (float) – Physical spacing between detector elements.

  • voxel_spacing (float, optional) – Physical size of one voxel (in same units as detector_spacing, default: 1.0).

Returns:

sinogram – 2D tensor of shape (n_views, num_detectors) containing the fan beam sinogram on the same device as image.

Return type:

torch.Tensor

Notes

  • Geometry tensors are moved to the image’s CUDA device and converted to float32.

  • Data derivatives support higher orders; geometry derivatives are first-order only.

  • Supports arbitrary fan beam geometries.

  • Uses cell-constant Siddon ray tracing.

Examples

>>> image = torch.randn(256, 256, device='cuda', requires_grad=True)
>>> src_pos, det_center, det_u_vec = circular_trajectory_2d_fan(360, 1000.0, 1500.0, device='cuda')
>>> sinogram = FanProjectorFunction.apply(
...     image, src_pos, det_center, det_u_vec, 512, 1.0
... )
class diffct_mlx.engine.FanBackprojectorFunction(*args, **kwargs)[source]

Bases: Function

Summary

PyTorch autograd function for differentiable 2D fan beam backprojection.

Notes

Provides a differentiable interface to the CUDA-accelerated Siddon ray-tracing method with a cell-constant image basis for fan beam backprojection. Implements the adjoint of the fan beam projection operator, distributing sinogram values back into the reconstruction volume along divergent ray paths. The forward pass computes reconstruction from sinogram data, and the backward pass computes gradients via forward projection.

Examples

>>> import torch
>>> from diffct import FanBackprojectorFunction, circular_trajectory_2d_fan
>>>
>>> sinogram = torch.randn(360, 512, device='cuda', requires_grad=True)
>>> src_pos, det_center, det_u_vec = circular_trajectory_2d_fan(360, sid=1000.0, sdd=1500.0, device='cuda')
>>> image = FanBackprojectorFunction.apply(sinogram, src_pos, det_center, det_u_vec, 1.0, 256, 256)
>>> image.sum().backward()
>>> sinogram.grad.shape
torch.Size([360, 512])
static backward(ctx, grad_output)[source]

Define a formula for differentiating the operation with backward mode automatic differentiation.

This function is to be overridden by all subclasses. (Defining this function is equivalent to defining the vjp function.)

It must accept a context ctx as the first argument, followed by as many outputs as the forward() returned (None will be passed in for non tensor outputs of the forward function), and it should return as many tensors, as there were inputs to forward(). Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input. If an input is not a Tensor or is a Tensor not requiring grads, you can just pass None as a gradient for that input.

The strides of the gradients passed to backward() are undefined: they are not guaranteed to be contiguous or to match the strides of the corresponding forward outputs, so implementations must not assume a particular memory layout.

The context can be used to retrieve tensors saved during the forward pass. It also has an attribute ctx.needs_input_grad as a tuple of booleans representing whether each input needs gradient. E.g., backward() will have ctx.needs_input_grad[0] = True if the first input to forward() needs gradient computed w.r.t. the output.

static forward(ctx, sinogram, src_pos, det_center, det_u_vec, detector_spacing, H, W, voxel_spacing=1.0)[source]

Compute the 2D fan beam backprojection with arbitrary trajectories using CUDA acceleration.

Parameters:
  • sinogram (torch.Tensor) – Floating-point CUDA fan sinogram of shape (n_views, num_detectors), converted to float32 for execution.

  • src_pos (torch.Tensor) – Source positions for each view, shape (n_views, 2), in physical units.

  • det_center (torch.Tensor) – Detector center positions for each view, shape (n_views, 2), in physical units.

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors for each view, shape (n_views, 2).

  • detector_spacing (float) – Physical spacing between detector elements.

  • H (int) – Height of the output reconstruction image.

  • W (int) – Width of the output reconstruction image.

  • voxel_spacing (float, optional) – Physical size of one voxel (in same units as detector_spacing, default: 1.0).

Returns:

reco – 2D tensor of shape (H, W) containing the reconstructed image on the same device as sinogram.

Return type:

torch.Tensor

Notes

  • Geometry tensors are moved to the sinogram’s CUDA device and converted to float32.

  • Data derivatives support higher orders; geometry derivatives are first-order only.

  • Supports arbitrary fan beam geometries.

  • Uses the adjoint of cell-constant Siddon ray tracing.

Examples

>>> sinogram = torch.randn(360, 512, device='cuda', requires_grad=True)
>>> src_pos, det_center, det_u_vec = circular_trajectory_2d_fan(360, 1000.0, 1500.0, device='cuda')
>>> reco = FanBackprojectorFunction.apply(
...     sinogram, src_pos, det_center, det_u_vec, 1.0, 256, 256
... )
class diffct_mlx.engine.ConeProjectorFunction(*args, **kwargs)[source]

Bases: Function

Summary

PyTorch autograd function for differentiable 3D cone beam forward projection.

Notes

Provides a differentiable interface to the CUDA-accelerated Siddon ray-tracing method with a cell-constant voxel basis for 3D cone beam geometry. Rays emanate from a point X-ray source to a 2D detector array capturing volumetric projection data. The forward pass computes 3D projections, and the backward pass computes gradients via adjoint 3D backprojection. Requires significant GPU memory.

Examples

>>> import torch
>>> from diffct import ConeProjectorFunction, circular_trajectory_3d
>>>
>>> volume = torch.randn(128, 128, 128, device='cuda', requires_grad=True)
>>> src_pos, det_center, det_u_vec, det_v_vec = circular_trajectory_3d(360, sid=1000.0, sdd=1500.0, device='cuda')
>>> projections = ConeProjectorFunction.apply(
...     volume, src_pos, det_center, det_u_vec, det_v_vec, 256, 256, 1.0, 1.0
... )
>>> projections.sum().backward()
>>> volume.grad.shape
torch.Size([128, 128, 128])
static backward(ctx, grad_sinogram)[source]

Define a formula for differentiating the operation with backward mode automatic differentiation.

This function is to be overridden by all subclasses. (Defining this function is equivalent to defining the vjp function.)

It must accept a context ctx as the first argument, followed by as many outputs as the forward() returned (None will be passed in for non tensor outputs of the forward function), and it should return as many tensors, as there were inputs to forward(). Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input. If an input is not a Tensor or is a Tensor not requiring grads, you can just pass None as a gradient for that input.

The strides of the gradients passed to backward() are undefined: they are not guaranteed to be contiguous or to match the strides of the corresponding forward outputs, so implementations must not assume a particular memory layout.

The context can be used to retrieve tensors saved during the forward pass. It also has an attribute ctx.needs_input_grad as a tuple of booleans representing whether each input needs gradient. E.g., backward() will have ctx.needs_input_grad[0] = True if the first input to forward() needs gradient computed w.r.t. the output.

static forward(ctx, volume, src_pos, det_center, det_u_vec, det_v_vec, det_u, det_v, du, dv, voxel_spacing=1.0)[source]

Compute the 3D cone beam forward projection with arbitrary trajectories using CUDA acceleration.

Parameters:
  • volume (torch.Tensor) – Floating-point CUDA volume of shape (D, H, W), converted to float32 for execution.

  • src_pos (torch.Tensor) – Source positions for each view, shape (n_views, 3), in physical units.

  • det_center (torch.Tensor) – Detector center positions for each view, shape (n_views, 3), in physical units.

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors for each view, shape (n_views, 3).

  • det_v_vec (torch.Tensor) – Detector v-direction unit vectors for each view, shape (n_views, 3).

  • det_u (int) – Number of detector elements along the u-axis (width).

  • det_v (int) – Number of detector elements along the v-axis (height).

  • du (float) – Physical spacing between detector elements along the u-axis.

  • dv (float) – Physical spacing between detector elements along the v-axis.

  • voxel_spacing (float, optional) – Physical size of one voxel (in same units as positions, default: 1.0).

Returns:

sino – 3D tensor of shape (n_views, det_u, det_v) containing the cone beam projections on the same device as volume.

Return type:

torch.Tensor

Notes

  • Geometry tensors are moved to the volume’s CUDA device and converted to float32.

  • Data derivatives support higher orders; geometry derivatives are first-order only.

  • Supports arbitrary source and detector trajectories, not limited to circular orbits.

  • Uses cell-constant Siddon ray tracing.

Examples

>>> volume = torch.randn(128, 128, 128, device='cuda', requires_grad=True)
>>> # Create circular trajectory
>>> src_pos, det_center, det_u_vec, det_v_vec = circular_trajectory_3d(360, 1000.0, 1500.0, device='cuda')
>>> sino = ConeProjectorFunction.apply(
...     volume, src_pos, det_center, det_u_vec, det_v_vec, 256, 256, 1.0, 1.0
... )
class diffct_mlx.engine.ConeBackprojectorFunction(*args, **kwargs)[source]

Bases: Function

Summary

PyTorch autograd function for differentiable 3D cone beam backprojection.

Notes

Provides a differentiable interface to the CUDA-accelerated Siddon ray-tracing method with a cell-constant voxel basis for 3D cone beam backprojection. The forward pass computes a 3D reconstruction from cone beam projection data using backprojection as the adjoint operation. The backward pass computes gradients via 3D cone beam forward projection. Requires CUDA-capable hardware and consistent device placements.

This operation may be memory- and computationally-intensive due to 3D geometry. Consider using gradient checkpointing, smaller volumes, or distributed computing for large-scale applications, and ensure sufficient GPU memory is available.

Examples

>>> import torch
>>> from diffct import ConeBackprojectorFunction, circular_trajectory_3d
>>>
>>> projections = torch.randn(360, 256, 256, device='cuda', requires_grad=True)
>>> src_pos, det_center, det_u_vec, det_v_vec = circular_trajectory_3d(360, sid=1000.0, sdd=1500.0, device='cuda')
>>> volume = ConeBackprojectorFunction.apply(
...     projections, src_pos, det_center, det_u_vec, det_v_vec, 128, 128, 128, 1.0, 1.0
... )
>>> volume.sum().backward()
>>> projections.grad.shape
torch.Size([360, 256, 256])
static backward(ctx, grad_output)[source]

Define a formula for differentiating the operation with backward mode automatic differentiation.

This function is to be overridden by all subclasses. (Defining this function is equivalent to defining the vjp function.)

It must accept a context ctx as the first argument, followed by as many outputs as the forward() returned (None will be passed in for non tensor outputs of the forward function), and it should return as many tensors, as there were inputs to forward(). Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input. If an input is not a Tensor or is a Tensor not requiring grads, you can just pass None as a gradient for that input.

The strides of the gradients passed to backward() are undefined: they are not guaranteed to be contiguous or to match the strides of the corresponding forward outputs, so implementations must not assume a particular memory layout.

The context can be used to retrieve tensors saved during the forward pass. It also has an attribute ctx.needs_input_grad as a tuple of booleans representing whether each input needs gradient. E.g., backward() will have ctx.needs_input_grad[0] = True if the first input to forward() needs gradient computed w.r.t. the output.

static forward(ctx, sinogram, src_pos, det_center, det_u_vec, det_v_vec, D, H, W, du, dv, voxel_spacing=1.0, native_layout=False)[source]

Compute the 3D cone beam backprojection with arbitrary trajectories using CUDA acceleration.

Parameters:
  • sinogram (torch.Tensor) – Floating-point CUDA cone sinogram of shape (n_views, det_u, det_v), converted to float32 for execution.

  • src_pos (torch.Tensor) – Source positions for each view, shape (n_views, 3), in physical units.

  • det_center (torch.Tensor) – Detector center positions for each view, shape (n_views, 3), in physical units.

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors for each view, shape (n_views, 3).

  • det_v_vec (torch.Tensor) – Detector v-direction unit vectors for each view, shape (n_views, 3).

  • D (int) – Depth (z-dimension) of the output reconstruction volume.

  • H (int) – Height (y-dimension) of the output reconstruction volume.

  • W (int) – Width (x-dimension) of the output reconstruction volume.

  • du (float) – Physical spacing between detector elements along the u-axis.

  • dv (float) – Physical spacing between detector elements along the v-axis.

  • voxel_spacing (float, optional) – Physical size of one voxel (in same units as positions, default: 1.0).

  • native_layout (bool, optional) – If True, return a (D, H, W) tensor with the kernel’s native (W, H, D)-contiguous strides instead of a contiguous copy (default: False). Projections accept such tensors without a copy.

Returns:

vol – 3D tensor of shape (D, H, W) containing the reconstructed volume on the same device as sinogram.

Return type:

torch.Tensor

Notes

  • Geometry tensors are moved to the sinogram’s CUDA device and converted to float32.

  • Data derivatives support higher orders; geometry derivatives are first-order only.

  • Supports arbitrary source and detector trajectories.

  • Uses the adjoint of cell-constant Siddon ray tracing.

Examples

>>> projections = torch.randn(360, 256, 256, device='cuda', requires_grad=True)
>>> src_pos, det_center, det_u_vec, det_v_vec = circular_trajectory_3d(360, 1000.0, 1500.0, device='cuda')
>>> vol = ConeBackprojectorFunction.apply(
...     projections, src_pos, det_center, det_u_vec, det_v_vec, 128, 128, 128, 1.0, 1.0
... )

Geometry Helpers

3D trajectories

diffct_mlx.engine.geometry.circular_trajectory_3d(n_views, sid, sdd, start_angle=0.0, end_angle=None, device='cuda', dtype=torch.float32)[source]

Generate circular trajectory geometry for cone-beam CT.

Creates source and detector position matrices for a standard circular orbit around the z-axis, commonly used in cone-beam CT imaging.

Parameters:
  • n_views (int or torch.Tensor) – Number of projection views, or a nonempty finite floating angle vector in radians. Angle tensors preserve their dtype, device and autograd graph.

  • sid (float) – Source-to-Isocenter Distance (SID), in physical units.

  • sdd (float) – Source-to-Detector Distance (SDD), in physical units.

  • start_angle (float, optional) – Starting angle in radians (default: 0.0).

  • end_angle (float, optional) – Ending angle in radians (default: 2*pi, full rotation).

  • device (str or torch.device, optional) – Device for tensors (default: ‘cuda’).

  • dtype (torch.dtype, optional) – Data type for tensors (default: torch.float32).

Returns:

  • src_pos (torch.Tensor) – Source positions, shape (n_views, 3).

  • det_center (torch.Tensor) – Detector center positions, shape (n_views, 3).

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors, shape (n_views, 3).

  • det_v_vec (torch.Tensor) – Detector v-direction unit vectors, shape (n_views, 3).

Examples

>>> src_pos, det_center, det_u_vec, det_v_vec = circular_trajectory_3d(
...     n_views=360, sid=1000.0, sdd=1500.0, device='cuda'
... )
>>> print(src_pos.shape)  # (360, 3)
diffct_mlx.engine.geometry.random_trajectory_3d(n_views, sid_mean, sdd_mean, sid_std=0.0, pos_std=0.0, angle_std=0.0, device='cuda', dtype=torch.float32, seed=None)[source]

Generate random trajectory geometry for cone-beam CT.

Creates source and detector position matrices with random perturbations, useful for testing reconstruction with non-ideal trajectories or for simulating robotic C-arm systems with positioning uncertainties.

Parameters:
  • n_views (int) – Number of projection views.

  • sid_mean (float) – Mean Source-to-Isocenter Distance, in physical units.

  • sdd_mean (float) – Mean Source-to-Detector Distance, in physical units.

  • sid_std (float, optional) – Standard deviation for SID variations (default: 0.0).

  • pos_std (float, optional) – Standard deviation for random position offsets (default: 0.0).

  • angle_std (float, optional) – Standard deviation for angular perturbations in radians (default: 0.0).

  • device (str or torch.device, optional) – Device for tensors (default: ‘cuda’).

  • dtype (torch.dtype, optional) – Data type for tensors (default: torch.float32).

  • seed (int, optional) – Random seed for reproducibility (default: None). The noise comes from a private generator, so the global PyTorch random state is unchanged.

Returns:

  • src_pos (torch.Tensor) – Source positions, shape (n_views, 3).

  • det_center (torch.Tensor) – Detector center positions, shape (n_views, 3).

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors, shape (n_views, 3).

  • det_v_vec (torch.Tensor) – Detector v-direction unit vectors, shape (n_views, 3).

Examples

>>> # Generate random trajectory with 10% SID variation and 5mm position noise
>>> src_pos, det_center, det_u_vec, det_v_vec = random_trajectory_3d(
...     n_views=180, sid_mean=1000.0, sdd_mean=1500.0,
...     sid_std=100.0, pos_std=5.0, seed=42, device='cuda'
... )
diffct_mlx.engine.geometry.spiral_trajectory_3d(n_views, sid, sdd, z_range=100.0, n_turns=2.0, start_angle=0.0, device='cuda', dtype=torch.float32)[source]

Generate spiral (helical) trajectory geometry for cone-beam CT.

Creates a helical trajectory where the source moves in a spiral pattern around the z-axis, commonly used in helical CT scanners.

Parameters:
  • n_views (int) – Number of projection views.

  • sid (float) – Source-to-Isocenter Distance (SID), in physical units.

  • sdd (float) – Source-to-Detector Distance (SDD), in physical units.

  • z_range (float, optional) – Total z-axis range covered during the spiral (default: 100.0).

  • n_turns (float, optional) – Number of complete rotations (default: 2.0).

  • start_angle (float, optional) – Starting angle in radians (default: 0.0).

  • device (str or torch.device, optional) – Device for tensors (default: ‘cuda’).

  • dtype (torch.dtype, optional) – Data type for tensors (default: torch.float32).

Returns:

  • src_pos (torch.Tensor) – Source positions, shape (n_views, 3).

  • det_center (torch.Tensor) – Detector center positions, shape (n_views, 3).

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors, shape (n_views, 3).

  • det_v_vec (torch.Tensor) – Detector v-direction unit vectors, shape (n_views, 3).

Examples

>>> src_pos, det_center, det_u_vec, det_v_vec = spiral_trajectory_3d(
...     n_views=360, sid=1000.0, sdd=1500.0, z_range=200.0, n_turns=3.0
... )
diffct_mlx.engine.geometry.sinusoidal_trajectory_3d(n_views, sid, sdd, amplitude=50.0, frequency=2.0, start_angle=0.0, device='cuda', dtype=torch.float32)[source]

Generate sinusoidal trajectory geometry for cone-beam CT.

Creates a trajectory where the source follows a sinusoidal path in 3D space, with radial oscillations as it rotates around the z-axis.

Parameters:
  • n_views (int) – Number of projection views.

  • sid (float) – Mean Source-to-Isocenter Distance (SID), in physical units.

  • sdd (float) – Source-to-Detector Distance (SDD), in physical units.

  • amplitude (float, optional) – Amplitude of sinusoidal radial variation (default: 50.0).

  • frequency (float, optional) – Number of oscillation cycles per full rotation (default: 2.0).

  • start_angle (float, optional) – Starting angle in radians (default: 0.0).

  • device (str or torch.device, optional) – Device for tensors (default: ‘cuda’).

  • dtype (torch.dtype, optional) – Data type for tensors (default: torch.float32).

Returns:

  • src_pos (torch.Tensor) – Source positions, shape (n_views, 3).

  • det_center (torch.Tensor) – Detector center positions, shape (n_views, 3).

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors, shape (n_views, 3).

  • det_v_vec (torch.Tensor) – Detector v-direction unit vectors, shape (n_views, 3).

Examples

>>> src_pos, det_center, det_u_vec, det_v_vec = sinusoidal_trajectory_3d(
...     n_views=360, sid=1000.0, sdd=1500.0, amplitude=100.0, frequency=3.0
... )
diffct_mlx.engine.geometry.saddle_trajectory_3d(n_views, sid, sdd, z_amplitude=50.0, radial_amplitude=30.0, start_angle=0.0, device='cuda', dtype=torch.float32)[source]

Generate saddle-shaped trajectory geometry for cone-beam CT.

The source height varies with cos(2 * angle) and its radius varies with sin(2 * angle).

Parameters:
  • n_views (int) – Number of projection views.

  • sid (float) – Mean Source-to-Isocenter Distance (SID), in physical units.

  • sdd (float) – Source-to-Detector Distance (SDD), in physical units.

  • z_amplitude (float, optional) – Amplitude of z-axis variation (default: 50.0).

  • radial_amplitude (float, optional) – Amplitude of radial variation (default: 30.0).

  • start_angle (float, optional) – Starting angle in radians (default: 0.0).

  • device (str or torch.device, optional) – Device for tensors (default: ‘cuda’).

  • dtype (torch.dtype, optional) – Data type for tensors (default: torch.float32).

Returns:

  • src_pos (torch.Tensor) – Source positions, shape (n_views, 3).

  • det_center (torch.Tensor) – Detector center positions, shape (n_views, 3).

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors, shape (n_views, 3).

  • det_v_vec (torch.Tensor) – Detector v-direction unit vectors, shape (n_views, 3).

Examples

>>> src_pos, det_center, det_u_vec, det_v_vec = saddle_trajectory_3d(
...     n_views=360, sid=1000.0, sdd=1500.0, z_amplitude=80.0, radial_amplitude=50.0
... )
diffct_mlx.engine.geometry.custom_trajectory_3d(n_views, sid, sdd, source_path_fn: Callable[[Tensor, float], Tensor], start_angle=0.0, device='cuda', dtype=torch.float32)[source]

Generate custom trajectory geometry for cone-beam CT using user-defined function.

Creates a trajectory based on a user-provided function that defines the source position as a function of angle and SID.

Parameters:
  • n_views (int) – Number of projection views.

  • sid (float) – Source-to-Isocenter Distance (SID), in physical units.

  • sdd (float) – Source-to-Detector Distance (SDD), in physical units.

  • source_path_fn (Callable[[torch.Tensor, float], torch.Tensor]) – Function that takes (angles, sid) and returns source positions (n_views, 3). The function signature should be: f(angles: torch.Tensor, sid: float) -> torch.Tensor where angles has shape (n_views,) and output has shape (n_views, 3).

  • start_angle (float, optional) – Starting angle in radians (default: 0.0).

  • device (str or torch.device, optional) – Device for tensors (default: ‘cuda’).

  • dtype (torch.dtype, optional) – Data type for tensors (default: torch.float32).

Returns:

  • src_pos (torch.Tensor) – Source positions, shape (n_views, 3).

  • det_center (torch.Tensor) – Detector center positions, shape (n_views, 3).

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors, shape (n_views, 3).

  • det_v_vec (torch.Tensor) – Detector v-direction unit vectors, shape (n_views, 3).

Examples

>>> # Circular orbit with a two-lobe (figure-8) vertical motion
>>> def figure8_path(angles, sid):
...     src_pos = torch.zeros((len(angles), 3), device=angles.device, dtype=angles.dtype)
...     src_pos[:, 0] = -sid * torch.sin(angles)
...     src_pos[:, 1] = sid * torch.cos(angles)
...     src_pos[:, 2] = 50 * torch.sin(2 * angles)
...     return src_pos
>>>
>>> src_pos, det_center, det_u_vec, det_v_vec = custom_trajectory_3d(
...     n_views=360, sid=1000.0, sdd=1500.0, source_path_fn=figure8_path
... )

2D trajectories

diffct_mlx.engine.geometry.circular_trajectory_2d_parallel(n_views, detector_distance=0.0, start_angle=0.0, end_angle=None, device='cuda', dtype=torch.float32)[source]

Generate circular trajectory geometry for 2D parallel-beam CT.

Creates ray direction and detector position matrices for a standard circular scanning geometry, commonly used in 2D parallel-beam CT imaging.

Parameters:
  • n_views (int or torch.Tensor) – Number of projection views, or a nonempty finite floating angle vector in radians. Angle tensors preserve their dtype, device and autograd graph.

  • detector_distance (float, optional) – Transverse detector-origin offset along det_u (default: 0.0).

  • start_angle (float, optional) – Starting angle in radians (default: 0.0).

  • end_angle (float, optional) – Ending angle in radians (default: pi, half rotation for parallel beam).

  • device (str or torch.device, optional) – Device for tensors (default: ‘cuda’).

  • dtype (torch.dtype, optional) – Data type for tensors (default: torch.float32).

Returns:

  • ray_dir (torch.Tensor) – Ray direction unit vectors for each view, shape (n_views, 2).

  • det_origin (torch.Tensor) – Detector origin positions for each view, shape (n_views, 2).

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors for each view, shape (n_views, 2).

Examples

>>> ray_dir, det_origin, det_u_vec = circular_trajectory_2d_parallel(
...     n_views=180, device='cuda'
... )
>>> print(ray_dir.shape)  # (180, 2)
diffct_mlx.engine.geometry.sinusoidal_trajectory_2d_parallel(n_views, amplitude=50.0, frequency=2.0, start_angle=0.0, device='cuda', dtype=torch.float32)[source]

Generate sinusoidal trajectory geometry for 2D parallel-beam CT.

Creates a trajectory where the detector follows a sinusoidal path while maintaining parallel rays.

Parameters:
  • n_views (int) – Number of projection views.

  • amplitude (float, optional) – Amplitude of sinusoidal detector displacement (default: 50.0).

  • frequency (float, optional) – Number of oscillation cycles per rotation (default: 2.0).

  • start_angle (float, optional) – Starting angle in radians (default: 0.0).

  • device (str or torch.device, optional) – Device for tensors (default: ‘cuda’).

  • dtype (torch.dtype, optional) – Data type for tensors (default: torch.float32).

Returns:

  • ray_dir (torch.Tensor) – Ray direction unit vectors for each view, shape (n_views, 2).

  • det_origin (torch.Tensor) – Detector origin positions for each view, shape (n_views, 2).

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors for each view, shape (n_views, 2).

Examples

>>> ray_dir, det_origin, det_u_vec = sinusoidal_trajectory_2d_parallel(
...     n_views=180, amplitude=100.0, frequency=3.0
... )
diffct_mlx.engine.geometry.custom_trajectory_2d_parallel(n_views, ray_dir_fn: Callable[[Tensor], Tensor], det_origin_fn: Callable[[Tensor], Tensor], start_angle=0.0, device='cuda', dtype=torch.float32)[source]

Generate custom trajectory geometry for 2D parallel-beam CT using user-defined functions.

Creates a trajectory based on user-provided functions that define the ray direction and detector origin as functions of angle.

Parameters:
  • n_views (int) – Number of projection views.

  • ray_dir_fn (Callable[[torch.Tensor], torch.Tensor]) – Function that takes angles and returns ray directions (n_views, 2).

  • det_origin_fn (Callable[[torch.Tensor], torch.Tensor]) – Function that takes angles and returns detector origins (n_views, 2).

  • start_angle (float, optional) – Starting angle in radians (default: 0.0).

  • device (str or torch.device, optional) – Device for tensors (default: ‘cuda’).

  • dtype (torch.dtype, optional) – Data type for tensors (default: torch.float32).

Returns:

  • ray_dir (torch.Tensor) – Ray direction unit vectors for each view, shape (n_views, 2).

  • det_origin (torch.Tensor) – Detector origin positions for each view, shape (n_views, 2).

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors for each view, shape (n_views, 2).

Examples

>>> # Define custom trajectory functions
>>> def ray_dirs(angles):
...     dirs = torch.zeros((len(angles), 2), device=angles.device, dtype=angles.dtype)
...     dirs[:, 0] = torch.cos(angles)
...     dirs[:, 1] = torch.sin(angles)
...     return dirs
>>>
>>> def det_origins(angles):
...     origins = torch.zeros((len(angles), 2), device=angles.device, dtype=angles.dtype)
...     return origins
>>>
>>> ray_dir, det_origin, det_u_vec = custom_trajectory_2d_parallel(
...     n_views=180, ray_dir_fn=ray_dirs, det_origin_fn=det_origins
... )
diffct_mlx.engine.geometry.circular_trajectory_2d_fan(n_views, sid, sdd, start_angle=0.0, end_angle=None, device='cuda', dtype=torch.float32)[source]

Generate circular trajectory geometry for 2D fan-beam CT.

Creates source and detector position matrices for a standard circular orbit around the origin, commonly used in 2D fan-beam CT imaging.

Parameters:
  • n_views (int or torch.Tensor) – Number of projection views, or a nonempty finite floating angle vector in radians. Angle tensors preserve their dtype, device and autograd graph.

  • sid (float) – Source-to-Isocenter Distance (SID), in physical units.

  • sdd (float) – Source-to-Detector Distance (SDD), in physical units.

  • start_angle (float, optional) – Starting angle in radians (default: 0.0).

  • end_angle (float, optional) – Ending angle in radians (default: 2*pi, full rotation).

  • device (str or torch.device, optional) – Device for tensors (default: ‘cuda’).

  • dtype (torch.dtype, optional) – Data type for tensors (default: torch.float32).

Returns:

  • src_pos (torch.Tensor) – Source positions, shape (n_views, 2).

  • det_center (torch.Tensor) – Detector center positions, shape (n_views, 2).

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors, shape (n_views, 2).

Examples

>>> src_pos, det_center, det_u_vec = circular_trajectory_2d_fan(
...     n_views=360, sid=1000.0, sdd=1500.0, device='cuda'
... )
>>> print(src_pos.shape)  # (360, 2)
diffct_mlx.engine.geometry.sinusoidal_trajectory_2d_fan(n_views, sid, sdd, amplitude=50.0, frequency=2.0, start_angle=0.0, device='cuda', dtype=torch.float32)[source]

Generate sinusoidal trajectory geometry for 2D fan-beam CT.

Creates a trajectory where the source follows a sinusoidal path, with radial oscillations as it rotates around the origin.

Parameters:
  • n_views (int) – Number of projection views.

  • sid (float) – Mean Source-to-Isocenter Distance (SID), in physical units.

  • sdd (float) – Source-to-Detector Distance (SDD), in physical units.

  • amplitude (float, optional) – Amplitude of sinusoidal radial variation (default: 50.0).

  • frequency (float, optional) – Number of oscillation cycles per full rotation (default: 2.0).

  • start_angle (float, optional) – Starting angle in radians (default: 0.0).

  • device (str or torch.device, optional) – Device for tensors (default: ‘cuda’).

  • dtype (torch.dtype, optional) – Data type for tensors (default: torch.float32).

Returns:

  • src_pos (torch.Tensor) – Source positions, shape (n_views, 2).

  • det_center (torch.Tensor) – Detector center positions, shape (n_views, 2).

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors, shape (n_views, 2).

Examples

>>> src_pos, det_center, det_u_vec = sinusoidal_trajectory_2d_fan(
...     n_views=360, sid=1000.0, sdd=1500.0, amplitude=100.0, frequency=3.0
... )
diffct_mlx.engine.geometry.custom_trajectory_2d_fan(n_views, sid, sdd, source_path_fn: Callable[[Tensor, float], Tensor], start_angle=0.0, device='cuda', dtype=torch.float32)[source]

Generate custom trajectory geometry for 2D fan-beam CT using user-defined function.

Creates a trajectory based on a user-provided function that defines the source position as a function of angle and SID.

Parameters:
  • n_views (int) – Number of projection views.

  • sid (float) – Source-to-Isocenter Distance (SID), in physical units.

  • sdd (float) – Source-to-Detector Distance (SDD), in physical units.

  • source_path_fn (Callable[[torch.Tensor, float], torch.Tensor]) – Function that takes (angles, sid) and returns source positions (n_views, 2). The function signature should be: f(angles: torch.Tensor, sid: float) -> torch.Tensor where angles has shape (n_views,) and output has shape (n_views, 2).

  • start_angle (float, optional) – Starting angle in radians (default: 0.0).

  • device (str or torch.device, optional) – Device for tensors (default: ‘cuda’).

  • dtype (torch.dtype, optional) – Data type for tensors (default: torch.float32).

Returns:

  • src_pos (torch.Tensor) – Source positions, shape (n_views, 2).

  • det_center (torch.Tensor) – Detector center positions, shape (n_views, 2).

  • det_u_vec (torch.Tensor) – Detector u-direction unit vectors, shape (n_views, 2).

Examples

>>> # Define a custom elliptical trajectory
>>> def ellipse_path(angles, sid):
...     src_pos = torch.zeros((len(angles), 2), device=angles.device, dtype=angles.dtype)
...     src_pos[:, 0] = -sid * 1.5 * torch.sin(angles)  # wider in x
...     src_pos[:, 1] = sid * torch.cos(angles)
...     return src_pos
>>>
>>> src_pos, det_center, det_u_vec = custom_trajectory_2d_fan(
...     n_views=360, sid=1000.0, sdd=1500.0, source_path_fn=ellipse_path
... )

Analytical Reconstruction Helpers

These helpers build the per-view pre-weights, angle-integration weights, filter, and backprojection pieces of an analytical FBP / FDK pipeline. They are plain functions (no autograd state) and can be freely mixed with the autograd operators above. Every helper is trajectory-agnostic: it takes the same (src_pos, det_center, det_u_vec[, det_v_vec]) arrays that the projector / backprojector Functions consume, so the same code path works for circular and non-circular trajectories.

diffct_mlx.engine.analytical.detector_coordinates_1d(num_detectors, detector_spacing, detector_offset=0.0, device=None, dtype=torch.float32)[source]

Return detector cell centre coordinates along a 1D axis.

The convention matches the CUDA kernels: the detector array is centred, u[k] = (k - (num_detectors - 1) * 0.5) * detector_spacing + detector_offset.

diffct_mlx.engine.analytical.angular_integration_weights(angles, redundant_full_scan=True)[source]

Trapezoidal per-view integration weights for the analytical FBP/FDK sum.

For a full 2*pi scan, each redundant ray is sampled twice so the classical FBP/FDK formula carries a 1/2 redundancy factor. When redundant_full_scan=True (the default) this factor is baked into the returned weights: they sum to pi over a uniform full scan, which is exactly what a voxel-driven gather backprojector with the (sid/U)^2 weight needs to produce a unit-amplitude reconstruction.

Short scans retain their actual angular range; the Parker window handles their redundancy at the sinogram-filtering stage. Leave redundant_full_scan=True for automatic fan/cone scan classification. Setting it to False explicitly disables the full-turn 1/2 factor.

Angles are in radians and weights are returned in input order. For a short scan wrapped modulo 2*pi, the gap outside the acquisition must be clearly more than twice every other gap. If the sorted range looks like a full turn, that isolated gap marks the scan boundary instead. A full turn with a similarly large missing sector is ambiguous from angles alone. Pass continuous (unwrapped) angles to parker_weights. FP16 and BF16 angles are promoted to FP32; FP64 angles retain their precision.

diffct_mlx.engine.analytical.fan_cosine_weights(num_detectors, detector_spacing, sdd, detector_offset=0.0, device=None, dtype=torch.float32)[source]

Per-detector-cell cos(gamma) weight for fan-beam FBP.

cos(gamma) = sdd / sqrt(sdd^2 + u^2) where u is the in-plane detector coordinate. Multiplying the sinogram by this weight before the ramp filter compensates for the extra path length that off- principal-ray fans traverse.

diffct_mlx.engine.analytical.cone_cosine_weights(det_u, det_v, du, dv, sdd, detector_offset_u=0.0, detector_offset_v=0.0, device=None, dtype=torch.float32)[source]

Per-detector-cell cos(gamma_cone) weight for cone-beam FDK.

cos(gamma_cone) = sdd / sqrt(sdd^2 + u^2 + v^2). Returns a (det_u, det_v) tensor ready to broadcast across the view axis of a cone sinogram (n_views, det_u, det_v).

diffct_mlx.engine.analytical.parker_weights(angles, num_detectors, detector_spacing, sdd, detector_offset=0.0)[source]

Parker redundancy weights for a circular fan-beam short scan.

The formula follows Parker (1982): each ray at view beta and fan angle gamma is weighted by a smooth window that guarantees every ray contributes exactly once when integrated over the scan. For a full 2*pi scan this returns a constant 1 tensor (the usual redundancy 1/2 factor lives in angular_integration_weights instead).

Only meaningful for circular (fan-shaped) trajectories — when using non-circular trajectories you typically want either a constant weight (full-coverage) or a custom redundancy scheme. FP16 and BF16 angles are promoted to FP32; FP64 angles retain their precision.

diffct_mlx.engine.analytical.ramp_filter_1d(sinogram_tensor, dim=-1, sample_spacing=1.0, pad_factor=1, window=None, use_rfft=True)[source]

Apply a finite discrete Ram-Lak filter along dim using FFT.

The angular-frequency impulse response is h[0] = pi/2, h[k] = -2/(pi*k**2) for odd k, and zero for nonzero even k (Kak and Slaney, chapter 3, equation 61, scaled by 2*pi). Transforming this finite kernel preserves its small positive DC response and avoids the low-frequency bias of directly sampling abs(omega). pad_factor >= 2 gives linear convolution over the retained samples for an unwindowed filter.

Parameters:
  • sinogram_tensor (torch.Tensor) – Real-valued sinogram tensor.

  • dim (int, optional) – Axis along which to filter. Default -1.

  • sample_spacing (float, optional) – Physical spacing between detector samples along dim. The continuous ramp filter has units of 1/length, so the FFT output is rescaled by 1 / sample_spacing to respect physical units.

  • pad_factor (int, optional) – Zero-pad the signal to pad_factor * N along dim before the FFT to suppress circular-convolution wrap-around artifacts.

  • window (str or None, optional) – Frequency-domain apodization: None / "ram-lak" (unwindowed), "hann", "hamming", "cosine", or "shepp-logan".

  • use_rfft (bool, optional) – Use the real-valued FFT path when True (default).

diffct_mlx.engine.analytical.parallel_weighted_backproject(sinogram, ray_dir, det_origin, det_u_vec, detector_spacing, H, W, voxel_spacing=1.0)[source]

Voxel-driven parallel-beam FBP backprojection with analytical constant.

Runs the dedicated parallel-beam FBP gather kernel (one thread per output pixel, linear interpolation of the filtered sinogram, no distance weighting because parallel beam has no source) and multiplies by 1 / (2 * pi) so a unit-density disk reconstructs to amplitude 1.

Assumes the input sinogram has already been ramp-filtered with ramp_filter_1d and weighted by angular_integration_weights.

diffct_mlx.engine.analytical.fan_weighted_backproject(sinogram, src_pos, det_center, det_u_vec, detector_spacing, H, W, voxel_spacing=1.0, *, isocenter=None)[source]

Voxel-driven fan-beam FBP backprojection with analytical constant.

Runs the dedicated fan-beam FBP gather kernel (one thread per output pixel, (sid_n/U_n)^2 distance weighting, linear interpolation of the filtered sinogram), applying the analytical factor sdd_n / (2 * pi * sid_n) to each view so a unit-density disk reconstructs to amplitude 1. Both distances are measured in the detector-normal direction per view, so the helper reduces to the classical sdd/(2*pi*sid) on a circular orbit. isocenter is a physical coordinate pair; by default it is inferred from the source lines along detector normals. Supply it explicitly for an ambiguous or non-circular acquisition. Analytical FBP remains acquisition-specific.

diffct_mlx.engine.analytical.cone_weighted_backproject(sinogram, src_pos, det_center, det_u_vec, det_v_vec, D, H, W, du, dv, voxel_spacing=1.0, *, isocenter=None)[source]

Voxel-driven cone-beam FDK backprojection with analytical constant.

Runs the dedicated cone-beam FDK gather kernel (one thread per output voxel, (sid_n/U_n)^2 distance weighting, bilinear interpolation of the filtered sinogram), applying sdd_n/(2*pi*sid_n) to each view so a unit-density sphere reconstructs to amplitude 1. Both distances are measured in the per-view detector-normal direction, so the helper reduces to the classical sdd/(2*pi*sid) on a circular orbit. isocenter is a physical coordinate triple, inferred from source lines along detector normals by default. Supply it explicitly for an ambiguous or non-circular acquisition. FDK remains an approximation outside its circular-acquisition assumptions.

Ramp Filter Options

ramp_filter_1d is a generic 1D ramp filter used by every analytical reconstruction example. Its call signature is:

ramp_filter_1d(sinogram_tensor, dim=-1, sample_spacing=1.0,
               pad_factor=1, window=None, use_rfft=True)
sample_spacing

Physical detector-cell spacing along dim (e.g. du for the cone-beam case). The filter is rescaled by 1 / sample_spacing internally so the output is in physical units and the reconstruction amplitude stays calibrated when detector pitch changes. Pass 1.0 to reproduce sample-unit behaviour.

pad_factor

Zero-pad the signal to pad_factor * N samples along dim before the FFT. Common values:

  • 1 (default): no padding, fastest but prone to circular convolution wrap-around at the detector edges.

  • 2: recommended for cone-beam FDK, good trade-off.

  • 4: stricter padding for objects close to the detector edge.

window

Frequency-domain apodization multiplied onto the bare Ram-Lak ramp:

  • None or "ram-lak": unwindowed Ram-Lak, sharpest, highest noise.

  • "hann" / "hanning": Hann window, strong high-frequency suppression.

  • "hamming": slightly milder than Hann.

  • "cosine": half-cosine rolloff.

  • "shepp-logan": sinc rolloff, classical choice.

use_rfft

Use torch.fft.rfft / irfft when the input is real. Defaults to True; set to False only if you need the complex FFT path.

Analytical FBP / FDK architecture

Each of the three analytical backprojection helpers (parallel_weighted_backproject, fan_weighted_backproject, cone_weighted_backproject) dispatches to a dedicated voxel-driven gather kernel, separate from the Siddon-based ray-driven scatter kernels that drive autograd. The autograd kernels are the pure adjoints P^T of the forward projectors (no distance weighting, no magnification scale), so the autograd classes form self-consistent forward / backward adjoint pairs. The analytical helpers on top apply the appropriate FBP / FDK distance weighting and the analytical scale so the returned image is already amplitude-calibrated.

Scale factors applied inside the analytical helpers:

  • parallel_weighted_backproject multiplies by 1 / (2 * pi) (Fourier-convention constant; parallel beam has no source and no magnification so there is no (sid/U)^2 weight).

  • fan_weighted_backproject applies a per-voxel (sid_n / U_n)^2 weight inside the gather kernel and a sdd_mean / (2 * pi * sid_mean) scale on top.

  • cone_weighted_backproject applies a per-voxel (sid_n / U_n)^2 weight inside the gather kernel and a sdd_mean / (2 * pi * sid_mean) scale on top.

sid_n and U_n are measured in the per-view detector-normal direction. For a canonical circular orbit sid_n reduces to the classical scalar sid, and U_n to the classical sid + x * sin(beta) - y * cos(beta). For non-circular trajectories (spiral, saddle, random) the helpers keep working by computing the per-view quantities directly from the trajectory arrays; the result is the standard heuristic generalisation of FDK beyond the circle.

Utilities

class diffct_mlx.engine.utils.DeviceManager[source]

Utilities for managing PyTorch tensor devices.

static ensure_device(tensor, device)[source]

Ensure a tensor resides on a given device.

Parameters:
  • tensor (torch.Tensor) – Tensor to move.

  • device (torch.device) – Desired device.

Returns:

Tensor on the specified device. Unchanged if already on it.

Return type:

torch.Tensor

Examples

>>> DeviceManager.ensure_device(
...     torch.tensor([1, 2, 3]),
...     torch.device('cuda')
... )
tensor([1, 2, 3], device='cuda:0')
static get_device(tensor)[source]

Get the device of a PyTorch tensor.

Parameters:

tensor (torch.Tensor) – Tensor whose device to determine.

Returns:

Device of the tensor or CPU if unavailable.

Return type:

torch.device

Examples

>>> DeviceManager.get_device(torch.tensor([1, 2, 3]))
device(type='cpu')
class diffct_mlx.engine.utils.TorchCUDABridge[source]

Bridge between PyTorch tensors and Numba CUDA arrays.

static tensor_to_cuda_array(tensor)[source]

Convert a PyTorch CUDA tensor to a Numba CUDA DeviceNDArray.

Provides a zero-copy view of a detached PyTorch tensor as a Numba CUDA array, avoiding CPU data transfers. The returned array shares memory with the original tensor.

Parameters:

tensor (torch.Tensor) – PyTorch tensor on a CUDA device.

Returns:

Numba CUDA array view sharing memory with tensor.

Return type:

numba.cuda.cudadrv.devicearray.DeviceNDArray

Raises:

ValueError – If tensor is not on a CUDA device.

Examples

>>> t = torch.randn(10, device='cuda')
>>> arr = TorchCUDABridge.tensor_to_cuda_array(t)

Additional helper functions (prefixed with an underscore) remain available for advanced integrations that require direct control over CUDA streams.

Constants

diffct_mlx.engine.constants._DTYPE = <class 'numpy.float32'>

Default data type for numerical computations (numpy.float32).

diffct_mlx.engine.constants._TPB_2D = (16, 16)

(16, 16) = 256 threads.

Type:

CUDA threads-per-block for 2D kernels (parallel/fan beam)

diffct_mlx.engine.constants._TPB_3D = (8, 8, 8)

(8, 8, 8) = 512 threads.

Type:

CUDA threads-per-block for 3D kernels (cone beam)

diffct_mlx.engine.constants._FASTMATH_DECORATOR = <function _FASTMATH_DECORATOR>[source]

Create a fastmath CUDA dispatcher when a native kernel is defined.

diffct_mlx.engine.constants._INF = np.float32(inf)

Floating-point infinity in default data type.

diffct_mlx.engine.constants._EPSILON = np.float32(1e-06)

Small epsilon value for numerical comparisons to avoid division by zero.

These values mirror the defaults used by the CUDA kernels. They are exposed for power users who need to fine-tune launch parameters or numeric tolerances; most applications should rely on the defaults.

Reconstruction and Solvers

diffct_mlx.engine.fbp(sinogram, trajectory, volume_shape, angles, *, beam='parallel', detector_spacing=1.0, voxel_spacing=1.0, window='ram-lak', pad_factor=2, projection_weights=None, angular_weights=None, filter_response=None, short_scan=False, isocenter=None, backend='auto', precision='fast', devices=None, view_chunk_size=None, volume_chunk_shape=None, distributed=False, process_group=None, partition='views', partition_grid=None)[source]

Differentiable parallel/fan FBP for fixed flat-detector geometry.

sinogram is a floating tensor (views, bins); volume_shape is (H,W). angles are explicit unwrapped radians. Detector/voxel spacings share the trajectory’s physical unit. projection_weights and angular_weights replace the default cosine and angular quadrature, respectively. filter_response replaces the complete real rFFT multiplier, including its physical units; length is pad_factor*bins//2+1. Its use ignores window. These tensors retain autograd. short_scan=True adds Parker weighting before filtering for a circular fan scan with sufficient coverage. precision="fast" preserves native FP32 execution; "float32" and "float64" select PyTorch arithmetic in that dtype. Output is signed and stays on the input device. View/spatial chunks, local devices and views/space/hybrid rank ownership are supported. Provide full global geometry/angles and the owned view data in distributed mode. Geometry gradients are rejected. Use fbp_into() for numerical block stores.

diffct_mlx.engine.fdk(sinogram, trajectory, volume_shape, angles, *, detector_spacing=1.0, voxel_spacing=1.0, window='ram-lak', pad_factor=2, projection_weights=None, angular_weights=None, filter_response=None, short_scan=False, isocenter=None, backend='auto', precision='fast', devices=None, view_chunk_size=None, volume_chunk_shape=None, distributed=False, process_group=None, partition='views', partition_grid=None)[source]

Differentiable flat-detector FDK; fixed geometry, approximate inversion.

sinogram is (views,U,V); volume_shape is (D,H,W). Filtering runs along U. detector_spacing is a scalar or (du,dv). The explicit weight/filter overrides and short_scan follow fbp(). Precision/backend, chunking and ownership follow fbp(). Voxel spacing may be a scalar or (dz,dy,dx). The backward pass is the precise discrete interpolation transpose; it does not make FDK an exact inverse. Use helical_fdk() for slice-centered integration of an axial helix.

diffct_mlx.engine.helical_fdk(sinogram, trajectory, volume_shape, angles, *, isocenter, detector_spacing=1.0, voxel_spacing=1.0, window='ram-lak', pad_factor=2, projection_weights=None, view_weights=None, filter_response=None)[source]

Approximate axial helical FDK with one complete angular turn per slice.

Filters detector U once, then applies helical_view_weights() inside the analytical gather. isocenter is required in physical coordinates. Source heights and unwrapped angles must agree with the actual helix; finite scans must cover a full turn around every requested slice. view_weights replaces the complete (D,views) window/quadrature stage. Projection/filter replacements follow fbp(). Custom tensors retain autograd and are not normalized or clamped. Detector truncation is not corrected. This native-cone approximation does not implement cone-parallel rebinning, 3D conjugate weights or exact Katsevich inversion.

diffct_mlx.engine.cgls(operator, measurements, iterations=30, *, x0=None, rtol=1e-06, atol=0.0, callback=None, checkpoint_directory=None, resume=None)[source]

CGLS with a total iteration target, including resumed iterations.

Callbacks observe a read-only iterate. Changed contents or device raise ValueError before another numerical call or a successful return. Callbacks must also leave the operator and measurements unchanged.

diffct_mlx.engine.sirt(operator, measurements, iterations=100, *, x0=None, rtol=1e-06, atol=0.0, callback=None, checkpoint_directory=None, resume=None, relaxation=1.0, nonnegative=True)[source]

Row/column-normalized SIRT, with optional nonnegative iterates.

diffct_mlx.engine.tv_reconstruction(operator, measurements, iterations=100, weight=1.0, lr=0.1, *, x0=None, rtol=1e-06, atol=0.0, callback=None, checkpoint_directory=None, resume=None)[source]

Adam on half the global mean squared data error plus physical mean TV.

Usage Notes

  • The autograd Functions run the native kernels on CUDA tensors. Projector with backend="torch" also runs on CPU, MPS and ROCm tensors, and the unified diffct_mlx Siddon projectors pick that path automatically for non-CUDA tensors.

  • Geometry helper functions build the ray_dir, det_origin, and detector orientation vectors expected by the projector operators.

  • Gradients flow through both forward and backward passes; set requires_grad=True on inputs that participate in optimisation loops.

  • Ensure tensors are contiguous and use consistent dtype (torch.float32) for maximum kernel performance.