当前位置: 首页>>代码示例>>Python>>正文


Python xdebug.set_trace函数代码示例

本文整理汇总了Python中xastropy.xutils.xdebug.set_trace函数的典型用法代码示例。如果您正苦于以下问题:Python set_trace函数的具体用法?Python set_trace怎么用?Python set_trace使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了set_trace函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: mean_templ_zi

def mean_templ_zi(zimag, debug=False, i_wind=0.1, z_wind=0.05,
                  boss_pca_fil=None):
    '''
    Generate 'mean' templates at given z,i

    Parameters
    ----------
    zimag: list of tuples
      Redshift, imag pairs for the templates
    i_wind: float (0.1 mag)
      Window for smoothing imag
    z_wind: float (0.05 mag)
      Window for smoothing redshift
    '''
    # PCA values
    if boss_pca_fil is None:
        boss_pca_fil = 'BOSS_DR10Lya_PCA_values_nocut.fits.gz'
    hdu = fits.open(boss_pca_fil)
    pca_coeff = hdu[1].data

    # BOSS Eigenvectors
    eigen, eigen_wave = fbq.read_qso_eigen()
    npix = len(eigen_wave)

    # Open the BOSS catalog file
    boss_cat_fil = os.environ.get('BOSSPATH')+'/DR10/BOSSLyaDR10_cat_v2.1.fits.gz'
    bcat_hdu = fits.open(boss_cat_fil)
    t_boss = bcat_hdu[1].data
    zQSO = t_boss['z_pipe']
    tmp = t_boss['PSFMAG']
    imag = tmp[:,3] # i-band mag

    # Output array
    ntempl = len(zimag)
    out_spec = np.zeros( (ntempl, npix) )

    # Iterate on z,imag
    for izi in zimag:
        tt = zimag.index(izi)
        # Find matches
        idx = np.where( (np.fabs(imag-izi[1]) < i_wind) &
                        (np.fabs(zQSO-izi[0]) < z_wind))[0]
        if len(idx) < 50:
            raise ValueError('mean_templ_zi: Not enough QSOs! {:d}'.format(len(idx)))

        # Calculate median PCA values
        PCA0 = np.median(pca_coeff['PCA0'][idx])
        PCA1 = np.median(pca_coeff['PCA1'][idx])
        PCA2 = np.median(pca_coeff['PCA2'][idx])
        PCA3 = np.median(pca_coeff['PCA3'][idx])
        acoeff = np.array( [PCA0, PCA1, PCA2, PCA3] )

        # Make the template
        out_spec[tt,:] = np.dot(eigen.T,acoeff)
        if debug is True:
            xdb.xplot(eigen_wave*(1.+izi[0]), out_spec[tt,:])
            xdb.set_trace()

    # Return
    return out_spec
开发者ID:desihub,项目名称:desisim,代码行数:60,代码来源:desi_qso_templ.py

示例2: trim

def trim(slf, file, det):
    for i in xrange (slf._spect['det'][det-1]['numamplifiers']):
        datasec = "datasec{0:02d}".format(i+1)
        x0, x1, y0, y1 = slf._spect['det'][det-1][datasec][0][0], slf._spect['det'][det-1][datasec][0][1], slf._spect['det'][det-1][datasec][1][0], slf._spect['det'][det-1][datasec][1][1]
        if x0 < 0: x0 += file.shape[0]
        if x1 <= 0: x1 += file.shape[0]
        if y0 < 0: y0 += file.shape[1]
        if y1 <= 0: y1 += file.shape[1]
        if i == 0:
            xv = np.arange(x0, x1)
            yv = np.arange(y0, y1)
        else:
            xv = np.unique(np.append(xv, np.arange(x0, x1)))
            yv = np.unique(np.append(yv, np.arange(y0, y1)))
    # Construct and array with the rows and columns to be extracted
    w = np.ix_(xv, yv)
