예제 #1
0
def Plot(n):
    p = figure(plot_width=1200,
               plot_height=500,
               toolbar_location='above',
               tools="pan,wheel_zoom,box_zoom,reset,hover,save")
    p.line(np.array(n.wave),
           np.array(n.flux),
           line_width=2,
           color='blue',
           legend='Flux')
    p.line(np.array(n.wave),
           np.array(n.noise),
           line_width=1,
           color='black',
           legend='Uncertainty')
    if request.form.get('compare'):
        standard_flux = splat.core.getStandard(
            splat.classifyByStandard(n)[0]).flux * n.fluxMax().value
        p.line(np.array(n.wave),
               np.array(standard_flux),
               line_width=1,
               color='red',
               legend='Spectral Standard')
    p.xaxis.axis_label = 'Wavelength (Microns)'
    p.yaxis.axis_label = 'Flux (erg/cm^2 micron s)'
    ymax = n.fluxMax().value
    p.y_range = Range1d(0, ymax)
    return p
예제 #2
0
def show_sd_standards(s, ax, comp_range):
    """
    plot sd standards on the same axis
    s must be a spectrum object

    """
    
    #std=splat.STDS_DWARF_SPEX[spt]
    #_, scale=splat.compareSpectra(s.splat_spectrum, std,  comprange=[[0.8, 1.3]], statistic='chisqr', scale=True) 
    #std.scale(scale)
    #xlim=[0.8, 2.5 ]
    #mask= np.logical_and(s.wave>xlim[0],  s.wave<xlim[-1])
    #a.plot(s.wave, s.flux, label=shortname,linewidth=3, c='k')
    #a.plot(std.wave.value, std.flux.value, linestyle='--', label='{} std'.format(spt),\
    #       alpha=0.5)
    #sd_std=None
    legend_list=[]
    d_sd_std=None
    try:
        dsd_type, _= splat.classifyByStandard(s.splat_spectrum, comprange=comp_range, dsd=True)
        d_sd_std=splat.STDS_DSD_SPEX[dsd_type]
        _, d_sd_scale=splat.compareSpectra(s.splat_spectrum, d_sd_std,  comprange=comp_range, statistic='chisqr', scale=True) 
        d_sd_std.scale(d_sd_scale)
        l=ax.step(d_sd_std.wave.value, d_sd_std.flux.value, linestyle='dotted', label='{} STD'.format(dsd_type),\
           alpha=1., color='#B10DC9')
        legend_list.append(l)
    except KeyError:
        pass
        
    try:
        sd_type, _= splat.classifyByStandard(s.splat_spectrum, comprange=comp_range, sd=True)
        sd_std=splat.STDS_SD_SPEX[sd_type]
        _, sd_scale=splat.compareSpectra(s.splat_spectrum, sd_std,  comprange=comp_range, statistic='chisqr', scale=True) 
        sd_std.scale(sd_scale)
        l=ax.step(sd_std.wave.value, sd_std.flux.value, linestyle='dashed', label='{}  STD'.format(sd_type),\
           alpha=1., color='#0074D9')
        #legend_list.append(l)
    except KeyError:
        pass
    
    
    return legend_list
예제 #3
0
def Standard(n):
    a = splat.classifyByStandard(n)
    data = dict()
    columns = list()
    if request.form.get('standard'):
        data.update(spt=[a])
        source = ColumnDataSource(data)
        column_standard = [
            TableColumn(field='spt', title='Spectral Type'),
        ]
        Analysis1 = DataTable(source=source,
                              columns=column_standard,
                              width=1200,
                              height=50)
        return Analysis1
예제 #4
0
파일: web.py 프로젝트: dhomeier/splat
def load_spectra():
	#'/Users/guillaumeshippee/Desktop/splat-master/reference/Spectra/10001_10443.fits' #change
	if request.method == 'GET':
		return render_template('input.html', error='')
	else:
#		for k in list(request.form.keys()):
#			print(k,request.form[k])

