Esempio n. 1
0
def compare_missing_mass(tab, mlb='i', cb1='g', cb2='r'):
    '''make figure showing effect of aperture correction on total mass
    
    Figure shows P+ (red) and S (blue) samples,
    with their integrated color, difference between aperture-corrected
    masses using CMLR and ring method
    
    Parameters
    ----------
    tab : astropy.table.Table
        full aggregation results table
    mlb : {str}, optional
        bandpass for mass-to-light ratio
        (the default is 'i', which [default_description])
    cb1 : {str}, optional
        bluer bandpass for color (the default is 'g', SDSS g band)
    cb2 : {str}, optional
        redder bandpass for color (the default is 'r', SDSS r band)
    '''
    cb1_nsa_mag = tab[f'mag_nsa_{cb1}']
    cb2_nsa_mag = tab[f'mag_nsa_{cb2}']

    broadband_color = cb1_nsa_mag - cb2_nsa_mag
    outermass_cmlr = (tab[f'logsollum_outer_{mlb}'] + tab['outerml_cmlr']).to(
        u.Msun)
    mass_cmlr = (tab['mass_in_ifu'].to(u.Msun) + outermass_cmlr)
    outermass_ring = (tab[f'logsollum_outer_{mlb}'] + tab['outerml_ring']).to(
        u.Msun)
    mass_ring = (tab['mass_in_ifu'].to(u.Msun) + outermass_ring)
    dlogmass_cmlr_ring = mass_cmlr.to(u.dex(u.Msun)) - mass_ring.to(u.dex(u.Msun))

    primarysample = m.mask_from_maskbits(tab['mngtarg1'], [10])
    secondarysample = m.mask_from_maskbits(tab['mngtarg1'], [11])

    fig, main_ax, hist_ax = make_panel_hist(top=0.9, left=.225)

    valid = np.isfinite(dlogmass_cmlr_ring)

    for selection, label, marker, color in zip(
        [primarysample, secondarysample], ['Primary', 'Secondary'],
        ['o', 'D'], ['r', 'b']):
    
        main_ax.scatter(
            x=broadband_color[selection * valid], y=dlogmass_cmlr_ring[selection * valid],
            c=color, edgecolor='None', s=3., marker=marker, label=label,
            alpha=0.5)

        hist_ax.hist(dlogmass_cmlr_ring[selection * valid], color=color, density=True, bins='auto',
                     histtype='step', orientation='horizontal', linewidth=0.75)

    main_ax.set_xlim(np.percentile(broadband_color[valid], [5., 99.]))
    main_ax.set_ylim(np.percentile(dlogmass_cmlr_ring[valid], [5., 99.]))

    main_ax.legend(loc='best', prop={'size': 'xx-small'})
    main_ax.tick_params(labelsize='xx-small')
    main_ax.set_xlabel(r'${}-{}$'.format(cb1, cb2), size='x-small')
    main_ax.set_ylabel(r'$\log \frac{M^{\rm tot}_{\rm CMLR}}{M^{\rm tot}_{\rm ring}}$',
                  size='x-small')
    fig.suptitle(r'Impact of aperture-correction on $M^{\rm tot}$', size='small')
    fig.savefig(os.path.join(csp_basedir, 'lib_diags/', 'mtot_compare_cmlr_ring.png'))
Esempio n. 2
0
def make_missing_flux_fig(tab, mlb='i', cb1='g', cb2='r'):
    mlb_ix = totalmass.StellarMass.bands_ixs[mlb]
    cb1_ix = totalmass.StellarMass.bands_ixs[cb1]
    cb2_ix = totalmass.StellarMass.bands_ixs[cb2]
    absmag_sun_mlb = totalmass.StellarMass.absmag_sun[mlb_ix]

    broadband_color = (tab['nsa_absmag'][:, cb1_ix] - tab['nsa_absmag'][:, cb2_ix])
    outerlum_frac = tab['outer_lum'][:, mlb_ix].to(m.bandpass_sol_l_unit) / \
                    tab['nsa_absmag'][:, mlb_ix].to(m.bandpass_sol_l_unit, 
                        totalmass.bandpass_flux_to_solarunits(absmag_sun_mlb))

    primarysample = m.mask_from_maskbits(tab['mngtarg1'], [10])
    secondarysample = m.mask_from_maskbits(tab['mngtarg1'], [11])

    fig, main_ax, hist_ax = make_panel_hist(top=0.875)

    for selection, label, marker, color in zip(
        [primarysample, secondarysample], ['Primary+', 'Secondary'],
        ['o', 'D'], ['r', 'b']):
    
        main_ax.scatter(
            x=broadband_color[selection], y=outerlum_frac[selection],
            c=color, edgecolor='None', s=5., marker=marker, label=label)

        hist_ax.hist(outerlum_frac[selection], color=color, density=True, bins='auto',
                     histtype='step', orientation='horizontal', linewidth=0.75)

    main_ax.set_xlim(np.percentile(broadband_color, [1., 99.]))

    main_ax.legend(loc='best', prop={'size': 'xx-small'})
    main_ax.tick_params(labelsize='xx-small')
    main_ax.set_xlabel(r'${}-{}$'.format(cb1, cb2), size='x-small')
    main_ax.set_ylabel('Flux fraction outside IFU', size='x-small')
    fig.suptitle('Flux fraction outside IFU', size='small')
    fig.savefig(os.path.join(basedir, 'lib_diags/', 'flux_outside_ifu.png'))
Esempio n. 3
0
    def __init__(self, results, pca_system, drp, dap, drpall_row, cosmo, mlband='i'):
        self.results = results
        self.pca_system = pca_system
        self.drp = drp
        self.dap = dap
        self.drpall_row = drpall_row
        self.cosmo = cosmo
        self.mlband = mlband

        with catch_warnings():
            simplefilter('ignore')
            self.results.setup_photometry(pca_system)

        self.s2p = results.spec2phot

        # stellar mass to light ratio
        self.ml0 = results.cubechannel('ML{}'.format(mlband), 0)
        self.badpdf = results.cubechannel('GOODFRAC', 2) < 1.0e-4
        self.ml_mask = np.logical_or.reduce((self.results.mask, self.badpdf))

        # infer values in interior spaxels affected by one of the following:
        # bad PDF, foreground star, dead fiber
        self.low_or_no_cov = m.mask_from_maskbits(
            self.drp['MASK'].data, [0, 1]).mean(axis=0) > .3
        self.drp3dmask_interior = m.mask_from_maskbits(
            self.drp['MASK'].data, [2, 3]).mean(axis=0) > .3
        self.interior_mask = np.logical_or.reduce((self.badpdf, self.drp3dmask_interior))

        self.logml_final = infer_masked(
            q_trn=self.ml0, bad_trn=self.ml_mask,
            infer_here=self.interior_mask) * u.dex(m.m_to_l_unit)