#	if len(file.shape) == 2:
#		trimfile = file[w]
#	elif len(file.shape) == 3:
#		trimfile = np.zeros((w[0].shape[0],w[1].shape[1],file.shape[2]))
#		for f in xrange(file.shape[2]):
#			trimfile[:,:,f] = file[:,:,f][w]
#	else:
#		msgs.error("Cannot trim {0:d}D frame".format(int(len(file.shape))))
    try:
        trim_file = file[w]
    except:
        msgs.bug("Odds are datasec is set wrong. Maybe due to transpose")
        set_trace()
        msgs.error("Cannot trim file")
    return file[w]
开发者ID:EdwardBetts,项目名称:PYPIT,代码行数:31,代码来源:arproc.py

示例3: mk_pix_stau

    def mk_pix_stau(self, spec, kbin=22.*u.km/u.s, debug=False, **kwargs):
        """ Generate the smoothed tau array for kinematic tests
    
        Parameters
        ----------
        spec: Spectrum1D class
          Input spectrum
          velo is expected to have been filled already
        fill: bool (True)
          Fill the dictionary with some items that other kin programs may need

        Returns
        -------
        out_kin : dict
           Dictionary of kinematic measurements
    
        JXP on 11 Dec 2014
        """
        # Calcualte dv
        imn = np.argmin( np.fabs(spec.velo) )
        dv = np.abs( spec.velo[imn] - spec.velo[imn+1] )

        # Test for bad pixels
        pixmin = np.argmin( np.fabs( spec.velo-self.vmnx[0] ) )
        pixmax = np.argmin( np.fabs( spec.velo-self.vmnx[1] ) )
        pix = np.arange(pixmin, pixmax+1)
        npix = len(pix)
        badzero=np.where((spec.flux[pix] == 0) & (spec.sig[pix] <= 0))[0]
        if len(badzero) > 0:
            if np.max(badzero)-np.min(badzero) >= 5: 
                raise ValueError('orig_kin: too many or too large sections of bad data')
            
            spec.flux[pix[badzero]] = np.mean(np.array([spec.flux[pix[np.min(badzero)-1]],
                                                        spec.flux[pix[np.max(badzero)+1]]]))
            xdb.set_trace() # Should add sig too

        # Generate the tau array
        tau = np.zeros(npix)
        gd = np.where((spec.flux[pix] > spec.sig[pix]/2.) &
                    (spec.sig[pix] > 0.) )
        if len(gd) == 0:
            raise ValueError('orig_kin: Profile too saturated.')

        tau[gd] = np.log(1./spec.flux[pix[gd]])
        sat = (pix == pix)
        sat[gd] = False
        tau[sat] = np.log(2./spec.sig[pix[sat]])

        # Smooth
        nbin = (np.round(kbin/dv)).value
        kernel = Box1DKernel(nbin, mode='center')
        stau = convolve(tau, kernel, boundary='fill', fill_value=0.)
        if debug is True:
            xdb.xplot(spec.velo[pix], tau, stau)

        # Fill
        self.stau = stau
        self.pix = pix
开发者ID:nhmc,项目名称:xastropy,代码行数:58,代码来源:absline.py

示例4: main

def main(*args, **kwargs):
    """ Runs the AbsKinGui

    Command line
    or from Python
    Examples:
      1.  python ~/xastropy/xastropy/xguis/abskingui.py
      2.  abskingui.main(filename)
      3.  abskingui.main(spec1d)
    """
    import sys
    import argparse

    parser = argparse.ArgumentParser(description='Parse for AbsKinGui')
    parser.add_argument("file", type=str, help="Spectral file")
    parser.add_argument("-sysfile", type=str, help="System JSON file")
    parser.add_argument("-zsys", type=float, help="System Redshift")
    parser.add_argument("-outfil", type=str, help="Output filename")
    parser.add_argument("--un_norm", help="Spectrum is NOT normalized",
                        action="store_true")

    if len(args) == 0:
        pargs = parser.parse_args()
    else: # better know what you are doing!
        if isinstance(args[0],(Spectrum1D, tuple)):
            if not kwargs['rerun']:
                app = QtGui.QApplication(sys.argv)
            xdb.set_trace()
            gui = AbsKinGui(args[0], **kwargs)
            gui.exec_()
            #gui.show()
            #app.exec_()
            return gui, app
        else: # String parsing
            largs = [iargs for iargs in args]
            pargs = parser.parse_args(largs)
            xdb.set_trace() # Not setup for command line yet

    # Normalized?
    norm = True
    if pargs.un_norm:
        norm = False

    # Read AbsSystem
    from linetools.isgm.abssystem import GenericAbsSystem
    if pargs.sysfile is not None:
        abs_sys = GenericAbsSystem.from_json(pargs.sysfile, chk_vel=False)
    else:
        abs_sys = None

    app = QtGui.QApplication(sys.argv)
    gui = AbsKinGui(pargs.file, z=pargs.zsys, norm=norm, abs_sys=abs_sys, outfil=pargs.outfil)
    gui.show()
    app.exec_()

    return gui, app