# search by file "upload"	
		if request.form['submit'] == 'Load File':
			try:
				path = request.form['path']
				sp = splat.Spectrum(file=str(path))
				sp = [sp]
			except:
				return render_template('input.html',  error = "\n\nProblem with file upload button")
		
# search by file path specification	
		if request.form['submit'] == 'Load File ':
			try:
				path = request.form['path']
				sp = splat.Spectrum(file=str(path))
				sp = [sp]
			except:
				return render_template('input.html',  error = "\n\nProblem with file path specification")
		
# search by spectrum key	
		if request.form['submit'] == 'Load by ID':
			try:
				sp = splat.Spectrum(int(str(request.form['key'])))
				sp = [sp]
			except:
				return render_template('input.html',  error = "\n\nProblem with key specification")
		
# search by date observed	
		if request.form['submit'] == 'Load by Date':
			try:
				sp = splat.getSpectrum(date = str(request.form['date']))
			except:
				return render_template('input.html',  error = "\n\nProblem with key specification")
		
# search by shortname	
		elif request.form['submit'] == 'Load by Shortname':
			try:
				sp = splat.getSpectrum(shortname = str(request.form['shortname']))
			except:
				return render_template('input.html',  error = "\n\nProblem with specifying file by shortname")
	
# search by name	
		elif request.form['submit'] == 'Load by Name':
			try:
				sp = splat.getSpectrum(name = str(request.form['name']))
			except:
				return render_template('input.html',  error = "\n\nProblem with specifying file by name")
	
			
# search by options
		elif request.form['submit'] == 'Load by Options':
			sp1 = request.form['sp1']
			sp2 = request.form['sp2']
			mag1 = request.form['mag1']
			mag2 =  request.form['mag2']


			if sp2 == '':
				sp = sp1
			elif sp1 == '':
				sp2 = sp1
			elif sp1 == '' and sp2 == '':
				sp = ''
			else:
				sp = [sp1, sp2]

			if mag2 == '':
				mag = mag1
			elif sp1 == '':
				mag2 = mag1
			elif sp1 == '' and sp2 == '':
				mag = ''
			else:
				mag = [mag1, mag2]

			kwargs = {'spt': sp, 'jmag' : mag, 'snr' : request.form['snr'], 'date' : request.form['date'] }
			kwargs = {k: v for k, v in kwargs.items() if v}

			try:
				sp = splat.getSpectrum(**kwargs)
			except:
				return render_template('input.html', error = "\n\nProblem with option search")
			
# lucky pull	
		elif request.form['submit'] == 'Get Lucky!':
			sp = splat.getSpectrum(lucky=True)

		if len(sp) == 0:
			return render_template('input.html', error = "\n\nNo spectra matched search constratins")

		try:
			tab = []

			for s in sp:
				spectral_type = splat.classifyByStandard(s)[0]
				mpl_fig = splat.plotSpectrum(s, web=True, uncertainty = True, mdwarf=True)[0]
				bokehfig = mpl.to_bokeh(fig=mpl_fig)
				bokehfig.set(x_range=Range1d(.8,2.4),y_range=Range1d(0,s.fluxMax().value*1.2))
#				sys.stdout = open("out1.txt", "w") 
#				sys.stdout = sys.__stdout__
#				with open("out1.txt", "r") as f:
#					content = f.read() 
				content = s.info(printout=False)
#				print(content)
				p = Paragraph(text=content)
				widget = VBox(bokehfig, p)
				tab.append(Panel(child=widget, title=str(s.name)))
#				tab.append(Panel(child=widget, title=str(spectral_type)+ " Star"))
				
			plottabs = Tabs(tabs= tab)
			script, div_dict = components({"plot" : plottabs})
		except:
				return render_template('input.html', error = "\n\nProblem Plotting Spectra")
		
		return render_template('out.html', star_type = spectral_type, script=script,  div=div_dict)	
