Example #1
0
def test_telfer_and_igm():
    telfer = pyicq.get_telfer_spec(zqso=3., igm=True, nproc=4)
    # Test in forest
    imin = np.argmin(np.abs(telfer.wavelength - 4800 * u.AA))
    np.testing.assert_allclose(telfer.flux[imin].value,
                               1.7800761461257935,
                               atol=1e-3)
Example #2
0
 def init_conti_full(self):
     print("Initializing the continuum")
     spec = self.spec_widg.orig_spec
     spec.select = self.model_spec  # Just in case, but this should already be the case
     # Full Model (LLS+continuum)
     self.full_model = XSpectrum1D.from_tuple(
         (spec.wavelength, np.ones(len(spec.wavelength))))
     self.conti_dict = pycc.init_conti_dict(
         Norm=float(np.median(spec.flux.value)),
         piv_wv=1215. * (1 + self.zqso),
         #piv_wv2=915.*(1+zqso),
         igm='True')
     # Read Telfer and apply IGM
     if self.template is not None:
         tspec = lsi.readspec(self.template)
         # assume wavelengths
         tspec = XSpectrum1D.from_tuple(
             (tspec.wavelength.value * (1 + self.zqso), tspec.flux.value))
     else:
         tspec = pycq.get_telfer_spec(
             zqso=self.zqso, igm=(self.conti_dict['igm'] == 'True'))
         # Rebin
         self.continuum = tspec.rebin(spec.wavelength)
         # Reset pivot wave
         self.conti_dict['piv_wv'] = 915. * (1 + self.zqso)
         #self.conti_dict['piv_wv'] = 1215.*(1+zqso)
         #self.conti_dict['piv_wv2'] = 915.*(1+zqso)
     self.base_continuum = self.continuum.flux
     self.update_conti()
     self.spec_widg.continuum = self.continuum
