Python astropy.io.fits.ImageHDU() Examples

The following are 30 code examples of astropy.io.fits.ImageHDU(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module astropy.io.fits , or try the search function .
Example #1
Source File: fits.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def from_tree(cls, data, ctx):
        hdus = []
        first = True
        for hdu_entry in data:
            header = fits.Header([fits.Card(*x) for x in hdu_entry['header']])
            data = hdu_entry.get('data')
            if data is not None:
                try:
                    data = data.__array__()
                except ValueError:
                    data = None
            if first:
                hdu = fits.PrimaryHDU(data=data, header=header)
                first = False
            elif data.dtype.names is not None:
                hdu = fits.BinTableHDU(data=data, header=header)
            else:
                hdu = fits.ImageHDU(data=data, header=header)
            hdus.append(hdu)
        hdulist = fits.HDUList(hdus)
        return hdulist 
Example #2
Source File: test_core.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_fix_invalid_keyword_value(self):
        hdu = fits.ImageHDU()
        hdu.header['TESTKW'] = 'foo'
        errs = hdu.req_cards('TESTKW', None,
                             lambda v: v == 'foo', 'foo', 'ignore', [])
        assert len(errs) == 0

        # Now try a test that will fail, and ensure that an error will be
        # raised in 'exception' mode
        errs = hdu.req_cards('TESTKW', None, lambda v: v == 'bar', 'bar',
                             'exception', [])
        assert len(errs) == 1
        assert errs[0][1] == "'TESTKW' card has invalid value 'foo'."

        # See if fixing will work
        hdu.req_cards('TESTKW', None, lambda v: v == 'bar', 'bar', 'silentfix',
                      [])
        assert hdu.header['TESTKW'] == 'bar' 
Example #3
Source File: test_nonstandard.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_create_fitshdu_from_filename(self):
        """Regression test on `FitsHDU.fromfile`"""

        # Build up a simple test FITS file
        a = np.arange(100)
        phdu = fits.PrimaryHDU(data=a)
        phdu.header['TEST1'] = 'A'
        phdu.header['TEST2'] = 'B'
        imghdu = fits.ImageHDU(data=a + 1)
        phdu.header['TEST3'] = 'C'
        phdu.header['TEST4'] = 'D'

        hdul = fits.HDUList([phdu, imghdu])
        hdul.writeto(self.temp('test.fits'))

        fitshdu = fits.FitsHDU.fromfile(self.temp('test.fits'))
        hdul2 = fitshdu.hdulist

        assert len(hdul2) == 2
        assert fits.FITSDiff(hdul, hdul2).identical 
Example #4
Source File: fits_utils.py    From banzai with GNU General Public License v3.0 6 votes vote down vote up
def pack(uncompressed_hdulist: fits.HDUList) -> fits.HDUList:
    if uncompressed_hdulist[0].data is None:
        primary_hdu = fits.PrimaryHDU(header=uncompressed_hdulist[0].header)
        hdulist = [primary_hdu]
    else:
        primary_hdu = fits.PrimaryHDU()
        compressed_hdu = fits.CompImageHDU(data=np.ascontiguousarray(uncompressed_hdulist[0].data),
                                           header=uncompressed_hdulist[0].header, quantize_level=64,
                                           dither_seed=2048, quantize_method=1)
        hdulist = [primary_hdu, compressed_hdu]

    for hdu in uncompressed_hdulist[1:]:
        if isinstance(hdu, fits.ImageHDU):
            compressed_hdu = fits.CompImageHDU(data=np.ascontiguousarray(hdu.data), header=hdu.header,
                                               quantize_level=64, quantize_method=1)
            hdulist.append(compressed_hdu)
        else:
            hdulist.append(hdu)
    return fits.HDUList(hdulist) 
Example #5
Source File: fits.py    From everest with MIT License 6 votes vote down vote up
def ApertureHDU(model):
    '''
    Construct the HDU containing the aperture used to de-trend.

    '''

    # Get mission cards
    cards = model._mission.HDUCards(model.meta, hdu=3)

    # Add EVEREST info
    cards.append(('COMMENT', '************************'))
    cards.append(('COMMENT', '*     EVEREST INFO     *'))
    cards.append(('COMMENT', '************************'))
    cards.append(('MISSION', model.mission, 'Mission name'))
    cards.append(('VERSION', EVEREST_MAJOR_MINOR, 'EVEREST pipeline version'))
    cards.append(('SUBVER', EVEREST_VERSION, 'EVEREST pipeline subversion'))
    cards.append(('DATE', strftime('%Y-%m-%d'),
                  'EVEREST file creation date (YYYY-MM-DD)'))

    # Create the HDU
    header = pyfits.Header(cards=cards)
    hdu = pyfits.ImageHDU(data=model.aperture,
                          header=header, name='APERTURE MASK')

    return hdu 
Example #6
Source File: save_seed.py    From mirage with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def save_single_fits(image, name, key_dict=None, image2=None, image2type=None):
        # Save an array into the first extension of a fits file
        h0 = fits.PrimaryHDU()
        h1 = fits.ImageHDU(image, name='DATA')
        if image2 is not None:
            h2 = fits.ImageHDU(image2)
            if image2type is not None:
                h2.header['EXTNAME'] = image2type

        # if a keyword dictionary is provided, put the
        # keywords into the 0th and 1st extension headers
        if key_dict is not None:
            for key in key_dict:
                h0.header[key] = key_dict[key]
                h1.header[key] = key_dict[key]

        if image2 is None:
            hdulist = fits.HDUList([h0, h1])
        else:
            hdulist = fits.HDUList([h0, h1, h2])
        hdulist.writeto(name, overwrite=True) 
Example #7
Source File: test_hdulist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_extname_in_hdulist(self):
        """
        Tests to make sure that the 'in' operator works.

        Regression test for https://github.com/astropy/astropy/issues/3060
        """
        with fits.open(self.data('o4sp040b0_raw.fits')) as hdulist:
            hdulist.append(fits.ImageHDU(name='a'))

            assert 'a' in hdulist
            assert 'A' in hdulist
            assert ('a', 1) in hdulist
            assert ('A', 1) in hdulist
            assert 'b' not in hdulist
            assert ('a', 2) not in hdulist
            assert ('b', 1) not in hdulist
            assert ('b', 2) not in hdulist
            assert hdulist[0] in hdulist
            assert fits.ImageHDU() not in hdulist 
Example #8
Source File: test_core.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_updated_file_permissions(self):
        """
        Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/79

        Tests that when a FITS file is modified in update mode, the file
        permissions are preserved.
        """

        filename = self.temp('test.fits')
        hdul = [fits.PrimaryHDU(), fits.ImageHDU()]
        hdul = fits.HDUList(hdul)
        hdul.writeto(filename)

        old_mode = os.stat(filename).st_mode

        hdul = fits.open(filename, mode='update')
        hdul.insert(1, fits.ImageHDU())
        hdul.flush()
        hdul.close()

        assert old_mode == os.stat(filename).st_mode 
Example #9
Source File: targetpixelfile.py    From lightkurve with MIT License 6 votes vote down vote up
def _make_aperture_extension(self):
        """Create the aperture mask extension (i.e. extension #2)."""
        mask = 3 * np.ones((self.n_rows, self.n_cols), dtype='int32')
        hdu = fits.ImageHDU(mask)

        # Set the header from the template TPF again
        template = self._header_template(2)
        for kw in template:
            if kw not in ['XTENSION', 'NAXIS1', 'NAXIS2', 'CHECKSUM', 'BITPIX']:
                try:
                    hdu.header[kw] = (self.keywords[kw],
                                      self.keywords.comments[kw])
                except KeyError:
                    hdu.header[kw] = (template[kw],
                                      template.comments[kw])

        # Override the defaults where necessary
        for keyword in ['CTYPE1', 'CTYPE2', 'CRPIX1', 'CRPIX2', 'CRVAL1', 'CRVAL2', 'CUNIT1',
                        'CUNIT2', 'CDELT1', 'CDELT2', 'PC1_1', 'PC1_2', 'PC2_1', 'PC2_2']:
                hdu.header[keyword] = ""  # override wcs keywords
        hdu.header['EXTNAME'] = 'APERTURE'
        return hdu 
Example #10
Source File: test_hdulist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_new_hdu_extname(self):
        """
        Tests that new extension HDUs that are added to an HDUList can be
        properly indexed by their EXTNAME/EXTVER (regression test for
        ticket:48).
        """

        with fits.open(self.data('test0.fits')) as f:
            hdul = fits.HDUList()
            hdul.append(f[0].copy())
            hdu = fits.ImageHDU(header=f[1].header)
            hdul.append(hdu)

        assert hdul[1].header['EXTNAME'] == 'SCI'
        assert hdul[1].header['EXTVER'] == 1
        assert hdul.index_of(('SCI', 1)) == 1
        assert hdul.index_of(hdu) == len(hdul) - 1 
Example #11
Source File: test_header.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_header_extend_unique(self):
        """
        Test extending the header with and without unique=True.
        """
        hdu = fits.PrimaryHDU()
        hdu2 = fits.ImageHDU()
        hdu.header['MYKEY'] = ('some val', 'some comment')
        hdu2.header['MYKEY'] = ('some other val', 'some other comment')
        hdu.header.extend(hdu2.header)
        assert len(hdu.header) == 6
        assert hdu.header[-2] == 'some val'
        assert hdu.header[-1] == 'some other val'

        hdu = fits.PrimaryHDU()
        hdu2 = fits.ImageHDU()
        hdu.header['MYKEY'] = ('some val', 'some comment')
        hdu2.header['MYKEY'] = ('some other val', 'some other comment')
        hdu.header.extend(hdu2.header, unique=True)
        assert len(hdu.header) == 5
        assert hdu.header[-1] == 'some val' 
Example #12
Source File: test_hdulist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_shallow_copy(self):
        """
        Tests that `HDUList.__copy__()` and `HDUList.copy()` return a
        shallow copy (regression test for #7211).
        """

        n = np.arange(10.0)
        primary_hdu = fits.PrimaryHDU(n)
        hdu = fits.ImageHDU(n)
        hdul = fits.HDUList([primary_hdu, hdu])

        for hdulcopy in (hdul.copy(), copy.copy(hdul)):
            assert isinstance(hdulcopy, fits.HDUList)
            assert hdulcopy is not hdul
            assert hdulcopy[0] is hdul[0]
            assert hdulcopy[1] is hdul[1] 
Example #13
Source File: test_hdulist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_deep_copy(self):
        """
        Tests that `HDUList.__deepcopy__()` returns a deep copy.
        """

        n = np.arange(10.0)
        primary_hdu = fits.PrimaryHDU(n)
        hdu = fits.ImageHDU(n)
        hdul = fits.HDUList([primary_hdu, hdu])

        hdulcopy = copy.deepcopy(hdul)

        assert isinstance(hdulcopy, fits.HDUList)
        assert hdulcopy is not hdul

        for index in range(len(hdul)):
            assert hdulcopy[index] is not hdul[index]
            assert hdulcopy[index].header == hdul[index].header
            np.testing.assert_array_equal(hdulcopy[index].data, hdul[index].data) 
Example #14
Source File: test_header.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_header_extend_update_commentary(self):
        """
        Test extending header with and without unique=True and commentary
        cards in the header being added.

        Though not quite the same as astropy/astropy#3967, update=True hits
        the same if statement as that issue.
        """
        for commentary_card in ['', 'COMMENT', 'HISTORY']:
            for is_update in [True, False]:
                hdu = fits.PrimaryHDU()
                # Make sure we are testing the case we want.
                assert commentary_card not in hdu.header
                hdu2 = fits.ImageHDU()
                hdu2.header[commentary_card] = 'My text'
                hdu.header.extend(hdu2.header, update=is_update)
                assert len(hdu.header) == 5
                assert hdu.header[commentary_card][0] == 'My text' 
Example #15
Source File: test_hdulist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_insert_image_extension_to_primary_in_non_empty_list(self):
        """
        Tests inserting a Simple Image ExtensionHDU to a non-empty HDUList
        as the primary HDU.
        """

        with fits.open(self.data('tb.fits')) as hdul:
            hdu = fits.ImageHDU(np.arange(100, dtype=np.int32))
            hdul.insert(0, hdu)

            info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 5, (100,), 'int32', ''),
                    (1, '', 1, 'ImageHDU', 12, (), '', ''),
                    (2, '', 1, 'BinTableHDU', 24, '2R x 4C', '[1J, 3A, 1E, 1L]', '')]

            assert hdul.info(output=False) == info

            hdul.writeto(self.temp('test-insert.fits'))

        assert fits.info(self.temp('test-insert.fits'), output=False) == info 