예제 #5
0
파일: splat_plot.py 프로젝트: caganze/splat
def plotSequence(*args, **kwargs):
    '''
    :Purpose: Compares a spectrum to a sequence of standards a batch of spectra into a 2x2 set of PDF files, with options of overplotting comparison spectra, including best-match spectral standards. 

    :param input: A single or list of Spectrum objects or filenames, or the glob search string for a set of files (e.g., '/Data/myspectra/*.fits'). 
    :type input: required

    :param type_range: Number of subtypes to consider above and below best-fit spectral type 
    :type type_range: optional, default = 2
    :param spt: Default spectral type for source; this input skips classifyByStandard
    :type spt: optional, default = None
    :param output: Filename for output; full path should be include if not saving to current directory. If blank, plot is shown on screen
    :type output: optional, default = None (screen display)

    Relevant parameters for plotSpectrum may also be passed

    :Example:
       >>> import glob, splat
       >>> files = glob.glob('/home/mydata/*.fits')
       >>> sp = splat.plotBatch(files,classify=True,output='comparison.pdf')
       >>> sp = splat.plotBatch('/home/mydata/*.fits',classify=True,output='comparison.pdf')
       >>> sp = splat.plotBatch([splat.Spectrum(file=f) for f in files],classify=True,output='comparison.pdf')
       All three of these commands produce the same result
    '''

# check inputs
    if len(args) == 0:
        raise ValueError('\nNeed to provide a spectrum object or filename for plotStandardSequence')

    parameters = ['type_range']
    splat.checkKeys(kwargs,parameters,forcekey=False)
    type_range =kwargs.get('type_range',2)
    kwargs['stack']=kwargs.get('stack',0.5)
#    kwargs['legendLocation']=kwargs.get('legendLocation','outside')
    kwargs['telluric']=kwargs.get('telluric',True)
    kwargs['method']=kwargs.get('method','kirkpatrick')
#    kwargs['color']=kwargs.get('color','r')
    kwargs['colorComparison']=kwargs.get('colorComparison','k')
    kwargs['colorScheme']=kwargs.get('colorScheme','winter')
    kwargs['figsize']=kwargs.get('figsize',[10,10*type_range*kwargs['stack']])
    kwargs['fontscale']=kwargs.get('fontscale',1.5)

# process input
    if isinstance(args[0],str):
        if len(glob.glob(args[0])) == 0:
            raise ValueError('\nCannot find input file {} - make sure full path is included'.format(args[0]))
        try:
            sp = splat.Spectrum(file = args[0])
        except:
            raise ValueError('\nCould not read in file {} - make sure the file is correctly formatted'.format(args[0]))
    elif isinstance(args[0],splat.Spectrum):
        sp = copy.deepcopy(args[0])
    else:
        raise ValueError('\nInput should be a Spectrum object or filename')
    sp.normalize()

# classify by comparison to standards
    spt = kwargs.get('spt',splat.classifyByStandard(sp,**kwargs)[0])
    if not isinstance(spt,str):
        spt = splat.typeToNum(spt)

# produce range of standards for plot
    stdnum = numpy.arange(numpy.floor(splat.typeToNum(spt)-type_range),numpy.ceil(splat.typeToNum(spt)+type_range)+1)
    if numpy.max(stdnum) > 39:
        stdnum-=(numpy.max(stdnum)-39)
    if numpy.min(stdnum) < 10:
        stdnum+=(10-numpy.min(stdnum))
    stdspt = [splat.typeToNum(i) for i in stdnum]
    stds = [splat.SPEX_STDS[s] for s in stdspt]
    stdlabels = ['{} Standard'.format(s) for s in stdspt]
    plotlist = []
    labels = []
    colors = []
    for i,stdsp in enumerate(stds):
        plotlist.append([stdsp,sp])
        labels.extend([])
    fig = splat.plotSpectrum(stds,comparison=sp,labels=stdlabels,**kwargs)

    return fig