Example #3
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()
Example #4
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()
Example #5
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()
Example #6
0
    def __init__(self, ispec, parent=None, lls_fit_file=None,
        outfil=None, smooth=3., zqso=None, fN_gamma=None, template=None,
        dw=0.1, skip_wveval=False):
        QtGui.QMainWindow.__init__(self, parent)
        '''
        ispec : Spectrum1D or specfil
        lls_fit_file: str, optional
          Name of the LLS fit file to input
        smooth : float, optional
          Number of pixels to smooth on (FWHM)
        zqso : float, optional
          Redshift of the quasar.  If input, a Telfer continuum is used
        fN_gamma : float, optional
          Redshift evolution of f(N) or IGM fiddled continuum
        template : str, optional
          Filename of a QSO template to use instead of the Telfer
          continuum. Only used if zqso is also given.
        dw : float, optional
          Pixel width in Angstroms for the wavelength array used to
          generate optical depths. Default is 0.1.
        skip_wveval : bool, optional
          Skip rebinning of wavelengths in the Voigt profile generation.
          This can speed up the code considerably, but use it wisely.
        '''

        # Build a widget combining several others
        self.main_widget = QtGui.QWidget()

        # Status bar
        self.create_status_bar()

        # Initialize
        if outfil is None:
            self.outfil = 'LLS_fit.json'
        else:
            self.outfil = outfil
        self.count_lls = 0
        self.lls_model = None
        self.smooth = None
        self.base_continuum = None
        self.all_forest = []
        self.flag_write = False
        self.dw = float(dw)
        self.skip_wveval = skip_wveval
        if skip_wveval:
            warnings.warn("Skipping wavelength rebinning in Voigt.")
            warnings.warn("Make sure you know what you are doing!")

        # Spectrum
        if isinstance(ispec, XSpectrum1D):
            spec = ispec
            spec_fil = spec.filename
        else:
            # this is broken
            spec, spec_fil = ltgu.read_spec(ispec)


        # LineList
        self.llist = ltgu.set_llist('Strong')
        self.llist['z'] = 0.
        self.plt_wv = zip(np.array([911.7, 949.743, 972.5367,1025.7222,1215.6700])*u.AA,
            ['LL','Lyd', 'Lyg','Lyb','Lya'])

        # z and N boxes
        self.zwidget = ltgsm.EditBox(-1., 'z_LLS=', '{:0.5f}')
        self.Nwidget = ltgsm.EditBox(-1., 'NHI=', '{:0.2f}')
        self.bwidget = ltgsm.EditBox(-1., 'b=', '{:0.1f}')
        self.Cwidget = ltgsm.EditBox('None', 'Comment=', '{:s}')

        # Grab the pieces and tie together
        self.abssys_widg = xspw.AbsSysWidget([],only_one=True,
            no_buttons=True, linelist=self.llist[self.llist['List']])

        vlines = [(912 * (1 + zqso) if zqso is not None else None)]
        self.spec_widg = ltgsp.ExamineSpecWidget(spec,status=self.statusBar,
                                           llist=self.llist, key_events=False,
                                           abs_sys=self.abssys_widg.abs_sys,
                                           vlines=vlines, plotzero=1)
        # Initialize continuum (and LLS if from a file)
        if lls_fit_file is not None:
            self.init_LLS(lls_fit_file,spec)
        else:
            self.conti_dict = pycc.init_conti_dict(
                Norm=float(np.median(spec.flux.value)),
                piv_wv=1215.*(1+zqso),
                #piv_wv2=915.*(1+zqso),
                igm='True')
        if self.base_continuum is None:
            if zqso is not None:
                self.zqso = zqso
                # Read Telfer and apply IGM
                if template is not None:
                    tspec = lsi.readspec(template)
                    # assume wavelengths
                    tspec = XSpectrum1D.from_tuple(
                        (tspec.dispersion.value * (1 + zqso),
                        tspec.flux.value))
                else:
                    tspec = pycq.get_telfer_spec(zqso=zqso,
                              igm=(self.conti_dict['igm']=='True'))
                # Rebin
                self.continuum = tspec.rebin(spec.dispersion)
                # Reset pivot wave
                self.conti_dict['piv_wv'] = 915.*(1+zqso)
                #self.conti_dict['piv_wv'] = 1215.*(1+zqso)
                #self.conti_dict['piv_wv2'] = 915.*(1+zqso)
            else:
                self.zqso = None
                self.continuum = XSpectrum1D.from_tuple((
                    spec.dispersion,np.ones(len(spec.dispersion))))
            self.base_continuum = self.continuum.flux
        self.update_conti()

        self.spec_widg.continuum = self.continuum

        # Full Model (LLS+continuum)
        self.full_model = XSpectrum1D.from_tuple((
            spec.dispersion,np.ones(len(spec.dispersion))))
        if self.smooth is None:
            self.smooth = smooth

        # Initialize as needed
        if lls_fit_file is not None:
            self.update_boxes()
            self.update_model()

        # Outfil
        wbtn = QtGui.QPushButton('Write', self)
        wbtn.setAutoDefault(False)
        wbtn.clicked.connect(self.write_out)
        #self.out_box = QtGui.QLineEdit()
        #self.out_box.setText(self.outfil)
        #self.connect(self.out_box, QtCore.SIGNAL('editingFinished ()'), self.set_outfil)

        # Quit
        buttons = QtGui.QWidget()
        wqbtn = QtGui.QPushButton('Write\n Quit', self)
        wqbtn.setAutoDefault(False)
        wqbtn.clicked.connect(self.write_quit)
        qbtn = QtGui.QPushButton('Quit', self)
        qbtn.setAutoDefault(False)
        qbtn.clicked.connect(self.quit)

        # Connections (buttons are above)
        self.spec_widg.canvas.mpl_connect('key_press_event', self.on_key)
        self.abssys_widg.abslist_widget.itemSelectionChanged.connect(
            self.on_list_change)
        self.connect(self.Nwidget.box,
            QtCore.SIGNAL('editingFinished ()'), self.setbzN)
        self.connect(self.zwidget.box,
            QtCore.SIGNAL('editingFinished ()'), self.setbzN)
        self.connect(self.bwidget.box,
            QtCore.SIGNAL('editingFinished ()'), self.setbzN)
        self.connect(self.Cwidget.box,
            QtCore.SIGNAL('editingFinished ()'), self.setbzN)

        # Layout
        anly_widg = QtGui.QWidget()
        anly_widg.setMaximumWidth(400)
        anly_widg.setMinimumWidth(250)

        # Write/Quit buttons
        hbox1 = QtGui.QHBoxLayout()
        hbox1.addWidget(wbtn)
        hbox1.addWidget(wqbtn)
        hbox1.addWidget(qbtn)
        buttons.setLayout(hbox1)

        # z,N
        zNwidg = QtGui.QWidget()
        hbox2 = QtGui.QHBoxLayout()
        hbox2.addWidget(self.zwidget)
        hbox2.addWidget(self.Nwidget)
        hbox2.addWidget(self.bwidget)
        zNwidg.setLayout(hbox2)
        #vbox.addWidget(self.pltline_widg)

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(zNwidg)
        vbox.addWidget(self.Cwidget)
        vbox.addWidget(self.abssys_widg)
        vbox.addWidget(buttons)
        anly_widg.setLayout(vbox)

        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(self.spec_widg)
        hbox.addWidget(anly_widg)

        self.main_widget.setLayout(hbox)

        # Point MainWindow
        self.setCentralWidget(self.main_widget)

        #self.spec_widg.setFixedWidth(900)
        self.spec_widg.setMinimumWidth(900)
