Python astropy.io.fits.Column() Examples

The following are 30 code examples of astropy.io.fits.Column(). 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: tests.py    From tom_base with GNU General Public License v3.0 6 votes vote down vote up
def test_is_fits_image_file_table_img(self, dp_mock):
        with tempfile.TemporaryDirectory() as tmpdir:
            with self.settings(MEDIA_ROOT=tmpdir):
                img_file = os.path.join(tmpdir, 'img.blah')  # file name should be irrelevant
                img = fits.PrimaryHDU(np.arange(100))
                img.header['EXTNAME'] = 'SCI'
                hdul = fits.HDUList([img])
                hdul.writeto(img_file)

                tabimg_file = os.path.join(tmpdir, 'both.fits')
                table = fits.BinTableHDU.from_columns([
                    fits.Column(name='col1', format='I', array=np.array([1, 2, 3])),
                    fits.Column(name='col2', format='I', array=np.array([4, 5, 6]))
                ])
                hdul = fits.HDUList([img, table])
                hdul.writeto(tabimg_file)
                self.data_product.data = tabimg_file
                self.assertTrue(is_fits_image_file(self.data_product.data.file)) 
Example #2
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_attribute_field_shadowing(self):
        """
        Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/86

        Numpy recarray objects have a poorly-considered feature of allowing
        field access by attribute lookup.  However, if a field name conincides
        with an existing attribute/method of the array, the existing name takes
        precence (making the attribute-based field lookup completely unreliable
        in general cases).

        This ensures that any FITS_rec attributes still work correctly even
        when there is a field with the same name as that attribute.
        """

        c1 = fits.Column(name='names', format='I', array=[1])
        c2 = fits.Column(name='formats', format='I', array=[2])
        c3 = fits.Column(name='other', format='I', array=[3])

        t = fits.BinTableHDU.from_columns([c1, c2, c3])
        assert t.data.names == ['names', 'formats', 'other']
        assert t.data.formats == ['I'] * 3
        assert (t.data['names'] == [1]).all()
        assert (t.data['formats'] == [2]).all()
        assert (t.data.other == [3]).all() 
Example #3
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_dim_column_byte_order_mismatch(self):
        """
        When creating a table column with non-trivial TDIMn, and
        big-endian array data read from an existing FITS file, the data
        should not be unnecessarily byteswapped.

        Regression test for https://github.com/astropy/astropy/issues/3561
        """

        data = fits.getdata(self.data('random_groups.fits'))['DATA']
        col = fits.Column(name='TEST', array=data, dim='(3,1,128,1,1)',
                          format='1152E')
        thdu = fits.BinTableHDU.from_columns([col])
        thdu.writeto(self.temp('test.fits'))

        with fits.open(self.temp('test.fits')) as hdul:
            assert np.all(hdul[1].data['TEST'] == data) 
Example #4
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_column_with_scaling(self):
        """Check that a scaled column if correctly saved once it is modified.
        Regression test for https://github.com/astropy/astropy/issues/6887
        """
        c1 = fits.Column(name='c1', array=np.array([1], dtype='>i2'),
                         format='1I', bscale=1, bzero=32768)
        S = fits.HDUList([fits.PrimaryHDU(),
                          fits.BinTableHDU.from_columns([c1])])

        # Change value in memory
        S[1].data['c1'][0] = 2
        S.writeto(self.temp("a.fits"))
        assert S[1].data['c1'] == 2

        # Read and change value in memory
        with fits.open(self.temp("a.fits")) as X:
            X[1].data['c1'][0] = 10
            assert X[1].data['c1'][0] == 10

            # Write back to file
            X.writeto(self.temp("b.fits"))

        # Now check the file
        with fits.open(self.temp("b.fits")) as hdul:
            assert hdul[1].data['c1'][0] == 10 
