Exemplo n.º 1
0
def read_spec(ispec, exten=None, norm=True):
    """Parse spectrum out of the input

    If 2 spectra are given, the 2nd is scaled to the first

    Parameters
    ----------
    ispec : Spectrum1D, str, list of files (ordered blue to red),
       or tuple of arrays
    exten : int, optional
      FITS extension

    Returns
    -------
    spec : XSpectrum1D
    spec_file : str
    """
    from specutils.spectrum1d import Spectrum1D
    from linetools.spectra import xspectrum1d as lsx
    #
    if isinstance(ispec,basestring):
        spec_fil = ispec
        spec = lsx.XSpectrum1D.from_file(spec_fil, exten=exten)
    elif isinstance(ispec,Spectrum1D):
        spec = ispec
        spec_fil = spec.filename # Grab from Spectrum1D
    elif isinstance(ispec,tuple):
        spec = lsx.XSpectrum1D.from_tuple(ispec)
        spec_fil = 'none'
    elif isinstance(ispec,list): # Multiple file names
        # Loop on the files
        for kk,ispecf in enumerate(ispec):
            jspec = lsx.XSpectrum1D.from_file(ispecf, exten=exten)
            if kk == 0:
                spec = jspec
                _, xper1 = ltsp.get_flux_plotrange(spec.flux, perc=0.9)
            else:
                # Scale flux for convenience of plotting (sig is not scaled)
                _, xper2 = ltsp.get_flux_plotrange(jspec.flux, perc=0.9)
                scl = xper1[1]/xper2[1]
                # Splice
                spec = spec.splice(jspec, scale=scl)
            # Filename
            spec_fil = ispec[0]
            spec.filename=spec_fil
    else:
        raise ValueError('Bad input to read_spec: {:s}'.format(type(ispec)))

    # Normalize?
    if norm:
        if hasattr(spec, 'co') and spec.co is not None:
            spec.normalize()

    # Return
    return spec, spec_fil
Exemplo n.º 2
0
 def init_spec(self):
     """ Initialize parameters for plotting the spectrum
     """
     #xy min/max
     xmin = np.min(self.spec.dispersion.value)
     xmax = np.max(self.spec.dispersion.value)
     from linetools.spectra.plotting import get_flux_plotrange
     ymin, ymax = get_flux_plotrange(self.spec.flux.value)
     #QtCore.pyqtRemoveInputHook()
     #xdb.set_trace()
     #QtCore.pyqtRestoreInputHook()
     self.psdict['x_minmax'] = np.array([xmin, xmax])
     self.psdict['y_minmax'] = [ymin, ymax]
     self.psdict['sv_xy_minmax'] = [[xmin, xmax], [ymin, ymax]]
     self.psdict['tmp_xy'] = None
     self.psdict['nav'] = ltgu.navigate(0, 0, init=True)
     # Analysis dict
     self.adict['flg'] = 0  # Column density flag
Exemplo n.º 3
0
def test_get_flux_plotrange():
    flux = [1, 2, 0.5, np.nan, 0.7, 1.1]
    qflux = u.quantity.Quantity(flux)
    ref = -0.273, 2.73
    np.testing.assert_allclose(get_flux_plotrange(flux), ref)
    np.testing.assert_allclose(get_flux_plotrange(qflux), ref)
