def qso_template(outfil='Figures/qso_template.pdf'):
    """ van den berk
    """
    pyigm_path = imp.find_module('pyigm')[1]

    # Load
    telfer = pyicq.get_telfer_spec()

    clight = const.c.cgs

    # Beta spliced to vanden Berk template with host galaxy  removed
    van_file = pyigm_path+'/data/quasar/VanDmeetBeta_fullResolution.txt'
    van_tbl = Table.read(van_file,format='ascii')
    isort = np.argsort(van_tbl['nu'])
    nu_van = van_tbl['nu'][isort]
    fnu_van = van_tbl['f_nu'][isort]
    lam_van = (clight/(nu_van*u.Hz)).to('AA')
    flam_van = fnu_van * clight / lam_van**2
    nrm_pix = np.abs(lam_van-1450*u.AA) < 10*u.AA
    nrm_van = np.median(flam_van[nrm_pix])
    flam_van = flam_van / nrm_van

    # Start the plot
    xmnx = (1170., 2300)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1,1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    #ax.set_ylim(ymnx) 
    ax.set_ylabel('Relative Flux')
    ax.set_xlabel('Rest Wavelength (Angstroms)')

    lw = 1.
    ax.plot(telfer.wavelength, telfer.flux, 'k', linewidth=lw, 
        label='Telfer (z~1)') 
    ax.plot(lam_van, flam_van, 'b', linewidth=lw, label='SDSS (z~2)')

    # Legend
    legend = plt.legend(loc='upper right', scatterpoints=1, borderpad=0.3, 
        handletextpad=0.3, fontsize='large', numpoints=1)
    # Layout and save
    xputils.set_fontsize(ax, 17.)
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
Exemple #2
0
def fig_lya(inp=('J1555+3628', '88_11'), outfil='fig_j1555_lya.png'):
    # Init COS-Halos sightline
    cos_halos = COSHalos()
    #cos_halos.load_single( ('J0950+4831','177_27'))
    cgm_abs = cos_halos[inp]

    # ########################################
    # Finder (out of order to avoid PDF issues)
    #finder.main([cgm_abs.name, cgm_abs.galaxy.coord], imsize=2.*u.arcmin, show_circ=False)

    lclr = 'blue'
    lw = 2.

    # Start the plot
    #outfil='fig_j1555_lya.pdf'
    #pp = PdfPages(outfil)

    # Full QSO spectrum
    spec = cos_halos.load_bg_cos_spec(inp, 1215.6700 * u.AA)
    plt.figure(figsize=(5, 5))
    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Axes
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(1.))
    #ax.get_xaxis().get_major_formatter().set_useOffset(False)
    ax.set_xlim(1436., 1455.)
    ax.set_ylim(-0.1, 1.3)
    ax.set_ylabel('Normalized Flux')
    ax.set_xlabel(r'Wavelength ($\AA$)')
    for axis in ['top', 'bottom', 'left', 'right']:
        ax.spines[axis].set_linewidth(2.0)

    # Zero line
    ax.plot([-1e9, 1e9], (0., 0.), 'g--', lw=lw)
    wv_lya = 1215.670 * (1 + cgm_abs.zabs)
    ax.plot([wv_lya] * 2, [-1e9, 1e9], 'b--', lw=lw)

    # Data
    ax.plot(spec.wavelength, spec.flux, 'k', drawstyle='steps-mid')
    ax.plot(spec.wavelength, spec.sig, 'r:')

    #ax.fill_between( [1455., 1490.], [ymnx[0]]*2, [ymnx[1]]*2, color='blue', alpha=0.3)
    # Label
    ax.text(1437., 0.3, r'HI Ly$\alpha$', ha='left',
            fontsize=21.)  #, color=lclr)

    # Fonts
    xputils.set_fontsize(ax, 17.)

    # Write
    plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
    plt.savefig(outfil)
    plt.close()
    print("Wrote {:s}".format(outfil))
def dla_vary_NHI(outfil='Figures/dla_vary_NHI.pdf'):
    """ DLA profiles with NHI varying
    """
    # Wavelength array for my 'perfect' instrument
    wave = np.linspace(1160., 1270., 20000) * u.AA
    vel = (wave-1215.67*u.AA)/(1215.67*u.AA) * const.c.to('km/s')

    # Lya line
    lya = AbsLine(1215.6700*u.AA)
    #lya.attrib['N'] = 10.**(13.6)/u.cm**2
    lya.attrib['b'] = 30 * u.km/u.s
    lya.attrib['z'] = 0.

    aNHI = [20.3, 21., 21.5, 22.]

    # Start the plot
    xmnx = (-10000, 10000)
    ymnx = (0., 1.0)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1,1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(ymnx)
    ax.set_ylabel('Normalized Flux')
    ax.set_xlabel('Relative Velocity (km/s)') 

    lw = 1.5
    # Data
    for NHI in aNHI:
        lyai = copy.deepcopy(lya)
        lyai.attrib['N'] = 10**NHI / u.cm**2
        f_obsi = ltav.voigt_from_abslines(wave, [lyai])
        ax.plot(vel, f_obsi.flux, linewidth=lw, 
            label=r'$\log N_{\rm HI} = $'+'{:0.2f}'.format(NHI))

    # Legend
    legend = plt.legend(loc='lower left', scatterpoints=1, borderpad=0.3, 
        handletextpad=0.3, fontsize='large', numpoints=1)
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
def sawtooth(outfil='Figures/sawtooth.pdf', all_tau=None):
    """ Sawtooth opacity
    """
    # Load fN
    fN_model = FNModel.default_model()
    fN_model.zmnx = (2.,4.1) # extrapolate a bit
    # teff
    zem = 4
    wave = np.arange(4500., 6200., 10)
    # Calculate
    if all_tau is None:
        all_tau = np.zeros_like(wave)
        for qq,iwave in enumerate(wave):
            all_tau[qq] = lyman_ew(iwave, zem, fN_model)
    # Flux attenuation
    flux = np.exp(-all_tau)

    # Start the plot
    xmnx = (4500, 6200)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1,1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(0., 1.1)
    ax.set_ylabel('IGM Transmission')
    ax.set_xlabel('Observed wavelength (z=4 source)')

    lw = 2.
    ax.plot(wave, flux, 'b', linewidth=lw)

    # Label
    csz = 17
    ax.text(0.10, 0.90, 'f(N) from Prochaska+14', color='blue',
            transform=ax.transAxes, size=csz, ha='left') 
    ax.text(0.10, 0.80, 'Ignores Lyman continuum opacity', color='blue',
            transform=ax.transAxes, size=csz, ha='left') 
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
    return all_tau
Exemple #5
0
def teff_LL(outfil='Figures/teff_LL.pdf'):
    """ Plot teff_LL from z=3.5 down
    """
    # z
    zem = 3.5
    z912 = 3.

    # f(N)
    fnmodel = FNModel.default_model()
    fnmodel.zmnx = (0.5, 4)  # extend default range

    # Calculate
    zval, teff_LL = lyman_limit(fnmodel, z912, zem)

    # Start the plot
    xmnx = (3.5, 3)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(0., 2)
    ax.set_ylabel(r'$\tau_{\rm eff}^{\rm LL}$')
    ax.set_xlabel('z')

    lw = 2.
    # Data
    ax.plot(zval, teff_LL, 'b', linewidth=lw)  #, label='SDSS QSOs (z=4)')

    # Label
    csz = 17
    ax.text(0.10,
            0.80,
            'Source at z=3.5',
            color='black',
            transform=ax.transAxes,
            size=csz,
            ha='left')
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
def q1422(outfil='Figures/q1422.pdf'):
    """ Series of plots on Q1422
    """
    q1422 = lsio.readspec('/Users/xavier/Keck/HIRES/RedData/Q1422+2309/Q1422+2309.fits')

    axmnx = [ [4000, 6000],
              [4900, 5500],
              [5100, 5300],
              [5150, 5250],
              [5190, 5220],
    ]
    aymnx = [ [0., 7300],
              [0., 2000],
              [0., 1700],
              [0., 1100],
              [0., 1100],
    ]
    lw = 1.
    csz = 19.

    # Start the plot
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1,1)

    # Loop
    for qq, xmnx in enumerate(axmnx):

        # Spectrum
        ax = plt.subplot(gs[0])
        ax.set_xlim(xmnx)
        ax.set_ylim(aymnx[qq])
        #ax.set_ylim(ymnx) 
        ax.set_ylabel('Relative Flux')
        ax.set_xlabel("Wavelength (Ang)")

        ax.plot(q1422.wavelength, q1422.flux, 'k', linewidth=lw)

        # 
        ax.text(0.05, 0.9, 'Keck/HIRES: Q1422+2309', color='blue',
            transform=ax.transAxes, size=csz, ha='left')#, bbox={'facecolor':'white'})
        #
        xputils.set_fontsize(ax, 17.)
        # Layout and save
        plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
        plt.subplots_adjust(hspace=0)
        pp.savefig(bbox_inches='tight', transparent=True)
        plt.close()
    # Finish
    print('Writing {:s}'.format(outfil))
    pp.close()
Exemple #7
0
def xq100_example(outfil='fig_xq100_example.pdf'):

    # Load spectrum
    spec_fil = os.getenv('DROPBOX_DIR') + '/XQ-100/data/J0030-5159_uvb.fits'
    spec = load_spectrum(spec_fil)

    # Start the plot
    if outfil is not None:
        pp = PdfPages(outfil)

    plt.figure(figsize=(8, 5))
    plt.clf()
    gs = gridspec.GridSpec(1, 1)
    fsz = 17.

    # Read and plot full spectrum
    ax_full = plt.subplot(gs[0])

    # Limits
    wvmnx = [3500., 7000.]
    gdpix = np.where(spec.dispersion < wvmnx[1] * u.AA)[0]
    perc = xsb.perc(spec.flux[gdpix])
    ax_full.set_xlim(wvmnx)
    #ax_full.set_ylim(-0.05*perc[1], 1.1*perc[1])
    ax_full.set_ylim(-1e-18, 7e-17)

    # Plot
    ax_full.plot(spec.dispersion, spec.flux, color='black', lw=1.0)
    ax_full.plot(wvmnx, [0., 0.], '--', color='green')

    # Label
    ax_full.set_xlabel('Wavelength')
    ax_full.set_ylabel('Relative Flux')
    ax_full.text(0.05,
                 0.9,
                 'XQ100 J0030-5159',
                 transform=ax_full.transAxes,
                 color='black',
                 size='x-large',
                 ha='left',
                 va='center',
                 bbox={'facecolor': 'white'})

    # Font size
    xputils.set_fontsize(ax_full, fsz)

    # Finish page
    plt.tight_layout(pad=0.2, h_pad=0.3, w_pad=0.0)
    pp.savefig()
    plt.close()
    print('Wrote: {:s}'.format(outfil))
    # Finish
    pp.close()
def dteff(outfil='Figures/dteff.pdf'):
    """ Differential teff (Lya)
    """
    # Load fN
    fN_model = FNModel.default_model()

    # teff
    cumul = []
    iwave = 1215.67 * (1+2.5)
    zem = 2.6
    teff_alpha = lyman_ew(iwave, zem, fN_model, cumul=cumul)
    print('teff = {:g}'.format(teff_alpha))

    dteff = cumul[1] - np.roll(cumul[1],1)
    dteff[0] = dteff[1] # Fix first value

    # Start the plot
    xmnx = (12, 22)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1,1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    #ax.set_ylim(ymnx) 
    ax.set_ylabel(r'$d\tau_{\rm eff, \alpha}/d\log N$')
    ax.set_xlabel(r'$\log \, N_{\rm HI}$')

    lw = 2.
    ax.plot(cumul[0], dteff, 'k', linewidth=lw)

    # Label
    csz = 17
    ax.text(0.60, 0.90, 'f(N) from Prochaska+14', color='blue',
            transform=ax.transAxes, size=csz, ha='left') 
    ax.text(0.60, 0.80, 'z=2.5', color='blue',
            transform=ax.transAxes, size=csz, ha='left') 
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
Exemple #9
0
def wfc3_qso(outfil='Figures/wfc3_qso.pdf'):
    """ Show a QSO that is transmissive at the Lyman limit
    """
    # WFC3
    wfc3, _ = pyicq.wfc3_continuum(0)
    #zem = 4.

    # Start the plot
    xmnx = (650, 1300)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(0., 70)
    ax.set_ylabel('Relative Flux')
    ax.set_xlabel('Rest wavelength')

    lw = 2.
    # Data
    ax.plot(wfc3.wavelength,
            wfc3.flux,
            'k',
            linewidth=lw,
            label='SDSS QSOs (z=4)')

    # Label
    csz = 17
    ax.text(0.10,
            0.80,
            'HST/WFC3: QSO spectrum (z~2)',
            color='black',
            transform=ax.transAxes,
            size=csz,
            ha='left')
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
Exemple #10
0
def qso_sed(outfil='Figures/qso_sed.pdf'):
    """ Plots a few QSO examples
    """
    sdss_dr7 = quasars.SdssQuasars()
    #bal = sdss_dr7[(367, 506)]
    #bal = sdss_dr7[(726, 60)]
    bal = sdss_dr7[(668, 193)]
    bal.load_spec(load_conti=False)
    fj0812 = sdss_dr7[(861, 333)]
    fj0812.load_spec(load_conti=False)
    # Start the plot
    xmnx = (1180., 1580)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(2, 1)

    # Lya line
    for qq in range(2):
        if qq == 0:
            qso = fj0812
        elif qq == 1:
            qso = bal
        ax = plt.subplot(gs[qq])
        #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
        #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
        #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
        #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
        ax.set_xlim(xmnx)
        #ax.set_ylim(ymnx)
        ax.set_ylabel('Relative Flux')
        if qq < 1:
            ax.get_xaxis().set_ticks([])
        else:
            ax.set_xlabel('Rest Wavelength (Angstroms)')

        lw = 1.
        ax.plot(qso.spec.wavelength / (qso.z + 1),
                qso.spec.flux,
                'k',
                linewidth=lw)
        xputils.set_fontsize(ax, 17.)

    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
Exemple #11
0
def real_dla_vary_NHI(outfil='Figures/real_dla_vary_NHI.pdf'):
    """ DLA profiles with NHI varying
    """
    # Wavelength array for my 'perfect' instrument
    files = ['/Users/xavier/GRB/data/080607/LRIS/GRB080607_B600N.fits']
    lbls = [r'GRB080607: $\log N_{\rm HI} = 22.7$']
    zdlas = [3.03626]

    # Start the plot
    xmnx = (-20000, 20000)
    ymnx = (0., 1.0)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(ymnx)
    ax.set_ylabel('Normalized Flux')
    ax.set_xlabel('Relative Velocity (km/s)')

    lw = 1.5
    # Data
    for zdla, lbl, fil in zip(zdlas, lbls, files):
        spec = lsio.readspec(fil)
        vel = spec.relative_vel(1215.6701 * u.AA * (1 + zdla))
        ax.plot(vel, spec.flux, linewidth=lw, label=lbl)

    # Legend
    legend = plt.legend(loc='lower left',
                        scatterpoints=1,
                        borderpad=0.3,
                        handletextpad=0.3,
                        fontsize='large',
                        numpoints=1)
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
Exemple #12
0
def qso_fuv(outfil='Figures/qso_fuv.pdf'):
    """ FUV flux from QSOs
    """
    pyigm_path = imp.find_module('pyigm')[1]

    # Load
    telfer = pyicq.get_telfer_spec()

    # Start the plot
    xmnx = (900., 1220)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    #ax.set_ylim(ymnx)
    ax.set_ylabel('Relative Flux')
    ax.set_xlabel('Rest Wavelength (Angstroms)')

    lw = 1.
    ax.plot(telfer.wavelength,
            telfer.flux,
            'k',
            linewidth=lw,
            label='Telfer Average QSO SED (z~1)')

    # Legend
    legend = plt.legend(loc='upper left',
                        scatterpoints=1,
                        borderpad=0.3,
                        handletextpad=0.3,
                        fontsize='x-large',
                        numpoints=1)
    # Layout and save
    xputils.set_fontsize(ax, 17.)
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
def teff_LL(outfil='Figures/teff_LL.pdf'):
    """ Plot teff_LL from z=3.5 down
    """
    # z
    zem = 3.5
    z912 = 3.

    # f(N)
    fnmodel = FNModel.default_model()
    fnmodel.zmnx = (0.5,4) # extend default range

    # Calculate
    zval, teff_LL = lyman_limit(fnmodel, z912, zem)

    # Start the plot
    xmnx = (3.5, 3)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1,1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(0., 2)
    ax.set_ylabel(r'$\tau_{\rm eff}^{\rm LL}$')
    ax.set_xlabel('z')

    lw = 2.
    # Data
    ax.plot(zval, teff_LL, 'b', linewidth=lw)#, label='SDSS QSOs (z=4)')

    # Label
    csz = 17
    ax.text(0.10, 0.80, 'Source at z=3.5',
        color='black', transform=ax.transAxes, size=csz, ha='left')
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
def qso_sed(outfil='Figures/qso_sed.pdf'):
    """ Plots a few QSO examples
    """
    sdss_dr7 = quasars.SdssQuasars()
    #bal = sdss_dr7[(367, 506)]
    #bal = sdss_dr7[(726, 60)]
    bal = sdss_dr7[(668, 193)]
    bal.load_spec(load_conti=False)
    fj0812 = sdss_dr7[(861,333)]
    fj0812.load_spec(load_conti=False)
    # Start the plot
    xmnx = (1180., 1580)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(2,1)

    # Lya line
    for qq in range(2):
        if qq == 0:
            qso = fj0812
        elif qq == 1:
            qso = bal
        ax = plt.subplot(gs[qq])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
        ax.set_xlim(xmnx)
    #ax.set_ylim(ymnx) 
        ax.set_ylabel('Relative Flux')
        if qq < 1:
            ax.get_xaxis().set_ticks([])
        else:
            ax.set_xlabel('Rest Wavelength (Angstroms)')

        lw = 1.
        ax.plot(qso.spec.wavelength/(qso.z+1), qso.spec.flux, 'k', linewidth=lw) 
        xputils.set_fontsize(ax, 17.)

    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