开发者ID:xastropy,项目名称:xastropy,代码行数:56,代码来源:abskingui.py

示例5: bspline_fit

def bspline_fit(x,y,order=3,knots=None,everyn=20,xmin=None,xmax=None,w=None,bkspace=None):
    ''' bspline fit to x,y
    Should probably only be called from func_fit

    Parameters:
    ---------
    x: ndarray
    y: ndarray
    func: str
      Name of the fitting function:  polynomial, legendre, chebyshev, bspline
    deg: int 
      deg of the spline.  Default=3 (cubic)
    xmin: float, optional
      Minimum value in the array  [both must be set to normalize]
    xmax: float, optional
      Maximum value in the array  [both must be set to normalize]
    w: ndarray, optional
      weights to be used in the fitting (weights = 1/sigma)
    everyn: int 
      Knot everyn good pixels, if used
    bkspace: float 
      Spacing of breakpoints in units of x

    Returns:
    ---------
    fit_dict: dict  
      dict describing the bspline fit 
    ''' 
    #
    if w is None:
        ngd = x.size
        gd = np.arange(ngd)
        weights = None
    else:
        gd = np.where(w > 0.)[0]
        weights = w[gd]
    # Make the knots
    if knots is None:
        if bkspace is not None: 
            xrnge = (np.max(x[gd]) - np.min(x[gd]))
            startx = np.min(x[gd])
            nbkpts = max(int(xrnge/bkspace) + 1,2)
            tempbkspace = xrnge/(nbkpts-1)
            knots = np.arange(1,nbkpts-1)*tempbkspace + startx
        elif everyn is not None:
            idx_knots = np.arange(10, ngd-10, everyn) # A knot every good N pixels
            knots = x[gd[idx_knots]]
        else:
            msgs.error("No method specified to generate knots")
    # Generate spline
    try:
        tck = interpolate.splrep(x[gd], y[gd], w=weights, k=order, t=knots)
    except ValueError: # Knot problem
        msgs.warn("Problem in the bspline knot")
        debugger.set_trace()
    return tck
开发者ID:adwasser,项目名称:PYPIT,代码行数:56,代码来源:arutils.py

示例6: __getattr__

 def __getattr__(self, k):
     # Try Self first
     try:
         lst = [getattr(cgm_abs,k) for cgm_abs in self.cgm_abs]
     except AttributeError:
         # Try AbsLine_Sys next
         try:
             lst = [getattr(cgm_abs.abs_sys,k) for cgm_abs in self.cgm_abs] 
         except AttributeError:
             # Galaxy?
             try:
                 lst = [getattr(cgm_abs.galaxy,k) for cgm_abs in self.cgm_abs] 
             except AttributeError:
                 print('cgm.core: Attribute not found!')
                 xdb.set_trace()
     # Return array
     return xu_array.lst_to_array(lst,mask=self.mask)
开发者ID:astronomeara,项目名称:xastropy-old,代码行数:17,代码来源:core.py

示例7: set_fn_data

