Skip to main content

FITS I/O for PyTorch with native tensor reads, datasets, and transforms

Project description

torchfits

PyPI

CI Python 3.10+ License: GPL-2.0

torchfits is FITS I/O for PyTorch: a multi-threaded C++ engine with vendored CFITSIO that reads and writes images, headers, HDUs, compressed images, and tables as tensors — without NumPy-to-torch glue. Optional torchfits.data datasets and torchfits.transforms provide header-aware preprocessing for ML training loops.

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, sky-domain simulation, and photometric physics are out of scope. Transforms cover FITS scale/null/dtype and tensor preprocessing only.

At a Glance

Task Traditional stack torchfits equivalent
Read image to GPU astropy/fitsio → numpy → torch → .to(device) torchfits.read_tensor("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: ...
PyTorch training loop hand-rolled Dataset + cache tuning FitsImageDataset + make_loader(..., num_workers=4)
Normalize for model input ad-hoc scaling in the training script Compose([BackgroundSubtract(), ZScaleNormalize()])
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.

ML Data Layertorchfits.data ships FitsImageDataset, FitsImageIterableDataset, FitsTableDataset, FitsTableIterableDataset, FitsCutoutDataset, and make_loader with automatic handle-cache warm-up.

Transforms — 25+ FITSTransform classes for image stretches, header-aware scaling (FITSHeaderScale, FITSScaleColumns, TNullToNan), spectral/hyperspectral preprocessing, and continuum estimators. Most ship .inverse() for decoding model outputs back to physical units. See docs/api.md and examples/example_transforms.py.

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

0.7.0 completes the ML data layer and removes legacy dataset aliases:

  • FitsTableIterableDataset — stream large catalogs via table.scan with multi-worker batch sharding.
  • FitsCutoutDataset — patch training from a cutout index table.
  • Legacy removalFITSDataset / IterableFITSDataset removed from the root namespace; see migration_datasets.md.
  • Docs site — Zensical + GitHub Pages at astroai.github.io/torchfits.

0.6.0 shipped the core ML surface (torchfits.data image/table datasets, torchfits.transforms, C++ predicate pushdown, thread-safe caches). See docs/changelog.md.

Full history: docs/changelog.md. Roadmap for 1.0: docs/roadmap.md.

Transforms

from torchfits.transforms 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

Representative classes (full catalog in docs/api.md):

Category Examples Inverse
Image stretches ArcsinhStretch, LogStretch, ZScaleNormalize, RobustNormalize
Header / table FITSHeaderScale, FITSHeaderNormalize, FITSScaleColumns, TNullToNan
Spectral ContinuumNormalize, ContinuumRemoval, DopplerShift, SpectralBinning ✓ (except BandMath)
Continuum estimators AsymmetricLeastSquares, AlphaShapeContinuum, WaveletDecompose, SavitzkyGolayFilter
Outlier / time SigmaClip, AsymmetricSigmaClip, PhaseFold ✗ (lossy or many-to-one)

Runnable demos: examples/example_transforms.py (image pipeline), examples/example_hyperspectral.py (spectral cube).

Performance

Median wall-clock from the lab exhaustive benchmark suite (run exhaustive_cuda_0.7.0_20260711_055635, CANFAR staging GPU + CPU rows; see docs/benchmarks.md for methodology, deficit transparency, and reproducible commands.

Case torchfits astropy fitsio Speedup vs astropy
Large float32 image read (16 MB, CPU) 3.93 ms 7.60 ms 6.09 ms 1.9×
Compressed Rice image (CPU) 8.99 ms 28.14 ms 9.36 ms 3.1×
50× repeated 100×100 cutouts (CPU) 4.63 ms 76.04 ms 4.76 ms 16×
Table read (100k rows, 8 cols) 86.9 μs 6.32 ms 59.41 ms 73×
Varlen table read (100k rows, 3 cols) 90.8 μs 3.49 ms 220 ms 38×

ML DataLoader (local diagnostic, not in lab CSV): 30×512² float32, CPU, 2 epochs — torchfits 1.12× vs fitsio on Rice-compressed files; uncompressed within ~4%. make_loader(..., optimize_cache=True) warms handle caches automatically when the dataset exposes a files attribute.

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

tensor = torchfits.read_tensor("science.fits", hdu=0, device="cuda")

PyTorch DataLoader

from torchfits.data import FitsImageDataset, make_loader

ds = FitsImageDataset("observations/*.fits", label_key="CLASS")
loader = make_loader(ds, batch_size=32, num_workers=4)

for images, labels in loader:
    ...  # images: [B, 1, H, W] when add_channel_dim=True (default)

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

Published site: astroai.github.io/torchfits

Documentation site Browse all docs on GitHub Pages
API Reference Full public API with signatures and examples
Migration from Astropy Side-by-side workflow translation
Migration from fitsio Side-by-side workflow translation
Dataset migration Removed FITSDatasettorchfits.data
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.7.0.tar.gz (496.8 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.7.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.7.0-cp313-cp313-macosx_11_0_arm64.whl (2.5 MB view details)

Uploaded CPython 3.13macOS 11.0+ ARM64

torchfits-0.7.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.7.0-cp312-cp312-macosx_11_0_arm64.whl (2.5 MB view details)

Uploaded CPython 3.12macOS 11.0+ ARM64

torchfits-0.7.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.7.0-cp311-cp311-macosx_11_0_arm64.whl (2.5 MB view details)

Uploaded CPython 3.11macOS 11.0+ ARM64

torchfits-0.7.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.7.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.7.0.tar.gz.

File metadata

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

File hashes

Hashes for torchfits-0.7.0.tar.gz
Algorithm Hash digest
SHA256 6224e959deff8d096f3586e35e127e52ccebdb56766201b2d943eb93ff8f715b
MD5 1db83204ec577a3e2cb0b9fe5b0b9aa7
BLAKE2b-256 9f8a265194a83fe8c3b0d9c4a20b48241da179c97c6937a637e2b0b6b4438bf8

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.7.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.7.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for torchfits-0.7.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 d68f8b806e367d4304e891a9b10d6df5cf3cefaf2a1b14e42af101a5d6451d32
MD5 d0c598b28188b1ab7fd16fc982dd2e2f
BLAKE2b-256 01eaea342ec7be28029c4b37f4304a4379c0218d2f3f52daf7df137432957de1

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.7.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.7.0-cp313-cp313-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for torchfits-0.7.0-cp313-cp313-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 4bf9d543c3d8fa9239ba6670451fe2260b65fb73856a9f83fbdcfba8d1e0a78f
MD5 928ba4bb3a09ec388d0b2a52b9222cae
BLAKE2b-256 0799a8a3149a680c40905bd7d8a5d74361f092987352e2edfe9eb41f343e717a

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.7.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.7.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for torchfits-0.7.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 fba40b5aaca1fe8fca5a8306508ebc0ab7d2ee5088f10fd947bfb3e99a2b89f5
MD5 0b5575dc15d97badc62da4f7bc18a0b0
BLAKE2b-256 89598090499027147b2072fd00281b8095b559c426c04b9c4828862b78450c96

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.7.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.7.0-cp312-cp312-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for torchfits-0.7.0-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 09cce3e6a08d65d83da08867a107f80d194716500f6dc54bbe65fdc6d9cbcc3e
MD5 e4359fb17c2a835c52c2e6ac0199bc80
BLAKE2b-256 9c6735ee6c4175bcaa33b6c4284c0d7fee38b684393d43bc31c4ad1105a0f06f

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.7.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.7.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for torchfits-0.7.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 523c94812db7afa276deebceb73120381e2262d6e96687cba2cad2b08b136105
MD5 2fdc1222afa0e6abe790281d391ec3a2
BLAKE2b-256 2dacfefd85bf0bc0bea6b666c144daa4b3ee1f0f99a3df9b189fc504cbd3dbff

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.7.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.7.0-cp311-cp311-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for torchfits-0.7.0-cp311-cp311-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 af56b95edd1e3c0b06784c7737306b179ec4819264e5be79a32c0cf806451c92
MD5 f236c3429f2f4e8427dd18001c8222f2
BLAKE2b-256 7558fbb564e4b196cad0632a7215b43a504bdf79a93b5bec27eaa75f69e39c9e

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.7.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.7.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for torchfits-0.7.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 454ed560785d6112380a2959ef3e4207a130588745b56bebe1becfe4ad16eaac
MD5 afaac29b19b6235b31e5e62e8cf335f7
BLAKE2b-256 e261a26b43cefc3a4afc73560bf0e5a6d9f83197a29ec0375ca08a2b6f20e358

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.7.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.7.0-cp310-cp310-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for torchfits-0.7.0-cp310-cp310-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 f991ef3b2e4e91a83e30a049b05b229bd01d6a77de4cdfd9f3b8c5e0daf1c9e9
MD5 99c60fd4191f8946951451793468b7b4
BLAKE2b-256 c10ec31ba7b511129691df3773f09fec7880b48243e9603ec760c7f8a9841a52

See more details on using hashes here.

Provenance

The following attestation bundles were made for torchfits-0.7.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