Exemplo n.º 1
0
    def test_getMap_invalid_channel(self, galaxy):
        maps = Maps(plateifu=galaxy.plateifu)
        with pytest.raises(ValueError) as ee:
            maps.getMap(property_name='emline_gflux',
                        channel='mythical_channel')

        assert 'Your input value is too ambiguous.' in str(ee.value)
    def __init__(self, file_path):
        self.file_path = file_path
        self.filename = self.file_path.split('/')[-1]
        self.data = gz3d_fits.gz3d_fits(file_path)
        self.mangaid = self.data.metadata['MANGAID'][0]

        self.maps = Maps(self.mangaid)
        self.hamap = self.maps.emline_gflux_ha_6564
        self.hbmap = self.maps.emline_gflux_hb_4862
        self.eff_rad = self.maps.nsa['elpetro_th50_r'] * 2
        self.redshift = self.maps.nsa['z']
        self.mass = self.maps.nsa['sersic_mass']
        self.lgmass = np.log10(self.mass)
        self.elpetro_ba = self.maps.nsa['elpetro_ba']
        self.theta = np.radians(self.maps.nsa['elpetro_phi'] - 90.0)
        self.map_shape = self.hamap.shape

        self.d_mpc = ((299792.458 * self.redshift) / 70)  #Mpc
        self.d_kpc = self.d_mpc * 1E3
        self.d_m = self.d_mpc * 3.085677581E+22  # m
        self.delta = (4 * np.pi * (self.d_m**2)) / ((2.8**2.36) * (10**41.1))
        self.spax_area = (0.0000024240684055477 * self.d_kpc)**2

        self.global_df_loaded = False
        self.bpt_masks_loaded = False
        self.r_array_loaded = False
Exemplo n.º 3
0
    def test_datamodel(self, galaxy, exporigin):

        maps = Maps(**self._get_maps_kwargs(galaxy, exporigin))

        fin = 'manga-{0}-{1}-MAPS-{2}.fits.gz'.format(galaxy.plate, galaxy.ifu,
                                                      galaxy.bintemp)
        path = join(galaxy.mangaanalysis, galaxy.drpver, galaxy.dapver,
                    galaxy.bintemp, str(galaxy.plate), galaxy.ifu, fin)
        hdus = astropy.io.fits.open(path)

        for hdu in hdus[1:]:

            if ('IVAR' in hdu.name) or ('MASK' in hdu.name) or ('SIGMACORR'
                                                                in hdu.name):
                continue

            name = hdu.name.lower()
            data = hdu.data
            header = hdu.header

            if len(data.shape) < 3:
                val = maps.getMap(name, exact=True).value
                assert val == pytest.approx(data, 0.0001), name

            else:
                for kk, vv in header.items():
                    channel_num = re.match('^[0-9]+$', kk[1:])

                    if (kk[0] == 'C') and (channel_num is not None):
                        channel = '_'.join(re.findall(r"[\w']+", vv)).lower()
                        fullname = '_'.join((name, channel))
                        val = maps.getMap(fullname, exact=True).value
                        assert val == pytest.approx(data[int(kk[1:]) - 1],
                                                    0.0001), name
Exemplo n.º 4
0
    def __init__(self, file_path):
        """initialises galaxy with certain methods variables and methods.
        
        Taking in file path for GZ3D .FITS, the class is initialised by
        initialising the `gz3d_fits` class, initialising variables like
        the MaNGA ID, Marvin Maps class attributes like the emission maps,
        and function 'switches' to make sure resource intensive methods are
        only run once.
        
        Args:
            file_path (str): File path to the GZ3D .FITS file.
        """

        self.file_path = file_path
        self.data = gz3d_fits.gz3d_fits(file_path)
        self.mangaid = self.data.metadata['MANGAID'][0]

        self.maps = Maps(self.mangaid)
        self.hamap = self.maps.emline_gflux_ha_6564
        self.hbmap = self.maps.emline_gflux_hb_4862
        self.eff_rad = self.maps.nsa['elpetro_th50_r'] * 2
        self.redshift = self.maps.nsa['z']
        self.mass = self.maps.nsa['sersic_mass']
        self.elpetro_ba = self.maps.nsa['elpetro_ba']
        self.theta = np.radians(self.maps.nsa['elpetro_phi'] - 90.0)

        self.flux_df_loaded = False
        self.sfr_cols_loaded = False
        self.ellipical_mask_loaded = False
        self.ellipical_cutout_on = True
