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: MIT

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 x86_64 and macOS arm64. No system CFITSIO is needed—it is vendored and compiled automatically. Other architectures install from source when a compatible compiler and PyTorch are available.

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

MIT

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.9.0.tar.gz (541.5 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.9.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (1.0 MB view details)

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

torchfits-0.9.0-cp313-cp313-macosx_11_0_arm64.whl (888.4 kB view details)

Uploaded CPython 3.13macOS 11.0+ ARM64

torchfits-0.9.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (1.0 MB view details)

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

torchfits-0.9.0-cp312-cp312-macosx_11_0_arm64.whl (888.4 kB view details)

Uploaded CPython 3.12macOS 11.0+ ARM64

torchfits-0.9.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (1.0 MB view details)

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

torchfits-0.9.0-cp311-cp311-macosx_11_0_arm64.whl (889.8 kB view details)

Uploaded CPython 3.11macOS 11.0+ ARM64

torchfits-0.9.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (1.0 MB view details)

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

torchfits-0.9.0-cp310-cp310-macosx_11_0_arm64.whl (890.4 kB view details)

Uploaded CPython 3.10macOS 11.0+ ARM64

File details

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

File metadata

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

File hashes

Hashes for torchfits-0.9.0.tar.gz
Algorithm Hash digest
SHA256 01029aab768dc1c2871404aa39eac041cdf7bfd80b083313f07931b488ceedac
MD5 46f6b27dc21c79ae7a33deb3409aa411
BLAKE2b-256 710d7343104acf332b55b2de451fc0ffaf3450354e75ba9bb01eb2f76a6c351d

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 77054a4671643b68ef2f48f863bfb671be01130326b623c262e0abce2f4959d9
MD5 830fe156d6e75b8f51c18f0a4f8fa0f0
BLAKE2b-256 d396b544056ee7c16ff9a319302beb0183eb5ea48d600022ac50ac902d906538

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.0-cp313-cp313-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 846fa0aa5736b46769fcdc22169b0b26130057a1b7f8df323d0645a651f9cf3e
MD5 87f2a49e9722d893dffe08db8e527ccf
BLAKE2b-256 a4977c7b208a9c1f32fd59030c9f88a37121a05eddda06427d7f3e300ccde36d

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 5ff291ed7c788fc6f9c863193ea9946cd3851dde1367b70a82604d854ec825a8
MD5 60f14f16aab7c00ec367e7e88e4c37db
BLAKE2b-256 241f0451924215ce98a1bb52fb54ead88a3282900c50c117759f765e351b223c

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.0-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 a06d6cfbd9642dea546b5c3c95cf8f1da98750b55a0b09b024e5217de43e5f47
MD5 c8eb5da8c0bf930e74d70ace700dd06f
BLAKE2b-256 cbcded5bfcd0442efd502fb5c4398b08410cc96447e80ea8c38a62caffcaa4b8

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 00bd355059ce1566f7a463cf8a85b35a05ba1616c2cd926a84bcde1d7e85fb4a
MD5 bfe9293af2cd56caed4561d8b719ac44
BLAKE2b-256 7d3a5f4b31f0f00fe258b5ace2fb8fd01252e651471dcf1a2828239da93c3fad

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.0-cp311-cp311-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 98f1e23f6afed0cf1d04077408512b5763a79219d51bc70742c1eee7884cdfc1
MD5 7ddfad24eb4ab507a74d9d94ae0f517c
BLAKE2b-256 bdd87e443b2560463077ac26654672ffda6442a15fe3987c60d198cba137a423

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 cda945f504a6d09da9659bff7cb581cd16a373382cc1481383c79c7878b61098
MD5 7f151c48a45f4bd292623d2f507f2b7d
BLAKE2b-256 19fca3839811bd1f6d9674dbced3a20f3781bf04001f7a1c17d9c7ec1c5e96bd

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.0-cp310-cp310-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 fef1164355043f830adceef62cdb2499ff0a4c9957001142479bbd911a02e2b9
MD5 ce74c9d0e676c4e984974d53642d2e31
BLAKE2b-256 8e90a72ca2d657f2f706873b730afdd0ce9f86ed16171282af6a9c14318d7211

See more details on using hashes here.

Provenance

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