예제 #1
0
def test_rdspec():
    spec, spec_fil = ltgu.read_spec(data_path('UM184_nF.fits'))
    #
    ispec = lsio.readspec(data_path('UM184_nF.fits'))
    spec, spec_fil = ltgu.read_spec(ispec)
    # as tuple without units
    ispec = (np.ones(10), np.ones(10), np.ones(10))
    spec, spec_fil = ltgu.read_spec(ispec)
    assert spec_fil == 'none'
    # as list of files
    ispec = [data_path('UM184_nF.fits')]*2
    spec, spec_fil = ltgu.read_spec(ispec)
    spec, spec_fil = ltgu.read_spec(ispec, exten=[1,1])  # is iterable exten
    # wrong format
    with pytest.raises(ValueError):
        spec, spec_fil = ltgu.read_spec(dict(a='dummy'))  # input is a dict
    # normalize
    spec, spec_fil = ltgu.read_spec(data_path('UM184_nF.fits'))
    spec.co = spec.flux
    spec, spec_fil = ltgu.read_spec(spec)
    assert spec.normed
예제 #2
0
def test_rdspec():
    spec, spec_fil = ltgu.read_spec(data_path('UM184_nF.fits'))
    #
    ispec = lsio.readspec(data_path('UM184_nF.fits'))
    spec, spec_fil = ltgu.read_spec(ispec)
    # as tuple without units
    ispec = (np.ones(10), np.ones(10), np.ones(10))
    spec, spec_fil = ltgu.read_spec(ispec)
    assert spec_fil == 'none'
    # as list of files
    ispec = [data_path('UM184_nF.fits')] * 2
    spec, spec_fil = ltgu.read_spec(ispec)
    spec, spec_fil = ltgu.read_spec(ispec, exten=[1, 1])  # is iterable exten
    # wrong format
    with pytest.raises(ValueError):
        spec, spec_fil = ltgu.read_spec(dict(a='dummy'))  # input is a dict
    # normalize
    spec, spec_fil = ltgu.read_spec(data_path('UM184_nF.fits'))
    spec.co = spec.flux
    spec, spec_fil = ltgu.read_spec(spec)
    assert spec.normed
예제 #3
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)
예제 #4
0
    def __init__(self, ispec, parent=None, status=None, llist=None,
                 abs_sys=None, norm=True, second_file=None, zsys=None,
                 key_events=True, vlines=None, plotzero=False, exten=None,
                 xlim=None, ylim=None):
        """
        Parameters
        ----------
        ispec : Spectrum1D or tuple of arrays
        exten : int, optional
          extension for the spectrum in multi-extension FITS file
        parent : Widget parent, optional
        status : Point to status bar, optional
        llist : dict, optional
          Used to guide the line lists
        abs_sys : list, optional
          AbsSystem's
        zsys : float, optional
          intial redshift
        key_events : bool, optional
          Use key events? [True]
          Useful when coupling to other widgets
        xlim : tuple of two floats
          Initial x plotting limits
        ylim : tuple of two floats
          Initial y plotting limits
        """
        super(ExamineSpecWidget, self).__init__(parent)

        # Spectrum
        spec, spec_fil = ltgu.read_spec(ispec, exten=exten, norm=norm)
        self.orig_spec = spec  # For smoothing
        self.spec = self.orig_spec

        self.vlines = []
        if vlines is not None:
            self.vlines.extend(vlines)

        self.plotzero = plotzero

        # Other bits (modified by other widgets)
        self.continuum = None
        self.model = None
        self.bad_model = None  # Discrepant pixels in model
        self.use_event = 1

        # Abs Systems
        if abs_sys is None:
            self.abs_sys = []
        else:
            self.abs_sys = abs_sys
        self.norm = norm
        self.psdict = {}  # Dict for spectra plotting
        self.adict = {}  # Dict for analysis
        self.init_spec(xlim=xlim, ylim=ylim)
        self.xval = None  # Used with velplt

        # Status Bar?
        if not status is None:
            self.statusBar = status

        # Line List?
        if llist is None:
            self.llist = {'Plot': False, 'List': 'None', 'z': 0., 'Lists': []}
        else:
            self.llist = llist

        # zsys
        if zsys is not None:
            self.llist['z'] = zsys

        # Create the mpl Figure and FigCanvas objects.
        # 5x4 inches, 100 dots-per-inch
        #
        self.dpi = 150  # 150
        self.fig = Figure((8.0, 4.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)

        self.canvas.setFocusPolicy( QtCore.Qt.ClickFocus )
        self.canvas.setFocus()
        if key_events:
            self.canvas.mpl_connect('key_press_event', self.on_key)
        self.canvas.mpl_connect('button_press_event', self.on_click)

        # Make two plots
        self.ax = self.fig.add_subplot(1, 1, 1)
        self.fig.subplots_adjust(hspace=0.1, wspace=0.1)

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.canvas)

        self.setLayout(vbox)

        # Draw on init
        self.on_draw()