Exemplo n.º 5
0
    def test_deepcopy(self, galaxy, property_name, channel):
        maps = Maps(plateifu=galaxy.plateifu)
        map1 = maps.getMap(property_name=property_name, channel=channel)
        map2 = deepcopy(map1)

        for attr in vars(map1):
            if not attr.startswith('_'):
                value = getattr(map1, attr)
                value2 = getattr(map2, attr)

                if isinstance(value, np.ndarray):
                    assert np.isclose(value, value2).all()

                elif isinstance(value, np.ma.core.MaskedArray):
                    assert (np.isclose(value.data, value2.data).all() and
                            (value.mask == value2.mask).all())

                elif isinstance(value, Maskbit) or isinstance(value[0], Maskbit):

                    if isinstance(value, Maskbit):
                        value = [value]
                        value2 = [value2]

                    for mb, mb2 in zip(value, value2):
                        for it in ['bits', 'description', 'labels', 'mask', 'name']:
                            assert getattr(mb, it) == getattr(mb2, it)

                        assert (mb.schema == mb2.schema).all().all()

                elif isinstance(value, Maps):
                    pass

                else:
                    assert value == value2, attr
Exemplo n.º 6
0
    def test_getMapRatio(self, galaxy):
        maps = Maps(galaxy.plateifu)
        map_ratio = maps.getMapRatio('emline_gflux', 'nii_6585', 'ha_6564')
        map_arith = maps.emline_gflux_nii_6585 / maps.emline_gflux_ha_6564

        assert map_ratio.value == pytest.approx(map_arith.value, nan_ok=True)
        assert map_ratio.ivar == pytest.approx(map_arith.ivar, nan_ok=True)
        assert map_ratio.mask == pytest.approx(map_arith.mask, nan_ok=True)
Exemplo n.º 7
0
    def test_8485_1901_bpt_no_figure(self):

        maps = Maps(plateifu=self.plateifu)
        bpt_return = maps.get_bpt(show_plot=False,
                                  return_figure=False,
                                  use_oi=False)

        self.assertIsInstance(bpt_return, dict)
Exemplo n.º 8
0
    def test_subtract_maps(self, galaxy, property1, channel1, property2, channel2):
        maps = Maps(plateifu=galaxy.plateifu)
        map1 = maps.getMap(property_name=property1, channel=channel1)
        map2 = maps.getMap(property_name=property2, channel=channel2)
        map12 = map1 - map2

        assert map12.value == pytest.approx(map1.value - map2.value)
        assert map12.ivar == pytest.approx(map1._add_ivar(map1.ivar, map2.ivar))
        assert map12.mask == pytest.approx(map1.mask | map2.mask)
Exemplo n.º 9
0
    def test_8485_1901_bpt_snr_min(self):

        maps = Maps(plateifu=self.plateifu)
        masks = maps.get_bpt(snr_min=5, return_figure=False, show_plot=False)

        for em_mech in self.emission_mechanisms:
            self.assertIn(em_mech, masks.keys())

        self.assertEqual(np.sum(masks['sf']['global']), 28)
        self.assertEqual(np.sum(masks['sf']['sii']), 112)
Exemplo n.º 10
0
def maps(galaxy, exporigin, mode):
    ''' Yield a Marvin Maps based on the expected origin combo of (mode+db).
        Fixture tests 6 cube origins from (mode+db) combos [file, db and api]
    '''
    if exporigin == 'file':
        m = Maps(filename=galaxy.mapspath, release=galaxy.release, mode=mode, bintype=galaxy.bintype)
    else:
        m = Maps(plateifu=galaxy.plateifu, release=galaxy.release, mode=mode, bintype=galaxy.bintype)
    m.exporigin = exporigin
    yield m
    m = None
Exemplo n.º 11
0
    def test_model_deprecated(self, galaxy, exporigin):

        if exporigin != 'db':
            pytest.skip()

        maps = Maps(**self._get_maps_kwargs(galaxy, exporigin))

        with pytest.raises(MarvinDeprecationError) as ee:
            maps.getSpaxel(x=0, y=0, model=True)

        assert 'the model parameter has been deprecated. Use models.' in str(ee)