Example #16
Source File: test_hdulist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_insert_groupshdu_to_non_empty_list(self):
        """Tests inserting a Simple GroupsHDU to an empty HDUList."""

        hdul = fits.HDUList()
        hdu = fits.PrimaryHDU(np.arange(100, dtype=np.int32))
        hdul.insert(0, hdu)
        hdu = fits.GroupsHDU()

        with pytest.raises(ValueError):
            hdul.insert(1, hdu)

        info = [(0, 'PRIMARY', 1, 'GroupsHDU', 8, (), '',
                 '1 Groups  0 Parameters'),
                (1, '', 1, 'ImageHDU', 6, (100,), 'int32', '')]

        hdul.insert(0, hdu)

        assert hdul.info(output=False) == info

        hdul.writeto(self.temp('test-insert.fits'))

        assert fits.info(self.temp('test-insert.fits'), output=False) == info 
Example #17
Source File: test_header.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_header_extend_update(self):
        """
        Test extending the header with and without update=True.
        """

        hdu = fits.PrimaryHDU()
        hdu2 = fits.ImageHDU()
        hdu.header['MYKEY'] = ('some val', 'some comment')
        hdu.header['HISTORY'] = 'history 1'
        hdu2.header['MYKEY'] = ('some other val', 'some other comment')
        hdu2.header['HISTORY'] = 'history 1'
        hdu2.header['HISTORY'] = 'history 2'
        hdu.header.extend(hdu2.header)
        assert len(hdu.header) == 9
        assert ('MYKEY', 0) in hdu.header
        assert ('MYKEY', 1) in hdu.header
        assert hdu.header[('MYKEY', 1)] == 'some other val'
        assert len(hdu.header['HISTORY']) == 3
        assert hdu.header[-1] == 'history 2'

        hdu = fits.PrimaryHDU()
        hdu.header['MYKEY'] = ('some val', 'some comment')
        hdu.header['HISTORY'] = 'history 1'
        hdu.header.extend(hdu2.header, update=True)
        assert len(hdu.header) == 7
        assert ('MYKEY', 0) in hdu.header
        assert ('MYKEY', 1) not in hdu.header
        assert hdu.header['MYKEY'] == 'some other val'
        assert len(hdu.header['HISTORY']) == 2
        assert hdu.header[-1] == 'history 2' 
