Skip to main content

High-performance FITS I/O for PyTorch

Project description

torchfits

PyPI

CI Python 3.10+ License: GPL-2.0

torchfits is a focused FITS I/O library for PyTorch. It reads and writes FITS images, headers, HDUs, compressed images, and FITS tables through a multi-threaded C++ engine with vendored CFITSIO, returning tensor-native data without requiring users to build NumPy-to-torch glue code.

It is not a full replacement for Astropy, fitsio, or CFITSIO. The supported surface is documented explicitly in docs/parity.md, with source-backed tests for each claimed parity area. WCS, sky-coordinate models, HEALPix, sphere geometry, and sky-domain simulation workflows are out of scope for torchfits.

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++
Read multi-extension files manual HDU dispatch with torchfits.open("mef.fits") as hdul: ...
Verify FITS checksums comparator-specific helpers torchfits.verify_checksums(path)

Features

FITS I/O — Multi-threaded C++ core with SIMD-optimized type conversion, memory-mapped image reads, intelligent chunking, and adaptive buffering. Reads and writes images, binary/ASCII tables, compressed images, and multi-extension FITS files with header round-trip coverage.

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.

Compatibility Contract — Parity is tracked by tier: truthful public docs, fitsio core workflow parity, Astropy common workflow parity, selected CFITSIO backend behavior, and explicit non-goals. See docs/parity.md.

What's New in 0.6.0

0.6.0 is a focused FITS I/O release with a maintainable Python/C++ core, first-class torch.utils.data integration, and header-aware preprocessing. Key improvements:

  • C++ engine hardening — Rule-of-5 fixes, RAII guards, unified BITPIX mapping.
  • Predicate filter C++ pushdown — all table sizes use C++ for where= filtering.
  • Lightweight is_compressed check — O(1) header probe for compressed images.
  • Thread-safe cachesstd::shared_mutex for concurrent multi-worker access.
  • torchfits.data moduleFitsImageDataset, make_loader with automatic cache tuning.
  • 25+ ML-friendly transforms — all with .inverse() for model output decoding.
  • 7 deficits remaining (down from 22) in the lab exhaustive benchmark suite.

Full history: docs/changelog.md. Roadmap for 0.6.x and beyond: docs/roadmap.md.

Transforms

torchfits includes over 20 ML-friendly FITS data transforms — all with .inverse() for decoding model outputs back to physical units. See docs/api.md for full signatures and the example scripts in examples/.

from torchfits import ArcsinhStretch, BackgroundSubtract, Compose, ZScaleNormalize

pipeline = Compose([BackgroundSubtract(), ArcsinhStretch(a=0.1), ZScaleNormalize()])
normalized = pipeline(image)     # forward → model input
restored  = pipeline.inverse(normalized)  # inverse → physical flux

Image stretches & normalizers (invertible)

Transform Description
ArcsinhStretch(a) LSST/SDSS standard for high-DR images
LogStretch(a, eps) Logarithmic stretch, negatives clamped
SqrtStretch() Poisson variance-stabilising
ZScaleNormalize(contrast, dim) IRAF auto-contrast → [0, 1]
RobustNormalize(dim) Median + MAD standardization (P1)
BackgroundSubtract(dim) Subtract median background
PercentileClipNormalize(lower, upper, dim) Percentile-clip → [0, 1]
MinMaxNormalize(dim) Min-max → [0, 1]
GlobalScalarNorm(stat, dim) Divide by median/max/mean/rms (P5)

Spectral & hyperspectral (astronomy-specific)

Transform Description
ContinuumNormalize(order, n_sigma) Fit continuum + divide by it. Inverse multiplies back.
ContinuumRemoval(method, order, n_knots) Fit continuum + subtract it. Inverse adds back.
DopplerShift(z) Redshift/blueshift via resampling. Inverse is opposite shift.
SpectralBinning(factor, mode, dim) Bin adjacent channels. Inverse nearest-neighbour upsamples.
BandMath(func, band_dim) Band ratios (NDVI etc.) via unbind. Inverse not available.

Continuum / baseline estimators (additive decomposition)

All use Original = Estimate + Residuals for perfect recovery. Based on post-2021 astro-ML research (SUPPNet, RASSINE, AstroCLIP).