Exemplo n.º 12
0
def maps(galaxy, mode):
    if galaxy.bintype.name != 'SPX':
        pytest.skip('Only running one bintype for bpt tests')

    # if galaxy.release != 'MPL-6':
    #     pytest.skip('Explicitly skipping here since marvin_test_if_class does not work in 2.7')

    maps = Maps(plateifu=galaxy.plateifu, mode=mode)
    maps.bptsums = galaxy.bptsums if hasattr(galaxy, 'bptsums') else None
    yield maps
    maps = None
Exemplo n.º 13
0
    def test_pow(self, galaxy, property_name, channel, power):
        maps = Maps(plateifu=galaxy.plateifu)
        map_orig = maps.getMap(property_name=property_name, channel=channel)
        map_new = map_orig**power

        sig_orig = np.sqrt(1. / map_orig.ivar)
        sig_new = map_new.value * power * sig_orig * map_orig.value
        ivar_new = 1 / sig_new**2.

        assert pytest.approx(map_new.value, map_orig.value**power)
        assert pytest.approx(map_new.ivar, ivar_new)
        assert (map_new.mask == map_orig.mask).all()
Exemplo n.º 14
0
    def test_get_spaxel_test2(self, galaxy, data_origin):

        maps = Maps(**self._get_maps_kwargs(galaxy, data_origin))

        spaxel = _get_spaxel_helper(maps, 5, 5)

        if maps.is_binned():
            assert isinstance(spaxel, Spaxel)
        else:
            assert isinstance(spaxel, Spaxel)

        assert len(spaxel.maps_quantities.keys()) > 0
Exemplo n.º 15
0
    def test_multiply_maps(self, galaxy, property1, channel1, property2, channel2):
        maps = Maps(plateifu=galaxy.plateifu)
        map1 = maps.getMap(property_name=property1, channel=channel1)
        map2 = maps.getMap(property_name=property2, channel=channel2)
        map12 = map1 * map2

        ivar = map1._mul_ivar(map1.ivar, map2.ivar, map1.value, map2.value, map12.value)
        ivar[np.isnan(ivar)] = 0
        ivar[np.isinf(ivar)] = 0

        assert map12.value == pytest.approx(map1.value * map2.value)
        assert map12.ivar == pytest.approx(ivar)
        assert map12.mask == pytest.approx(map1.mask | map2.mask)
Exemplo n.º 16
0
    def test_multiply_maps(self, galaxy, property1, channel1, property2,
                           channel2):
        maps = Maps(plateifu=galaxy.plateifu)
        map1 = maps.getMap(property_name=property1, channel=channel1)
        map2 = maps.getMap(property_name=property2, channel=channel2)
        map12 = map1 * map2

        assert pytest.approx(map12.value, map1.value * map2.value)
        assert pytest.approx(
            map12.ivar,
            map1._mul_ivar(map1.ivar, map2.ivar, map1.value, map2.value,
                           map12.value))
        assert pytest.approx(map12.mask, map1.mask | map2.mask)
Exemplo n.º 17
0
    def test_pow(self, galaxy, property_name, channel, power):
        maps = Maps(plateifu=galaxy.plateifu)
        map_orig = maps.getMap(property_name=property_name, channel=channel)
        map_new = map_orig**power

        sig_orig = np.sqrt(1. / map_orig.ivar)
        sig_new = map_new.value * power * sig_orig * map_orig.value
        ivar_new = 1 / sig_new**2.
        ivar_new[np.isnan(ivar_new)] = 0
        ivar_new[np.isinf(ivar_new)] = 0

        assert map_new.value == pytest.approx(map_orig.value**power, nan_ok=True)
        assert map_new.ivar == pytest.approx(ivar_new)
        assert (map_new.mask == map_orig.mask).all()
Exemplo n.º 18
0
    def test_deprecated(self, galaxy, exporigin):

        if exporigin != 'db':
            pytest.skip()

        maps = Maps(**self._get_maps_kwargs(galaxy, exporigin))

        for old_arg in ['drp', 'model', 'models']:

            with pytest.raises(MarvinDeprecationError) as ee:
                kwargs = {old_arg: True}
                maps.getSpaxel(x=0, y=0, **kwargs)

            assert 'the {0} parameter has been deprecated.'.format(old_arg) in str(ee)
