Example #1
0
File: mcmc.py Project: pyigm/pyigm
def set_fn_model(flg=0):
    """ Load up f(N) model

    Parameters
    ----------
    flg : int, optional
      * 0 = Default model
      * 1 = Gamma

    Returns
    -------
    sfN_model : FNModel
    """
    if flg==0: # I may choose to pickle a few of these
        sfN_model = FNModel.default_model(use_mcmc=True) # Hermite Spline
    elif flg==1:
        sfN_model = FNModel('Gamma')
    elif flg==2:
        tfN_model = FNModel.default_model()
        NHI_pivots = [11., 15., 17.0, 20.0, 21.5, 22.]
        param = []
        for NHI in NHI_pivots:
            imin = np.argmin(np.abs(NHI-tfN_model.pivots))
            param.append(tfN_model.param['sply'][imin])
        # Init
        sfN_model = FNModel('Hspline', zmnx=(0.5,5.5), pivots=NHI_pivots,
                           param=dict(sply=np.array(param)))
    else:
        raise ValueError('mcmc.set_model: Not ready for this type of fN model {:d}'.format(flg))
    #
    return sfN_model
Example #2
0
def set_fn_model(flg=0):
    """ Load up f(N) model

    Parameters
    ----------
    flg : int, optional
      * 0 = Default model
      * 1 = Gamma

    Returns
    -------
    sfN_model : FNModel
    """
    if flg == 0:  # I may choose to pickle a few of these
        sfN_model = FNModel.default_model(use_mcmc=True)  # Hermite Spline
    elif flg == 1:
        sfN_model = FNModel('Gamma')
    elif flg == 2:
        tfN_model = FNModel.default_model()
        NHI_pivots = [11., 15., 17.0, 20.0, 21.5, 22.]
        param = []
        for NHI in NHI_pivots:
            imin = np.argmin(np.abs(NHI - tfN_model.pivots))
            param.append(tfN_model.param['sply'][imin])
        # Init
        sfN_model = FNModel('Hspline',
                            zmnx=(0.5, 5.5),
                            pivots=NHI_pivots,
                            param=dict(sply=np.array(param)))
    else:
        raise ValueError(
            'mcmc.set_model: Not ready for this type of fN model {:d}'.format(
                flg))
    #
    return sfN_model
Example #3
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.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)
Example #4
0
def set_fn_model(flg=0, use_p14=False):
    """ Load up f(N) model

    Parameters
    ----------
    flg : int, optional
      * 0 = Default model
      * 1 = Gamma

    Returns
    -------
    sfN_model : FNModel
    """
    if flg == 0:  # I may choose to pickle a few of these
        sfN_model = FNModel.default_model(use_mcmc=True)  # Hermite Spline
    elif flg == 1:
        sfN_model = FNModel('Gamma')
    elif flg == 2:
        tfN_model = FNModel.default_model()
        # GGG analysis
        pdb.set_trace()  # BEING DEVELOPED IN GGG/LLS/Analysis/py
        zpivot = 4.4
        #NHI_pivots = [11., 15., 17.0, 20.0, 21.5, 22.]
        NHI_pivots = [11., 15., 17.0, 18.0, 20.0, 21.5, 22.]
        if use_p14:
            param = []
            for NHI in NHI_pivots:
                imin = np.argmin(np.abs(NHI - tfN_model.pivots))
                # Adjust for zpivot
                adj_parm = tfN_model.param['sply'][imin] + np.log10(
                    ((1 + zpivot) / (1 + tfN_model.zpivot))**tfN_model.gamma)
                param.append(adj_parm)
        else:
            #param = [-8.45, -13.959, -18.06, -21.000, -23.735, -24.88]
            if len(param) != len(NHI_pivots):
                raise ValueError("Incorrect number of parameters")
        # Init
        sfN_model = FNModel('Hspline',
                            zmnx=(0.5, 5.5),
                            pivots=NHI_pivots,
                            zpivot=zpivot,
                            param=dict(sply=np.array(param)))
    else:
        raise ValueError(
            'mcmc.set_model: Not ready for this type of fN model {:d}'.format(
                flg))
    #
    return sfN_model