Transform Description
AsymmetricLeastSquares(lam, p, max_iter) Eilers 2003 penalised baseline (Raman/NIR)
AlphaShapeContinuum(half_window, iterations) Morphological closing — guaranteed upper envelope
SavitzkyGolayFilter(window, polyorder) Polynomial smoothing (P4)
RunningPercentile(percentile, window) Sliding-window percentile continuum (P6)
UpperEnvelopeContinuum(window, smooth) Local-max interpolation (RASSINE-like) (P3)
WaveletDecompose(levels) Multi-level Haar DWT frequency split (P2)

Time-domain & meta

Transform Description
PhaseFold(period, n_bins) Fold time series into phase bins
FITSHeaderScale(bscale, bzero) Apply/remove BSCALE/BZERO
FITSHeaderNormalize(header) Auto-normalize from BITPIX
SigmaClip(n_sigma, max_iter, dim) Iterative outlier rejection
AsymmetricSigmaClip(n_low, n_high, dim) One-pass asymmetric sigma-clip (median+MAD)
Compose(transforms) Chain transforms; inverse unwinds in reverse

Performance

Median wall-clock from the lab exhaustive benchmark suite (exhaustive_mmap_0.5.0b4_20260630_162835, H100 CUDA). See docs/benchmarks.md for methodology, deficit transparency, and reproducible commands.

Case torchfits astropy Speedup
Large float32 image read (16 MB, CPU) 4.89 ms 15.66 ms 3.3×
Same read @ CUDA 3.26 ms 15.46 ms 4.7×
Compressed Rice image (CPU) 9.22 ms 28.70 ms 3.1×
50× repeated 100×100 cutouts (CPU) 6.34 ms 80.25 ms 13.3×
Table read (100k rows, 8 cols) 102 μs 6.37 ms 62×

ML DataLoader (local diagnostic, 30×512² float32, CPU, 2 epochs): torchfits 1.12× vs fitsio on Rice-compressed files; uncompressed within ~4% (handle-cache tuning matters — call torchfits.cache.optimize_for_dataset before training loops).

GPU integer reads: Default read(..., device="cuda") applies BSCALE/BZERO on device and returns float32 for generic scaled pixels — good for ML. For native integer dtypes (int8, uint16) matching fitsio, use read_tensor(..., raw_scale=True) or rely on the automatic signed-byte / unsigned-integer fast paths (see benchmarks doc). Tables remain CPU-resident in all backends; GPU rows measure host decode + H2D copy, not disk→GPU bypass.

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/astroai/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",
)
# table: pyarrow.Table

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

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     # dict-like table accessor
    tbl_filtered = hdul[1].filter("FLUX > 100 AND FLAG = 0")

Write back

torchfits.write("output.fits", data, header=header, overwrite=True)
# table_dict is a dict of column names to 1D arrays/tensors
torchfits.table.write("catalog_out.fits", table_dict, header=header, overwrite=True)

Benchmarks

torchfits benchmark evidence is limited to FITS image I/O and FITS table I/O. Comparators are astropy.io.fits and fitsio; selected CFITSIO behavior is validated through the torchfits native backend and smoke tests.

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

Documentation

API Reference Full public API with signatures and examples
Roadmap FITS I/O roadmap and parity tiers
Parity Matrix Supported, partial, unsupported, and out-of-scope features
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/astroai/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.6.0.tar.gz (477.2 kB view details)

Uploaded Source

Built Distributions

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

torchfits-0.6.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (6.2 MB view details)

Uploaded CPython 3.13manylinux: glibc 2.27+ x86-64manylinux: glibc 2.28+ x86-64

torchfits-0.6.0-cp313-cp313-macosx_11_0_arm64.whl (2.5 MB view details)

Uploaded CPython 3.13macOS 11.0+ ARM64

torchfits-0.6.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (6.2 MB view details)

Uploaded CPython 3.12manylinux: glibc 2.27+ x86-64manylinux: glibc 2.28+ x86-64

torchfits-0.6.0-cp312-cp312-macosx_11_0_arm64.whl (2.5 MB view details)

Uploaded CPython 3.12macOS 11.0+ ARM64

torchfits-0.6.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (6.2 MB view details)

Uploaded CPython 3.11manylinux: glibc 2.27+ x86-64manylinux: glibc 2.28+ x86-64

torchfits-0.6.0-cp311-cp311-macosx_11_0_arm64.whl (2.5 MB view details)

Uploaded CPython 3.11macOS 11.0+ ARM64

torchfits-0.6.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (6.2 MB view details)

Uploaded CPython 3.10manylinux: glibc 2.27+ x86-64manylinux: glibc 2.28+ x86-64

