Ejemplo n.º 1
0
def test_assert_same_class():
    ad = astrodata.create({})
    ad2 = astrodata.create({})
    assert_same_class(ad, ad2)

    with pytest.raises(AssertionError):
        assert_same_class(ad, np.array([1]))
Ejemplo n.º 2
0
def test_append_table_to_extensions(tmp_path):
    testfile = tmp_path / 'test.fits'
    ad = astrodata.create({})
    ad.append(NDData(np.zeros((4, 5))))
    ad.append(NDData(np.zeros((4, 5))))
    ad.append(NDData(np.zeros((4, 5)), meta={'header': {'FOO': 'BAR'}}))
    ad[0].TABLE1 = Table([[1]])
    ad[0].TABLE2 = Table([[22]])
    ad[1].TABLE2 = Table([[2]])  # extensions can have the same table name
    ad[2].TABLE3 = Table([[3]])
    ad.write(testfile)

    ad = astrodata.open(testfile)

    # Check that slices do not report extension tables
    assert ad.exposed == set()
    assert ad[0].exposed == {'TABLE1', 'TABLE2'}
    assert ad[1].exposed == {'TABLE2'}
    assert ad[2].exposed == {'TABLE3'}
    assert ad[1:].exposed == set()

    assert ad[2].hdr['FOO'] == 'BAR'

    match = ("Cannot append table 'TABLE1' because it would hide an "
             "extension table")
    with pytest.raises(ValueError, match=match):
        ad.TABLE1 = Table([[1]])
def test_create_with_no_data():
    for phu in (fits.PrimaryHDU(), fits.Header(), {}):
        ad = astrodata.create(phu)
        assert isinstance(ad, astrodata.AstroData)
        assert len(ad) == 0
        assert ad.instrument() is None
        assert ad.object() is None
Ejemplo n.º 4
0
def test_append_arrays(tmp_path):
    testfile = tmp_path / 'test.fits'

    ad = astrodata.create({})
    ad.append(np.zeros(10))
    ad[0].ARR = np.arange(5)

    with pytest.raises(AttributeError):
        ad[0].SCI = np.arange(5)
    with pytest.raises(AttributeError):
        ad[0].VAR = np.arange(5)
    with pytest.raises(AttributeError):
        ad[0].DQ = np.arange(5)

    match = ("Arbitrary image extensions can only be added in association "
             "to a 'SCI'")
    with pytest.raises(ValueError, match=match):
        ad.append(np.zeros(10), name='FOO')

    with pytest.raises(ValueError, match=match):
        ad.append(np.zeros(10), header=fits.Header({'EXTNAME': 'FOO'}))

    ad.write(testfile)

    ad = astrodata.open(testfile)
    assert len(ad) == 1
    assert ad[0].nddata.meta['header']['EXTNAME'] == 'SCI'
    assert_array_equal(ad[0].ARR, np.arange(5))
Ejemplo n.º 5
0
    def test_can_make_and_write_ad_object(self, test_path):

        # Creates data and ad object
        phu = fits.PrimaryHDU()
        pixel_data = np.random.rand(100, 100)

        hdu = fits.ImageHDU()
        hdu.data = pixel_data

        ad = astrodata.create(phu)
        ad.append(hdu, name='SCI')

        # Write file and test it exists properly
        test_file_location = os.path.join(test_path, 'created_fits_file.fits')

        if os.path.exists(test_file_location):
            os.remove(test_file_location)
        ad.write(test_file_location)

        assert os.path.exists(test_file_location)
        # Opens file again and tests data is same as above

        adnew = astrodata.open(test_file_location)
        assert np.array_equal(adnew[0].data, pixel_data)
        os.remove(test_file_location)