Esempio n. 4
0
def make_missing_mass_fig(tab, mltype='ring', mlb='i', cb1='g', cb2='r'):
    '''figure with comparison between aperture correction two M/L
    
    Parameters
    ----------
    tab : astropy.table.Table
        full aggregation results table
    mltype : {str}
        'ring' or 'cmlr', the M/L applied to the ouside flux
        (the default is 'ring')
    mlb : {str}, optional
        bandpass for mass-to-light ratio
        (the default is 'i')
    cb1 : {str}, optional
        bluer bandpass for color (the default is 'g', SDSS g band)
    cb2 : {str}, optional
        redder bandpass for color (the default is 'r', SDSS r band)
    '''
    cb1_nsa_mag = tab[f'mag_nsa_{cb1}']
    cb2_nsa_mag = tab[f'mag_nsa_{cb2}']

    broadband_color = cb1_nsa_mag - cb2_nsa_mag
    outermass = (tab[f'logsollum_outer_{mlb}'] + tab[f'outerml_{mltype}']).to(
        u.Msun)

    outermass_frac = outermass / (
        tab['mass_in_ifu'].to(u.Msun) + outermass.to(u.Msun))

    valid = np.isfinite(tab['outerml_{}'.format(mltype)])

    primarysample = m.mask_from_maskbits(tab['mngtarg1'], [10])
    secondarysample = m.mask_from_maskbits(tab['mngtarg1'], [11])

    fig, main_ax, hist_ax = make_panel_hist(top=0.875)

    for selection, label, marker, color in zip(
        [primarysample, secondarysample], ['Primary+', 'Secondary'],
        ['o', 'D'], ['r', 'b']):
    
        main_ax.scatter(
            x=broadband_color[selection * valid], y=outermass_frac[selection * valid],
            c=color, edgecolor='None', s=3., marker=marker, label=label,
            alpha=0.5)

        hist_ax.hist(outermass_frac[selection * valid], color=color, density=True, bins='auto',
                     histtype='step', orientation='horizontal', linewidth=0.75)

    main_ax.set_xlim([0.1, 0.9])

    main_ax.legend(loc='best', prop={'size': 'xx-small'})
    main_ax.tick_params(labelsize='xx-small')
    main_ax.set_xlabel(r'${}-{}$'.format(cb1, cb2), size='x-small')
    main_ax.set_ylabel('Stellar-mass fraction outside IFU', size='x-small')
    fig.suptitle('Inferred mass fraction outside IFU', size='small')
    fig.savefig(os.path.join(csp_basedir, 'lib_diags/', f'mass_outside_ifu_{mltype}.png'))
Esempio n. 5
0
def make_missing_flux_fig(tab, mlb='i', cb1='g', cb2='r'):
    '''make figure comparing missing flux for P+ & S samples
    
    Figure shows P+ (red) and S (blue) samples,
    with their integrated color, fraction of bandpass flux outside IFU
    
    Parameters
    ----------
    tab : astropy.table.Table
        full aggregation results table
    mlb : {str}, optional
        bandpass for mass-to-light ratio
        (the default is 'i', which [default_description])
    cb1 : {str}, optional
        bluer bandpass for color (the default is 'g', SDSS g band)
    cb2 : {str}, optional
        redder bandpass for color (the default is 'r', SDSS r band)
    '''

    cb1_nsa_mag = tab[f'mag_nsa_{cb1}']
    cb2_nsa_mag = tab[f'mag_nsa_{cb2}']

    broadband_color = cb1_nsa_mag - cb2_nsa_mag
    outerlum_frac = tab[f'flux_outer_{mlb}'] / tab[f'flux_nsa_{mlb}']

    primarysample = m.mask_from_maskbits(tab['mngtarg1'], [10])
    secondarysample = m.mask_from_maskbits(tab['mngtarg1'], [11])

    fig, main_ax, hist_ax = make_panel_hist(top=0.875)

    for selection, label, marker, color in zip(
        [primarysample, secondarysample], ['Primary+', 'Secondary'],
        ['o', 'D'], ['r', 'b']):
    
        main_ax.scatter(
            x=broadband_color[selection], y=outerlum_frac[selection],
            c=color, edgecolor='None', s=3., marker=marker, label=label,
            alpha=0.5)

        hist_ax.hist(outerlum_frac[selection], color=color, density=True, bins='auto',
                     histtype='step', orientation='horizontal', linewidth=0.75)

    main_ax.set_xlim([0.1, 0.9])

    main_ax.legend(loc='best', prop={'size': 'xx-small'})
    main_ax.tick_params(labelsize='xx-small')
    main_ax.set_xlabel(r'${}-{}$'.format(cb1, cb2), size='x-small')
    main_ax.set_ylabel('Flux fraction outside IFU', size='x-small')
    fig.suptitle('Flux fraction outside IFU', size='small')
    fig.savefig(os.path.join(csp_basedir, 'lib_diags/', 'flux_outside_ifu.png'))
Esempio n. 6
0
def get_emline_qty(maps, qty, key, sn_th=3., maskbits=list(range(64))):
    '''
    return a masked array for a particular emission-line
    '''

    qty = qty.upper()
    qty_extname = 'EMLINE_{}'.format(qty)
    qty_ivar_extname = 'EMLINE_{}_IVAR'.format(qty)
    qty_mask_extname = 'EMLINE_{}_MASK'.format(qty)

    qty_hdu = maps[qty_extname]
    qty_ivar_hdu = maps[qty_ivar_extname]
    qty_mask_hdu = maps[qty_mask_extname]

    # get a mapping from eline key to channel key
    v2k = {v: k for (k, v) in qty_hdu.header.items()}
    # get a mapping from channel key to channel
    cstring2ix = lambda s: int(s[1:]) - 1

    ix = cstring2ix(v2k[key])

    meas = qty_hdu.data[ix, ...]
    ivar = qty_ivar_hdu.data[ix, ...]
    snr = meas * np.sqrt(ivar)
    snr_mask = (snr < sn_th)

    map_mask = m.mask_from_maskbits(qty_mask_hdu.data[ix, ...])
    mask = np.logical_or.reduce((snr_mask, map_mask))

    return np.ma.array(meas, mask=mask)
Esempio n. 7
0
def fit_dlogM_mw(tab, sfrsd_tab, mltype='ring', mlb='i'):
    merge_tab = t.join(tab, sfrsd_tab, 'plateifu')
    is_agn = m.mask_from_maskbits(merge_tab['mngtarg3'], [1, 2, 3, 4])

    mlb_ix = totalmass.StellarMass.bands_ixs[mlb]
    absmag_sun_mlb = totalmass.StellarMass.absmag_sun[mlb_ix]

    logmass_in_ifu = merge_tab['mass_in_ifu'].to(u.dex(u.Msun))
    logmass_in_ifu_lw = merge_tab['ml_fluxwt'] + merge_tab['ifu_absmag'][:, mlb_ix].to(
        u.dex(m.bandpass_sol_l_unit), totalmass.bandpass_flux_to_solarunits(absmag_sun_mlb))
    merge_tab['dlogmass_lw'] = logmass_in_ifu - logmass_in_ifu_lw
    ha_corr = np.exp(merge_tab['mean_atten_mwtd'] * (6563 / 5500)**-1.3)
    sfrsd = merge_tab['sigma_sfr'] * ha_corr * u.Msun / u.yr / u.pc**2
    mass_pca = merge_tab['mass_in_ifu'] + merge_tab['outer_mass_{}'.format(mltype)]
    ssfrsd = sfrsd / mass_pca
    merge_tab['log_ssfrsd'] = ssfrsd.to(u.dex(ssfrsd.unit))
    merge_tab['log_ssfrsd'][~np.isfinite(merge_tab['log_ssfrsd'])] = np.nan * merge_tab['log_ssfrsd'].unit

    ols = OLS(
        endog=np.array(merge_tab['dlogmass_lw'][~is_agn]),
        exog=sm_add_constant(
            t.Table(merge_tab['mean_atten_mwtd', 'std_atten_mwtd', 'log_ssfrsd'])[~is_agn].to_pandas(),
            prepend=False),
        hasconst=True, missing='drop')

    olsfit = ols.fit()

    return olsfit
