Example #1
0
def phxCompare(star, wlim=None, maxpow=None, mindw=None, ax=None):
    if ax is None: ax = plt.gca()

    xf = db.findfiles('ir', 'phx', star, fullpaths=True)
    pf = db.panpath(star)

    phx = io.read(xf)[0]
    pan = io.read(pf)[0]
    normfac = pan['normfac'][-1]
    if wlim is not None:
        phx, pan = utils.keepranges(phx, wlim), utils.keepranges(pan, wlim)

    if maxpow or mindw:
        pan = utils.fancyBin(pan, maxpow=maxpow, mindw=mindw)
        phx = utils.fancyBin(phx, maxpow=maxpow, mindw=mindw)

    Fbol = utils.bolo_integral(star)
    pan['normflux'] = pan['flux'] / Fbol
    pan['normerr'] = pan['error'] / Fbol
    phx['normflux'] = phx['flux'] * normfac / Fbol

    line = specstep(pan, key='normflux', label='Panspec', ax=ax)
    specstep(pan,
             key='normerr',
             label='Panspec Error',
             ax=ax,
             color=line.get_color(),
             ls=':')
    specstep(phx, key='normflux', label='Phoenix', ax=ax, color='r', alpha=0.5)
    ax.set_xlim(wlim)
    ax.legend(loc='best')
Example #2
0
def compare_v20_v10(stars=None, plot=False):

    if stars is None:
        stars = mlstars

    oldfile_template = '/Users/rolo7566/Datasets/MUSCLES/products/archive/panspecs v10/p_msl_pan_-----_{}_panspec_native_resolution.fits'
    hlspfile_template = '/Users/rolo7566/Google Drive/Grad School/PhD Work/muscles/share/hlsp/archive/hlsp_muscles_multi_multi_{}_broadband_v10_var-res-sed.fits'
    compare_template = '/Users/rolo7566/Google Drive/Grad School/PhD Work/muscles/scratchwork/v10 - v20 comparisons/{' \
                       '} v20 vs v10 ratio.fits'

    for star in stars:
        p = io.readpan(star)
        op, = io.read(oldfile_template.format(star))
        hp, = io.read(hlspfile_template.format(star))
        op = red.splice(op, utils.keepranges(hp, 100., 1169.))
        p, op = [utils.keepranges(spec, 0, 10000.) for spec in [p, op]]
        cs = utils.compare_specs(p, op, savetxt=compare_template.format(star))

        cf = compare_template.format(star)
        cs.write(cf, overwrite=True)

        if plot:
            plt.figure()
            ss(cs, key='ratio')
            plt.title(star)
            plt.xlabel('Wavelength $\AA$')
            plt.ylabel('Ratio of v20 to v10 SED')
Example #3
0
def vetnormfacs(spec, panspec, normfac, normranges):
    """Check the normalization of files by plotting normalized and unnormalieze
    versions. Called from reduce.panspec"""
    name = spec.meta['NAME']
    oranges = utils.overlap_ranges(spec, panspec)
    if normranges is None:
        normranges = oranges
    else:
        normranges = mnp.rangeset_intersect(normranges, oranges)

    # construct bins from lower res in each normrange
    overbins = []
    for normrange in normranges:
        getbins = lambda s: utils.wbins(utils.keepranges(s, normrange))
        possible_bins = map(getbins, [spec, panspec])
        bins = min(possible_bins, key=lambda b: len(b))
        overbins.append(bins)
    overbins = np.vstack(overbins)

    # rebin each spec to the lowest res within the overlap
    def coarsebin(s):
        overspec = utils.rebin(s, overbins)
        return red.splice(s, overspec)

    spec, panspec = map(coarsebin, [spec, panspec])

    # plot the spectrum being normalized, highlighting the normranges
    plt.figure()
    #    ax = plt.axes()
    inranges, _ = utils.argoverlap(spec, normranges)
    specin = spec[inranges]
    specout = spec[~inranges]
    kwargs = {'err': False}
    line1 = specstep(specout, alpha=0.3, linestyle='--', **kwargs)
    kwargs['color'] = line1.get_color()
    line2 = specstep(specin, alpha=0.3, **kwargs)
    specin['flux'] *= normfac
    specout['flux'] *= normfac
    line3 = specstep(specout, linestyle='--', **kwargs)
    line4 = specstep(specin, **kwargs)
    plt.legend((line2, line4), ('original', 'normalized'))

    # plot panspec
    fullrange = spec['w0'][0], spec['w1'][-1]
    panspec = utils.keepranges(panspec, fullrange)
    #    ymax = np.max(panspec['flux'])
    piecespec(panspec, err=False)
    normed = panspec['normfac'] != 1.0
    if np.any(normed):
        normspec = panspec[normed]
        normspec['flux'] /= normspec['normfac']
        specstep(normspec, color='k', linestyle='--', alpha=0.5, err=False)