Example #5
0
def test_mfp():
    fN_default = FNModel.default_model()
    z = 2.44
    mfp = fN_default.mfp(z)
    # Test
    assert mfp.unit == u.Mpc
    np.testing.assert_allclose(mfp.value, 257.10258545808983)
Example #6
0
def test_rhoHI():
    fN_default = FNModel.default_model()
    z = 2.44
    rho_HI = fN_default.calculate_rhoHI(z, (20.3, 22.))
    # Test
    assert rho_HI.unit == u.solMass / u.Mpc**3
    np.testing.assert_allclose(rho_HI.value, 83553755.13025708)
Example #7
0
def test_rhoHI():
    fN_default = FNModel.default_model()
    z=2.44
    rho_HI = fN_default.calculate_rhoHI(z, (20.3, 22.))
    # Test
    assert rho_HI.unit == u.solMass/u.Mpc**3
    np.testing.assert_allclose(rho_HI.value, 83553755.13025708)
Example #8
0
def test_mfp():
    fN_default = FNModel.default_model()
    z=2.44
    mfp = fN_default.mfp(z)
    # Test
    assert mfp.unit == u.Mpc
    np.testing.assert_allclose(mfp.value, 257.53517867221353)
Example #9
0
def test_teff():
    fN_default = FNModel.default_model()
    zval, teff_LL = pyteff.lyman_limit(fN_default, 0.5, 2.45)
    #
    np.testing.assert_allclose(zval[0], 0.5)
    #np.testing.assert_allclose(teff_LL[0], 1.8176161746504436) scipy 0.16
    np.testing.assert_allclose(teff_LL[0], 1.8190744845274058)  # scipy 0.17
Example #10
0
def test_teff():
    fN_default = FNModel.default_model()
    zval,teff_LL = pyteff.lyman_limit(fN_default, 0.5, 2.45)
    #
    np.testing.assert_allclose(zval[0], 0.5)
    #np.testing.assert_allclose(teff_LL[0], 1.8176161746504436) scipy 0.16
    np.testing.assert_allclose(teff_LL[0], 1.8190744845274058) # scipy 0.17
Example #11
0
def get_telfer_spec(zqso=0., igm=False, fN_gamma=None, LL_flatten=True):
    '''Generate a Telfer QSO composite spectrum

    Parameters:
    ----------
    zqso: float, optional
      Redshift of the QSO
    igm: bool, optional
      Include IGM opacity? [False]
    fN_gamma: float, optional
      Power-law evolution in f(N,X)
    LL_flatten: bool, optional
      Set Telfer to a constant below the LL?

    Returns:
    --------
    telfer_spec: XSpectrum1D
      Spectrum
    '''
    # Read
    telfer = ascii.read(
        xa_path+'/data/quasar/telfer_hst_comp01_rq.ascii', comment='#')
    scale = telfer['flux'][(telfer['wrest'] == 1450.)]
    telfer_spec = XSpectrum1D.from_tuple((telfer['wrest']*(1+zqso),
        telfer['flux']/scale[0])) # Observer frame

    # IGM?
    if igm is True:
        '''The following is quite experimental.
        Use at your own risk.
        '''
        import multiprocessing
        fN_model = FNModel.default_model()
        # Expanding range of zmnx (risky)
        fN_model.zmnx = (0.,5.)
        if fN_gamma is not None:
            fN_model.gamma = fN_gamma
        # Parallel
        igm_wv = np.where(telfer['wrest']<1220.)[0]
        adict = []
        for wrest in telfer_spec.dispersion[igm_wv].value:
            tdict = dict(ilambda=wrest, zem=zqso, fN_model=fN_model)
            adict.append(tdict)
        # Run
        #xdb.set_trace()
        pool = multiprocessing.Pool(4) # initialize thread pool N threads
        ateff = pool.map(pyift.map_lymanew, adict)
        # Apply
        telfer_spec.flux[igm_wv] *= np.exp(-1.*np.array(ateff))
        # Flatten?
        if LL_flatten:
            wv_LL = np.where(np.abs(telfer_spec.dispersion/(1+zqso)-914.*u.AA)<3.*u.AA)[0]
            f_LL = np.median(telfer_spec.flux[wv_LL])
            wv_low = np.where(telfer_spec.dispersion/(1+zqso)<911.7*u.AA)[0]
            telfer_spec.flux[wv_low] = f_LL

    # Return
    return telfer_spec