Example #5
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_bin_table_with_logical_array(self):
        c1 = fits.Column(name='flag', format='2L',
                         array=[[True, False], [False, True]])
        coldefs = fits.ColDefs([c1])

        tbhdu1 = fits.BinTableHDU.from_columns(coldefs)

        assert (tbhdu1.data.field('flag')[0] ==
                np.array([True, False], dtype=bool)).all()
        assert (tbhdu1.data.field('flag')[1] ==
                np.array([False, True], dtype=bool)).all()

        tbhdu = fits.BinTableHDU.from_columns(tbhdu1.data)

        assert (tbhdu.data.field('flag')[0] ==
                np.array([True, False], dtype=bool)).all()
        assert (tbhdu.data.field('flag')[1] ==
                np.array([False, True], dtype=bool)).all() 
Example #6
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_extend_variable_length_array(self):
        """Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/54"""

        def test(format_code):
            arr = [[1] * 10] * 10
            col1 = fits.Column(name='TESTVLF', format=format_code, array=arr)
            col2 = fits.Column(name='TESTSCA', format='J', array=[1] * 10)
            tb_hdu = fits.BinTableHDU.from_columns([col1, col2], nrows=15)
            # This asserts that the normal 'scalar' column's length was extended
            assert len(tb_hdu.data['TESTSCA']) == 15
            # And this asserts that the VLF column was extended in the same manner
            assert len(tb_hdu.data['TESTVLF']) == 15
            # We can't compare the whole array since the _VLF is an array of
            # objects, but comparing just the edge case rows should suffice
            assert (tb_hdu.data['TESTVLF'][0] == arr[0]).all()
            assert (tb_hdu.data['TESTVLF'][9] == arr[9]).all()
            assert (tb_hdu.data['TESTVLF'][10] == ([0] * 10)).all()
            assert (tb_hdu.data['TESTVLF'][-1] == ([0] * 10)).all()

        for code in ('PJ()', 'QJ()'):
            test(code) 
Example #7
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_fits_record_len(self):
        counts = np.array([312, 334, 308, 317])
        names = np.array(['NGC1', 'NGC2', 'NGC3', 'NCG4'])
        c1 = fits.Column(name='target', format='10A', array=names)
        c2 = fits.Column(name='counts', format='J', unit='DN', array=counts)
        c3 = fits.Column(name='notes', format='A10')
        c4 = fits.Column(name='spectrum', format='5E')
        c5 = fits.Column(name='flag', format='L', array=[1, 0, 1, 1])
        coldefs = fits.ColDefs([c1, c2, c3, c4, c5])
        tbhdu = fits.BinTableHDU.from_columns(coldefs)
        tbhdu.writeto(self.temp('table1.fits'))

        t1 = fits.open(self.temp('table1.fits'))

        assert len(t1[1].data[0]) == 5
        assert len(t1[1].data[0][0:4]) == 4
        assert len(t1[1].data[0][0:5]) == 5
        assert len(t1[1].data[0][0:6]) == 5
        assert len(t1[1].data[0][0:7]) == 5
        assert len(t1[1].data[0][1:4]) == 3
        assert len(t1[1].data[0][1:5]) == 4
        assert len(t1[1].data[0][1:6]) == 4
        assert len(t1[1].data[0][1:7]) == 4

        t1.close() 
Example #8
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_variable_length_table_format_pd_from_object_array(self):
        def test(format_code):
            a = np.array([np.array([7.2e-20, 7.3e-20]), np.array([0.0]),
                          np.array([0.0])], 'O')
            acol = fits.Column(name='testa', format=format_code, array=a)
            tbhdu = fits.BinTableHDU.from_columns([acol])
            with ignore_warnings():
                tbhdu.writeto(self.temp('newtable.fits'), overwrite=True)
            with fits.open(self.temp('newtable.fits')) as tbhdu1:
                assert tbhdu1[1].columns[0].format.endswith('D(2)')
                for j in range(3):
                    for i in range(len(a[j])):
                        assert tbhdu1[1].data.field(0)[j][i] == a[j][i]

        for code in ('PD()', 'QD()'):
            test(code) 
