コード例 #1
0
ファイル: test_taueff.py プロジェクト: yzhenggit/pyigm
def test_lya():
    # f(N)
    fN_model = FNModel.default_model()

    # tau_eff
    lamb = 1215.6701 * (1 + 2.4)
    teff = pyteff.lyman_ew(lamb, 2.5, fN_model, NHI_MIN=12., NHI_MAX=17.)
    # Test
    #np.testing.assert_allclose(teff, 0.19821452949713764)
    np.testing.assert_allclose(teff, 0.19827, atol=1e-3)  # scipy 0.19
    # Change cosmology
    cosmo = FlatLambdaCDM(H0=60, Om0=0.2)
    fN_model2 = FNModel.default_model(cosmo=cosmo)
    teff2 = pyteff.lyman_ew(lamb, 2.5, fN_model2, NHI_MIN=12., NHI_MAX=17.)
    np.testing.assert_allclose(teff2, 0.2381, atol=3e-4)
コード例 #2
0
ファイル: test_taueff.py プロジェクト: yzhenggit/pyigm
def test_lyx():
    # f(N)
    fN_model = FNModel.default_model()

    # tau_eff
    lamb = 917. * (1 + 2.4)
    teff = pyteff.lyman_ew(lamb, 2.5, fN_model, NHI_MIN=12., NHI_MAX=17.)
    # Test
    np.testing.assert_allclose(teff, 0.234765, rtol=2e-4)  # scipy 0.19
コード例 #3
0
ファイル: test_taueff.py プロジェクト: mneeleman/pyigm
def test_lyx():
    # f(N)
    fN_model = FNModel.default_model()

    # tau_eff
    lamb = 917.*(1+2.4)
    teff = pyteff.lyman_ew(lamb, 2.5, fN_model, NHI_MIN=12., NHI_MAX=17.)
    # Test
    np.testing.assert_allclose(teff, 0.234694549996041)
コード例 #4
0
ファイル: test_taueff.py プロジェクト: mneeleman/pyigm
def test_lya():
    # f(N)
    fN_model = FNModel.default_model()

    # tau_eff
    lamb = 1215.6701*(1+2.4)
    teff = pyteff.lyman_ew(lamb, 2.5, fN_model, NHI_MIN=12., NHI_MAX=17.)
    # Test
    np.testing.assert_allclose(teff, 0.19821452949713764)
コード例 #5
0
ファイル: mcmc.py プロジェクト: pyigm/pyigm
 def pymc_teff_model(parm=parm):
     # Set parameters
     aparm = np.array([parm[i] for i in range(parm.size)])
     fN_model.update_parameters(aparm)
     # Calculate teff
     model_teff = []
     for teff_input in teff_inputs:
         model_teff.append(tau_eff.lyman_ew(1215.6701*(1+teff_input[0]), teff_input[0]+0.1,
                                        fN_model, NHI_MIN=teff_input[1], NHI_MAX=teff_input[2]))
     return np.array(model_teff)
コード例 #6
0
def test_lya():
    # f(N)
    fN_model = FNModel.default_model()

    # tau_eff
    lamb = 1215.6701 * (1 + 2.4)
    teff = pyteff.lyman_ew(lamb, 2.5, fN_model, NHI_MIN=12., NHI_MAX=17.)
    # Test
    #np.testing.assert_allclose(teff, 0.19821452949713764)
    np.testing.assert_allclose(teff, 0.1981831995528795)  # scipy 0.17
コード例 #7
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
コード例 #8
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()
コード例 #9
0
ファイル: mcmc.py プロジェクト: SunilSimha/pyigm
 def pymc_teff_model(parm=parm):
     # Set parameters
     aparm = np.array([parm[i] for i in range(parm.size)])
     fN_model.update_parameters(aparm)
     # Calculate teff
     model_teff = []
     for teff_input in teff_inputs:
         model_teff.append(
             tau_eff.lyman_ew(1215.6701 * (1 + teff_input[0]),
                              teff_input[0] + 0.1,
                              fN_model,
                              NHI_MIN=teff_input[1],
                              NHI_MAX=teff_input[2]))
     return np.array(model_teff)