Example #12
0
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)
Example #13
0
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
Example #14
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)
Example #15
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
Example #16
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()
Example #17
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
Example #18
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()
Example #19
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()
Example #20
0
def test_mk_mock():
    # Quasar
    zem = 2.5
    # Spectral properties
    s2n = 10.
    sampling = 2.
    R = 2000.
    # Resultant wavelength array (using constant dwv instead of constant dv)
    disp = 4000/R/sampling # Angstrom
    wave = np.arange(3800., 1300*(1+zem), disp)*u.AA
    # f(N)
    fN_model = FNModel.default_model(cosmo=Planck15)

    #
    mock_spec, HI_comps, _ = mk_mock(wave, zem, fN_model, s2n=s2n,
                                     fwhm=sampling, seed=11223)
    np.testing.assert_allclose(mock_spec.flux[300].value, 21.77, rtol=0.05)  # scipy 0.17
Example #21
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()
Example #22
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()
Example #23
0
def test_parallel():
    import multiprocessing
    from linetools.lists.linelist import LineList
    # f(N)
    fN_model = FNModel.default_model()
    # Lines
    HI = LineList('HI')
    tst_wv = HI._data['wrest']
    #
    adict = []
    for wrest in tst_wv:
        tdict = dict(ilambda=wrest.value*(1+2.4), zem=2.5, fN_model=fN_model, wrest=copy.deepcopy(tst_wv))
        adict.append(tdict)

    pool = multiprocessing.Pool(2) # initialize thread pool N threads
    ateff = pool.map(pyteff.map_lymanew, adict)
    # Test
    np.testing.assert_allclose(ateff[-3:],
                               np.array([0.23440858789182742,
                                0.20263221240650739, 0.21927057420866358]))
Example #24
0
def test_mk_mock():
    # Quasar
    zem = 2.5
    # Spectral properties
    s2n = 10.
    sampling = 2.
    R = 2000.
    # Resultant wavelength array (using constant dwv instead of constant dv)
    disp = 4000 / R / sampling  # Angstrom
    wave = np.arange(3800., 1300 * (1 + zem), disp) * u.AA
    # f(N)
    fN_model = FNModel.default_model(cosmo=Planck15)

    #
    mock_spec, HI_comps, _ = mk_mock(wave,
                                     zem,
                                     fN_model,
                                     s2n=s2n,
                                     fwhm=sampling,
                                     seed=11223)
    np.testing.assert_allclose(mock_spec.flux[300].value, 21.77,
                               rtol=0.05)  # scipy 0.17
Example #25
0
def init_fNHI(slls=False, mix=False, high=False):
    """ Generate the interpolator for log NHI

    Returns
    -------
    fNHI : scipy.interpolate.interp1d function
    """
    from pyigm.fN.fnmodel import FNModel
    # f(N)
    fN_model = FNModel.default_model()
    # Integrate on NHI
    if slls:
        lX, cum_lX, lX_NHI = fN_model.calculate_lox(fN_model.zpivot,
                                                    19.5,
                                                    NHI_max=20.3,
                                                    cumul=True)
    elif high:
        lX, cum_lX, lX_NHI = fN_model.calculate_lox(fN_model.zpivot,
                                                    21.2,
                                                    NHI_max=22.5,
                                                    cumul=True)
    elif mix:
        lX, cum_lX, lX_NHI = fN_model.calculate_lox(fN_model.zpivot,
                                                    19.5,
                                                    NHI_max=22.5,
                                                    cumul=True)
    else:
        lX, cum_lX, lX_NHI = fN_model.calculate_lox(fN_model.zpivot,
                                                    20.3,
                                                    NHI_max=22.5,
                                                    cumul=True)
    # Interpolator
    cum_lX /= cum_lX[-1]  # Normalize
    fNHI = interpolate.interp1d(cum_lX,
                                lX_NHI,
                                bounds_error=False,
                                fill_value=lX_NHI[0])
    return fNHI
