Skip to content

Error When Constructing WCS and/or Map Object for FITs files Containing SIP projection #8918

Open

Description

@Vsalinas91

Describe the bug

SunPy v8.0.0 ensured that header entries for the SIP projection are not skipped upon loading them to construct
a generic map object. However, how the SIP WCS is constructed upon generating a SunPy map object differs compared to
standard projection types (e.g., TAN, ZPN, etc). In sunpy/map/mapbase.py, the WCS for a SIP projection is handled separately
(lines 679 - 681), and relies on passing through the entire metadata object into the AstroPy WCS class in contrast to the manual
WCS build as done so for all other projection types.

The issue in question stems from generating a SunPy map object via direct ingest of a FITs file:

sunpy.map.Map(filename.fits)

This is because SunPy uses it's own FITs reader to generate the data/metadata pairs for each header data unit (HDU) contained in the file.
Unlike using AstroPy directly, which raises no errors, the SunPy reader adds a KEYCOMMENTS header item into the Map's metadata object

{"KEY": value, ...., "KEYCOMMENTS": {}, .....}

which is used to store the relevant comments for each header key, if any exist. In mapbase.py, if -SIPS is a detected WCS suffix in the header,
the entire metadata object is passed through AstroPy's WCS class, which includes the added KEYCOMMENTS item. As a result, when building the
map object, once printed, the following error is raised.

fits_map = sunpy.map.Map(filename.fits)
print(fits_map)

llegal value: {'SIMPLE': 'conforms to FITS standard', 'BITPIX': 'array data type', 'NAXIS': 'number of array dimensions'}. [sunpy.map.mapbase]

This can be replicated directly by passing through the fits_map.meta object into WCS which gives the entire AstroPy traceback. To resolve this error,
the KEYCOMMENTS item must be removed from the Map's meta object prior to constructing the WCS object. See example code to reproduce this error.

Additional note: Illegal value errors may also arise if COMMENT cards, or HISTORY streams are also present in a FITs file. Namely, if the strings for these
items contain non-ASCII characters (e.g., "\b"). Because some scientific FITs files may contain such metadata entries, it is recommended to also remove these
items from the Map's meta object prior to constructing the WCS to be safe.

To Reproduce

from sunpy.map import Map
from astropy.wcs import WCS
from astropy.io import fits
import sunpy.io._fits

import sunpy
import astropy
import numpy as np

import traceback
from pathlib import Path
import tempfile
import pprint

print(sunpy.__version__)
print(astropy.__version__)