コード例 #10
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
コード例 #11
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
コード例 #12
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()
コード例 #13
0
def tst_fn_data(fN_model=None, model_two=None, data_list=None, outfil=None):
    """ Make a matplotlib plot like the final figure from P14
    See the Notebook for Bokeh plots
    Taken from xastropy without actually trying to run

    Parameters
    ----------
    fN_model
    model_two
    data_list
    outfil
    """
    import matplotlib as mpl
    mpl.rcParams['font.family'] = 'STIXGeneral-Regular' # Not for PDF
    mpl.rcParams['lines.linewidth'] = 2

    from matplotlib import pyplot as plt
    #from matplotlib.backends.backend_pdf import PdfPages

    # fN data
    all_fN_cs = FNConstraint.load_defaults()

    # Remove K12
    if data_list is None:
        fN_cs = [fN_c for fN_c in all_fN_cs if ((fN_c.ref != 'K02') & (fN_c.ref != 'PW09'))]
    else:
        fN_cs = [fN_c for fN_c in all_fN_cs if fN_c.ref in data_list]
    fN_dtype = [fc.fN_dtype for fc in fN_cs]

    fig = plt.figure(figsize=(8, 5))
    fig.clf()
    main = fig.add_axes( [0.1, 0.1, 0.8, 0.8] ) # xypos, xy-size

    # f(N) data
    main.set_ylabel(r'$\log f(N_{\rm HI})$')
    main.set_xlabel(r'$\log N_{\rm HI}$')
    main.set_ylim(-25., -9)

    for fN_c in fN_cs:
        if fN_c.fN_dtype == 'fN':
            # Length
            ip = range(fN_c.data['NPT'])
            val = np.where(fN_c.data['FN'][ip] > -90)[0]
            if len(val) > 0:
                ipv = np.array(ip)[val]
                xval = np.median(fN_c.data['BINS'][:,ipv],0)
                xerror = [ fN_c.data['BINS'][1,ipv]-xval, xval-fN_c.data['BINS'][0,ipv] ]
                yerror = [ fN_c.data['SIG_FN'][1,ipv], fN_c.data['SIG_FN'][0,ipv] ] # Inverted!
                main.errorbar(xval, fN_c.data['FN'][ipv], xerr=xerror, yerr=yerror, fmt='o',
                              label=fN_c.ref,capthick=2)
    main.legend(loc='lower left', numpoints=1)

    # Model?
    if fN_model is not None:
        xplt = 12.01 + 0.01*np.arange(1100)
        yplt = fN_model.evaluate(xplt, 2.4)
        main.plot(xplt,yplt,'-',color='black')
        print(xplt[0],yplt[0])
    if model_two is not None:
        xplt = 12.01 + 0.01*np.arange(1100)
        yplt = model_two.evaluate(xplt, 2.4)
        main.plot(xplt,yplt,'-',color='gray')

    # Extras
    #mpl.rcParams['lines.capthick'] = 2

    inset = fig.add_axes( [0.55, 0.6, 0.25, 0.25] ) # xypos, xy-size
    inset.set_ylabel('Value') # LHS
    inset.xaxis.set_major_locator(plt.FixedLocator(range(5)))
    inset.xaxis.set_major_formatter(plt.FixedFormatter(['',r'$\tau_{\rm eff}^{\rm Ly\alpha}$',
                                                        r'$\ell(X)_{\rm LLS}$',
                                                        r'$\lambda_{\rm mfp}^{912}$', '']))
    inset.set_ylim(0., 0.6)

    # tau_eff
    flg_teff = 1
    try:
        itau = fN_dtype.index('teff') # Passes back the first one
    except:
        flg_teff = 0

    if flg_teff:
        teff=float(fN_cs[itau].data['TEFF'])
        D_A = 1. - np.exp(-1. * teff)
        SIGDA_LIMIT = 0.1  # Allows for systemtics and b-value uncertainty
        sig_teff = np.max([fN_cs[itau].data['SIG_TEFF'], (SIGDA_LIMIT*teff)])
        # Plot
        inset.errorbar(1, teff, sig_teff, fmt='_', capthick=2)
        # Model
        if fN_model is not None:
            model_teff = tau_eff.lyman_ew(1215.6701*(1+fN_cs[itau].zeval), fN_cs[itau].zeval+0.1,
                                          fN_model, NHI_MIN=fN_cs[itau].data['NHI_MNX'][0],
                                          NHI_MAX=fN_cs[itau].data['NHI_MNX'][1])
            inset.plot(1, model_teff, 'ko')
            #xdb.set_trace()

    ## #######
    # LLS constraint
    flg_LLS = 1
    try:
        iLLS = fN_dtype.index('LLS') # Passes back the first one
    except:
        #raise ValueError('fN.data: Missing LLS type')
        flg_LLS = 0
    if flg_LLS:
        inset.errorbar(2, fN_cs[iLLS].data['LX'], yerr=fN_cs[iLLS].data['SIG_LX'],
                       fmt='_', capthick=2)
        # Model
        if fN_model != None:
            lX = fN_model.calculate_lox(fN_cs[iLLS].zeval,
                                        17.19+np.log10(fN_cs[iLLS].data['TAU_LIM']), 22.)
            inset.plot(2, lX, 'ko')

    ## #######
    # MFP constraint
    flg_MFP = 1
    try:
        iMFP = fN_dtype.index('MFP') # Passes back the first one
    except:
        #raise ValueError('fN.data: Missing MFP type')
        flg_MFP = 0

    if flg_MFP:
        inset2 = inset.twinx()
        inset2.errorbar(3, fN_cs[iMFP].data['MFP'], yerr=fN_cs[iMFP].data['SIG_MFP'],
                        fmt='_', capthick=2)
        inset2.set_xlim(0,4)
        inset2.set_ylim(0,350)
        inset2.set_ylabel('(Mpc)')

        # Model
        if fN_model is not None:
            #fN_model.zmnx = (0.1, 20.) # Reset for MFP calculation
            mfp = fN_model.mfp(fN_cs[iMFP].zeval)
            inset2.plot(3, mfp, 'ko')

    # Show
    if outfil != None:
        plt.savefig(outfil,bbox_inches='tight')
    else:
        plt.show()