Example #26
0
def test_parallel():
    import multiprocessing
    from linetools.lists.linelist import LineList
    # f(N)
    fN_model = FNModel.default_model()
    # Lines
    HI = LineList('HI')
    tst_wv = u.Quantity(HI._data['wrest'])
    #
    adict = []
    for wrest in tst_wv:
        tdict = dict(ilambda=wrest.value * (1 + 2.4),
                     zem=2.5,
                     fN_model=fN_model,
                     wrest=copy.deepcopy(tst_wv))
        adict.append(tdict)

    pool = multiprocessing.Pool(2)  # initialize thread pool N threads
    ateff = pool.map(pyteff.map_lymanew, adict)
    # Test
    np.testing.assert_allclose(ateff[-3:],
                               np.array([0.238569, 0.206972, 0.225049]),
                               atol=3e-4)
Example #27
0
def get_telfer_spec(zqso=0., igm=False, fN_gamma=None,
                    LL_flatten=True, nproc=6):
    """Generate a Telfer QSO composite spectrum

    Parameters
    ----------
    zqso : float, optional
      Redshift of the QSO
    igm : bool, optional
      Include IGM opacity? [False]
    fN_gamma : float, optional
      Power-law evolution in f(N,X)
    LL_flatten : bool, optional
      Set Telfer to a constant below the LL?
    nproc : int, optional
      For multi-processing with IGM

    Returns
    -------
    telfer_spec : XSpectrum1D
      Spectrum
    """
    # Read
    telfer = ascii.read(
        pyigm_path+'/data/quasar/telfer_hst_comp01_rq.ascii', comment='#')
    scale = telfer['flux'][(telfer['wrest'] == 1450.)]
    telfer_spec = XSpectrum1D.from_tuple((np.array(telfer['wrest'])*(1+zqso),
        np.array(telfer['flux'])/scale[0]))  # Observer frame

    # IGM?
    if igm is True:
        """The following concept is rather experimental.
        Use at your own risk.
        """
        import multiprocessing
        fN_model = FNModel.default_model()
        # Expanding range of zmnx (risky)
        fN_model.zmnx = (0.,5.5)
        if fN_gamma is not None:
            fN_model.gamma = fN_gamma
        # Setup inputs
        #EW_FIL = pyigm_path+'/data/fN/EW_SPLINE_b24.yml'
        #with open(EW_FIL, 'r') as infile:
        #    EW_spline = yaml.load(infile)  # dict from mk_ew_lyman_spline
        HI = LineList('HI')
        twrest = HI._data['wrest']
        # Parallel
        if LL_flatten:
            igm_wv = np.where((telfer['wrest'] > 900.) & (telfer['wrest'] < 1220.))[0]
        else:
            igm_wv = np.where(telfer['wrest'] < 1220.)[0]
        adict = []
        for wrest in telfer_spec.wavelength[igm_wv].value:
            tdict = dict(ilambda=wrest, zem=zqso, fN_model=fN_model,
                         wrest=twrest.copy())
            adict.append(tdict)
        # Run
        if nproc > 1:
            pool = multiprocessing.Pool(nproc) # initialize thread pool N threads
            ateff = pool.map(pyift.map_lymanew, adict)
        else:
            ateff = map(pyift.map_lymanew, adict)
        # Apply
        new_flux = telfer_spec.flux.value
        new_flux[igm_wv] *= np.exp(-1.*np.array(ateff))
        # Flatten?
        if LL_flatten:
            wv_LL = np.where(np.abs(telfer_spec.wavelength/(1+zqso)-914.*u.AA)<3.*u.AA)[0]
            f_LL = np.median(new_flux[wv_LL])
            wv_low = np.where(telfer_spec.wavelength/(1+zqso)<911.7*u.AA)[0]
            new_flux[wv_low] = f_LL
        # Regenerate spectrum
        telfer_spec = XSpectrum1D.from_tuple(
                (np.array(telfer['wrest'])*(1+zqso), new_flux))

    # Return
    return telfer_spec