Ejemplo n.º 6
0
def test_add_table():
    shape = (3, 4)
    fakedata = np.arange(np.prod(shape)).reshape(shape)

    ad = astrodata.create({'OBJECT': 'M42'})
    ad.append(fakedata)

    tbl = Table([['a', 'b', 'c'], [1, 2, 3]])
    ad.append(tbl)
    assert ad.tables == {'TABLE1'}
    ad.append(tbl)
    assert ad.tables == {'TABLE1', 'TABLE2'}
    ad.append(tbl, name='MYTABLE')
    assert ad.tables == {'TABLE1', 'TABLE2', 'MYTABLE'}

    hdr = fits.Header({'INSTRUME': 'darkimager', 'OBJECT': 'M42'})
    tbl = Table([['aa', 'bb', 'cc'], [1, 2, 3]])
    ad.append(tbl, add_to=ad[0].nddata, header=hdr)
    ad.append(tbl, add_to=ad[0].nddata)
    ad.append(tbl, add_to=ad[0].nddata, name='OTHERTABLE')

    assert list(ad[0].OTHERTABLE['col0']) == ['aa', 'bb', 'cc']
    assert ad[0].tables == {'TABLE1', 'MYTABLE', 'TABLE2'}
    assert ad[0].exposed == {'TABLE1', 'TABLE2', 'MYTABLE', 'OTHERTABLE'}

    assert ad[0].nddata.TABLE1.meta['header']['INSTRUME'] == 'darkimager'
    assert (set(ad[0].nddata.meta['other'].keys()) == {
        'TABLE2', 'OTHERTABLE', 'TABLE1'
    })
    assert_array_equal(ad[0].nddata.TABLE1['col0'], ['aa', 'bb', 'cc'])
    assert_array_equal(ad[0].nddata.TABLE2['col0'], ['aa', 'bb', 'cc'])
    assert_array_equal(ad[0].nddata.OTHERTABLE['col0'], ['aa', 'bb', 'cc'])
Ejemplo n.º 7
0
    def test_can_make_and_write_ad_object(self, test_path):

        # Creates data and ad object
        phu = fits.PrimaryHDU()
        pixel_data = np.random.rand(100, 100)

        hdu = fits.ImageHDU()
        hdu.data = pixel_data

        ad = astrodata.create(phu)
        ad.append(hdu, name='SCI')

        # Write file and test it exists properly
        test_file_location = os.path.join(
            test_path, 'created_fits_file.fits')

        if os.path.exists(test_file_location):
            os.remove(test_file_location)
        ad.write(test_file_location)

        assert os.path.exists(test_file_location)
        # Opens file again and tests data is same as above

        adnew = astrodata.open(test_file_location)
        assert np.array_equal(adnew[0].data, pixel_data)
        os.remove(test_file_location)
Ejemplo n.º 8
0
def test_extver():
    ad = astrodata.create({})
    for _ in range(10):
        ad.append(np.zeros((4, 5)))

    assert type(ad[0].data) == np.ndarray

    ext = ad[2]
    assert ext.hdr['EXTNAME'] == 'SCI'
    assert ext.hdr['EXTVER'] == 3
    assert ad.extver_map()[3] == 2  # map EXTVER to HDU index

    ext = ad.extver(5)
    assert ext.hdr['EXTNAME'] == 'SCI'
    assert ext.hdr['EXTVER'] == 5

    ext = ad[:8].extver(5)
    assert ext.hdr['EXTNAME'] == 'SCI'
    assert ext.hdr['EXTVER'] == 5

    with pytest.raises(ValueError, match='SCI is not an integer EXTVER'):
        ad.extver('SCI')

    with pytest.raises(IndexError, match='EXTVER 15 not found'):
        ad.extver(15)

    with pytest.raises(ValueError,
                       match="Trying to get a mapping out of a single slice"):
        ext.extver(15)