Example #9
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_column_endianness(self):
        """
        Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/77
        (Astropy doesn't preserve byte order of non-native order column arrays)
        """

        a = [1., 2., 3., 4.]
        a1 = np.array(a, dtype='<f8')
        a2 = np.array(a, dtype='>f8')

        col1 = fits.Column(name='a', format='D', array=a1)
        col2 = fits.Column(name='b', format='D', array=a2)
        cols = fits.ColDefs([col1, col2])
        tbhdu = fits.BinTableHDU.from_columns(cols)

        assert (tbhdu.data['a'] == a1).all()
        assert (tbhdu.data['b'] == a2).all()

        # Double check that the array is converted to the correct byte-order
        # for FITS (big-endian).
        tbhdu.writeto(self.temp('testendian.fits'), overwrite=True)
        with fits.open(self.temp('testendian.fits')) as hdul:
            assert (hdul[1].data['a'] == a2).all()
            assert (hdul[1].data['b'] == a2).all() 
Example #10
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_variable_length_table_format_pd_from_list(self):
        def test(format_code):
            a = [np.array([7.2e-20, 7.3e-20]), np.array([0.0]),
                 np.array([0.0])]
            acol = fits.Column(name='testa', format=format_code, array=a)
            tbhdu = fits.BinTableHDU.from_columns([acol])
            with ignore_warnings():
                tbhdu.writeto(self.temp('newtable.fits'), overwrite=True)

            with fits.open(self.temp('newtable.fits')) as tbhdu1:
                assert tbhdu1[1].columns[0].format.endswith('D(2)')
                for j in range(3):
                    for i in range(len(a[j])):
                        assert tbhdu1[1].data.field(0)[j][i] == a[j][i]

        for code in ('PD()', 'QD()'):
            test(code) 
Example #11
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_variable_length_table_format_pa_from_object_array(self):
        def test(format_code):
            a = np.array([np.array(['a', 'b', 'c']), np.array(['d', 'e']),
                          np.array(['f'])], 'O')
            acol = fits.Column(name='testa', format=format_code, array=a)
            tbhdu = fits.BinTableHDU.from_columns([acol])
            with ignore_warnings():
                tbhdu.writeto(self.temp('newtable.fits'), overwrite=True)

            with fits.open(self.temp('newtable.fits')) as hdul:
                assert hdul[1].columns[0].format.endswith('A(3)')
                for j in range(3):
                    for i in range(len(a[j])):
                        assert hdul[1].data.field(0)[j][i] == a[j][i]

        for code in ('PA()', 'QA()'):
            test(code) 
Example #12
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_variable_length_table_format_pa_from_list(self):
        def test(format_code):
            a = ['a', 'ab', 'abc']
            acol = fits.Column(name='testa', format=format_code, array=a)
            tbhdu = fits.BinTableHDU.from_columns([acol])
            with ignore_warnings():
                tbhdu.writeto(self.temp('newtable.fits'), overwrite=True)

            with fits.open(self.temp('newtable.fits')) as hdul:
                assert hdul[1].columns[0].format.endswith('A(3)')
                for j in range(3):
                    for i in range(len(a[j])):
                        assert hdul[1].data.field(0)[j][i] == a[j][i]

        for code in ('PA()', 'QA()'):
            test(code) 
Example #13
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_zero_precision_float_column(self):
        """
        Regression test for https://github.com/astropy/astropy/issues/3422
        """

        c = fits.Column('TEST', 'F5.0', array=[1.1, 2.2, 3.3])
        # The decimal places will be clipped
        t = fits.TableHDU.from_columns([c])
        t.writeto(self.temp('test.fits'))

        with fits.open(self.temp('test.fits')) as hdul:
            assert hdul[1].header['TFORM1'] == 'F5.0'
            assert hdul[1].data['TEST'].dtype == np.dtype('float64')
            assert np.all(hdul[1].data['TEST'] == [1.0, 2.0, 3.0])

            # Check how the raw data looks
            raw = np.rec.recarray.field(hdul[1].data, 'TEST')
            assert raw.tostring() == b'   1.   2.   3.' 