def real_dla_vary_NHI(outfil='Figures/real_dla_vary_NHI.pdf'):
    """ DLA profiles with NHI varying
    """
    # Wavelength array for my 'perfect' instrument
    files = ['/Users/xavier/GRB/data/080607/LRIS/GRB080607_B600N.fits']
    lbls  = [r'GRB080607: $\log N_{\rm HI} = 22.7$']
    zdlas = [3.03626]

    # Start the plot
    xmnx = (-20000, 20000)
    ymnx = (0., 1.0)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1,1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(ymnx)
    ax.set_ylabel('Normalized Flux')
    ax.set_xlabel('Relative Velocity (km/s)') 

    lw = 1.5
    # Data
    for zdla,lbl,fil in zip(zdlas,lbls,files):
        spec = lsio.readspec(fil)
        vel = spec.relative_vel(1215.6701*u.AA*(1+zdla))
        ax.plot(vel, spec.flux, linewidth=lw, 
            label=lbl)

    # Legend
    legend = plt.legend(loc='lower left', scatterpoints=1, borderpad=0.3, 
        handletextpad=0.3, fontsize='large', numpoints=1)
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
def dXdz(outfil='Figures/dXdz.pdf'):
    """ Plot dXdz vs. z
    """
    # z
    zval = np.linspace(1., 5, 100)

    # dX/dz
    dXdz = pyiu.cosm_xz(zval, cosmo=Planck15, flg_return=1)

    # Start the plot
    xmnx = (1., 5)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1,1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(0., 5)
    ax.set_ylabel('dX/dz')
    ax.set_xlabel('z')

    lw = 2.
    # Data
    ax.plot(zval, dXdz, 'k', linewidth=lw)#, label='SDSS QSOs (z=4)')

    # Label
    csz = 17
    #ax.text(0.10, 0.80, 'HST/WFC3: QSO spectrum (z~2)', color='black',
    #        transform=ax.transAxes, size=csz, ha='left') 
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
def drho_dNHI(outfil='Figures/drho_dNHI.pdf'):
    """ Differential contribution to rho_HI
    """
    # Wavelength array for my 'perfect' instrument
    fnmodel = FNModel.default_model()

    rhoHI, cumul, lgNHI = fnmodel.calculate_rhoHI(2.5, (12., 22.5), cumul=True)
    cumul = cumul/cumul[-1] / (lgNHI[1]-lgNHI[0]) # dlogN
    diff = cumul - np.roll(cumul,1)
    diff[0] = diff[1]

    # Start the plot
    xmnx = (16., 22.5)
    ymnx = (0., 1.0)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1,1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    #ax.set_ylim(ymnx)
    ax.set_ylabel(r'Normalized $d\rho_{\rm HI} / d\log N_{\rm HI}$')
    ax.set_xlabel(r'$\log N_{\rm HI}$')

    ax.plot(lgNHI, diff, 'b')

    # Legend
    #legend = plt.legend(loc='lower left', scatterpoints=1, borderpad=0.3, 
    #    handletextpad=0.3, fontsize='large', numpoints=1)
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
Exemple #18
0
def drho_dNHI(outfil='Figures/drho_dNHI.pdf'):
    """ Differential contribution to rho_HI
    """
    # Wavelength array for my 'perfect' instrument
    fnmodel = FNModel.default_model()

    rhoHI, cumul, lgNHI = fnmodel.calculate_rhoHI(2.5, (12., 22.5), cumul=True)
    cumul = cumul / cumul[-1] / (lgNHI[1] - lgNHI[0])  # dlogN
    diff = cumul - np.roll(cumul, 1)
    diff[0] = diff[1]

    # Start the plot
    xmnx = (16., 22.5)
    ymnx = (0., 1.0)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    #ax.set_ylim(ymnx)
    ax.set_ylabel(r'Normalized $d\rho_{\rm HI} / d\log N_{\rm HI}$')
    ax.set_xlabel(r'$\log N_{\rm HI}$')

    ax.plot(lgNHI, diff, 'b')

    # Legend
    #legend = plt.legend(loc='lower left', scatterpoints=1, borderpad=0.3,
    #    handletextpad=0.3, fontsize='large', numpoints=1)
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
Exemple #19
0
def dXdz(outfil='Figures/dXdz.pdf'):
    """ Plot dXdz vs. z
    """
    # z
    zval = np.linspace(1., 5, 100)

    # dX/dz
    dXdz = pyiu.cosm_xz(zval, cosmo=Planck15, flg_return=1)

    # Start the plot
    xmnx = (1., 5)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(0., 5)
    ax.set_ylabel('dX/dz')
    ax.set_xlabel('z')

    lw = 2.
    # Data
    ax.plot(zval, dXdz, 'k', linewidth=lw)  #, label='SDSS QSOs (z=4)')

    # Label
    csz = 17
    #ax.text(0.10, 0.80, 'HST/WFC3: QSO spectrum (z~2)', color='black',
    #        transform=ax.transAxes, size=csz, ha='left')
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
def qso_fuv(outfil='Figures/qso_fuv.pdf'):
    """ FUV flux from QSOs
    """
    pyigm_path = imp.find_module('pyigm')[1]

    # Load
    telfer = pyicq.get_telfer_spec()


    # Start the plot
    xmnx = (900., 1220)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1,1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    #ax.set_ylim(ymnx) 
    ax.set_ylabel('Relative Flux')
    ax.set_xlabel('Rest Wavelength (Angstroms)')

    lw = 1.
    ax.plot(telfer.wavelength, telfer.flux, 'k', linewidth=lw, 
        label='Telfer Average QSO SED (z~1)') 

    # Legend
    legend = plt.legend(loc='upper left', scatterpoints=1, borderpad=0.3, 
        handletextpad=0.3, fontsize='x-large', numpoints=1)
    # Layout and save
    xputils.set_fontsize(ax, 17.)
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
def wfc3_qso(outfil='Figures/wfc3_qso.pdf'):
    """ Show a QSO that is transmissive at the Lyman limit
    """
    # WFC3
    wfc3, _ = pyicq.wfc3_continuum(0)
    #zem = 4.


    # Start the plot
    xmnx = (650, 1300)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1,1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(0., 70)
    ax.set_ylabel('Relative Flux')
    ax.set_xlabel('Rest wavelength')

    lw = 2.
    # Data
    ax.plot(wfc3.wavelength, wfc3.flux, 'k', linewidth=lw, label='SDSS QSOs (z=4)')

    # Label
    csz = 17
    ax.text(0.10, 0.80, 'HST/WFC3: QSO spectrum (z~2)', color='black',
            transform=ax.transAxes, size=csz, ha='left') 
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
Exemple #22
0
def fig_sngl_metPDF(system):
    """ Shows a single metallicity PDF
    """
    from matplotlib import transforms

    # Read Metallicity input
    mfile = '../Analysis/COS_Halos_MTL.ascii'
    data = Table.read(mfile, format='ascii')
    mtl_inps = np.where(data['name'] == system[0]+'_'+system[1])[0]

    ion_lst = []
    clrs = []
    cdict = {0:'black', -1:'red', -2:'green'}
    for inp in mtl_inps:
        ion_lst.append(data[inp]['ion'])
        clrs.append(cdict[data[inp]['flag']])

    # Read COS-Halos
    cos_halos = COSHalos()
    cos_halos.load_single_fits(system, skip_ions=True)
    orig_NHI = cos_halos.NHI
    orig_fNHI = cos_halos.flag_NHI

    # Read PDF
    mtlfil = '../Analysis/COS_Halos_MTL.hdf5'
    fh5 = h5py.File(mtlfil,'r')
    mPDF = MetallicityPDF(fh5['met']['left_edge_bins']+
                                     fh5['met']['left_edge_bins'].attrs['BINSIZE']/2.,
                                     fh5['met'][system[0]+'_'+system[1]])

    # KLUDGE
    print("BIG KLUDGE HERE")
    bad = np.where(mPDF.ZH < -2)[0]
    mPDF.pdf_ZH[bad] = 0.
    mPDF.normalize()

    # Init
    NHI_mnx = (14.8, 19.1)

    # Start the plot
    outfil = 'fig_metPDF_'+system[0]+'_'+system[1]+'.pdf'
    pp = PdfPages(outfil)

    fig = plt.figure(figsize=(7, 4))
    plt.clf()
    ax = plt.gca()

    # Axes
    #wvmnx = awvmnx[iuvq['instr']]
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(500.))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(1.))
    #plt.ylim(0, nsys+1)
    ax.set_xlim(-2,1)

    # Labels
    lsz = 19.

    # Giddy up
    ax.bar(mPDF.ZH-mPDF.dZH/2., mPDF.pdf_ZH, width=mPDF.dZH)
    ax.set_xlabel("[Z/H]", size=lsz)
    ax.set_ylabel("PDF", size=lsz)

    # Label system
    csz = 18.
    lbl = '{:s}_{:s}'.format(system[0], system[1])
    ax.text(0.1, 0.87, lbl, transform=ax.transAxes, color='black',
            size=csz, ha='left')

    # Ions
    x = -1.8
    ymnx = ax.get_ylim()
    y = 0.75 * ymnx[1]
    isz = 14.
    t = plt.gca().transData
    for s,c in zip(ion_lst,clrs):
        text = plt.text(x,y," "+s+" ",color=c, transform=t, size=isz)
        text.draw(fig.canvas.get_renderer())
        ex = text.get_window_extent()
        t = transforms.offset_copy(text._transform, x=ex.width*0.9, units='dots')

    # End
    xputils.set_fontsize(ax, 16.)
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.,w_pad=0.1)
    pp.savefig()
    pp.close()
    plt.close()
Exemple #23
0
def mfp_spec(outfil='Figures/mfp_spec.pdf', all_tau=None, scl=1.):
    """ Stacked spectrum for MFP
    """
    # SDSS
    zq = 4.
    hdu = fits.open(
        '/Users/xavier/paper/LLS/taueff/Analysis/stack_DR7_z3.92_z4.02.fits')
    sdss_fx = hdu[0].data
    sdss_wave = hdu[2].data
    zem = 4.

    # Start the plot
    xmnx = (800, 1000)
    ymnx = (0., 1.0)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(ymnx)
    ax.set_ylabel('Relative Flux')
    ax.set_xlabel('Rest Wavelength (Ang)')

    lw = 1.5
    # Data
    ax.plot(sdss_wave, sdss_fx, 'k', linewidth=lw, label='SDSS QSOs (z=4)')

    # Label
    xexp = 860.
    headl = 6.
    ax.plot([911.7] * 2, ymnx, '--', color='red', linewidth=1.5)
    ax.arrow(911.7,
             0.6,
             xexp - 911.7 + headl,
             0.,
             linewidth=2,
             head_width=0.03,
             head_length=headl,
             fc='blue',
             ec='blue')
    csz = 19.
    ax.text(890.,
            0.63,
            r'r = $\lambda_{\rm mfp}$',
            color='blue',
            size=csz,
            ha='center')

    # exp(-1)
    y1 = 0.43
    y2 = np.exp(-1) * y1
    yplt = (y1 + y2) / 2.
    yerr = (y2 - y1) / 2.
    ax.errorbar([xexp], [yplt],
                yerr=yerr,
                color='green',
                linewidth=2,
                capthick=2)
    ax.plot([xexp, 911.7], [y1] * 2, ':', color='green', linewidth=2)
    ax.text(855., yplt, 'exp(-1)', color='green', size=csz, ha='right')

    #
    ax.text(0.05,
            0.90,
            'SDSS QSO stack (z=4)',
            color='black',
            transform=ax.transAxes,
            size=csz,
            ha='left')
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
    return all_tau
Exemple #24
0
    def on_draw(self, replot=True, in_wrest=None, rescale=True, fig_clear=False):
        """ Redraws the figure
        """
        #
        if replot is True:
            if fig_clear:
                self.fig.clf()
            # Loop on windows
            all_idx = self.llist['show_line']
            nplt = self.sub_xy[0]*self.sub_xy[1]
            if len(all_idx) <= nplt:
                self.idx_line = 0
            subp = np.arange(nplt) + 1
            subp_idx = np.hstack(subp.reshape(self.sub_xy[0],self.sub_xy[1]).T)
            #print('idx_l={:d}, nplt={:d}, lall={:d}'.format(self.idx_line,nplt,len(all_idx)))
            for jj in range(min(nplt, len(all_idx))):
                try:
                    idx = all_idx[jj+self.idx_line]
                except IndexError:
                    continue # Likely too few lines
                #print('jj={:d}, idx={:d}'.format(jj,idx))
                # Grab line
                wrest = self.llist[self.llist['List']].wrest[idx] 
                kwrest = wrest.value # For the Dict
                # Single window?
                if in_wrest is not None:
                    if np.abs(wrest-in_wrest) > (1e-3*u.AA):
                        continue

                # Abs_Sys: Color the lines
                if self.abs_sys is not None:
                    absline = self.grab_line(wrest)

                # Generate plot
                self.ax = self.fig.add_subplot(self.sub_xy[0],self.sub_xy[1], subp_idx[jj])
                self.ax.clear()        
                #QtCore.pyqtRemoveInputHook()
                #xdb.set_trace()
                #QtCore.pyqtRestoreInputHook()

                # Zero line
                self.ax.plot( [0., 0.], [-1e9, 1e9], ':', color='gray')
                # Velocity
                wvobs = (1+self.z) * wrest
                velo = (self.spec.dispersion/wvobs - 1.)*const.c.to('km/s')
                
                # Plot
                self.ax.plot(velo, self.spec.flux, 'k-',drawstyle='steps-mid')

                # GID for referencing
                self.ax.set_gid(wrest)

                # Labels
                #if jj >= (self.sub_xy[0]-1)*(self.sub_xy[1]):
                if (((jj+1) % self.sub_xy[0]) == 0) or ((jj+1) == len(all_idx)):
                    self.ax.set_xlabel('Relative Velocity (km/s)')
                else:
                    self.ax.get_xaxis().set_ticks([])
                lbl = self.llist[self.llist['List']].name[idx]
                # Kinematics
                kinl = ''
                if absline is not None:
                    if (absline.analy['flag_kin'] % 2) >= 1:
                        kinl = kinl + 'L'
                    if (absline.analy['flag_kin'] % 4) >= 2:
                        kinl = kinl + 'H'
                self.ax.text(0.1, 0.05, lbl+kinl, color='blue', transform=self.ax.transAxes,
                             size='x-small', ha='left')

                # Reset window limits
                #QtCore.pyqtRemoveInputHook()
                #xdb.set_trace()
                #QtCore.pyqtRestoreInputHook()
                self.ax.set_xlim(self.psdict['xmnx'])

                # Rescale?
                if (rescale is True) & (self.norm is False):
                    gdp = np.where( (velo.value > self.psdict['xmnx'][0]) &
                                    (velo.value < self.psdict['xmnx'][1]))[0]
                    if len(gdp) > 5:
                        per = xstats.basic.perc(self.spec.flux[gdp])
                        self.ax.set_ylim((0., 1.1*per[1]))
                    else:
                        self.ax.set_ylim(self.psdict['ymnx'])
                else:
                    self.ax.set_ylim(self.psdict['ymnx'])

                # Fonts
                xputils.set_fontsize(self.ax,6.)


                clr='black'
                if absline is not None:
                    try:
                        vlim = absline.analy['vlim']
                    except KeyError:
                        pass
                    # Color coding
                    try:  # .clm style
                        flag = absline.analy['FLAGS'][0]
                    except KeyError:
                        flag = None
                    else:
                        if flag <= 1: # Standard detection
                            clr = 'green'
                        elif flag in [2,3]:
                            clr = 'blue'
                        elif flag in [4,5]:
                            clr = 'purple'
                    # ABS ID
                    try: # NG?
                        flagA = absline.analy['do_analysis']
                    except KeyError:
                        flagA = None
                    else:
                        if (flagA>0) & (clr == 'black'):
                            clr = 'green'
                    try: # Limit?
                        flagL = absline.analy['flg_limit']
                    except KeyError:
                        flagL = None
                    else:
                        if flagL == 2:
                            clr = 'blue'
                        if flagL == 3:
                            clr = 'purple'
                    try: # Blends?
                        flagE = absline.analy['flg_eye']
                    except KeyError:
                        flagE = None
                    else:
                        if flagE == 1:
                            clr = 'orange'
                    if flagA == 0:
                        clr = 'red'

                    pix = np.where( (velo > vlim[0]) & (velo < vlim[1]))[0]
                    self.ax.plot(velo[pix], self.spec.flux[pix], '-',
                                 drawstyle='steps-mid', color=clr)
        # Draw
        self.canvas.draw()