def set_fn_data(sources=None, extra_fNc=[]):
    '''
    Load up f(N) data

    Parameters
    ----------

    Returns
    -------
    fN_data :: List of fN_Constraint Classes

    JXP on 27 Nov 2014
    '''
    if sources is None:
        sources = ['OPB07', 'OPW12', 'OPW13', 'K05', 'K13R13', 'N12']

    fn_file = xa_path+'/igm/fN/fn_constraints_z2.5_vanilla.fits'
    k13r13_file = xa_path+'/igm/fN/fn_constraints_K13R13_vanilla.fits'
    n12_file = xa_path+'/igm/fN/fn_constraints_N12_vanilla.fits'
    all_fN_cs = xifd.fn_data_from_fits([fn_file,k13r13_file,n12_file])

    # Add on, e.g. user-supplied 
    if len(extra_fNc) > 0:
    	for src in extra_fNc:
        	all_fN_cs.append(xifd.fN_data_from_ascii_file(os.path.abspath(src)))

    # Include good data sources
    fN_cs = []
    for fN_c in all_fN_cs:
        # In list?
        if fN_c.ref in sources:
            print('Using {:s} as a constraint'.format(fN_c.ref))
            # Append
            fN_cs.append(fN_c)
            # Pop
            idx = sources.index(fN_c.ref)
            sources.pop(idx)
    
    # Check that all the desired sources were used
    if len(sources) > 0:
        xdb.set_trace()

    #xdb.set_trace()

    return fN_cs
开发者ID:afeinsod,项目名称:alresearch,代码行数:45,代码来源:draftmcmc.py

示例8: fit_component

    def fit_component(self,component):
        '''Fit the component and save values'''
        from astropy.modeling import fitting
        # Generate Fit line
        fit_line = AbsLine(component.init_wrest,
            linelist=self.llist[self.llist['List']])
        fit_line.analy['vlim'] = component.vlim
        fit_line.analy['spec'] = self.spec
        fit_line.attrib['z'] = component.zcomp
        fit_line.measure_aodm()
        # Guesses
        fmin = np.argmin(self.spec.flux[fit_line.analy['pix']])
        zguess = self.spec.dispersion[fit_line.analy['pix'][fmin]]/component.init_wrest - 1.
        bguess = (component.vlim[1]-component.vlim[0])/2.
        Nguess = fit_line.attrib['logN']
        # Voigt model
        fitvoigt = xsv.single_voigt_model(logN=Nguess,b=bguess.value,
                                z=zguess, wrest=component.init_wrest.value,
                                gamma=fit_line.data['gamma'].value, 
                                f=fit_line.data['f'], fwhm=self.fwhm)
        # Restrict z range
        try:
            fitvoigt.z.min = component.zcomp+component.vlim[0].value/3e5/(1+component.zcomp)
        except TypeError:
            QtCore.pyqtRemoveInputHook()
            xdb.set_trace()
            QtCore.pyqtRestoreInputHook()
        fitvoigt.z.max = component.zcomp+component.vlim[1].value/3e5/(1+component.zcomp)
        #QtCore.pyqtRemoveInputHook()
        #xdb.set_trace()
        #QtCore.pyqtRestoreInputHook()
        # Fit
        fitter = fitting.LevMarLSQFitter()
        parm = fitter(fitvoigt,self.spec.dispersion[fit_line.analy['pix']],
            self.spec.flux[fit_line.analy['pix']].value)

        # Save and sync
        component.attrib['N'] = parm.logN.value
        component.attrib['z'] = parm.z.value
        component.attrib['b'] = parm.b.value * u.km/u.s
        component.sync_lines()
开发者ID:jsribaud,项目名称:xastropy,代码行数:41,代码来源:igmguesses.py

示例9: setwave

def setwave(hdr):

    # DEPRECATED
    xdb.set_trace()
    # Initialize
    SCL = 1.0

    # Parse the header
    npix = hdr["NAXIS1"]
    crpix1 = hdr["CRPIX1"] if "CRPIX1" in hdr else 1.0
    crval1 = hdr["CRVAL1"] if "CRVAL1" in hdr else 1.0
    cdelt1 = hdr["CDELT1"] if "CDELT1" in hdr else 1.0
    ctype1 = hdr["CTYPE1"] if "CTYPE1" in hdr else None
    dcflag = hdr["DC-FLAG"] if "DC-FLAG" in hdr else None

    # Generate
    if (dcflag == 1) or (cdelt1 < 1e-4):
        wave = SCL * 10.0 ** (crval1 + (cdelt1 * np.arange(npix) + 1.0 - crpix1))  # Log
    xdb.set_trace()

    # Return
    return wave