Example #14
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 #15
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 #16
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_p_column_deepcopy(self):
        """
        Regression test for https://github.com/astropy/astropy/pull/4514

        Tests that columns with the P/Q formats (variable length arrays) can be
        deep-copied.
        """

        c = fits.Column('pcol', format='PJ', array=[[1, 2], [3, 4, 5]])
        c2 = copy.deepcopy(c)
        assert c2.name == c.name
        assert c2.format == c.format
        assert np.all(c2.array[0] == c.array[0])
        assert np.all(c2.array[1] == c.array[1])

        c3 = fits.Column('qcol', format='QJ', array=[[1, 2], [3, 4, 5]])
        c4 = copy.deepcopy(c3)
        assert c4.name == c3.name
        assert c4.format == c3.format
        assert np.all(c4.array[0] == c3.array[0])
        assert np.all(c4.array[1] == c3.array[1]) 
Example #17
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_column_verify_keywords(self):
        """
        Test that the keyword arguments used to initialize a Column, specifically
        those that typically read from a FITS header (so excluding array),
        are verified to have a valid value.
        """

        with pytest.raises(AssertionError) as err:
            _ = fits.Column(1, format='I', array=[1, 2, 3, 4, 5])
        assert 'Column name must be a string able to fit' in str(err.value)

        with pytest.raises(VerifyError) as err:
            _ = fits.Column('col', format='I', null='Nan', disp=1, coord_type=1,
                            coord_unit=2, coord_ref_point='1', coord_ref_value='1',
                            coord_inc='1', time_ref_pos=1)
        err_msgs = ['keyword arguments to Column were invalid', 'TNULL', 'TDISP',
                    'TCTYP', 'TCUNI', 'TCRPX', 'TCRVL', 'TCDLT', 'TRPOS']
        for msg in err_msgs:
            assert msg in str(err.value) 
Example #18
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_column_verify_start(self):
        """
        Regression test for https://github.com/astropy/astropy/pull/6359

        Test the validation of the column start position option (ASCII table only),
        corresponding to ``TBCOL`` keyword.
        Test whether the VerifyError message generated is the one with highest priority,
        i.e. the order of error messages to be displayed is maintained.
        """

        with pytest.raises(VerifyError) as err:
            _ = fits.Column('a', format='B', start='a', array=[1, 2, 3])
        assert "start option (TBCOLn) is not allowed for binary table columns" in str(err.value)

        with pytest.raises(VerifyError) as err:
            _ = fits.Column('a', format='I', start='a', array=[1, 2, 3])
        assert "start option (TBCOLn) must be a positive integer (got 'a')." in str(err.value)

        with pytest.raises(VerifyError) as err:
            _ = fits.Column('a', format='I', start='-56', array=[1, 2, 3])
        assert "start option (TBCOLn) must be a positive integer (got -56)." in str(err.value) 
Example #19
Source File: test_fitstime.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_io_time_read_fits_datetime(self, table_types):
        """
        Test that ISO-8601 Datetime String Columns are read correctly.
        """
        # Datetime column
        c = fits.Column(name='datetime', format='A29', coord_type='TCG',
                        time_ref_pos='GEOCENTER', array=self.time)

        # Explicitly create a FITS Binary Table
        bhdu = fits.BinTableHDU.from_columns([c])
        bhdu.writeto(self.temp('time.fits'), overwrite=True)

        tm = table_types.read(self.temp('time.fits'), astropy_native=True)

        assert isinstance(tm['datetime'], Time)
        assert tm['datetime'].scale == 'tcg'
        assert tm['datetime'].format == 'fits'
        assert (tm['datetime'] == self.time).all() 