Exemple #25
0
    def on_draw(self,
                replot=True,
                in_wrest=None,
                rescale=True,
                fig_clear=False):
        """ Redraws the figure
        """
        #
        if replot is True:
            if fig_clear:
                self.fig.clf()
            # Loop on windows
            all_idx = self.llist['show_line']
            nplt = self.sub_xy[0] * self.sub_xy[1]
            if len(all_idx) <= nplt:
                self.idx_line = 0
            subp = np.arange(nplt) + 1
            subp_idx = np.hstack(
                subp.reshape(self.sub_xy[0], self.sub_xy[1]).T)
            #print('idx_l={:d}, nplt={:d}, lall={:d}'.format(self.idx_line,nplt,len(all_idx)))
            for jj in range(min(nplt, len(all_idx))):
                try:
                    idx = all_idx[jj + self.idx_line]
                except IndexError:
                    continue  # Likely too few lines
                #print('jj={:d}, idx={:d}'.format(jj,idx))
                # Grab line
                wrest = self.llist[self.llist['List']].wrest[idx]
                kwrest = wrest.value  # For the Dict
                # Single window?
                if in_wrest is not None:
                    if np.abs(wrest - in_wrest) > (1e-3 * u.AA):
                        continue

                # Abs_Sys: Color the lines
                if self.abs_sys is not None:
                    absline = self.grab_line(wrest)

                # Generate plot
                self.ax = self.fig.add_subplot(self.sub_xy[0], self.sub_xy[1],
                                               subp_idx[jj])
                self.ax.clear()
                #QtCore.pyqtRemoveInputHook()
                #xdb.set_trace()
                #QtCore.pyqtRestoreInputHook()

                # Zero line
                self.ax.plot([0., 0.], [-1e9, 1e9], ':', color='gray')
                # Velocity
                wvobs = (1 + self.z) * wrest
                velo = (self.spec.dispersion / wvobs - 1.) * const.c.to('km/s')

                # Plot
                self.ax.plot(velo, self.spec.flux, 'k-', drawstyle='steps-mid')

                # GID for referencing
                self.ax.set_gid(wrest)

                # Labels
                #if jj >= (self.sub_xy[0]-1)*(self.sub_xy[1]):
                if (((jj + 1) % self.sub_xy[0]) == 0) or ((jj + 1)
                                                          == len(all_idx)):
                    self.ax.set_xlabel('Relative Velocity (km/s)')
                else:
                    self.ax.get_xaxis().set_ticks([])
                lbl = self.llist[self.llist['List']].name[idx]
                # Kinematics
                kinl = ''
                if absline is not None:
                    if (absline.analy['flag_kin'] % 2) >= 1:
                        kinl = kinl + 'L'
                    if (absline.analy['flag_kin'] % 4) >= 2:
                        kinl = kinl + 'H'
                self.ax.text(0.1,
                             0.05,
                             lbl + kinl,
                             color='blue',
                             transform=self.ax.transAxes,
                             size='x-small',
                             ha='left')

                # Reset window limits
                #QtCore.pyqtRemoveInputHook()
                #xdb.set_trace()
                #QtCore.pyqtRestoreInputHook()
                self.ax.set_xlim(self.psdict['xmnx'])

                # Rescale?
                if (rescale is True) & (self.norm is False):
                    gdp = np.where((velo.value > self.psdict['xmnx'][0])
                                   & (velo.value < self.psdict['xmnx'][1]))[0]
                    if len(gdp) > 5:
                        per = xstats.basic.perc(self.spec.flux[gdp])
                        self.ax.set_ylim((0., 1.1 * per[1]))
                    else:
                        self.ax.set_ylim(self.psdict['ymnx'])
                else:
                    self.ax.set_ylim(self.psdict['ymnx'])

                # Fonts
                xputils.set_fontsize(self.ax, 6.)

                clr = 'black'
                if absline is not None:
                    try:
                        vlim = absline.analy['vlim']
                    except KeyError:
                        pass
                    # Color coding
                    try:  # .clm style
                        flag = absline.analy['FLAGS'][0]
                    except KeyError:
                        flag = None
                    else:
                        if flag <= 1:  # Standard detection
                            clr = 'green'
                        elif flag in [2, 3]:
                            clr = 'blue'
                        elif flag in [4, 5]:
                            clr = 'purple'
                    # ABS ID
                    try:  # NG?
                        flagA = absline.analy['do_analysis']
                    except KeyError:
                        flagA = None
                    else:
                        if (flagA > 0) & (clr == 'black'):
                            clr = 'green'
                    try:  # Limit?
                        flagL = absline.analy['flg_limit']
                    except KeyError:
                        flagL = None
                    else:
                        if flagL == 2:
                            clr = 'blue'
                        if flagL == 3:
                            clr = 'purple'
                    try:  # Blends?
                        flagE = absline.analy['flg_eye']
                    except KeyError:
                        flagE = None
                    else:
                        if flagE == 1:
                            clr = 'orange'
                    if flagA == 0:
                        clr = 'red'

                    pix = np.where((velo > vlim[0]) & (velo < vlim[1]))[0]
                    self.ax.plot(velo[pix],
                                 self.spec.flux[pix],
                                 '-',
                                 drawstyle='steps-mid',
                                 color=clr)
        # Draw
        self.canvas.draw()
Exemple #26
0
def fig_boss_pca_coeff(outfil=None, boss_fil=None,scl=100.):

    # Todo
    #   Include NHI on the label
    # Imports

    # Read FITS table
    if boss_fil is None:
        boss_fil = 'BOSS_DR10Lya_PCA_values_nocut.fits.gz'
    hdu = fits.open(boss_fil)
    pca_coeff = hdu[1].data
    #xdb.set_trace()
    
    # Initialize
    #if 'xmnx' not in locals():
    #    xmnx = (17.0, 20.4)
    #ymnx = ((-1.9, 2.3),
    #        (-1.9, 1.4),
    #        (-1.1, 1.4),
    #        (-2.1, 0.9))
                
    ms = 1. # point size
            
    allxi = [0,0,0,1,1,2]
    allyi = [1,2,3,2,3,3]

    rngi = ([-0.02, 0.3],
            [-0.2,0.4],
            [-0.2, 0.5],
            [-0.2, 0.4])
    
    # Start the plot
    if outfil != None:
        pp = PdfPages(outfil)

    plt.figure(figsize=(5.5, 4))
    plt.clf()
    gs = gridspec.GridSpec(2, 3)


    # Looping
    for ii in range(6):

        # Axis
        ax = plt.subplot(gs[ii])
        #ax = plt.subplot(gs[ii//2,ii%2])

        '''
        ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
        ax.xaxis.set_major_locator(plt.MultipleLocator(1.))
        #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.5))
        ax.yaxis.set_major_locator(plt.MultipleLocator(0.5))
        ax.set_xlim(xmnx)
        ax.set_ylim((-0.5, 0.5))
        '''

        xi = allxi[ii]
        xlbl=str('PCA'+str(xi))
        yi = allyi[ii]
        ylbl=str('PCA'+str(yi))


        # Labels
        ax.set_xlabel(xlbl)
        ax.set_ylabel(ylbl)

        # Data

        # Values
        #ax.scatter(pca_coeff[xlbl], pca_coeff[ylbl], color='black', s=ms)#, marker=mark)
        ax.hist2d(scl*pca_coeff[xlbl], scl*pca_coeff[ylbl], bins=100, norm=LogNorm(),
                  range=[rngi[xi],rngi[yi]])

        # Font size
        xputils.set_fontsize(ax,8.)

    # Layout and save
    plt.tight_layout(pad=0.2,h_pad=0.1,w_pad=0.25)
    if outfil != None:
        pp.savefig(bbox_inches='tight')
        pp.close()
    else: 
        plt.show()
def obs_sawtooth(outfil='Figures/obs_sawtooth.pdf', all_tau=None, scl=1.):
    """ Sawtooth opacity
    """
    # SDSS
    hdu = fits.open('/Users/xavier/paper/LLS/taueff/Analysis/stack_DR7_z3.92_z4.02.fits')
    sdss_fx = hdu[0].data
    sdss_wave = hdu[2].data
    # Telfer
    telfer = pyicq.get_telfer_spec()
    i1450 = np.argmin(np.abs(telfer.wavelength.value - 1450.))
    nrm = np.median(telfer.flux[i1450-5:i1450+5])
    telfer.flux = telfer.flux / nrm
    trebin = telfer.rebin(sdss_wave*u.AA)
    # Load fN
    fN_model = FNModel.default_model()
    fN_model.zmnx = (2.,4.1) # extrapolate a bit
    # teff
    zem = 4.
    wave = np.arange(4500., 6200., 10)
    # Calculate
    if all_tau is None:
        all_tau = np.zeros_like(wave)
        for qq,iwave in enumerate(wave):
            all_tau[qq] = lyman_ew(iwave, zem, fN_model)
    # Flux attenuation
    trans = np.exp(-all_tau)

    ftrans = interp1d(wave, trans, fill_value=1.,
        bounds_error=False)

    # Start the plot
    xmnx = (4500, 6200)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1,1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(0., 1.5)
    ax.set_ylabel('Relative Flux')
    ax.set_xlabel('Observed wavelength')

    lw = 2.
    # Data
    ax.plot(sdss_wave*(1+zem), sdss_fx, 'k', linewidth=lw, label='SDSS QSOs (z=4)')
    # Model
    model = trebin.flux * ftrans(sdss_wave*(1+zem)) * scl
    ax.plot(sdss_wave*(1+zem), model, 'r', linewidth=lw, label='IGM+Telfer model')

    # Label
    csz = 17
    #ax.text(0.10, 0.10, 'SDSS quasar stack at z=4', color='black',
    #        transform=ax.transAxes, size=csz, ha='left') 
    # Legend
    legend = plt.legend(loc='upper left', scatterpoints=1, borderpad=0.3, 
        handletextpad=0.3, fontsize='large', numpoints=1)
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
    return all_tau
Exemple #28
0
def fig_z_vs_dNHI(cos_halos=None, outfil='fig_z_vs_dNHI.pdf'):
    """ Shows change in NHI vs. z
    """
    # Read LLS
    jfile = '../Analysis/COS_Halos_LLS.json'
    with open(jfile) as json_file:
        fdict = json.load(json_file)
    keys = fdict.keys()
    nsys = len(keys)
    zabs = np.array([fdict[key]['z'] for key in keys])
    srt = np.argsort(zabs)


    # Read COS-Halos
    if cos_halos is None:
        cos_halos = load_ch(load_mtl=False)
    orig_NHI = cos_halos.NHI
    orig_fNHI = cos_halos.flag_NHI
    werk_NHI = cos_halos.werk14_NHI

    # Init
    NHI_mnx = (14.8, 19.1)

    # Start the plot
    if outfil is not None:
        pp = PdfPages(outfil)

    plt.figure(figsize=(5, 5))
    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    ax = plt.subplot(gs[0])

    # Axes
    #wvmnx = awvmnx[iuvq['instr']]
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(500.))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(1.))
    ax.minorticks_on()
    ax.set_xlim(NHI_mnx)
    ax.set_ylim(0, nsys+1)

    # Labels
    lsz = 16.
    ax.set_xlabel(r'$\log_{10} \, N_{\rm HI}$', size=lsz)
    ax.set_ylabel(r'System (Ordered by $z$)', size=lsz)
    new_lbl = False

    # Loop on Systems
    for jj, isrt in enumerate(srt):
        key = keys[isrt]
        # Original
        mt = np.where((cos_halos.field == fdict[key]['quasar']) &
                      (cos_halos.gal_id == fdict[key]['galaxy']))[0]
        if len(mt) != 1:
            raise ValueError("Not a proper match")
        # Plot original
        if orig_fNHI[mt] == 1:
            warnings.warn("Assuming the value for {:s}_{:s} is a lower limit".format(
                fdict[key]['quasar'],fdict[key]['galaxy']))
            #ax.quiver(orig_NHI[mt], fdict[key]['fit_NHI'][0], 1, 0,
            #          units='x', width=0.03, headwidth=2., headlength=5.)
        elif orig_fNHI[mt] == 2:
            pass
            #ax.quiver(orig_NHI[mt], fdict[key]['fit_NHI'][0], 1, 0,
            #          units='x', width=0.03, headwidth=2., headlength=5.)
        elif orig_fNHI[mt] == 3:
            xdb.set_trace()
            raise ValueError("Very Unlikely")
        else:
            xdb.set_trace()
            raise ValueError("Nope")

        # Tumlinson NHI
        if jj == 0:
            lbl = 'Tumlinson+13'
        else:
            lbl = None
        ax.scatter([orig_NHI[mt]], [jj+1], marker='o', edgecolor='gray',
                   facecolor='none', label=lbl)

        # Werk+14 NHI
        if jj == 0:
            lbl2 = 'Werk+14'
        else:
            lbl2 = None
        ax.scatter([werk_NHI[mt]], [jj+1], marker='s', edgecolor='red',
                   facecolor='none', label=lbl2)

        # New value
        if fdict[key]['flag_NHI'] == 1:
            xerr=[[fdict[key]['fit_NHI'][0]-fdict[key]['fit_NHI'][1]],
                  [fdict[key]['fit_NHI'][2]-fdict[key]['fit_NHI'][0]]]
            if new_lbl is False:
                lbl = 'New'
                new_lbl = True
            else:
                lbl = None
            ax.errorbar([fdict[key]['fit_NHI'][0]], [jj+1], xerr=xerr,
                        capthick=2, fmt='o', color='blue', label=lbl)
        elif fdict[key]['flag_NHI'] == 2:  # Lower limit
            ax.plot([fdict[key]['fit_NHI'][1]], [jj+1], '>', color='blue')
        elif fdict[key]['flag_NHI'] == 3:  # Upper limit
            ax.plot([fdict[key]['fit_NHI'][2]], [jj+1], '<', color='blue')

    legend = plt.legend(loc='upper right', scatterpoints=1, borderpad=0.3,
                        handletextpad=0.3, fontsize='small', numpoints=1)

    # End
    xputils.set_fontsize(ax,15.)
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.,w_pad=0.1)
    pp.savefig()
    pp.close()
    plt.close()
Exemple #29
0
def fig_sngl_cldy_model(sys, dpath=os.getenv('COSHALOS_DATA')+'/Cloudy/', ax=None, outfil=None,
                        lsz=15., show_sys=False):
    """ Compare columns between model and data
    """
    # Read
    fh5 = h5py.File(dpath+sys+'_emcee.hd5', 'r')
    ions = fh5['inputs']['ions'].value
    data = fh5['inputs']['data'].value
    fit = fh5['outputs']['best_fit'].value
    fh5.close()

    # IP values
    IPs = np.zeros(len(ions))
    for ii,ion in enumerate(ions):
        Zion = lai.name_ion(ion)
        elm = ELEMENTS[Zion[0]]
        IPs[ii] = elm.ionenergy[Zion[1]-1]
    #xdb.set_trace()
    resid = data[:,1].astype(float) - fit

    # Start the plot
    if outfil is not None:
        pp = PdfPages(outfil)
        plt.figure(figsize=(7, 7))
        plt.clf()
        gs = gridspec.GridSpec(1, 1)
        ax = plt.subplot(gs[0])

    # Axes
    #wvmnx = awvmnx[iuvq['instr']]
    #ax.yaxis.set_major_locator(plt.MultipleLocator(1.))
    ax.minorticks_on()
    xlim = (5., np.max(IPs)+4)
    ax.set_xlim(xlim)
    ylim = (-1., 1.)
    ax.set_ylim(ylim)

    # Labels
    ax.set_xlabel('IP (eV)', size=lsz)
    ax.set_ylabel(r'$\Delta \, \log \, N$', size=lsz)
    ax.xaxis.set_major_locator(plt.MultipleLocator(10.))

    # Values
    gdv = np.where(data[:,3].astype(int) == 0)[0]
    if len(gdv) > 0:
        ax.errorbar(IPs[gdv],resid[gdv], xerr=0, linestyle='None',
                    yerr=data[:,2].astype(float)[gdv], color='blue', marker='o')
    # Limits
    limsz = 50.
    ulim = np.where(data[:,3].astype(int) == -1)[0]
    ax.scatter(IPs[ulim],resid[ulim], color='red', marker='v', s=limsz)
    llim = np.where(data[:,3].astype(int) == -2)[0]
    ax.scatter(IPs[llim],resid[llim], color='green', marker='^', s=limsz)

    # Label
    for kk,ion in enumerate(ions):
        if (resid[kk] < ylim[1]) & (resid[kk] > ylim[0]):
            ax.text(IPs[kk]+1, resid[kk], ion, color='k', size=lsz)  # Only if on page
    if show_sys:
        ax.text(0.04, 0.04, sys, transform=ax.transAxes, size=lsz-1, ha='left')
                #bbox={'facecolor':'white'})

    #legend = plt.legend(loc='upper right', scatterpoints=1, borderpad=0.3,
    #                    handletextpad=0.3, fontsize='small', numpoints=1)
    ax.plot(xlim, [0.,0.], 'g:')

    # End
    xputils.set_fontsize(ax,lsz)
    if outfil is not None:
        print('Writing {:s}'.format(outfil))
        plt.tight_layout(pad=0.2,h_pad=0.,w_pad=0.1)
        pp.savefig()
        pp.close()
        plt.close()
Exemple #30
0
    def on_draw(self, replot=True, in_wrest=None, rescale=True, fig_clear=False):
        """ Redraws the figure
        """
        #
        if replot is True:
            if fig_clear:
                self.fig.clf()
            # Title
            self.fig.suptitle('z={:g}'.format(self.z),fontsize=7.)
            # Components
            #components = self.parent.comps_widg.all_comp
            components = self.parent.comps_widg.selected_components()
            iwrest = np.array([comp.init_wrest.value for comp in components])*u.AA
            # Loop on windows
            all_idx = self.llist['show_line']
            #QtCore.pyqtRemoveInputHook()
            #xdb.set_trace()
            #QtCore.pyqtRestoreInputHook()
            # Labels
            if self.flag_idlbl:
                line_wvobs = []
                line_lbl = []
                for comp in components:
                    for line in comp.lines:
                        line_wvobs.append(line.wrest.value*(line.attrib['z']+1))
                        line_lbl.append(line.trans+',{:.4f}'.format(line.attrib['z']))
                line_wvobs = np.array(line_wvobs)*u.AA
                line_lbl = np.array(line_lbl)
            # Subplots
            nplt = self.sub_xy[0]*self.sub_xy[1]
            if len(all_idx) <= nplt:
                self.idx_line = 0
            subp = np.arange(nplt) + 1
            subp_idx = np.hstack(subp.reshape(self.sub_xy[0],self.sub_xy[1]).T)
            #print('idx_l={:d}, nplt={:d}, lall={:d}'.format(self.idx_line,nplt,len(all_idx)))
            for jj in range(min(nplt, len(all_idx))):
                try:
                    idx = all_idx[jj+self.idx_line]
                except IndexError:
                    continue # Likely too few lines
                #print('jj={:d}, idx={:d}'.format(jj,idx))
                # Grab line
                wrest = self.llist[self.llist['List']].wrest[idx] 
                kwrest = wrest.value # For the Dict
                # Single window?
                #if in_wrest is not None:
                #    if np.abs(wrest-in_wrest) > (1e-3*u.AA):
                #        continue
                # Generate plot
                self.ax = self.fig.add_subplot(self.sub_xy[0],self.sub_xy[1], subp_idx[jj])
                self.ax.clear()        

                # GID for referencing
                self.ax.set_gid(wrest)

                # Zero line
                self.ax.plot( [0., 0.], [-1e9, 1e9], ':', color='gray')
                # Velocity
                wvobs = (1+self.z) * wrest
                wvmnx = wvobs*(1 + np.array(self.psdict['xmnx'])/3e5)
                velo = (self.spec.dispersion/wvobs - 1.)*const.c.to('km/s')
                
                # Plot
                self.ax.plot(velo, self.spec.flux, 'k-',drawstyle='steps-mid')

                # Model
                self.ax.plot(velo, self.model.flux, 'b-')
                # Labels
                if (((jj+1) % self.sub_xy[0]) == 0) or ((jj+1) == len(all_idx)):
                    self.ax.set_xlabel('Relative Velocity (km/s)')
                else:
                    self.ax.get_xaxis().set_ticks([])
                lbl = self.llist[self.llist['List']].name[idx]
                self.ax.text(0.05, 0.90, lbl, color='blue', transform=self.ax.transAxes,
                             size='x-small', ha='left')
                if self.flag_idlbl:
                    # Any lines inside?
                    mtw = np.where((line_wvobs > wvmnx[0]) & (line_wvobs<wvmnx[1]))[0]
                    for imt in mtw:
                        v = 3e5*(line_wvobs[imt]/wvobs - 1)
                        self.ax.text(v, 0.90, line_lbl[imt], color='green', 
                            size='x-small', rotation=90.)

                # Analysis regions
                if np.sum(self.spec.mask) > 0.:
                    gdp = self.spec.mask==1
                    if len(gdp) > 0:
                        self.ax.scatter(velo[gdp],self.spec.flux[gdp],
                            marker='o',color='gray',s=10.)

                # Reset window limits
                self.ax.set_ylim(self.psdict['ymnx'])
                self.ax.set_xlim(self.psdict['xmnx'])

                # Add line?
                if self.wrest == wrest:
                    self.ax.plot([self.vtmp]*2,self.psdict['ymnx'], '--',
                        color='red')

                # Components
                mtc = np.where(wrest == iwrest)[0]
                if len(mtc) > 0:
                    #QtCore.pyqtRemoveInputHook()
                    #xdb.set_trace()
                    #QtCore.pyqtRestoreInputHook()
                    for mt in mtc:
                        comp = components[mt]
                        #QtCore.pyqtRemoveInputHook()
                        #xdb.set_trace()
                        #QtCore.pyqtRestoreInputHook()
                        dvz = const.c.to('km/s')*(self.z-comp.zcomp)/(1+self.z)
                        if dvz.value < np.max(np.abs(self.psdict['xmnx'])):
                            if comp is self.parent.fiddle_widg.component:
                                lw = 1.5
                            else:
                                lw = 1.
                            # Plot
                            for vlim in comp.vlim:
                                self.ax.plot([vlim.value-dvz.value]*2,self.psdict['ymnx'], 
                                    '--', color='gray',linewidth=lw)
                            self.ax.plot([-1.*dvz.value]*2,[1.0,1.05],
                                '-', color='gray',linewidth=lw)

                # Fonts
                xputils.set_fontsize(self.ax,6.)
        # Draw
        self.canvas.draw()