Example #18
Source File: test_checksum.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_hdu_writeto(self):
        n = np.arange(100, dtype='int16')
        hdu = fits.ImageHDU(n)
        hdu.writeto(self.temp('tmp.fits'), checksum=True)
        hdul = fits.open(self.temp('tmp.fits'), checksum=True)
        self._check_checksums(hdul[0])
        hdul.close() 
Example #19
Source File: test_checksum.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_compressed_image_data_int16(self):
        n = np.arange(100, dtype='int16')
        hdu = fits.ImageHDU(n)
        comp_hdu = fits.CompImageHDU(hdu.data, hdu.header)
        comp_hdu.writeto(self.temp('tmp.fits'), checksum=True)
        hdu.writeto(self.temp('uncomp.fits'), checksum=True)
        with fits.open(self.temp('tmp.fits'), checksum=True) as hdul:
            assert np.all(hdul[1].data == comp_hdu.data)
            assert np.all(hdul[1].data == hdu.data)
            assert 'CHECKSUM' in hdul[0].header
            assert hdul[0].header['CHECKSUM'] == 'D8iBD6ZAD6fAD6ZA'
            assert 'DATASUM' in hdul[0].header
            assert hdul[0].header['DATASUM'] == '0'

            assert 'CHECKSUM' in hdul[1].header
            assert hdul[1]._header['CHECKSUM'] == 'J5cCJ5c9J5cAJ5c9'
            assert 'DATASUM' in hdul[1].header
            assert hdul[1]._header['DATASUM'] == '2453673070'
            assert 'CHECKSUM' in hdul[1].header

            with fits.open(self.temp('uncomp.fits'), checksum=True) as hdul2:
                header_comp = hdul[1]._header
                header_uncomp = hdul2[1].header
                assert 'ZHECKSUM' in header_comp
                assert 'CHECKSUM' in header_uncomp
                assert header_uncomp['CHECKSUM'] == 'ZE94eE91ZE91bE91'
                assert header_comp['ZHECKSUM'] == header_uncomp['CHECKSUM']
                assert 'ZDATASUM' in header_comp
                assert 'DATASUM' in header_uncomp
                assert header_uncomp['DATASUM'] == '160565700'
                assert header_comp['ZDATASUM'] == header_uncomp['DATASUM'] 