开发者ID:profxj,项目名称:old_xastropy,代码行数:22,代码来源:readwrite.py

示例10: run_xvelp

def run_xvelp(*args, **kwargs):
    '''
    Runs the XVelPltGui

    Command line
    or from Python
    Examples:
      1.  python ~/xastropy/xastropy/xguis/spec_guis.py 3
      2.  spec_guis.run_xvelp(filename)
      3.  spec_guis.run_xvelp(spec1d)
    '''

    import argparse
    from specutils import Spectrum1D

    xdb.set_trace() # DEPRECATED FOR NOW

    parser = argparse.ArgumentParser(description='Parse for XVelPlt')
    parser.add_argument("flag", type=int, help="GUI flag (ignored)")
    parser.add_argument("file", type=str, help="Spectral file")
    parser.add_argument("-zsys", type=float, help="System Redshift")
    parser.add_argument("--un_norm", help="Spectrum is NOT normalized",
                        action="store_true")

    if len(args) == 0:
        pargs = parser.parse_args()
    else: # better know what you are doing!
        if isinstance(args[0],(Spectrum1D,tuple)):
            if not kwargs['rerun']:
                app = QtGui.QApplication(sys.argv)
            xdb.set_trace()
            gui = XVelPltGui(args[0], **kwargs)
            gui.exec_()
            #gui.show()
            #app.exec_()
            return gui, app
        else: # String parsing 
            largs = ['1'] + [iargs for iargs in args]
            pargs = parser.parse_args(largs)
    
    # Normalized?
    norm=True
    if pargs.un_norm:
        norm=False

    # Second spectral file?
    try:
        zsys = pargs.zsys
    except AttributeError:
        zsys=None

    xdb.set_trace() # Not setup for command line yet
    app = QtGui.QApplication(sys.argv)
    gui = XSpecGui(pargs.file, zsys=zsys, norm=norm)
    gui.show()
    app.exec_()

    return gui
开发者ID:nhmc,项目名称:xastropy,代码行数:58,代码来源:spec_guis.py

示例11: box_smooth

    def box_smooth(self, nbox, preserve=False):
        """ Box car smooth spectrum and return a new one
        Is a simple wrapper to the rebin routine

        Parameters
        ----------
        nbox: integer
          Number of pixels to smooth over
        preserve: bool (False) 
          Keep the new spectrum at the same number of pixels as original
        Returns:
          XSpectrum1D of the smoothed spectrum
        """
        from xastropy.xutils import arrays as xxa
        if preserve:
            from astropy.convolution import convolve, Box1DKernel
            new_fx = convolve(self.flux, Box1DKernel(nbox))
            new_sig = convolve(self.sig, Box1DKernel(nbox))
            new_wv = self.dispersion
        else:
            # Truncate arrays as need be
            npix = len(self.flux)
            try:
                new_npix = npix // nbox # New division
            except ZeroDivisionError:
                xdb.set_trace()
            orig_pix = np.arange( new_npix * nbox )

            # Rebin (mean)
            new_wv = xxa.scipy_rebin( self.dispersion[orig_pix], new_npix )
            new_fx = xxa.scipy_rebin( self.flux[orig_pix], new_npix )
            new_sig = xxa.scipy_rebin( self.sig[orig_pix], new_npix ) / np.sqrt(nbox)

        # Return
        return XSpectrum1D.from_array(new_wv, new_fx,
                                      uncertainty=apy.nddata.StdDevUncertainty(new_sig))
开发者ID:mneeleman,项目名称:xastropy,代码行数:36,代码来源:utils.py

示例12: set_params