Exemple #31
0
def qso_template(outfil='Figures/qso_template.pdf'):
    """ van den berk
    """
    pyigm_path = imp.find_module('pyigm')[1]

    # Load
    telfer = pyicq.get_telfer_spec()

    clight = const.c.cgs

    # Beta spliced to vanden Berk template with host galaxy  removed
    van_file = pyigm_path + '/data/quasar/VanDmeetBeta_fullResolution.txt'
    van_tbl = Table.read(van_file, format='ascii')
    isort = np.argsort(van_tbl['nu'])
    nu_van = van_tbl['nu'][isort]
    fnu_van = van_tbl['f_nu'][isort]
    lam_van = (clight / (nu_van * u.Hz)).to('AA')
    flam_van = fnu_van * clight / lam_van**2
    nrm_pix = np.abs(lam_van - 1450 * u.AA) < 10 * u.AA
    nrm_van = np.median(flam_van[nrm_pix])
    flam_van = flam_van / nrm_van

    # Start the plot
    xmnx = (1170., 2300)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    #ax.set_ylim(ymnx)
    ax.set_ylabel('Relative Flux')
    ax.set_xlabel('Rest Wavelength (Angstroms)')

    lw = 1.
    ax.plot(telfer.wavelength,
            telfer.flux,
            'k',
            linewidth=lw,
            label='Telfer (z~1)')
    ax.plot(lam_van, flam_van, 'b', linewidth=lw, label='SDSS (z~2)')

    # Legend
    legend = plt.legend(loc='upper right',
                        scatterpoints=1,
                        borderpad=0.3,
                        handletextpad=0.3,
                        fontsize='large',
                        numpoints=1)
    # Layout and save
    xputils.set_fontsize(ax, 17.)
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
Exemple #32
0
def fig_full_nH_PDF(cos_halos=None, outfil = 'fig_full_nH_PDF.pdf'):
    """ Shows the combined PDF
    """
    # Read COS-Halos
    if cos_halos is None:
        cos_halos = load_ch()

    # Init
    nH_mnx = (-5., 1)

    # Start the plot
    pp = PdfPages(outfil)

    plt.figure(figsize=(5, 5))
    plt.clf()
    ax = plt.gca()

    # Axes
    #wvmnx = awvmnx[iuvq['instr']]
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(500.))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(1.))
    #plt.ylim(0, nsys+1)
    ax.set_xlim(nH_mnx)


    sumPDF = None
    # Loop on the systems
    nsys = 0
    for cgm_abs in cos_halos.cgm_abs:
        # Cut on quality
        qual = chmtl.mtl_quality(cgm_abs)
        if qual < 1:
            continue
        # Sum the PDF
        nsys += 1
        if sumPDF is None:
            sumPDF = cgm_abs.igm_sys.density
        else:
            sumPDF = sumPDF + cgm_abs.igm_sys.density

    print("We are using {:d} systems in COS-Halos".format(nsys))
    sumPDF.normalize()

    # Giddy up
    lsz = 19.
    ax.bar(sumPDF.nH-sumPDF.dnH/2., sumPDF.pdf_nH, width=sumPDF.dnH, color='green')
    ax.set_xlabel(r"$\log \, n_{\rm H}$", size=lsz)
    ax.set_ylabel("Normalized PDF", size=lsz)

    # Label
    csz = 18.
    lbl = 'COS-Halos'
    ax.text(0.05, 0.87, lbl, transform=ax.transAxes, color='black', size=csz, ha='left')
    lbl2 = '({:d} systems)'.format(nsys)
    ax.text(0.05, 0.75, lbl2, transform=ax.transAxes, color='black', size=csz, ha='left')

    # End
    xputils.set_fontsize(ax, 16.)
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.,w_pad=0.1)
    pp.savefig()
    pp.close()
    plt.close()
Exemple #33
0
def xq100_plls_ex(outfil='fig_xq100_plls_ex.pdf'):

    # Load spectrum
    spec_fil = os.getenv('DROPBOX_DIR') + '/XQ-100/data/J0030-5159_uvb.fits'
    spec = load_spectrum(spec_fil)

    # Generate model
    model_file = os.getenv(
        'DROPBOX_DIR') + '/XQ-100/LLS/convg_J0030-5159_llsfit.json'
    with open(model_file) as data_file:
        lls_dict = json.load(data_file)
    # Continuum
    basec = Quantity(lls_dict['conti'])
    telfer_spec = XSpectrum1D.from_tuple((spec.dispersion.value, basec.value))

    # Start the plot
    if outfil is not None:
        pp = PdfPages(outfil)

    plt.figure(figsize=(8, 4))
    plt.clf()
    gs = gridspec.GridSpec(1, 1)
    fsz = 17.

    # Read and plot full spectrum
    ax_full = plt.subplot(gs[0])

    # Limits
    wvmnx = [3600., 5000.]
    gdpix = np.where(spec.dispersion < wvmnx[1] * u.AA)[0]
    perc = xsb.perc(spec.flux[gdpix])
    ax_full.set_xlim(wvmnx)
    #ax_full.set_ylim(-0.05*perc[1], 1.1*perc[1])
    ax_full.set_ylim(-1e-18, 4e-17)

    # Plot
    ax_full.plot(spec.dispersion, spec.flux, color='black', lw=1.0)
    ax_full.plot(wvmnx, [0., 0.], '--', color='green')

    # Label
    ax_full.set_xlabel('Wavelength')
    ax_full.set_ylabel('Relative Flux')
    ax_full.text(0.05,
                 0.9,
                 'XQ100 J0030-5159',
                 transform=ax_full.transAxes,
                 color='black',
                 size='x-large',
                 ha='left',
                 va='center',
                 bbox={'facecolor': 'white'})

    all_ills = []
    all_lls = []
    all_zlls = []
    for key in lls_dict['LLS'].keys():
        new_sys = LLSSystem(NHI=lls_dict['LLS'][key]['NHI'])
        new_sys.zabs = lls_dict['LLS'][key]['z']
        new_sys.fill_lls_lines(bval=lls_dict['LLS'][key]['bval'] * u.km / u.s)
        #
        all_ills.append(new_sys)
        all_lls.append(new_sys)
        all_zlls.append(new_sys.zabs)
    # Model
    norm_flux = lls_model(spec.dispersion, all_ills, smooth=lls_dict['smooth'])
    continuum = telfer_spec.flux * lls_dict['conti_model']['Norm'] * (
        spec.dispersion.value /
        lls_dict['conti_model']['piv_wv'])**lls_dict['conti_model']['tilt']

    #  Model
    ax_full.plot(spec.dispersion, continuum * norm_flux)

    # Font size
    xputils.set_fontsize(ax_full, fsz)

    # Finish page
    plt.tight_layout(pad=0.2, h_pad=0.3, w_pad=0.0)
    pp.savefig()
    plt.close()
    print('Wrote: {:s}'.format(outfil))
    # Finish
    pp.close()
Exemple #34
0
def fig_x_vs_ZH(x, xmnx, xlbl, cos_halos=None, msk=None,
                outfil = None, lsz=16., ax=None, log=None):
    """ Plot ZH vs. a input quantity
    """
    # Read COS-Halos
    if cos_halos is None:
        cos_halos = load_ch()

    # Init
    ZH_mnx = (-2., 1)

    # Start the plot
    if ax is None:
        pp = PdfPages(outfil)
        plt.figure(figsize=(5, 5))
        plt.clf()
        ax = plt.gca()

    # Axes
    #wvmnx = awvmnx[iuvq['instr']]
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(500.))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(1.))
    #plt.ylim(0, nsys+1)
    ax.set_xlim(xmnx)
    ax.set_ylim(ZH_mnx)


    # Loop on the systems
    for ii, cgm_abs in enumerate(cos_halos.cgm_abs):
        if msk is None:
            # Cut on quality
            try:
                flgs = cgm_abs.igm_sys.metallicity.inputs['data'][:, 3]
            except IndexError:
                print('No constraint for {:s}'.format(cgm_abs.name))
                print('Skipping')
                continue
            indices = np.where(flgs != "-1")[0]
            if len(indices) == 0:
                print('No constraint for {:s}'.format(cgm_abs.name))
                print('Skipping')
                continue
        else:
            if msk[ii] is False:
                continue
        #
        ZH = cgm_abs.igm_sys.metallicity.medianZH
        sig = cgm_abs.igm_sys.metallicity.confidence_limits(0.68)
        yerr = [[ZH-sig[0]], [sig[1]-ZH]]
        if np.sum(np.array(yerr)) > 1.:
            pcolor='lightgray'
            eclr = 'none'
        else:
            pcolor='blue'
            fclr ='blue'
            eclr = 'black'

        if x == 'NHI':
            xval = cgm_abs.igm_sys.NHIPDF.median
        elif x == 'nH':
            xval = cgm_abs.igm_sys.density.median
        else:
            xval = getattr(cgm_abs, x)
            if isinstance(xval, Quantity):
                xval = xval.value
        if log:
            xval = np.log10(xval)
        #if (x == 'NHI') and (xval < 16) and (ZH < -1):
        #    xdb.set_trace()
        ax.errorbar([xval], [ZH], yerr=yerr, capthick=2, fmt='o', color=pcolor)
                    #edgecolor=eclr)

    # Labels
    ax.set_xlabel(xlbl)
    ax.set_ylabel("[Z/H]")
    ax.plot(xmnx, [0., 0.], '--', color='green')

    # End
    xputils.set_fontsize(ax, lsz)
    if outfil is not None:
        print('Writing {:s}'.format(outfil))
        plt.tight_layout(pad=0.2,h_pad=0.,w_pad=0.1)
        pp.savefig()
        pp.close()
        plt.close()
Exemple #35
0
def fig_boss_x_vs_pca(outfil=None, boss_fil=None, flg=0):
    '''
    flg = 0:  Redshift
    flg = 1:  imag
    '''

    # Todo
    #   Include NHI on the label
    # Imports

    # Read PCA FITS table
    if boss_fil is None:
        boss_fil = 'BOSS_DR10Lya_PCA_values_nocut.fits.gz'
    hdu = fits.open(boss_fil)
    pca_coeff = hdu[1].data

    # Read BOSS catalog table
    boss_cat_fil = os.environ.get('BOSSPATH')+'/DR10/BOSSLyaDR10_cat_v2.1.fits.gz'
    bcat_hdu = fits.open(boss_cat_fil)
    t_boss = bcat_hdu[1].data
    #xdb.set_trace()
    if flg == 0:
        xparm = t_boss['z_pipe']
        xmnx = [2., 4.]
        xlbl=str(r'$z_{\rm QSO}$')
    elif flg == 1:
        tmp = t_boss['PSFMAG']
        xparm = tmp[:,3] # i-band mag
        xlbl=str('i mag')
        xmnx = [17.,22.5]
    else:
        raise ValueError('fig_boss_x_vs_pca: flg={:d} not allowed'.format(flg))
    
    # Initialize
    #if 'xmnx' not in locals():
    #    xmnx = (17.0, 20.4)
    ymnx = ((-0.02, 0.3),
            (-0.2,0.4),
            (-0.2, 0.5),
            (-0.2, 0.4))
                
    ms = 1. # point size
    scl = 100.
            
    
    # Start the plot
    if outfil != None:
        pp = PdfPages(outfil)

    plt.figure(figsize=(4, 4))
    plt.clf()
    gs = gridspec.GridSpec(2, 2)

    # Looping
    for ii in range(4):

        # Axis
        ax = plt.subplot(gs[ii])
        #ax = plt.subplot(gs[ii//2,ii%2])


        ylbl=str('PCA'+str(ii))

        # Labels
        ax.set_xlabel(xlbl)
        ax.set_ylabel(ylbl)

        # Data

        # Values
        #xdb.set_trace()
        ax.hist2d(xparm, scl*pca_coeff[ylbl], bins=100, norm=LogNorm(),
                  range=[xmnx, [ymnx[ii][0], ymnx[ii][1]]])

        # Font size
        xputils.set_fontsize(ax,8.)

    # Layout and save
    plt.tight_layout(pad=0.2,h_pad=0.1,w_pad=0.25)
    if outfil != None:
        pp.savefig(bbox_inches='tight')
        pp.close()
    else: 
        plt.show()
Exemple #36
0
def fig_NH_hist(cos_halos=None, outfil = 'fig_NH_hist.pdf', lsz=17.):
    """ Shows a histogram of NH values
    """
    # Read COS-Halos
    if cos_halos is None:
        cos_halos = load_ch()

    # Read the grid
    model = os.getenv('DROPBOX_DIR')+'/cosout/grid_minextended.pkl'
    fil=open(model)
    modl=pickle.load(fil)
    fil.close()

    # Init
    NH_mnx = (18., 23)
    ymnx = (0., 9)
    binsz = 0.25
    nbins = (NH_mnx[1]-NH_mnx[0])/binsz

    # Start the plot
    pp = PdfPages(outfil)

    plt.figure(figsize=(5, 5))
    plt.clf()
    ax = plt.gca()

    # Axes
    #wvmnx = awvmnx[iuvq['instr']]
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(500.))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(1.))
    #plt.ylim(0, nsys+1)
    ax.set_xlim(NH_mnx)
    ax.set_ylim(ymnx)


    sumPDF = None
    # Loop on the systems
    nsys = 0
    NH_val = []
    for cgm_abs in cos_halos.cgm_abs:
        # Cut on quality
        try:
            flgs = cgm_abs.igm_sys.metallicity.inputs['data'][:, 3]
        except IndexError:
            print('No constraint for {:s}'.format(cgm_abs.name))
            print('Skipping')
            continue
        indices = np.where(flgs != "-1")[0]
        if len(indices) == 0:
            print('No constraint for {:s}'.format(cgm_abs.name))
            print('Skipping')
            continue
        # Find best indices
        mtl = cgm_abs.igm_sys.metallicity.medianZH
        imet = np.argmin(np.abs(modl[1]['met']-mtl))
        dens = cgm_abs.igm_sys.density.mediannH
        idens = np.argmin(np.abs(modl[1]['dens']-dens))
        ired = np.argmin(np.abs(modl[1]['red']-cgm_abs.zabs))
        icol = np.argmin(np.abs(modl[1]['col']-cgm_abs.igm_sys.NHI))
        # xHI, NH
        xHI = modl[2]['HI'][icol][idens][imet][ired]
        NH = cgm_abs.igm_sys.NHI - xHI
        NH_val.append(NH)

    print("We are using {:d} systems in COS-Halos".format(nsys))

    # Histogram
    lsz = 19.
    hist, edges = np.histogram(np.array(NH_val), range=NH_mnx, bins=nbins)
    ax.bar(edges[:-1], hist, width=binsz, color='green')
    ax.set_xlabel(r'$\log \, N_{\rm H}$')
    ax.set_ylabel(r"$N_{\rm sys}$")

    # Label
    prev_medNH = 19.1  # Eyeball
    ax.plot([prev_medNH]*2, ymnx, '--', color='red')
    '''
    csz = 18.
    lbl = 'COS-Halos'
    ax.text(0.05, 0.87, lbl, transform=ax.transAxes, color='black', size=csz, ha='left')
    lbl2 = '({:d} systems)'.format(nsys)
    ax.text(0.05, 0.75, lbl2, transform=ax.transAxes, color='black', size=csz, ha='left')
    '''

    # End
    xputils.set_fontsize(ax, lsz)
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.,w_pad=0.1)
    pp.savefig()
    pp.close()
    plt.close()