Ejemplo n.º 9
0
def test_build_ad_multiple_extensions(tmp_path):
    """Build an AD object with multiple extensions and check that we retrieve
    everything in the correct order after writing.
    """
    shape = (4, 5)
    testfile = tmp_path / 'test.fits'

    ad = astrodata.create({})
    for i in range(1, 4):
        nd = NDData(np.zeros(shape) + i,
                    uncertainty=VarianceUncertainty(np.ones(shape)),
                    mask=np.zeros(shape, dtype='uint16'))
        ad.append(nd)
        ad[-1].OBJCAT = Table([[i]])
        ad[-1].MYARR = np.zeros(10) + i

    ad.REFCAT = Table([['ref']])
    ad.write(testfile)

    ad2 = astrodata.open(testfile)

    for ext, ext2 in zip(ad, ad2):
        assert_array_equal(ext.data, ext2.data)
        assert_array_equal(ext.MYARR, ext2.MYARR)
        assert_array_equal(ext.OBJCAT['col0'], ext2.OBJCAT['col0'])
Ejemplo n.º 10
0
def test_can_append_table_and_access_data(capsys, tmpdir):
    tbl = Table([np.zeros(10), np.ones(10)], names=['col1', 'col2'])
    phu = fits.PrimaryHDU()
    ad = astrodata.create(phu)

    with pytest.raises(ValueError,
                       match='Tables should be set directly as attribute'):
        ad.append(tbl, name='BOB')

    ad.BOB = tbl
    assert ad.exposed == {'BOB'}

    assert ad.tables == {'BOB'}
    assert np.all(ad.table()['BOB'] == tbl)

    ad.info()
    captured = capsys.readouterr()
    assert '.BOB           Table       (10, 2)' in captured.out

    # Write file and test it exists properly
    testfile = str(tmpdir.join('created_fits_file.fits'))
    ad.write(testfile)
    adnew = astrodata.open(testfile)
    assert adnew.exposed == {'BOB'}
    assert len(adnew.BOB) == 10

    del ad.BOB
    assert ad.tables == set()
    with pytest.raises(AttributeError):
        del ad.BOB
Ejemplo n.º 11
0
def test_create_with_header():
    hdr = fits.Header({'INSTRUME': 'darkimager', 'OBJECT': 'M42'})
    for phu in (hdr, fits.PrimaryHDU(header=hdr), dict(hdr), list(hdr.cards)):
        ad = astrodata.create(phu)
        assert isinstance(ad, astrodata.AstroData)
        assert len(ad) == 0
        assert ad.instrument() == 'darkimager'
        assert ad.object() == 'M42'
Ejemplo n.º 12
0
def test_can_append_an_image_hdu_object_to_an_astrodata_object():
    ad = astrodata.create(fits.PrimaryHDU())
    hdu = fits.ImageHDU(data=np.zeros(SHAPE))
    ad.append(hdu, name='SCI')
    ad.append(hdu, name='SCI2')

    assert len(ad) == 2
    assert ad[0].data is hdu.data
    assert ad[1].data is hdu.data
Ejemplo n.º 13
0
def test_append_image_hdu():
    ad = astrodata.create(fits.PrimaryHDU())
    hdu = fits.ImageHDU(data=np.zeros((4, 5)))
    ad.append(hdu, name='SCI')
    ad.append(hdu, name='SCI2')

    assert len(ad) == 2
    assert ad[0].data is hdu.data
    assert ad[1].data is hdu.data
Ejemplo n.º 14
0
def test_create_from_hdu():
    phu = fits.PrimaryHDU()
    hdu = fits.ImageHDU(data=np.zeros((4, 5)), name='SCI')
    ad = astrodata.create(phu, [hdu])

    assert isinstance(ad, astrodata.AstroData)
    assert len(ad) == 1
    assert isinstance(ad[0].data, np.ndarray)
    assert ad[0].data is hdu.data
Ejemplo n.º 15
0
def test_append_table_and_write(tmp_path):
    testfile = tmp_path / 'test.fits'
    ad = astrodata.create({})
    ad.append(NDData(np.zeros((4, 5))))
    ad[0].TABLE1 = Table([[1]])
    ad.write(testfile)
    ad.write(testfile, overwrite=True)

    ad = astrodata.open(testfile)
    assert ad[0].exposed == {'TABLE1'}
