Skip to main content

High-performance FITS I/O for PyTorch

Project description

torchfits

PyPI Wheels CI Python 3.10+ License: GPL-2.0

torchfits reads and writes FITS files directly as PyTorch tensors on CPU, CUDA, or Apple Silicon MPS. It is built on a multi-threaded C++ engine with vendored CFITSIO and covers the same ground as astropy.io.fits, fitsio, healpy, healsparse, and astropy.wcs—but with native tensor output and no intermediate NumPy copies.

At a Glance

Task Traditional stack torchfits equivalent
Read image to GPU astropy/fitsio → numpy → torch → .to(device) torchfits.read("img.fits", device="cuda")
Write tensor to FITS tensor → numpy → astropy HDU → writeto torchfits.write("out.fits", tensor)
Filter large table load all rows → mask in Python where="MAG < 20" pushdown in C++
WCS coordinate transform astropy.wcs / PyAST / Kapteyn torchfits.get_wcs() — pure PyTorch, batch, any device
HEALPix pixelization healpy / hpgeom / astropy-healpix torchfits.sphere.ang2pix() — CPU + CUDA + MPS
Spherical harmonics healpy (CPU, NumPy) torchfits.sphere.map2alm() / alm2map()
Sparse HEALPix maps healsparse (NumPy) torchfits.sphere.sparse (tensor-native)
Spherical polygons spherical-geometry (NumPy) torchfits.sphere.geom (non-convex, GPU)

Features

FITS I/O — Multi-threaded C++ core with SIMD-optimized type conversion, memory-mapped reads, intelligent chunking, and adaptive buffering. Reads and writes images, binary tables, compressed tiles (Rice, HCOMPRESS, GZIP, PLIO), and multi-extension FITS files with full header round-trip fidelity.

Table Engine — Arrow-native table API with predicate pushdown (where=), column projection, row slicing, streaming scan(), and in-place mutations (append, insert, update, delete rows and columns). Interop with Pandas, Polars, DuckDB, and PyArrow.

WCS — Pure-PyTorch implementation of 13 projections (TAN, SIN, ARC, ZPN, ZEA, STG, CEA, CAR, MER, AIT, MOL, HPX, SFL) with SIP, TPV, TNX, and ZPX polynomial distortions. Batch pixel_to_world / world_to_pixel on any device. Validated against astropy.wcs, PyAST, and Kapteyn.

Sphere — HEALPix primitives (ang2pix, pix2ang, nest2ring, ring2nest, neighbors, interpolation), spherical polygons (non-convex region queries, area, containment), Multi-Order Coverage (MOC) maps, HealSparse interop, and spherical harmonic transforms (map2alm, alm2map, scalar and spin). Benchmarked against healpy, hpgeom, astropy-healpix, mhealpy, healsparse, and spherical-geometry.

Compatibilitytorchfits.sphere.compat provides a healpy-compatible API surface (ang2pix, pix2ang, query_circle, map2alm, alm2map, synalm, synfast, anafast, smoothing, and more) so existing healpy code can switch with minimal changes. WCS objects follow the same pixel_to_world / world_to_pixel interface as astropy.wcs.

ML IntegrationFITSDataset and IterableFITSDataset work with torch.utils.data.DataLoader for multi-worker streaming. Built-in astronomical transforms (ZScale, Asinh, Log, Power stretches; crop, flip, rotation augmentations; redshift shift, error perturbation) with composable pipelines.

Install

pip install torchfits

Pre-built wheels are available for Linux and macOS (x86_64, arm64). No system CFITSIO needed—it's vendored and compiled automatically.

From source:

git clone https://github.com/sfabbro/torchfits.git
cd torchfits
pip install -e .

Requires Python 3.10+, a C++17 compiler, CMake 3.21+, and PyTorch 2.0+.

Quick Start

Read an image to GPU

import torchfits

data, header = torchfits.read("science.fits", device="cuda", return_header=True)
# data: torch.Tensor on CUDA, shape e.g. (4096, 4096), dtype torch.float32

Filter and stream a catalog

# Predicate pushdown — only matching rows leave C++
table = torchfits.table.read(
    "catalog.fits",
    columns=["RA", "DEC", "MAG_G"],
    where="MAG_G < 20.0 AND CLASS_STAR > 0.9",
)

# Stream 100M rows in constant memory
for batch in torchfits.table.scan("survey.fits", batch_size=50_000):
    process(batch)

WCS coordinate transforms

wcs = torchfits.get_wcs("image.fits")

# Batch pixel → sky on GPU
ra, dec = wcs.pixel_to_world(x_pixels, y_pixels)  # torch.Tensor in, Tensor out

HEALPix and spherical harmonics

from torchfits.sphere import ang2pix, map2alm, alm2map