Example #28
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
Example #29
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
Example #30
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()
Example #31
0
def redshift(outfil='Figures/redshift.pdf'):
    """ Series of plots illustrating redshift in the Lya forest
    """
    lrest = np.array([900., 1250])  # Ang
    zem = 3.
    toff = 0.15
    yqso = 0.7
    sqso = 35

    # QSO lines
    qsolya = AbsLine(1215.6700 * u.AA)
    qsolya.attrib['N'] = 10.**(16.0) / u.cm**2
    qsolya.attrib['b'] = 40 * u.km / u.s
    qsolya.attrib['z'] = zem
    qsolyb = AbsLine('HI 1025')
    qsolyb.attrib['N'] = qsolya.attrib['N']
    qsolyb.attrib['b'] = qsolya.attrib['b']
    qsolyb.attrib['z'] = qsolya.attrib['z']

    def tick_function(z, X):
        V = X * (1 + z)
        return ["{:d}".format(int(round(x))) for x in V]

    def add_lines(axi, z):
        wvtwo = (1 + z) * 1215.67 / (1 + zem)
        axi.scatter([wvtwo], [yqso],
                    marker='o',
                    facecolor='none',
                    edgecolor='green',
                    s=sqso * 5)
        axi.text(wvtwo,
                 yqso - 1.7 * toff,
                 'HI Gas (z={:0.1f})'.format(z),
                 color='green',
                 ha='center')
        #
        twolya = copy.deepcopy(qsolya)
        twolya.attrib['z'] = z
        twolyb = copy.deepcopy(qsolyb)
        twolyb.attrib['z'] = z
        return [twolya, twolyb]

    # Telfer
    telfer = pyicq.get_telfer_spec()

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

    plt.clf()
    gs = gridspec.GridSpec(5, 1)
    jet = cm = plt.get_cmap('jet')

    # Loop
    for qq in range(9):
        # Cartoon
        ax0 = plt.subplot(gs[0, 0])
        ax0.set_xlim(lrest)
        ax0.set_ylim(0., 1.)
        ax0.set_frame_on(False)
        ax0.axes.get_yaxis().set_visible(False)
        ax0.axes.get_xaxis().set_visible(False)

        # QSO
        ax0.scatter([1215.67], [yqso], marker='o', facecolor='blue', s=sqso)
        ax0.text(1215.67,
                 yqso + toff,
                 'Quasar (z=3)',
                 color='blue',
                 ha='center')

        # Redshifted light
        if qq > 0:
            light = np.linspace(1215.67, lrest[0], 20)
            ax0.scatter(light, [yqso] * len(light),
                        marker='_',
                        s=40,
                        cmap=cm,
                        c=1. / light)

        # Gas at QSO
        if qq > 1:
            ax0.scatter([1215.67], [yqso],
                        marker='o',
                        facecolor='none',
                        edgecolor='green',
                        s=sqso * 5)
            ax0.text(1215.67,
                     yqso - 1.7 * toff,
                     'HI Gas (z=3)',
                     color='green',
                     ha='center')

        # Spectrum
        ax = plt.subplot(gs[1:, 0])
        ax.set_xlim(lrest)
        #ax.set_ylim(ymnx)
        ax.set_ylabel('Relative Flux')
        ax.set_xlabel("Rest Wavelength")
        if qq < 3:
            tsty = 'k'
        else:
            tsty = 'b:'
        ax.plot(telfer.wavelength, telfer.flux, tsty)

        # Observer frame axis
        if qq > 0:
            ax2 = ax.twiny()
            ax2.set_xlim(ax.get_xlim())
            xtcks = ax.get_xticks()
            ax2.set_xticks(xtcks)
            ax2.set_xticklabels(tick_function(zem, xtcks))
            ax2.set_xlabel('Observed Wavelength (Angstroms)')

        # Absorption lines
        abslines = []
        if (qq > 2) and (qq != 8):
            # Lya at zem

            abslines.append(qsolya)
            if qq > 3:  # Lyb at zem
                abslines.append(qsolyb)
            # Gas at z=2.8
            if qq > 4:
                zadd = 2.8
                abslines += add_lines(ax0, zadd)
            # Gas at z=2.5
            if qq > 5:
                zadd = 2.5
                abslines += add_lines(ax0, zadd)
            if qq > 6:
                zadd = 2.2
                abslines += add_lines(ax0, zadd)
            #
            abs_model = ltav.voigt_from_abslines(telfer.wavelength * (1 + zem),
                                                 abslines)
            #ax.plot(telfer.wavelength, telfer.flux*abs_model.flux, 'k')
            ax.plot(telfer.wavelength, telfer.flux.value * abs_model.flux, 'k')

        # Final plot
        if qq == 8:
            nlin = 100
            dotwv = np.linspace(900, 1215., nlin)
            ax0.scatter(dotwv, [yqso] * nlin,
                        marker='o',
                        facecolor='none',
                        edgecolor='green',
                        s=sqso * 5)
            # Mock spectrum
            fN_model = FNModel.default_model()
            gdp = np.where(telfer.wavelength > 900. * u.AA)[0]
            mock_spec, HI_comps, misc = pyimock.mk_mock(
                telfer.wavelength[gdp] * (1 + zem),
                zem,
                fN_model,
                s2n=100.,
                fwhm=3,
                add_conti=False)
            ax.plot(telfer.wavelength[gdp],
                    telfer.flux[gdp].value * mock_spec.flux, 'k')

        # 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()
    return mock_spec