Ejemplo n.º 16
0
def test_can_read_write_pathlib(tmp_path):
    testfile = tmp_path / 'test.fits'

    ad = astrodata.create({})
    ad.append(np.zeros((4, 5)))
    ad.write(testfile)

    ad = astrodata.open(testfile)
    assert len(ad) == 1
    assert ad.shape == [(4, 5)]
Ejemplo n.º 17
0
def test_append_tables():
    """If both ad and ad[0] have a TABLE1, check that ad[0].TABLE1 return the
    extension table.
    """
    nd = NDData(np.zeros((4, 5)), meta={'header': {}})
    ad = astrodata.create({})
    ad.append(nd)
    ad.append(Table([[1]]))
    ad.append(Table([[2]]), add_to=ad[0].nddata)
    assert ad[0].TABLE2['col0'][0] == 2
Ejemplo n.º 18
0
def sample_astrodata_with_ones():

    data_array = np.ones((100, 100))

    phu = fits.PrimaryHDU()
    hdu = fits.ImageHDU(data=data_array, name='SCI')

    ad = astrodata.create(phu, [hdu])

    return ad
Ejemplo n.º 19
0
def test_can_read_write_pathlib(tmp_path):
    testfile = tmp_path / 'test.fits'

    ad = astrodata.create({'INSTRUME': 'MYINSTRUMENT'})
    ad.append(np.zeros((4, 5)))
    ad.write(testfile)

    ad = astrodata.open(testfile)
    assert isinstance(ad, AstroDataMyInstrument)
    assert len(ad) == 1
    assert ad.shape == [(4, 5)]
Ejemplo n.º 20
0
def test_can_create_astrodata_from_image_hdu():
    data_array = np.zeros((100, 100))

    phu = fits.PrimaryHDU()
    hdu = fits.ImageHDU(data=data_array, name='SCI')

    ad = astrodata.create(phu, [hdu])

    assert isinstance(ad, astrodata.AstroData)
    assert len(ad) == 1
    assert isinstance(ad[0].data, np.ndarray)
Ejemplo n.º 21
0
def niri_adinputs():
    phu = fits.PrimaryHDU()
    phu.header.update(OBSERVAT='Gemini-North', INSTRUME='NIRI',
                      ORIGNAME='N20010101S0001.fits')
    data = np.ones((2, 2))
    adinputs = []
    for i in range(2):
        ad = astrodata.create(phu)
        ad.append(data + i)
        adinputs.append(ad)
    return adinputs
Ejemplo n.º 22
0
def test_append_image_hdu():
    ad = astrodata.create(fits.PrimaryHDU())
    ad.append(fits.ImageHDU(data=np.zeros((4, 5))))
    ad.append(fits.ImageHDU(data=np.zeros((4, 5))), name='SCI')

    with pytest.raises(ValueError,
                       match="Arbitrary image extensions can only be added "
                       "in association to a 'SCI'"):
        ad.append(fits.ImageHDU(data=np.zeros((4, 5))), name='SCI2')

    assert len(ad) == 2
Ejemplo n.º 23
0
def test_extver_del():
    ad = astrodata.create({})
    for _ in range(5):
        ad.append(np.zeros((4, 5)))

    assert ad.extver_map() == {1: 0, 2: 1, 3: 2, 4: 3, 5: 4}

    del ad[2]
    assert ad.extver_map() == {1: 0, 2: 1, 4: 2, 5: 3}

    ad.append(np.zeros((4, 5)))
    assert ad.extver_map() == {1: 0, 2: 1, 4: 2, 5: 3, 6: 4}
Ejemplo n.º 24
0
def test_operate():
    ad = astrodata.create({})
    nd = NDData(data=[[1, 2], [3, 4]],
                uncertainty=VarianceUncertainty(np.ones((2, 2))),
                mask=np.identity(2),
                meta={'header': fits.Header()})
    ad.append(nd)

    ad.operate(np.sum, axis=1)
    assert_array_equal(ad[0].data, [3, 7])
    assert_array_equal(ad[0].variance, [2, 2])
    assert_array_equal(ad[0].mask, [1, 1])