Esempio n. 8
0
def fit_dlogM_mw(tab, sfrsd_tab, mltype='ring', mlb='i'):
    merge_tab = t.join(tab, sfrsd_tab, 'plateifu')
    is_agn = m.mask_from_maskbits(merge_tab['mngtarg3'], [1, 2, 3, 4])

    mlb_ix = totalmass.StellarMass.bands_ixs[mlb]
    absmag_sun_mlb = totalmass.StellarMass.absmag_sun[mlb_ix]

    logmass_in_ifu = merge_tab['mass_in_ifu'].to(u.dex(u.Msun))
    logmass_in_ifu_lw = merge_tab['ml_fluxwt'] + merge_tab[f'logsollum_in_ifu_{mlb}']
    merge_tab['dlogmass_lw'] = logmass_in_ifu - logmass_in_ifu_lw
    std_atten_mwtd = merge_tab['std_atten_mwtd']
    mean_atten_mwtd = merge_tab['mean_atten_mwtd']
    ha_corr = np.exp(merge_tab['mean_atten_mwtd'] * (6563 / 5500)**-1.3)
    sfrsd = merge_tab['sigma_sfr'] * ha_corr * u.Msun / u.yr / u.pc**2
    outer_mass = (merge_tab[f'outerml_{mltype}'] + \
                  merge_tab[f'logsollum_outer_{mlb}']).to(u.Msun)
    mass_pca = merge_tab['mass_in_ifu'].to(u.Msun) + outer_mass
    ssfrsd = sfrsd / mass_pca
    merge_tab['log_ssfrsd'] = ssfrsd.to(u.dex(ssfrsd.unit))
    merge_tab['log_ssfrsd'][~np.isfinite(merge_tab['log_ssfrsd'])] = np.nan * merge_tab['log_ssfrsd'].unit

    ols = OLS(
        endog=np.array(merge_tab['dlogmass_lw'][~is_agn]),
        exog=sm_add_constant(
            t.Table(merge_tab['mean_atten_mwtd', 'std_atten_mwtd', 'log_ssfrsd'])[~is_agn].to_pandas(),
            prepend=False),
        hasconst=True, missing='drop')

    olsfit = ols.fit()

    return olsfit
Esempio n. 9
0
    def __init__(self, drpall):
        sky_ifus = drpall[np.where(
            m.mask_from_maskbits(drpall['mngtarg2'], [1]))[0]]

        flux, ivar, lam = zip(
            *[self.get_ifu_sky_spectra(row) for row in sky_ifus])
        self.flux, self.ivar = np.row_stack(flux), np.row_stack(ivar)
        self.lam = lam[0]
Esempio n. 10
0
 def get_ifu_sky_spectra(self, row):
     drp = m.load_drp_logcube(row['plate'], row['ifudsgn'], mpl_v)
     mask = m.mask_from_maskbits(drp['MASK'].data,
                                 [3, 10]).astype(float).mean(axis=0) >= .1
     sp_i, sp_j = np.where(~mask)
     flux = drp['FLUX'].data[:, sp_i, sp_j].T
     ivar = drp['IVAR'].data[:, sp_i, sp_j].T
     lam = drp['WAVE'].data
     drp.close()
     return flux, ivar, lam
Esempio n. 11
0
 def get_ifu_sky_spectra(self, row):
     drp = m.load_drp_logcube(row['plate'], row['ifudsgn'], mpl_v)
     mask = m.mask_from_maskbits(
         drp['MASK'].data, [3, 10]).astype(float).mean(axis=0) >= .1
     sp_i, sp_j = np.where(~mask)
     flux = drp['FLUX'].data[:, sp_i, sp_j].T
     ivar = drp['IVAR'].data[:, sp_i, sp_j].T
     lam = drp['WAVE'].data
     drp.close()
     return flux, ivar, lam
Esempio n. 12
0
def compare_missing_mass(tab, mlb='i', cb1='g', cb2='r'):
    mlb_ix = totalmass.StellarMass.bands_ixs[mlb]
    cb1_ix = totalmass.StellarMass.bands_ixs[cb1]
    cb2_ix = totalmass.StellarMass.bands_ixs[cb2]
    absmag_sun_mlb = totalmass.StellarMass.absmag_sun[mlb_ix]

    broadband_color = (tab['nsa_absmag'][:, cb1_ix] - tab['nsa_absmag'][:, cb2_ix])
    outerlum_frac = tab['outer_lum'][:, mlb_ix].to(m.bandpass_sol_l_unit) / \
                    tab['nsa_absmag'][:, mlb_ix].to(m.bandpass_sol_l_unit, 
                        totalmass.bandpass_flux_to_solarunits(absmag_sun_mlb))
    dlogmass_cmlr_ring = ((tab['mass_in_ifu'] + tab['outer_mass_cmlr']).to(u.dex(u.Msun)) - \
                          (tab['mass_in_ifu'] + tab['outer_mass_ring']).to(u.dex(u.Msun)))

    primarysample = m.mask_from_maskbits(tab['mngtarg1'], [10])
    secondarysample = m.mask_from_maskbits(tab['mngtarg1'], [11])

    fig, main_ax, hist_ax = make_panel_hist(top=0.9, left=.225)

    valid = np.isfinite(dlogmass_cmlr_ring)

    for selection, label, marker, color in zip(
        [primarysample, secondarysample], ['Primary', 'Secondary'],
        ['o', 'D'], ['r', 'b']):
    
        main_ax.scatter(
            x=broadband_color[selection * valid], y=dlogmass_cmlr_ring[selection * valid],
            c=color, edgecolor='None', s=5., marker=marker, label=label)

        hist_ax.hist(dlogmass_cmlr_ring[selection * valid], color=color, density=True, bins='auto',
                     histtype='step', orientation='horizontal', linewidth=0.75)

    main_ax.set_xlim(np.percentile(broadband_color[valid], [1., 99.]))
    main_ax.set_ylim(np.percentile(dlogmass_cmlr_ring[valid], [1., 99.]))

    main_ax.legend(loc='best', prop={'size': 'xx-small'})
    main_ax.tick_params(labelsize='xx-small')
    main_ax.set_xlabel(r'${}-{}$'.format(cb1, cb2), size='x-small')
    main_ax.set_ylabel(r'$\log \frac{M^{\rm tot}_{\rm CMLR}}{M^{\rm tot}_{\rm ring}}$',
                  size='x-small')
    fig.suptitle(r'Impact of aperture-correction on $M^{\rm tot}$', size='small')
    fig.savefig(os.path.join(basedir, 'lib_diags/', 'mtot_compare_cmlr_ring.png'))
