示例#1
0
def plot_extmodels(extdata, alax=False):
    """
    Plot Milky Way extinction curve models of Cardelli, Clayton, and Mathis (1989, ApJ, 345, 245), only possible for wavelengths between 0.1 and 3.33 micron

    Parameters
    ----------
    extdata : ExtData
        Extinction data under consideration

    alax : boolean [default=False]
        Whether or not to plot A(lambda)/A(X) instead of E(lambda-X)

    Returns
    -------
    Overplots extinction curve models
    """
    x = np.arange(0.1, 3.33, 0.01) * u.micron
    Rvs = [2.0, 3.1, 4.0, 5.0]
    style = ["--", "-", ":", "-."]
    for i, cRv in enumerate(Rvs):
        curve = CCM89(Rv=cRv)
        if alax:
            if extdata.type_rel_band != "V":
                emod = CCM89(cRv)
                (indx, ) = np.where(
                    extdata.type_rel_band == extdata.names["BAND"])
                axav = emod(extdata.waves["BAND"][indx[0]])
            else:
                axav = 1.0
            y = curve(x) / axav
        else:
            # compute A(V)
            extdata.calc_AV()
            # convert the model curve from A(lambda)/A(V) to E(lambda-V), using the computed A(V) of the data.
            y = (curve(x) - 1) * extdata.columns["AV"]
        plt.plot(
            x.value,
            y,
            style[i],
            color="k",
            alpha=0.7,
            linewidth=1,
            label="R(V) = {:4.1f}".format(cRv),
        )
        plt.legend(bbox_to_anchor=(0.99, 0.9))
示例#2
0
def NewPredictor(spectra, ext1=CCM89(Rv=3.1), ext1bv=0, z=0):
    #To notice, the ext1 is the extinction of the host galaxy, while the ext2 is the extinction of milky way.
    spectra[:, 0] = spectra[:, 0] / (1 + z)
    spectra[:, 1] = spectra[:, 1] / ext1.extinguish(spectra[:, 0] * u.AA,
                                                    Ebv=ext1bv)
    fw = interp1d(spectra[:, 0], spectra[:, 1], fill_value='extrapolate')
    flux = fw(wave2)
    spnew = np.array([wave2, flux]).T
    spnew = Normalizer(spnew, shortwave=3000, longwave=5000)
    flux = spnew[:, 1]
    Yout = model.predict(flux.reshape(1, 719, 1))
    return Yout
示例#3
0
    def test_extcurve_call_2(self):
        from dust_extinction.parameter_averages import CCM89

        Av = 2
        wav = np.arange(0.1, 3, 0.001) * u.micron
        ext = CCM89(Rv=3.1)
        ans = ext.extinguish(wav, Av)

        ebv = Av / ext.Rv
        redlaw = ReddeningLaw(ext)
        extcurve = redlaw.extinction_curve(ebv, wavelengths=wav)

        assert_quantity_allclose(extcurve(wav), ans)
        assert extcurve.meta['header']['ReddeningLaw'] == '<CCM89(Rv=3.1)>'
示例#4
0
def plot_ext_curves():
    """
    Plot model extinction curves.
    """
    # create the plot
    fig, ax = plt.subplots(figsize=(6, 3.5))

    # UV-NIR (Cardelli et al. 1989)
    x = np.arange(0.12, 3.33, 0.001) * u.micron
    curve = CCM89(Rv=3.1)
    ax.plot(x.value, curve(x), label="Cardelli+1989")

    # finalize and save the plot
    ax.set_xscale("log")
    plt.rc("axes.formatter", min_exponent=2)
    plt.xticks(
        [0.1, 0.2, 0.3, 0.4, 0.5, 0.8, 1.0, 2.0, 3.0],
        [0.1, 0.2, 0.3, 0.4, 0.5, 0.8, 1.0, 2.0, 3.0],
    )
    ax.spines["right"].set_visible(False)
    ax.spines["top"].set_visible(False)
    ax.legend()
    plt.savefig("Figures/CCM89_ext_curve.pdf")

    # add NIR-MIR (Gordon et al. 2021)
    x = np.arange(3, 30.0, 0.1) * u.micron
    curve = G21_MWAvg()
    ax.plot(x, curve(x), label="Gordon+2021")

    # finalize and save the plot
    ax.legend(loc="best")
    ax.set_yscale("log")
    plt.xticks(
        [0.1, 0.2, 0.3, 0.5, 0.8, 1, 2, 3, 4, 5, 8, 10, 20, 30],
        [0.1, 0.2, 0.3, 0.5, 0.8, 1, 2, 3, 4, 5, 8, 10, 20, 30],
    )
    plt.tight_layout()
    plt.savefig("Figures/model_ext_curve.pdf")

    # Gordon et al. 2009
    fig, ax = plt.subplots(figsize=(6, 3.5))
    curve = GCC09_MWAvg()
    x = np.arange(0.116, 0.3, 0.001) * u.micron
    ax.plot(x, curve(x), label="Gordon+2009")
    ax.spines["right"].set_visible(False)
    ax.spines["top"].set_visible(False)
    ax.legend()
    plt.tight_layout()
    plt.savefig("Figures/GCC09_ext_curve.pdf")