Exemplo n.º 4
0
def read_spec(ispec, exten=None, norm=True, **kwargs):
    """Parse spectrum out of the input

    If 2 spectra are given, the 2nd is scaled to the first

    Parameters
    ----------
    ispec : XSpectrum1D, str, list of files (ordered blue to red),
       or tuple of arrays
    exten : int, optional
      FITS extension

    Returns
    -------
    spec : XSpectrum1D
    spec_file : str
    """
    from linetools.spectra import xspectrum1d as lsx
    from linetools.spectra import utils as ltsu
    from astropy.utils.misc import isiterable
    #
    if isinstance(ispec,basestring):
        spec_fil = ispec
        if 'rsp_kwargs' in kwargs.keys():
            spec = lsx.XSpectrum1D.from_file(spec_fil, exten=exten, **kwargs['rsp_kwargs'])
        else:
            spec = lsx.XSpectrum1D.from_file(spec_fil, exten=exten)
    elif isinstance(ispec, lsx.XSpectrum1D):
        spec = ispec
        spec_fil = spec.filename  # Grab from Spectrum1D
    elif isinstance(ispec,tuple):
        spec = lsx.XSpectrum1D.from_tuple(ispec)
        spec_fil = 'none'
    elif isinstance(ispec,list): # Multiple file names
        # Loop on the files
        for kk,ispecf in enumerate(ispec):
            if isiterable(exten):
                iexten = exten[kk]
            else:
                iexten = exten
            jspec = lsx.XSpectrum1D.from_file(ispecf, exten=iexten)
            if kk == 0:
                spec = jspec
                _, xper1 = ltsp.get_flux_plotrange(spec.flux, perc=0.9)
            else:
                # Scale flux for convenience of plotting (sig is not scaled)
                _, xper2 = ltsp.get_flux_plotrange(jspec.flux, perc=0.9)
                scl = xper1/xper2
                # Splice
                #from PyQt4 import QtCore
                #QtCore.pyqtRemoveInputHook()
                #pdb.set_trace()
                #QtCore.pyqtRestoreInputHook()
                spec = ltsu.splice_two(spec, jspec)#, scale=scl)
            # Filename
            spec_fil = ispec[0]
            spec.filename=spec_fil
    else:
        raise ValueError('Bad input to read_spec: {}'.format(type(ispec)))

    # Normalize?
    if norm:
        if spec.co_is_set:
            spec.normed=True

    # Demand AA for wavelength unit (unless over-ridden)
    if spec.wavelength.unit != u.AA:
        wvAA = spec.wavelength.to('AA')
        spec.wavelength = wvAA
    #from PyQt4 import QtCore
    #QtCore.pyqtRemoveInputHook()
    #pdb.set_trace()
    #QtCore.pyqtRestoreInputHook()

    # Return
    return spec, spec_fil
Exemplo n.º 5
0
def navigate(psdict, event, init=False, wave=None, flux=None):
    """ Method to Navigate spectrum

    Updates the dict

    Parameters
    ----------
    init :  (False) Initialize
      Just pass back valid key strokes

    wave, flux : array of floats, optional
      The spectrum wavelength and flux values (both unitless). Only
      used for the 'y' option.

    """
    # Initalize
    if init is True:
        return ['l','r','b','t','T','i','I', 'o','O',
                '[',']','W','Z', 'y', 'Y', '{', '}', 's']
    #
    if (not isinstance(event.xdata,float)) or (not isinstance(event.ydata,float)):
        print('Navigate: You entered the {:s} key out of bounds'.format(
            event.key))
        return 0

    if event.key == 'l':  # Set left
        psdict['x_minmax'][0] = event.xdata
    elif event.key == 'r':  # Set Right
        psdict['x_minmax'][1] = event.xdata
    elif event.key == 'b':  # Set Bottom
        psdict['y_minmax'][0] = event.ydata
    elif event.key == 't':  # Set Top
        psdict['y_minmax'][1] = event.ydata
    elif event.key == 'T':  # Set Top to 1.1
        psdict['y_minmax'][1] = 1.1
    elif event.key == 's':  # Select window (i.e. zoom-in)
        if psdict['tmp_xy'] is None:
            psdict['tmp_xy'] = [event.xdata,event.ydata]
            print('Press another s to set the zoom-in window')
        else:
            psdict['x_minmax'][0] = np.minimum(event.xdata,psdict['tmp_xy'][0])
            psdict['x_minmax'][1] = np.maximum(event.xdata,psdict['tmp_xy'][0])
            psdict['y_minmax'][0] = np.minimum(event.ydata,psdict['tmp_xy'][1])
            psdict['y_minmax'][1] = np.maximum(event.ydata,psdict['tmp_xy'][1])
            psdict['tmp_xy'] = None
    elif event.key == 'i':  # Zoom in (and center)
        deltx = (psdict['x_minmax'][1]-psdict['x_minmax'][0])/4.
        psdict['x_minmax'] = [event.xdata-deltx, event.xdata+deltx]
    elif event.key == 'I':  # Zoom in (and center)
        deltx = (psdict['x_minmax'][1]-psdict['x_minmax'][0])/16.
        psdict['x_minmax'] = [event.xdata-deltx, event.xdata+deltx]
    elif event.key == 'o':  # Zoom in (and center)
        deltx = psdict['x_minmax'][1]-psdict['x_minmax'][0]
        psdict['x_minmax'] = [event.xdata-deltx, event.xdata+deltx]
    elif event.key == 'O':  # Zoom in (and center)
        deltx = psdict['x_minmax'][1]-psdict['x_minmax'][0]
        psdict['x_minmax'] = [event.xdata-2*deltx, event.xdata+2*deltx]
    elif event.key == 'y' and wave is not None and flux is not None:
        # guess y limits
        x0,x1 = psdict['x_minmax']
        y0,y1 = ltsp.get_flux_plotrange(
            flux[between(wave, x0, x1)], perc=90, mult_pos=2)
        psdict['y_minmax'] = [y0, y1]
    elif event.key == 'Y':  # Zoom in (and center)
        delty = psdict['y_minmax'][1]-psdict['y_minmax'][0]
        psdict['y_minmax'] = [event.ydata-delty, event.ydata+delty]
    elif event.key in ['[',']','{','}']:  # Pan
        center = (psdict['x_minmax'][1]+psdict['x_minmax'][0])/2.
        deltx = (psdict['x_minmax'][1]-psdict['x_minmax'][0])/2.
        if event.key == '[':
            new_center = center - deltx
        elif event.key == ']':
            new_center = center + deltx
        elif event.key == '{':
            new_center = center - 4*deltx
        elif event.key == '}':
            new_center = center + 4*deltx
        psdict['x_minmax'] = [new_center-deltx, new_center+deltx]
    elif event.key == 'W': # Reset the Window
        psdict['x_minmax'] = copy.deepcopy(psdict['sv_xy_minmax'][0])
        psdict['y_minmax'] = copy.deepcopy(psdict['sv_xy_minmax'][1])
    elif event.key == 'Z': # Zero
        psdict['y_minmax'][0] = 0.
    else:
        if not (event.key in ['shift']):
            rstr = 'Key {:s} not supported.'.format(event.key)
            print(rstr)
        return 0
    return 1