Example #32
0
import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
from astropy.cosmology import Planck15

from lyacolore import DLA

#Import pyigm modules
from pyigm.fN.fnmodel import FNModel
fN_default = FNModel.default_model(cosmo=Planck15)
fN_default.zmnx = (0.5, 5)
fN_cosmo = fN_default.cosmo
use_pyigm = True

include_RSDs = True
#basedir = '/global/cscratch1/sd/jfarr/LyaSkewers/CoLoRe_GAUSS/test_DLA_sample/'
basedir = '/global/projecta/projectdirs/desi/mocks/lya_forest/develop/london/v9.0/v9.0.0/'
#basedir = '/global/projecta/projectdirs/desi/mocks/lya_forest/develop/saclay/v4.4/v4.4.0/'
qso_z_buffer = 0.00

save_plot = True
ver = 'london_v9.0.0'
f_filename = 'f_NHI_{}.pdf'.format(ver)
dndz_filename = 'dndz_{}.pdf'.format(ver)

#Open a DLA master file and extract the relevant data.
h = fits.open(basedir + '/master_DLA.fits')
if include_RSDs:
    dla_z = h['DLACAT'].data['Z_DLA_RSD']
    dla_z_qso = h['DLACAT'].data['Z_QSO_RSD']
else:
Example #33
0
def get_telfer_spec(zqso=0., igm=False, fN_gamma=None, LL_flatten=True):
    '''Generate a Telfer QSO composite spectrum

    Parameters:
    ----------
    zqso: float, optional
      Redshift of the QSO
    igm: bool, optional
      Include IGM opacity? [False]
    fN_gamma: float, optional
      Power-law evolution in f(N,X)
    LL_flatten: bool, optional
      Set Telfer to a constant below the LL?

    Returns:
    --------
    telfer_spec: XSpectrum1D
      Spectrum
    '''
    # Read
    telfer = ascii.read(xa_path + '/data/quasar/telfer_hst_comp01_rq.ascii',
                        comment='#')
    scale = telfer['flux'][(telfer['wrest'] == 1450.)]
    telfer_spec = XSpectrum1D.from_tuple(
        (telfer['wrest'] * (1 + zqso),
         telfer['flux'] / scale[0]))  # Observer frame

    # IGM?
    if igm is True:
        '''The following is quite experimental.
        Use at your own risk.
        '''
        import multiprocessing
        fN_model = FNModel.default_model()
        # Expanding range of zmnx (risky)
        fN_model.zmnx = (0., 5.)
        if fN_gamma is not None:
            fN_model.gamma = fN_gamma
        # Parallel
        igm_wv = np.where(telfer['wrest'] < 1220.)[0]
        adict = []
        for wrest in telfer_spec.dispersion[igm_wv].value:
            tdict = dict(ilambda=wrest, zem=zqso, fN_model=fN_model)
            adict.append(tdict)
        # Run
        #xdb.set_trace()
        pool = multiprocessing.Pool(4)  # initialize thread pool N threads
        ateff = pool.map(pyift.map_lymanew, adict)
        # Apply
        telfer_spec.flux[igm_wv] *= np.exp(-1. * np.array(ateff))
        # Flatten?
        if LL_flatten:
            wv_LL = np.where(
                np.abs(telfer_spec.dispersion /
                       (1 + zqso) - 914. * u.AA) < 3. * u.AA)[0]
            f_LL = np.median(telfer_spec.flux[wv_LL])
            wv_low = np.where(telfer_spec.dispersion /
                              (1 + zqso) < 911.7 * u.AA)[0]
            telfer_spec.flux[wv_low] = f_LL

    # Return
    return telfer_spec