if __name__ == '__main__':
    # generate test data
    data = np.ones((10, 10), dtype=np.int16)
    header = fits.Header({
        'AP_ORDER': 3,
        'A_0_2': 1e-07,
        'A_0_3': 1e-13,
        'A_1_1': -1e-07,
        'A_1_2': -1e-09,
        'A_2_0': 1e-07,
        'A_2_1': 1e-13,
        'A_3_0': -1e-09,
        'A_ORDER': 3,
        'BP_ORDER': 3,
        'B_0_2': -1e-07,
        'B_0_3': -1e-09,
        'B_1_1': 1e-07,
        'B_1_2': 1e-13,
        'B_2_0': -1e-07,
        'B_2_1': -1e-09,
        'B_3_0': 1e-13,
        'B_ORDER': 3,
        'CTYPE1': 'HPLN-TAN-SIP',
        'CTYPE2': 'HPLT-TAN-SIP',
        'CUNIT1': 'deg',
        'CUNIT2': 'deg',
        'CRVAL1': 0.0,
        'CRVAL2': 0.0,
        'CRPIX1': 5.0,
        'CRPIX2': 5.0,
        'CDELT1': 1.0,
        'CDELT2': 1.0,
        'DATE-OBS': '2026-11-17T00:00:00',

    })

    with tempfile.TemporaryDirectory() as tmpdir:
        file_path = Path(tmpdir) / "fits_file.fits"
        primary_hdu = fits.PrimaryHDU(data=data, header=header)
        hdul = fits.HDUList(primary_hdu).writeto(file_path)

        # 1st: Build the map object and see the error raised when SIP is present:
        # ----------------------------------------------
        fits_map = Map(file_path)
        print(fits_map)
        # > Illegal value: {'SIMPLE': 'conforms to FITS standard', 'BITPIX': 'array data type', 'NAXIS': 'number of array dimensions'}. [sunpy.map.mapbase]

        # 2nd: Direclty open the file using SunPy's file reader to see what the header object looks like:
        # This is exactly what is contained in: fits_map.meta
        # ----------------------------------------------
        fits_loaded = sunpy.io._fits.read(file_path)
        print(fits_loaded[0].header)
        # > FileHeader({'SIMPLE': True, 'BITPIX': 16, 'NAXIS': 2, 'NAXIS1': 10, 'NAXIS2': 10, 'AP_ORDER': 3, 'A_0_2': 1e-07, 'A_0_3': 1e-13, 'A_1_1': -1e-07,
        #               'A_1_2': -1e-09, 'A_2_0': 1e-07, 'A_2_1': 1e-13, 'A_3_0': -1e-09, 'A_ORDER': 3, 'BP_ORDER': 3, 'B_0_2': -1e-07, 'B_0_3': -1e-09,
        #               'B_1_1': 1e-07, 'B_1_2': 1e-13, 'B_2_0': -1e-07, 'B_2_1': -1e-09, 'B_3_0': 1e-13, 'B_ORDER': 3, 'CTYPE1': 'HPLN-TAN-SIP', 'CTYPE2': 'HPLT-TAN-SIP',
        #               'CUNIT1': 'deg', 'CUNIT2': 'deg', 'CRVAL1': 0.0, 'CRVAL2': 0.0, 'CRPIX1': 5.0, 'CRPIX2': 5.0, 'CDELT1': 1.0, 'CDELT2': 1.0,
        #               'DATE-OBS': '2026-11-17T00:00:00', 'COMMENT': '', 'HISTORY': '',
        #               'KEYCOMMENTS': {'SIMPLE': 'conforms to FITS standard', 'BITPIX': 'array data type', 'NAXIS': 'number of array dimensions'}}) <--dict object

        # 3rd: Pass this directly into WCS to construct the SIP WCS object as one so in lines 679-681 of mapbase.py
        # ----------------------------------------------
        try:
            wcs_sips = WCS(fits_map.meta)
        except ValueError as e:
            traceback = traceback.format_exc()
            print("Resulting Error: ", traceback)
            # > Resulting Error:  Traceback (most recent call last):
            #   File "/Users/user.name/Desktop/CCOR_Testing/test_sunpy/sunpy_sips_failure.py", line 79, in <module>
            #     wcs_sips = WCS(fits_map.meta)
            #   File "/Users/user.name/miniforge3/envs/test_sunpy/lib/python3.15/site-packages/astropy/wcs/wcs.py", line 577, in __init__
            #     header[dict_key] = orig_header[dict_key]
            #     ~~~~~~^^^^^^^^^^
            #   File "/Users/user.name/miniforge3/envs/test_sunpy/lib/python3.15/site-packages/astropy/io/fits/header.py", line 222, in __setitem__
            #     self._update((key, value, comment))
            #     ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
            #   File "/Users/user.name/miniforge3/envs/test_sunpy/lib/python3.15/site-packages/astropy/io/fits/header.py", line 1671, in _update
            #     self.append(card)
            #     ~~~~~~~~~~~^^^^^^
            #   File "/Users/user.name/miniforge3/envs/test_sunpy/lib/python3.15/site-packages/astropy/io/fits/header.py", line 1128, in append
            #     card = Card(*card)
            #   File "/Users/user.name/miniforge3/envs/test_sunpy/lib/python3.15/site-packages/astropy/io/fits/card.py", line 201, in __init__
            #     self.value = value
            #     ^^^^^^^^^^
            #   File "/Users/user.name/miniforge3/envs/test_sunpy/lib/python3.15/site-packages/astropy/io/fits/card.py", line 341, in value
            #     raise ValueError(f"Illegal value: {value!r}.")
            # ValueError: Illegal value: {'SIMPLE': 'conforms to FITS standard', 'BITPIX': 'array data type', 'NAXIS': 'number of array dimensions'}.


        # 4th: Remove the problematic header key "KEYCOMMENTS" since astropy only accepts strings/ints/floats
        # ----------------------------------------------
        if "KEYCOMMENTS" in fits_map.meta:
            fits_map.meta.pop("KEYCOMMENTS")

        print(fits_map)
        # > Valid map object is printed without error

        # And now directly generate a WCS object
        wcs_sips = WCS(fits_map.meta)
        print(wcs_sips)
        # > Number of WCS axes: 2
        # CTYPE : 'HPLN-TAN-SIP' 'HPLT-TAN-SIP'
        # CUNIT : 'deg' 'deg'
        # CRVAL : 0.0 0.0
        # CRPIX : 5.0 5.0
        # PC1_1 PC1_2  : 1.0 0.0
        # PC2_1 PC2_2  : 0.0 1.0
        # CDELT : 1.0 1.0
        # NAXIS : 10  10



### Screenshots

_No response_

### System Details

- sunpy: 8.0.1
- astropy: 8.0.2
- python: 3.15.2
- numpy: 2.5.5

### Installation method

_No response_

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions