Ejemplo n.º 1
0
def test_windows(options):
    elems = [
        'C', 'N', 'O', 'Na', 'Mg', 'Al', 'Si', 'S', 'K', 'Ca', 'Ti', 'V', 'Mn',
        'Fe', 'Ni', 'Ce', 'Co', 'Cr', 'Cu', 'Ge', 'Nd', 'P', 'Rb', 'Y'
    ]
    if options.savefilename is None or \
            not os.path.exists(options.savefilename):
        # Set default linelist for Turbospectrum or MOOG
        if options.linelist is None and options.moog:
            linelist = 'moog.201312161124.vac'
        elif options.linelist is None:
            linelist = 'turbospec.201312161124'
        else:
            linelist = options.linelist
        # set up a model atmosphere for the requested atmospheric parameters
        if options.arcturus:
            options.teff = 4286.
            options.logg = 1.66
            options.metals = -0.52
            options.am = 0.4
            options.cm = 0.09
            options.vm = 1.7
        atm = atlas9.Atlas9Atmosphere(teff=options.teff,
                                      logg=options.logg,
                                      metals=options.metals,
                                      am=options.am,
                                      cm=options.cm)
        # create baseline
        if options.moog:
            baseline= \
                apogee.modelspec.moog.synth(modelatm=atm,
                                            linelist=linelist,
                                            lsf='all',cont='aspcap',
                                            vmacro=6.,isotopes='arcturus',
                                            vmicro=options.vm)
        else:
            baseline= \
                apogee.modelspec.turbospec.synth(modelatm=atm,
                                                 linelist=linelist,
                                                 lsf='all',cont='aspcap',
                                                 vmacro=6.,isotopes='arcturus',
                                                 vmicro=options.vm)
        # Loop through elements
        elem_synspec = {}
        # Run through once to simulate all differences
        for elem in elems:
            # First check that this element has windows
            elemPath = apwindow.path(elem, dr=options.dr)
            if not os.path.exists(elemPath): continue
            # Simulate deltaAbu up and down
            print "Working on %s" % (elem.capitalize())
            abu = [atomic_number(elem), -options.deltaAbu, options.deltaAbu]
            if options.moog:
                synspec= \
                    apogee.modelspec.moog.synth(abu,
                                                modelatm=atm,
                                                linelist=linelist,
                                                lsf='all',cont='aspcap',
                                                vmacro=6.,
                                                isotopes='arcturus',
                                                vmicro=options.vm)
            else:
                synspec= \
                    apogee.modelspec.turbospec.synth(abu,
                                                     modelatm=atm,
                                                     linelist=linelist,
                                                     lsf='all',cont='aspcap',
                                                     vmacro=6.,
                                                     isotopes='arcturus',
                                                     vmicro=options.vm)
            elem_synspec[elem] = synspec
        if not options.savefilename is None:
            save_pickles(options.savefilename, baseline, elem_synspec)
    else:
        with open(options.savefilename, 'rb') as savefile:
            baseline = pickle.load(savefile)
            elem_synspec = pickle.load(savefile)
    # Now run through the different elements again and plot windows for each
    # with elements that vary significantly
    colors = sns.color_palette("colorblind")
    plotelems = [
        elem if not elem in ['C', 'N', 'O', 'Fe'] else '%s1' % elem
        for elem in elems
    ]
    plotelems.extend(['C2', 'N2', 'O2', 'Fe2'])
    for pelem in plotelems:
        if '1' in pelem or '2' in pelem: elem = pelem[:-1]
        else: elem = pelem
        if not elem in elem_synspec: continue
        # Figure out which elements have significant variations in these
        # windows and always plot the element that should vary
        elemIndx = apwindow.tophat(elem, dr=options.dr)
        elemWeights = apwindow.read(elem, dr=options.dr)
        elemWeights /= numpy.nansum(elemWeights)
        # Start with the element in question
        splot.windows(1. + options.amplify *
                      (elem_synspec[elem][0] - baseline[0]),
                      pelem,
                      color=colors[0],
                      yrange=[0., 1.4],
                      plot_weights=True,
                      zorder=len(elems))
        splot.windows(1. + options.amplify *
                      (elem_synspec[elem][1] - baseline[0]),
                      pelem,
                      color=colors[0],
                      overplot=True,
                      zorder=len(elems))
        elem_shown = [elem]
        # Run through the rest to figure out the order
        elemVar = numpy.zeros(len(elems))
        for ii, altElem in enumerate(elems):
            if altElem == elem: continue
            if not altElem in elem_synspec: continue
            elemVar[ii] = 0.5 * numpy.nansum(
                (elem_synspec[altElem][0] - baseline[0])**2. * elemWeights)
            elemVar[ii] += 0.5 * numpy.nansum(
                (elem_synspec[altElem][1] - baseline[0])**2. * elemWeights)
        jj = 0
        sortindx = numpy.argsort(elemVar)[::-1]
        for altElem in numpy.array(elems)[sortindx]:
            if altElem == elem: continue
            if not altElem in elem_synspec: continue
            if numpy.fabs(\
                numpy.nanmax([(elem_synspec[altElem][0]-baseline[0])[elemIndx],
                            (elem_synspec[altElem][1]-baseline[0])[elemIndx]]))\
                            > options.varthreshold:
                jj += 1
                if jj >= len(colors): jj = len(colors) - 1
                elem_shown.append(altElem)
                splot.windows(1. + options.amplify *
                              (elem_synspec[altElem][0] - baseline[0]),
                              pelem,
                              color=colors[jj],
                              overplot=True,
                              zorder=len(elems) - jj)
                splot.windows(1. + options.amplify *
                              (elem_synspec[altElem][1] - baseline[0]),
                              pelem,
                              color=colors[jj],
                              overplot=True,
                              zorder=len(elems) - jj)
        t = pyplot.gca().transData
        fig = pyplot.gcf()
        for s, c in zip(elem_shown, colors[:jj + 1]):
            xc = 0.05
            if elem == 'K' or elem == 'Ce' or elem == 'Ge' or elem == 'Nd' \
                    or elem == 'Rb':
                xc = apwindow.waveregions(elem, dr=options.dr,
                                          pad=3)[0][0] - 15000. + 1.
            text = pyplot.text(xc,
                               1.2,
                               " " + (r"$\mathrm{%s}$" % s) + " ",
                               color=c,
                               transform=t,
                               size=16.,
                               backgroundcolor='w')
            text.draw(fig.canvas.get_renderer())
            ex = text.get_window_extent()
            t = transforms.offset_copy(text._transform,
                                       x=1.5 * ex.width,
                                       units='dots')
        # Save
        bovy_plot.bovy_end_print(options.plotfilename.replace('ELEM', pelem))
    return None
Ejemplo n.º 2
0
def elements(elem,*args,**kwargs):
    """
    NAME:
       elements
    PURPOSE:
       make a plot of measurements of the elemental abundances vs. atomic number
    INPUT:
       elem - dictionary with elemental abundances relative to H
       wrtFe= (True) if True, plot elements wrt Fe on the left Y
       inclwrtH= (True) if True, indicate what X/H is on the right Y
       bovy_plot.bovy_plot args and kwargs
    OUTPUT:
       plot to output
    HISTORY:
       2015-03-10 - Written - Bovy (IAS)
    """
    # Process the input dictionary
    xs= []
    names= []
    ys= []
    wrtFe= kwargs.pop('wrtFe',True)
    for el in elem:
        try:
            xs.append(atomic_number(el))
        except KeyError: # ignore things that aren't known elements
            continue
        names.append(r'$\mathrm{%s}$' % el.lower().capitalize())
        try:
            if not wrtFe: raise KeyError
            ys.append(elem[el]-elem['Fe'])
        except KeyError:
            ys.append(elem[el])
            wrtFe= False
    xs= numpy.array(xs,dtype='int')
    ys= numpy.array(ys)
    names= numpy.array(names)
    # sort
    sindx= numpy.argsort(xs)
    xs= xs[sindx]
    ys= ys[sindx]
    names= names[sindx]
    # add second y axis?
    inclwrtH= kwargs.pop('inclwrtH',True)
    if wrtFe:
        feh= elem['Fe']
        ylabel= kwargs.pop('ylabel',r'$[\mathrm{X/Fe}]$')
    else:
        ylabel= kwargs.pop('ylabel',r'$[\mathrm{X/H}]$')
    if not kwargs.get('overplot',False):
        bovy_plot.bovy_print(fig_width=7.,fig_height=4.)
    basezorder= kwargs.pop('zorder',0)
    yrange=kwargs.pop('yrange',[-0.5,0.5])
    ls= kwargs.pop('ls','-')
    lw= kwargs.pop('lw',0.25)
    bovy_plot.bovy_plot(xs,ys,*args,
                        ylabel=ylabel,
                        xrange=[4,numpy.amax(xs)+2],
                        yrange=yrange,zorder=2+basezorder,ls=ls,lw=lw,
                        **kwargs)
    pyplot.xticks(list(xs),names)
    pyplot.tick_params(axis='x',labelsize=11.)
    if wrtFe and inclwrtH:
        bovy_plot.bovy_plot([4,numpy.amax(xs)+2],[0.,0.],'-',lw=2.,
                            color='0.65',overplot=True,zorder=basezorder)
        ax= pyplot.gca()
        ax2= ax.twinx()
        ax2.set_ylim(yrange[0]+feh,yrange[1]+feh)
        ax2.set_ylabel(r'$[\mathrm{X/H}]$')
        pyplot.sca(ax2)
        bovy_plot._add_ticks(yticks=True,xticks=False)
    return None
Ejemplo n.º 3
0
def elements(elem, *args, **kwargs):
    """
    NAME:
       elements
    PURPOSE:
       make a plot of measurements of the elemental abundances vs. atomic number
    INPUT:
       elem - dictionary with elemental abundances relative to H
       wrtFe= (True) if True, plot elements wrt Fe on the left Y
       inclwrtH= (True) if True, indicate what X/H is on the right Y
       bovy_plot.bovy_plot args and kwargs
    OUTPUT:
       plot to output
    HISTORY:
       2015-03-10 - Written - Bovy (IAS)
    """
    # Process the input dictionary
    xs = []
    names = []
    ys = []
    wrtFe = kwargs.pop('wrtFe', True)
    for el in elem:
        try:
            xs.append(atomic_number(el))
        except KeyError:  # ignore things that aren't known elements
            continue
        names.append(r'$\mathrm{%s}$' % el.lower().capitalize())
        try:
            if not wrtFe: raise KeyError
            ys.append(elem[el] - elem['Fe'])
        except KeyError:
            ys.append(elem[el])
            wrtFe = False
    xs = numpy.array(xs, dtype='int')
    ys = numpy.array(ys)
    names = numpy.array(names)
    # sort
    sindx = numpy.argsort(xs)
    xs = xs[sindx]
    ys = ys[sindx]
    names = names[sindx]
    # add second y axis?
    inclwrtH = kwargs.pop('inclwrtH', True)
    if wrtFe:
        feh = elem['Fe']
        ylabel = kwargs.pop('ylabel', r'$[\mathrm{X/Fe}]$')
    else:
        ylabel = kwargs.pop('ylabel', r'$[\mathrm{X/H}]$')
    if not kwargs.get('overplot', False):
        bovy_plot.bovy_print(fig_width=7., fig_height=4.)
    basezorder = kwargs.pop('zorder', 0)
    yrange = kwargs.pop('yrange', [-0.5, 0.5])
    ls = kwargs.pop('ls', '-')
    lw = kwargs.pop('lw', 0.25)
    bovy_plot.bovy_plot(xs,
                        ys,
                        *args,
                        ylabel=ylabel,
                        xrange=[4, numpy.amax(xs) + 2],
                        yrange=yrange,
                        zorder=2 + basezorder,
                        ls=ls,
                        lw=lw,
                        **kwargs)
    pyplot.xticks(list(xs), names)
    pyplot.tick_params(axis='x', labelsize=11.)
    if wrtFe and inclwrtH:
        bovy_plot.bovy_plot([4, numpy.amax(xs) + 2], [0., 0.],
                            '-',
                            lw=2.,
                            color='0.65',
                            overplot=True,
                            zorder=basezorder)
        ax = pyplot.gca()
        ax2 = ax.twinx()
        ax2.set_ylim(yrange[0] + feh, yrange[1] + feh)
        ax2.set_ylabel(r'$[\mathrm{X/H}]$')
        pyplot.sca(ax2)
        bovy_plot._add_ticks(yticks=True, xticks=False)
    return None
Ejemplo n.º 4
0
def test_windows(options):
    elems= ['C','N','O','Na','Mg','Al','Si','S','K','Ca','Ti','V','Mn','Fe',
            'Ni','Ce','Co','Cr','Cu','Ge','Nd','P','Rb','Y']
    if options.savefilename is None or \
            not os.path.exists(options.savefilename):
        # Set default linelist for Turbospectrum or MOOG
        if options.linelist is None and options.moog:
            linelist= 'moog.201312161124.vac'
        elif options.linelist is None:
            linelist= 'turbospec.201312161124'
        else:
            linelist= options.linelist
        # set up a model atmosphere for the requested atmospheric parameters
        if options.arcturus:
            options.teff= 4286.
            options.logg= 1.66
            options.metals= -0.52
            options.am= 0.4
            options.cm= 0.09
            options.vm= 1.7
        atm= atlas9.Atlas9Atmosphere(teff=options.teff,logg=options.logg,
                                     metals=options.metals,
                                     am=options.am,cm=options.cm)
        # create baseline
        if options.moog:
            baseline= \
                apogee.modelspec.moog.synth(modelatm=atm,
                                            linelist=linelist,
                                            lsf='all',cont='aspcap',
                                            vmacro=6.,isotopes='arcturus',
                                            vmicro=options.vm)
        else:
            baseline= \
                apogee.modelspec.turbospec.synth(modelatm=atm,
                                                 linelist=linelist,
                                                 lsf='all',cont='aspcap',
                                                 vmacro=6.,isotopes='arcturus',
                                                 vmicro=options.vm)
        # Loop through elements
        elem_synspec= {}
        # Run through once to simulate all differences
        for elem in elems:
            # First check that this element has windows
            elemPath= apwindow.path(elem,dr=options.dr)
            if not os.path.exists(elemPath): continue
            # Simulate deltaAbu up and down
            print "Working on %s" % (elem.capitalize())
            abu= [atomic_number(elem),-options.deltaAbu,options.deltaAbu]
            if options.moog:
                synspec= \
                    apogee.modelspec.moog.synth(abu,
                                                modelatm=atm,
                                                linelist=linelist,
                                                lsf='all',cont='aspcap',
                                                vmacro=6.,
                                                isotopes='arcturus',
                                                vmicro=options.vm)
            else:
                synspec= \
                    apogee.modelspec.turbospec.synth(abu,
                                                     modelatm=atm,
                                                     linelist=linelist,
                                                     lsf='all',cont='aspcap',
                                                     vmacro=6.,
                                                     isotopes='arcturus',
                                                     vmicro=options.vm)
            elem_synspec[elem]= synspec
        if not options.savefilename is None:
            save_pickles(options.savefilename,baseline,elem_synspec)
    else:
        with open(options.savefilename,'rb') as savefile:
            baseline= pickle.load(savefile)
            elem_synspec= pickle.load(savefile)
    # Now run through the different elements again and plot windows for each
    # with elements that vary significantly
    colors= sns.color_palette("colorblind")
    plotelems= [elem if not elem in ['C','N','O','Fe'] else '%s1' % elem
                for elem in elems]
    plotelems.extend(['C2','N2','O2','Fe2'])
    for pelem in plotelems:
        if '1' in pelem or '2' in pelem: elem = pelem[:-1]
        else: elem= pelem
        if not elem in elem_synspec: continue
        # Figure out which elements have significant variations in these 
        # windows and always plot the element that should vary
        elemIndx= apwindow.tophat(elem,dr=options.dr)
        elemWeights= apwindow.read(elem,dr=options.dr)
        elemWeights/= numpy.nansum(elemWeights)
        # Start with the element in question
        splot.windows(1.+options.amplify*(elem_synspec[elem][0]-baseline[0]),
                      pelem,
                      color=colors[0],
                      yrange=[0.,1.4],
                      plot_weights=True,
                      zorder=len(elems))
        splot.windows(1.+options.amplify*(elem_synspec[elem][1]-baseline[0]),
                      pelem,
                      color=colors[0],overplot=True, 
                      zorder=len(elems))
        elem_shown= [elem]
        # Run through the rest to figure out the order
        elemVar= numpy.zeros(len(elems))
        for ii,altElem in enumerate(elems):
            if altElem == elem: continue
            if not altElem in elem_synspec: continue
            elemVar[ii]= 0.5*numpy.nansum((elem_synspec[altElem][0]-baseline[0])**2.*elemWeights)
            elemVar[ii]+= 0.5*numpy.nansum((elem_synspec[altElem][1]-baseline[0])**2.*elemWeights)
        jj= 0
        sortindx= numpy.argsort(elemVar)[::-1]
        for altElem in numpy.array(elems)[sortindx]:
            if altElem == elem: continue
            if not altElem in elem_synspec: continue
            if numpy.fabs(\
                numpy.nanmax([(elem_synspec[altElem][0]-baseline[0])[elemIndx],
                            (elem_synspec[altElem][1]-baseline[0])[elemIndx]]))\
                            > options.varthreshold:
                jj+= 1
                if jj >= len(colors): jj= len(colors)-1
                elem_shown.append(altElem)
                splot.windows(1.+options.amplify*(elem_synspec[altElem][0]-baseline[0]),
                              pelem,
                              color=colors[jj],overplot=True,
                              zorder=len(elems)-jj)
                splot.windows(1.+options.amplify*(elem_synspec[altElem][1]-baseline[0]),
                              pelem,
                              color=colors[jj],overplot=True,
                              zorder=len(elems)-jj)
        t = pyplot.gca().transData
        fig= pyplot.gcf()
        for s,c in zip(elem_shown,colors[:jj+1]):
            xc= 0.05
            if elem == 'K' or elem == 'Ce' or elem == 'Ge' or elem == 'Nd' \
                    or elem == 'Rb':
                xc= apwindow.waveregions(elem,dr=options.dr,
                                         pad=3)[0][0]-15000.+1.
            text = pyplot.text(xc,1.2," "+(r"$\mathrm{%s}$" % s)+" ",color=c,
                               transform=t,size=16.,backgroundcolor='w')
            text.draw(fig.canvas.get_renderer())
            ex= text.get_window_extent()
            t= transforms.offset_copy(text._transform,x=1.5*ex.width,
                                      units='dots')
        # Save
        bovy_plot.bovy_end_print(options.plotfilename.replace('ELEM',pelem))
    return None