예제 #6
0
파일: splat_plot.py 프로젝트: caganze/splat
def plotBatch(*args, **kwargs):
    '''
    :Purpose: Plots a batch of spectra into a 2x2 set of PDF files, with options of overplotting comparison spectra, including best-match spectral standards. 

    :param input: A single or list of Spectrum objects or filenames, or the glob search string for a set of files (e.g., '/Data/myspectra/*.fits'). 
    :type input: required

    :param output: Filename for PDF file output; full path should be include if not saving to current directory
    :type output: optional, default = 'spectra_plot.pdf'
    :param comparisons: list of Spectrum objects or filenames for comparison spectra. If comparisons list is shorter than source list, then last comparison source will be repeated. If the comparisons list is longer, the list will be truncated. 
    :type comparisons: optional, default = None
    :param classify: Set to True to classify sources based on comparison to MLT spectral standards following the method of `Kirkpatrick et al. (2010) <http://adsabs.harvard.edu/abs/2010ApJS..190..100K>`_. This option normalizes the spectra by default
    :type classify: optional, default = False
    :param normalize: Set to True to normalize source and (if passed) comparison spectra.
    :type normalize: optional, default = False
    :param legend: Set to list of legends for plots. The number of legends should equal the number of sources and comparisons (if passed) in an alternating sequence. T
    :type legend: optional, default = displays file name for source and object name for comparison (if passed)

    Relevant parameters for plotSpectrum may also be passed

    :Example:
       >>> import glob, splat
       >>> files = glob.glob('/home/mydata/*.fits')
       >>> sp = splat.plotBatch(files,classify=True,output='comparison.pdf')
       >>> sp = splat.plotBatch('/home/mydata/*.fits',classify=True,output='comparison.pdf')
       >>> sp = splat.plotBatch([splat.Spectrum(file=f) for f in files],classify=True,output='comparison.pdf')
       All three of these commands produce the same result
    '''

# keyword check
    parameters = ['output','comparisons','classify','normalize','legend']
    splat.checkKeys(kwargs,parameters,forcekey=False)
    kwargs['layout']=kwargs.get('layout',[2,2])
    kwargs['fontscale']=kwargs.get('fontscale',0.7)

# input check
    if len(args) == 0:
        print('\nNeed to provide a list of spectra or filenames, or a file search string, to use plotBatch')
        return
    kwargs['output'] = kwargs.get('output','spectra_plot.pdf')

# break out a list
    if isinstance(args[0],list):
        inputlist = args[0]
    else:
        inputlist = args

# if filenames, read in each file to a spectrum object
    if isinstance(inputlist[0],str):
# try a glob search string  
        files = glob.glob(inputlist[0])
        if len(files) > 1 or (len(files) == 1 and inputlist[0].find('*') != -1):
            inputlist = files
# try reading in files into Spectrum object
        try:
            splist = [splat.Spectrum(file = f) for f in inputlist]
        except:
            raise ValueError('\nCould not read in list of files - make sure the full path is specified and the files are correctly formatted')

# if filenames, read in each file to a spectrum object
    elif isinstance(inputlist[0],splat.Spectrum):
        splist = copy.deepcopy(inputlist)
    else:
        print('\nInput should be list of Spectra objects or filenames')
        return

# comparison files are present
    compflag = False
    complist = []
    if kwargs.get('comparisons',False) != False:
        comp = kwargs.get('comparisons')
        if not isinstance(comp,list):
            comp = [comp]
        if len(comp) < len(splist):
            while len(comp) < len(splist):
                comp.append(comp[-1])
        if isinstance(comp[0],str):
            try:
                complist = [splat.Spectrum(file = f) for f in comp]
                compflag = True
            except:
                print('\nCould not read in comparison files: ignoring comparisons')
        if isinstance(comp[0],splat.Spectrum):
            complist = comp
            compflag = True

# set comparison files to be standards for spectral classification
    if kwargs.get('classify',False):
        complist = []
        for sp in splist:
            spt = splat.classifyByStandard(sp,method='kirkpatrick')
            complist.append(splat.SPEX_STDS[spt[0]])
        compflag = True
        kwargs['normalize'] = kwargs.get('normalize',True)