def set_params(lines, indict, setstr=""):
    """
    Adjust settings parameters.
    lines    : an array of settings with the same format as the default 'settings.armed'
    indict  : a dictionary generated by initialise that contains all settings
    setstr   : a string argument for error messages that tells the user which file the error occured in.
    """
    for i in range(len(lines)):
        if lines[i].strip() == '' or lines[i].strip() == '\n': continue
        if lines[i].strip()[0] == '#': continue
        tline = lines[i].strip().split("#")[0]
        linspl = tline.split()
        if len(linspl) <= 2:
            msgs.error("Not enough parameters given on line:"+msgs.newline()+lines[i])
        if linspl[0] == 'check':
            text = str(linspl[2]).strip().replace('_', ' ')
            if ',' in text:  # There are multiple possibilities
                indict[linspl[0]][linspl[1]] += text.split(',')
            else:
                indict[linspl[0]][linspl[1]] = text
        elif linspl[0] in indict.keys():
            if linspl[1] in ['check', 'match', 'combsame']:
                text = str(linspl[3]).strip().replace('_', ' ')
                if ',' in text and text[0:2] != '%,':  # There are multiple possibilities - split the infile
                    indict[linspl[0]][linspl[1]][linspl[2]] += text.split(',')
                else:
                    indict[linspl[0]][linspl[1]][linspl[2]] = text
            elif linspl[1][:6] == 'ndet':  # Mosaic of Detectors
                indict[linspl[0]][linspl[1]] = int(linspl[2])
                tmp = []
                for ii in range(indict['mosaic']['ndet']):  # List
                    tmpi = copy.deepcopy(indict['det'])
                    tmpi['suffix'] = str(ii)
                    tmp.append(tmpi)
                indict['det'] = tmp
            elif linspl[1][:7] == 'headext':  # Header Sections
                try:
                    null = np.int(linspl[1][7:])
                except ValueError:
                    msgs.error("keyword headext must contain an integer suffix")
                indict[linspl[0]][linspl[1]] = int(linspl[2])
            elif linspl[1][:8] == 'lampname':  # Lamp names
                try:
                    null = np.int(linspl[1][8:])
                except ValueError:
                    msgs.error("keyword lampname must contain an integer suffix")
                indict[linspl[0]][linspl[1]] = linspl[2]
            elif linspl[1][:8] == 'lampstat': # Lamp status
                try:
                    null = np.int(linspl[1][8:])
                except ValueError:
                    msgs.error("keyword lampstat must contain an integer suffix")
                indict[linspl[0]][linspl[1]] = linspl[2]
            elif linspl[1] in indict[linspl[0]].keys():
                indict[linspl[0]][linspl[1]] = set_params_wtype(indict[linspl[0]][linspl[1]], linspl[2], lines=tline, setstr=setstr)
            else:
                debugger.set_trace()
                msgs.error(setstr + "Settings contains bad line (arg 2):"+msgs.newline()+lines[i].split('#')[0].strip())
        elif linspl[0][:3] == 'det': # Detector parameters
            try:
                didx = np.int(linspl[0][4:]) - 1 
            except ValueError:
                msgs.error("keyword det must contain an integer suffix")
            else:
                linspl[0] = 'det'
            if linspl[1][:6] == 'ampsec': # Amplifier Sections
                try:
                    null = np.int(linspl[1][6:])
                except ValueError:
                    msgs.error("keyword ampsec must contain an integer suffix")
                indict[linspl[0]][didx][linspl[1]] = load_sections(linspl[2], strtxt=linspl[1])
            elif linspl[1][:7] == 'datasec': # Data Sections
                try:
                    null = np.int(linspl[1][7:])
                except ValueError:
                    msgs.error("keyword datasec must contain an integer suffix")
                indict[linspl[0]][didx][linspl[1]] = load_sections(linspl[2], strtxt=linspl[1])
            elif linspl[1][:8] == 'oscansec': # Overscan Sections
                try:
                    null = np.int(linspl[1][8:])
                except ValueError:
                    msgs.error("keyword oscansec must contain an integer suffix")
                indict[linspl[0]][didx][linspl[1]] = load_sections(linspl[2], strtxt=linspl[1])
            elif linspl[1][:6] == 'numamp':
                indict[linspl[0]][didx]['numamplifiers'] = int(linspl[2])
                indict[linspl[0]][didx]['gain'] = [indict['det'][didx]['gain'][0]]*int(linspl[2])
                indict[linspl[0]][didx]['ronoise'] = [indict['det'][didx]['ronoise'][0]]*int(linspl[2])
            else:  # Read value
                indict[linspl[0]][didx][linspl[1]] = set_params_wtype(indict[linspl[0]][didx][linspl[1]], linspl[2], lines=tline,setstr=setstr)
        else:
            msgs.error(setstr + "Settings contains bad line (arg 1):"+msgs.newline()+lines[i].split('#')[0].strip())
    return indict