Example #20
Source File: test_fitstime.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_time_to_fits_header(self, table_types):
        """
        Test the header and metadata returned by ``time_to_fits``.
        """
        t = table_types()
        t['a'] = Time(self.time, format='isot', scale='utc',
                      location=EarthLocation(-2446354,
                      4237210, 4077985, unit='m'))
        t['b'] = Time([1,2], format='cxcsec', scale='tt')

        ideal_col_hdr = {'OBSGEO-X' : t['a'].location.x.value,
                         'OBSGEO-Y' : t['a'].location.y.value,
                         'OBSGEO-Z' : t['a'].location.z.value}

        with pytest.warns(AstropyUserWarning, match=r'Time Column "b" has no '
                          r'specified location, but global Time Position is present'):
            table, hdr = time_to_fits(t)

        # Check the global time keywords in hdr
        for key, value in GLOBAL_TIME_INFO.items():
            assert hdr[key] == value[0]
            assert hdr.comments[key] == value[1]
            hdr.remove(key)

        for key, value in ideal_col_hdr.items():
            assert hdr[key] == value
            hdr.remove(key)

        # Check the column-specific time metadata
        coord_info = table.meta['__coordinate_columns__']
        for colname in coord_info:
            assert coord_info[colname]['coord_type'] == t[colname].scale.upper()
            assert coord_info[colname]['coord_unit'] == 'd'

        assert coord_info['a']['time_ref_pos'] == 'TOPOCENTER'
        assert coord_info['b']['time_ref_pos'] == None

        assert len(hdr) == 0 
Example #21
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_column_array_type_mismatch(self):
        """Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/218"""

        arr = [-99] * 20
        col = fits.Column('mag', format='E', array=arr)
        assert (arr == col.array).all() 
Example #22
Source File: processing_utils.py    From drizzlepac with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def update_hdrtab(image, level, total_obj_list, input_exposures):
    """Build HAP entry table extension for product"""
    # Convert input_exposure filenames into HAP product filenames
    name_col = []
    orig_tab = image['hdrtab'].data

    for row in orig_tab:
        rootname = str(row['rootname'])

        # The rootname is ipppssoot, but the expname is only contains ipppssoo,
        # so remove the last character for the comparisons
        rootname = rootname[0:-1]

        for expname in input_exposures:
            if rootname in expname:
                if level == 1:
                    # Intrepret inputs as exposures (FLT/FLC) filename not HAP names
                    name_col.append(expname)
                else:
                    # Convert input exposure names into HAP names
                    foundit = False
                    for tot_obj in total_obj_list:
                        for exposure in tot_obj.edp_list:
                            if rootname in exposure.full_filename:
                                name_col.append(exposure.drizzle_filename)
                                foundit = True
                                break

    # define new column with HAP expname
    max_len = min(max([len(name) for name in name_col]), 51)
    hapcol = Column(array=np.array(name_col, dtype=np.str), name=HAPCOLNAME, format='{}A'.format(max_len + 4))
    newcol = fits.ColDefs([hapcol])

    # define new extension
    haphdu = fits.BinTableHDU.from_columns(orig_tab.columns + newcol)
    haphdu.header['extname'] = 'HDRTAB'
    haphdu.header['extver'] = 1
    # remove old extension
    del image['hdrtab']
    # replace with new extension
    image.append(haphdu) 