# normalize if desired
    if kwargs.get('normalize',False):
        tmp = [sp.normalize() for sp in splist]
        if compflag == True:
            tmp = [sp.normalize() for sp in complist]

# prep for plotting
    plotlist = []
    clist = []
    for i,sp in enumerate(splist):
        if compflag == True:
            plotlist.append([sp,complist[i]])
            clist.extend(['k','r'])
        else:
            plotlist.append([sp])
            clist.extend(['k'])

# manage legends
    if kwargs.get('legend',False) != False:
        legends = kwargs.get('legend')
        if not isinstance(legends,list):
            legends = [legends]
        if len(legends) < (len(splist)+len(complist)):
# guess: just left out the comparison legends            
            if len(complist) > 0 and len(legends) == len(splist):
                legtmp = []
                for i,l in enumerate(legends):
                    legtmp.extend([l,'{}'.format(complist[i].name)])
                legends = legtmp
            else:
# otherwise: pad the remaining legends with the last legend (pairs)           
                while len(legends) < (len(splist)+len(complist)):
                    if compflag:
                        legends.extend([legends[-2],legends[-1]])
                    else:
                        legends.extend([legends[-1]])
        if len(legends) > (len(splist)+len(complist)):
            legends = legends[0:(len(splist)+len(complist))]
    else:
        legends = []
        for i,sp in enumerate(splist):
            if compflag == True:
                legends.extend(['{}'.format(os.path.basename(sp.filename)),'{}'.format(complist[i].name)])
            else:
                legends.extend(['{}'.format(os.path.basename(sp.filename))])

# generate pdf
    splat.plotSpectrum(plotlist,multiplot=True,multipage=True,legends=legends,colors=clist,**kwargs)

    return
예제 #7
0
def load_spectra():
    #'/Users/guillaumeshippee/Desktop/splat-master/reference/Spectra/10001_10443.fits' #change
    if request.method == 'GET':
        return render_template('input.html', error='')
    else:
        #		for k in list(request.form.keys()):
        #			print(k,request.form[k])

        # search by file "upload"
        if request.form['submit'] == 'Load File':
            try:
                path = request.form['path']
                sp = splat.Spectrum(file=str(path))
                sp = [sp]
            except:
                return render_template(
                    'input.html', error="\n\nProblem with file upload button")

# search by file path specification
        if request.form['submit'] == 'Load File ':
            try:
                path = request.form['path']
                sp = splat.Spectrum(file=str(path))
                sp = [sp]
            except:
                return render_template(
                    'input.html',
                    error="\n\nProblem with file path specification")

# search by spectrum key
        if request.form['submit'] == 'Load by ID':
            try:
                sp = splat.Spectrum(int(str(request.form['key'])))
                sp = [sp]
            except:
                return render_template(
                    'input.html', error="\n\nProblem with key specification")

# search by date observed
        if request.form['submit'] == 'Load by Date':
            try:
                sp = splat.getSpectrum(date=str(request.form['date']))
            except:
                return render_template(
                    'input.html', error="\n\nProblem with key specification")

# search by shortname
        elif request.form['submit'] == 'Load by Shortname':
            try:
                sp = splat.getSpectrum(
                    shortname=str(request.form['shortname']))
            except:
                return render_template(
                    'input.html',
                    error="\n\nProblem with specifying file by shortname")

# search by name
        elif request.form['submit'] == 'Load by Name':
            try:
                sp = splat.getSpectrum(name=str(request.form['name']))
            except:
                return render_template(
                    'input.html',
                    error="\n\nProblem with specifying file by name")

