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 reads and writes FITS files as PyTorch tensors. A multi-threaded C++ engine (vendored CFITSIO) handles images, tables, headers, compression, and MEF files. Optional datasets, transforms, and a torchfits CLI sit on top.

pip install torchfits

Requires Python 3.10+ and PyTorch 2.10. Docs: astroai.github.io/torchfits.

At a Glance

Task torchfits
Image → GPU tensor torchfits.read_tensor("img.fits", device="cuda")
Write a tensor torchfits.write("out.fits", tensor)
Filter a catalog in C++ table.read(..., where="MAG < 20")
Open a MEF with torchfits.open("mef.fits") as hdul: …
Train FitsImageDataset + make_loader(..., num_workers=4)
Shell torchfits info / header / convert / …

Features

  • Fast FITS I/O — mmap image reads, compressed images, MEF, checksums
  • Tables — Arrow-native with where= pushdown, scan/stream, Parquet/CSV/TSV/Arrow IPC export
  • MLtorchfits.data datasets + make_loader
  • Transforms — stretches, FITS scale/null handling, spectral prep (torchfits.transforms)
  • CLI — MEF-aware inspect/convert tools (docs/cli.md)

Supported feature matrix: docs/parity.md.

What's New in 0.9.2 / 0.9.3

  • CLItorchfits for info, header, verify, stats, table, cutout, convert, … (docs/cli.md)
  • Leaner imports — transforms from torchfits.transforms; use read / read_tensor (not read_fast / read_image)
  • Convert — tables → Parquet, CSV, TSV, or Arrow IPC; images → Lupton PNG
  • Scorecard — CUDA 0 strict deficits; Linux CPU 1; Mac MPS 16 (docs/benchmarks.md)

Full notes: docs/changelog.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, SqrtStretch, ZScaleNormalize, RobustNormalize, MinMaxNormalize, PercentileClipNormalize
Background / normalization BackgroundSubtract, GlobalScalarNorm, FITSHeaderNormalize
Header / table FITSHeaderScale, FITSScaleColumns, TNullToNan
Spectral ContinuumNormalize, ContinuumRemoval, DopplerShift, SpectralBinning ✓ (except BandMath)
Continuum estimators AsymmetricLeastSquares, AlphaShapeContinuum, WaveletDecompose, SavitzkyGolayFilter, RunningPercentile, UpperEnvelopeContinuum
Outlier / time SigmaClip, AsymmetricSigmaClip, PhaseFold ✗ (lossy or many-to-one)

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

Performance

Lab multi-host exhaustive scorecard (exhaustive_mps_20260717_040150 Mac MPS, exhaustive_cpu_20260717_040146 CANFAR CPU, exhaustive_cuda_20260717_042840 CANFAR CUDA); see docs/benchmarks.md for methodology, full exhaustive table, category summaries, RSS columns, and deficit transparency.

Under the strict gate (images: any lag; Arrow tables: ≤1.05×), CANFAR CUDA reports 0 TorchFits deficits; Linux CPU 1 (narrow 1M-row predicate); Mac MPS 16. MPS is not the Linux CUDA release gate.

Headline numbers

Case torchfits astropy fitsio Speedup vs astropy
Large float32 image read (16 MB, CPU) 6.51 ms 13.95 ms 8.83 ms 2.1×
Compressed Rice image (CPU) 15.17 ms 75.41 ms 18.45 ms 5.2×
50× repeated 100×100 cutouts (CPU) 21.75 ms 335.26 ms 21.03 ms 18.3×
Table read (100k rows, 8 cols) 6.97 ms 95.60 ms 30.20 ms 13.7×
Varlen table read (100k rows, 3 cols) 258.11 ms 1.624 s 337.40 ms 6.4×

By benchmark category

Category ranges and the full exhaustive table live in docs/benchmarks.md (CANFAR CUDA exhaustive_cuda_20260717_042840). Use the headline table above for this release’s absolute timings.

Current deficits

Scorecard policy (same-mmap peers):

  • Images / cubes / spectra / cutouts: any lag above float-timer ε is a deficit (rice/hcompress included — no percent floor).
  • Arrow tables: allow up to 1.05×.

Prior “0 deficit” claims used a 25% lag floor and are retracted. Re-score after the SIMD endian + thin device + WHERE⇒mmap-scan fixes; see docs/benchmarks.md.

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.

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.

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

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)

Shell (CLI)

torchfits info science.fits
torchfits header science.fits --keyword OBJECT --json
torchfits verify science.fits
torchfits stats science.fits --hdu 0
torchfits convert catalog.fits out.csv --to csv --hdu 1