Ejemplo n.º 25
0
    def test_can_append_table_and_access_data(self):

        my_astropy_table = Table(list(np.random.rand(2, 100)),
                                 names=['col1', 'col2'])

        phu = fits.PrimaryHDU()
        ad = astrodata.create(phu)
        astrodata.add_header_to_table(my_astropy_table)

        ad.append(my_astropy_table, name='BOB')

        print(ad.info())
Ejemplo n.º 26
0
    def test_can_append_table_and_access_data(self):

        my_astropy_table = Table(list(np.random.rand(2, 100)),
                                 names=['col1', 'col2'])

        phu = fits.PrimaryHDU()
        ad = astrodata.create(phu)
        astrodata.add_header_to_table(my_astropy_table)

        ad.append(my_astropy_table, name='BOB')

        print(ad.info())
Ejemplo n.º 27
0
    def create_slit_package(self, tmpdir_factory):
        """
        Generate a package of dummy slit files.

        .. note::
            Fixture.
        """
        rawfilename = 'testslitpackage.fits'
        tmpsubdir = tmpdir_factory.mktemp('ghost_slit')
        os.chdir(os.path.join(tmpsubdir.dirname, tmpsubdir.basename))

        # Create the AstroData object
        phu = fits.PrimaryHDU()
        phu.header.set('CAMERA', 'slit')
        phu.header.set('CCDNAME', 'Sony-ICX674')
        phu.header.set('UTSTART', SLIT_UT_START.strftime(STRFTIME))
        phu.header.set('UTEND', (SLIT_UT_START + datetime.timedelta(
            seconds=(NO_SLITS + 1) * EXPTIME_SLITS)).strftime(STRFTIME))
        phu.header.set('INSTRUME', 'GHOST')

        hdus = []
        for i in range(NO_SLITS):
            hdu = fits.ImageHDU(data=np.zeros(SLIT_CAMERA_SIZE), name='SCI')
            hdu.header.set('CAMERA', phu.header.get('CAMERA'))
            hdu.header.set('CCDNAME', phu.header.get('CCDNAME'))
            hdu.header.set('EXPID', i + 1)
            hdu.header.set('CCDSUM', '2 2')
            hdu.header.set('EXPUTST', (SLIT_UT_START + datetime.timedelta(
                seconds=(i * 0.2) * EXPTIME_SLITS)).strftime(STRFTIME))
            hdu.header.set(
                'EXPUTST', (SLIT_UT_START + datetime.timedelta(seconds=(
                    (i * 0.2) + 1) * EXPTIME_SLITS)).strftime(STRFTIME))
            hdu.header.set('GAIN', 1.0)
            hdu.header.set('RDNOISE', 8.0)
            hdus.append(hdu)

        # Create AstroData
        ad = astrodata.create(phu, hdus)
        ad.filename = rawfilename

        yield ad, tmpsubdir

        # Teardown code - remove files in this tmpdir
        for _ in glob.glob(
                os.path.join(tmpsubdir.dirname, tmpsubdir.basename, '*.fits')):
            os.remove(_)
        try:
            shutil.rmtree(
                os.path.join(tmpsubdir.dirname, tmpsubdir.basename,
                             'calibrations'))
        except OSError:
            pass
Ejemplo n.º 28
0
def test_append_tables2():
    """Check that slices do not report extension tables."""
    ad = astrodata.create({})
    ad.append(NDData(np.zeros((4, 5)), meta={'header': {}}))
    ad.append(NDData(np.zeros((4, 5)), meta={'header': {}}))
    ad.append(NDData(np.zeros((4, 5)), meta={'header': {}}))
    ad.append(Table([[1]]), name='TABLE1', add_to=ad[0].nddata)
    ad.append(Table([[1]]), name='TABLE2', add_to=ad[1].nddata)
    ad.append(Table([[1]]), name='TABLE3', add_to=ad[2].nddata)

    assert ad.exposed == set()
    assert ad[1].exposed == {'TABLE2'}
    assert ad[1:].exposed == set()