# search by options
        elif request.form['submit'] == 'Load by Options':
            sp1 = request.form['sp1']
            sp2 = request.form['sp2']
            mag1 = request.form['mag1']
            mag2 = request.form['mag2']

            if sp2 == '':
                sp = sp1
            elif sp1 == '':
                sp2 = sp1
            elif sp1 == '' and sp2 == '':
                sp = ''
            else:
                sp = [sp1, sp2]

            if mag2 == '':
                mag = mag1
            elif sp1 == '':
                mag2 = mag1
            elif sp1 == '' and sp2 == '':
                mag = ''
            else:
                mag = [mag1, mag2]

            kwargs = {
                'spt': sp,
                'jmag': mag,
                'snr': request.form['snr'],
                'date': request.form['date']
            }
            kwargs = {k: v for k, v in kwargs.items() if v}

            try:
                sp = splat.getSpectrum(**kwargs)
            except:
                return render_template('input.html',
                                       error="\n\nProblem with option search")

# lucky pull
        elif request.form['submit'] == 'Get Lucky!':
            sp = splat.getSpectrum(lucky=True)

        if len(sp) == 0:
            return render_template(
                'input.html',
                error="\n\nNo spectra matched search constratins")

        try:
            tab = []

            for s in sp:
                spectral_type = splat.classifyByStandard(s)[0]
                mpl_fig = splot.plotSpectrum(s, web=True, uncertainty=True)[0]
                bokehfig = mpl.to_bokeh(fig=mpl_fig)
                bokehfig.set(x_range=Range1d(.8, 2.4),
                             y_range=Range1d(0,
                                             s.fluxMax().value * 1.2))
                #				sys.stdout = open("out1.txt", "w")
                #				sys.stdout = sys.__stdout__
                #				with open("out1.txt", "r") as f:
                #					content = f.read()
                content = s.info(printout=False)
                #				print(content)
                p = Paragraph(text=content)
                widget = VBox(bokehfig, p)
                tab.append(Panel(child=widget, title=str(s.name)))


#				tab.append(Panel(child=widget, title=str(spectral_type)+ " Star"))

            plottabs = Tabs(tabs=tab)
            script, div_dict = components({"plot": tab})
        except:
            return render_template('input.html',
                                   error="\n\nProblem Plotting Spectra")

        return render_template('output.html',
                               star_type=spectral_type,
                               script=script,
                               div=div_dict)
예제 #8
0
def plotSequence(*args, **kwargs):
    '''
    :Purpose: Compares a spectrum to a sequence of standards a batch of spectra into a 2x2 set of PDF files, with options of overplotting comparison spectra, including best-match spectral standards. 

    :param input: A single or list of Spectrum objects or filenames, or the glob search string for a set of files (e.g., '/Data/myspectra/*.fits'). 
    :type input: required

    :param type_range: Number of subtypes to consider above and below best-fit spectral type 
    :type type_range: optional, default = 2
    :param spt: Default spectral type for source; this input skips classifyByStandard
    :type spt: optional, default = None
    :param output: Filename for output; full path should be include if not saving to current directory. If blank, plot is shown on screen
    :type output: optional, default = None (screen display)

    Relevant parameters for plotSpectrum may also be passed

    :Example:
       >>> import glob, splat
       >>> files = glob.glob('/home/mydata/*.fits')
       >>> sp = splat.plotBatch(files,classify=True,output='comparison.pdf')
       >>> sp = splat.plotBatch('/home/mydata/*.fits',classify=True,output='comparison.pdf')
       >>> sp = splat.plotBatch([splat.Spectrum(file=f) for f in files],classify=True,output='comparison.pdf')
       All three of these commands produce the same result
    '''

    # check inputs
    if len(args) == 0:
        raise ValueError(
            '\nNeed to provide a spectrum object or filename for plotStandardSequence'
        )

    parameters = ['type_range']
    splat.checkKeys(kwargs, parameters, forcekey=False)
    type_range = kwargs.get('type_range', 2)
    kwargs['stack'] = kwargs.get('stack', 0.5)
    #    kwargs['legendLocation']=kwargs.get('legendLocation','outside')
    kwargs['telluric'] = kwargs.get('telluric', True)
    kwargs['method'] = kwargs.get('method', 'kirkpatrick')
    #    kwargs['color']=kwargs.get('color','r')
    kwargs['colorComparison'] = kwargs.get('colorComparison', 'k')
    kwargs['colorScheme'] = kwargs.get('colorScheme', 'winter')
    kwargs['figsize'] = kwargs.get('figsize',
                                   [10, 10 * type_range * kwargs['stack']])
    kwargs['fontscale'] = kwargs.get('fontscale', 1.5)

    # process input
    if isinstance(args[0], str):
        if len(glob.glob(args[0])) == 0:
            raise ValueError(
                '\nCannot find input file {} - make sure full path is included'
                .format(args[0]))
        try:
            sp = splat.Spectrum(file=args[0])
        except:
            raise ValueError(
                '\nCould not read in file {} - make sure the file is correctly formatted'
                .format(args[0]))
    elif isinstance(args[0], splat.Spectrum):
        sp = copy.deepcopy(args[0])
    else:
        raise ValueError('\nInput should be a Spectrum object or filename')
    sp.normalize()

    # classify by comparison to standards
    spt = kwargs.get('spt', splat.classifyByStandard(sp, **kwargs)[0])
    if not isinstance(spt, str):
        spt = splat.typeToNum(spt)