示例#5
0
def deredden(wavelength, flux, r_v, e_bv, curve="CCM89"):
    """Deredden a spectrum.

    Remove the interstellar/dust reddening from a spectrum, given the colour
    excess (E(B-V)) and selective extinction (Rv).

    This function assumes that the flux is in units of erg s^-1 cm^-2 AA^-1

    Parameters
    ----------
    wavelength: np.ndarray
        The wavelength bins of the spectrum.
    flux: np.ndarray
        The flux bins of the spectrum.
    r_v: float
        The selective extinction coefficient.
    e_bv: float
        The color excess.
    curve: str
        The name of the extinction curve to use, either CCM89 or F99.

    Returns
    -------
    flux: np.ndarray
        The corrected flux.
    """

    wavelength *= u.angstrom
    flux *= u.erg / u.s / u.cm / u.cm / u.AA

    if curve == "CCM89":
        curve = CCM89(Rv=r_v)
    elif curve == "F99":
        curve = F99(Rv=r_v)
    else:
        raise ValueError(
            "Unknown extinction curve {curve}: CCM89 and F99 are available.")

    flux /= curve.extinguish(wavelength, Ebv=e_bv)

    return flux
示例#6
0
import numpy as np
import matplotlib.pyplot as plt

import astropy.units as u
from dust_extinction.parameter_averages import O94, CCM89

from astrotools.constants import single_column, two_column

extinction_model = CCM89(Rv=3.1)


def extinction(EBV, EBV_err, wavelength, plot=False):
    '''Calculate the extinction for a given EBV and wavelength with errors
    
    
    flux_corr = flux / ext
    
    '''

    EBV = np.atleast_1d(EBV)
    sample_size = 100000

    ext = extinction_model.extinguish(wavelength, Ebv=EBV)

    EBV_rand = np.random.normal(loc=EBV,
                                scale=EBV_err,
                                size=(sample_size, len(EBV)))
    ext_arr = extinction_model.extinguish(wavelength, Ebv=EBV_rand)

    ext_err = np.std(ext_arr, axis=0)
    ext_mean = np.mean(ext_arr, axis=0)
示例#7
0
np.save(Youtposition, Yout)

HSTlist = pd.read_csv('HSTplotout/EbvChi2HST/HSTlist_Ebv.csv')


def NewPredictor(spectra, ext1=CCM89(Rv=3.1), ext1bv=0, z=0):
    #To notice, the ext1 is the extinction of the host galaxy, while the ext2 is the extinction of milky way.
    spectra[:, 0] = spectra[:, 0] / (1 + z)
    spectra[:, 1] = spectra[:, 1] / ext1.extinguish(spectra[:, 0] * u.AA,
                                                    Ebv=ext1bv)
    fw = interp1d(spectra[:, 0], spectra[:, 1], fill_value='extrapolate')
    flux = fw(wave2)
    spnew = np.array([wave2, flux]).T
    spnew = Normalizer(spnew, shortwave=3000, longwave=5000)
    flux = spnew[:, 1]
    Yout = model.predict(flux.reshape(1, 719, 1))
    return Yout


ObserveYoutData = []
for i in range(len(HSTlist)):
    name = glob.glob('ObserveSpectra/HST_UV_raw/' + HSTlist['Name'][i] +
                     '*')[0]
    spr = np.genfromtxt(name)[:, 0:2]
    ObserveYoutData.append(
        NewPredictor(spr, CCM89(Rv=3.1), HSTlist['Select'][i],
                     HSTlist['Redshift'][i]))