Ejemplo n.º 29
0
def test_append_lowercase_name():
    nd = NDData(np.zeros((4, 5)), meta={'header': {}})
    ad = astrodata.create({})
    ad.append(nd)
    ad.append(Table([[1]]), name='foo')
    ad.append(Table([[1], [2]]), name='bar', add_to=ad[0].nddata)
    ad.append(np.zeros(3), name='arr', add_to=ad[0].nddata)

    assert ad.tables == {'FOO'}
    assert ad.exposed == {'FOO'}

    assert ad[0].tables == {'FOO', 'BAR'}
    assert ad[0].exposed == {'FOO', 'BAR', 'ARR'}
Ejemplo n.º 30
0
def test_table_with_units(tmp_path):
    testfile = tmp_path / 'test.fits'
    ad = astrodata.create({})
    ad.append(NDData(np.zeros((4, 5))))
    ad[0].TABLE1 = Table([[1]])
    ad[0].TABLE1['col0'].unit = 'mag(cm2 electron / erg)'

    with pytest.warns(None) as w:
        ad.write(testfile)

    assert len(w) == 0
    ad = astrodata.open(testfile)
    assert ad[0].TABLE1['col0'].unit == u.Unit('mag(cm2 electron / erg)')
Ejemplo n.º 31
0
def test_write_and_read(tmpdir, capsys):
    ad = astrodata.create({})
    nd = NDData(data=[[1, 2], [3, 4]],
                uncertainty=VarianceUncertainty(np.ones((2, 2))),
                mask=np.identity(2),
                meta={'header': fits.Header()})
    ad.append(nd)

    tbl = Table([np.zeros(10), np.ones(10)], names=('a', 'b'))

    with pytest.raises(ValueError,
                       match='Tables should be set directly as attribute'):
        ad.append(tbl, name='BOB')

    ad.BOB = tbl

    tbl = Table([np.zeros(5) + 2, np.zeros(5) + 3], names=('c', 'd'))

    match = "Cannot append table 'BOB' because it would hide a top-level table"
    with pytest.raises(ValueError, match=match):
        ad[0].BOB = tbl

    ad[0].BOB2 = tbl
    ad[0].MYVAL_WITH_A_VERY_LONG_NAME = np.arange(10)

    match = "You can only append NDData derived instances at the top level"
    with pytest.raises(TypeError, match=match):
        ad[0].MYNDD = NDData(data=np.ones(10), meta={'header': fits.Header()})

    testfile = str(tmpdir.join('testfile.fits'))
    ad.write(testfile)

    ad = astrodata.open(testfile)
    ad.info()
    captured = capsys.readouterr()
    assert captured.out.splitlines()[3:] == [
        'Pixels Extensions',
        'Index  Content                  Type              Dimensions     Format',
        '[ 0]   science                  NDAstroData       (2, 2)         int64',
        '          .variance             ADVarianceUncerta (2, 2)         float64',
        '          .mask                 ndarray           (2, 2)         uint16',
        '          .BOB2                 Table             (5, 2)         n/a',
        '          .MYVAL_WITH_A_VERY_LO ndarray           (10,)          int64',
        '',
        'Other Extensions',
        '               Type        Dimensions',
        '.BOB           Table       (10, 2)'
    ]
    assert_array_equal(ad[0].nddata.data[0], nd.data[0])
    assert_array_equal(ad[0].nddata.variance[0], nd.uncertainty.array[0])
    assert_array_equal(ad[0].nddata.mask[0], nd.mask[0])