Exemple #37
0
    def on_draw(self, replot=True, in_wrest=None, rescale=True, fig_clear=False):
        """ Redraws the figure
        """
        #
        if replot is True:
            if fig_clear:
                self.fig.clf()
            # Title
            self.fig.suptitle('z={:.5f}'.format(self.z),fontsize='large')
            # Components
            components = self.parent.comps_widg.all_comp 
            iwrest = np.array([comp.init_wrest.value for comp in components])*u.AA
            # Loop on windows
            all_idx = self.llist['show_line']
            #QtCore.pyqtRemoveInputHook()
            #xdb.set_trace()
            #QtCore.pyqtRestoreInputHook()
            # Labels
            if self.flag_idlbl:
                line_wvobs = []
                line_lbl = []
                for comp in components:
                    if comp.attrib['Quality'] == 'None':
                        la = ''
                    else: 
                        la = comp.attrib['Quality']
                    for line in comp.lines:
                        line_wvobs.append(line.wrest.value*(line.attrib['z']+1))
                        line_lbl.append(line.trans+',{:.3f}{:s}'.format(line.attrib['z'],la))
                line_wvobs = np.array(line_wvobs)*u.AA
                line_lbl = np.array(line_lbl)
            # Subplots
            nplt = self.sub_xy[0]*self.sub_xy[1]
            if len(all_idx) <= nplt:
                self.idx_line = 0
            subp = np.arange(nplt) + 1
            subp_idx = np.hstack(subp.reshape(self.sub_xy[0],self.sub_xy[1]).T)
            #print('idx_l={:d}, nplt={:d}, lall={:d}'.format(self.idx_line,nplt,len(all_idx)))
            
            #try different color per ion species
            color_model = '#999966'
            colors = ['#0066FF','#339933','#CC3300','#660066','#FF9900','#B20047']
            color_ind = 0

            #loop over individual velplot axes
            for jj in range(min(nplt, len(all_idx))):
                try:
                    idx = all_idx[jj+self.idx_line]
                except IndexError:
                    continue # Likely too few lines
                #print('jj={:d}, idx={:d}'.format(jj,idx))
                # Grab line
                wrest = self.llist[self.llist['List']].wrest[idx]
                kwrest = wrest.value # For the Dict
                
                #define colors for visually grouping same species
                if jj > 0:
                    name_aux = self.llist[self.llist['List']].name[idx].split(' ')[0]
                    name_aux2 = self.llist[self.llist['List']].name[idx-1].split(' ')[0]
                    if name_aux != name_aux2:
                        color_ind += 1
                color = colors[color_ind % len(colors)]

                # Single window?
                #if in_wrest is not None:
                #    if np.abs(wrest-in_wrest) > (1e-3*u.AA):
                #        continue
                # Generate plot
                self.ax = self.fig.add_subplot(self.sub_xy[0],self.sub_xy[1], subp_idx[jj])
                self.ax.clear()        

                # GID for referencing
                self.ax.set_gid(wrest)

                # Zero velocity line
                self.ax.plot( [0., 0.], [-1e9, 1e9], ':', color='gray')
                # Velocity
                wvobs = (1+self.z) * wrest
                wvmnx = wvobs*(1 + np.array(self.psdict['xmnx'])/3e5)
                velo = (self.spec.dispersion/wvobs - 1.)*const.c.to('km/s')
                
                # Plot
                self.ax.plot(velo, self.spec.flux, '-',color=color,drawstyle='steps-mid',lw=0.5)
                # Model
                self.ax.plot(velo, self.model.flux, '-',color=color_model,lw=0.5)

                #Error & residuals
                if self.plot_residuals:
                    self.ax.plot(velo, self.residual_limit, 'k-',drawstyle='steps-mid',lw=0.5)
                    self.ax.plot(velo, -self.residual_limit, 'k-',drawstyle='steps-mid',lw=0.5)
                    self.ax.plot(velo, self.residual, '.',color='grey',ms=2)

                #import pdb
                #pdb.set_trace()

                # Labels
                if (((jj+1) % self.sub_xy[0]) == 0) or ((jj+1) == len(all_idx)):
                    self.ax.set_xlabel('Relative Velocity (km/s)')
                else:
                    self.ax.get_xaxis().set_ticks([])
                lbl = self.llist[self.llist['List']].name[idx]
                self.ax.text(0.01, 0.15, lbl, color=color, transform=self.ax.transAxes,
                             size='x-small', ha='left',va='center',backgroundcolor='w',bbox={'pad':0,'edgecolor':'none'})
                if self.flag_idlbl:
                    # Any lines inside?
                    mtw = np.where((line_wvobs > wvmnx[0]) & (line_wvobs<wvmnx[1]))[0]
                    for imt in mtw:
                        v = 3e5*(line_wvobs[imt]/wvobs - 1)
                        self.ax.text(v, 0.5, line_lbl[imt], color=color_model,backgroundcolor='w',
                            bbox={'pad':0,'edgecolor':'none'}, size='xx-small', rotation=90.,ha='center',va='center')

                # Analysis regions
                if np.sum(self.spec.mask) > 0.:
                    gdp = self.spec.mask==1
                    if len(gdp) > 0:
                        self.ax.scatter(velo[gdp],self.spec.flux[gdp],
                            marker='o',color=color,s=3.,alpha=0.5)

                # Reset window limits
                self.ax.set_ylim(self.psdict['ymnx'])
                self.ax.set_xlim(self.psdict['xmnx'])

                # Add line?
                if self.wrest == wrest:
                    self.ax.plot([self.vtmp]*2,self.psdict['ymnx'], '--',
                        color='red')

                # Components
                mtc = np.where(wrest == iwrest)[0]
                if len(mtc) > 0:
                    #QtCore.pyqtRemoveInputHook()
                    #xdb.set_trace()
                    #QtCore.pyqtRestoreInputHook()
                    for mt in mtc:
                        comp = components[mt]
                        #QtCore.pyqtRemoveInputHook()
                        #xdb.set_trace()
                        #QtCore.pyqtRestoreInputHook()
                        dvz = const.c.to('km/s')*(self.z-comp.zcomp)/(1+self.z)
                        if dvz.value < np.max(np.abs(self.psdict['xmnx'])):
                            if comp is self.parent.fiddle_widg.component:
                                lw = 1.5
                            else:
                                lw = 1.
                            # Plot
                            for vlim in comp.vlim:
                                self.ax.plot([vlim.value-dvz.value]*2,self.psdict['ymnx'], 
                                    '--', color='r',linewidth=lw)
                            self.ax.plot([-1.*dvz.value]*2,[1.0,1.05],
                                '-', color='grey',linewidth=lw)

                # Fonts
                xputils.set_fontsize(self.ax,6.)
        # Draw
        self.canvas.draw()
Exemple #38
0
def fig_mtlPDF_cuts(cos_halos=None, outfil = 'fig_mtlPDF_cuts.pdf',
                    qcut=1):
    """ Shows the metallicity PDF for various cuts
    Avoids 0 detection systems
    """
    # Read COS-Halos
    if cos_halos is None:
        cos_halos = load_ch()

    # Quality cut
    msk = [False]*len(cos_halos.cgm_abs)
    for ii,cgm_abs in enumerate(cos_halos.cgm_abs):
        # Cut on quality
        if chmtl.mtl_quality(cgm_abs) <= qcut:
            print('No constraint for {:s}'.format(cgm_abs.name))
            print('Skipping')
            continue
        msk[ii] = True
    mska = np.array(msk)

    # Init
    ZH_mnx = (-2., 1)

    # Start the plot
    pp = PdfPages(outfil)

    plt.figure(figsize=(5, 5))
    plt.clf()
    gs = gridspec.GridSpec(2, 2)

    for qq in range(4):
        ax = plt.subplot(gs[qq])
        if qq == 0:  # Mstar
            lbl = r'$\log \, M_*$'
            xval = getattr(cos_halos, 'stellar_mass')
            medx = 0
        elif qq == 1:  # sSFR
            lbl = 'sSFR'
            xval = getattr(cos_halos, 'ssfr')
            medx = 1e-11
        elif qq == 2:  # Rperp
            lbl = r'$R_\perp$'
            xval = getattr(cos_halos, 'rho').value
            medx = 0
        elif qq == 3:  # NHI
            lbl = r'$N_{\rm HI}$'
            #xval = getattr(cos_halos, 'NHI')
            xarr = getattr(cos_halos, 'NHIPDF')  # USE THE PDF
            xval = np.array([ixa.median for ixa in xarr])
            medx = 0

        # Stats (as needed)
        if medx == 0:
            medx = np.median(xval[mska])

        # Build PDFs
        lowPDF, hiPDF = None, None
        for ii, cgm_abs in enumerate(cos_halos.cgm_abs):
            if msk[ii] is False:
                continue
            # Sum the PDF
            if xval[ii] > medx:
                if hiPDF is None:
                    hiPDF = cgm_abs.igm_sys.metallicity
                else:
                    hiPDF = hiPDF + cgm_abs.igm_sys.metallicity
            else:
                if lowPDF is None:
                    lowPDF = cgm_abs.igm_sys.metallicity
                else:
                    lowPDF = lowPDF + cgm_abs.igm_sys.metallicity

        ax.set_xlim(ZH_mnx)
        lowPDF.normalize()
        hiPDF.normalize()

        # Giddy up
        lsz = 19.
        ax.bar(lowPDF.ZH-lowPDF.dZH/2., lowPDF.pdf_ZH, width=lowPDF.dZH, color='red', alpha=0.5)
        ax.bar(hiPDF.ZH-hiPDF.dZH/2., hiPDF.pdf_ZH, width=hiPDF.dZH, color='blue', alpha=0.5)
        ax.set_xlabel("[Z/H]", size=lsz)
        ax.set_ylabel("Normalized PDFs", size=lsz)

        # Label
        csz = 14.
        ax.text(0.05, 0.87, lbl, transform=ax.transAxes, color='black', size=csz, ha='left')
        #lbl2 = '({:d} systems)'.format(nsys)
        #ax.text(0.05, 0.75, lbl2, transform=ax.transAxes, color='black', size=csz, ha='left')
        # Axes
        ax.xaxis.set_major_locator(plt.MultipleLocator(1.))
        xputils.set_fontsize(ax, 13.)

    # End
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.,w_pad=0.1)
    pp.savefig()
    pp.close()
    plt.close()
Exemple #39
0
def pdf_1dspec(uvq, spec, pdf_fil, title=None, ymnx=None):
    '''
    Generate a 1D spec file

    Parameters:
    -----------
    uvq: QTable row
      From UVQ summary
    spec: Spectrum1D
      Spectrum to plot
    pdf_fil: string
      Name of the PDF file
    title: string
      Title for the plot
    '''
    # Import
    import matplotlib as mpl
    mpl.rcParams['font.family'] = 'stixgeneral'
    from matplotlib.backends.backend_pdf import PdfPages
    from matplotlib import pyplot as plt
    import matplotlib.gridspec as gridspec
    from xastropy.plotting import utils as xputils

    # b-spline for limits
    gd = np.where( (spec.sig > 0.) & (spec.flux > 0.))[0]
    try:
        xmnx = [np.min(spec.wavelength.value[gd]), np.max(spec.wavelength.value[gd])]
    except ValueError:
        if uvq['SCI_FILE'] in ['August2014/CAHA_none.fits']: # None file for CAHA stars
            ymnx = np.array([-0.05,1.])
    # Special
    if uvq['OBSV'] == 'CAHA':
        xmnx = (3800., 9000.)
        gd = np.where( (spec.sig > 0.) & (spec.flux > 0.) & 
            (spec.wavelength > xmnx[0]*u.AA))[0]
    elif uvq['instr'] == 'MagE':
        xmnx = (3300., 9000.)
        gd = np.where( (spec.sig > 0.) & (spec.flux > 0.) & 
            (spec.wavelength > xmnx[0]*u.AA))[0]
    elif uvq['instr'] == 'Kast':
        xmnx[1] = 7500. 
    elif uvq['instr'] == 'ESI':
        xmnx = (4200., 8000.)
        gd = np.where( (spec.sig > 0.) & (spec.flux > 0.) & 
            (spec.wavelength > xmnx[0]*u.AA))[0]
    if ymnx is None:
        ymnx = bspline_ymnx(spec,gd)

    yscl = 10.**(int(np.log10(ymnx[1])))

    # Start the plot
    #pp = PdfPages(pdf_fil)

    plt.figure(figsize=(8, 5))
    plt.clf()
    gs = gridspec.GridSpec(1, 1)
    ax = plt.subplot(gs[0,0])

    # Axes
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(1.))
    ax.yaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(1.))
    ax.set_xlim(xmnx)
    ax.set_ylim(ymnx/yscl)

    ax.set_xlabel(r'Wavelength ($\AA$)')
    ax.set_ylabel('Relative Flux')

    # Plot
    ax.plot(spec.wavelength, spec.flux/yscl, 'k-',drawstyle='steps-mid', linewidth=0.9)
    ax.plot(spec.wavelength, spec.sig/yscl, 'r:')

    # Title
    y0 = 0.92
    if title is not None:
        ax.text(0.5, y0, title, transform=ax.transAxes, size=18, color='blue',
               ha='center', bbox={'facecolor':'white', 'edgecolor':'white'})
    # Other data
    x1_lbl = 0.94
    yoff = 0.05
    ax.text(x1_lbl, y0, uvq['OBSV'], transform=ax.transAxes, size=14, color='black', ha='right')
    ax.text(x1_lbl, y0-yoff, uvq['instr'], transform=ax.transAxes, size=14, color='black', ha='right')
    ax.text(x1_lbl, y0-2*yoff, uvq['OBS_DATE'], transform=ax.transAxes, size=14, color='black',
        ha='right')
    ax.text(x1_lbl, y0-3*yoff, 'z={:0.3f}'.format(uvq['Z']), transform=ax.transAxes, size=14,
        color='black', ha='right')
    ax.text(x1_lbl, y0-4*yoff, r'$z_Q=$'+'{:d}'.format(uvq['Z_QUAL']), transform=ax.transAxes,
        size=14, color='black', ha='right')
    ax.text(x1_lbl, y0-5*yoff, r'$S_Q=$'+'{:d}'.format(uvq['SPEC_QUAL']), transform=ax.transAxes,
        size=14, color='black', ha='right')

    # Template
    #xdb.set_trace()
    zfil = os.getenv('UVQ_DATA')+'2D_Spectra/'+uvq['dbx_path']+'/'+uvq['ZASS_FIL']
    try:
        new_eigen = fits.open(zfil)[2].data
    except:
        pass
    else:
        rebin_wv2 = fits.open(zfil)[3].data
        sz_eigen = new_eigen.shape
        model_flux = np.dot(new_eigen.transpose(), uvq['THETA'][0:sz_eigen[0]])
        ax.plot(rebin_wv2*(1+uvq['Z']), model_flux/yscl, 'g-', linewidth=0.5, alpha=0.6)
        #xdb.set_trace()

    # Label a few lines 
    line_lbls = {1903.91: 'CIII]', 4341.69: r'H$\gamma$', 4862.70: r'H$\beta$', 
        5008.24: '[OIII]', 2799.40: 'MgII', 6564.63: r'H$\alpha$'}
    for key in line_lbls.keys():
        xplt = (1+uvq['Z'])*key
        if (xplt>xmnx[0]) & (xplt<xmnx[1]):
            ax.text((1+uvq['Z'])*key, 0.8*ymnx[1]/yscl, line_lbls[key], size=11, color='green', ha='center')

    # Font size
    xputils.set_fontsize(ax,15.)

    # Layout and save
    plt.tight_layout(pad=0.2,h_pad=0.,w_pad=0.1)
    plt.savefig(pdf_fil)
    #pp.savefig(bbox_inches='tight')
    #pp.close()
    plt.close()
    print('Wrote spectrum to {:s}'.format(pdf_fil))
Exemple #40
0
def q1422(outfil='Figures/q1422.pdf'):
    """ Series of plots on Q1422
    """
    q1422 = lsio.readspec(
        '/Users/xavier/Keck/HIRES/RedData/Q1422+2309/Q1422+2309.fits')

    axmnx = [
        [4000, 6000],
        [4900, 5500],
        [5100, 5300],
        [5150, 5250],
        [5190, 5220],
    ]
    aymnx = [
        [0., 7300],
        [0., 2000],
        [0., 1700],
        [0., 1100],
        [0., 1100],
    ]
    lw = 1.
    csz = 19.

    # Start the plot
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Loop
    for qq, xmnx in enumerate(axmnx):

        # Spectrum
        ax = plt.subplot(gs[0])
        ax.set_xlim(xmnx)
        ax.set_ylim(aymnx[qq])
        #ax.set_ylim(ymnx)
        ax.set_ylabel('Relative Flux')
        ax.set_xlabel("Wavelength (Ang)")

        ax.plot(q1422.wavelength, q1422.flux, 'k', linewidth=lw)

        #
        ax.text(0.05,
                0.9,
                'Keck/HIRES: Q1422+2309',
                color='blue',
                transform=ax.transAxes,
                size=csz,
                ha='left')  #, bbox={'facecolor':'white'})
        #
        xputils.set_fontsize(ax, 17.)
        # Layout and save
        plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
        plt.subplots_adjust(hspace=0)
        pp.savefig(bbox_inches='tight', transparent=True)
        plt.close()
    # Finish
    print('Writing {:s}'.format(outfil))
    pp.close()
Exemple #41
0
def dteff(outfil='Figures/dteff.pdf'):
    """ Differential teff (Lya)
    """
    # Load fN
    fN_model = FNModel.default_model()

    # teff
    cumul = []
    iwave = 1215.67 * (1 + 2.5)
    zem = 2.6
    teff_alpha = lyman_ew(iwave, zem, fN_model, cumul=cumul)
    print('teff = {:g}'.format(teff_alpha))

    dteff = cumul[1] - np.roll(cumul[1], 1)
    dteff[0] = dteff[1]  # Fix first value

    # Start the plot
    xmnx = (12, 22)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    #ax.set_ylim(ymnx)
    ax.set_ylabel(r'$d\tau_{\rm eff, \alpha}/d\log N$')
    ax.set_xlabel(r'$\log \, N_{\rm HI}$')

    lw = 2.
    ax.plot(cumul[0], dteff, 'k', linewidth=lw)

    # Label
    csz = 17
    ax.text(0.60,
            0.90,
            'f(N) from Prochaska+14',
            color='blue',
            transform=ax.transAxes,
            size=csz,
            ha='left')
    ax.text(0.60,
            0.80,
            'z=2.5',
            color='blue',
            transform=ax.transAxes,
            size=csz,
            ha='left')
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
Exemple #42
0
def obs_sawtooth(outfil='Figures/obs_sawtooth.pdf', all_tau=None, scl=1.):
    """ Sawtooth opacity
    """
    # SDSS
    hdu = fits.open(
        '/Users/xavier/paper/LLS/taueff/Analysis/stack_DR7_z3.92_z4.02.fits')
    sdss_fx = hdu[0].data
    sdss_wave = hdu[2].data
    # Telfer
    telfer = pyicq.get_telfer_spec()
    i1450 = np.argmin(np.abs(telfer.wavelength.value - 1450.))
    nrm = np.median(telfer.flux[i1450 - 5:i1450 + 5])
    telfer.flux = telfer.flux / nrm
    trebin = telfer.rebin(sdss_wave * u.AA)
    # Load fN
    fN_model = FNModel.default_model()
    fN_model.zmnx = (2., 4.1)  # extrapolate a bit
    # teff
    zem = 4.
    wave = np.arange(4500., 6200., 10)
    # Calculate
    if all_tau is None:
        all_tau = np.zeros_like(wave)
        for qq, iwave in enumerate(wave):
            all_tau[qq] = lyman_ew(iwave, zem, fN_model)
    # Flux attenuation
    trans = np.exp(-all_tau)

    ftrans = interp1d(wave, trans, fill_value=1., bounds_error=False)

    # Start the plot
    xmnx = (4500, 6200)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(0., 1.5)
    ax.set_ylabel('Relative Flux')
    ax.set_xlabel('Observed wavelength')

    lw = 2.
    # Data
    ax.plot(sdss_wave * (1 + zem),
            sdss_fx,
            'k',
            linewidth=lw,
            label='SDSS QSOs (z=4)')
    # Model
    model = trebin.flux * ftrans(sdss_wave * (1 + zem)) * scl
    ax.plot(sdss_wave * (1 + zem),
            model,
            'r',
            linewidth=lw,
            label='IGM+Telfer model')

    # Label
    csz = 17
    #ax.text(0.10, 0.10, 'SDSS quasar stack at z=4', color='black',
    #        transform=ax.transAxes, size=csz, ha='left')
    # Legend
    legend = plt.legend(loc='upper left',
                        scatterpoints=1,
                        borderpad=0.3,
                        handletextpad=0.3,
                        fontsize='large',
                        numpoints=1)
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
    return all_tau