Esempio n. 13
0
def compare_outerml_ring_cmlr(tab, mlb='i', cb1='g', cb2='r'):
    mlb_ix = totalmass.StellarMass.bands_ixs[mlb]
    cb1_ix = totalmass.StellarMass.bands_ixs[cb1]
    cb2_ix = totalmass.StellarMass.bands_ixs[cb2]
    absmag_sun_mlb = totalmass.StellarMass.absmag_sun[mlb_ix]

    broadband_color = (tab['nsa_absmag'][:, cb1_ix] - tab['nsa_absmag'][:, cb2_ix])
    ml_cmlr_ring = tab['outer_ml_cmlr'] - tab['outer_ml_ring']
    ifu_lum = tab['ifu_absmag'][:, mlb_ix].to(
        m.bandpass_sol_l_unit, totalmass.bandpass_flux_to_solarunits(absmag_sun_mlb))
    outer_lum = tab['outer_lum'][:, mlb_ix].to(m.bandpass_sol_l_unit)
    total_lum = tab['nsa_absmag'][:, mlb_ix].to(
        m.bandpass_sol_l_unit, totalmass.bandpass_flux_to_solarunits(absmag_sun_mlb))
    lum_frac_outer = outer_lum / total_lum

    valid = np.isfinite(tab['outer_ml_cmlr'])

    primarysample = m.mask_from_maskbits(tab['mngtarg1'], [10])
    secondarysample = m.mask_from_maskbits(tab['mngtarg1'], [11])

    fig, main_ax, hist_ax = make_panel_hist(top=0.875)

    for selection, label, marker, color in zip(
        [primarysample, secondarysample], ['Primary+', 'Secondary'],
        ['o', 'D'], ['r', 'b']):
        
        main_ax.scatter(x=broadband_color[selection * valid], y=ml_cmlr_ring[selection * valid],
                       c=color, marker=marker, s=8. * lum_frac_outer[selection * valid],
                       edgecolor='None', label=label)

        hist_ax.hist(ml_cmlr_ring[selection * valid], color=color, density=True, bins='auto',
                     histtype='step', orientation='horizontal', linewidth=0.75)

    main_ax.legend(loc='best', prop={'size': 'xx-small'})
    main_ax.tick_params(labelsize='xx-small')
    main_ax.set_xlabel(r'${}-{}$'.format(cb1, cb2), size='x-small')
    main_ax.set_ylabel(r'$\log{\frac{\Upsilon^*_{\rm CMLR}}{\Upsilon^*_{\rm ring}}}$',
                       size='x-small')
    main_ax.set_ylim(np.percentile(ml_cmlr_ring[valid], [1., 99.]))
    fig.suptitle(r'$\Upsilon^*_{\rm CMLR}$ vs $\Upsilon^*_{\rm ring}$', size='small')
    fig.savefig(os.path.join(basedir, 'lib_diags/', 'outer_ml.png'))
Esempio n. 14
0
    def __init__(self,
                 drp_hdulist,
                 dap_hdulist,
                 drpall_row,
                 max_vel_unc=500. * u.Unit('km/s'),
                 drp_dlogl=None):
        self.drp_hdulist = drp_hdulist
        self.dap_hdulist = dap_hdulist
        self.drpall_row = drpall_row
        self.plateifu = self.drp_hdulist[0].header['PLATEIFU']

        self.vel = dap_hdulist['STELLAR_VEL'].data * u.Unit('km/s')
        self.vel_ivar = dap_hdulist['STELLAR_VEL_IVAR'].data * u.Unit('km-2s2')

        self.z = drpall_row['nsa_z']

        # mask all the spaxels that have high stellar velocity uncertainty
        self.vel_ivar_mask = (1. / np.sqrt(self.vel_ivar)) > max_vel_unc
        self.vel_mask = m.mask_from_maskbits(
            self.dap_hdulist['STELLAR_VEL_MASK'].data, [30])

        self.drp_l = drp_hdulist['WAVE'].data
        self.drp_logl = np.log10(self.drp_l)
        if drp_dlogl is None:
            drp_dlogl = ut.determine_dlogl(self.drp_logl)
        self.drp_dlogl = drp_dlogl

        flux_hdu, ivar_hdu, l_hdu = (drp_hdulist['FLUX'], drp_hdulist['IVAR'],
                                     drp_hdulist['WAVE'])

        self.flux = flux_hdu.data
        self.ivar = ivar_hdu.data

        self.units = {'l': u.AA, 'flux': u.Unit('1e-17 erg s-1 cm-2 AA-1')}

        self.S2P = Spec2Phot(lam=(self.drp_l * self.units['l']),
                             flam=(self.flux * self.units['flux']))

        self.DONOTUSE = m.mask_from_maskbits(drp_hdulist['MASK'].data, [10])

        self.ivar *= ~self.DONOTUSE
Esempio n. 15
0
    def __init__(self,
                 results,
                 pca_system,
                 drp,
                 dap,
                 drpall_row,
                 cosmo,
                 mlband='i'):
        self.results = results
        self.pca_system = pca_system
        self.drp = drp
        self.dap = dap
        self.drpall_row = drpall_row
        self.cosmo = cosmo
        self.mlband = mlband

        with catch_warnings():
            simplefilter('ignore')
            self.results.setup_photometry(pca_system)

        self.s2p = results.spec2phot

        # stellar mass to light ratio
        self.ml0 = results.cubechannel('ML{}'.format(mlband), 0)
        self.badpdf = results.cubechannel('GOODFRAC', 2) < 1.0e-4
        self.ml_mask = np.logical_or.reduce((self.results.mask, self.badpdf))

        # infer values in interior spaxels affected by one of the following:
        # bad PDF, foreground star, dead fiber
        self.low_or_no_cov = m.mask_from_maskbits(self.drp['MASK'].data,
                                                  [0, 1]).mean(axis=0) > .3
        self.drp3dmask_interior = m.mask_from_maskbits(
            self.drp['MASK'].data, [2, 3]).mean(axis=0) > .3
        self.interior_mask = np.logical_or.reduce(
            (self.badpdf, self.drp3dmask_interior))

        self.logml_final = infer_masked(q_trn=self.ml0,
                                        bad_trn=self.ml_mask,
                                        infer_here=self.interior_mask) * u.dex(
                                            m.m_to_l_unit)