예제 #5
0
    def __init__(self, ispec, z, abs_lines=None, parent=None, llist=None, norm=True,
                 vmnx=[-300., 300.]*u.km/u.s):
        '''
        spec : XSpectrum1D
        z : float
        abs_lines: list, optional
          List of AbsLines
        llist : LineList, optional
          Input line list.  Defaults to 'Strong'
        norm : bool, optional
          Normalized spectrum?
        vmnx : Quantity array, optional
          Starting velocity range for the widget
        '''
        super(VelPlotWidget, self).__init__(parent)
        self.help_message = """
Click on any white region within the velocity plots
for the following keystroke commands to work:

i,o       : zoom in/out x limits
I,O       : zoom in/out x limits (larger re-scale)
y         : zoom out y limits
t,b       : set y top/bottom limit
l,r       : set left/right x limit
[,]       : pan left/right
C,c       : add/remove column
K,k       : add/remove row
=,-       : move to next/previous page
1,2       : Modify velocity region of the single line (left, right sides)
!,@       : Modify velocity region of all lines (left, right)
A,x       : Add/remove select line from analysis list
X         : Remove all lines from analysis list
^,&       : Flag line to be analyzed for low/high-ion kinematics
B         : Toggle as blend/no-blend  (orange color = blend)
N         : Toggle as do/do-not include for analysis  (red color = exclude)
V         : Indicate as a normal value
L         : Indicate as a lower limit
U         : Indicate as a upper limit
?         : Print this
        """

        # Initialize
        spec, spec_fil = ltgu.read_spec(ispec)

        self.spec = spec
        self.spec_fil = spec_fil
        self.z = z
        self.vmnx = vmnx
        self.norm = norm

        # Abs Lines
        if abs_lines is None:
            self.abs_lines = []
        else:
            self.abs_lines = abs_lines

        #QtCore.pyqtRemoveInputHook()
        #xdb.set_trace()
        #QtCore.pyqtRestoreInputHook()

        self.psdict = {} # Dict for spectra plotting
        self.psdict['x_minmax'] = self.vmnx.value # Too much pain to use units with this
        self.psdict['y_minmax'] = [-0.1, 1.1]
        self.psdict['nav'] = ltgu.navigate(0,0,init=True)

        # Line List
        if llist is None:
            self.llist = ltgu.set_llist('Strong')
        else:
            self.llist = llist
        self.llist['z'] = self.z

        # Indexing for line plotting
        self.idx_line = 0
        self.init_lines()

        # Create the mpl Figure and FigCanvas objects.
        self.dpi = 150
        self.fig = Figure((8.0, 4.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)

        self.canvas.setFocusPolicy( QtCore.Qt.ClickFocus )
        self.canvas.setFocus()
        self.canvas.mpl_connect('key_press_event', self.on_key)
        self.canvas.mpl_connect('button_press_event', self.on_click)

        # Sub_plots (Initial)
        self.sub_xy = [3,4]
        self.fig.subplots_adjust(hspace=0.0, wspace=0.1)

        # Layout
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.canvas)
        self.setLayout(vbox)

        # Print help message
        print(self.help_message)

        # Draw on init
        self.on_draw()