Example #34
0
    if outfil != None:
        plt.savefig(outfil,bbox_inches='tight')
    else: 
        plt.show()
        
    
## #################################    
## #################################    
## TESTING
## #################################    
if __name__ == '__main__':

    # Read a dataset
    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)
    
    print(all_fN_cs)
    for fN_c in all_fN_cs: print(fN_c)

    # Plot with model
    fnmodel = FNModel.default_model()
    tst_fn_data(fN_model=fnmodel)
    xdb.set_trace()
    print('fN.data: All done testing..')

Example #35
0
        if verbose:
            print('Calculating tau_eff from Becker+13')
        tau0 = 0.751
        beta = 2.90
        C = -0.132
        z0 = 3.5
        teff[np.where(highz)] = tau0 * ((1+z[highz])/(1+z0))**beta + C
    badz = z>zmax
    if np.sum(badz) > 0:
        raise ValueError('teff_obs: Not ready for z>{:f}'.format(zmax))

    # Return
    if flg_float:
        return teff[0]
    else:
        return teff

if __name__ == '__main__':
    import profile, pstats
    fN_model = FNModel.default_model()
    fN_model.zmnx = (0.,5.)
    zem=3.
    # Profile
    outfil = 'tmp.prof'
    profile.run('print lyman_ew(900.*(1+zem), zem, fN_model)', outfil)
    # Stats
    stats = pstats.Stats(outfil)
    stats.strip_dirs()
    stats.sort_stats('tottime')
    stats.print_stats()
Example #36
0
        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()


if __name__ == '__main__':

    flg_fig = 0
    #flg_fig += 2**0   # Without model
    flg_fig += 2**1   # With model

    # Without model
    if (flg_fig % 2**1) >= 2**0:
        tst_fn_data()

    # With model
    if (flg_fig % 2**2) >= 2**1:
        fN_default = FNModel.default_model()
        tst_fn_data(fN_model=fN_default)
Example #37
0
def test_default():
    fN_default = FNModel.default_model()
    #
    assert fN_default.mtype == 'Hspline'
    assert fN_default.zmnx == (0.5, 3)
Example #38
0
def test_lx():
    fN_default = FNModel.default_model()
    lX = fN_default.calculate_lox(2.4, 17.19 + np.log10(2.), 23.)
    np.testing.assert_allclose(lX, 0.36298679339713974)
Example #39
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
Example #40
0
def test_lx():
    fN_default = FNModel.default_model()
    lX = fN_default.calculate_lox(2.4, 17.19+np.log10(2.), 23.)
    np.testing.assert_allclose(lX, 0.36298679339713974)
Example #41
0
def test_init_I14():
    # Class
    fN_I14 = FNModel('Gamma')
    # Mtype
    assert fN_I14.mtype == 'Gamma'
    assert fN_I14.zmnx == (0., 10.)