Benchmarks

torchfits is benchmarked across FITS image I/O (1D/2D/3D, all integer and float dtypes, compressed, scaled, MEF, cutouts, time series) and FITS table I/O (read, projection, row slicing, predicate filtering, streaming). GPU (CUDA) transport rows are included for image reads.

Comparators are astropy.io.fits and fitsio; selected CFITSIO behavior is validated through the torchfits native backend and smoke tests.

Methodology, full exhaustive table, category summaries, 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
CLI torchfits command-line tools
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.3.tar.gz (1.7 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.9.3-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.3-cp313-cp313-macosx_11_0_arm64.whl (918.7 kB view details)

Uploaded CPython 3.13macOS 11.0+ ARM64

torchfits-0.9.3-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.3-cp312-cp312-macosx_11_0_arm64.whl (918.8 kB view details)

Uploaded CPython 3.12macOS 11.0+ ARM64

torchfits-0.9.3-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.3-cp311-cp311-macosx_11_0_arm64.whl (920.1 kB view details)

Uploaded CPython 3.11macOS 11.0+ ARM64

torchfits-0.9.3-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.3-cp310-cp310-macosx_11_0_arm64.whl (920.5 kB view details)

Uploaded CPython 3.10macOS 11.0+ ARM64

File details

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

File metadata

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

File hashes

Hashes for torchfits-0.9.3.tar.gz
Algorithm Hash digest
SHA256 b3d6151cd58b85e20613da6e8a65b87a593de452ef1823a4237a28fa0254dac1
MD5 cfe39c0b56a4609593911d6a87c789cf
BLAKE2b-256 45844462a2b17003233edd1ad23e8f6540db5feff9ac64088e53f81092293e6a

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.3-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 358f1a38e7c345adb3ccb67ba21e897968bda4b3faf9ae231c418a597f348231
MD5 1ee964d8bcce370740099bace535e8f2
BLAKE2b-256 0788310029d37e7c69766a4fab77cb2bcb42cbf293b4428a169e065e4a3f1030

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.3-cp313-cp313-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 3eefbf61bd65fcad55a874900b3ab50d077bfd098ea881db66000a10ba0c3c61
MD5 f9cd6bee4b9fc28fdaa2e3bc742f1937
BLAKE2b-256 9640be54940cbf72fa0a8a7cf8dd372d84d5e32c2aef3997ecc08001e2079fc2

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 f48fa550f2a24e49b7f0d8889ec793bdfa29652e3ba43420e08b4d0270da1328
MD5 20135a80e7a8b55b983c528321276acf
BLAKE2b-256 8cfdf83e5aaf53a476679d36aaf0c666b31bab80ac5d8671d71dbaf7193480d6

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.3-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 f7a2ec22e1cab83443715bf37354748e45bfcf888fecc1bdaacf957006164055
MD5 435f85c9b4055d57c432d1773cf0b1a4
BLAKE2b-256 91cce1d8917afc84e10a7ff67af9fbd1435b7488186c4cff4ccb6621ef26e8c4

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.3-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 fa0e7c8b6459fb5c0c2cd0aee6c99c3b3d11fb6f8188114c00f6bfd1c2d0d64d
MD5 b977e4e3e8a0ce2aa1be6c0bd871789c
BLAKE2b-256 49759e4c93e76b39cf63edddb1a2118f1abf63317c1c0dcb733a7b621de1e54b

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.3-cp311-cp311-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 a5fa23423de8cf1bcab646f5e4c3a671fe63e4c3729169c5935472aa22c8e2d9
MD5 20a5b3522ca999471086ef66c2b6322a
BLAKE2b-256 4e40ee457aeb7a0657b833bce88ab39df9d0e9de020b2ca5d99b04c189e84b06

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.3-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 864105d03ce270b66213d575496962e0dbc8f9dcf212aae13ab8aac6a197356e
MD5 8665e71bb3674322eac78d26fbffb6bf
BLAKE2b-256 2487a49b711470c1c6e75c738bf8e30b08efda8191715658f13fa05ad9bc3c7b

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for torchfits-0.9.3-cp310-cp310-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 b417c3a411d2be444eae4aa38e44d97ac24bbb18cf1ad928b582f6ec078a9f04
MD5 5484e87aaca007651e2515b7c6b8ba8c
BLAKE2b-256 11e4495dfcb86ad9cb829a4f20cfc0b85b130c006f6d18dc5b3a9f4b2227094b

See more details on using hashes here.

Provenance

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