def dla_deviation(outfil='Figures/dla_deviation.pdf'):
    """ Deviations from Voigt (Lee 2003)
    """
    # Wavelength array for my 'perfect' instrument
    wave = np.linspace(1140., 1290., 20000) * u.AA
    vel = (wave-1215.67*u.AA)/(1215.67*u.AA) * const.c.to('km/s')
    nu = (const.c/wave).to('Hz')

    # Lya line
    lya = AbsLine(1215.6700*u.AA)
    lya.attrib['N'] = 10.**(22)/u.cm**2
    lya.attrib['b'] = 30 * u.km/u.s
    lya.attrib['z'] = 0.

    # Lee
    sigmaT = (6.65e-29 * u.m**2).to('cm**2')  # Approximate!
    f_jk = 0.4162
    nu_jk = (const.c/lya.wrest).to('Hz')
    def eval_cross_Lee(nu):
        return sigmaT * (f_jk/2)**2 * (nu_jk/(nu-nu_jk))**2 * (1-1.792*(nu-nu_jk)/nu_jk)
    tau_lee = lya.attrib['N']*eval_cross_Lee(nu)
    flux_lee = np.exp(-1*tau_lee.value)
    # Start the plot
    xmnx = (-15000, 15000)
    ymnx = (0., 1.0)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1,1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(ymnx)
    ax.set_ylabel('Normalized Flux')
    ax.set_xlabel('Relative Velocity (km/s)') 

    f_voigt = ltav.voigt_from_abslines(wave, [lya])
    lw = 2
    ax.plot(vel, f_voigt.flux, 'k', linewidth=lw, 
        label=r'Voigt: $\log N_{\rm HI} = 22$')
    ax.plot(vel, flux_lee, 'r', linewidth=lw, 
        label=r'Lee2003: $\log N_{\rm HI} = 22$')

    # Legend
    legend = plt.legend(loc='lower left', scatterpoints=1, borderpad=0.3, 
        handletextpad=0.3, fontsize='large', numpoints=1)
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
def fig_mtlPDF_cuts(cos_halos=None, outfil='fig_mtlPDF_cuts.pdf', qcut=1):
    """ Shows the metallicity PDF for various cuts
    Avoids 0 detection systems
    """
    # Read COS-Halos
    if cos_halos is None:
        cos_halos = load_ch()

    # Quality cut
    msk = [False] * len(cos_halos.cgm_abs)
    for ii, cgm_abs in enumerate(cos_halos.cgm_abs):
        # Cut on quality
        if chmtl.mtl_quality(cgm_abs) <= qcut:
            print('No constraint for {:s}'.format(cgm_abs.name))
            print('Skipping')
            continue
        msk[ii] = True
    mska = np.array(msk)

    # Init
    ZH_mnx = (-2., 1)

    # Start the plot
    pp = PdfPages(outfil)

    plt.figure(figsize=(5, 5))
    plt.clf()
    gs = gridspec.GridSpec(2, 2)

    for qq in range(4):
        ax = plt.subplot(gs[qq])
        if qq == 0:  # Mstar
            lbl = r'$\log \, M_*$'
            xval = getattr(cos_halos, 'stellar_mass')
            medx = 0
        elif qq == 1:  # sSFR
            lbl = 'sSFR'
            xval = getattr(cos_halos, 'ssfr')
            medx = 1e-11
        elif qq == 2:  # Rperp
            lbl = r'$R_\perp$'
            xval = getattr(cos_halos, 'rho').value
            medx = 0
        elif qq == 3:  # NHI
            lbl = r'$N_{\rm HI}$'
            #xval = getattr(cos_halos, 'NHI')
            xarr = getattr(cos_halos, 'NHIPDF')  # USE THE PDF
            xval = np.array([ixa.median for ixa in xarr])
            medx = 0

        # Stats (as needed)
        if medx == 0:
            medx = np.median(xval[mska])

        # Build PDFs
        lowPDF, hiPDF = None, None
        for ii, cgm_abs in enumerate(cos_halos.cgm_abs):
            if msk[ii] is False:
                continue
            # Sum the PDF
            if xval[ii] > medx:
                if hiPDF is None:
                    hiPDF = cgm_abs.igm_sys.metallicity
                else:
                    hiPDF = hiPDF + cgm_abs.igm_sys.metallicity
            else:
                if lowPDF is None:
                    lowPDF = cgm_abs.igm_sys.metallicity
                else:
                    lowPDF = lowPDF + cgm_abs.igm_sys.metallicity

        ax.set_xlim(ZH_mnx)
        lowPDF.normalize()
        hiPDF.normalize()

        # Giddy up
        lsz = 19.
        ax.bar(lowPDF.ZH - lowPDF.dZH / 2.,
               lowPDF.pdf_ZH,
               width=lowPDF.dZH,
               color='red',
               alpha=0.5)
        ax.bar(hiPDF.ZH - hiPDF.dZH / 2.,
               hiPDF.pdf_ZH,
               width=hiPDF.dZH,
               color='blue',
               alpha=0.5)
        ax.set_xlabel("[Z/H]", size=lsz)
        ax.set_ylabel("Normalized PDFs", size=lsz)

        # Label
        csz = 14.
        ax.text(0.05,
                0.87,
                lbl,
                transform=ax.transAxes,
                color='black',
                size=csz,
                ha='left')
        #lbl2 = '({:d} systems)'.format(nsys)
        #ax.text(0.05, 0.75, lbl2, transform=ax.transAxes, color='black', size=csz, ha='left')
        # Axes
        ax.xaxis.set_major_locator(plt.MultipleLocator(1.))
        xputils.set_fontsize(ax, 13.)

    # End
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
    pp.savefig()
    pp.close()
    plt.close()
Exemple #45
0
def dla_vary_NHI(outfil='Figures/dla_vary_NHI.pdf'):
    """ DLA profiles with NHI varying
    """
    # Wavelength array for my 'perfect' instrument
    wave = np.linspace(1160., 1270., 20000) * u.AA
    vel = (wave - 1215.67 * u.AA) / (1215.67 * u.AA) * const.c.to('km/s')

    # Lya line
    lya = AbsLine(1215.6700 * u.AA)
    #lya.attrib['N'] = 10.**(13.6)/u.cm**2
    lya.attrib['b'] = 30 * u.km / u.s
    lya.attrib['z'] = 0.

    aNHI = [20.3, 21., 21.5, 22.]

    # Start the plot
    xmnx = (-10000, 10000)
    ymnx = (0., 1.0)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(ymnx)
    ax.set_ylabel('Normalized Flux')
    ax.set_xlabel('Relative Velocity (km/s)')

    lw = 1.5
    # Data
    for NHI in aNHI:
        lyai = copy.deepcopy(lya)
        lyai.attrib['N'] = 10**NHI / u.cm**2
        f_obsi = ltav.voigt_from_abslines(wave, [lyai])
        ax.plot(vel,
                f_obsi.flux,
                linewidth=lw,
                label=r'$\log N_{\rm HI} = $' + '{:0.2f}'.format(NHI))

    # Legend
    legend = plt.legend(loc='lower left',
                        scatterpoints=1,
                        borderpad=0.3,
                        handletextpad=0.3,
                        fontsize='large',
                        numpoints=1)
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
Exemple #46
0
def fig_images(outfil=None):

    from xastropy.obs import x_getsdssimg as xgs

    # Init COS-Halos sightline
    cos_halos = COSHalos()
    cos_halos.load_mega(skip_ions=True)
    #xdb.set_trace()

    # Start the plot
    if outfil is None:
        outfil = 'fig_coshalo_images.pdf'
    pp = PdfPages(outfil)

    dx = 0.2
    dy = 0.55
    imsize = 1.2

    for ss in range(5):
        fig = plt.figure(figsize=(8, 5))
        fig.clf()
        # Setup for dark
        xpsimp.dark_bkgd(plt)
        gs = gridspec.GridSpec(1, 1)

        # Axes
        ax = plt.subplot(gs[0, 0])
        ax.set_xlim(9.4, 11.7)
        #ax.xaxis.set_major_locator(plt.MultipleLocator(300.))
        ax.set_ylim(-13, -9)
        ax.set_ylabel('sSFR')
        ax.set_xlabel('log M*')

        # Plot
        if ss == 0:
            mstar = [
                cgm_abs.galaxy.stellar_mass for cgm_abs in cos_halos.cgm_abs
            ]
            sSFR = [
                np.log10(cgm_abs.galaxy.sfr[1]) - cgm_abs.galaxy.stellar_mass
                for cgm_abs in cos_halos.cgm_abs
            ]
            ax.scatter(mstar, sSFR)
        elif ss == 1:  # Show our first one
            cgm_abs = cos_halos[('J0950+4831', '177_27')]
            img, oBW = xgs.getimg(cgm_abs.galaxy.coord.ra.deg,
                                  cgm_abs.galaxy.coord.dec.deg,
                                  imsize=imsize)
            # Figure out placement
            ximg = cgm_abs.galaxy.stellar_mass
            yimg = np.log10(
                cgm_abs.galaxy.sfr[1]) - cgm_abs.galaxy.stellar_mass
            # Show
            ax.imshow(img,
                      extent=(ximg - dx, ximg + dx, yimg - dy, yimg + dy),
                      aspect=dx / dy)
        elif ss == 2:  # Show two
            cgm_list = [('J0950+4831', '177_27'), ('J1245+3356', '236_36')]
            for icgm in cgm_list:
                cgm_abs = cos_halos[icgm]
                img, oBW = xgs.getimg(cgm_abs.galaxy.coord.ra.deg,
                                      cgm_abs.galaxy.coord.dec.deg,
                                      imsize=imsize)
                # Figure out placement
                ximg = cgm_abs.galaxy.stellar_mass
                yimg = np.log10(
                    cgm_abs.galaxy.sfr[1]) - cgm_abs.galaxy.stellar_mass
                # Show
                ax.imshow(img,
                          extent=(ximg - dx, ximg + dx, yimg - dy, yimg + dy),
                          aspect=dx / dy)
        elif ss >= 3:  # Show half
            if ss == 3:
                iend = 20
            else:
                iend = -1
            for cgm_abs in cos_halos.cgm_abs[0:iend]:
                img, oBW = xgs.getimg(cgm_abs.galaxy.coord.ra.deg,
                                      cgm_abs.galaxy.coord.dec.deg,
                                      imsize=1.2)
                # Figure out placement
                ximg = cgm_abs.galaxy.stellar_mass
                yimg = np.log10(
                    cgm_abs.galaxy.sfr[1]) - cgm_abs.galaxy.stellar_mass
                # Show
                scl = 2.
                ax.imshow(img,
                          extent=(ximg - dx / scl, ximg + dx / scl,
                                  yimg - dy / scl, yimg + dy / scl),
                          aspect=dx / dy)

        xputils.set_fontsize(ax, 17.)
        # Write
        fig.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
        pp.savefig()
        plt.close()

    # Finish
    print('tlk_coshalos: Wrote {:s}'.format(outfil))
    pp.close()
Exemple #47
0
def dla_deviation(outfil='Figures/dla_deviation.pdf'):
    """ Deviations from Voigt (Lee 2003)
    """
    # Wavelength array for my 'perfect' instrument
    wave = np.linspace(1140., 1290., 20000) * u.AA
    vel = (wave - 1215.67 * u.AA) / (1215.67 * u.AA) * const.c.to('km/s')
    nu = (const.c / wave).to('Hz')

    # Lya line
    lya = AbsLine(1215.6700 * u.AA)
    lya.attrib['N'] = 10.**(22) / u.cm**2
    lya.attrib['b'] = 30 * u.km / u.s
    lya.attrib['z'] = 0.

    # Lee
    sigmaT = (6.65e-29 * u.m**2).to('cm**2')  # Approximate!
    f_jk = 0.4162
    nu_jk = (const.c / lya.wrest).to('Hz')

    def eval_cross_Lee(nu):
        return sigmaT * (f_jk /
                         2)**2 * (nu_jk /
                                  (nu - nu_jk))**2 * (1 - 1.792 *
                                                      (nu - nu_jk) / nu_jk)

    tau_lee = lya.attrib['N'] * eval_cross_Lee(nu)
    flux_lee = np.exp(-1 * tau_lee.value)
    # Start the plot
    xmnx = (-15000, 15000)
    ymnx = (0., 1.0)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(ymnx)
    ax.set_ylabel('Normalized Flux')
    ax.set_xlabel('Relative Velocity (km/s)')

    f_voigt = ltav.voigt_from_abslines(wave, [lya])
    lw = 2
    ax.plot(vel,
            f_voigt.flux,
            'k',
            linewidth=lw,
            label=r'Voigt: $\log N_{\rm HI} = 22$')
    ax.plot(vel,
            flux_lee,
            'r',
            linewidth=lw,
            label=r'Lee2003: $\log N_{\rm HI} = 22$')

    # Legend
    legend = plt.legend(loc='lower left',
                        scatterpoints=1,
                        borderpad=0.3,
                        handletextpad=0.3,
                        fontsize='large',
                        numpoints=1)
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
Exemple #48
0
def fig_abs_gallery(wrest=None,
                    lbl=None,
                    outfil=None,
                    cos_halos=None,
                    passback=False,
                    axes_flg=0):
    # import tlk_coshalos as tch
    # reload(tch)
    # cos_halos = tch.fig_abs_gallery(passback=True)
    '''Gallery of absorption lines
    Default is M* vs. sSFR
      But you can do rho vs. M* too
    axes_flg: int, optional
      0: M* vs. sSFR
      1: rho vs. M*
    '''
    # Linelist
    llist = lll.LineList('Strong')
    if wrest is None:
        wrest = 1215.670 * u.AA
    Zion = (llist[wrest]['Z'], llist[wrest]['ion'])
    if lbl is None:
        lbl = r'HI Ly$\alpha$'
    if outfil is None:
        outfil = 'fig_HI_gallery.pdf'
    # Init COS-Halos (slow)
    if cos_halos is None:
        cos_halos = COSHalos()
        cos_halos.load_mega()  #skip_ions=True)
        if passback:
            return cos_halos

    if axes_flg == 0:
        xmnx = (9.4, 11.7)
        ymnx = (-13., -9.)
    elif axes_flg == 1:
        ymnx = (9.4, 11.7)  # log Msun
        xmnx = (15., 163)  # kpc
    vmnx = (-600., 600.)  # km/s
    wbox = {'facecolor': 'white', 'edgecolor': 'white'}
    lclr = 'blue'

    # To help with looping
    def sngl_abs(ax,
                 field_gal,
                 wbox=wbox,
                 lclr=lclr,
                 vmnx=vmnx,
                 xmnx=xmnx,
                 ymnx=ymnx,
                 cos_halos=cos_halos,
                 show_xylbl=True,
                 srect=0.2,
                 show_ewlbl=True,
                 lw=1.3,
                 axes_flg=axes_flg):
        #
        cgm_abs = cos_halos[field_gal]
        if axes_flg == 0:
            xplt = cgm_abs.galaxy.stellar_mass
            yplt = np.log10(
                cgm_abs.galaxy.sfr[1]) - cgm_abs.galaxy.stellar_mass
        elif axes_flg == 1:
            yplt = cgm_abs.galaxy.stellar_mass
            xplt = cgm_abs.rho.value
        # Spec
        spec = cos_halos.load_bg_cos_spec(field_gal, wrest)
        velo = spec.relative_vel(wrest * (cgm_abs.galaxy.z + 1))
        # EW
        data = cgm_abs.abs_sys.ions[Zion]
        itrans = np.where(np.abs(data['LAMBDA'] - wrest.value) < 1e-3)[0]
        if len(itrans) == 0:
            print('No measurement of {:g} for {:s} {:s}'.format(
                wrest, field_gal[0], field_gal[1]))
            return
        EW = data['WREST'][itrans][0] * u.AA / 1e3
        sigEW = data['SIGWREST'][itrans][0] * u.AA / 1e3
        if sigEW <= 0.:  # Something must be wrong
            return
        if EW > 3 * sigEW:
            sclr = 'k'
        else:
            sclr = 'r'
        #
        xrect = (xplt - xmnx[0]) / (xmnx[1] - xmnx[0])
        yrect = (yplt - ymnx[0]) / (ymnx[1] - ymnx[0])
        rect = [xrect, yrect, srect, srect]
        axsp = xpsimp.add_subplot_axes(ax, rect)  #,axisbg=axisbg)
        axsp.set_xlim(vmnx)
        axsp.set_ylim(-0.1, 1.3)
        if show_xylbl:
            axsp.set_xlabel('Relative Velocity (km/s)', fontsize=9.)
            axsp.set_ylabel('Normalized Flux', fontsize=9.)
        # Plot
        axsp.plot(velo, spec.flux, sclr, drawstyle='steps', lw=lw)
        # Label
        #llbl = (r'$W_\lambda = $'+'{:0.2f} A \n'.format(EW.value)+
        #    '$z=${:.3f}\n'.format(cgm_abs.galaxy.z)+
        #    r'$\rho=$'+'{:d}kpc'.format(int(np.round(cgm_abs.rho.to('kpc').value))))
        if show_ewlbl:
            llbl = r'$W_\lambda = $' + '{:0.2f} A'.format(EW.value)
            axsp.text(-300.,
                      1.1,
                      llbl,
                      ha='left',
                      fontsize=7.,
                      color=lclr,
                      bbox=wbox)  #multialignment='left')

    # Start the plot
    pp = PdfPages(outfil)

    if axes_flg == 0:
        loop = range(4)
    else:
        loop = range(3, 4)

    for ss in loop:
        plt.figure(figsize=(8, 5))
        plt.clf()
        gs = gridspec.GridSpec(1, 1)

        # Axes
        ax = plt.subplot(gs[0, 0])
        ax.set_xlim(xmnx)
        ax.set_ylim(ymnx)
        if axes_flg == 0:
            ax.set_ylabel('sSFR')
            ax.set_xlabel('log M*')
            ax.text(9.75, -12., lbl, color=lclr, fontsize=21.)
        elif axes_flg == 1:
            ax.set_ylabel('log M*')
            ax.set_xlabel('Impact Parameter (kpc)')
            ax.text(40., 11.5, lbl, color=lclr, fontsize=21.)
        #ax.xaxis.set_major_locator(plt.MultipleLocator(300.))

        #
        if ss == 0:  # Single system
            field_gal = ('J0950+4831', '177_27')
            sngl_abs(ax, field_gal)
        elif ss == 1:  # Two systems
            cgm_list = [('J0950+4831', '177_27'), ('J1245+3356', '236_36')]
            for field_gal in cgm_list:
                sngl_abs(ax, field_gal)
        elif ss > 1:  # Half systems
            if ss == 2:
                iend = 20
            else:
                iend = -1
            for cgm_abs in cos_halos.cgm_abs[0:iend]:
                field_gal = (cgm_abs.field, cgm_abs.gal_id)
                sngl_abs(ax,
                         field_gal,
                         show_xylbl=False,
                         srect=0.1,
                         show_ewlbl=False,
                         lw=0.5)
        else:
            pass

        xputils.set_fontsize(ax, 17.)
        # Write
        plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
        pp.savefig()
        plt.close()

    # Finish
    print('tlk_coshalos: Wrote {:s}'.format(outfil))
    pp.close()