Example #23
Source File: test_utils.py    From astropy-healpix with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_parse_input_healpix_data(tmpdir):

    data = np.arange(3072)

    col = fits.Column(array=data, name='flux', format="E")
    hdu = fits.BinTableHDU.from_columns([col])
    hdu.header['NSIDE'] = 512
    hdu.header['COORDSYS'] = "G"

    # As HDU
    array, coordinate_system, nested = parse_input_healpix_data(hdu)
    np.testing.assert_allclose(array, data)

    # As filename
    filename = tmpdir.join('test.fits').strpath
    hdu.writeto(filename)
    array, coordinate_system, nested = parse_input_healpix_data(filename)
    np.testing.assert_allclose(array, data)

    # As array
    array, coordinate_system, nested = parse_input_healpix_data((data, "galactic"))
    np.testing.assert_allclose(array, data)

    # Invalid
    with pytest.raises(TypeError) as exc:
        parse_input_healpix_data(data)
    assert exc.value.args[0] == ("input_data should either be an HDU object or "
                                 "a tuple of (array, frame)") 
Example #24
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_pseudo_unsigned_ints(self):
        """
        Tests updating a table column containing pseudo-unsigned ints.
        """

        data = np.array([1, 2, 3], dtype=np.uint32)
        col = fits.Column(name='A', format='1J', bzero=2**31, array=data)
        thdu = fits.BinTableHDU.from_columns([col])
        thdu.writeto(self.temp('test.fits'))

        # Test that the file wrote out correctly
        with fits.open(self.temp('test.fits'), uint=True) as hdul:
            hdu = hdul[1]
            assert 'TZERO1' in hdu.header
            assert hdu.header['TZERO1'] == 2**31
            assert hdu.data['A'].dtype == np.dtype('uint32')
            assert np.all(hdu.data['A'] == data)

            # Test updating the unsigned int data
            hdu.data['A'][0] = 99
            hdu.writeto(self.temp('test2.fits'))

        with fits.open(self.temp('test2.fits'), uint=True) as hdul:
            hdu = hdul[1]
            assert 'TZERO1' in hdu.header
            assert hdu.header['TZERO1'] == 2**31
            assert hdu.data['A'].dtype == np.dtype('uint32')
            assert np.all(hdu.data['A'] == [99, 2, 3]) 
Example #25
Source File: test_fitstime.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_io_time_read_fits_location_warnings(self, table_types):
        """
        Test warnings for time column reference position.
        """
        # Time reference position "TOPOCENTER" without corresponding
        # observatory position.
        c = fits.Column(name='datetime', format='A29', coord_type='TT',
                        time_ref_pos='TOPOCENTER', array=self.time)

        bhdu = fits.BinTableHDU.from_columns([c])
        bhdu.writeto(self.temp('time.fits'), overwrite=True)

        with catch_warnings() as w:
            table_types.read(self.temp('time.fits'), astropy_native=True)
        assert len(w) == 1
        assert ('observatory position is not properly specified' in
                str(w[0].message))

        # Warning for default value of time reference position "TOPOCENTER"
        # not generated when there is no specified observatory position.
        c = fits.Column(name='datetime', format='A29', coord_type='TT',
                        array=self.time)

        bhdu = fits.BinTableHDU.from_columns([c])
        bhdu.writeto(self.temp('time.fits'), overwrite=True)
        with catch_warnings() as w:
            table_types.read(self.temp('time.fits'), astropy_native=True)
        assert len(w) == 0 