# produce range of standards for plot
    stdnum = numpy.arange(numpy.floor(splat.typeToNum(spt) - type_range),
                          numpy.ceil(splat.typeToNum(spt) + type_range) + 1)
    if numpy.max(stdnum) > 39:
        stdnum -= (numpy.max(stdnum) - 39)
    if numpy.min(stdnum) < 10:
        stdnum += (10 - numpy.min(stdnum))
    stdspt = [splat.typeToNum(i) for i in stdnum]
    stds = [splat.SPEX_STDS[s] for s in stdspt]
    stdlabels = ['{} Standard'.format(s) for s in stdspt]
    plotlist = []
    labels = []
    colors = []
    for i, stdsp in enumerate(stds):
        plotlist.append([stdsp, sp])
        labels.extend([])
    fig = splat.plotSpectrum(stds, comparison=sp, labels=stdlabels, **kwargs)

    return fig
예제 #9
0
def plotBatch(*args, **kwargs):
    '''
    :Purpose: Plots a batch of spectra into a 2x2 set of PDF files, with options of overplotting comparison spectra, including best-match spectral standards. 

    :param input: A single or list of Spectrum objects or filenames, or the glob search string for a set of files (e.g., '/Data/myspectra/*.fits'). 
    :type input: required

    :param output: Filename for PDF file output; full path should be include if not saving to current directory
    :type output: optional, default = 'spectra_plot.pdf'
    :param comparisons: list of Spectrum objects or filenames for comparison spectra. If comparisons list is shorter than source list, then last comparison source will be repeated. If the comparisons list is longer, the list will be truncated. 
    :type comparisons: optional, default = None
    :param classify: Set to True to classify sources based on comparison to MLT spectral standards following the method of `Kirkpatrick et al. (2010) <http://adsabs.harvard.edu/abs/2010ApJS..190..100K>`_. This option normalizes the spectra by default
    :type classify: optional, default = False
    :param normalize: Set to True to normalize source and (if passed) comparison spectra.
    :type normalize: optional, default = False
    :param legend: Set to list of legends for plots. The number of legends should equal the number of sources and comparisons (if passed) in an alternating sequence. T
    :type legend: optional, default = displays file name for source and object name for comparison (if passed)

    Relevant parameters for plotSpectrum may also be passed

    :Example:
       >>> import glob, splat
       >>> files = glob.glob('/home/mydata/*.fits')
       >>> sp = splat.plotBatch(files,classify=True,output='comparison.pdf')
       >>> sp = splat.plotBatch('/home/mydata/*.fits',classify=True,output='comparison.pdf')
       >>> sp = splat.plotBatch([splat.Spectrum(file=f) for f in files],classify=True,output='comparison.pdf')
       All three of these commands produce the same result
    '''

    # keyword check
    parameters = ['output', 'comparisons', 'classify', 'normalize', 'legend']
    splat.checkKeys(kwargs, parameters, forcekey=False)
    kwargs['layout'] = kwargs.get('layout', [2, 2])
    kwargs['fontscale'] = kwargs.get('fontscale', 0.7)

    # input check
    if len(args) == 0:
        print(
            '\nNeed to provide a list of spectra or filenames, or a file search string, to use plotBatch'
        )
        return
    kwargs['output'] = kwargs.get('output', 'spectra_plot.pdf')

    # break out a list
    if isinstance(args[0], list):
        inputlist = args[0]
    else:
        inputlist = args