Example #20
Source File: test_checksum.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_compressed_image_data_float32(self):
        n = np.arange(100, dtype='float32')
        hdu = fits.ImageHDU(n)
        comp_hdu = fits.CompImageHDU(hdu.data, hdu.header)
        comp_hdu.writeto(self.temp('tmp.fits'), checksum=True)
        hdu.writeto(self.temp('uncomp.fits'), checksum=True)
        with fits.open(self.temp('tmp.fits'), checksum=True) as hdul:
            assert np.all(hdul[1].data == comp_hdu.data)
            assert np.all(hdul[1].data == hdu.data)
            assert 'CHECKSUM' in hdul[0].header
            assert hdul[0].header['CHECKSUM'] == 'D8iBD6ZAD6fAD6ZA'
            assert 'DATASUM' in hdul[0].header
            assert hdul[0].header['DATASUM'] == '0'

            assert 'CHECKSUM' in hdul[1].header
            assert 'DATASUM' in hdul[1].header

            if not sys.platform.startswith('win32'):
                # The checksum ends up being different on Windows, possibly due
                # to slight floating point differences
                assert hdul[1]._header['CHECKSUM'] == 'eATIf3SHe9SHe9SH'
                assert hdul[1]._header['DATASUM'] == '1277667818'

            with fits.open(self.temp('uncomp.fits'), checksum=True) as hdul2:
                header_comp = hdul[1]._header
                header_uncomp = hdul2[1].header
                assert 'ZHECKSUM' in header_comp
                assert 'CHECKSUM' in header_uncomp
                assert header_uncomp['CHECKSUM'] == 'Cgr5FZo2Cdo2CZo2'
                assert header_comp['ZHECKSUM'] == header_uncomp['CHECKSUM']
                assert 'ZDATASUM' in header_comp
                assert 'DATASUM' in header_uncomp
                assert header_uncomp['DATASUM'] == '2393636889'
                assert header_comp['ZDATASUM'] == header_uncomp['DATASUM'] 