Esempio n. 16
0
    def __init__(self, drp_hdulist, dap_hdulist, drpall_row,
                 max_vel_unc=500. * u.Unit('km/s'), drp_dlogl=None):
        self.drp_hdulist = drp_hdulist
        self.dap_hdulist = dap_hdulist
        self.drpall_row = drpall_row
        self.plateifu = self.drp_hdulist[0].header['PLATEIFU']

        self.vel = dap_hdulist['STELLAR_VEL'].data * u.Unit('km/s')
        self.vel_ivar = dap_hdulist['STELLAR_VEL_IVAR'].data * u.Unit(
            'km-2s2')

        self.z = drpall_row['nsa_z']

        # mask all the spaxels that have high stellar velocity uncertainty
        self.vel_ivar_mask = (1. / np.sqrt(self.vel_ivar)) > max_vel_unc
        self.vel_mask = m.mask_from_maskbits(
            self.dap_hdulist['STELLAR_VEL_MASK'].data, [30])

        self.drp_l = drp_hdulist['WAVE'].data
        self.drp_logl = np.log10(self.drp_l)
        if drp_dlogl is None:
            drp_dlogl = ut.determine_dlogl(self.drp_logl)
        self.drp_dlogl = drp_dlogl

        flux_hdu, ivar_hdu, l_hdu = (drp_hdulist['FLUX'], drp_hdulist['IVAR'],
                                     drp_hdulist['WAVE'])

        self.flux = flux_hdu.data
        self.ivar = ivar_hdu.data

        self.units = {'l': u.AA, 'flux': u.Unit('1e-17 erg s-1 cm-2 AA-1')}

        self.S2P = Spec2Phot(lam=(self.drp_l * self.units['l']),
                             flam=(self.flux * self.units['flux']))

        self.DONOTUSE = m.mask_from_maskbits(drp_hdulist['MASK'].data, [10])

        self.ivar *= ~self.DONOTUSE
Esempio n. 17
0
    def get_qty(self, qty, key, sn_th, maskbits=[30]):
        maps = self.hdulist
        qty = qty.upper()
        qty_extname = 'EMLINE_{}'.format(qty)
        qty_ivar_extname = 'EMLINE_{}_IVAR'.format(qty)
        qty_mask_extname = 'EMLINE_{}_MASK'.format(qty)

        qty_hdu = maps[qty_extname]
        qty_ivar_hdu = maps[qty_ivar_extname]
        qty_mask_hdu = maps[qty_mask_extname]

        # get a mapping from eline key to channel key
        v2k = {v: k for (k, v) in qty_hdu.header.items()}
        # get a mapping from channel key to channel
        cstring2ix = lambda s: int(s[1:]) - 1

        ix = cstring2ix(v2k[key])

        meas = qty_hdu.data[ix, ...]
        ivar = qty_ivar_hdu.data[ix, ...]
        ivar_zero = (ivar == 0.)
        std = 1. / np.sqrt(ivar.clip(min=1.0e-20))
        std[ivar_zero] = 0.

        snr_mask = ((meas * np.sqrt(ivar)) < sn_th)

        map_mask = m.mask_from_maskbits(qty_mask_hdu.data[ix, ...])
        mask = np.logical_or.reduce((ivar_zero, map_mask, snr_mask))

        unit = self.units[qty]

        data = nddata.NDDataRef(
            meas, uncertainty=nddata.StdDevUncertainty(std, unit=unit),
            unit=unit, mask=mask, wcs=wcs)

        return data
Esempio n. 18
0
    def __init__(self, drpall):
        sky_ifus = drpall[np.where(m.mask_from_maskbits(drpall['mngtarg2'], [1]))[0]]

        flux, ivar, lam = zip(*[self.get_ifu_sky_spectra(row) for row in sky_ifus])
        self.flux, self.ivar = np.row_stack(flux), np.row_stack(ivar)
        self.lam = lam[0]
Esempio n. 19
0
    def __init__(self, lam_model, spec_model, meta_model,
                 row, drp_base, dap_base, plateifu_base, model_ix,
                 Kspec_obs=None, sky=None):
        '''
        create mocks of DRP LOGCUBE and DAP MAPS

        1. characterize SNR of observed data
        2. redshift model to observed-frame
        3. attenuate according to MW reddening law
        4. blur according to instrumental dispersion
        5. resample onto rectified (observed) wavelength grid
        6. add noise from full covariance prescription OR from SNR
        7. scale according to r-band surface brightness
        8. mask where there's no flux
        '''

        self.model_ix = model_ix

        flux_obs = drp_base['FLUX'].data
        ivar_obs = drp_base['IVAR'].data
        lam_obs = drp_base['WAVE'].data
        specres_obs = drp_base['SPECRES'].data

        cubeshape = drp_base['FLUX'].data.shape
        nl_obs, *mapshape = cubeshape
        mapshape = tuple(mapshape)

        '''STEP 1'''
        # find SNR of each pixel in cube (used to scale noise later)
        snrcube_obs, rmsmap_obs = compute_snrcube(
            flux=flux_obs, ivar=ivar_obs,
            filtersize_l=15, return_rms_map=True)

        '''STEP 2'''
        # compute the redshift map
        z_cosm = row['nsa_zdist']
        z_pec = (dap_base['STELLAR_VEL'].data * u.Unit('km/s') / c.c).to('').value
        z_obs = (1. + z_cosm) * (1. + z_pec) - 1.

        # create a placeholder model cube since flexible broadcasting is hard
        if specmodel.ndim == 3:
            spec_model_cube = specmodel
        else:
            spec_model_cube = np.tile(spec_model[:, None, None], (1, ) + mapshape)
        ivar_model_cube = np.ones_like(spec_model_cube)
        lam_model_z, spec_model_z, ivar_model_z = ut.redshift(
            l=lam_model, f=spec_model_cube, ivar=ivar_model_cube,
            z_in=0., z_out=z_obs)

        '''STEP 3'''
        # figure out attenuation
        # there are issues with extinction library's handling of multidim arrays
        # so we'll interpolate
        atten_l = np.linspace(3000., 20000., 10000)
        r_v = 3.1
        ext_mag_interp = interp1d(
            x=atten_l,
            y=extinction.fitzpatrick99(
                atten_l, r_v=r_v, a_v=drp_base[0].header['EBVGAL'] * r_v),
            fill_value='extrapolate', bounds_error=False)
        ext_mag = ext_mag_interp(lam_model_z)
        atten_factor = 2.5**-ext_mag
        spec_model_mwred = spec_model_z * atten_factor
        ivar_model_mwred = ivar_model_z / atten_factor**2.

        '''STEP 4'''
        # specres of observed cube at model wavelengths
        spec_model_instblur = ut.blur_cube_to_psf(
            l_ref=drp_base['WAVE'].data, specres_ref=drp_base['SPECRES'].data,
            l_eval=lam_model_z, spec_unblurred=spec_model_mwred)

        ivar_model_instblur = ivar_model_mwred

        '''STEP 5'''
        # create placeholder arrays for ivar and flux
        final_fluxcube = np.empty(cubeshape)

        # wavelength grid for final cube
        l_grid = drp_base['WAVE'].data

        # populate flam and ivar pixel-by-pixel
        for ind in np.ndindex(mapshape):
            final_fluxcube[:, ind[0], ind[1]] = np.interp(
                xp=lam_model_z[:, ind[0], ind[1]],
                fp=spec_model_instblur[:, ind[0], ind[1]],
                x=l_grid)
        # normalize each spectrum to mean 1
        final_fluxcube /= np.mean(final_fluxcube, axis=0, keepdims=True)

        '''STEP 6'''
        # spectrophotometric noise
        cov_noise = noisify_cov(Kspec_obs, mapshape=mapshape)
        # random noise: signal * (gauss / snr)
        random_noise = np.random.randn(*cubeshape) / (snrcube_obs + 1.0e-6)
        fluxscaled_random_noise = random_noise * final_fluxcube

        final_fluxcube += (cov_noise + fluxscaled_random_noise)

        '''STEP 7'''
        # normalize everything to have the same observed-frame r-band flux
        u_flam = 1.0e-17 * (u.erg / (u.s * u.cm**2 * u.AA))
        rband_drp = Spec2Phot(
            lam=drp_base['WAVE'].data,
            flam=drp_base['FLUX'].data * u_flam).ABmags['sdss2010-r'] * u.ABmag
        rband_drp[~np.isfinite(rband_drp)] = rband_drp[np.isfinite(rband_drp)].max()
        rband_model = Spec2Phot(
            lam=drp_base['WAVE'].data,
            flam=final_fluxcube * u_flam).ABmags['sdss2010-r'] * u.ABmag
        rband_model[~np.isfinite(rband_model)] = rband_model[np.isfinite(rband_model)].max()
        # flux ratio map
        r = (rband_drp.to(m.Mgy) / rband_model.to(m.Mgy)).value

        final_fluxcube *= r[None, ...]
        # initialize the ivar cube according to the SNR cube
        # of base observations
        # this is because while we think we know the actual spectral covariance,
        # that is not necessarily reflected in the quoted ivars!!!
        final_ivarcube = (snrcube_obs / final_fluxcube)**2.

        # add sky spectrum
        if sky:
            skyfluxs, skyivars = sky.make_skycube(mapshape)
            final_fluxcube = final_fluxcube + skyfluxs
            #final_ivarcube = 1. / (1. / final_ivarcube + 1. / skyivars)


        '''STEP 8'''
        # mask where the native datacube has no signal
        rimg = drp_base['RIMG'].data
        nosignal = (rimg == 0.)[None, ...]
        nosignal_cube = np.broadcast_to(nosignal, final_fluxcube.shape)
        final_fluxcube[nosignal_cube] = 0.
        final_ivarcube[final_fluxcube == 0.] = 0.

        # mask where there's bad velocity info
        badvel = m.mask_from_maskbits(
            dap_base['STELLAR_VEL_MASK'].data, [30])[None, ...]
        final_ivarcube[np.tile(badvel, (nl_obs, 1, 1))] = 0.

        # replace infinite flux elements with median-filtered
        flux_is_inf = ~np.isfinite(final_fluxcube)
        final_fluxcube[flux_is_inf] = medfilt(
            np.nan_to_num(final_fluxcube), [11, 1, 1])[flux_is_inf]

        self.dap_base = dap_base
        self.drp_base = drp_base
        self.fluxcube = final_fluxcube
        self.fluxcube_ivar = final_ivarcube
        self.row = row
        self.metadata = meta_model

        self.plateifu_base = plateifu_base