torchfits-0.6.0-cp310-cp310-macosx_11_0_arm64.whl (2.5 MB view details)

Uploaded CPython 3.10macOS 11.0+ ARM64

File details

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

File metadata

  • Download URL: torchfits-0.6.0.tar.gz
  • Upload date:
  • Size: 477.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for torchfits-0.6.0.tar.gz
Algorithm Hash digest
SHA256 bf25d62e78f734cc2d7ea0467df6d189828fbe65254de7a01206a3cd9af04bba
MD5 65cd2c6844436cc062a8a4fd41c22fa4
BLAKE2b-256 63b7bf99dc421b2649d37f028e889d8cdbc7d299a995962dd81acb9361cba8d0

See more details on using hashes here.

Provenance

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

Publisher: build_wheels.yml on astroai/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.6.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for torchfits-0.6.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 596c0d361523c0ca12f8c729dd4a586eca2673b51f919adc6e15bdcef854eca7
MD5 b02a5061edae73cfaed0e95ff5b58971
BLAKE2b-256 67b457232b5a143324d556751728c03f0b7c67f787544132187bd342183d9668

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.6.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl:

Publisher: build_wheels.yml on astroai/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.6.0-cp313-cp313-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for torchfits-0.6.0-cp313-cp313-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 d426dcd58636ffc4afa9d79495edd33240180b895fbe87d9fccf74a7b42bbcdf
MD5 61a024c46c4ad6dca70c69a57c50bbda
BLAKE2b-256 5d1aa9bf6e7e955445ce6c3eddd0b20ce76760cb5c81c6424b6358a4a8e7e2db

See more details on using hashes here.

Provenance

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

Publisher: build_wheels.yml on astroai/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.6.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for torchfits-0.6.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 97fc47c95e1d6e6fd31d495070ea6be3cf47d4267b19a9e71245d0800c198824
MD5 c3bf1d74e39e02bb342c2f52c60b6d43
BLAKE2b-256 f4e61adb602521a6abe351432cf088415e313ae0fe8d605efb53027330751c66

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.6.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl:

Publisher: build_wheels.yml on astroai/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.6.0-cp312-cp312-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for torchfits-0.6.0-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 6f82c439f12c696a6a93e9ec85da6646b6011fb404b27cd33322ad1c9b3adae4
MD5 084f44578bbc6d9e7bc2c6b46c7271fd
BLAKE2b-256 19597c54bc30fe7a307d41792b78b694172fd72c7d31ac037e090b0f31aaf2be

See more details on using hashes here.

Provenance

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

Publisher: build_wheels.yml on astroai/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.6.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for torchfits-0.6.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 25d550efe25278e710d83aeffe836800cf1d4a5dacb95c7a068d25a00c7871aa
MD5 72ad662df21cc85c7852e8fcb1e21cf4
BLAKE2b-256 ae6fa5ad646c8858f480788239b8d11b60100979bc2568640227c532f3c5f72b

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.6.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl:

Publisher: build_wheels.yml on astroai/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.6.0-cp311-cp311-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for torchfits-0.6.0-cp311-cp311-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 19f2caa26d71853258d3aa32e47ec146b7af9c05365b941cfa067fa5f4237eae
MD5 aa45ea6aa650427508f8635423612728
BLAKE2b-256 84a45a0dbd5234472ace7188c8c8828b34fa699823084b90b1f44235b009437a

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.6.0-cp311-cp311-macosx_11_0_arm64.whl:

Publisher: build_wheels.yml on astroai/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.6.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for torchfits-0.6.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 262c5c46eaf93045353c8d7a4db1a49c71ebf6fa09dbb14dcf5d366bb022e496
MD5 625b48228069e62b30d2c6ec30131ac3
BLAKE2b-256 5d6cb2d4973aeaf8597527c81d6779b9ac4f2f19ab161755ad67f2105dd15072

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.6.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl:

Publisher: build_wheels.yml on astroai/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.6.0-cp310-cp310-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for torchfits-0.6.0-cp310-cp310-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 435e9926966d4ed2f71df70c01fa1df47f4dc64d96a81187abf242995669b06e
MD5 c5945d1a802b7f767bd6a3c4d116e0a3
BLAKE2b-256 041c9952a68c1bcd5f84602f68a6984cf1d7d293276a85329cb3bd51c6371ead

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.6.0-cp310-cp310-macosx_11_0_arm64.whl:

Publisher: build_wheels.yml on astroai/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