Example #26
Source File: test_fitstime.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_io_time_read_fits_scale(self, table_types):
        """
        Test handling of 'GPS' and 'LOCAL' time scales which are
        recognized by the FITS standard but are not native to astropy.
        """
        # GPS scale column
        gps_time = np.array([630720013, 630720014])
        c = fits.Column(name='gps_time', format='D', unit='s', coord_type='GPS',
                        coord_unit='s', time_ref_pos='TOPOCENTER', array=gps_time)

        cards = [('OBSGEO-L', 0), ('OBSGEO-B', 0), ('OBSGEO-H', 0)]

        bhdu = fits.BinTableHDU.from_columns([c], header=fits.Header(cards))
        bhdu.writeto(self.temp('time.fits'), overwrite=True)

        with catch_warnings() as w:
            tm = table_types.read(self.temp('time.fits'), astropy_native=True)
            assert len(w) == 1
            assert 'FITS recognized time scale value "GPS"' in str(w[0].message)

        assert isinstance(tm['gps_time'], Time)
        assert tm['gps_time'].format == 'gps'
        assert tm['gps_time'].scale == 'tai'
        assert (tm['gps_time'].value == gps_time).all()

        # LOCAL scale column
        local_time = np.array([1, 2])
        c = fits.Column(name='local_time', format='D', unit='d',
                        coord_type='LOCAL', coord_unit='d',
                        time_ref_pos='RELOCATABLE', array=local_time)

        bhdu = fits.BinTableHDU.from_columns([c])
        bhdu.writeto(self.temp('time.fits'), overwrite=True)

        tm = table_types.read(self.temp('time.fits'), astropy_native=True)

        assert isinstance(tm['local_time'], Time)
        assert tm['local_time'].format == 'mjd'

        assert tm['local_time'].scale == 'local'
        assert (tm['local_time'].value == local_time).all() 
Example #27
Source File: test_fitstime.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_io_time_read_fits_location(self, table_types):
        """
        Test that geocentric/geodetic observatory position is read
        properly, as and when it is specified.
        """
        # Datetime column
        c = fits.Column(name='datetime', format='A29', coord_type='TT',
                        time_ref_pos='TOPOCENTER', array=self.time)

        # Observatory position in ITRS Cartesian coordinates (geocentric)
        cards = [('OBSGEO-X', -2446354), ('OBSGEO-Y', 4237210),
                 ('OBSGEO-Z', 4077985)]

        # Explicitly create a FITS Binary Table
        bhdu = fits.BinTableHDU.from_columns([c], header=fits.Header(cards))
        bhdu.writeto(self.temp('time.fits'), overwrite=True)

        tm = table_types.read(self.temp('time.fits'), astropy_native=True)

        assert isinstance(tm['datetime'], Time)
        assert tm['datetime'].location.x.value == -2446354
        assert tm['datetime'].location.y.value == 4237210
        assert tm['datetime'].location.z.value == 4077985

        # Observatory position in geodetic coordinates
        cards = [('OBSGEO-L', 0), ('OBSGEO-B', 0), ('OBSGEO-H', 0)]

        # Explicitly create a FITS Binary Table
        bhdu = fits.BinTableHDU.from_columns([c], header=fits.Header(cards))
        bhdu.writeto(self.temp('time.fits'), overwrite=True)

        tm = table_types.read(self.temp('time.fits'), astropy_native=True)

        assert isinstance(tm['datetime'], Time)
        assert tm['datetime'].location.lon.value == 0
        assert tm['datetime'].location.lat.value == 0
        assert np.isclose(tm['datetime'].location.height.value, 0,
                          rtol=0, atol=1e-9) 
Example #28
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_column_lookup_by_name(self):
        """Tests that a `ColDefs` can be indexed by column name."""

        a = fits.Column(name='a', format='D')
        b = fits.Column(name='b', format='D')

        cols = fits.ColDefs([a, b])

        assert cols['a'] == cols[0]
        assert cols['b'] == cols[1] 
Example #29
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_regression_5383():

    # Regression test for an undefined variable

    x = np.array([1, 2, 3])
    col = fits.Column(name='a', array=x, format='E')
    hdu = fits.BinTableHDU.from_columns([col])
    del hdu._header['TTYPE1']
    hdu.columns[0].name = 'b' 
Example #30
Source File: test_table.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_x_column_deepcopy(self):
        """
        Regression test for https://github.com/astropy/astropy/pull/4514

        Tests that columns with the X (bit array) format can be deep-copied.
        """

        c = fits.Column('xcol', format='5X', array=[1, 0, 0, 1, 0])
        c2 = copy.deepcopy(c)
        assert c2.name == c.name
        assert c2.format == c.format
        assert np.all(c2.array == c.array)