Esempio n. 20
0
    def __init__(self,
                 lam_model,
                 spec_model,
                 meta_model,
                 row,
                 drp_base,
                 dap_base,
                 plateifu_base,
                 model_ix,
                 Kspec_obs=None,
                 sky=None):
        '''
        create mocks of DRP LOGCUBE and DAP MAPS

        1. characterize SNR of observed data
        2. redshift model to observed-frame
        3. attenuate according to MW reddening law
        4. blur according to instrumental dispersion
        5. resample onto rectified (observed) wavelength grid
        6. add noise from full covariance prescription OR from SNR
        7. scale according to r-band surface brightness
        8. mask where there's no flux
        '''

        self.model_ix = model_ix

        flux_obs = drp_base['FLUX'].data
        ivar_obs = drp_base['IVAR'].data
        lam_obs = drp_base['WAVE'].data
        specres_obs = drp_base['SPECRES'].data

        cubeshape = drp_base['FLUX'].data.shape
        nl_obs, *mapshape = cubeshape
        mapshape = tuple(mapshape)
        '''STEP 1'''
        # find SNR of each pixel in cube (used to scale noise later)
        snrcube_obs, rmsmap_obs = compute_snrcube(flux=flux_obs,
                                                  ivar=ivar_obs,
                                                  filtersize_l=15,
                                                  return_rms_map=True)
        '''STEP 2'''
        # compute the redshift map
        z_cosm = row['nsa_zdist']
        z_pec = (dap_base['STELLAR_VEL'].data * u.Unit('km/s') /
                 c.c).to('').value
        z_obs = (1. + z_cosm) * (1. + z_pec) - 1.

        # create a placeholder model cube since flexible broadcasting is hard
        if specmodel.ndim == 3:
            spec_model_cube = specmodel
        else:
            spec_model_cube = np.tile(spec_model[:, None, None],
                                      (1, ) + mapshape)
        ivar_model_cube = np.ones_like(spec_model_cube)
        lam_model_z, spec_model_z, ivar_model_z = ut.redshift(
            l=lam_model,
            f=spec_model_cube,
            ivar=ivar_model_cube,
            z_in=0.,
            z_out=z_obs)
        '''STEP 3'''
        # figure out attenuation
        # there are issues with extinction library's handling of multidim arrays
        # so we'll interpolate
        atten_l = np.linspace(3000., 20000., 10000)
        r_v = 3.1
        ext_mag_interp = interp1d(x=atten_l,
                                  y=extinction.fitzpatrick99(
                                      atten_l,
                                      r_v=r_v,
                                      a_v=drp_base[0].header['EBVGAL'] * r_v),
                                  fill_value='extrapolate',
                                  bounds_error=False)
        ext_mag = ext_mag_interp(lam_model_z)
        atten_factor = 2.5**-ext_mag
        spec_model_mwred = spec_model_z * atten_factor
        ivar_model_mwred = ivar_model_z / atten_factor**2.
        '''STEP 4'''
        # specres of observed cube at model wavelengths
        spec_model_instblur = ut.blur_cube_to_psf(
            l_ref=drp_base['WAVE'].data,
            specres_ref=drp_base['SPECRES'].data,
            l_eval=lam_model_z,
            spec_unblurred=spec_model_mwred)

        ivar_model_instblur = ivar_model_mwred
        '''STEP 5'''
        # create placeholder arrays for ivar and flux
        final_fluxcube = np.empty(cubeshape)

        # wavelength grid for final cube
        l_grid = drp_base['WAVE'].data

        # populate flam and ivar pixel-by-pixel
        for ind in np.ndindex(mapshape):
            final_fluxcube[:, ind[0],
                           ind[1]] = np.interp(xp=lam_model_z[:, ind[0],
                                                              ind[1]],
                                               fp=spec_model_instblur[:,
                                                                      ind[0],
                                                                      ind[1]],
                                               x=l_grid)
        # normalize each spectrum to mean 1
        final_fluxcube /= np.mean(final_fluxcube, axis=0, keepdims=True)
        '''STEP 6'''
        # spectrophotometric noise
        cov_noise = noisify_cov(Kspec_obs, mapshape=mapshape)
        # random noise: signal * (gauss / snr)
        random_noise = np.random.randn(*cubeshape) / (snrcube_obs + 1.0e-6)
        fluxscaled_random_noise = random_noise * final_fluxcube

        final_fluxcube += (cov_noise + fluxscaled_random_noise)
        '''STEP 7'''
        # normalize everything to have the same observed-frame r-band flux
        u_flam = 1.0e-17 * (u.erg / (u.s * u.cm**2 * u.AA))
        rband_drp = Spec2Phot(
            lam=drp_base['WAVE'].data,
            flam=drp_base['FLUX'].data * u_flam).ABmags['sdss2010-r'] * u.ABmag
        rband_drp[~np.isfinite(rband_drp)] = rband_drp[np.isfinite(
            rband_drp)].max()
        rband_model = Spec2Phot(
            lam=drp_base['WAVE'].data,
            flam=final_fluxcube * u_flam).ABmags['sdss2010-r'] * u.ABmag
        rband_model[~np.isfinite(rband_model)] = rband_model[np.isfinite(
            rband_model)].max()
        # flux ratio map
        r = (rband_drp.to(m.Mgy) / rband_model.to(m.Mgy)).value

        final_fluxcube *= r[None, ...]
        # initialize the ivar cube according to the SNR cube
        # of base observations
        # this is because while we think we know the actual spectral covariance,
        # that is not necessarily reflected in the quoted ivars!!!
        final_ivarcube = (snrcube_obs / final_fluxcube)**2.

        # add sky spectrum
        if sky:
            skyfluxs, skyivars = sky.make_skycube(mapshape)
            final_fluxcube = final_fluxcube + skyfluxs
            #final_ivarcube = 1. / (1. / final_ivarcube + 1. / skyivars)
        '''STEP 8'''
        # mask where the native datacube has no signal
        rimg = drp_base['RIMG'].data
        nosignal = (rimg == 0.)[None, ...]
        nosignal_cube = np.broadcast_to(nosignal, final_fluxcube.shape)
        final_fluxcube[nosignal_cube] = 0.
        final_ivarcube[final_fluxcube == 0.] = 0.

        # mask where there's bad velocity info
        badvel = m.mask_from_maskbits(dap_base['STELLAR_VEL_MASK'].data,
                                      [30])[None, ...]
        final_ivarcube[np.tile(badvel, (nl_obs, 1, 1))] = 0.

        # replace infinite flux elements with median-filtered
        flux_is_inf = ~np.isfinite(final_fluxcube)
        final_fluxcube[flux_is_inf] = medfilt(np.nan_to_num(final_fluxcube),
                                              [11, 1, 1])[flux_is_inf]

        self.dap_base = dap_base
        self.drp_base = drp_base
        self.fluxcube = final_fluxcube
        self.fluxcube_ivar = final_ivarcube
        self.row = row
        self.metadata = meta_model

        self.plateifu_base = plateifu_base