예제 #6
0
파일: fitlls.py 프로젝트: yzhenggit/pyigm
    def __init__(self,
                 ispec,
                 zqso,
                 parent=None,
                 lls_fit_file=None,
                 outfil=None,
                 smooth=3.,
                 fN_gamma=None,
                 template=None,
                 dw=0.1,
                 skip_wveval=False,
                 coord=None,
                 **kwargs):
        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 = QWidget()

        # Status bar
        self.create_status_bar()

        # Initialize
        self.update = True
        if outfil is None:
            self.outfil = 'LLS_fit.json'
        else:
            self.outfil = outfil
        self.zqso = zqso
        self.count_lls = 0
        self.model_spec = -1
        self.lls_model = None
        self.template = template
        self.coord = coord
        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, **kwargs)

        # 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 = ltgsp.AbsSysWidget(
            [],
            only_one=True,
            no_buttons=True,
            linelist=self.llist[self.llist['List']])

        vlines = [912 * (1 + zqso)]
        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=False)
        #QtCore.pyqtRemoveInputHook()
        #pdb.set_trace()
        #QtCore.pyqtRestoreInputHook()
        #self.spec_widg.canvas.mpl_connect('button_press_event', self.on_click)
        # Multi spec
        self.mspec_widg = ltgsp.MultiSpecWidget(self.spec_widg)

        # Initialize continuum (and LLS if from a file)
        if lls_fit_file is not None:
            self.init_LLS(lls_fit_file, spec)
            #QtCore.pyqtRemoveInputHook()
            #pdb.set_trace()
            #QtCore.pyqtRestoreInputHook()
            self.update_conti()
            self.spec_widg.continuum = self.continuum

        if self.model_spec < 0:
            print(
                "NOTE: You must specify the spectrum for fitting the LLS with # before modeling will begin"
            )

        if self.smooth is None:
            self.smooth = smooth
        self.llist['Plot'] = False

        # Initialize as needed
        if lls_fit_file is not None:
            if len(self.abssys_widg.all_abssys) > 0:
                self.update_boxes()
                self.update_model()

        # Outfil
        wbtn = 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 = QWidget()
        wqbtn = QPushButton('Write\n Quit', self)
        wqbtn.setAutoDefault(False)
        wqbtn.clicked.connect(self.write_quit)
        qbtn = 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.Nwidget.box.textChanged[str].connect(self.setbzN)
        self.zwidget.box.textChanged[str].connect(self.setbzN)
        self.bwidget.box.textChanged[str].connect(self.setbzN)
        self.Cwidget.box.textChanged[str].connect(self.setbzN)

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

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

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

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

        hbox = 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)
예제 #7
0
    def __init__(self, ispec, z=None, parent=None, llist=None, norm=True,
                 vmnx=[-300., 300.]*u.km/u.s, abs_sys=None):
        '''
        spec = Spectrum1D
        Norm: Bool (False)
          Normalized spectrum?
        abs_sys: AbsSystem
          Absorption system class
        '''
        super(VelPlotWidget, self).__init__(parent)

        # Initialize
        spec, spec_fil = ltgu.read_spec(ispec)
        
        self.spec = spec
        self.spec_fil = spec_fil
        self.z = z
        self.vmnx = vmnx
        self.norm = norm

        # Abs_System 
        self.abs_sys = abs_sys
        if self.abs_sys is None:
            self.abs_sys = GenericAbsSystem((0.*u.deg,0.*u.deg), self.z, self.vmnx)
            self.abs_lines = []
        else:
            self.z = self.abs_sys.zabs
            # Line list
            if llist is None:
                self.abs_lines = self.abs_sys.list_of_abslines()
                if len(self.abs_lines)>0:
                    lwrest = [iline.wrest for iline in self.abs_lines]
                else:
                    lwrest = None
                if lwrest is not None:
                    llist = ltgu.set_llist(lwrest) # Not sure this is working..

        #QtCore.pyqtRemoveInputHook()
        #xdb.set_trace()
        #QtCore.pyqtRestoreInputHook()

        self.psdict = {} # Dict for spectra plotting
        self.psdict['xmnx'] = self.vmnx.value # Too much pain to use units with this
        self.psdict['ymnx'] = [-0.1, 1.1]
        self.psdict['nav'] = ltgu.navigate(0,0,init=True)

        # Status Bar?
        #if not status is None:
        #    self.statusBar = status

        # Line List
        if llist is None:
            self.llist = ltgu.set_llist('Strong')
        else:
            self.llist = llist
        self.llist['z'] = self.z

        # Indexing for line plotting
        self.idx_line = 0

        self.init_lines()
        
        # Create the mpl Figure and FigCanvas objects. 
        #
        self.dpi = 150
        self.fig = Figure((8.0, 4.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)

        self.canvas.setFocusPolicy( QtCore.Qt.ClickFocus )
        self.canvas.setFocus()
        self.canvas.mpl_connect('key_press_event', self.on_key)
        self.canvas.mpl_connect('button_press_event', self.on_click)

        # Sub_plots
        self.sub_xy = [3,4]

        self.fig.subplots_adjust(hspace=0.0, wspace=0.1)
        
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.canvas)
        
        self.setLayout(vbox)

        # Draw on init
        self.on_draw()