Example #21
Source File: test_header.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_hdu_writeto_mode(self, mode):

        with open(self.temp('mode.fits'), mode=mode) as ff:
            hdu = fits.ImageHDU(data=np.ones(5))
            hdu.writeto(ff) 
Example #22
Source File: test_core.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ignore_verification_error(self):
        hdu = fits.ImageHDU()
        # The default here would be to issue a warning; ensure that no warnings
        # or exceptions are raised
        with catch_warnings():
            warnings.simplefilter('error')
            del hdu.header['NAXIS']
            try:
                hdu.verify('ignore')
            except Exception as exc:
                self.fail('An exception occurred when the verification error '
                          'should have been ignored: {}'.format(exc))
        # Make sure the error wasn't fixed either, silently or otherwise
        assert 'NAXIS' not in hdu.header 
Example #23
Source File: test_hdulist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_append_extension_to_empty_list(self):
        """Tests appending a Simple ImageHDU to an empty HDUList."""

        hdul = fits.HDUList()
        hdu = fits.ImageHDU(np.arange(100, dtype=np.int32))
        hdul.append(hdu)
        info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 4, (100,), 'int32', '')]
        assert hdul.info(output=False) == info

        hdul.writeto(self.temp('test-append.fits'))

        assert fits.info(self.temp('test-append.fits'), output=False) == info 
Example #24
Source File: test_hdulist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_append_primary_to_non_empty_list(self):
        """Tests appending a Simple PrimaryHDU to a non-empty HDUList."""

        with fits.open(self.data('arange.fits')) as hdul:
            hdu = fits.PrimaryHDU(np.arange(100, dtype=np.int32))
            hdul.append(hdu)

            info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 7, (11, 10, 7), 'int32', ''),
                    (1, '', 1, 'ImageHDU', 6, (100,), 'int32', '')]

            assert hdul.info(output=False) == info

            hdul.writeto(self.temp('test-append.fits'))

        assert fits.info(self.temp('test-append.fits'), output=False) == info 