def mfp_spec(outfil='Figures/mfp_spec.pdf', all_tau=None, scl=1.):
    """ Stacked spectrum for MFP
    """
    # SDSS
    zq = 4.
    hdu = fits.open('/Users/xavier/paper/LLS/taueff/Analysis/stack_DR7_z3.92_z4.02.fits')
    sdss_fx = hdu[0].data
    sdss_wave = hdu[2].data
    zem = 4.

    # Start the plot
    xmnx = (800, 1000)
    ymnx = (0., 1.0)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1,1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(ymnx)
    ax.set_ylabel('Relative Flux')
    ax.set_xlabel('Rest Wavelength (Ang)')

    lw = 1.5
    # Data
    ax.plot(sdss_wave, sdss_fx, 'k', linewidth=lw, label='SDSS QSOs (z=4)')

    # Label
    xexp = 860.
    headl = 6.
    ax.plot([911.7]*2, ymnx, '--', color='red', linewidth=1.5)
    ax.arrow(911.7, 0.6, xexp-911.7+headl, 0., linewidth=2,
        head_width=0.03, head_length=headl, fc='blue', ec='blue')
    csz = 19.
    ax.text(890., 0.63, r'r = $\lambda_{\rm mfp}$', color='blue', size=csz,
        ha='center')

    # exp(-1)
    y1 = 0.43
    y2 = np.exp(-1)*y1
    yplt = (y1+y2)/2.
    yerr = (y2-y1)/2.
    ax.errorbar([xexp], [yplt], yerr=yerr, color='green', linewidth=2,
        capthick=2)
    ax.plot([xexp,911.7], [y1]*2, ':', color='green', linewidth=2)
    ax.text(855., yplt, 'exp(-1)', color='green', size=csz, ha='right')

    #
    ax.text(0.05, 0.90, 'SDSS QSO stack (z=4)', color='black',
            transform=ax.transAxes, size=csz, ha='left') 
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
    return all_tau
Exemple #50
0
def fig_experiment(outfil=None):

    # Init COS-Halos sightline
    cos_halos = COSHalos()
    cos_halos.load_single(('J0950+4831', '177_27'))
    cgm_abs = cos_halos.cgm_abs[0]
    print('zem = {:g}'.format(cgm_abs.abs_sys.zem))

    # ########################################
    # Finder (out of order to avoid PDF issues)
    #finder.main([cgm_abs.name, cgm_abs.galaxy.coord], imsize=2.*u.arcmin, show_circ=False)

    lclr = 'blue'

    # Start the plot
    if outfil is None:
        outfil = 'fig_experiment.pdf'
    pp = PdfPages(outfil)

    # Full QSO spectrum
    spec_fil = os.getenv(
        'DROPBOX_DIR'
    ) + '/COS-Halos/Targets/J0950+4831/Data/J0950+4831_nbin6_coadd.fits'
    spec = lsio.readspec(spec_fil)
    xmnx = (1135., 1750.)
    ymnx = (-0.0002, 0.0106)
    for ss in range(2):
        plt.figure(figsize=(8, 5))
        plt.clf()
        gs = gridspec.GridSpec(1, 1)

        # Axes
        ax = plt.subplot(gs[0, 0])
        #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
        #ax.xaxis.set_major_locator(plt.MultipleLocator(1.))
        #ax.get_xaxis().get_major_formatter().set_useOffset(False)
        ax.set_xlim(1135., 1750.)
        ax.set_ylim(-0.0002, 0.0106)
        ax.set_ylabel('Relative Flux')
        ax.set_xlabel(r'Wavelength ($\AA$)')

        # Zero line
        ax.plot(xmnx, (0., 0.), 'g--')

        # Data
        ax.plot(spec.dispersion, spec.flux, 'k')
        ax.plot(spec.dispersion, spec.sig, 'r:')

        if ss > 0:
            ax.fill_between([1455., 1490.], [ymnx[0]] * 2, [ymnx[1]] * 2,
                            color='blue',
                            alpha=0.3)
        # Label
        ax.text(1500.,
                0.008,
                cgm_abs.field,
                ha='left',
                fontsize=21.,
                color=lclr)

        # Fonts
        xputils.set_fontsize(ax, 17.)

        # Write
        plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
        pp.savefig()
        plt.close()

    # Lya spec
    for ss in range(3):

        plt.figure(figsize=(8, 5))
        plt.clf()
        gs = gridspec.GridSpec(1, 1)

        # Axes
        if ss == 0:
            spec = cos_halos.load_bg_cos_spec(0, 1215.6700 * u.AA)
            wvmnx = np.array([1455., 1490.]) * u.AA
            scl_wv = 1.
        elif ss == 1:
            scl_wv = (1 + cgm_abs.galaxy.z)
        elif ss == 2:
            spec = cos_halos.load_bg_cos_spec(0, 1025.7222 * u.AA)
            scl_wv = (1 + cgm_abs.galaxy.z)
            wvmnx = np.array([1015., 1037.]) * u.AA * scl_wv  # convoluted, yes

        ax = plt.subplot(gs[0, 0])
        #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
        #ax.xaxis.set_major_locator(plt.MultipleLocator(1.))
        #ax.get_xaxis().get_major_formatter().set_useOffset(False)
        ax.set_xlim(wvmnx.value / scl_wv)
        ax.set_ylim(-0.1, 1.3)
        ax.set_ylabel('Normalized Flux')

        # Zero line
        ax.plot(wvmnx.value / scl_wv, (0., 0.), 'g--')

        # Data
        ax.plot(spec.dispersion / scl_wv, spec.flux, 'k')
        ax.plot(spec.dispersion / scl_wv, spec.sig, 'r:')

        # Label
        if ss == 0:
            ax.set_xlabel(r'Wavelength ($\AA$)')
            ax.text(1480.,
                    0.4,
                    cgm_abs.field,
                    ha='left',
                    fontsize=21.,
                    color=lclr)
        elif ss == 1:
            ax.set_xlabel(r'Rest Wavelength ($\AA$)')
            ax.text(1220.,
                    0.4,
                    r'HI Ly$\alpha$' + ' \n ' +
                    r'$z=${:0.4f}'.format(cgm_abs.galaxy.z),
                    ha='left',
                    fontsize=21.,
                    multialignment='center',
                    color=lclr)
        elif ss == 2:
            ax.set_xlabel(r'Rest Wavelength ($\AA$)')
            ax.text(1017.,
                    0.4,
                    r'HI Ly$\beta$' + ' \n ' +
                    r'$z=${:0.4f}'.format(cgm_abs.galaxy.z),
                    ha='left',
                    fontsize=21.,
                    multialignment='center',
                    color=lclr)

        # Fonts
        xputils.set_fontsize(ax, 17.)

        # Write
        plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
        pp.savefig()
        plt.close()

    # ########################################
    # Galaxy spectrum
    plt.figure(figsize=(8, 5))
    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Load
    spec = cos_halos.load_gal_spec(0)
    # Axes
    ax = plt.subplot(gs[0, 0])
    ax.set_xlim(4000., 8000.)
    ax.set_ylim(-0.1, 25.)
    ax.set_xlabel(r'Wavelength ($\AA$)')
    ax.set_ylabel('Relative Flux')
    # Velo
    ax.plot(spec.dispersion, spec.flux, 'k')  #, lw=1.3)
    ax.plot(spec.dispersion, spec.sig, 'r:')  #, lw=1.3)
    # Label
    #ax.text(-800., 0.2, lbl, ha='left', fontsize=21., color=lclr)
    # Fonts
    xputils.set_fontsize(ax, 17.)
    # Write
    plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
    pp.savefig()
    plt.close()

    # ########################################
    # Simple HI stack plot
    trans = np.array([1215.6701, 1025.7223]) * u.AA
    lbls = [r'HI Ly$\alpha$', r'HI Ly$\beta$']

    plt.figure(figsize=(8, 5))
    plt.clf()
    gs = gridspec.GridSpec(2, 1)

    for qq, itran, lbl in zip(range(len(trans)), trans, lbls):
        # Load
        spec = cos_halos.load_bg_cos_spec(0, itran)
        # Axes
        ax = plt.subplot(gs[qq, 0])
        ax.set_xlim(-1000., 1000.)
        ax.set_ylim(-0.1, 1.3)
        ax.set_ylabel('Normalized Flux')
        if qq == 0:
            ax.xaxis.set_ticklabels([])
        else:
            ax.set_xlabel('Relative Velocity (km/s)')
        # Velo
        velo = spec.relative_vel(itran * (cgm_abs.galaxy.z + 1))
        ax.plot(velo, spec.flux, 'k', drawstyle='steps', lw=1.3)
        # Label
        ax.text(-800., 0.2, lbl, ha='left', fontsize=21., color=lclr)
        # Fonts
        xputils.set_fontsize(ax, 17.)
    # Write
    plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
    pp.savefig()
    plt.close()

    # ########################################
    # Greater stack plot
    trans = np.array([
        1215.6701, 1025.7223, 2852.9642, 2803.5315, 1083.9937, 1206.5,
        1393.755, 1037.6167
    ]) * u.AA
    lbls = [
        r'HI Ly$\alpha$', r'HI Ly$\beta$', 'MgI 2852', 'MgII 2796', 'NII 1083',
        'SiIII 1206', 'SiIV 1393', 'OVI 1037'
    ]

    plt.figure(figsize=(8, 5))
    plt.clf()
    gs = gridspec.GridSpec(2, 4)
    xmnx = (-500., 500.)
    ymnx = (-0.1, 1.3)

    wbox = {'facecolor': 'white', 'edgecolor': 'white'}
    for qq, itran, lbl in zip(range(len(trans)), trans, lbls):
        # Load
        spec = cos_halos.load_bg_cos_spec(0, itran)
        # Axes
        ax = plt.subplot(gs[qq % 2, qq // 2])
        ax.set_xlim(xmnx)
        ax.xaxis.set_major_locator(plt.MultipleLocator(300.))
        ax.set_ylim(ymnx)
        if qq % 2 == 0:
            ax.xaxis.set_ticklabels([])
        if qq < 2:
            ax.set_ylabel('Normalized Flux')
        else:
            ax.yaxis.set_ticklabels([])
        #if qq == 3:
        #    ax.set_xlabel('Relative Velocity (km/s)')
        # Velo
        velo = spec.relative_vel(itran * (cgm_abs.galaxy.z + 1))
        ax.plot(velo, spec.flux, 'k', drawstyle='steps', lw=1.3)
        ax.plot([0., 0.], ymnx, 'g:')
        # Label
        ax.text(10., 1.15, lbl, ha='left', fontsize=15., color=lclr, bbox=wbox)
        # Fonts
        xputils.set_fontsize(ax, 17.)
    # Write
    plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
    pp.savefig()
    plt.close()

    # Finish
    print('tlk_coshalos: Wrote {:s}'.format(outfil))
    pp.close()
Exemple #51
0
def fig_boss_x_vs_pca(outfil=None, boss_fil=None, flg=0):
    '''
    flg = 0:  Redshift
    flg = 1:  imag
    '''

    # Todo
    #   Include NHI on the label
    # Imports

    # Read PCA FITS table
    if boss_fil is None:
        boss_fil = 'BOSS_DR10Lya_PCA_values_nocut.fits.gz'
    hdu = fits.open(boss_fil)
    pca_coeff = hdu[1].data

    # Read BOSS catalog table
    boss_cat_fil = os.environ.get(
        'BOSSPATH') + '/DR10/BOSSLyaDR10_cat_v2.1.fits.gz'
    bcat_hdu = fits.open(boss_cat_fil)
    t_boss = bcat_hdu[1].data
    #xdb.set_trace()
    if flg == 0:
        xparm = t_boss['z_pipe']
        xmnx = [2., 4.]
        xlbl = str(r'$z_{\rm QSO}$')
    elif flg == 1:
        tmp = t_boss['PSFMAG']
        xparm = tmp[:, 3]  # i-band mag
        xlbl = str('i mag')
        xmnx = [17., 22.5]
    else:
        raise ValueError('fig_boss_x_vs_pca: flg={:d} not allowed'.format(flg))

    # Initialize
    #if 'xmnx' not in locals():
    #    xmnx = (17.0, 20.4)
    ymnx = ((-0.02, 0.3), (-0.2, 0.4), (-0.2, 0.5), (-0.2, 0.4))

    ms = 1.  # point size
    scl = 100.

    # Start the plot
    if outfil != None:
        pp = PdfPages(outfil)

    plt.figure(figsize=(4, 4))
    plt.clf()
    gs = gridspec.GridSpec(2, 2)

    # Looping
    for ii in range(4):

        # Axis
        ax = plt.subplot(gs[ii])
        #ax = plt.subplot(gs[ii//2,ii%2])

        ylbl = str('PCA' + str(ii))

        # Labels
        ax.set_xlabel(xlbl)
        ax.set_ylabel(ylbl)

        # Data

        # Values
        #xdb.set_trace()
        ax.hist2d(xparm,
                  scl * pca_coeff[ylbl],
                  bins=100,
                  norm=LogNorm(),
                  range=[xmnx, [ymnx[ii][0], ymnx[ii][1]]])

        # Font size
        xputils.set_fontsize(ax, 8.)

    # Layout and save
    plt.tight_layout(pad=0.2, h_pad=0.1, w_pad=0.25)
    if outfil != None:
        pp.savefig(bbox_inches='tight')
        pp.close()
    else:
        plt.show()
def evolving_forest(outfil='Figures/evolving_forest.pdf'):
    """ Show varying IGM transmission
    """
    hdlls_path = '/Users/xavier/paper/LLS/Optical/Data/DR1/Spectra/'
    esi_path = '/Users/xavier/Keck/ESI/RedData/'
    hst_path = '/Users/xavier/HST/Cycle23/z1IGM/Archive/PG1206+459/'
    dat_files = [
                hdlls_path+'HD-LLS_J212329.50-005052.9_HIRES.fits',
                hdlls_path+'HD-LLS_J020951.10-000513.0_HIRES.fits',
                hdlls_path+'HD-LLS_J113621.00+005021.0_MIKE.fits',
                hdlls_path+'HD-LLS_J094932.27+033531.7_MIKE.fits',
                esi_path+'PSS0134+3307/PSS0134+3307_f.fits',
                esi_path+'J0831+4046/J0831+4046a_f.fits',
                esi_path+'J1132+1209/J1132+1209a_f.fits',
                esi_path+'J1148+5251/SDSSJ1148+5251_stack.fits',
                hdlls_path+'HD-LLS_J212329.50-005052.9_HIRES.fits',
                hst_path+'PG1206+459_E230M_f.fits',
                '/Users/xavier/MLSS/data/3C273/STIS/E140M/3C273_STIS_E140M_F.fits',
                ]
    conti_fil = '/Users/xavier/MLSS/data/3C273/STIS/E140M/3C273_STIS_E140M_c.fits'
    conti_3c273 = fits.open(conti_fil)[0].data
    lbls = [
            'Keck/HIRES: J2123-0050',
            'Keck/HIRES: J0209-0005',
            'Magellan/MIKE: J1136+0050',
            'Magellan/MIKE: J0949+0335',
            'Keck/ESI: PSS0134+3307',
            'Keck/ESI: J0831+4046',
            'Keck/ESI: J1132+1209',
            'Keck/ESI: J1148+5251',
            'Keck/HIRES: J2123-0050',
            'HST/STIS: PG1206+459',
            'HST/STIS: 3C273',
            ]
    zems = [2.26, 2.86, 3.43, 4.05, 4.52, 4.89, 5.17, 6.4, 2.26, 1.16, 0.17]
    xrest = np.array([1080, 1200.])
    ymnx = [-0.1, 1.1]

    lw = 1.
    csz = 19.

    # Start the plot
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1,1)

    # Loop
    for qq, lbl in enumerate(lbls):

        spec = lsio.readspec(dat_files[qq])
        if lbl == 'HST/STIS: 3C273':
            spec.co = conti_3c273
            spec.normed = True

        # Spectrum
        ax = plt.subplot(gs[0])
        ax.set_xlim(xrest*(1+zems[qq])/1215.67 - 1)
        ax.set_ylim(ymnx) 
        ax.set_ylabel('Normalized Flux')
        ax.set_xlabel(r'Redshift of Ly$\alpha$')


        ax.plot(spec.wavelength.value/1215.6701 - 1, spec.flux, 'k', linewidth=lw)

        # 
        ax.text(0.05, 0.95, lbl+' zem={:0.1f}'.format(zems[qq]), color='blue',
            transform=ax.transAxes, size=csz, ha='left', bbox={'facecolor':'white'})
        #
        xputils.set_fontsize(ax, 17.)
        # Layout and save
        plt.tight_layout(pad=0.2,h_pad=0.0,w_pad=0.4)
        plt.subplots_adjust(hspace=0)
        pp.savefig(bbox_inches='tight', transparent=True)
        plt.close()
    # Finish
    print('Writing {:s}'.format(outfil))
    pp.close()
Exemple #53
0
def evolving_forest(outfil='Figures/evolving_forest.pdf'):
    """ Show varying IGM transmission
    """
    hdlls_path = '/Users/xavier/paper/LLS/Optical/Data/DR1/Spectra/'
    esi_path = '/Users/xavier/Keck/ESI/RedData/'
    hst_path = '/Users/xavier/HST/Cycle23/z1IGM/Archive/PG1206+459/'
    dat_files = [
        hdlls_path + 'HD-LLS_J212329.50-005052.9_HIRES.fits',
        hdlls_path + 'HD-LLS_J020951.10-000513.0_HIRES.fits',
        hdlls_path + 'HD-LLS_J113621.00+005021.0_MIKE.fits',
        hdlls_path + 'HD-LLS_J094932.27+033531.7_MIKE.fits',
        esi_path + 'PSS0134+3307/PSS0134+3307_f.fits',
        esi_path + 'J0831+4046/J0831+4046a_f.fits',
        esi_path + 'J1132+1209/J1132+1209a_f.fits',
        esi_path + 'J1148+5251/SDSSJ1148+5251_stack.fits',
        hdlls_path + 'HD-LLS_J212329.50-005052.9_HIRES.fits',
        hst_path + 'PG1206+459_E230M_f.fits',
        '/Users/xavier/MLSS/data/3C273/STIS/E140M/3C273_STIS_E140M_F.fits',
    ]
    conti_fil = '/Users/xavier/MLSS/data/3C273/STIS/E140M/3C273_STIS_E140M_c.fits'
    conti_3c273 = fits.open(conti_fil)[0].data
    lbls = [
        'Keck/HIRES: J2123-0050',
        'Keck/HIRES: J0209-0005',
        'Magellan/MIKE: J1136+0050',
        'Magellan/MIKE: J0949+0335',
        'Keck/ESI: PSS0134+3307',
        'Keck/ESI: J0831+4046',
        'Keck/ESI: J1132+1209',
        'Keck/ESI: J1148+5251',
        'Keck/HIRES: J2123-0050',
        'HST/STIS: PG1206+459',
        'HST/STIS: 3C273',
    ]
    zems = [2.26, 2.86, 3.43, 4.05, 4.52, 4.89, 5.17, 6.4, 2.26, 1.16, 0.17]
    xrest = np.array([1080, 1200.])
    ymnx = [-0.1, 1.1]

    lw = 1.
    csz = 19.

    # Start the plot
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Loop
    for qq, lbl in enumerate(lbls):

        spec = lsio.readspec(dat_files[qq])
        if lbl == 'HST/STIS: 3C273':
            spec.co = conti_3c273
            spec.normed = True

        # Spectrum
        ax = plt.subplot(gs[0])
        ax.set_xlim(xrest * (1 + zems[qq]) / 1215.67 - 1)
        ax.set_ylim(ymnx)
        ax.set_ylabel('Normalized Flux')
        ax.set_xlabel(r'Redshift of Ly$\alpha$')

        ax.plot(spec.wavelength.value / 1215.6701 - 1,
                spec.flux,
                'k',
                linewidth=lw)

        #
        ax.text(0.05,
                0.95,
                lbl + ' zem={:0.1f}'.format(zems[qq]),
                color='blue',
                transform=ax.transAxes,
                size=csz,
                ha='left',
                bbox={'facecolor': 'white'})
        #
        xputils.set_fontsize(ax, 17.)
        # Layout and save
        plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
        plt.subplots_adjust(hspace=0)
        pp.savefig(bbox_inches='tight', transparent=True)
        plt.close()
    # Finish
    print('Writing {:s}'.format(outfil))
    pp.close()
Exemple #54
0
def fig_boss_pca_coeff(outfil=None, boss_fil=None, scl=100.):

    # Todo
    #   Include NHI on the label
    # Imports

    # Read FITS table
    if boss_fil is None:
        boss_fil = 'BOSS_DR10Lya_PCA_values_nocut.fits.gz'
    hdu = fits.open(boss_fil)
    pca_coeff = hdu[1].data
    #xdb.set_trace()

    # Initialize
    #if 'xmnx' not in locals():
    #    xmnx = (17.0, 20.4)
    #ymnx = ((-1.9, 2.3),
    #        (-1.9, 1.4),
    #        (-1.1, 1.4),
    #        (-2.1, 0.9))

    ms = 1.  # point size

    allxi = [0, 0, 0, 1, 1, 2]
    allyi = [1, 2, 3, 2, 3, 3]

    rngi = ([-0.02, 0.3], [-0.2, 0.4], [-0.2, 0.5], [-0.2, 0.4])

    # Start the plot
    if outfil != None:
        pp = PdfPages(outfil)

    plt.figure(figsize=(5.5, 4))
    plt.clf()
    gs = gridspec.GridSpec(2, 3)

    # Looping
    for ii in range(6):

        # Axis
        ax = plt.subplot(gs[ii])
        #ax = plt.subplot(gs[ii//2,ii%2])
        '''
        ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
        ax.xaxis.set_major_locator(plt.MultipleLocator(1.))
        #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.5))
        ax.yaxis.set_major_locator(plt.MultipleLocator(0.5))
        ax.set_xlim(xmnx)
        ax.set_ylim((-0.5, 0.5))
        '''

        xi = allxi[ii]
        xlbl = str('PCA' + str(xi))
        yi = allyi[ii]
        ylbl = str('PCA' + str(yi))

        # Labels
        ax.set_xlabel(xlbl)
        ax.set_ylabel(ylbl)

        # Data

        # Values
        #ax.scatter(pca_coeff[xlbl], pca_coeff[ylbl], color='black', s=ms)#, marker=mark)
        ax.hist2d(scl * pca_coeff[xlbl],
                  scl * pca_coeff[ylbl],
                  bins=100,
                  norm=LogNorm(),
                  range=[rngi[xi], rngi[yi]])

        # Font size
        xputils.set_fontsize(ax, 8.)

    # Layout and save
    plt.tight_layout(pad=0.2, h_pad=0.1, w_pad=0.25)
    if outfil != None:
        pp.savefig(bbox_inches='tight')
        pp.close()
    else:
        plt.show()
Exemple #55
0
def sawtooth(outfil='Figures/sawtooth.pdf', all_tau=None):
    """ Sawtooth opacity
    """
    # Load fN
    fN_model = FNModel.default_model()
    fN_model.zmnx = (2., 4.1)  # extrapolate a bit
    # teff
    zem = 4
    wave = np.arange(4500., 6200., 10)
    # Calculate
    if all_tau is None:
        all_tau = np.zeros_like(wave)
        for qq, iwave in enumerate(wave):
            all_tau[qq] = lyman_ew(iwave, zem, fN_model)
    # Flux attenuation
    flux = np.exp(-all_tau)

    # Start the plot
    xmnx = (4500, 6200)
    pp = PdfPages(outfil)
    fig = plt.figure(figsize=(8.0, 5.0))

    plt.clf()
    gs = gridspec.GridSpec(1, 1)

    # Lya line
    ax = plt.subplot(gs[0])
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
    #ax.xaxis.set_major_locator(plt.MultipleLocator(20.))
    #ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(0.2))
    ax.set_xlim(xmnx)
    ax.set_ylim(0., 1.1)
    ax.set_ylabel('IGM Transmission')
    ax.set_xlabel('Observed wavelength (z=4 source)')

    lw = 2.
    ax.plot(wave, flux, 'b', linewidth=lw)

    # Label
    csz = 17
    ax.text(0.10,
            0.90,
            'f(N) from Prochaska+14',
            color='blue',
            transform=ax.transAxes,
            size=csz,
            ha='left')
    ax.text(0.10,
            0.80,
            'Ignores Lyman continuum opacity',
            color='blue',
            transform=ax.transAxes,
            size=csz,
            ha='left')
    xputils.set_fontsize(ax, 17.)
    # Layout and save
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0.0, w_pad=0.4)
    plt.subplots_adjust(hspace=0)
    pp.savefig(bbox_inches='tight')
    plt.close()
    # Finish
    pp.close()
    return all_tau