コード例 #14
0
ファイル: data.py プロジェクト: ntejos/xastropy
def tst_fn_data(fN_model=None, model_two=None, data_list=None, outfil=None):
    """ Make a plot like the final figure from P14 

    Parameters:
       noshow: boolean (False)
          Show the plot?

    JXP 07 Nov 2014
    """

    import matplotlib as mpl
    mpl.rcParams['font.family'] = 'STIXGeneral-Regular' # Not for PDF
    mpl.rcParams['lines.linewidth'] = 2
    from matplotlib import pyplot as plt
    #from matplotlib.backends.backend_pdf import PdfPages

    # Output
    #if outfil != None:
    #    pp = PdfPages(outfil)

    #mpl.rcParams['font.family'] = 'stixgeneral'  # For PDF

    # fN data
    #fn_file = os.environ.get('XIDL_DIR')+'IGM/fN_empirical/fn_constraints_z2.5_vanilla.fits'
    #k13r13_file = os.environ.get('XIDL_DIR')+'IGM/fN_empirical/fn_constraints_K13R13_vanilla.fits'
    #n12_file = os.environ.get('XIDL_DIR')+'IGM/fN_empirical/fn_constraints_N12_vanilla.fits'
    fn_file = xa_path+'/igm/fN/fn_constraints_z2.5_vanilla.fits'
    k13r13_file = xa_path+'/igm/fN/fn_constraints_K13R13_vanilla.fits'
    n12_file = xa_path+'/igm/fN/fn_constraints_N12_vanilla.fits'
    all_fN_cs = fn_data_from_fits([fn_file,k13r13_file, n12_file])
    #ascii_file = xa_path+'/igm/fN/asciidatan12'
    #ascii_data = fN_data_from_ascii_file(ascii_file)
    #all_fN_cs.append(ascii_data)
    
    # Remove K12
    #data_list = ['K13R13','OPB07', 'N12']
    #outfil = 'tmp.png'
    if data_list is None:
        fN_cs = [fN_c for fN_c in all_fN_cs if ((fN_c.ref != 'K02') & (fN_c.ref != 'PW09'))]
    else:
        fN_cs = [fN_c for fN_c in all_fN_cs if fN_c.ref in data_list]
    fN_dtype = [fc.fN_dtype for fc in fN_cs]

    fig = plt.figure(figsize=(8, 5))
    fig.clf()
    main = fig.add_axes( [0.1, 0.1, 0.8, 0.8] ) # xypos, xy-size

    # f(N) data
    main.set_ylabel(r'$\log f(N_{\rm HI})$')
    main.set_xlabel(r'$\log N_{\rm HI}$')
    main.set_ylim(-25., -9)

    for fN_c in fN_cs: 
        if fN_c.fN_dtype == 'fN':
            # Length
            ip = range(fN_c.data['NPT'])
            #xdb.set_trace()
            val = np.where(fN_c.data['FN'][ip] > -90)[0]
            #xdb.set_trace()
            if len(val) > 0:
                #xdb.set_trace()
                ipv = np.array(ip)[val]
                xval = np.median(fN_c.data['BINS'][:,ipv],0)
                xerror = [ fN_c.data['BINS'][1,ipv]-xval, xval-fN_c.data['BINS'][0,ipv] ]
                yerror = [ fN_c.data['SIG_FN'][1,ipv], fN_c.data['SIG_FN'][0,ipv] ] # Inverted!
                main.errorbar(xval, fN_c.data['FN'][ipv], xerr=xerror, yerr=yerror, fmt='o',
                             label=fN_c.ref,capthick=2)
    main.legend(loc='lower left', numpoints=1)

    # Model?
    #print(fN_model.param)
    if fN_model is not None: 
        xplt = 12.01 + 0.01*np.arange(1100)
        yplt = fN_model.evaluate(xplt, 2.4)
        main.plot(xplt,yplt,'-',color='black')
        print(xplt[0],yplt[0])
    if model_two is not None: 
        xplt = 12.01 + 0.01*np.arange(1100)
        yplt = model_two.evaluate(xplt, 2.4)
        main.plot(xplt,yplt,'-',color='gray')
        

    #xdb.set_trace()

    # Extras
    #mpl.rcParams['lines.capthick'] = 2

    inset = fig.add_axes( [0.55, 0.6, 0.25, 0.25] ) # xypos, xy-size
    inset.set_ylabel('Value') # LHS
    inset.xaxis.set_major_locator(plt.FixedLocator(range(5)))
    #lbl1 = r'$\tau_{\rm eff}^{\rm Ly\alpha}'
    inset.xaxis.set_major_formatter(plt.FixedFormatter(['',r'$\tau_{\rm eff}^{\rm Ly\alpha}$',
                                                        r'$\ell(X)_{\rm LLS}$',
                                                        r'$\lambda_{\rm mfp}^{912}$', '']))
    inset.set_ylim(0., 0.6)

    ## #######
    # tau_eff
    flg_teff = 1
    try:
        itau = fN_dtype.index('teff') # Passes back the first one
    except:
        #raise ValueError('fN.data: Missing teff type')
        flg_teff = 0    
    
    #xdb.set_trace()
    if flg_teff: 
        teff=float(fN_cs[itau].data['TEFF'])
        D_A = 1. - np.exp(-1. * teff)
        SIGDA_LIMIT = 0.1  # Allows for systemtics and b-value uncertainty
        sig_teff = np.max([fN_cs[itau].data['SIG_TEFF'], (SIGDA_LIMIT*teff)])
        # Plot
        inset.errorbar(1, teff, sig_teff, fmt='_', capthick=2)
        # Model
        if fN_model is not None:
            model_teff = pyiteff.lyman_ew(1215.6701*(1+fN_cs[itau].zeval), fN_cs[itau].zeval+0.1,
                                        fN_model, NHI_MIN=fN_cs[itau].data['NHI_MNX'][0],
                                        NHI_MAX=fN_cs[itau].data['NHI_MNX'][1])
            inset.plot(1, model_teff, 'ko')
        #xdb.set_trace()

    ## #######
    # LLS constraint
    flg_LLS = 1    
    try:
        iLLS = fN_dtype.index('LLS') # Passes back the first one
    except:
        #raise ValueError('fN.data: Missing LLS type')
        flg_LLS = 0    
    if flg_LLS: 
        inset.errorbar(2, fN_cs[iLLS].data['LX'], yerr=fN_cs[iLLS].data['SIG_LX'],
                    fmt='_', capthick=2)
        # Model
        if fN_model != None:
            lX = fN_model.calculate_lox(fN_cs[iLLS].zeval,
                                17.19+np.log10(fN_cs[iLLS].data['TAU_LIM']), 22.) 
            inset.plot(2, lX, 'ko')

    ## #######
    # MFP constraint
    flg_MFP = 1
    try:
        iMFP = fN_dtype.index('MFP') # Passes back the first one
    except:
        #raise ValueError('fN.data: Missing MFP type')
        flg_MFP = 0

    if flg_MFP:
        inset2 = inset.twinx()
        inset2.errorbar(3, fN_cs[iMFP].data['MFP'], yerr=fN_cs[iMFP].data['SIG_MFP'], 
                    fmt='_', capthick=2)
        inset2.set_xlim(0,4)
        inset2.set_ylim(0,350)
        inset2.set_ylabel('(Mpc)')

        # Model
        if fN_model is not None:
            #fN_model.zmnx = (0.1, 20.) # Reset for MFP calculation
            mfp = fN_model.mfp(fN_cs[iMFP].zeval)
            inset2.plot(3, mfp, 'ko')

    # Show
    if outfil != None:
        plt.savefig(outfil,bbox_inches='tight')
    else: 
        plt.show()