Exemplo n.º 19
0
    def test_get_spaxel_no_db(self, galaxy, exporigin):
        """Tests getting an spaxel if there is no DB."""

        maps = Maps(**self._get_maps_kwargs(galaxy, exporigin))
        spaxel = _get_spaxel_helper(maps, 5, 5)

        assert spaxel.getMaps().data_origin == exporigin

        if maps.is_binned():
            assert isinstance(spaxel, Spaxel)
        else:
            assert isinstance(spaxel, Spaxel)

        assert len(spaxel.maps_quantities.keys()) > 0
Exemplo n.º 20
0
    def test_get_spaxel(self, galaxy, data_origin):

        maps = Maps(**self._get_maps_kwargs(galaxy, data_origin))

        spaxel = _get_spaxel_helper(maps, 15, 8, xyorig='lower')

        if maps.is_binned():
            assert isinstance(spaxel, Bin)
        else:
            assert isinstance(spaxel, Spaxel)
            expected = galaxy.stellar_vel_ivar_x15_y8_lower[galaxy.release][galaxy.template.name]
            assert spaxel.maps_quantities['stellar_vel'].ivar == pytest.approx(expected, abs=1e-6)

        assert len(spaxel.maps_quantities.keys()) > 0
Exemplo n.º 21
0
    def test_8485_1901_bpt_no_oi(self):

        maps = Maps(plateifu=self.plateifu)
        masks, figure = maps.get_bpt(show_plot=False,
                                     return_figure=True,
                                     use_oi=False)
        self.assertIsInstance(figure, plt.Figure)

        for em_mech in self.emission_mechanisms:
            self.assertIn(em_mech, masks.keys())

        self.assertNotIn('oi', masks['sf'].keys())

        self.assertEqual(np.sum(masks['sf']['global']), 149)
        self.assertEqual(np.sum(masks['sf']['sii']), 176)
Exemplo n.º 22
0
    def test_divide_maps(self, galaxy, property1, channel1, property2,
                         channel2):
        maps = Maps(plateifu=galaxy.plateifu)
        map1 = maps.getMap(property_name=property1, channel=channel1)
        map2 = maps.getMap(property_name=property2, channel=channel2)
        map12 = map1 / map2

        with np.errstate(divide='ignore', invalid='ignore'):
            assert pytest.approx(map12.value, map1.value / map2.value)

        assert pytest.approx(
            map12.ivar,
            map1._mul_ivar(map1.ivar, map2.ivar, map1.value, map2.value,
                           map12.value))
        assert pytest.approx(map12.mask, map1.mask | map2.mask)
Exemplo n.º 23
0
    def test_sort_dir_map(self, galaxy, class_, expected):
        maps = Maps(plateifu=galaxy.plateifu)
        ha = maps['emline_gflux_ha_6564']

        dir_ = _sort_dir(ha, class_)
        dir_public = [it for it in dir_ if it[0] != '_']
        assert set(dir_public) == set(expected)
Exemplo n.º 24
0
    def test_deepcopy(self, galaxy):
        maps1 = Maps(plateifu=galaxy.plateifu)
        maps2 = copy.deepcopy(maps1)

        for attr in vars(maps1):
            if not attr.startswith('_'):
                value = getattr(maps1, attr)
                value2 = getattr(maps2, attr)

                if isinstance(value, np.ndarray):
                    assert np.isclose(value, value2).all()

                elif isinstance(value, astropy.wcs.wcs.WCS):
                    for key in vars(value):
                        assert getattr(value, key) == getattr(value2, key)

                elif isinstance(value, marvin.tools.cube.Cube):
                    pass

                elif attr in ['vacs']:
                    pass

                elif (isinstance(value, list) and len(value) > 0
                      and isinstance(value[0], Property)):
                    for property1, property2 in zip(value, value2):
                        assert property1 == property2

                else:
                    assert value == value2, attr