开发者ID:ntejos,项目名称:PYPIT,代码行数:92,代码来源:arload.py

示例13: MasterTrace

    def MasterTrace(self, fitsdict, det):
        """
        Generate Master Trace frame for a given detector

        Parameters
        ----------
        fitsdict : dict
          Contains relevant information from fits header files
        det : int
          Index of the detector

        Returns
        -------
        boolean : bool
          Should other ScienceExposure classes be updated?
        """

        # If the master trace is already made, use it
        if self._mstrace[det-1] is not None:
            msgs.info("An identical master trace frame already exists")
            return False
        if self._argflag['reduce']['usetrace'] in ['trace', 'blzflat']:
            if self._argflag['masters']['use']:
                # Attempt to load the Master Frame
                mstrace_name = armasters.master_name(self._argflag['run']['masterdir'],
                                                   'trace', self._argflag['masters']['setup'])
                try:
                    mstrace, head = arload.load_master(mstrace_name, frametype="trace")
                except IOError:
                    msgs.warn("No MasterTrace frame found {:s}".format(mstrace_name))
                else:
                    # Extras
                    lordloc, _ = arload.load_master(mstrace_name, frametype="trace", exten=1)
                    rordloc, _ = arload.load_master(mstrace_name, frametype="trace", exten=2)
                    pixcen, _ = arload.load_master(mstrace_name, frametype="trace", exten=3)
                    pixwid, _ = arload.load_master(mstrace_name, frametype="trace", exten=4)
                    lordpix, _ = arload.load_master(mstrace_name, frametype="trace", exten=5)
                    rordpix, _ = arload.load_master(mstrace_name, frametype="trace", exten=6)
                    self.SetFrame(self._lordloc, lordloc, det)
                    self.SetFrame(self._rordloc, rordloc, det)
                    self.SetFrame(self._pixcen, pixcen.astype(np.int), det)
                    self.SetFrame(self._pixwid, pixwid.astype(np.int), det)
                    self.SetFrame(self._lordpix, lordpix.astype(np.int), det)
                    self.SetFrame(self._rordpix, rordpix.astype(np.int), det)
                    #
                    self._argflag['masters']['loaded'].append('trace'+self._argflag['masters']['setup'])
            if 'trace'+self._argflag['masters']['setup'] not in self._argflag['masters']['loaded']:
                msgs.info("Preparing a master trace frame with {0:s}".format(self._argflag['reduce']['usetrace']))
                ind = self._idx_trace
                # Load the frames for tracing
                frames = arload.load_frames(self, fitsdict, ind, det, frametype='trace', msbias=self._msbias[det-1],
                                            trim=self._argflag['reduce']['trim'], transpose=self._transpose)
                if self._argflag['reduce']['flatmatch'] > 0.0:
                    sframes = arsort.match_frames(frames, self._argflag['reduce']['flatmatch'], msgs, frametype='trace', satlevel=self._spect['det'][det-1]['saturation']*self._spect['det'][det-1]['nonlinear'])
                    subframes = np.zeros((frames.shape[0], frames.shape[1], len(sframes)))
                    numarr = np.array([])
                    for i in xrange(len(sframes)):
                        numarr = np.append(numarr, sframes[i].shape[2])
                        mstrace = arcomb.comb_frames(sframes[i], det, spect=self._spect, frametype='trace', **self._argflag['trace']['comb'])
                        subframes[:,:,i] = mstrace.copy()
                    del sframes
                    # Combine all sub-frames
                    mstrace = arcomb.comb_frames(subframes, det, spect=self._spect, frametype='trace', weights=numarr, **self._argflag['trace']['comb'])
                    del subframes
                else:
                    mstrace = arcomb.comb_frames(frames, det, spect=self._spect, frametype='trace', **self._argflag['trace']['comb'])
                del frames
        elif self._argflag['reduce']['usetrace'] == 'science':
            msgs.error("Tracing with a science frame is not yet implemented")
        else: # It must be the name of a file the user wishes to load
            mstrace_name = self._argflag['run']['masterdir']+'/'+self._argflag['reduce']['usetrace']
            mstrace, head = arload.load_master(mstrace_name, frametype=None)
            debugger.set_trace()  # NEED TO LOAD EXTRAS AS ABOVE
        # Set and then delete the Master Trace frame
        self.SetMasterFrame(mstrace, "trace", det)
        del mstrace
        return True