コード例 #15
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
コード例 #16
0
ファイル: data.py プロジェクト: ntejos/xastropy
def tst_fn_data(fN_model=None, model_two=None, data_list=None, outfil=None):
    """ Make a plot like the final figure from P14 

    Parameters:
       noshow: boolean (False)
          Show the plot?

    JXP 07 Nov 2014
    """

    import matplotlib as mpl
    mpl.rcParams['font.family'] = 'STIXGeneral-Regular'  # Not for PDF
    mpl.rcParams['lines.linewidth'] = 2
    from matplotlib import pyplot as plt
    #from matplotlib.backends.backend_pdf import PdfPages

    # Output
    #if outfil != None:
    #    pp = PdfPages(outfil)

    #mpl.rcParams['font.family'] = 'stixgeneral'  # For PDF

    # fN data
    #fn_file = os.environ.get('XIDL_DIR')+'IGM/fN_empirical/fn_constraints_z2.5_vanilla.fits'
    #k13r13_file = os.environ.get('XIDL_DIR')+'IGM/fN_empirical/fn_constraints_K13R13_vanilla.fits'
    #n12_file = os.environ.get('XIDL_DIR')+'IGM/fN_empirical/fn_constraints_N12_vanilla.fits'
    fn_file = xa_path + '/igm/fN/fn_constraints_z2.5_vanilla.fits'
    k13r13_file = xa_path + '/igm/fN/fn_constraints_K13R13_vanilla.fits'
    n12_file = xa_path + '/igm/fN/fn_constraints_N12_vanilla.fits'
    all_fN_cs = fn_data_from_fits([fn_file, k13r13_file, n12_file])
    #ascii_file = xa_path+'/igm/fN/asciidatan12'
    #ascii_data = fN_data_from_ascii_file(ascii_file)
    #all_fN_cs.append(ascii_data)

    # Remove K12
    #data_list = ['K13R13','OPB07', 'N12']
    #outfil = 'tmp.png'
    if data_list is None:
        fN_cs = [
            fN_c for fN_c in all_fN_cs
            if ((fN_c.ref != 'K02') & (fN_c.ref != 'PW09'))
        ]
    else:
        fN_cs = [fN_c for fN_c in all_fN_cs if fN_c.ref in data_list]
    fN_dtype = [fc.fN_dtype for fc in fN_cs]

    fig = plt.figure(figsize=(8, 5))
    fig.clf()
    main = fig.add_axes([0.1, 0.1, 0.8, 0.8])  # xypos, xy-size

    # f(N) data
    main.set_ylabel(r'$\log f(N_{\rm HI})$')
    main.set_xlabel(r'$\log N_{\rm HI}$')
    main.set_ylim(-25., -9)

    for fN_c in fN_cs:
        if fN_c.fN_dtype == 'fN':
            # Length
            ip = range(fN_c.data['NPT'])
            #xdb.set_trace()
            val = np.where(fN_c.data['FN'][ip] > -90)[0]
            #xdb.set_trace()
            if len(val) > 0:
                #xdb.set_trace()
                ipv = np.array(ip)[val]
                xval = np.median(fN_c.data['BINS'][:, ipv], 0)
                xerror = [
                    fN_c.data['BINS'][1, ipv] - xval,
                    xval - fN_c.data['BINS'][0, ipv]
                ]
                yerror = [
                    fN_c.data['SIG_FN'][1, ipv], fN_c.data['SIG_FN'][0, ipv]
                ]  # Inverted!
                main.errorbar(xval,
                              fN_c.data['FN'][ipv],
                              xerr=xerror,
                              yerr=yerror,
                              fmt='o',
                              label=fN_c.ref,
                              capthick=2)
    main.legend(loc='lower left', numpoints=1)

    # Model?
    #print(fN_model.param)
    if fN_model is not None:
        xplt = 12.01 + 0.01 * np.arange(1100)
        yplt = fN_model.evaluate(xplt, 2.4)
        main.plot(xplt, yplt, '-', color='black')
        print(xplt[0], yplt[0])
    if model_two is not None:
        xplt = 12.01 + 0.01 * np.arange(1100)
        yplt = model_two.evaluate(xplt, 2.4)
        main.plot(xplt, yplt, '-', color='gray')

    #xdb.set_trace()

    # Extras
    #mpl.rcParams['lines.capthick'] = 2

    inset = fig.add_axes([0.55, 0.6, 0.25, 0.25])  # xypos, xy-size
    inset.set_ylabel('Value')  # LHS
    inset.xaxis.set_major_locator(plt.FixedLocator(range(5)))
    #lbl1 = r'$\tau_{\rm eff}^{\rm Ly\alpha}'
    inset.xaxis.set_major_formatter(
        plt.FixedFormatter([
            '', r'$\tau_{\rm eff}^{\rm Ly\alpha}$', r'$\ell(X)_{\rm LLS}$',
            r'$\lambda_{\rm mfp}^{912}$', ''
        ]))
    inset.set_ylim(0., 0.6)

    ## #######
    # tau_eff
    flg_teff = 1
    try:
        itau = fN_dtype.index('teff')  # Passes back the first one
    except:
        #raise ValueError('fN.data: Missing teff type')
        flg_teff = 0

    #xdb.set_trace()
    if flg_teff:
        teff = float(fN_cs[itau].data['TEFF'])
        D_A = 1. - np.exp(-1. * teff)
        SIGDA_LIMIT = 0.1  # Allows for systemtics and b-value uncertainty
        sig_teff = np.max([fN_cs[itau].data['SIG_TEFF'], (SIGDA_LIMIT * teff)])
        # Plot
        inset.errorbar(1, teff, sig_teff, fmt='_', capthick=2)
        # Model
        if fN_model is not None:
            model_teff = pyiteff.lyman_ew(
                1215.6701 * (1 + fN_cs[itau].zeval),
                fN_cs[itau].zeval + 0.1,
                fN_model,
                NHI_MIN=fN_cs[itau].data['NHI_MNX'][0],
                NHI_MAX=fN_cs[itau].data['NHI_MNX'][1])
            inset.plot(1, model_teff, 'ko')
        #xdb.set_trace()

    ## #######
    # LLS constraint
    flg_LLS = 1
    try:
        iLLS = fN_dtype.index('LLS')  # Passes back the first one
    except:
        #raise ValueError('fN.data: Missing LLS type')
        flg_LLS = 0
    if flg_LLS:
        inset.errorbar(2,
                       fN_cs[iLLS].data['LX'],
                       yerr=fN_cs[iLLS].data['SIG_LX'],
                       fmt='_',
                       capthick=2)
        # Model
        if fN_model != None:
            lX = fN_model.calculate_lox(
                fN_cs[iLLS].zeval,
                17.19 + np.log10(fN_cs[iLLS].data['TAU_LIM']), 22.)
            inset.plot(2, lX, 'ko')

    ## #######
    # MFP constraint
    flg_MFP = 1
    try:
        iMFP = fN_dtype.index('MFP')  # Passes back the first one
    except:
        #raise ValueError('fN.data: Missing MFP type')
        flg_MFP = 0

    if flg_MFP:
        inset2 = inset.twinx()
        inset2.errorbar(3,
                        fN_cs[iMFP].data['MFP'],
                        yerr=fN_cs[iMFP].data['SIG_MFP'],
                        fmt='_',
                        capthick=2)
        inset2.set_xlim(0, 4)
        inset2.set_ylim(0, 350)
        inset2.set_ylabel('(Mpc)')

        # Model
        if fN_model is not None:
            #fN_model.zmnx = (0.1, 20.) # Reset for MFP calculation
            mfp = fN_model.mfp(fN_cs[iMFP].zeval)
            inset2.plot(3, mfp, 'ko')

    # Show
    if outfil != None:
        plt.savefig(outfil, bbox_inches='tight')
    else:
        plt.show()