Ejemplo n.º 32
0
def test_extver2(tmp_path):
    """Test renumbering of EXTVER."""
    testfile = tmp_path / 'test.fits'

    ad = astrodata.create(fits.PrimaryHDU())
    data = np.arange(5)
    ad.append(fits.ImageHDU(data=data, header=fits.Header({'EXTVER': 2})))
    ad.append(fits.ImageHDU(data=data + 2, header=fits.Header({'EXTVER': 5})))
    ad.append(fits.ImageHDU(data=data + 5))
    ad.append(fits.ImageHDU(data=data + 7, header=fits.Header({'EXTVER': 3})))
    ad.write(testfile)

    ad = astrodata.open(testfile)
    assert [hdr['EXTVER'] for hdr in ad.hdr] == [1, 2, 3, 4]
Ejemplo n.º 33
0
def test_can_append_an_image_hdu_object_to_an_astrodata_object():
    primary_header_unit = fits.PrimaryHDU()

    ad = astrodata.create(primary_header_unit)

    data_array = np.zeros((100, 100))

    header_data_unit = fits.ImageHDU()
    header_data_unit.data = data_array

    ad.append(header_data_unit, name='SCI')
    ad.append(header_data_unit, name='SCI2')

    assert len(ad) == 2
Ejemplo n.º 34
0
def test_can_create_new_astrodata_object_with_no_data():
    primary_header_unit = fits.PrimaryHDU()

    ad = astrodata.create(primary_header_unit)

    assert isinstance(ad, astrodata.AstroData)
Ejemplo n.º 35
0
    def _tile_blocks(self, block=None, doimg=False, return_ROI=True):
        """
        Tiles data into separate extensions for each CCD chip.
        In mosaicAD terms, these are called "blocks." Each block comprises
        all amplifier extensions that are part of the chip. Nominal GMOS
        Hamamatsu images result in a 3-extension FITS file, and GSAOI, a
        4-extension FITS file.

        This method is called when the primitive MosaicDetectors passes the
        tile_all parameter as False, which implies chip separated tiling.

        Parameters
        ----------
        block: <2-tuple>
            Users can select a particular block to tile. None indicates all
            blocks will be tiled. Default is None.

        doimg: <bool>
             Tile only the image (SCI) extension data. Fast for quicklook.

        return_ROI: <bool>
            Returns the minimum frame size calculated from the location of the
            amplifiers in a given block. If False, uses the blocksize value.
            Default is True.

        Returns
        -------
        adout: <AstroData>
            instance of astrodata containg the tiled data. Ready for writing.

        """
        warn = "No {} array for block {} on {}"
        adout = astrodata.create(self.ad.phu)
        adout.phu['TILED'] = (True, "True: tiled; False: Mosaic")

        # SCI
        self.data_list = self.get_data_list('data')
        if not self.data_list:
            emsg = "MosaicAD received a dataset with no data: {}"
            self.log.error(emsg.format(self.ad.filename))
            raise IOError("No science data found on file {}".format(self.ad.filename))

        self.log.stdinfo("MosaicAD v{} working on data arrays ...".format(__version__))
        dblocks = self.get_blocks()
        if not doimg:
            # VAR
            self.data_list = self.get_data_list('variance')
            varblocks = self.get_blocks()

            # DQ
            self.data_list = self.get_data_list('mask')
            maskblocks = self.get_blocks()

            # OBJMASK
            self.data_list = self.get_data_list('OBJMASK')
            objmaskblocks = self.get_blocks()

            blocks_indx = list(dblocks.keys())
            i = 0
            for iblock in blocks_indx:
                darray = dblocks[iblock]
                header = self._tile_header(darray.shape, iblock)
                adout.append(darray, header=header)

                varray = None
                if varblocks:
                    self.log.stdinfo("Working on VAR arrays ...")
                    varray = varblocks[iblock]
                else:
                    self.log.stdinfo(warn.format('VAR', iblock, self.ad.filename))

                marray = None
                if maskblocks:
                    self.log.stdinfo("Working on DQ arrays ...")
                    marray = maskblocks[iblock]
                else:
                    self.log.stdinfo(warn.format('DQ', iblock, self.ad.filename))

                adout[i].reset(data=darray, variance=varray, mask=marray)

                if objmaskblocks:
                    self.log.stdinfo("Working on OBJMASK arrays ...")
                    adout[i].OBJMASK = objmaskblocks[iblock]
                else:
                    self.log.stdinfo(warn.format('OBJMASK', iblock, self.ad.filename))
                i += 1

            # tile OBJCATS
            self.log.stdinfo("Tiling OBJCATS ...")
            adout = self._tile_objcats(adout)

            # Propagate any REFCAT
            if hasattr(self.ad, 'REFCAT'):
                self.log.stdinfo("Keeping REFCAT ...")
                adout.REFCAT = self.ad.REFCAT

        return adout