#    ax.set_ylim(-0.05 * ymax, 1.05 * ymax)
    plt.title('{} normalization'.format(name))
Example #4
0
def phxFit(star='gj832', ax=None):
    if ax is None: ax = plt.gca()
    ax.autoscale(axis='x', tight=True)
    ax.set_yscale('log')

    pan = io.readpan(star)
    bolo = utils.bolo_integral(star)
    xf = db.findfiles('ir', 'phx', star, fullpaths=True)
    phx = io.read(xf)[0]
    phx['flux'] *= pan['normfac'][-1]
    pan = pan[pan['instrument'] != pan['instrument'][-1]]
    fmin = np.min(pan['error'][pan['error'] > 0]) / bolo
    rng = [phx['w0'][0], 6000.]
    phx, pan = [
        utils.keepranges(spec, rng, ends='loose') for spec in [phx, pan]
    ]
    phx, pan = [utils.fancyBin(s, mindw=10.0) for s in [phx, pan]]
    pan['flux'][pan['flux'] < pan['error'] / 2.0] = np.nan
    pan['normflux'] = pan['flux'] / bolo
    phx['normflux'] = phx['flux'] / bolo
    ymax = 10**np.ceil(np.log10(np.max(phx['normflux'])))
    ymin = 10**np.floor(np.log10(fmin) - 3)
    ax.set_ylim(ymin, ymax)

    pline = plot.specstep(pan, ax=ax, color='k', err=False, key='normflux')
    xline = plot.specstep(phx, ax=ax, color='gray', err=False, key='normflux')
    ax.legend((pline, xline), ('$HST$ Data', 'PHOENIX Model'),
              loc='lower right')
Example #5
0
def splitSpec(spec, ax=None, wsplit=3000., scale_fac=50.):
    ax1 = plt.gca() if ax is None else ax

    ax2 = ax1.twinx()
    leftspec = utils.keepranges(spec, 0.0, wsplit)
    rightspec = utils.keepranges(spec, wsplit, np.inf)
    step = lambda spec, ax: plot.specstep(
        spec, err=False, ax=ax, color='k', autolabel=False)
    leftline = step(leftspec, ax1)
    rightline = step(rightspec, ax2)
    ax2.set_ylim(0.0, None)
    ax1.set_ylim(0.0, ax2.get_ylim()[1] / scale_fac)

    ax1.axvline(wsplit, ls=':')

    return (ax1, leftline), (ax2, rightline)
Example #6
0
def fuv_cont_stats(star):
    """
    Get stats on FUV continuum flux:
        - avg flux
        - avg flux error
        - raito of FUV continuum to total flux in the FUV assuming flat continuum
        - error on ratio
    """
    pan = io.readpan(star)
    cont = utils.keepranges(pan, rc.contbands, ends='exact')
    dw = cont['w1'] - cont['w0']

    # assume flat continuum
    # Fcont_avg = np.sum(cont['flux'] * dw)/np.sum(dw)
    # Fcont_avg_err = mnp.quadsum(cont['error'] * dw)/np.sum(dw)
    # dw_fuv = rc.fuv[1] - rc.fuv[0]
    # Fall_FUV, Fall_FUV_err = utils.flux_integral(pan, *rc.fuv)
    # ratio = Fcont_avg * dw_fuv / Fall_FUV
    # ratio_err = abs(ratio)*np.sqrt((Fall_FUV_err/Fall_FUV)**2 + (Fcont_avg_err/Fcont_avg)**2)

    # just do continuum actual measured, ignore "in-between" continuumFcont_avg
    Fcont  = np.sum(cont['flux'] * dw)
    Fcont_err = mnp.quadsum(cont['error'] * dw)
    Fall_FUV, Fall_FUV_err = utils.flux_integral(pan, cont['w0'][0], cont['w1'][-1])
    ratio = Fcont / Fall_FUV
    ratio_err = abs(ratio)*np.sqrt((Fall_FUV_err/Fall_FUV)**2 + (Fcont_err/Fcont)**2)
    return Fcont, Fcont_err, ratio, ratio_err