Exemplo n.º 6
0
def test_get_flux_plotrange():
    flux = [1, 2, 0.5, np.nan, 0.7, 1.1]
    qflux = u.quantity.Quantity(flux)
    ref = -0.273, 2.73
    np.testing.assert_allclose(get_flux_plotrange(flux), ref)
    np.testing.assert_allclose(get_flux_plotrange(qflux), ref)
Exemplo n.º 7
0
def read_spec(ispec, exten=None, norm=True, **kwargs):
    """Parse spectrum out of the input

    If 2 spectra are given, the 2nd is scaled to the first

    Parameters
    ----------
    ispec : Spectrum1D, str, list of files (ordered blue to red),
       or tuple of arrays
    exten : int, optional
      FITS extension

    Returns
    -------
    spec : XSpectrum1D
    spec_file : str
    """
    from linetools.spectra import xspectrum1d as lsx
    #
    if isinstance(ispec,basestring):
        spec_fil = ispec
        if 'rsp_kwargs' in kwargs.keys():
            spec = lsx.XSpectrum1D.from_file(spec_fil, exten=exten, **kwargs['rsp_kwargs'])
        else:
            spec = lsx.XSpectrum1D.from_file(spec_fil, exten=exten)
        #from PyQt4 import QtCore
        #QtCore.pyqtRemoveInputHook()
        #pdb.set_trace()
        #QtCore.pyqtRestoreInputHook()
    elif isinstance(ispec, lsx.XSpectrum1D):
        spec = ispec
        spec_fil = spec.filename  # Grab from Spectrum1D
    elif isinstance(ispec,tuple):
        spec = lsx.XSpectrum1D.from_tuple(ispec)
        spec_fil = 'none'
    elif isinstance(ispec,list): # Multiple file names
        # Loop on the files
        for kk,ispecf in enumerate(ispec):
            jspec = lsx.XSpectrum1D.from_file(ispecf, exten=exten)
            if kk == 0:
                spec = jspec
                _, xper1 = ltsp.get_flux_plotrange(spec.flux, perc=0.9)
            else:
                # Scale flux for convenience of plotting (sig is not scaled)
                _, xper2 = ltsp.get_flux_plotrange(jspec.flux, perc=0.9)
                scl = xper1[1]/xper2[1]
                # Splice
                spec = spec.splice(jspec, scale=scl)
            # Filename
            spec_fil = ispec[0]
            spec.filename=spec_fil
    else:
        raise ValueError('Bad input to read_spec: {:s}'.format(type(ispec)))

    # Normalize?
    if norm:
        if spec.co_is_set:
            spec.normed=True

    # Return
    return spec, spec_fil