Exemplo n.º 25
0
    def test_values(self, galaxy, exporigin):

        template = str(galaxy.template)

        if template not in galaxy.dap:
            pytest.skip()

        maps = Maps(**self._get_maps_kwargs(galaxy, exporigin))

        xx = galaxy.dap['x']
        yy = galaxy.dap['y']

        for channel in galaxy.dap[template]:

            if channel == 'model':
                continue

            channel_data = galaxy.dap[template][channel]
            map = maps[channel]

            assert map[yy, xx].value == pytest.approx(channel_data['value'],
                                                      abs=1.e-4)
            assert map.unit.scale == 1e-17
            assert map.unit.to_string() == channel_data['unit']

            assert map[yy, xx].mask == pytest.approx(channel_data['mask'],
                                                     abs=1.e-4)
            assert map[yy, xx].ivar == pytest.approx(channel_data['ivar'],
                                                     abs=1.e-4)
Exemplo n.º 26
0
def return_dict(filepath):
    galdict = {'filepath': filepath}

    galdict['filename'] = galdict['filepath'].split('/')[-1]
    galdict['mangaid'] = galdict['filename'].split('_')[0]

    maps = Maps(galdict['mangaid'])

    galdict['z'] = maps.nsa['z']
    galdict['d_mpc'] = (299792.458 * galdict['z']) / 70  #Mpc
    galdict['d_kpc'] = galdict['d_mpc'] * 1E3  #Kpc
    galdict['d_m'] = galdict['d_mpc'] * 3.085677581E+22  # m
    galdict['delta'] = (4 * np.pi * (galdict['d_m']**2)) / ((2.8**2.36) *
                                                            (10**41.1))
    galdict['spax_area'] = (0.0000024240684055477 *
                            galdict['d_kpc'])**2  # Kpc^2
    galdict['map_shape'] = maps.emline_gflux_ha_6564.shape

    galdict['eff_rad'] = maps.nsa[
        'elpetro_th50_r'] * 2  #maps.nsa['elpetro_th50_r'] is in " units, so we multiply by 2 to get effective radius in units of spaxels
    galdict['mass'] = maps.nsa['sersic_mass']
    galdict['theta'] = np.radians(maps.nsa['elpetro_phi'] - 90.0)
    galdict['elpetro_ba'] = maps.nsa['elpetro_ba']

    return galdict
Exemplo n.º 27
0
    def test_pickling_only_cube_file(self, temp_scratch, galaxy):
        if galaxy.bintype.name != 'SPX':
            pytest.skip("Can't instantiate a Spaxel from a binned Maps.")

        cube = Cube(filename=galaxy.cubepath)
        maps = Maps(filename=galaxy.mapspath)

        spaxel = cube.getSpaxel(1, 3, maps=maps, modelcube=False)

        file = temp_scratch.join('test_spaxel.mpf')

        path_saved = spaxel.save(str(file), overwrite=True)
        assert file.check() is True
        assert os.path.exists(path_saved)

        del spaxel

        spaxel_restored = Spaxel.restore(str(file))
        assert spaxel_restored is not None
        assert isinstance(spaxel_restored, Spaxel)

        assert spaxel_restored._cube is not None
        assert spaxel_restored._cube.data_origin == 'file'
        assert isinstance(spaxel_restored._cube.data, astropy.io.fits.HDUList)

        assert spaxel_restored._maps is not None
        assert spaxel_restored._maps.data_origin == 'file'
        assert isinstance(spaxel_restored._maps.data, astropy.io.fits.HDUList)
Exemplo n.º 28
0
    def test_stellar_sigma_correction_MPL4(self, galaxy):
        maps = Maps(plateifu=galaxy.plateifu)
        stsig = maps['stellar_sigma']
        with pytest.raises(MarvinError) as ee:
            stsig.inst_sigma_correction()

        assert 'Instrumental broadening correction not implemented for MPL-4.' in str(
            ee.value)
Exemplo n.º 29
0
    def test_load_mpl4_global_mpl5(self, galaxy, monkeyconfig, data_origin):

        assert marvin.config.release == 'MPL-5'
        maps = Maps(**self._get_maps_kwargs(galaxy, data_origin))

        assert maps.release == galaxy.release
        assert maps._drpver == galaxy.drpver
        assert maps._dapver == galaxy.dapver
Exemplo n.º 30
0
 def test_hasmap(self):
     maps = Maps(plateifu='8485-1901', release='MPL-6', bintype='HYB10')
     spaxel = maps[22, 14]
     b = spaxel.stellar_vel.bin
     assert isinstance(b._parent, Maps)
     assert isinstance(b._datamodel, Property)
     assert b._datamodel.name == 'stellar_vel'
     assert b.binid_map is not None