ipix = ang2pix(nside=2048, theta=theta, phi=phi, nest=True)  # GPU-accelerated
alm = map2alm(healpix_map, lmax=512)
smoothed = alm2map(alm, nside=2048, lmax=512)

Multi-HDU access

with torchfits.open("multi_ext.fits") as hdul:
    print(hdul)            # pretty-printed summary
    img = hdul[0].data     # image tensor
    tbl = hdul[1].data     # table dict
    tbl_filtered = hdul[1].filter("FLUX > 100 AND FLAG = 0")

Write back

torchfits.write("output.fits", data, header=header, overwrite=True)
torchfits.table.write("catalog_out.fits", table_dict, header=header)

Benchmarks

torchfits is benchmarked against astropy, fitsio, healpy, hpgeom, astropy-healpix, mhealpy, healsparse, spherical-geometry, PyAST, and Kapteyn across four domains (FITS I/O, tables, WCS, sphere). Correctness is validated against each upstream library using their own test fixtures and public reference data.

Methodology, reproducible commands, results, and known deficits: docs/benchmarks.md

Documentation

API Reference Full public API with signatures and examples
Examples Runnable scripts for every major workflow
Installation Build from source, GPU setup, troubleshooting
Benchmarks Methodology, commands, and latest numbers
Changelog Version history and migration notes
Release Checklist Maintainer guide for cutting releases

Contributing

git clone https://github.com/sfabbro/torchfits.git
cd torchfits
pixi install
pixi run test

The project uses pixi for environment management, ruff for linting, and pytest for testing.

License

GPL-2.0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

torchfits-0.3.2.tar.gz (1.5 MB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

torchfits-0.3.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (7.4 MB view details)

Uploaded CPython 3.13manylinux: glibc 2.17+ x86-64

torchfits-0.3.2-cp313-cp313-macosx_11_0_arm64.whl (3.6 MB view details)

Uploaded CPython 3.13macOS 11.0+ ARM64

torchfits-0.3.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (7.4 MB view details)

Uploaded CPython 3.12manylinux: glibc 2.17+ x86-64

torchfits-0.3.2-cp312-cp312-macosx_11_0_arm64.whl (3.6 MB view details)

Uploaded CPython 3.12macOS 11.0+ ARM64

File details

Details for the file torchfits-0.3.2.tar.gz.

File metadata

  • Download URL: torchfits-0.3.2.tar.gz
  • Upload date:
  • Size: 1.5 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for torchfits-0.3.2.tar.gz
Algorithm Hash digest
SHA256 360a341c68a9af793e5d2dbd918de394a0edb182507cc7afc345b2bd1f985b9d
MD5 07b064481884f259d65ff8e3db3b9103
BLAKE2b-256 9c0bc0cc5e48c820c250a6061cc8983d66bb9aa14d1d552cae544c61d946317a

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.3.2.tar.gz:

Publisher: build_wheels.yml on sfabbro/torchfits

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file torchfits-0.3.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for torchfits-0.3.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 6c7015f07366b87408b3bf61088627660983ead80d7c3b2795e54491789ede76
MD5 f9ebfba6dbedbe958457685e7f16e0ab
BLAKE2b-256 7c51257b2d44f720bae5b21d5e280c33ff3a388acdbf2ce65c3064d1f1827047

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.3.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: build_wheels.yml on sfabbro/torchfits

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file torchfits-0.3.2-cp313-cp313-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for torchfits-0.3.2-cp313-cp313-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 c5c119641c30976de550a6e922f31edbdc4819968a22872699e5bfc55bcc42b0
MD5 bac868f4b8870699d6f14e1520dbbbde
BLAKE2b-256 0277ae7f1501308800b421b48f940782007d975e1ab22139331a479900e35d6b

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.3.2-cp313-cp313-macosx_11_0_arm64.whl:

Publisher: build_wheels.yml on sfabbro/torchfits

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file torchfits-0.3.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for torchfits-0.3.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 44f4877300775ec127b94963d5be24a0772d35661e781c842ba2af27fbbbc894
MD5 f85aa301f5411fb397e9f65a5c7d93bf
BLAKE2b-256 8c1890c2ecbf114c16c7094934b731d1370b4b425f5661f26e70d4c5f7823c3d

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.3.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: build_wheels.yml on sfabbro/torchfits

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file torchfits-0.3.2-cp312-cp312-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for torchfits-0.3.2-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 e56fd921fb5ebd42a8ccce62fe2065f797bbdafa1495d19cb5ef48a59b5bf107
MD5 5a7a7be5b7a0dfe6c5ab34722c562347
BLAKE2b-256 2be013d52c3f6ccdb355176bf1e0eff5be849e919728622cb44ebff904ed6e0f

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.3.2-cp312-cp312-macosx_11_0_arm64.whl:

Publisher: build_wheels.yml on sfabbro/torchfits

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page