# if filenames, read in each file to a spectrum object
    if isinstance(inputlist[0], str):
        # try a glob search string
        files = glob.glob(inputlist[0])
        if len(files) > 1 or (len(files) == 1
                              and inputlist[0].find('*') != -1):
            inputlist = files
# try reading in files into Spectrum object
        try:
            splist = [splat.Spectrum(file=f) for f in inputlist]
        except:
            raise ValueError(
                '\nCould not read in list of files - make sure the full path is specified and the files are correctly formatted'
            )

# if filenames, read in each file to a spectrum object
    elif isinstance(inputlist[0], splat.Spectrum):
        splist = copy.deepcopy(inputlist)
    else:
        print('\nInput should be list of Spectra objects or filenames')
        return

# comparison files are present
    compflag = False
    complist = []
    if kwargs.get('comparisons', False) != False:
        comp = kwargs.get('comparisons')
        if not isinstance(comp, list):
            comp = [comp]
        if len(comp) < len(splist):
            while len(comp) < len(splist):
                comp.append(comp[-1])
        if isinstance(comp[0], str):
            try:
                complist = [splat.Spectrum(file=f) for f in comp]
                compflag = True
            except:
                print(
                    '\nCould not read in comparison files: ignoring comparisons'
                )
        if isinstance(comp[0], splat.Spectrum):
            complist = comp
            compflag = True

# set comparison files to be standards for spectral classification
    if kwargs.get('classify', False):
        complist = []
        for sp in splist:
            spt = splat.classifyByStandard(sp, method='kirkpatrick')
            complist.append(splat.SPEX_STDS[spt[0]])
        compflag = True
        kwargs['normalize'] = kwargs.get('normalize', True)

# normalize if desired
    if kwargs.get('normalize', False):
        tmp = [sp.normalize() for sp in splist]
        if compflag == True:
            tmp = [sp.normalize() for sp in complist]

# prep for plotting
    plotlist = []
    clist = []
    for i, sp in enumerate(splist):
        if compflag == True:
            plotlist.append([sp, complist[i]])
            clist.extend(['k', 'r'])
        else:
            plotlist.append([sp])
            clist.extend(['k'])

# manage legends
    if kwargs.get('legend', False) != False:
        legends = kwargs.get('legend')
        if not isinstance(legends, list):
            legends = [legends]
        if len(legends) < (len(splist) + len(complist)):
            # guess: just left out the comparison legends
            if len(complist) > 0 and len(legends) == len(splist):
                legtmp = []
                for i, l in enumerate(legends):
                    legtmp.extend([l, '{}'.format(complist[i].name)])
                legends = legtmp
            else:
                # otherwise: pad the remaining legends with the last legend (pairs)
                while len(legends) < (len(splist) + len(complist)):
                    if compflag:
                        legends.extend([legends[-2], legends[-1]])
                    else:
                        legends.extend([legends[-1]])
        if len(legends) > (len(splist) + len(complist)):
            legends = legends[0:(len(splist) + len(complist))]
    else:
        legends = []
        for i, sp in enumerate(splist):
            if compflag == True:
                legends.extend([
                    '{}'.format(os.path.basename(sp.filename)),
                    '{}'.format(complist[i].name)
                ])
            else:
                legends.extend(['{}'.format(os.path.basename(sp.filename))])


# generate pdf
    splat.plotSpectrum(plotlist,
                       multiplot=True,
                       multipage=True,
                       legends=legends,
                       colors=clist,
                       **kwargs)

    return