예제 #8
0
    def __init__(self,
                 ispec,
                 guessfile=None,
                 parent=None,
                 zsys=None,
                 norm=None,
                 exten=None,
                 rsp_kwargs={},
                 unit_test=False,
                 screen_scale=1.,
                 **kwargs):
        QMainWindow.__init__(self, parent)
        """
        ispec = str, XSpectrum1D or tuple of arrays
          Input spectrum or spectrum filename.  If tuple then (wave,
          fx), (wave, fx, sig) or (wave, fx, sig, co)
        guessfile : str, optional
          name of the .json file generated with igmguesses GUI in Pyigm (see https://github.com/pyigm/pyigm/blob/master/docs/igmguesses.rst)
          if not None - overplot fitted line profiles from igmguesses
        parent : Widget parent, optional
        zsys : float, optional
          intial redshift
        exten : int, optional
          extension for the spectrum in multi-extension FITS file
        norm : bool, optional
          True if the spectrum is normalized
        screen_scale : float, optional
          Scale the default sizes for the gui size
        """
        #reload(ltgl)
        #reload(ltgsp)
        # INIT
        #QtCore.pyqtRemoveInputHook()
        #xdb.set_trace()
        #QtCore.pyqtRestoreInputHook()

        self.scale = screen_scale

        # Needed to avoid crash in large spectral files
        rcParams['agg.path.chunksize'] = 20000
        rcParams[
            'axes.formatter.useoffset'] = False  # avoid scientific notation in axes tick labels

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

        # Status bar
        self.create_status_bar()

        # Grab the pieces and tie together
        self.pltline_widg = ltgl.PlotLinesWidget(status=self.statusBar,
                                                 init_z=zsys,
                                                 screen_scale=self.scale)
        self.pltline_widg.setMaximumWidth(300 * self.scale)

        ## Abs sys
        abs_sys = None
        voigtsfit = None
        if guessfile is not None:
            # Load
            ism = LineList('ISM')
            igm_guess = ltu.loadjson(guessfile)
            comps = []
            for key in igm_guess['cmps'].keys():
                comp = AbsComponent.from_dict(igm_guess['cmps'][key],
                                              chk_vel=False,
                                              linelist=ism)
                comps.append(comp)
            abs_sys = ltiu.build_systems_from_components(
                comps, vsys=500. * u.km /
                u.s)  # ,chk_z=False)  ### 100000.*u.km/u.s   ok

            ### voigt fit - added
            # Spectrum
            spec, spec_fil = ltgu.read_spec(ispec,
                                            exten=exten,
                                            norm=norm,
                                            rsp_kwargs=rsp_kwargs)

            voigtsfit = np.asarray([0] * len(spec.wavelength))
            alllines = []
            for iabs_sys in abs_sys:
                lines = iabs_sys.list_of_abslines()
                alllines = alllines + lines
            if len(alllines) > 0:
                voigtsfit = lav.voigt_from_abslines(spec.wavelength,
                                                    alllines,
                                                    fwhm=3.).flux.value

            if not norm:
                voigtsfit = voigtsfit * spec.co

        # Hook the spec widget to Plot Line
        self.spec_widg = ltgsp.ExamineSpecWidget(ispec,
                                                 guessfile=guessfile,
                                                 voigtsfit=voigtsfit,
                                                 status=self.statusBar,
                                                 parent=self,
                                                 llist=self.pltline_widg.llist,
                                                 zsys=zsys,
                                                 norm=norm,
                                                 exten=exten,
                                                 abs_sys=abs_sys,
                                                 screen_scale=self.scale,
                                                 rsp_kwargs=rsp_kwargs,
                                                 **kwargs)
        # Reset redshift from spec
        if zsys is None:
            if hasattr(self.spec_widg.spec, 'z'):
                self.pltline_widg.setz(
                    str(self.spec_widg.spec.z[self.spec_widg.select]))
        # Auto set line list if spec has proper object type
        if hasattr(self.spec_widg.spec, 'stypes'):
            if self.spec_widg.spec.stypes[
                    self.spec_widg.select].lower() == 'galaxy':
                self.pltline_widg.llist = ltgu.set_llist(
                    'Galaxy', in_dict=self.pltline_widg.llist)
            elif self.spec_widg.spec.stypes[
                    self.spec_widg.select].lower() == 'absorber':
                self.pltline_widg.llist = ltgu.set_llist(
                    'Strong', in_dict=self.pltline_widg.llist)
            self.pltline_widg.llist['Plot'] = True
            idx = self.pltline_widg.lists.index(
                self.pltline_widg.llist['List'])
            self.pltline_widg.llist_widget.setCurrentRow(idx)
        #
        self.pltline_widg.spec_widg = self.spec_widg
        # Multi spec
        self.mspec_widg = ltgsp.MultiSpecWidget(self.spec_widg)

        self.spec_widg.canvas.mpl_connect('button_press_event', self.on_click)

        # Layout

        # Extras
        extras = QWidget()
        extras.setMinimumWidth(180 * self.scale)
        extras.setMaximumWidth(280 * self.scale)
        vbox = QVBoxLayout()
        qbtn = QPushButton(self)
        qbtn.setText('Quit')
        qbtn.clicked.connect(self.quit)
        vbox.addWidget(self.pltline_widg)
        vbox.addWidget(self.mspec_widg)
        vbox.addWidget(qbtn)
        extras.setLayout(vbox)

        # Main window
        hbox = QHBoxLayout()
        hbox.addWidget(self.spec_widg)
        hbox.addWidget(extras)

        self.main_widget.setLayout(hbox)

        # Point MainWindow
        self.setCentralWidget(self.main_widget)
        if unit_test:
            self.quit()