ObserveYoutData = np.array(ObserveYoutData)
np.save(observeoutposition, ObserveYoutData)
示例#8
0
文件: old.py 项目: fschmnn/pnlf
def old_vs_new_linemaps():
    with fits.open(data_raw / name / 'ngc628_ha.fits') as hdul:
        HA6562_old = hdul[0].data
        HA6562_old_header = hdul[0].header

    with fits.open(data_raw / name / 'ngc628_ha_err.fits') as hdul:
        HA6562_old_err = hdul[0].data

    galaxy.lines.append('HA6562_old')

    x, y = sources['SkyCoord'].to_pixel(WCS(HA6562_old_header))

    sources['x_big'] = x
    sources['y_big'] = y

    peak_tbl = sources

    from pnlf.photometry import light_in_moffat, correct_PSF
    from photutils import CircularAnnulus, CircularAperture, aperture_photometry

    alpha = galaxy.alpha
    aperture_size = galaxy.aperturesize
    wavelength = 6562
    PSF_correction = correct_PSF(wavelength)

    del flux_HA

    for fwhm in np.unique(peak_tbl['fwhm']):

        source_part = peak_tbl[peak_tbl['fwhm'] == fwhm]
        positions = np.transpose((source_part['x_big'], source_part['y_big']))

        gamma = (fwhm - PSF_correction) / (2 * np.sqrt(2**(1 / alpha) - 1))

        r = aperture_size * (fwhm - PSF_correction) / 2
        aperture = CircularAperture(positions, r=r)

        # measure the flux for each source
        phot = aperture_photometry(
            HA6562_old,
            aperture,
            error=HA6562_old_err,
        )

        r_in = 5 * (fwhm - PSF_correction) / 2
        r_out = 1. * np.sqrt(3 * r**2 + r_in**2)
        annulus_aperture = CircularAnnulus(positions, r_in=r_in, r_out=r_out)
        annulus_masks = annulus_aperture.to_mask(method='center')

        bkg_median = []
        for mask in annulus_masks:
            # select the pixels inside the annulus and calulate sigma clipped median
            annulus_data = mask.multiply(HA6562_old)
            annulus_data_1d = annulus_data[mask.data > 0]
            _, median_sigclip, _ = sigma_clipped_stats(
                annulus_data_1d[~np.isnan(annulus_data_1d)],
                sigma=5,
                maxiters=None)
            bkg_median.append(median_sigclip)

        # save bkg_median in case we need it again
        phot['bkg_median'] = np.array(bkg_median)
        # multiply background with size of the aperture
        phot['aperture_bkg'] = phot['bkg_median'] * aperture.area

        phot['flux'] = phot['aperture_sum'] - phot['aperture_bkg']

        # correct for flux that is lost outside of the aperture
        phot['flux'] /= light_in_moffat(r, alpha, gamma)

        # save fwhm in an additional column
        phot['fwhm'] = fwhm

        # concatenate new sources with output table
        if 'flux_HA' in locals():
            phot['id'] += np.amax(flux_HA['id'], initial=0)
            flux_HA = vstack([flux_HA, phot])
        else:
            flux_HA = phot

    from dust_extinction.parameter_averages import CCM89

    # initialize extinction model
    extinction_model = CCM89(Rv=Rv)
    k = lambda lam: ext_model.evaluate(wavelength * u.angstrom, Rv) * Rv

    extinction_mw = extinction_model.extinguish(wavelength * u.angstrom,
                                                Ebv=Ebv)

    flux_HA['flux'] /= extinction_mw

    flux['HA6562_old'] = flux_HA['flux']

    fig, ax = plt.subplots(figsize=(4, 4))
    plt.scatter(flux[tbl['type'] == 'PN']['HA6562'],
                flux[tbl['type'] == 'PN']['HA6562_old'],
                label='PN')
    plt.scatter(flux[tbl['type'] == 'SNR']['HA6562'],
                flux[tbl['type'] == 'SNR']['HA6562_old'],
                label='SNR')
    plt.legend()
    plt.plot([-1e5, 3e4], [-1e5, 3e4])
    plt.xlim([-15000, 20000])
    plt.ylim([-15000, 20000])

    plt.xlabel(r'H$\alpha$ old / (erg/s$^2$ / cm$^2$ / \AA)')
    plt.ylabel(r'H$\alpha$ DR1 / (erg/s$^2$ / cm$^2$ / \AA)')

    plt.show()
示例#9
0
    ax.set_xlabel('$\lambda$ [$\mu m$]', fontsize=1.3 * fontsize)
    if args.alav:
        ytype = 'alav'
    else:
        ytype = 'elv'
    ax.set_ylabel(extdata._get_ext_ytitle(ytype), fontsize=1.3 * fontsize)
    ax.tick_params('both', length=10, width=2, which='major')
    ax.tick_params('both', length=5, width=1, which='minor')
    ax.set_title(args.extfile)

    # plot extinctionm models
    if args.extmodels:
        x = np.arange(0.12, 3.0, 0.01) * u.micron
        Rvs = [2.0, 3.1, 4.0, 5.0]
        for cRv in Rvs:
            t = CCM89(Rv=cRv)
            ax.plot(x,
                    t(x),
                    'k--',
                    linewidth=2,
                    label='R(V) = {:4.2f}'.format(cRv))

    # plot NIR power law model
    if args.powerlaw:
        ftype = 'BAND'
        gbool = np.all([(extdata.npts[ftype] > 0),
                        (extdata.waves[ftype] > 1.0),
                        (extdata.waves[ftype] < 5.0)],
                       axis=0)
        xdata = extdata.waves[ftype][gbool]
        ydata = extdata.exts[ftype][gbool]