Esempio n. 21
0
def compare_outerml_ring_cmlr(tab, mlb='i', cb1='g', cb2='r'):
    '''figure with comparison between aperture correction two M/L
    
    Parameters
    ----------
    tab : astropy.table.Table
        full aggregation results table
    mlb : {str}, optional
        bandpass for mass-to-light ratio
        (the default is 'i', which [default_description])
    cb1 : {str}, optional
        bluer bandpass for color (the default is 'g', SDSS g band)
    cb2 : {str}, optional
        redder bandpass for color (the default is 'r', SDSS r band)
    '''

    cb1_nsa_mag = tab[f'mag_nsa_{cb1}']
    cb2_nsa_mag = tab[f'mag_nsa_{cb2}']

    broadband_color = cb1_nsa_mag - cb2_nsa_mag
    ml_cmlr_ring = tab['outerml_diff']
    lum_frac_outer = tab[f'flux_outer_{mlb}'] / tab[f'flux_nsa_{mlb}']

    valid = np.isfinite(tab['outerml_cmlr'])

    primarysample = m.mask_from_maskbits(tab['mngtarg1'], [10])
    secondarysample = m.mask_from_maskbits(tab['mngtarg1'], [11])

    fig, main_ax, hist_ax = make_panel_hist(top=0.875)

    for selection, label, marker, color in zip(
        [primarysample, secondarysample], ['Primary+', 'Secondary'],
        ['o', 'D'], ['r', 'b']):
        
        main_ax.scatter(x=broadband_color[selection * valid], y=ml_cmlr_ring[selection * valid],
                       c=color, marker=marker, s=10. * lum_frac_outer[selection * valid],
                       edgecolor='None', label=label, alpha=0.5)

        hist_ax.hist(ml_cmlr_ring[selection * valid], color=color, density=True, bins='auto',
                     histtype='step', orientation='horizontal', linewidth=0.75)

    main_ax.legend(loc='lower right', prop={'size': 'xx-small'})

    # make point size legend
    legend_lumfracs = np.array([.05, .1, .25, .5])

    sc_pri = [main_ax.scatter(
                  [], [], c='r', marker='o', s=10. * frac, edgecolor='None', alpha=0.5)
              for frac in legend_lumfracs]
    sc_sec = [main_ax.scatter(
                  [], [], c='b', marker='D', s=10. * frac, edgecolor='None', alpha=0.5)
              for frac in legend_lumfracs]

    merged_markers = list(zip(sc_pri, sc_sec))
    merged_labels = [r'{:.0f}\%'.format(frac * 100.) for frac in legend_lumfracs]
    hmap = {tuple: HandlerTuple(ndivide=None)}
    lumfrac_legend = hist_ax.legend(
        list(zip(sc_pri, sc_sec)), merged_labels,
        handler_map=hmap, loc='upper right', prop={'size': 'xx-small'},
        title='\% flux outside IFU', title_fontsize='xx-small')

    main_ax.tick_params(labelsize='xx-small')
    main_ax.set_xlabel(r'${}-{}$'.format(cb1, cb2), size='x-small')
    main_ax.set_ylabel(r'$\log{\frac{\Upsilon^*_{\rm CMLR}}{\Upsilon^*_{\rm ring}}}$',
                       size='x-small')
    main_ax.set_xlim([0.1, 0.9])
    main_ax.set_ylim([-0.5, 0.5])
    fig.suptitle(r'$\Upsilon^*_{\rm CMLR}$ vs $\Upsilon^*_{\rm ring}$', size='small')
    fig.savefig(os.path.join(csp_basedir, 'lib_diags/', 'outer_ml.png'))