예제 #9
0
    def __init__(self,
                 ispec,
                 parent=None,
                 dla_fit_file=None,
                 zqso=None,
                 outfil=None,
                 smooth=3.,
                 dw=0.1,
                 skip_wveval=False,
                 norm=True):
        QtGui.QMainWindow.__init__(self, parent)
        """
        ispec : Spectrum1D or specfil
        dla_fit_file: str, optional
          Name of the LLS fit file to input
        smooth : float, optional
          Number of pixels to smooth on (FWHM)
        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 = 'DLA_fit.json'
        else:
            self.outfil = outfil
        self.count_dla = 0
        self.dla_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
        self.zqso = zqso
        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:
            spec, spec_fil = ltgu.read_spec(ispec)
        self.spec = spec

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

        # z and N boxes
        self.zwidget = ltgsm.EditBox(-1., 'z_DLA=', '{: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']])

        self.spec_widg = ltgsp.ExamineSpecWidget(
            spec,
            status=self.statusBar,
            llist=self.llist,
            key_events=False,
            abs_sys=self.abssys_widg.abs_sys,
            plotzero=1,
            norm=norm)
        # Initialize continuum (and LLS if from a file)
        if dla_fit_file is not None:
            self.init_DLA(dla_fit_file, spec)
        else:
            if zqso is not None:
                co, knots = laco.find_continuum(spec, redshift=self.zqso)
            else:
                co, knots = laco.find_continuum(spec, kind='default')
            self.conti_dict = dict(co=co, knots=knots)

        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 dla_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)
예제 #10
0
    def __init__(self,
                 ispec,
                 z=None,
                 parent=None,
                 llist=None,
                 norm=True,
                 vmnx=[-300., 300.] * u.km / u.s,
                 abs_sys=None):
        '''
        spec = Spectrum1D
        Norm: Bool (False)
          Normalized spectrum?
        abs_sys: AbsSystem
          Absorption system class
        '''
        super(VelPlotWidget, self).__init__(parent)

        # Initialize
        spec, spec_fil = ltgu.read_spec(ispec)

        self.spec = spec
        self.spec_fil = spec_fil
        self.z = z
        self.vmnx = vmnx
        self.norm = norm

        # Abs_System
        self.abs_sys = abs_sys
        if self.abs_sys is None:
            self.abs_sys = GenericAbsSystem((0. * u.deg, 0. * u.deg), self.z,
                                            self.vmnx)
            self.abs_lines = []
        else:
            self.z = self.abs_sys.zabs
            # Line list
            if llist is None:
                self.abs_lines = self.abs_sys.list_of_abslines()
                if len(self.abs_lines) > 0:
                    lwrest = [iline.wrest for iline in self.abs_lines]
                else:
                    lwrest = None
                if lwrest is not None:
                    llist = ltgu.set_llist(
                        lwrest)  # Not sure this is working..

        #QtCore.pyqtRemoveInputHook()
        #xdb.set_trace()
        #QtCore.pyqtRestoreInputHook()

        self.psdict = {}  # Dict for spectra plotting
        self.psdict[
            'xmnx'] = self.vmnx.value  # Too much pain to use units with this
        self.psdict['ymnx'] = [-0.1, 1.1]
        self.psdict['nav'] = ltgu.navigate(0, 0, init=True)

        # Status Bar?
        #if not status is None:
        #    self.statusBar = status

        # Line List
        if llist is None:
            self.llist = ltgu.set_llist('Strong')
        else:
            self.llist = llist
        self.llist['z'] = self.z

        # Indexing for line plotting
        self.idx_line = 0

        self.init_lines()

        # Create the mpl Figure and FigCanvas objects.
        #
        self.dpi = 150
        self.fig = Figure((8.0, 4.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)

        self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
        self.canvas.setFocus()
        self.canvas.mpl_connect('key_press_event', self.on_key)
        self.canvas.mpl_connect('button_press_event', self.on_click)

        # Sub_plots
        self.sub_xy = [3, 4]

        self.fig.subplots_adjust(hspace=0.0, wspace=0.1)

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.canvas)

        self.setLayout(vbox)

        # Draw on init
        self.on_draw()
예제 #11
0
    def __init__(self, ispec, parent=None, dla_fit_file=None,
                 zqso=None, outfil=None, smooth=3., dw=0.1,
                 skip_wveval=False, norm=True):
        QtGui.QMainWindow.__init__(self, parent)
        """
        ispec : Spectrum1D or specfil
        dla_fit_file: str, optional
          Name of the LLS fit file to input
        smooth : float, optional
          Number of pixels to smooth on (FWHM)
        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 = 'DLA_fit.json'
        else:
            self.outfil = outfil
        self.count_dla = 0
        self.dla_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
        self.zqso = zqso
        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:
            spec, spec_fil = ltgu.read_spec(ispec)
        self.spec = spec


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

        # z and N boxes
        self.zwidget = ltgsm.EditBox(-1., 'z_DLA=', '{: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']])

        self.spec_widg = ltgsp.ExamineSpecWidget(spec,status=self.statusBar,
                                           llist=self.llist, key_events=False,
                                           abs_sys=self.abssys_widg.abs_sys,
                                           plotzero=1, norm=norm)
        # Initialize continuum (and LLS if from a file)
        if dla_fit_file is not None:
            self.init_DLA(dla_fit_file,spec)
        else:
            if zqso is not None:
                co, knots = laco.find_continuum(spec, redshift=self.zqso)
            else:
                co, knots = laco.find_continuum(spec, kind='default')
            self.conti_dict = dict(co=co, knots=knots)

        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 dla_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)