Example #7
0
def lya_splices(stars='all'):
    if stars == 'all':
        stars = rc.stars[:11]
        stars.remove('gj551')
    dw = 0.05
    for star in stars:
        pan = io.readpan(star)
        pan = utils.keepranges(pan, 1100, 1300)
        pan = utils.evenbin(pan, dw)

        sf = db.findfiles('u', star, 'coadd', 'cos_g130m')
        spec, = io.read(sf)
        spec = utils.evenbin(spec, dw)

        lf = db.findfiles('u', star, 'mod', 'lya')
        lya, = io.read(lf)

        plt.figure()
        [ss(s, err=False) for s in [pan, spec, lya]]
        plt.xlim(1210, 1222)
        up, _ = utils.flux_integral(spec, 1217, 1220)
        plt.ylim(0, up * 4)
        plt.legend(['pan', 'cos', 'lya'], loc='best')
        plt.savefig(
            os.path.join(rc.scratchpath, 'lya splices',
                         '{} linear.pdf'.format(star)))

        mx = spec['flux'].max()
        plt.ylim(mx / 1e7, mx)
        plt.yscale('log')
        plt.savefig(
            os.path.join(rc.scratchpath, 'lya splices',
                         '{} log.pdf'.format(star)))
Example #8
0
 def plotspec(version, ax):
     f, = db.findfiles(rc.hlsppath, star, 'broadband', version, res)
     spec, = io.read(f)
     spec = utils.keepranges(spec, 0, maxw)
     spec = utils.evenbin(spec, binto)
     plt.axes(ax)
     piecespec(spec)
     plt.text(0.05, 0.9, version, transform=ax.transAxes)
Example #9
0
def vetpanspec(pan_or_star, constant_dw=None, redlim=8000.0):
    """Plot unnormalized components of the panspec with the panspec to see that
    all choices were good. Phoenix spectrum is excluded because it is too big."""
    if type(pan_or_star) is str:
        star = pan_or_star
        panspec = io.read(db.panpath(star))[0]
    else:
        panspec = pan_or_star
        star = panspec.meta['STAR']
    files = db.panfiles(star)[0]
    panspec = utils.keepranges(panspec, 0.0, redlim)

    if constant_dw is None:
        plotfun = specstep
    else:
        panspec = utils.evenbin(panspec, constant_dw)
        wbins = utils.wbins(panspec)

        def plotfun(spec, **kwargs):
            s = utils.rebin(spec, wbins)
            return specstep(s, **kwargs)

    for f in files:
        if 'phx' in f: continue
        specs = io.read(f)
        for spec in specs:
            p = plotfun(spec, err=True)[0]
            x = (spec['w0'][0] + spec['w0'][-1]) / 2.0
            y = np.mean(spec['flux'])
            inst = db.parse_instrument(spec.meta['NAME'])
            plt.text(x,
                     y,
                     inst,
                     bbox={
                         'facecolor': 'w',
                         'alpha': 0.5,
                         'color': p.get_color()
                     },
                     ha='center',
                     va='center')
    plotfun(panspec, color='k', alpha=0.5)
    ymax = np.max(utils.keepranges(panspec, 3000.0, 8000.0)['flux'])
    plt.gca().set_ylim(-0.01 * ymax, 1.05 * ymax)
    plt.draw()
Example #10
0
def stackpans(range=[1310, 1350],
              keeprange=[1100, 2000],
              xlim=None,
              norm=True,
              offfac=1.0):
    if xlim is None: xlim = keeprange
    pans = []
    for star in rc.observed:
        p = io.read(db.panpath(star))[0]
        pans.append(utils.keepranges(p, *keeprange))
    stackspecs(pans, range, norm=norm, offfac=offfac, xlim=xlim)
Example #11
0
def fuv_cont_spec(star):
    """Get just the continuum flux regions of a star's panspec."""
    spec = io.readpan(star)
    return utils.keepranges(spec, rc.contbands, ends='exact')