Exemple #56
0
def mean_sdss_spec(outfil=None):

    # Init
    mean_spec_fil = '/u/xavier/paper/LLS/taueff/Analysis/stack_DR7_z3.59_z3.63.fits'
    mean_hdu = fits.open(mean_spec_fil)
    head = mean_hdu[0].header
    zqso = head['AVG_Z']
    mean_wrest = mean_hdu[2].data * u.AA
    mean_flux = mean_hdu[0].data

    # Single QSO
    dr7 = xsq.SdssQuasars()
    qso = dr7[(2161, 206)]
    qso.load_spec()

    # Plot boundaries
    print('zqso = {:g}'.format(zqso))
    #wvmnx = np.array((850., 1205.))*u.AA*(1+zqso)
    wvmnx = (3400., 5700) * u.AA
    mean_ymnx = (0.0, 2.0)

    if outfil == None:
        outfil = 'fig_mean_sdss_spec.pdf'

    elbl_dict = {
        r'Ly$\alpha$ (QSO)': [5450., 1.5],
        r'Ly$\beta$ (QSO)': [4750., 1.6]
    }
    albl_dict = {
        r'Ly$\alpha$': [5200., 0.6],
        r'Ly$\beta$': [4600., 0.6],
        r'Ly$\gamma$': [4420., 0.50],
        r'Ly$\delta$': [4350., 0.4],
        'LL': [912. * (1 + zqso), 0.25]
    }
    # Start the plot
    if outfil != None:
        pp = PdfPages(outfil)

    # Make the plots
    for ss in range(2):

        if ss == 0:
            ymnx = [0., 25.]
            wave = qso.spec.dispersion
            flux = qso.spec.flux.value
            title = 'Individual QSO at z=3.6'
        elif ss == 1:
            ymnx = mean_ymnx
            wave = mean_wrest * (1 + zqso)
            flux = mean_flux
            title = '150 QSOs at z=3.6'

        plt.figure(figsize=(8, 4))
        plt.clf()
        gs = gridspec.GridSpec(1, 1)

        # Axes
        ax = plt.subplot(gs[0, 0])
        #ax.xaxis.set_minor_locator(plt.MultipleLocator(0.5))
        #ax.xaxis.set_major_locator(plt.MultipleLocator(1.))
        #ax.get_xaxis().get_major_formatter().set_useOffset(False)
        ax.set_xlim(wvmnx.value)
        ax.set_ylim(ymnx)
        ax.set_ylabel('Relative Flux')
        ax.set_xlabel(r'Observed Wavelength ($\AA$)')

        # Zero line
        ax.plot(wave, flux, 'b')

        # Label
        if ss == 1:
            for key in albl_dict.keys():
                ax.text(albl_dict[key][0],
                        albl_dict[key][1],
                        key,
                        color='green',
                        ha='center')
            for key in elbl_dict.keys():
                ax.text(elbl_dict[key][0],
                        elbl_dict[key][1],
                        key,
                        color='red',
                        ha='center')
        ax.text(3550.,
                ymnx[1] * 0.85,
                title,
                color='black',
                ha='left',
                size=17.)

        # Data
        '''
        if ss > 0:
            #ax.fill_between( vmodel.dispersion, vmodel.flux, [1.]*len(wave),
            #                        color='blue', alpha=0.3)
            csz = 20.
            ax.text(1215.670, 0.5, 'EW', color='black', ha='center',
                size=csz)
            ax.text(1214.8, 0.2, 
                r'$W_\lambda = \, $'+'{:.2f}'.format(EW.value)+r' $\AA$',
                color='blue', ha='left', size=csz)
        '''

        # Fonts
        xputils.set_fontsize(ax, 15.)

        # Write
        plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
        pp.savefig()
        plt.close()

    # Finish
    print('tlk_spectra.fig_ew: Wrote {:s}'.format(outfil))
    pp.close()
Exemple #57
0
def fig_cos_dwarfs_images(outfil=None):

    from xastropy.obs import x_getsdssimg as xgs

    # Init COS-Dwarfs, COS-Halos 
    cos_dwarfs = COSDwarfs()
    cos_dwarfs.load_mega(skip_ions=True)
    cos_halos = COSHalos()
    cos_halos.load_mega(skip_ions=True)

    # Start the plot
    if outfil is None:
        outfil='fig_cos_dwarfs_images.pdf'
    pp = PdfPages(outfil)

    dx = 0.2
    dy = 0.40

    fig = plt.figure(figsize=(8, 5))
    fig.clf()
    # Setup for dark
    xpsimp.dark_bkgd(plt)
    gs = gridspec.GridSpec(1, 1)

    # Axes
    ax = plt.subplot(gs[0,0])
    ax.set_xlim(8.0, 11.7) 
    #ax.xaxis.set_major_locator(plt.MultipleLocator(300.))
    ax.set_ylim(-13,-8.2)
    ax.set_ylabel('sSFR')
    ax.set_xlabel('log M*')

    iend = -1
    #iend = 5
    imsize = 0.3 # arcmin
    for cgm_abs in cos_halos.cgm_abs[0:iend]:
        img, oBW = xgs.getimg(cgm_abs.galaxy.coord.ra.deg, 
            cgm_abs.galaxy.coord.dec.deg, imsize=imsize)
        # Figure out placement
        ximg = cgm_abs.galaxy.stellar_mass
        yimg = np.log10(cgm_abs.galaxy.sfr[1])-cgm_abs.galaxy.stellar_mass
        # Show
        scl=2.
        ax.imshow(img,extent=(ximg-dx/scl, ximg+dx/scl, yimg-dy/scl, yimg+dy/scl),aspect=dx/dy)

    iend = -1
    #iend = 5
    imsize = 0.8 # arcmin
    for cgm_abs in cos_dwarfs.cgm_abs[0:iend]:
        img, oBW = xgs.getimg(cgm_abs.galaxy.coord.ra.deg, 
            cgm_abs.galaxy.coord.dec.deg, imsize=imsize)
        # Figure out placement
        ximg = cgm_abs.galaxy.stellar_mass
        yimg = np.log10(cgm_abs.galaxy.sfr[1])-cgm_abs.galaxy.stellar_mass
        # Show
        scl=2.
        ax.imshow(img,extent=(ximg-dx/scl, ximg+dx/scl, yimg-dy/scl, yimg+dy/scl),aspect=dx/dy)



    xputils.set_fontsize(ax,17.)
    # Write
    fig.tight_layout(pad=0.2,h_pad=0.,w_pad=0.1)
    pp.savefig()
    plt.close()

    # Finish
    print('tlk_coshalos: Wrote {:s}'.format(outfil))
    pp.close()
def fig_NH_hist(cos_halos=None, outfil='fig_NH_hist.pdf', lsz=17.):
    """ Shows a histogram of NH values
    """
    # Read COS-Halos
    if cos_halos is None:
        cos_halos = load_ch()

    # Read the grid
    model = os.getenv('DROPBOX_DIR') + '/cosout/grid_minextended.pkl'
    fil = open(model)
    modl = pickle.load(fil)
    fil.close()

    # Init
    NH_mnx = (18., 23)
    ymnx = (0., 9)
    binsz = 0.25
    nbins = (NH_mnx[1] - NH_mnx[0]) / binsz

    # Start the plot
    pp = PdfPages(outfil)

    plt.figure(figsize=(5, 5))
    plt.clf()
    ax = plt.gca()

    # Axes
    #wvmnx = awvmnx[iuvq['instr']]
    #ax.xaxis.set_minor_locator(plt.MultipleLocator(500.))
    #ax.yaxis.set_major_locator(plt.MultipleLocator(1.))
    #plt.ylim(0, nsys+1)
    ax.set_xlim(NH_mnx)
    ax.set_ylim(ymnx)

    sumPDF = None
    # Loop on the systems
    nsys = 0
    NH_val = []
    for cgm_abs in cos_halos.cgm_abs:
        # Cut on quality
        try:
            flgs = cgm_abs.igm_sys.metallicity.inputs['data'][:, 3]
        except IndexError:
            print('No constraint for {:s}'.format(cgm_abs.name))
            print('Skipping')
            continue
        indices = np.where(flgs != "-1")[0]
        if len(indices) == 0:
            print('No constraint for {:s}'.format(cgm_abs.name))
            print('Skipping')
            continue
        # Find best indices
        mtl = cgm_abs.igm_sys.metallicity.medianZH
        imet = np.argmin(np.abs(modl[1]['met'] - mtl))
        dens = cgm_abs.igm_sys.density.mediannH
        idens = np.argmin(np.abs(modl[1]['dens'] - dens))
        ired = np.argmin(np.abs(modl[1]['red'] - cgm_abs.zabs))
        icol = np.argmin(np.abs(modl[1]['col'] - cgm_abs.igm_sys.NHI))
        # xHI, NH
        xHI = modl[2]['HI'][icol][idens][imet][ired]
        NH = cgm_abs.igm_sys.NHI - xHI
        NH_val.append(NH)

    print("We are using {:d} systems in COS-Halos".format(nsys))

    # Histogram
    lsz = 19.
    hist, edges = np.histogram(np.array(NH_val), range=NH_mnx, bins=nbins)
    ax.bar(edges[:-1], hist, width=binsz, color='green')
    ax.set_xlabel(r'$\log \, N_{\rm H}$')
    ax.set_ylabel(r"$N_{\rm sys}$")

    # Label
    prev_medNH = 19.1  # Eyeball
    ax.plot([prev_medNH] * 2, ymnx, '--', color='red')
    '''
    csz = 18.
    lbl = 'COS-Halos'
    ax.text(0.05, 0.87, lbl, transform=ax.transAxes, color='black', size=csz, ha='left')
    lbl2 = '({:d} systems)'.format(nsys)
    ax.text(0.05, 0.75, lbl2, transform=ax.transAxes, color='black', size=csz, ha='left')
    '''

    # End
    xputils.set_fontsize(ax, lsz)
    print('Writing {:s}'.format(outfil))
    plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
    pp.savefig()
    pp.close()
    plt.close()