Python astropy.io.fits.writeto() Examples

The following are 30 code examples of astropy.io.fits.writeto(). 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: test_image.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_fortran_array_non_contiguous(self):
        # Test that files are being correctly written+read for 'C' and 'F' order arrays
        a = np.arange(105).reshape(3,5,7)
        b = np.asfortranarray(a)

        # writting to str specified files
        afits = self.temp('a_str_slice.fits')
        bfits = self.temp('b_str_slice.fits')
        fits.PrimaryHDU(data=a[::2, ::2]).writeto(afits)
        fits.PrimaryHDU(data=b[::2, ::2]).writeto(bfits)
        np.testing.assert_array_equal(fits.getdata(afits), a[::2, ::2])
        np.testing.assert_array_equal(fits.getdata(bfits), a[::2, ::2])

        # writting to fileobjs
        aafits = self.temp('a_fileobj_slice.fits')
        bbfits = self.temp('b_fileobj_slice.fits')
        with open(aafits, mode='wb') as fd:
            fits.PrimaryHDU(data=a[::2, ::2]).writeto(fd)
        with open(bbfits, mode='wb') as fd:
            fits.PrimaryHDU(data=b[::2, ::2]).writeto(fd)
        np.testing.assert_array_equal(fits.getdata(aafits), a[::2, ::2])
        np.testing.assert_array_equal(fits.getdata(bbfits), a[::2, ::2]) 
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_writeto_append_mode_gzip(self):
        """Regression test for
        https://github.com/spacetelescope/PyFITS/issues/33

        Check that a new GzipFile opened in append mode can be used to write
        out a new FITS file.
        """

        # Note: when opening a GzipFile the 'b+' is superfluous, but this was
        # still how the original test case looked
        # Note: with statement not supported on GzipFile in older Python
        # versions
        fileobj = gzip.GzipFile(self.temp('test.fits.gz'), 'ab+')
        h = fits.PrimaryHDU()
        try:
            h.writeto(fileobj)
        finally:
            fileobj.close()

        with fits.open(self.temp('test.fits.gz')) as hdul:
            assert hdul[0].header == h.header 
Example #3
Source File: test_core.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_writeto_2(self):
        """
        Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/107

        Test of `writeto()` with a trivial header containing a single keyword.
        """
        filename = self.temp('array.fits')
        data = np.zeros((100, 100))
        header = fits.Header()
        header.set('CRPIX1', 1.)
        fits.writeto(filename, data, header=header,
                     overwrite=True, output_verify='silentfix')
        with fits.open(filename) as hdul:
            assert len(hdul) == 1
            assert (data == hdul[0].data).all()
            assert 'CRPIX1' in hdul[0].header
            assert hdul[0].header['CRPIX1'] == 1.0 
Example #4
Source File: test_core.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_write_read_gzip_file(self):
        """
        Regression test for https://github.com/astropy/astropy/issues/2794

        Ensure files written through gzip are readable.
        """

        data = np.arange(100)
        hdu = fits.PrimaryHDU(data=data)
        hdu.writeto(self.temp('test.fits.gz'))

        with open(self.temp('test.fits.gz'), 'rb') as f:
            assert f.read(3) == GZIP_MAGIC

        with fits.open(self.temp('test.fits.gz')) as hdul:
            assert np.all(hdul[0].data == data) 
Example #5
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 #6
Source File: test_core.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_write_bytesio_discontiguous(self):
        """
        Regression test related to
        https://github.com/astropy/astropy/issues/2794#issuecomment-55441539

        Demonstrates that writing an HDU containing a discontiguous Numpy array
        should work properly.
        """

        data = np.arange(100)[::3]
        hdu = fits.PrimaryHDU(data=data)
        fileobj = io.BytesIO()
        hdu.writeto(fileobj)

        fileobj.seek(0)

        with fits.open(fileobj) as h:
            assert np.all(h[0].data == data) 
Example #7
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_extname(self, capsys):
        phdu = fits.PrimaryHDU()
        ihdu = fits.ImageHDU()
        ihdu.header['EXTNAME'] = 12345678
        hdul = fits.HDUList([phdu, ihdu])
        filename = self.temp('temp.fits')

        pytest.raises(fits.VerifyError, hdul.writeto, filename,
                      output_verify='exception')
        with pytest.warns(fits.verify.VerifyWarning,
                          match=r'Verification reported errors'):
            hdul.writeto(filename, output_verify='fix')
        with fits.open(filename):
            assert hdul[1].name == '12345678'
            assert hdul[1].header['EXTNAME'] == '12345678'

        hdul.close() 