Esempio n. 22
0
def overplot_spectroscopic(res,
                           drp_logcube,
                           drpall_row,
                           mass_ax,
                           ml_ax,
                           f_ax,
                           pca_system,
                           res_wcs,
                           cmlr,
                           mlb='i'):
    '''
    overplot cumulative spectroscopic masses, log M/L, cumulative fluxes
    '''

    # synthetic photometry of IFU data in rest frame
    ebvgal = drpall_row['ebvgal']
    r_v = 3.1
    dustcorr = 10.**(0.4 * extinction.fitzpatrick99(
        drp_logcube['WAVE'].data, a_v=r_v * ebvgal, r_v=r_v))[:, None, None]

    ifu_s2p = spectrophot.Spec2Phot(
        lam=drp_logcube['WAVE'].data / (1. + drpall_row['nsa_z']),
        flam=1.0e-17 * drp_logcube['FLUX'].data * (1. + drpall_row['nsa_z']) *
        dustcorr)
    res_flux = (ifu_s2p.ABmags['sdss2010-{}'.format(mlb)] * u.ABmag).to(m.Mgy)

    # map sky coordinates to number of effective radii from center
    pos_to_nRe = RotatedParaboloid(ctr=np.array(
        [drpall_row['objra'], drpall_row['objdec']]),
                                   phi=drpall_row['nsa_elpetro_phi'] * u.deg,
                                   axis_ratio=drpall_row['nsa_elpetro_ba'],
                                   Re=drpall_row['nsa_elpetro_th50_r'] / 3600.)

    badpdf = res.badPDF()
    ml_mask = np.logical_or(res.mask, badpdf)

    # WCS from results file determines where elliptical projection is sampled
    #res_wcs = wcs.WCS(res['SNRMED'].header)
    res_II, res_JJ = np.meshgrid(
        *[np.linspace(0., s - 1., s) for s in res['SNRMED'].shape],
        indexing='ij')
    res_AA, res_DD = res_wcs.wcs_pix2world(res_JJ, res_II, 1)

    # sample Re at spaxel centers
    res_Re = pos_to_nRe(np.column_stack([res_AA.flatten(),
                                         res_DD.flatten()
                                         ])).reshape(res_AA.shape)
    nRe_to_plot = np.linspace(0., res_Re[~ml_mask].max(), 50.)

    # mass, log M/L
    badpdf = res.badPDF()
    ml_mask = np.logical_or.reduce((res.mask, badpdf))
    interior_mask = np.logical_or.reduce(
        (badpdf,
         (m.mask_from_maskbits(drp_logcube['MASK'].data, [3]).sum(axis=0) > 0),
         (m.mask_from_maskbits(drp_logcube['MASK'].data, [2]).sum(axis=0) >
          0)))
    logml = infer_masked(res.param_dist_med(extname='ML{}'.format(mlb)),
                         ml_mask, interior_mask)
    ml = 10.**logml * m.m_to_l_unit
    res_MAG = res_flux.to(u.ABmag) - cosmo.distmod(drpall_row['nsa_zdist'])
    mlb_sollum = 10.**(-0.4 * (res_MAG - spectrophot.absmag_sun_band[mlb] * u.ABmag)).value * \
                 m.bandpass_sol_l_unit
    spectro_mass = (ml * mlb_sollum).to(u.Msun)

    # sum mass within some number of Re
    mass_within_nRe = np.array(
        [sum_within_nRe(spectro_mass, res_Re, n) for n in nRe_to_plot])
    mass_ax.plot(nRe_to_plot, mass_within_nRe, c='C1')

    # plot mass to light versus Re
    ml_sc = ml_ax.scatter(res_Re[~ml_mask],
                          logml[~ml_mask],
                          c='C1',
                          edgecolor='None',
                          s=.5)

    res_Re_m = np.ma.array(res_Re, mask=ml_mask)
    # find ring method log M/L
    outer_ring = np.logical_and((res_Re_m <= res_Re_m.max()),
                                (res_Re_m >= res_Re_m.max() - .5))
    outer_logml_ring = np.median(logml[~ml_mask * outer_ring])
    ml_ax.scatter(x=[np.median(res_Re_m[~ml_mask * outer_ring])],
                  y=[outer_logml_ring],
                  marker='x',
                  c='C1')
    # find CMLR log M/L
    nsa_MAG = (np.array(drpall_row['nsa_elpetro_absmag'][2:]) * \
                        (u.ABmag - u.MagUnit(u.littleh**2))).to(u.ABmag, u.with_H0(cosmo.H0))
    nsa_mag = (nsa_MAG + cosmo.distmod(drpall_row['nsa_zdist']))
    nsa_flux = nsa_mag.to(m.Mgy)
    ifu_mag = np.array(
        [ifu_s2p.ABmags['sdss2010-{}'.format(b_)] for b_ in 'ugriz']) * u.ABmag
    ifu_mag[~np.isfinite(ifu_mag)] = 40. * u.ABmag
    ifu_flux = ifu_mag.to(m.Mgy)
    flux_deficit = nsa_flux - ifu_flux.sum(axis=(1, 2))
    logml_missingflux_cmlr = cmlr(2.5 *
                                  np.log10(flux_deficit[1] / flux_deficit[2]))
    ml_ax.scatter(x=[np.median(res_Re_m[~ml_mask * outer_ring])],
                  y=[logml_missingflux_cmlr],
                  marker='s',
                  c='C1',
                  edgecolor='k')

    #
    ml_missingflux_cmlr = 10.**logml_missingflux_cmlr * m.m_to_l_unit
    ml_missingflux_ring = 10.**outer_logml_ring * m.m_to_l_unit
    missing_mlb_MAG = flux_deficit[3].to(u.ABmag) - cosmo.distmod(
        drpall_row['nsa_zdist'])
    missing_mlb_sollum = 10.**(-0.4 * (missing_mlb_MAG - spectrophot.absmag_sun_band[mlb] * u.ABmag)).value * \
        m.bandpass_sol_l_unit
    missing_mass_cmlr = (ml_missingflux_cmlr * missing_mlb_sollum).to(u.Msun)
    missing_mass_ring = (ml_missingflux_ring * missing_mlb_sollum).to(u.Msun)

    mass_ax.scatter(x=res_Re.max() - .1,
                    y=mass_within_nRe[-1] * u.Msun + missing_mass_cmlr,
                    marker='s',
                    c='C1',
                    edgecolor='k',
                    zorder=3,
                    label='+AC(CMLR)')
    mass_ax.scatter(x=res_Re.max(),
                    y=mass_within_nRe[-1] * u.Msun + missing_mass_ring,
                    marker='x',
                    c='C1',
                    edgecolor='k',
                    zorder=3,
                    label='+AC(RING)')
    mass_ax.legend(loc='best', prop={'size': 'x-small'})

    summed_flux = np.array([
        sum_within_nRe(arr=res_flux, Re_a=res_Re, nRe=n) for n in nRe_to_plot
    ])
    f_ax.plot(nRe_to_plot, summed_flux, label='IFU', c='C1')
    f_ax.scatter(x=res_Re.max() + .1,
                 y=summed_flux[-1] * m.Mgy + flux_deficit[3],
                 marker='o',
                 c='C1',
                 edgecolor='k',
                 zorder=3)
Esempio n. 23
0
                           ydata=mean_smsd_in_bin[usebin],
                           sigma=std_smsd_in_bin[usebin],
                           absolute_sigma=True,
                           p0=[2.])

    return popt, pcov


if __name__ == '__main__':
    import read_results
    import os

    pca_system = read_results.PCASystem.fromfile(
        os.path.join(basedir, 'pc_vecs.fits'))
    drpall = m.load_drpall(mpl_v, index='plateifu')
    all_dms_galaxies = drpall[m.mask_from_maskbits(drpall['mngtarg3'], [16])]
    h_dms = 0.7

    fig, (ax1, ax2, ax3, ax4, ax5, _) = plt.subplots(nrows=2,
                                                     ncols=3,
                                                     figsize=(7, 8),
                                                     sharex=True,
                                                     sharey=True)
    for plateifu, dms_name, ax, Rbulge, F, incl in zip(
        [
            '8566-12705', '8567-12701', '8939-12704', '10494-12705',
            '10510-12704'
        ], ['UGC3997', 'UGC4107', 'UGC4368', 'UGC4380', 'UGC6918'],
        [ax1, ax2, ax3, ax4, ax5], [1.97, 1.18, 2.23, 2.44, 0.655],
        [.48, .56, .72, .46, .64],
            np.array([26.2, 24.1, 45.3, 14.2, 38.0]) * u.deg):