Example #7
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 #8
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 #9
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()
Example #10
0
def test_telfer_and_igm():
    telfer = pyicq.get_telfer_spec(zqso=3., igm=True, nproc=4)
    # Test
    np.testing.assert_allclose(telfer.flux[100].value, 0.9383676133341446)
Example #11
0
def test_telfer():
    #
    telfer = pyicq.get_telfer_spec(3.)
    np.testing.assert_allclose(telfer.flux[100].value, 2.297435281318983)
Example #12
0
def test_telfer():
    #
    telfer = pyicq.get_telfer_spec(3.)
    np.testing.assert_allclose(telfer.flux[100].value, 2.297435281318983)
Example #13
0
    def __init__(self,
                 ispec,
                 parent=None,
                 lls_fit_file=None,
                 outfil=None,
                 smooth=3.,
                 zqso=None,
                 fN_gamma=None,
                 template=None,
                 dw=0.1,
                 skip_wveval=False,
                 norm=True):
        QtGui.QMainWindow.__init__(self, parent)
        '''
        ispec : Spectrum1D or specfil
        lls_fit_file: str, optional
          Name of the LLS fit file to input
        smooth : float, optional
          Number of pixels to smooth on (FWHM)
        zqso : float, optional
          Redshift of the quasar.  If input, a Telfer continuum is used
        fN_gamma : float, optional
          Redshift evolution of f(N) or IGM fiddled continuum
        template : str, optional
          Filename of a QSO template to use instead of the Telfer
          continuum. Only used if zqso is also given.
        dw : float, optional
          Pixel width in Angstroms for the wavelength array used to
          generate optical depths. Default is 0.1.
        skip_wveval : bool, optional
          Skip rebinning of wavelengths in the Voigt profile generation.
          This can speed up the code considerably, but use it wisely.
        norm : bool, optional
          Whether to normalize the spectrum by dividing by the
          continuum (default True).
        '''

        # Build a widget combining several others
        self.main_widget = QtGui.QWidget()

        # Status bar
        self.create_status_bar()

        # Initialize
        if outfil is None:
            self.outfil = 'LLS_fit.json'
        else:
            self.outfil = outfil
        self.count_lls = 0
        self.lls_model = None
        self.smooth = None
        self.base_continuum = None
        self.all_forest = []
        self.flag_write = False
        self.dw = float(dw)
        self.skip_wveval = skip_wveval
        if skip_wveval:
            warnings.warn("Skipping wavelength rebinning in Voigt.")
            warnings.warn("Make sure you know what you are doing!")

        # Spectrum
        if isinstance(ispec, XSpectrum1D):
            spec = ispec
            spec_fil = spec.filename
        else:
            # this is broken
            spec, spec_fil = ltgu.read_spec(ispec)

        # LineList
        self.llist = ltgu.set_llist('Strong')
        self.llist['z'] = 0.
        self.plt_wv = zip(
            np.array([911.7, 949.743, 972.5367, 1025.7222, 1215.6700]) * u.AA,
            ['LL', 'Lyd', 'Lyg', 'Lyb', 'Lya'])

        # z and N boxes
        self.zwidget = ltgsm.EditBox(-1., 'z_LLS=', '{:0.5f}')
        self.Nwidget = ltgsm.EditBox(-1., 'NHI=', '{:0.2f}')
        self.bwidget = ltgsm.EditBox(-1., 'b=', '{:0.1f}')
        self.Cwidget = ltgsm.EditBox('None', 'Comment=', '{:s}')

        # Grab the pieces and tie together
        self.abssys_widg = xspw.AbsSysWidget(
            [],
            only_one=True,
            no_buttons=True,
            linelist=self.llist[self.llist['List']])

        vlines = [(912 * (1 + zqso) if zqso is not None else None)]
        self.spec_widg = ltgsp.ExamineSpecWidget(
            spec,
            status=self.statusBar,
            llist=self.llist,
            key_events=False,
            abs_sys=self.abssys_widg.abs_sys,
            vlines=vlines,
            plotzero=1,
            norm=norm)
        # Initialize continuum (and LLS if from a file)
        if lls_fit_file is not None:
            self.init_LLS(lls_fit_file, spec)
        else:
            self.conti_dict = pycc.init_conti_dict(
                Norm=float(np.median(spec.flux.value)),
                piv_wv=1215. * (1 + zqso),
                #piv_wv2=915.*(1+zqso),
                igm='True')
        if self.base_continuum is None:
            if zqso is not None:
                self.zqso = zqso
                # Read Telfer and apply IGM
                if template is not None:
                    tspec = lsi.readspec(template)
                    # assume wavelengths
                    tspec = XSpectrum1D.from_tuple(
                        (tspec.wavelength.value * (1 + zqso),
                         tspec.flux.value))
                else:
                    tspec = pycq.get_telfer_spec(
                        zqso=zqso, igm=(self.conti_dict['igm'] == 'True'))
                # Rebin
                self.continuum = tspec.rebin(spec.wavelength)
                # Reset pivot wave
                self.conti_dict['piv_wv'] = 915. * (1 + zqso)
                #self.conti_dict['piv_wv'] = 1215.*(1+zqso)
                #self.conti_dict['piv_wv2'] = 915.*(1+zqso)
            else:
                self.zqso = None
                self.continuum = XSpectrum1D.from_tuple(
                    (spec.wavelength, np.ones(len(spec.wavelength))))
            self.base_continuum = self.continuum.flux
        self.update_conti()

        self.spec_widg.continuum = self.continuum

        # Full Model (LLS+continuum)
        self.full_model = XSpectrum1D.from_tuple(
            (spec.wavelength, np.ones(len(spec.wavelength))))
        if self.smooth is None:
            self.smooth = smooth

        # Initialize as needed
        if lls_fit_file is not None:
            self.update_boxes()
            self.update_model()

        # Outfil
        wbtn = QtGui.QPushButton('Write', self)
        wbtn.setAutoDefault(False)
        wbtn.clicked.connect(self.write_out)
        #self.out_box = QtGui.QLineEdit()
        #self.out_box.setText(self.outfil)
        #self.connect(self.out_box, QtCore.SIGNAL('editingFinished ()'), self.set_outfil)

        # Quit
        buttons = QtGui.QWidget()
        wqbtn = QtGui.QPushButton('Write\n Quit', self)
        wqbtn.setAutoDefault(False)
        wqbtn.clicked.connect(self.write_quit)
        qbtn = QtGui.QPushButton('Quit', self)
        qbtn.setAutoDefault(False)
        qbtn.clicked.connect(self.quit)

        # Connections (buttons are above)
        self.spec_widg.canvas.mpl_connect('key_press_event', self.on_key)
        self.abssys_widg.abslist_widget.itemSelectionChanged.connect(
            self.on_list_change)
        self.connect(self.Nwidget.box, QtCore.SIGNAL('editingFinished ()'),
                     self.setbzN)
        self.connect(self.zwidget.box, QtCore.SIGNAL('editingFinished ()'),
                     self.setbzN)
        self.connect(self.bwidget.box, QtCore.SIGNAL('editingFinished ()'),
                     self.setbzN)
        self.connect(self.Cwidget.box, QtCore.SIGNAL('editingFinished ()'),
                     self.setbzN)

        # Layout
        anly_widg = QtGui.QWidget()
        anly_widg.setMaximumWidth(400)
        anly_widg.setMinimumWidth(250)

        # Write/Quit buttons
        hbox1 = QtGui.QHBoxLayout()
        hbox1.addWidget(wbtn)
        hbox1.addWidget(wqbtn)
        hbox1.addWidget(qbtn)
        buttons.setLayout(hbox1)

        # z,N
        zNwidg = QtGui.QWidget()
        hbox2 = QtGui.QHBoxLayout()
        hbox2.addWidget(self.zwidget)
        hbox2.addWidget(self.Nwidget)
        hbox2.addWidget(self.bwidget)
        zNwidg.setLayout(hbox2)
        #vbox.addWidget(self.pltline_widg)

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(zNwidg)
        vbox.addWidget(self.Cwidget)
        vbox.addWidget(self.abssys_widg)
        vbox.addWidget(buttons)
        anly_widg.setLayout(vbox)

        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(self.spec_widg)
        hbox.addWidget(anly_widg)

        self.main_widget.setLayout(hbox)

        # Point MainWindow
        self.setCentralWidget(self.main_widget)

        #self.spec_widg.setFixedWidth(900)
        self.spec_widg.setMinimumWidth(900)
Example #14
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 #15
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 #16
0
def test_telfer_and_igm():
    telfer = pyicq.get_telfer_spec(zqso=3., igm=True, nproc=4)
    # Test in forest
    imin = np.argmin(np.abs(telfer.wavelength - 4800*u.AA))
    np.testing.assert_allclose(telfer.flux[imin].value, 1.7800761461257935)