Example #8
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 #9
Source File: test_core.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_byteswap(self):
        p = fits.PrimaryHDU()
        l = fits.HDUList()

        n = np.zeros(3, dtype='i2')
        n[0] = 1
        n[1] = 60000
        n[2] = 2

        c = fits.Column(name='foo', format='i2', bscale=1, bzero=32768,
                        array=n)
        t = fits.BinTableHDU.from_columns([c])

        l.append(p)
        l.append(t)

        l.writeto(self.temp('test.fits'), overwrite=True)

        with fits.open(self.temp('test.fits')) as p:
            assert p[1].data[1]['foo'] == 60000.0 
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_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 #11
Source File: test_checksum.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_binary_table_data(self):
        a1 = np.array(['NGC1001', 'NGC1002', 'NGC1003'])
        a2 = np.array([11.1, 12.3, 15.2])
        col1 = fits.Column(name='target', format='20A', array=a1)
        col2 = fits.Column(name='V_mag', format='E', array=a2)
        cols = fits.ColDefs([col1, col2])
        tbhdu = fits.BinTableHDU.from_columns(cols)
        tbhdu.writeto(self.temp('tmp.fits'), overwrite=True, checksum=True)
        with fits.open(self.temp('tmp.fits'), checksum=True) as hdul:
            assert comparerecords(tbhdu.data, hdul[1].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'] == 'aD1Oa90MaC0Ma90M'
            assert 'DATASUM' in hdul[1].header
            assert hdul[1].header['DATASUM'] == '1062205743' 
Example #12
Source File: test_checksum.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_variable_length_table_data(self):
        c1 = fits.Column(name='var', format='PJ()',
                         array=np.array([[45.0, 56], np.array([11, 12, 13])],
                         'O'))
        c2 = fits.Column(name='xyz', format='2I', array=[[11, 3], [12, 4]])
        tbhdu = fits.BinTableHDU.from_columns([c1, c2])
        tbhdu.writeto(self.temp('tmp.fits'), overwrite=True, checksum=True)
        with fits.open(self.temp('tmp.fits'), checksum=True) as hdul:
            assert comparerecords(tbhdu.data, hdul[1].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'] == 'YIGoaIEmZIEmaIEm'
            assert 'DATASUM' in hdul[1].header
            assert hdul[1].header['DATASUM'] == '1507485' 
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_update_filelike(self):
        """Test opening a file-like object in update mode and resizing the
        HDU.
        """

        sf = io.BytesIO()
        arr = np.zeros((100, 100))
        hdu = fits.PrimaryHDU(data=arr)
        hdu.writeto(sf)

        sf.seek(0)
        arr = np.zeros((200, 200))
        hdul = fits.open(sf, mode='update')
        hdul[0].data = arr
        hdul.flush()

        sf.seek(0)
        hdul = fits.open(sf)
        assert len(hdul) == 1
        assert (hdul[0].data == arr).all() 
Example #14
Source File: read_spec.py    From serval with MIT License 6 votes vote down vote up
def write_res(filename, datas, extnames, header='', hdrref=None, clobber=False):
   if not header and hdrref: header = pyfits.getheader(hdrref)
   hdu = pyfits.PrimaryHDU(header=header)
   warnings.resetwarnings() # supress nasty overwrite warning http://pythonhosted.org/pyfits/users_guide/users_misc.html
   warnings.filterwarnings('ignore', category=UserWarning, append=True)
   hdu.writeto(filename, clobber=clobber, output_verify='fix')
   warnings.resetwarnings()
   warnings.filterwarnings('always', category=UserWarning, append=True)

   for i,extname in enumerate(extnames):
     data = datas[extname]
     if isinstance(data, np.ndarray):
        pyfits.append(filename, data)
     else:
        1/0

     pyfits.setval(filename, 'EXTNAME', value=extname, ext=i+1)
   #fitsio.write(filename, flux) 
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_open_file_with_end_padding(self):
        """Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/106

        Open files with end padding bytes.
        """

        with fits.open(self.data('test0.fits'),
                       do_not_scale_image_data=True) as hdul:
            info = hdul.info(output=False)
            hdul.writeto(self.temp('temp.fits'))

        with open(self.temp('temp.fits'), 'ab') as f:
            f.seek(0, os.SEEK_END)
            f.write(b'\0' * 2880)
        with ignore_warnings():
            assert info == fits.info(self.temp('temp.fits'), output=False,
                                     do_not_scale_image_data=True) 
Example #16
Source File: test_image.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_fortran_array(self):
        # Test that files are being correctly written+read for "C" and "F" order arrays
        a = np.arange(21).reshape(3,7)
        b = np.asfortranarray(a)

        afits = self.temp('a_str.fits')
        bfits = self.temp('b_str.fits')
        # writting to str specified files
        fits.PrimaryHDU(data=a).writeto(afits)
        fits.PrimaryHDU(data=b).writeto(bfits)
        np.testing.assert_array_equal(fits.getdata(afits), a)
        np.testing.assert_array_equal(fits.getdata(bfits), a)

        # writting to fileobjs
        aafits = self.temp('a_fileobj.fits')
        bbfits = self.temp('b_fileobj.fits')
        with open(aafits, mode='wb') as fd:
            fits.PrimaryHDU(data=a).writeto(fd)
        with open(bbfits, mode='wb') as fd:
            fits.PrimaryHDU(data=b).writeto(fd)
        np.testing.assert_array_equal(fits.getdata(aafits), a)
        np.testing.assert_array_equal(fits.getdata(bbfits), a) 
Example #17
Source File: test_checksum.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_hdu_writeto_existing(self):
        """
        Tests that when using writeto with checksum=True, a checksum and
        datasum are added to HDUs that did not previously have one.

        Regression test for https://github.com/spacetelescope/PyFITS/issues/8
        """

        with fits.open(self.data('tb.fits')) as hdul:
            hdul.writeto(self.temp('test.fits'), checksum=True)

        with fits.open(self.temp('test.fits')) as hdul:
            assert 'CHECKSUM' in hdul[0].header
            # These checksums were verified against CFITSIO
            assert hdul[0].header['CHECKSUM'] == '7UgqATfo7TfoATfo'
            assert 'DATASUM' in hdul[0].header
            assert hdul[0].header['DATASUM'] == '0'
            assert 'CHECKSUM' in hdul[1].header
            assert hdul[1].header['CHECKSUM'] == '99daD8bX98baA8bU'
            assert 'DATASUM' in hdul[1].header
            assert hdul[1].header['DATASUM'] == '1829680925' 
Example #18
Source File: prep.py    From grizli with MIT License 6 votes vote down vote up
def update_wcs_fits_log(file, wcs_ref, xyscale=[0, 0, 0, 1], initialize=True, replace=('.fits', '.wcslog.fits'), wcsname='SHIFT'):
    """
    Make FITS log when updating WCS
    """
    new_hdu = wcs_ref.to_fits(relax=True)[0]
    new_hdu.header['XSHIFT'] = xyscale[0]
    new_hdu.header['YSHIFT'] = xyscale[1]
    new_hdu.header['ROT'] = xyscale[2], 'WCS fit rotation, degrees'
    new_hdu.header['SCALE'] = xyscale[3], 'WCS fit scale'
    new_hdu.header['WCSNAME'] = wcsname

    wcs_logfile = file.replace(replace[0], replace[1])

    if os.path.exists(wcs_logfile):
        if initialize:
            os.remove(wcs_logfile)
            hdu = pyfits.HDUList([pyfits.PrimaryHDU()])
        else:
            hdu = pyfits.open(wcs_logfile)
    else:
        hdu = pyfits.HDUList([pyfits.PrimaryHDU()])

    hdu.append(new_hdu)
    hdu.writeto(wcs_logfile, overwrite=True, output_verify='fix') 
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_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 #20
Source File: test_hdulist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_write_hdulist_to_stream(self):
        """
        Unit test for https://github.com/astropy/astropy/issues/7435
        to ensure that an HDUList can be written to a stream.
        """
        data = np.array([[1, 2, 3], [4, 5, 6]])
        hdu = fits.PrimaryHDU(data)
        hdulist = fits.HDUList([hdu])

        with open(self.temp('test.fits'), 'wb') as fout:
            with subprocess.Popen(["cat"], stdin=subprocess.PIPE,
                                  stdout=fout) as p:
                hdulist.writeto(p.stdin) 
Example #21
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(self):
        with fits.open(self.data('comp.fits')) as h1:
            h1.writeto(self.temp('tmp.fits'), overwrite=True, checksum=True)
            with fits.open(self.temp('tmp.fits'), checksum=True) as h2:
                assert np.all(h1[1].data == h2[1].data)
                assert 'CHECKSUM' in h2[0].header
                assert h2[0].header['CHECKSUM'] == 'D8iBD6ZAD6fAD6ZA'
                assert 'DATASUM' in h2[0].header
                assert h2[0].header['DATASUM'] == '0'
                assert 'CHECKSUM' in h2[1].header
                assert h2[1].header['CHECKSUM'] == 'ZeAbdb8aZbAabb7a'
                assert 'DATASUM' in h2[1].header
                assert h2[1].header['DATASUM'] == '113055149' 
Example #22
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 #23
Source File: test_image.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_primary_with_extname(self):
        """Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/151

        Tests that the EXTNAME keyword works with Primary HDUs as well, and
        interacts properly with the .name attribute.  For convenience
        hdulist['PRIMARY'] will still refer to the first HDU even if it has an
        EXTNAME not equal to 'PRIMARY'.
        """

        prihdr = fits.Header([('EXTNAME', 'XPRIMARY'), ('EXTVER', 1)])
        hdul = fits.HDUList([fits.PrimaryHDU(header=prihdr)])
        assert 'EXTNAME' in hdul[0].header
        assert hdul[0].name == 'XPRIMARY'
        assert hdul[0].name == hdul[0].header['EXTNAME']

        info = [(0, 'XPRIMARY', 1, 'PrimaryHDU', 5, (), '', '')]
        assert hdul.info(output=False) == info

        assert hdul['PRIMARY'] is hdul['XPRIMARY']
        assert hdul['PRIMARY'] is hdul[('XPRIMARY', 1)]

        hdul[0].name = 'XPRIMARY2'
        assert hdul[0].header['EXTNAME'] == 'XPRIMARY2'

        hdul.writeto(self.temp('test.fits'))
        with fits.open(self.temp('test.fits')) as hdul:
            assert hdul[0].name == 'XPRIMARY2'

    # This test used to fail on Windows - if it fails again in future, see
    # https://github.com/astropy/astropy/issues/5797
    # The warning appears on Windows but cannot be explicitly caught. 
Example #24
Source File: test_core.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_writeto(self):
        """
        Simple test for writing a trivial header and some data to a file
        with the `writeto()` convenience function.
        """
        filename = self.temp('array.fits')
        data = np.zeros((100, 100))
        header = fits.Header()
        fits.writeto(filename, data, header=header, overwrite=True)
        with fits.open(filename) as hdul:
            assert len(hdul) == 1
            assert (data == hdul[0].data).all() 
Example #25
Source File: test_core.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_consecutive_writeto(self):
        """
        Regression test for an issue where calling writeto twice on the same
        HDUList could write a corrupted file.

        https://github.com/spacetelescope/PyFITS/issues/40 is actually a
        particular instance of this problem, though isn't unique to sys.stdout.
        """

        with fits.open(self.data('test0.fits')) as hdul1:
            # Add a bunch of header keywords so that the data will be forced to
            # new offsets within the file:
            for idx in range(40):
                hdul1[1].header[f'TEST{idx}'] = 'test'

            hdul1.writeto(self.temp('test1.fits'))
            hdul1.writeto(self.temp('test2.fits'))

            # Open a second handle to the original file and compare it to hdul1
            # (We only compare part of the one header that was modified)
            # Compare also with the second writeto output
            with fits.open(self.data('test0.fits')) as hdul2:
                with fits.open(self.temp('test2.fits')) as hdul3:
                    for hdul in (hdul1, hdul3):
                        for idx, hdus in enumerate(zip(hdul2, hdul)):
                            hdu2, hdu = hdus
                            if idx != 1:
                                assert hdu.header == hdu2.header
                            else:
                                assert (hdu2.header ==
                                        hdu.header[:len(hdu2.header)])
                            assert np.all(hdu.data == hdu2.data) 
Example #26
Source File: test_core.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_hdu_fromstring(self):
        """
        Tests creating a fully-formed HDU object from a string containing the
        bytes of the HDU.
        """
        infile = self.data('test0.fits')
        outfile = self.temp('test.fits')

        with open(infile, 'rb') as fin:
            dat = fin.read()

        offset = 0
        with fits.open(infile) as hdul:
            hdulen = hdul[0]._data_offset + hdul[0]._data_size
            hdu = fits.PrimaryHDU.fromstring(dat[:hdulen])
            assert isinstance(hdu, fits.PrimaryHDU)
            assert hdul[0].header == hdu.header
            assert hdu.data is None

        hdu.header['TEST'] = 'TEST'
        hdu.writeto(outfile)
        with fits.open(outfile) as hdul:
            assert isinstance(hdu, fits.PrimaryHDU)
            assert hdul[0].header[:-1] == hdu.header[:-1]
            assert hdul[0].header['TEST'] == 'TEST'
            assert hdu.data is None

        with fits.open(infile)as hdul:
            for ext_hdu in hdul[1:]:
                offset += hdulen
                hdulen = len(str(ext_hdu.header)) + ext_hdu._data_size
                hdu = fits.ImageHDU.fromstring(dat[offset:offset + hdulen])
                assert isinstance(hdu, fits.ImageHDU)
                assert ext_hdu.header == hdu.header
                assert (ext_hdu.data == hdu.data).all() 
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_replace_mmap_data(self):
        """Regression test for
        https://github.com/spacetelescope/PyFITS/issues/25

        Replacing the mmap'd data of one file with mmap'd data from a
        different file should work.
        """

        arr_a = np.arange(10)
        arr_b = arr_a * 2

        def test(mmap_a, mmap_b):
            hdu_a = fits.PrimaryHDU(data=arr_a)
            hdu_a.writeto(self.temp('test_a.fits'), overwrite=True)
            hdu_b = fits.PrimaryHDU(data=arr_b)
            hdu_b.writeto(self.temp('test_b.fits'), overwrite=True)

            with fits.open(self.temp('test_a.fits'), mode='update',
                           memmap=mmap_a) as hdul_a:
                with fits.open(self.temp('test_b.fits'),
                               memmap=mmap_b) as hdul_b:
                    hdul_a[0].data = hdul_b[0].data

            with fits.open(self.temp('test_a.fits')) as hdul_a:
                assert np.all(hdul_a[0].data == arr_b)

        with ignore_warnings():
            test(True, True)

            # Repeat the same test but this time don't mmap A
            test(False, True)

            # Finally, without mmaping B
            test(True, False) 
Example #28
Source File: test_core.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_add_del_columns2(self):
        hdulist = fits.open(self.data('tb.fits'))
        table = hdulist[1]
        assert table.data.dtype.names == ('c1', 'c2', 'c3', 'c4')
        assert table.columns.names == ['c1', 'c2', 'c3', 'c4']
        table.columns.del_col('c1')
        assert table.data.dtype.names == ('c2', 'c3', 'c4')
        assert table.columns.names == ['c2', 'c3', 'c4']

        table.columns.del_col('c3')
        assert table.data.dtype.names == ('c2', 'c4')
        assert table.columns.names == ['c2', 'c4']

        table.columns.add_col(fits.Column('foo', '3J'))
        assert table.data.dtype.names == ('c2', 'c4', 'foo')
        assert table.columns.names == ['c2', 'c4', 'foo']

        hdulist.writeto(self.temp('test.fits'), overwrite=True)
        with ignore_warnings():
            # TODO: The warning raised by this test is actually indication of a
            # bug and should *not* be ignored. But as it is a known issue we
            # hide it for now.  See
            # https://github.com/spacetelescope/PyFITS/issues/44
            with fits.open(self.temp('test.fits')) as hdulist:
                table = hdulist[1]
                assert table.data.dtype.names == ('c2', 'c4', 'foo')
                assert table.columns.names == ['c2', 'c4', 'foo'] 
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_replace_mmap_data_2(self):
        """Regression test for
        https://github.com/spacetelescope/PyFITS/issues/25

        Replacing the mmap'd data of one file with mmap'd data from a
        different file should work.  Like test_replace_mmap_data but with
        table data instead of image data.
        """

        arr_a = np.arange(10)
        arr_b = arr_a * 2

        def test(mmap_a, mmap_b):
            col_a = fits.Column(name='a', format='J', array=arr_a)
            col_b = fits.Column(name='b', format='J', array=arr_b)
            hdu_a = fits.BinTableHDU.from_columns([col_a])
            hdu_a.writeto(self.temp('test_a.fits'), overwrite=True)
            hdu_b = fits.BinTableHDU.from_columns([col_b])
            hdu_b.writeto(self.temp('test_b.fits'), overwrite=True)

            with fits.open(self.temp('test_a.fits'), mode='update',
                           memmap=mmap_a) as hdul_a:
                with fits.open(self.temp('test_b.fits'),
                               memmap=mmap_b) as hdul_b:
                    hdul_a[1].data = hdul_b[1].data

            with fits.open(self.temp('test_a.fits')) as hdul_a:
                assert 'b' in hdul_a[1].columns.names
                assert 'a' not in hdul_a[1].columns.names
                assert np.all(hdul_a[1].data['b'] == arr_b)

        with ignore_warnings():
            test(True, True)

            # Repeat the same test but this time don't mmap A
            test(False, True)

            # Finally, without mmaping B
            test(True, False) 
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_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()