Example #25
Source File: test_hdulist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_iteration_of_lazy_loaded_hdulist(self):
        """
        Regression test for https://github.com/astropy/astropy/issues/5585
        """
        hdulist = fits.HDUList(fits.PrimaryHDU())
        hdulist.append(fits.ImageHDU(name='SCI'))
        hdulist.append(fits.ImageHDU(name='SCI'))
        hdulist.append(fits.ImageHDU(name='nada'))
        hdulist.append(fits.ImageHDU(name='SCI'))

        filename = self.temp('many_extension.fits')
        hdulist.writeto(filename)
        f = fits.open(filename)

        # Check that all extensions are read if f is not sliced
        all_exts = [ext for ext in f]
        assert len(all_exts) == 5

        # Reload the file to ensure we are still lazy loading
        f.close()
        f = fits.open(filename)

        # Try a simple slice with no conditional on the ext. This is essentially
        # the reported failure.
        all_exts_but_zero = [ext for ext in f[1:]]
        assert len(all_exts_but_zero) == 4

        # Reload the file to ensure we are still lazy loading
        f.close()
        f = fits.open(filename)

        # Check whether behavior is proper if the upper end of the slice is not
        # omitted.
        read_exts = [ext for ext in f[1:4] if ext.header['EXTNAME'] == 'SCI']
        assert len(read_exts) == 2
        f.close() 
Example #26
Source File: test_hdulist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_invalid_hdu_key_in_contains(self):
        """
        Make sure invalid keys in the 'in' operator return False.
        Regression test for https://github.com/astropy/astropy/issues/5583
        """
        hdulist = fits.HDUList(fits.PrimaryHDU())
        hdulist.append(fits.ImageHDU())
        hdulist.append(fits.ImageHDU())

        # A more or less random assortment of things which are not valid keys.
        bad_keys = [None, 3.5, {}]

        for key in bad_keys:
            assert not (key in hdulist) 
Example #27
Source File: test_hdulist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_insert_extension_to_empty_list(self):
        """Tests inserting a Simple ImageHDU to an empty HDUList."""

        hdul = fits.HDUList()
        hdu = fits.ImageHDU(np.arange(100, dtype=np.int32))
        hdul.insert(0, hdu)

        info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 4, (100,), 'int32', '')]

        assert hdul.info(output=False) == info

        hdul.writeto(self.temp('test-insert.fits'))

        assert fits.info(self.temp('test-insert.fits'), output=False) == info 
Example #28
Source File: test_hdulist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_insert_primary_to_non_empty_list(self):
        """Tests inserting a Simple PrimaryHDU to a non-empty HDUList."""

        with fits.open(self.data('arange.fits')) as hdul:
            hdu = fits.PrimaryHDU(np.arange(100, dtype=np.int32))
            hdul.insert(1, hdu)

            info = [(0, 'PRIMARY', 1, 'PrimaryHDU', 7, (11, 10, 7), 'int32', ''),
                    (1, '', 1, 'ImageHDU', 6, (100,), 'int32', '')]

            assert hdul.info(output=False) == info

            hdul.writeto(self.temp('test-insert.fits'))

        assert fits.info(self.temp('test-insert.fits'), output=False) == info 
Example #29
Source File: test_hdulist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_update_resized_header2(self):
        """
        Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/150

        This is similar to test_update_resized_header, but specifically tests a
        case of multiple consecutive flush() calls on the same HDUList object,
        where each flush() requires a resize.
        """

        data1 = np.arange(100)
        data2 = np.arange(100) + 100
        phdu = fits.PrimaryHDU(data=data1)
        hdu = fits.ImageHDU(data=data2)

        phdu.writeto(self.temp('temp.fits'))

        with fits.open(self.temp('temp.fits'), mode='append') as hdul:
            hdul.append(hdu)

        with fits.open(self.temp('temp.fits'), mode='update') as hdul:
            idx = 1
            while len(str(hdul[0].header)) <= 2880 * 2:
                hdul[0].header[f'TEST{idx}'] = idx
                idx += 1
            hdul.flush()
            hdul.append(hdu)

        with fits.open(self.temp('temp.fits')) as hdul:
            assert (hdul[0].data == data1).all()
            assert hdul[1].header == hdu.header
            assert (hdul[1].data == data2).all()
            assert (hdul[2].data == data2).all() 
Example #30
Source File: test_hdulist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_fix_extend_keyword(self):
        hdul = fits.HDUList()
        hdul.append(fits.PrimaryHDU())
        hdul.append(fits.ImageHDU())
        del hdul[0].header['EXTEND']
        hdul.verify('silentfix')

        assert 'EXTEND' in hdul[0].header
        assert hdul[0].header['EXTEND'] is True