Ejemplo n.º 36
0
    def as_astrodata(self, block=None, doimg=False, tile=False, return_ROI=True):
        """
        Returns an AstroData object  containing by default the mosaiced IMAGE
        extensions. WCS information in headers of the IMAGE extensions and
        updated appropriately. When tiling, OBJCATS are retained.

        Parameters
        ----------
        block: <2-tuple>
              Return a specific block as the output mosaic as (col, row).
              (0, 0) is lower left.

        tile: <bool>
              Tile rather than transform data blocks. Default is False.

        doimg: <bool>
              Process only science ("SCI') extensions. Default is False.

        return_ROI: <bool>
              Returns the minimum frame size calculated from the location of the
              amplifiers in a given block. If False, uses the blocksize value.
              Default is True.

        Returns
        -------
        adout: <AstroData> instance, mosaic or tiled as requested.

        """
        adout = astrodata.create(self.ad.phu)
        adout.phu['TILED'] = (repr(tile).upper(), "True: tiled; False: Mosaic")

        # image arrays mosaicked: 'data', 'variance', 'mask', 'OBJMASK'.
        # SCI
        self.data_list = self.get_data_list('data')
        if not self.data_list:
            emsg = "MosaicAD received a dataset with no data: {}"
            self.log.error(emsg.format(self.ad.filename))
            raise IOError("No science data found on file {}".format(self.ad.filename))
        else:
            self.log.stdinfo("MosaicAD working on data arrays ...")
            darray = self.mosaic_image_data(block=block,return_ROI=return_ROI,tile=tile)
            self.mosaic_shape = darray.shape
            header = self.mosaic_header(darray.shape, block, False)
            adout.append(darray, header=header)

        # VAR
        varray = None
        if not doimg:
            self.data_list = self.get_data_list('variance')
            if not self.data_list:
                self.log.stdinfo("No VAR array on {} ".format(self.ad.filename))
            else:
                self.log.stdinfo("Working on VAR arrays ...")
                varray = self.mosaic_image_data(block=block,return_ROI=return_ROI,
                                                tile=tile)
        # DQ
        marray = None
        if not doimg:
            self.data_list = self.get_data_list('mask')
            if not self.data_list:
                self.log.stdinfo("No DQ array on {} ".format(self.ad.filename))
            else:
                self.log.stdinfo("Working on DQ arrays ...")
                marray= self.mosaic_image_data(block=block,return_ROI=return_ROI,
                                               tile=tile, dq_data=True)

        adout[0].reset(data=darray, variance=varray, mask=marray)

        # Handle extras ...
        if not doimg:
            self.data_list = self.get_data_list('OBJMASK')
            if not self.data_list:
                self.log.stdinfo("No OBJMASK on {} ".format(self.ad.filename))
            else:
                self.log.stdinfo("Working on OBJMASK arrays ...")
                adout[0].OBJMASK = self.mosaic_image_data(block=block,
                                                          return_ROI=return_ROI,
                                                          tile=tile)

        # When tiling, tile OBJCATS
        if not doimg and tile:
            self.log.stdinfo("Tiling OBJCATS ...")
            adout = self._tile_objcats(adout)

        # Propagate any REFCAT
        if not doimg:
            if hasattr(self.ad, 'REFCAT'):
                self.log.stdinfo("Keeping REFCAT ...")
                adout.REFCAT = self.ad.REFCAT

        return adout