开发者ID:adwasser,项目名称:PYPIT,代码行数:77,代码来源:arsciexp.py

示例14: load_low_kin

 def load_low_kin(self):
     from xastropy import kinematics as xkin
     # Grab spectrum from ions
     xdb.set_trace()
     out_kin = xkin.orig_kin(spec, vmnx)
开发者ID:nhmc,项目名称:xastropy,代码行数:5,代码来源:abssys_utils.py

示例15: wiki

def wiki(targs, keys, fndr_pth=None, dbx_pth=None, outfil=None, skip_finder=False):
    """
    Generate a Wiki table for Lick observing.
    Should work for any of the Wiki pages

    Parameters:
    ----------
    targs: Table (RA, DEC keys required)
    keys: List
      List of keys to include in the Table + order
    fndr_pth: string
      Folder for finder charts
    dbx_pth: string
      Dropbox path for the finders
    skip_finder: False
      Skip making the finders

    Writes a file to disk that can be pasted into the Wiki
    """
    reload(x_finder)
    # Outfil
    if outfil is None:
        outfil = 'tmp_wiki.txt'
    f = open(outfil, 'w')

    # Finders?
    if not fndr_pth is None:
        if dbx_pth is None:
            dbx_pth = './'
            dbx_folder = './'
        else: # Expecting Public
            ifind = dbx_pth.find('Observing/')
            if ifind == -1:
                xdb.set_trace()
            else:
                dbx_folder = os.getenv('DROPBOX_DIR')+'/Public/'+dbx_pth[ifind:]
        #
        print('lick.wiki: Will copy finders to {:s}'.format(dbx_folder))
        # Get name tag
        name_tag = get_name_tag(targs.dtype.names)
        # Type
        #if isinstance(targs['RA'][0], basestring):
        #    radec = 1 # : separated strings
        #else:
        #    radec = 2 # decimal degrees
        # Finders
        fndr_files = []
        for targ in targs:
            # Finder
            #xdb.set_trace()
            if not skip_finder:
                x_finder.main([targ[name_tag], targ['RA'], targ['DEC']], fpath=fndr_pth)
            # Copy? + Save
            fil1 = fndr_pth+targ[name_tag]+'.pdf'
            fil2 = dbx_folder
            if not skip_finder:
                subprocess.call(["cp", fil1, dbx_folder])
            fndr_files.append(dbx_pth+targ[name_tag]+'.pdf')
        
    # Header
    lin = '||' 
    for key in keys:
        lin = lin+str(key)+'||'
    if 'fndr_files' in locals():
        lin=lin+'finder||comment||'
    f.write(str(lin+'\n'))
    
    # Targets
    for ii,targ in enumerate(targs):
        lin = '||' 
        for key in keys:
            lin = lin+str(targ[key])+'||'
        # Finder chart
        if 'fndr_files' in locals():
            lin = lin+'['+fndr_files[ii]+' pdf_finder]|| ||' # Lick formatting is different
        # Write
        f.write(str(lin+'\n'))

    # Close
    print('lick.wiki: Wrote {:s}'.format(outfil))
    f.close()
开发者ID:banados,项目名称:xastropy,代码行数:81,代码来源:lick.py


注:本文中的xastropy.xutils.xdebug.set_trace函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。