예제 #12
0
def test_rdspec():
    spec, spec_fil = ltgu.read_spec(data_path('UM184_nF.fits'))
    #
    ispec = lsio.readspec(data_path('UM184_nF.fits'))
    spec, spec_fil = ltgu.read_spec(ispec)
예제 #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)
예제 #14
0
    def __init__(self, ispec, parent=None, dla_fit_file=None,
                 zqso=None, outfil=None, smooth=None, dw=0.1, zdla=None,
                 NHI=None,
                 skip_wveval=False, norm=True, conti_file=None):
        QMainWindow.__init__(self, parent)
        """
        ispec : Spectrum1D or specfil
        dla_fit_file: str, optional
          Name of the LLS fit file to input
        smooth : float, optional
          Number of pixels to smooth on (FWHM).  Will not smooth if 0.
        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).
        conti_file : str, optional
          ASCII file containing the continuum knots (wave, flux)
        zdla : float, optional
          Create a DLA at the input redshift
        """

        self.help_message = """
Begin by left-clicking in the plot window!

Then any of the following keystroke commands will work:

i,o       : zoom in/out x limits
I,O       : zoom in/out x limits (larger re-scale)
Y         : zoom out y limits
y         : guess y limits
W         : Show original zooom
t,b       : set y top/bottom limit
l,r       : set left/right x limit
a,m,d     : Add/modify/delete continuum knot
A         : Add a new DLA
g         : Move nearest Lyman line to cursor and reset z
N/n       : Increase/decrease NHI
V/v       : Increase/decrease bvalue
Z/z       : Increase/decrease zabs
U/u       : Increase/decrease sig_NHI  [Default is 0.1 dex]
D         : Delete DLA
$         : Toggle displaying metal lines
6,7,8,9   : Add forest lines
?         : Print these help notes
P         : Save current screen in dla_plot.pdf
Q         : Quit the GUI
        """

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

        # Status bar
        self.create_status_bar()

        # Initialize
        self.update = True
        self.sig_NHI = 0.1
        if outfil is None:
            self.outfil = 'DLA_fit.json'
        else:
            self.outfil = outfil
        self.count_dla = 0
        self.dla_model = None
        if smooth is None:
            self.smooth = 3.  # Pixels to smooth model by
        else:
            self.smooth = smooth
        self.base_continuum = None
        self.all_forest = []
        self.flag_write = False
        self.dw = float(dw)
        self.skip_wveval = skip_wveval
        self.zqso = zqso
        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:
            kwargs = {}
            kwargs['rsp_kwargs'] = {}
            kwargs['rsp_kwargs']['masking'] = 'edges'
            spec, spec_fil = ltgu.read_spec(ispec, norm=norm, **kwargs)
        self.spec = spec


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

        # z and N boxes
        self.zwidget = ltgsm.EditBox(-1., 'z_DLA=', '{: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 = ltgsp.AbsSysWidget([],only_one=True,
            no_buttons=True, linelist=self.llist[self.llist['List']])

        self.spec_widg = ltgsp.ExamineSpecWidget(spec,status=self.statusBar,
                                           llist=self.llist, key_events=False,
                                           abs_sys=self.abssys_widg.abs_sys,
                                           plotzero=1, norm=norm)
        # Create a DLA?
        if zdla is not None:
            self.add_DLA(zdla, NHI=NHI, model=False)

        # Initialize continuum (and DLA if from a file)
        if dla_fit_file is not None:
            self.init_DLA(dla_fit_file,spec)
        else:
            if conti_file is not None:
                # Read continuum
                cspec = lsi.readspec(conti_file)
                if not cspec.sig_is_set:
                    cspec.sig = 0.1*np.median(cspec.flux)
            else:
                cspec = spec
            if zqso is not None:
                co, knots = laco.find_continuum(cspec, redshift=self.zqso)
            else:
                co, knots = laco.find_continuum(cspec, kind='default')
            self.conti_dict = dict(co=co, knots=knots)

        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))))

        # Initialize as needed
        if (dla_fit_file is not None) or (zdla is not None):
            self.update_boxes()
            self.update_model()

        # Outfil
        wbtn = QPushButton(self)
        wbtn.setText('Write')
        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 = QWidget()
        wqbtn = QPushButton(self)
        wqbtn.setText('Write\n Quit')
        wqbtn.setAutoDefault(False)
        wqbtn.clicked.connect(self.write_quit)
        qbtn = QPushButton(self)
        qbtn.setText('Quit')
        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.Nwidget.box.textChanged[str].connect(self.setbzN)
        self.zwidget.box.textChanged[str].connect(self.setbzN)
        self.bwidget.box.textChanged[str].connect(self.setbzN)
        self.Cwidget.box.textChanged[str].connect(self.setbzN)

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

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

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

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

        hbox = 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)

        # Print help message
        print(self.help_message)