Example #42
0
def redshift(outfil='Figures/redshift.pdf'):
    """ Series of plots illustrating redshift in the Lya forest
    """
    lrest = np.array([900., 1250])  # Ang
    zem = 3.
    toff = 0.15
    yqso = 0.7
    sqso = 35

    # QSO lines
    qsolya = AbsLine(1215.6700*u.AA)
    qsolya.attrib['N'] = 10.**(16.0)/u.cm**2
    qsolya.attrib['b'] = 40 * u.km/u.s
    qsolya.attrib['z'] = zem
    qsolyb = AbsLine('HI 1025')
    qsolyb.attrib['N'] = qsolya.attrib['N'] 
    qsolyb.attrib['b'] = qsolya.attrib['b'] 
    qsolyb.attrib['z'] = qsolya.attrib['z'] 

    def tick_function(z, X):
        V = X*(1+z)
        return ["{:d}".format(int(round(x))) for x in V]

    def add_lines(axi,z):
        wvtwo = (1+z)*1215.67/(1+zem)
        axi.scatter([wvtwo], [yqso], marker='o', facecolor='none', 
            edgecolor='green', s=sqso*5)
        axi.text(wvtwo, yqso-1.7*toff, 'HI Gas (z={:0.1f})'.format(z), 
            color='green', ha='center')
        #
        twolya = copy.deepcopy(qsolya)
        twolya.attrib['z'] = z
        twolyb = copy.deepcopy(qsolyb)
        twolyb.attrib['z'] = z
        return [twolya, twolyb]

    # Telfer
    telfer = pyicq.get_telfer_spec()

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

    plt.clf()
    gs = gridspec.GridSpec(5,1)
    jet = cm = plt.get_cmap('jet') 

    # Loop
    for qq in range(9):
        # Cartoon
        ax0 = plt.subplot(gs[0,0])
        ax0.set_xlim(lrest)
        ax0.set_ylim(0.,1.)
        ax0.set_frame_on(False)
        ax0.axes.get_yaxis().set_visible(False)
        ax0.axes.get_xaxis().set_visible(False)


        # QSO
        ax0.scatter([1215.67], [yqso], marker='o', facecolor='blue', s=sqso)
        ax0.text(1215.67, yqso+toff, 'Quasar (z=3)', color='blue', ha='center')

        # Redshifted light
        if qq > 0:
            light = np.linspace(1215.67, lrest[0],20)
            ax0.scatter(light, [yqso]*len(light), marker='_', s=40, cmap=cm, c=1./light)

        # Gas at QSO
        if qq > 1:
            ax0.scatter([1215.67], [yqso], marker='o', facecolor='none', 
                edgecolor='green', s=sqso*5)
            ax0.text(1215.67, yqso-1.7*toff, 'HI Gas (z=3)', color='green', ha='center')

        # Spectrum
        ax = plt.subplot(gs[1:,0])
        ax.set_xlim(lrest)
        #ax.set_ylim(ymnx) 
        ax.set_ylabel('Relative Flux')
        ax.set_xlabel("Rest Wavelength")
        if qq < 3:
            tsty = 'k'
        else: 
            tsty = 'b:'
        ax.plot(telfer.wavelength, telfer.flux, tsty)

        # Observer frame axis
        if qq > 0:
            ax2 = ax.twiny()
            ax2.set_xlim(ax.get_xlim())
            xtcks = ax.get_xticks()
            ax2.set_xticks(xtcks)
            ax2.set_xticklabels(tick_function(zem, xtcks))
            ax2.set_xlabel('Observed Wavelength (Angstroms)')

        # Absorption lines
        abslines = []
        if (qq > 2) and (qq != 8):  
            # Lya at zem

            abslines.append(qsolya)
            if qq > 3: # Lyb at zem
                abslines.append(qsolyb)
            # Gas at z=2.8
            if qq > 4:
                zadd = 2.8
                abslines += add_lines(ax0, zadd)
            # Gas at z=2.5
            if qq > 5:
                zadd = 2.5
                abslines += add_lines(ax0, zadd)
            if qq > 6:
                zadd = 2.2
                abslines += add_lines(ax0, zadd)
            #
            abs_model = ltav.voigt_from_abslines(telfer.wavelength*(1+zem), abslines)
            #ax.plot(telfer.wavelength, telfer.flux*abs_model.flux, 'k')
            ax.plot(telfer.wavelength, telfer.flux.value*abs_model.flux, 'k')

        # Final plot
        if qq == 8:
            nlin = 100
            dotwv = np.linspace(900,1215.,nlin)
            ax0.scatter(dotwv, [yqso]*nlin, marker='o', facecolor='none', 
                edgecolor='green', s=sqso*5)
            # Mock spectrum
            fN_model = FNModel.default_model()
            gdp = np.where(telfer.wavelength > 900.*u.AA)[0]
            mock_spec, HI_comps, misc = pyimock.mk_mock(
                telfer.wavelength[gdp]*(1+zem), 
                zem, fN_model, s2n=100., fwhm=3, add_conti=False)
            ax.plot(telfer.wavelength[gdp], 
                telfer.flux[gdp].value*mock_spec.flux, 'k')


        # 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()
    return mock_spec
Example #43
0
def test_teff():
    fN_default = FNModel.default_model()
    zval, teff_LL = pyteff.lyman_limit(fN_default, 0.5, 2.45)
    #
    np.testing.assert_allclose(zval[0], 0.5)
    np.testing.assert_allclose(teff_LL[0], 1.8197, rtol=1e-4)  # scipy 0.19
Example #44
0
def test_default():
    fN_default = FNModel.default_model()
    #
    assert fN_default.mtype == 'Hspline'
    assert fN_default.zmnx == (0.5, 3)