Exemple #1
0
def kepdeltapix(infile,
                nexp,
                columns,
                rows,
                fluxes,
                prfdir,
                interpolation,
                tolerance,
                fittype,
                imscale,
                colmap,
                verbose,
                logfile,
                status,
                cmdLine=False):

    # input arguments

    status = 0
    seterr(all="ignore")

    # log the call

    hashline = '----------------------------------------------------------------------------'
    kepmsg.log(logfile, hashline, verbose)
    call = 'KEPDELTAPIX -- '
    call += 'infile=' + infile + ' '
    call += 'nexp=' + str(nexp) + ' '
    call += 'columns=' + columns + ' '
    call += 'rows=' + rows + ' '
    call += 'fluxes=' + fluxes + ' '
    call += 'prfdir=' + prfdir + ' '
    call += 'interpolation=' + interpolation + ' '
    call += 'tolerance=' + str(tolerance) + ' '
    call += 'fittype=' + str(fittype) + ' '
    call += 'imscale=' + imscale + ' '
    call += 'colmap=' + colmap + ' '
    chatter = 'n'
    if (verbose): chatter = 'y'
    call += 'verbose=' + chatter + ' '
    call += 'logfile=' + logfile
    kepmsg.log(logfile, call + '\n', verbose)

    # test log file

    logfile = kepmsg.test(logfile)

    # start time

    kepmsg.clock('KEPDELTAPIX started at', logfile, verbose)

    # reference color map

    if colmap == 'browse':
        status = cmap_plot(cmdLine)

# open TPF FITS file

    if status == 0:
        try:
            kepid, channel, skygroup, module, output, quarter, season, \
                ra, dec, column, row, kepmag, xdim, ydim, barytime, status = \
                kepio.readTPF(infile,'TIME',logfile,verbose)
        except:
            message = 'ERROR -- KEPDELTAPIX: is %s a Target Pixel File? ' % infile
            status = kepmsg.err(logfile, message, verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, tcorr, status = \
            kepio.readTPF(infile,'TIMECORR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, cadno, status = \
            kepio.readTPF(infile,'CADENCENO',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, fluxpixels, status = \
            kepio.readTPF(infile,'FLUX',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, errpixels, status = \
            kepio.readTPF(infile,'FLUX_ERR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, qual, status = \
            kepio.readTPF(infile,'QUALITY',logfile,verbose)

# print target data

    if status == 0 and verbose:
        print ''
        print '      KepID:  %s' % kepid
        print ' RA (J2000):  %s' % ra
        print 'Dec (J2000): %s' % dec
        print '     KepMag:  %s' % kepmag
        print '   SkyGroup:    %2s' % skygroup
        print '     Season:    %2s' % str(season)
        print '    Channel:    %2s' % channel
        print '     Module:    %2s' % module
        print '     Output:     %1s' % output
        print ''

# determine suitable PRF calibration file

    if status == 0:
        if int(module) < 10:
            prefix = 'kplr0'
        else:
            prefix = 'kplr'
        prfglob = prfdir + '/' + prefix + str(module) + '.' + str(
            output) + '*' + '_prf.fits'
        try:
            prffile = glob.glob(prfglob)[0]
        except:
            message = 'ERROR -- KEPDELTAPIX: No PRF file found in ' + prfdir
            status = kepmsg.err(logfile, message, verbose)

# read PRF images

    if status == 0:
        prfn = [0, 0, 0, 0, 0]
        crpix1p = numpy.zeros((5), dtype='float32')
        crpix2p = numpy.zeros((5), dtype='float32')
        crval1p = numpy.zeros((5), dtype='float32')
        crval2p = numpy.zeros((5), dtype='float32')
        cdelt1p = numpy.zeros((5), dtype='float32')
        cdelt2p = numpy.zeros((5), dtype='float32')
        for i in range(5):
            prfn[i], crpix1p[i], crpix2p[i], crval1p[i], crval2p[i], cdelt1p[i], cdelt2p[i], status \
                = kepio.readPRFimage(prffile,i+1,logfile,verbose)

# choose rows in the TPF table at random

    if status == 0:
        i = 0
        rownum = []
        while i < nexp:
            work = int(random.random() * len(barytime))
            if numpy.isfinite(barytime[work]) and numpy.isfinite(
                    fluxpixels[work, ydim * xdim / 2]):
                rownum.append(work)
                i += 1

# construct input pixel image

    if status == 0:
        fscat = numpy.empty((len(fluxes), nexp), dtype='float32')
        xscat = numpy.empty((len(columns), nexp), dtype='float32')
        yscat = numpy.empty((len(rows), nexp), dtype='float32')
        for irow in range(nexp):
            flux = fluxpixels[rownum[irow], :]

            # image scale and intensity limits of pixel data

            if status == 0:
                flux_pl, zminfl, zmaxfl = kepplot.intScale1D(flux, imscale)
                n = 0
                imgflux_pl = empty((ydim, xdim))
                for i in range(ydim):
                    for j in range(xdim):
                        imgflux_pl[i, j] = flux_pl[n]
                        n += 1

# fit PRF model to pixel data

            if status == 0:
                start = time.time()
                f, y, x, prfMod, prfFit, prfRes = kepfit.fitMultiPRF(
                    flux, ydim, xdim, column, row, prfn, crval1p, crval2p,
                    cdelt1p, cdelt2p, interpolation, tolerance, fluxes,
                    columns, rows, fittype, verbose, logfile)
                if verbose:
                    print '\nConvergence time = %.1fs' % (time.time() - start)

# best fit parameters

            if status == 0:
                for i in range(len(f)):
                    fscat[i, irow] = f[i]
                    xscat[i, irow] = x[i]
                    yscat[i, irow] = y[i]

# replace starting guess with previous fit parameters

            if status == 0:
                fluxes = copy(f)
                columns = copy(x)
                rows = copy(y)

# mean and rms results

    if status == 0:
        fmean = []
        fsig = []
        xmean = []
        xsig = []
        ymean = []
        ysig = []
        for i in range(len(f)):
            fmean.append(numpy.mean(fscat[i, :]))
            xmean.append(numpy.mean(xscat[i, :]))
            ymean.append(numpy.mean(yscat[i, :]))
            fsig.append(numpy.std(fscat[i, :]))
            xsig.append(numpy.std(xscat[i, :]))
            ysig.append(numpy.std(yscat[i, :]))
            txt = 'Flux = %10.2f e-/s ' % fmean[-1]
            txt += 'X = %7.4f +/- %6.4f pix ' % (xmean[-1], xsig[i])
            txt += 'Y = %7.4f +/- %6.4f pix' % (ymean[-1], ysig[i])
            kepmsg.log(logfile, txt, True)

# output results for kepprfphot

    if status == 0:
        txt1 = 'columns=0.0'
        txt2 = '   rows=0.0'
        for i in range(1, len(f)):
            txt1 += ',%.4f' % (xmean[i] - xmean[0])
            txt2 += ',%.4f' % (ymean[i] - ymean[0])
        kepmsg.log(logfile, '\nkepprfphot input fields:', True)
        kepmsg.log(logfile, txt1, True)
        kepmsg.log(logfile, txt2, True)

# image scale and intensity limits for PRF model image

    if status == 0:
        imgprf_pl, zminpr, zmaxpr = kepplot.intScale2D(prfMod, imscale)

# image scale and intensity limits for PRF fit image

    if status == 0:
        imgfit_pl, zminfi, zmaxfi = kepplot.intScale2D(prfFit, imscale)

# image scale and intensity limits for data - fit residual

    if status == 0:
        imgres_pl, zminre, zmaxre = kepplot.intScale2D(prfRes, imscale)

# plot style

    if status == 0:
        try:
            params = {
                'backend': 'png',
                'axes.linewidth': 2.5,
                'axes.labelsize': 24,
                'axes.font': 'sans-serif',
                'axes.fontweight': 'bold',
                'text.fontsize': 12,
                'legend.fontsize': 12,
                'xtick.labelsize': 10,
                'ytick.labelsize': 10
            }
            pylab.rcParams.update(params)
        except:
            pass
        pylab.figure(figsize=[10, 10])
        pylab.clf()
        plotimage(imgflux_pl, zminfl, zmaxfl, 1, row, column, xdim, ydim, 0.06,
                  0.52, 'flux', colmap)
        plotimage(imgfit_pl, zminfl, zmaxfl, 3, row, column, xdim, ydim, 0.06,
                  0.06, 'fit', colmap)
        plotimage(imgres_pl, zminfl, zmaxfl, 4, row, column, xdim, ydim, 0.52,
                  0.06, 'residual', colmap)
        plotimage(imgprf_pl, zminpr, zmaxpr * 0.9, 2, row, column, xdim, ydim,
                  0.52, 0.52, 'model', colmap)
        for i in range(len(f)):
            pylab.plot(xscat[i, :], yscat[i, :], 'o', color='k')

# Plot creep of target position over time, relative to the central source

#	barytime0 = float(int(barytime[0] / 100) * 100.0)
#	barytime -= barytime0
#        xlab = 'BJD $-$ %d' % barytime0
#	xmin = numpy.nanmin(barytime)
#	xmax = numpy.nanmax(barytime)
#	y1min = numpy.nanmin(data)
#	y1max = numpy.nanmax(data)
#	xr = xmax - xmin
#	yr = ymax - ymin
#        barytime = insert(barytime,[0],[barytime[0]])
#        barytime = append(barytime,[barytime[-1]])
#        data = insert(data,[0],[0.0])
#        data = append(data,0.0)
#
#        pylab.figure(2,figsize=[10,10])
#        pylab.clf()
#	ax = pylab.subplot(211)
#	pylab.subplots_adjust(0.1,0.5,0.88,0.42)
#        pylab.gca().xaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
#        pylab.gca().yaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
#        labels = ax.get_yticklabels()
#        setp(labels, 'rotation', 90, fontsize=ticksize)
#        for i in range(1,len(f)):
#            pylab.plot(rownum,xscat[i,:]-xscat[0,:],'o')
#        pylab.ylabel('$\Delta$Columns', {'color' : 'k'})
#	ax = pylab.subplot(211)
#	pylab.subplots_adjust(0.1,0.1,0.88,0.42)
#        pylab.gca().xaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
#        pylab.gca().yaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
#        labels = ax.get_yticklabels()
#        setp(labels, 'rotation', 90, fontsize=ticksize)
#        for i in range(1,len(f)):
#            pylab.plot(rownum,yscat[i,:]-yscat[0,:],'o')
#	pylab.xlim(xmin-xr*0.01,xmax+xr*0.01)
#	if ymin-yr*0.01 <= 0.0 or fullrange:
#            pylab.ylim(1.0e-10,ymax+yr*0.01)
#	else:
#            pylab.ylim(ymin-yr*0.01,ymax+yr*0.01)
#        pylab.ylabel('$\Delta$Rows', {'color' : 'k'})
#        pylab.xlabel(xlab, {'color' : 'k'})

# render plot

    if status == 0:
        if cmdLine:
            pylab.show(block=True)
        else:
            pylab.ion()
            pylab.plot([])
            pylab.ioff()

# stop time

    kepmsg.clock('\nKEPDELTAPIX ended at', logfile, verbose)

    return
Exemple #2
0
def kepmask(infile,mfile,pfile,tabrow,imin,imax,iscale,cmap,verbose,logfile,status,cLine=False): 

    global pimg, zscale, zmin, zmax, xmin, xmax, ymin, ymax, quarter
    global pxdim, pydim, kepmag, skygroup, season, channel
    global module, output, row, column, maskfile, plotfile
    global pkepid, pkepmag, pra, pdec, colmap, cmdLine

# input arguments

    status = 0
    numpy.seterr(all="ignore") 
    zmin = imin; zmax = imax; zscale = iscale; colmap = cmap
    maskfile = mfile; plotfile = pfile
    cmdLine = cLine

# log the call 

    hashline = '----------------------------------------------------------------------------'
    kepmsg.log(logfile,hashline,verbose)
    call = 'KEPMASK -- '
    call += 'infile='+infile+' '
    call += 'maskfile='+mfile+' '
    call += 'plotfile='+pfile+' '
    call += 'tabrow='+str(tabrow)+' '
    call += 'imin='+str(imin)+' '
    call += 'imax='+str(imax)+' '
    call += 'iscale='+str(iscale)+' '
    call += 'cmap='+str(cmap)+' '
    chatter = 'n'
    if (verbose): chatter = 'y'
    call += 'verbose='+chatter+' '
    call += 'logfile='+logfile
    kepmsg.log(logfile,call+'\n',verbose)

# start time

    kepmsg.clock('KEPMASK started at',logfile,verbose)

# reference color map

    if cmap == 'browse':
        status = cmap_plot()

# open TPF FITS file and check tabrow exists

    if status == 0:
        tpf, status = kepio.openfits(infile,'readonly',logfile,verbose)
    if status == 0:
        try:
            naxis2 = tpf['TARGETTABLES'].header['NAXIS2']
        except:
            txt = 'ERROR -- KEPMASK: No NAXIS2 keyword in ' + infile + '[TARGETTABLES]'
            status = kepmsg.err(logfile,txt,True)
    if status == 0 and tabrow > naxis2:
        txt = 'ERROR -- KEPMASK: tabrow is too large. There are ' + str(naxis2) + ' rows in the table.'
        status = kepmsg.err(logfile,txt,True)
    if status == 0:
        status = kepio.closefits(tpf,logfile,verbose)

# read TPF data pixel image

    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, pixels, status = \
            kepio.readTPF(infile,'FLUX',logfile,verbose)
        img = pixels[tabrow]
        pkepid = copy(kepid)
        pra = copy(ra)
        pdec = copy(dec)
        pkepmag = copy(kepmag)
        pxdim = copy(xdim)
        pydim = copy(ydim)
        pimg = copy(img)

# print target data

    if status == 0:
        print('')
        print('      KepID:  %s' % kepid)
        print(' RA (J2000):  %s' % ra)
        print('Dec (J2000):   %s' % dec)
        print('     KepMag:   %s' % kepmag)
        print('   SkyGroup:   %2s' % skygroup)
        print('     Season:   %2s' % str(season))
        print('    Channel:   %2s' % channel)
        print('     Module:   %2s' % module)
        print('     Output:    %1s' % output)
        print('')

# subimage of channel for plot

    if status == 0:
        ymin = copy(row)
        ymax = ymin + ydim
        xmin = copy(column)
        xmax = xmin + xdim

# intensity scale

    if status == 0:
        pimg, imin, imax = kepplot.intScale1D(pimg,zscale)
        if zmin and zmax and 'log' in zscale:
            zmin = log10(zmin)
            zmax = log10(zmax)
        elif zmin and zmax and 'sq' in zscale:
            zmin = sqrt(zmin)
            zmax = sqrt(zmax)
        elif zmin and zmax and 'li' in zscale:
            zmin *= 1.0
            zmax *= 1.0
        else:
            zmin = copy(imin)
            zmax = copy(imax)


#        nstat = 2; pixels = []
#        work = array(sort(img),dtype=float32)
#        for i in range(len(work)):
#            if 'nan' not in str(work[i]):
#                pixels.append(work[i])
#        pixels = array(pixels,dtype=float32)
#        if int(float(len(pixels)) / 10 + 0.5) > nstat:
#            nstat = int(float(len(pixels)) / 10 + 0.5)
#        if not zmin:
#            zmin = median(pixels[:nstat])
#        if not zmax:
#            zmax = median(pixels[-nstat:])
#        if 'log' in zscale:
#            pimg = log10(pimg)
#        if 'sq' in zscale:
#            pimg = sqrt(pimg)

# plot limits

        ymin = float(ymin) - 0.5
        ymax = float(ymax) - 0.5
        xmin = float(xmin) - 0.5
        xmax = float(xmax) - 0.5

# plot style

        try:
            params = {'backend': 'png',
                      'axes.linewidth': 2.5,
                      'axes.labelsize': 24,
                      'axes.font': 'sans-serif',
                      'axes.fontweight' : 'bold',
                      'text.fontsize': 12,
                      'legend.fontsize': 12,
                      'xtick.labelsize': 14,
                      'ytick.labelsize': 14}
            pylab.rcParams.update(params)
        except:
            pass

    if status == 0:
        pylab.figure(figsize=[10,7])
        plotimage(cmdLine)

    return
Exemple #3
0
def kepmask(infile,
            mfile,
            pfile,
            tabrow,
            imin,
            imax,
            iscale,
            cmap,
            verbose,
            logfile,
            status,
            cLine=False):

    global pimg, zscale, zmin, zmax, xmin, xmax, ymin, ymax, quarter
    global pxdim, pydim, kepmag, skygroup, season, channel
    global module, output, row, column, maskfile, plotfile
    global pkepid, pkepmag, pra, pdec, colmap, cmdLine

    # input arguments

    status = 0
    numpy.seterr(all="ignore")
    zmin = imin
    zmax = imax
    zscale = iscale
    colmap = cmap
    maskfile = mfile
    plotfile = pfile
    cmdLine = cLine

    # log the call

    hashline = '----------------------------------------------------------------------------'
    kepmsg.log(logfile, hashline, verbose)
    call = 'KEPMASK -- '
    call += 'infile=' + infile + ' '
    call += 'maskfile=' + mfile + ' '
    call += 'plotfile=' + pfile + ' '
    call += 'tabrow=' + str(tabrow) + ' '
    call += 'imin=' + str(imin) + ' '
    call += 'imax=' + str(imax) + ' '
    call += 'iscale=' + str(iscale) + ' '
    call += 'cmap=' + str(cmap) + ' '
    chatter = 'n'
    if (verbose): chatter = 'y'
    call += 'verbose=' + chatter + ' '
    call += 'logfile=' + logfile
    kepmsg.log(logfile, call + '\n', verbose)

    # start time

    kepmsg.clock('KEPMASK started at', logfile, verbose)

    # reference color map

    if cmap == 'browse':
        status = cmap_plot()

# open TPF FITS file and check tabrow exists

    if status == 0:
        tpf, status = kepio.openfits(infile, 'readonly', logfile, verbose)
    if status == 0:
        try:
            naxis2 = tpf['TARGETTABLES'].header['NAXIS2']
        except:
            txt = 'ERROR -- KEPMASK: No NAXIS2 keyword in ' + infile + '[TARGETTABLES]'
            status = kepmsg.err(logfile, txt, True)
    if status == 0 and tabrow > naxis2:
        txt = 'ERROR -- KEPMASK: tabrow is too large. There are ' + str(
            naxis2) + ' rows in the table.'
        status = kepmsg.err(logfile, txt, True)
    if status == 0:
        status = kepio.closefits(tpf, logfile, verbose)

# read TPF data pixel image

    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, pixels, status = \
            kepio.readTPF(infile,'FLUX',logfile,verbose)
        img = pixels[tabrow]
        pkepid = copy(kepid)
        pra = copy(ra)
        pdec = copy(dec)
        pkepmag = copy(kepmag)
        pxdim = copy(xdim)
        pydim = copy(ydim)
        pimg = copy(img)

# print target data

    if status == 0:
        print ''
        print '      KepID:  %s' % kepid
        print ' RA (J2000):  %s' % ra
        print 'Dec (J2000):   %s' % dec
        print '     KepMag:   %s' % kepmag
        print '   SkyGroup:   %2s' % skygroup
        print '     Season:   %2s' % str(season)
        print '    Channel:   %2s' % channel
        print '     Module:   %2s' % module
        print '     Output:    %1s' % output
        print ''

# subimage of channel for plot

    if status == 0:
        ymin = copy(row)
        ymax = ymin + ydim
        xmin = copy(column)
        xmax = xmin + xdim

# intensity scale

    if status == 0:
        pimg, imin, imax = kepplot.intScale1D(pimg, zscale)
        if zmin and zmax and 'log' in zscale:
            zmin = log10(zmin)
            zmax = log10(zmax)
        elif zmin and zmax and 'sq' in zscale:
            zmin = sqrt(zmin)
            zmax = sqrt(zmax)
        elif zmin and zmax and 'li' in zscale:
            zmin *= 1.0
            zmax *= 1.0
        else:
            zmin = copy(imin)
            zmax = copy(imax)

#        nstat = 2; pixels = []
#        work = array(sort(img),dtype=float32)
#        for i in range(len(work)):
#            if 'nan' not in str(work[i]):
#                pixels.append(work[i])
#        pixels = array(pixels,dtype=float32)
#        if int(float(len(pixels)) / 10 + 0.5) > nstat:
#            nstat = int(float(len(pixels)) / 10 + 0.5)
#        if not zmin:
#            zmin = median(pixels[:nstat])
#        if not zmax:
#            zmax = median(pixels[-nstat:])
#        if 'log' in zscale:
#            pimg = log10(pimg)
#        if 'sq' in zscale:
#            pimg = sqrt(pimg)

# plot limits

        ymin = float(ymin) - 0.5
        ymax = float(ymax) - 0.5
        xmin = float(xmin) - 0.5
        xmax = float(xmax) - 0.5

        # plot style

        try:
            params = {
                'backend': 'png',
                'axes.linewidth': 2.5,
                'axes.labelsize': 24,
                'axes.font': 'sans-serif',
                'axes.fontweight': 'bold',
                'text.fontsize': 12,
                'legend.fontsize': 12,
                'xtick.labelsize': 14,
                'ytick.labelsize': 14
            }
            pylab.rcParams.update(params)
        except:
            pass

    if status == 0:
        pylab.figure(figsize=[10, 7])
        plotimage(cmdLine)

    return
Exemple #4
0
def kepfield(infile,plotfile,rownum,imscale,colmap,lcolor,srctab,verbose,logfile,status,cmdLine=False): 

# input arguments

    status = 0
    seterr(all="ignore") 

# log the call 

    hashline = '----------------------------------------------------------------------------'
    kepmsg.log(logfile,hashline,verbose)
    call = 'KEPFIELD -- '
    call += 'infile='+infile+' '
    call += 'plotfile='+plotfile+' '
    call += 'rownum='+str(rownum)+' '
    call += 'imscale='+imscale+' '
    call += 'colmap='+colmap+' '
    call += 'lcolor='+lcolor+' '
    srct = 'n'
    if (srctab): srct = 'y'
    call += 'srctab='+srct+' '
    chatter = 'n'
    if (verbose): chatter = 'y'
    call += 'verbose='+chatter+' '
    call += 'logfile='+logfile
    kepmsg.log(logfile,call+'\n',verbose)

# start time

    kepmsg.clock('KEPFIELD started at',logfile,verbose)

# test log file

    logfile = kepmsg.test(logfile)

# reference color map

    if colmap == 'browse':
        status = cmap_plot(cmdLine)

# open TPF FITS file

    if status == 0:
        try:
            kepid, channel, skygroup, module, output, quarter, season, \
                ra, dec, column, row, kepmag, xdim, ydim, barytime, status = \
                kepio.readTPF(infile,'TIME',logfile,verbose)
        except:
            message = 'ERROR -- KEPFIELD: is %s a Target Pixel File? ' % infile
            status = kepmsg.err(logfile,message,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, tcorr, status = \
            kepio.readTPF(infile,'TIMECORR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, cadno, status = \
            kepio.readTPF(infile,'CADENCENO',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, fluxpixels, status = \
            kepio.readTPF(infile,'FLUX',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, errpixels, status = \
            kepio.readTPF(infile,'FLUX_ERR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, qual, status = \
            kepio.readTPF(infile,'QUALITY',logfile,verbose)

# read mask defintion data from TPF file

    if status == 0:
        maskimg, pixcoord1, pixcoord2, status = kepio.readMaskDefinition(infile,logfile,verbose)

# observed or simulated data?
        
    if status == 0:
        coa = False
        instr = pyfits.open(infile,mode='readonly',memmap=True)
        filever, status = kepkey.get(infile,instr[0],'FILEVER',logfile,verbose)
        if filever == 'COA': coa = True

# print target data

    if status == 0 and verbose:
        print('')
        print('      KepID: %s' % kepid)
        print('        BJD: %.2f' % (barytime[rownum-1] + 2454833.0))
        print(' RA (J2000): %s' % ra)
        print('Dec (J2000):  %s' % dec)
        print('     KepMag:  %s' % kepmag)
        print('   SkyGroup:   %2s' % skygroup)
        print('     Season:   %2s' % str(season))
        print('    Channel:   %2s' % channel)
        print('     Module:   %2s' % module)
        print('     Output:    %1s' % output)
        print('')

# is this a good row with finite timestamp and pixels?

    if status == 0:
        if not numpy.isfinite(barytime[rownum-1]) or not numpy.nansum(fluxpixels[rownum-1,:]):
            message = 'ERROR -- KEPFIELD: Row ' + str(rownum) + ' is a bad quality timestamp'
            status = kepmsg.err(logfile,message,verbose)

# construct input pixel image

    if status == 0:
        flux = fluxpixels[rownum-1,:]

# image scale and intensity limits of pixel data

    if status == 0:
        flux_pl, zminfl, zmaxfl = kepplot.intScale1D(flux,imscale)
        n = 0
        imgflux_pl = empty((ydim+2,xdim+2))
        for i in range(ydim+2):
            for j in range(xdim+2):
                imgflux_pl[i,j] = numpy.nan
        for i in range(ydim):
            for j in range(xdim):
                imgflux_pl[i+1,j+1] = flux_pl[n]
                n += 1
        
# cone search around target coordinates using the MAST target search form 

    if status == 0:
        dr = max([ydim+2,xdim+2]) * 4.0
        kepid,ra,dec,kepmag = MASTRADec(float(ra),float(dec),dr,srctab)

# convert celestial coordinates to detector coordinates

    if status == 0:
        sx = numpy.array([])
        sy = numpy.array([])
        inf, status = kepio.openfits(infile,'readonly',logfile,verbose)
        try:
            crpix1, crpix2, crval1, crval2, cdelt1, cdelt2, pc, status = \
                kepkey.getWCSs(infile,inf['APERTURE'],logfile,verbose) 
            crpix1p, crpix2p, crval1p, crval2p, cdelt1p, cdelt2p, status = \
                kepkey.getWCSp(infile,inf['APERTURE'],logfile,verbose)     
            for i in range(len(kepid)):
                dra = (ra[i] - crval1) * math.cos(math.radians(dec[i])) / cdelt1
                ddec = (dec[i] - crval2) / cdelt2
                if coa:
                    sx = numpy.append(sx,-(pc[0,0] * dra + pc[0,1] * ddec) + crpix1 + crval1p - 1.0)
                else:
                    sx = numpy.append(sx,pc[0,0] * dra + pc[0,1] * ddec + crpix1 + crval1p - 1.0) 
                sy = numpy.append(sy,pc[1,0] * dra + pc[1,1] * ddec + crpix2 + crval2p - 1.0)
        except:
            message = 'ERROR -- KEPFIELD: Non-compliant WCS information within file %s' % infile
            status = kepmsg.err(logfile,message,verbose)    

# plot style

    if status == 0:
        try:
            params = {'backend': 'png',
                      'axes.linewidth': 2.5,
                      'axes.labelsize': 48,
                      'axes.font': 'sans-serif',
                      'axes.fontweight' : 'bold',
                      'text.fontsize': 12,
                      'legend.fontsize': 12,
                      'xtick.labelsize': 20,
                      'ytick.labelsize': 20}
            pylab.rcParams.update(params)
        except:
            pass
        pylab.figure(figsize=[10,10])
        pylab.clf()
            
# pixel limits of the subimage

    if status == 0:
        ymin = copy(float(row))
        ymax = ymin + ydim
        xmin = copy(float(column))
        xmax = xmin + xdim

# plot limits for flux image

    if status == 0:
        ymin = float(ymin) - 1.5
        ymax = float(ymax) + 0.5
        xmin = float(xmin) - 1.5
        xmax = float(xmax) + 0.5

# plot the image window
        
    if status == 0:
        ax = pylab.axes([0.1,0.11,0.88,0.88])
        pylab.imshow(imgflux_pl,aspect='auto',interpolation='nearest',origin='lower',
                     vmin=zminfl,vmax=zmaxfl,extent=(xmin,xmax,ymin,ymax),cmap=colmap)
        pylab.gca().set_autoscale_on(False)
        labels = ax.get_yticklabels()
        setp(labels, 'rotation', 90)
        pylab.gca().xaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
        pylab.gca().yaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
        pylab.xlabel('Pixel Column Number', {'color' : 'k'})
        pylab.ylabel('Pixel Row Number', {'color' : 'k'})

# plot mask borders

    if status == 0:
        kepplot.borders(maskimg,xdim,ydim,pixcoord1,pixcoord2,1,lcolor,'--',0.5)

# plot aperture borders

    if status == 0:
        kepplot.borders(maskimg,xdim,ydim,pixcoord1,pixcoord2,2,lcolor,'-',4.0)

# list sources

    if status == 0:
        print('Column    Row  RA J2000 Dec J2000    Kp    Kepler ID')
        print('----------------------------------------------------')
        for i in range(len(sx)-1,-1,-1):
            if sx[i] >= xmin and sx[i] < xmax and sy[i] >= ymin and sy[i] < ymax:
                if kepid[i] != 0 and kepmag[i] != 0.0:
                    print('%6.1f %6.1f %9.5f  %8.5f %5.2f KIC %d' % \
                        (float(sx[i]),float(sy[i]),float(ra[i]),float(dec[i]),float(kepmag[i]),int(kepid[i])))
                elif kepid[i] != 0 and kepmag[i] == 0.0:
                    print('%6.1f %6.1f %9.5f  %8.5f       KIC %d' % \
                        (float(sx[i]),float(sy[i]),float(ra[i]),float(dec[i]),int(kepid[i])))
                else:
                    print('%6.1f %6.1f %9.5f  %8.5f' % (float(sx[i]),float(sy[i]),float(ra[i]),float(dec[i])))

# plot sources

    if status == 0:
        for i in range(len(sx)-1,-1,-1):
            if kepid[i] != 0 and kepmag[i] != 0.0:
                size = max(array([80.0,80.0 + (2.5**(18.0 - max(12.0,float(kepmag[i])))) * 250.0]))
                pylab.scatter(sx[i],sy[i],s=size,facecolors='g',edgecolors='k',alpha=0.4)
            else:
                pylab.scatter(sx[i],sy[i],s=80,facecolors='r',edgecolors='k',alpha=0.4)

# render plot

    if status == 0 and len(plotfile) > 0 and plotfile.lower() != 'none':
        pylab.savefig(plotfile)
    if status == 0:
        if cmdLine: 
            pylab.show(block=True)
        else: 
            pylab.ion()
            pylab.plot([])
            pylab.ioff()
	
# stop time

    kepmsg.clock('\nKEPFIELD ended at',logfile,verbose)

    return
Exemple #5
0
def kepdiffim(infile,
              outfile,
              plotfile,
              imscale,
              colmap,
              filter,
              function,
              cutoff,
              clobber,
              verbose,
              logfile,
              status,
              cmdLine=False):

    # input arguments

    status = 0
    seterr(all="ignore")

    # log the call

    hashline = '----------------------------------------------------------------------------'
    kepmsg.log(logfile, hashline, verbose)
    call = 'KEPDIFFIM -- '
    call += 'infile=' + infile + ' '
    call += 'outfile=' + outfile + ' '
    call += 'plotfile=' + plotfile + ' '
    call += 'imscale=' + imscale + ' '
    call += 'colmap=' + colmap + ' '
    filt = 'n'
    if (filter): filt = 'y'
    call += 'filter=' + filt + ' '
    call += 'function=' + function + ' '
    call += 'cutoff=' + str(cutoff) + ' '
    overwrite = 'n'
    if (clobber): overwrite = 'y'
    call += 'clobber=' + overwrite + ' '
    chatter = 'n'
    if (verbose): chatter = 'y'
    call += 'verbose=' + chatter + ' '
    call += 'logfile=' + logfile
    kepmsg.log(logfile, call + '\n', verbose)

    # start time

    kepmsg.clock('KEPDIFFIM started at: ', logfile, verbose)

    # test log file

    logfile = kepmsg.test(logfile)

    # clobber output file

    if clobber: status = kepio.clobber(outfile, logfile, verbose)
    if kepio.fileexists(outfile):
        message = 'ERROR -- KEPDIFFIM: ' + outfile + ' exists. Use --clobber'
        status = kepmsg.err(logfile, message, verbose)

# reference color map

    if colmap == 'browse':
        status = cmap_plot()

# open TPF FITS file

    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, barytime, status = \
            kepio.readTPF(infile,'TIME',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, tcorr, status = \
            kepio.readTPF(infile,'TIMECORR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, cadno, status = \
            kepio.readTPF(infile,'CADENCENO',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, fluxpixels, status = \
            kepio.readTPF(infile,'FLUX',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, errpixels, status = \
            kepio.readTPF(infile,'FLUX_ERR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, qual, status = \
            kepio.readTPF(infile,'QUALITY',logfile,verbose)

# read mask defintion data from TPF file

    if status == 0:
        maskimg, pixcoord1, pixcoord2, status = kepio.readMaskDefinition(
            infile, logfile, verbose)

# print target data

    if status == 0:
        print('')
        print('      KepID:  %s' % kepid)
        print(' RA (J2000):  %s' % ra)
        print('Dec (J2000): %s' % dec)
        print('     KepMag:  %s' % kepmag)
        print('   SkyGroup:    %2s' % skygroup)
        print('     Season:    %2s' % str(season))
        print('    Channel:    %2s' % channel)
        print('     Module:    %2s' % module)
        print('     Output:     %1s' % output)
        print('')

# how many quality = 0 rows?

    if status == 0:
        npts = 0
        nrows = len(fluxpixels)
        for i in range(nrows):
            if qual[i] == 0 and \
                    numpy.isfinite(barytime[i]) and \
                    numpy.isfinite(fluxpixels[i,ydim*xdim/2]):
                npts += 1
        time = empty((npts))
        timecorr = empty((npts))
        cadenceno = empty((npts))
        quality = empty((npts))
        pixseries = empty((ydim * xdim, npts))
        errseries = empty((ydim * xdim, npts))

# construct output light curves

    if status == 0:
        np = 0
        for i in range(ydim * xdim):
            npts = 0
            for k in range(nrows):
                if qual[k] == 0 and \
                        numpy.isfinite(barytime[k]) and \
                        numpy.isfinite(fluxpixels[k,ydim*xdim/2]):
                    time[npts] = barytime[k]
                    timecorr[npts] = tcorr[k]
                    cadenceno[npts] = cadno[k]
                    quality[npts] = qual[k]
                    pixseries[i, npts] = fluxpixels[k, np]
                    errseries[i, npts] = errpixels[k, np]
                    npts += 1
            np += 1

# define data sampling

    if status == 0 and filter:
        tpf, status = kepio.openfits(infile, 'readonly', logfile, verbose)
    if status == 0 and filter:
        cadence, status = kepkey.cadence(tpf[1], infile, logfile, verbose)
        tr = 1.0 / (cadence / 86400)
        timescale = 1.0 / (cutoff / tr)

# define convolution function

    if status == 0 and filter:
        if function == 'boxcar':
            filtfunc = numpy.ones(numpy.ceil(timescale))
        elif function == 'gauss':
            timescale /= 2
            dx = numpy.ceil(timescale * 10 + 1)
            filtfunc = kepfunc.gauss()
            filtfunc = filtfunc([1.0, dx / 2 - 1.0, timescale],
                                linspace(0, dx - 1, dx))
        elif function == 'sinc':
            dx = numpy.ceil(timescale * 12 + 1)
            fx = linspace(0, dx - 1, dx)
            fx = fx - dx / 2 + 0.5
            fx /= timescale
            filtfunc = numpy.sinc(fx)
        filtfunc /= numpy.sum(filtfunc)

# pad time series at both ends with noise model

    if status == 0 and filter:
        for i in range(ydim * xdim):
            ave, sigma = kepstat.stdev(pixseries[i, :len(filtfunc)])
            padded = numpy.append(kepstat.randarray(numpy.ones(len(filtfunc)) * ave, \
                                                        numpy.ones(len(filtfunc)) * sigma), pixseries[i,:])
            ave, sigma = kepstat.stdev(pixseries[i, -len(filtfunc):])
            padded = numpy.append(padded, kepstat.randarray(numpy.ones(len(filtfunc)) * ave, \
                                                                numpy.ones(len(filtfunc)) * sigma))

            # convolve data

            if status == 0:
                convolved = convolve(padded, filtfunc, 'same')

# remove padding from the output array

            if status == 0:
                outdata = convolved[len(filtfunc):-len(filtfunc)]

# subtract low frequencies

            if status == 0:
                outmedian = median(outdata)
                pixseries[i, :] = pixseries[i, :] - outdata + outmedian

# sum pixels over cadence

    if status == 0:
        np = 0
        nrows = len(fluxpixels)
        pixsum = zeros((ydim * xdim))
        errsum = zeros((ydim * xdim))
        for i in range(npts):
            if quality[i] == 0:
                pixsum += pixseries[:, i]
                errsum += errseries[:, i]**2
                np += 1
        pixsum /= np
        errsum = sqrt(errsum) / np

# calculate standard deviation pixels

    if status == 0:
        pixvar = zeros((ydim * xdim))
        for i in range(npts):
            if quality[i] == 0:
                pixvar += (pixsum - pixseries[:, i] / errseries[:, i])**2
        pixvar = numpy.sqrt(pixvar)

# median pixel errors

    if status == 0:
        errmed = empty((ydim * xdim))
        for i in range(ydim * xdim):
            errmed[i] = numpy.median(errseries[:, i])

# calculate chi distribution pixels

    if status == 0:
        pixdev = zeros((ydim * xdim))
        for i in range(npts):
            if quality[i] == 0:
                pixdev += ((pixsum - pixseries[:, i]) / pixsum)**2
        pixdev = numpy.sqrt(pixdev)

#        pixdev = numpy.sqrt(pixvar) / errsum #errmed

# image scale and intensity limits

    if status == 0:
        pixsum_pl, zminsum, zmaxsum = kepplot.intScale1D(pixsum, imscale)
        pixvar_pl, zminvar, zmaxvar = kepplot.intScale1D(pixvar, imscale)
        pixdev_pl, zmindev, zmaxdev = kepplot.intScale1D(pixdev, imscale)

# construct output summed image

    if status == 0:
        imgsum = empty((ydim, xdim))
        imgvar = empty((ydim, xdim))
        imgdev = empty((ydim, xdim))
        imgsum_pl = empty((ydim, xdim))
        imgvar_pl = empty((ydim, xdim))
        imgdev_pl = empty((ydim, xdim))
        n = 0
        for i in range(ydim):
            for j in range(xdim):
                imgsum[i, j] = pixsum[n]
                imgvar[i, j] = pixvar[n]
                imgdev[i, j] = pixdev[n]
                imgsum_pl[i, j] = pixsum_pl[n]
                imgvar_pl[i, j] = pixvar_pl[n]
                imgdev_pl[i, j] = pixdev_pl[n]
                n += 1

# construct output file

    if status == 0:
        instruct, status = kepio.openfits(infile, 'readonly', logfile, verbose)
        status = kepkey.history(call, instruct[0], outfile, logfile, verbose)
        hdulist = HDUList(instruct[0])
        hdulist.writeto(outfile)
        status = kepkey.new('EXTNAME', 'FLUX', 'name of extension',
                            instruct[2], outfile, logfile, verbose)
        pyfits.append(outfile, imgsum, instruct[2].header)
        status = kepkey.new('EXTNAME', 'CHI', 'name of extension', instruct[2],
                            outfile, logfile, verbose)
        pyfits.append(outfile, imgvar, instruct[2].header)
        status = kepkey.new('EXTNAME', 'STDDEV', 'name of extension',
                            instruct[2], outfile, logfile, verbose)
        pyfits.append(outfile, imgdev, instruct[2].header)
        status = kepkey.new('EXTNAME', 'APERTURE', 'name of extension',
                            instruct[2], outfile, logfile, verbose)
        pyfits.append(outfile, instruct[2].data, instruct[2].header)
        status = kepio.closefits(instruct, logfile, verbose)

# pixel limits of the subimage

    if status == 0:
        ymin = row
        ymax = ymin + ydim
        xmin = column
        xmax = xmin + xdim

        # plot limits for summed image

        ymin = float(ymin) - 0.5
        ymax = float(ymax) - 0.5
        xmin = float(xmin) - 0.5
        xmax = float(xmax) - 0.5

        # plot style

        try:
            params = {
                'backend': 'png',
                'axes.linewidth': 2.5,
                'axes.labelsize': 24,
                'axes.font': 'sans-serif',
                'axes.fontweight': 'bold',
                'text.fontsize': 12,
                'legend.fontsize': 12,
                'xtick.labelsize': 10,
                'ytick.labelsize': 10
            }
            pylab.rcParams.update(params)
        except:
            'ERROR -- KEPDIFFIM: install latex for scientific plotting'
            status = 1

    if status == 0:
        plotimage(imgsum_pl, imgvar_pl, imgdev_pl, zminsum, zminvar, zmindev,
                  zmaxsum, zmaxvar, zmaxdev, xmin, xmax, ymin, ymax, colmap,
                  plotfile, cmdLine)

# stop time

    kepmsg.clock('KEPDIFFIM ended at: ', logfile, verbose)

    return
Exemple #6
0
def kepdiffim(infile,outfile,plotfile,imscale,colmap,filter,function,cutoff,clobber,verbose,logfile,status,cmdLine=False): 

# input arguments

    status = 0
    seterr(all="ignore") 

# log the call 

    hashline = '----------------------------------------------------------------------------'
    kepmsg.log(logfile,hashline,verbose)
    call = 'KEPDIFFIM -- '
    call += 'infile='+infile+' '
    call += 'outfile='+outfile+' '
    call += 'plotfile='+plotfile+' '
    call += 'imscale='+imscale+' '
    call += 'colmap='+colmap+' '
    filt = 'n'
    if (filter): filt = 'y'
    call += 'filter='+filt+ ' '
    call += 'function='+function+' '
    call += 'cutoff='+str(cutoff)+' '
    overwrite = 'n'
    if (clobber): overwrite = 'y'
    call += 'clobber='+overwrite+ ' '
    chatter = 'n'
    if (verbose): chatter = 'y'
    call += 'verbose='+chatter+' '
    call += 'logfile='+logfile
    kepmsg.log(logfile,call+'\n',verbose)

# start time

    kepmsg.clock('KEPDIFFIM started at: ',logfile,verbose)

# test log file

    logfile = kepmsg.test(logfile)

# clobber output file

    if clobber: status = kepio.clobber(outfile,logfile,verbose)
    if kepio.fileexists(outfile): 
        message = 'ERROR -- KEPDIFFIM: ' + outfile + ' exists. Use --clobber'
        status = kepmsg.err(logfile,message,verbose)

# reference color map

    if colmap == 'browse':
        status = cmap_plot()

# open TPF FITS file

    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, barytime, status = \
            kepio.readTPF(infile,'TIME',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, tcorr, status = \
            kepio.readTPF(infile,'TIMECORR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, cadno, status = \
            kepio.readTPF(infile,'CADENCENO',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, fluxpixels, status = \
            kepio.readTPF(infile,'FLUX',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, errpixels, status = \
            kepio.readTPF(infile,'FLUX_ERR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, qual, status = \
            kepio.readTPF(infile,'QUALITY',logfile,verbose)

# read mask defintion data from TPF file

    if status == 0:
        maskimg, pixcoord1, pixcoord2, status = kepio.readMaskDefinition(infile,logfile,verbose)

# print target data

    if status == 0:
        print ''
        print '      KepID:  %s' % kepid
        print ' RA (J2000):  %s' % ra
        print 'Dec (J2000): %s' % dec
        print '     KepMag:  %s' % kepmag
        print '   SkyGroup:    %2s' % skygroup
        print '     Season:    %2s' % str(season)
        print '    Channel:    %2s' % channel
        print '     Module:    %2s' % module
        print '     Output:     %1s' % output
        print ''

# how many quality = 0 rows?

    if status == 0:
        npts = 0
        nrows = len(fluxpixels)
        for i in range(nrows):
            if qual[i] == 0 and \
                    numpy.isfinite(barytime[i]) and \
                    numpy.isfinite(fluxpixels[i,ydim*xdim/2]):
                npts += 1
        time = empty((npts))
        timecorr = empty((npts))
        cadenceno = empty((npts))
        quality = empty((npts))
        pixseries = empty((ydim*xdim,npts))
        errseries = empty((ydim*xdim,npts))

# construct output light curves

    if status == 0:
        np = 0
        for i in range(ydim*xdim):
            npts = 0
            for k in range(nrows):
                if qual[k] == 0 and \
                        numpy.isfinite(barytime[k]) and \
                        numpy.isfinite(fluxpixels[k,ydim*xdim/2]):
                    time[npts] = barytime[k]
                    timecorr[npts] = tcorr[k]
                    cadenceno[npts] = cadno[k]
                    quality[npts] = qual[k]
                    pixseries[i,npts] = fluxpixels[k,np]
                    errseries[i,npts] = errpixels[k,np]
                    npts += 1
            np += 1

# define data sampling

    if status == 0 and filter:
        tpf, status = kepio.openfits(infile,'readonly',logfile,verbose)
    if status == 0 and filter:
        cadence, status = kepkey.cadence(tpf[1],infile,logfile,verbose)     
        tr = 1.0 / (cadence / 86400)
        timescale = 1.0 / (cutoff / tr)

# define convolution function

    if status == 0 and filter:
        if function == 'boxcar':
            filtfunc = numpy.ones(numpy.ceil(timescale))
        elif function == 'gauss':
            timescale /= 2
            dx = numpy.ceil(timescale * 10 + 1)
            filtfunc = kepfunc.gauss()
            filtfunc = filtfunc([1.0,dx/2-1.0,timescale],linspace(0,dx-1,dx))
        elif function == 'sinc':
            dx = numpy.ceil(timescale * 12 + 1)
            fx = linspace(0,dx-1,dx)
            fx = fx - dx / 2 + 0.5
            fx /= timescale
            filtfunc = numpy.sinc(fx)
        filtfunc /= numpy.sum(filtfunc)

# pad time series at both ends with noise model

    if status == 0 and filter:
        for i in range(ydim*xdim):
            ave, sigma  = kepstat.stdev(pixseries[i,:len(filtfunc)])
            padded = numpy.append(kepstat.randarray(numpy.ones(len(filtfunc)) * ave, \
                                                        numpy.ones(len(filtfunc)) * sigma), pixseries[i,:])
            ave, sigma  = kepstat.stdev(pixseries[i,-len(filtfunc):])
            padded = numpy.append(padded, kepstat.randarray(numpy.ones(len(filtfunc)) * ave, \
                                                                numpy.ones(len(filtfunc)) * sigma))

# convolve data

            if status == 0:
                convolved = convolve(padded,filtfunc,'same')

# remove padding from the output array

            if status == 0:
                outdata = convolved[len(filtfunc):-len(filtfunc)]
                            
# subtract low frequencies

            if status == 0:
                outmedian = median(outdata)
                pixseries[i,:] = pixseries[i,:] - outdata + outmedian

# sum pixels over cadence

    if status == 0:
        np = 0
        nrows = len(fluxpixels)
        pixsum = zeros((ydim*xdim))
        errsum = zeros((ydim*xdim))
        for i in range(npts):
            if quality[i] == 0:
                pixsum += pixseries[:,i]
                errsum += errseries[:,i]**2
                np += 1
        pixsum /= np
        errsum = sqrt(errsum) / np

# calculate standard deviation pixels

    if status == 0:
        pixvar = zeros((ydim*xdim))
        for i in range(npts):
            if quality[i] == 0:
                pixvar += (pixsum - pixseries[:,i] / errseries[:,i])**2 
        pixvar = numpy.sqrt(pixvar)

# median pixel errors

    if status == 0:
        errmed = empty((ydim*xdim))
        for i in range(ydim*xdim):
            errmed[i] = numpy.median(errseries[:,i])

# calculate chi distribution pixels

    if status == 0:
        pixdev = zeros((ydim*xdim))
        for i in range(npts):
            if quality[i] == 0:
                pixdev += ((pixsum - pixseries[:,i]) / pixsum)**2 
        pixdev = numpy.sqrt(pixdev)


#        pixdev = numpy.sqrt(pixvar) / errsum #errmed

# image scale and intensity limits

    if status == 0:
        pixsum_pl, zminsum, zmaxsum = kepplot.intScale1D(pixsum,imscale)
        pixvar_pl, zminvar, zmaxvar = kepplot.intScale1D(pixvar,imscale)
        pixdev_pl, zmindev, zmaxdev = kepplot.intScale1D(pixdev,imscale)

# construct output summed image

    if status == 0:
        imgsum = empty((ydim,xdim))
        imgvar = empty((ydim,xdim))
        imgdev = empty((ydim,xdim))
        imgsum_pl = empty((ydim,xdim))
        imgvar_pl = empty((ydim,xdim))
        imgdev_pl = empty((ydim,xdim))
        n = 0
        for i in range(ydim):
            for j in range(xdim):
                imgsum[i,j] = pixsum[n]
                imgvar[i,j] = pixvar[n]
                imgdev[i,j] = pixdev[n]
                imgsum_pl[i,j] = pixsum_pl[n]
                imgvar_pl[i,j] = pixvar_pl[n]
                imgdev_pl[i,j] = pixdev_pl[n]
                n += 1

# construct output file

    if status == 0:
        instruct, status = kepio.openfits(infile,'readonly',logfile,verbose)
        status = kepkey.history(call,instruct[0],outfile,logfile,verbose)
        hdulist = HDUList(instruct[0])
        hdulist.writeto(outfile)
        status = kepkey.new('EXTNAME','FLUX','name of extension',instruct[2],outfile,logfile,verbose)
        pyfits.append(outfile,imgsum,instruct[2].header)
        status = kepkey.new('EXTNAME','CHI','name of extension',instruct[2],outfile,logfile,verbose)
        pyfits.append(outfile,imgvar,instruct[2].header)
        status = kepkey.new('EXTNAME','STDDEV','name of extension',instruct[2],outfile,logfile,verbose)
        pyfits.append(outfile,imgdev,instruct[2].header)
        status = kepkey.new('EXTNAME','APERTURE','name of extension',instruct[2],outfile,logfile,verbose)
        pyfits.append(outfile,instruct[2].data,instruct[2].header)
        status = kepio.closefits(instruct,logfile,verbose)

# pixel limits of the subimage

    if status == 0:
        ymin = row
        ymax = ymin + ydim
        xmin = column
        xmax = xmin + xdim

# plot limits for summed image

        ymin = float(ymin) - 0.5
        ymax = float(ymax) - 0.5
        xmin = float(xmin) - 0.5
        xmax = float(xmax) - 0.5

# plot style

        try:
            params = {'backend': 'png',
                      'axes.linewidth': 2.5,
                      'axes.labelsize': 24,
                      'axes.font': 'sans-serif',
                      'axes.fontweight' : 'bold',
                      'text.fontsize': 12,
                      'legend.fontsize': 12,
                      'xtick.labelsize': 10,
                      'ytick.labelsize': 10}
            pylab.rcParams.update(params)
        except:
            'ERROR -- KEPDIFFIM: install latex for scientific plotting'
            status = 1

    if status == 0:
        plotimage(imgsum_pl,imgvar_pl,imgdev_pl,zminsum,zminvar,zmindev,
                  zmaxsum,zmaxvar,zmaxdev,xmin,xmax,ymin,ymax,colmap,plotfile,cmdLine)
        
# stop time

    kepmsg.clock('KEPDIFFIM ended at: ',logfile,verbose)

    return
def kepfield(infile,plotfile,rownum,imscale='linear',colmap='YlOrBr',lcolor='gray',verbose=0,
             logfile='kepfield.log',status=0,kic=0,cmdLine=False): 

# input arguments
    seterr(all="ignore") 

# log the call 

    hashline = '----------------------------------------------------------------------------'
    kepmsg.log(logfile,hashline,verbose)
    call = 'KEPFIELD -- '
    call += 'infile='+infile+' '
    call += 'plotfile='+plotfile+' '
    call += 'rownum='+str(rownum)+' '
    call += 'imscale='+imscale+' '
    call += 'colmap='+colmap+' '
    call += 'lcolor='+lcolor+' '
    chatter = 'n'
    if (verbose): chatter = 'y'
    call += 'verbose='+chatter+' '
    call += 'logfile='+logfile
    kepmsg.log(logfile,call+'\n',verbose)

# start time

    kepmsg.clock('KEPFIELD started at',logfile,verbose)

# test log file

    logfile = kepmsg.test(logfile)

# reference color map

    if colmap == 'browse':
        status = cmap_plot(cmdLine)

# open TPF FITS file

    if status == 0:
        try:
            kepid, channel, skygroup, module, output, quarter, season, \
                ra, dec, column, row, kepmag, xdim, ydim, barytime, status = \
                kepio.readTPF(infile,'TIME',logfile,verbose)
        except:
            message = 'ERROR -- KEPFIELD: is %s a Target Pixel File? ' % infile
            status = kepmsg.err(logfile,message,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, tcorr, status = \
            kepio.readTPF(infile,'TIMECORR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, cadno, status = \
            kepio.readTPF(infile,'CADENCENO',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, fluxpixels, status = \
            kepio.readTPF(infile,'FLUX',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, errpixels, status = \
            kepio.readTPF(infile,'FLUX_ERR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, qual, status = \
            kepio.readTPF(infile,'QUALITY',logfile,verbose)

# read mask defintion data from TPF file

    if status == 0:
        maskimg, pixcoord1, pixcoord2, status = kepio.readMaskDefinition(infile,logfile,verbose)

# observed or simulated data?
        
    if status == 0:
        coa = False
        instr = pyfits.open(infile,mode='readonly',memmap=True)
        filever, status = kepkey.get(infile,instr[0],'FILEVER',logfile,verbose)
        if filever == 'COA': coa = True

# print target data

    if status == 0 and verbose:
        print ''
        print '      KepID:  %s' % kepid
        print ' RA (J2000):  %s' % ra
        print 'Dec (J2000): %s' % dec
        print '     KepMag:  %s' % kepmag
        print '   SkyGroup:    %2s' % skygroup
        print '     Season:    %2s' % str(season)
        print '    Channel:    %2s' % channel
        print '     Module:    %2s' % module
        print '     Output:     %1s' % output
        print ''

# is this a good row with finite timestamp and pixels?

    if status == 0:
        if not numpy.isfinite(barytime[rownum-1]) or not numpy.nansum(fluxpixels[rownum-1,:]):
            message = 'ERROR -- KEPFIELD: Row ' + str(rownum) + ' is a bad quality timestamp'
            status = kepmsg.err(logfile,message,verbose)

# construct input pixel image

    if status == 0:
        flux = fluxpixels[rownum-1,:]

# image scale and intensity limits of pixel data

    if status == 0:
        flux_pl, zminfl, zmaxfl = kepplot.intScale1D(flux,imscale)
        n = 0
        imgflux_pl = empty((ydim+2,xdim+2))
        for i in range(ydim+2):
            for j in range(xdim+2):
                imgflux_pl[i,j] = numpy.nan
        for i in range(ydim):
            for j in range(xdim):
                imgflux_pl[i+1,j+1] = flux_pl[n]
                n += 1
        
# cone search around target coordinates using the MAST target search form 

    if status == 0:
        dr = max([ydim+2,xdim+2]) * 4.0
        kepid,ra,dec,kepmag = MASTRADec(float(ra),float(dec),dr)

# convert celestial coordinates to detector coordinates

    if status == 0:
        sx = numpy.array([])
        sy = numpy.array([])
        inf, status = kepio.openfits(infile,'readonly',logfile,verbose)
        crpix1, crpix2, crval1, crval2, cdelt1, cdelt2, pc, status = \
            kepkey.getWCSs(infile,inf['APERTURE'],logfile,verbose) 
        crpix1p, crpix2p, crval1p, crval2p, cdelt1p, cdelt2p, status = \
            kepkey.getWCSp(infile,inf['APERTURE'],logfile,verbose)     
        for i in range(len(kepid)):
            dra = (ra[i] - crval1) * math.sin(math.radians(dec[i])) / cdelt1
            ddec = (dec[i] - crval2) / cdelt2
            if coa:
                sx = numpy.append(sx,-(pc[0,0] * dra + pc[0,1] * ddec) + crpix1 + crval1p - 1.0)
            else:
                sx = numpy.append(sx,pc[0,0] * dra + pc[0,1] * ddec + crpix1 + crval1p - 1.0) 
            sy = numpy.append(sy,pc[1,0] * dra + pc[1,1] * ddec + crpix2 + crval2p - 1.0)

# plot style

    if status == 0:
        try:
            params = {'backend': 'png',
                      'axes.linewidth': 2.0,
                      'axes.labelsize': 24,
                      'axes.font': 'sans-serif',
                      'axes.fontweight' : 'bold',
                      'text.fontsize': 12,
                      'legend.fontsize': 12,
                      'xtick.labelsize': 18,
                      'ytick.labelsize': 18}
            pylab.rcParams.update(params)
        except:
            pass
        pylab.figure(figsize=[10,10])
        pylab.clf()
            
# pixel limits of the subimage

    if status == 0:
        ymin = copy(float(row))
        ymax = ymin + ydim
        xmin = copy(float(column))
        xmax = xmin + xdim

# plot limits for flux image

    if status == 0:
        ymin = float(ymin) - 1.5
        ymax = float(ymax) + 0.5
        xmin = float(xmin) - 1.5
        xmax = float(xmax) + 0.5

# plot the image window
        
    if status == 0:
        ax = pylab.axes([0.1,0.11,0.88,0.88])
        pylab.imshow(imgflux_pl,aspect='auto',interpolation='nearest',origin='lower',
                     vmin=zminfl,vmax=zmaxfl,extent=(xmin,xmax,ymin,ymax),cmap=colmap)
        pylab.gca().set_autoscale_on(False)
        labels = ax.get_yticklabels()
        setp(labels, 'rotation', 90)
        pylab.gca().xaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
        pylab.gca().yaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
        pylab.xlabel('Pixel Column Number', {'color' : 'k'})
        pylab.ylabel('Pixel Row Number', {'color' : 'k'})

# plot mask borders

    if status == 0:
        kepplot.borders(maskimg,xdim,ydim,pixcoord1,pixcoord2,1,lcolor,'-',1)

# plot aperture borders

    if status == 0:
        kepplot.borders(maskimg,xdim,ydim,pixcoord1,pixcoord2,2,lcolor,'-',4.0)

# list sources

    if status == 0 and verbose:
        print 'Column    Row  RA J2000 Dec J2000    Kp    Kepler ID'
        print '----------------------------------------------------'
        for i in range(len(sx)-1,-1,-1):
            if sx[i] >= xmin and sx[i] < xmax and sy[i] >= ymin and sy[i] < ymax:
                if kepid[i] != 0 and kepmag[i] != 0.0:
                    print '%6.1f %6.1f %9.5f  %8.5f %5.2f KIC %d' % \
                        (float(sx[i]),float(sy[i]),float(ra[i]),float(dec[i]),float(kepmag[i]),int(kepid[i]))
                elif kepid[i] != 0 and kepmag[i] == 0.0:
                    print '%6.1f %6.1f %9.5f  %8.5f       KIC %d' % \
                        (float(sx[i]),float(sy[i]),float(ra[i]),float(dec[i]),int(kepid[i]))
                else:
                    print '%6.1f %6.1f %9.5f  %8.5f' % (float(sx[i]),float(sy[i]),float(ra[i]),float(dec[i]))

# plot sources

    if status == 0:
        for i in range(len(sx)-1,-1,-1):
            if kepid[i] != 0 and kepmag[i] != 0.0:
                size = max(array([80.0,80.0 + (2.5**(18.0 - max(12.0,float(kepmag[i])))) * 250.0]))
                pylab.scatter(sx[i],sy[i],s=size,facecolors='g',edgecolors='k',alpha=0.4)
            else:
                pylab.scatter(sx[i],sy[i],s=80,facecolors='r',edgecolors='k',alpha=0.4)

# render plot

    if status == 0 and len(plotfile) > 0 and plotfile.lower() != 'none':
        pylab.savefig(plotfile)
    if status == 0:
        if cmdLine: 
            pylab.show(block=True)
        else: 
            pylab.ion()
            pylab.plot([])
            pylab.ioff()
            pylab.clf()

# stop time

    kepmsg.clock('\nKEPFIELD ended at',logfile,verbose)


#    pdb.set_trace()

    if kic > 0:
        ind = np.where(kepid == kic)
        colret = sx[ind]
        rowret = sy[ind]
        raret = ra[ind]
        decret = dec[ind]
        kepmagret = kepmag[ind]
        kepidret = kepid[ind]
    else:
        inds = np.where(kepmag != 0.0)
        colret = sx[inds]
        rowret = sy[inds]
        raret = ra[inds]
        decret = dec[inds]
        kepmagret = kepmag[inds]
        kepidret = kepid[inds]


    return colret,rowret,raret,decret,kepmagret,kepidret
Exemple #8
0
def kepdeltapix(infile,nexp,columns,rows,fluxes,prfdir,interpolation,tolerance,fittype,imscale,
           colmap,verbose,logfile,status,cmdLine=False): 

# input arguments

    status = 0
    seterr(all="ignore") 

# log the call 

    hashline = '----------------------------------------------------------------------------'
    kepmsg.log(logfile,hashline,verbose)
    call = 'KEPDELTAPIX -- '
    call += 'infile='+infile+' '
    call += 'nexp='+str(nexp)+' '
    call += 'columns='+columns+' '
    call += 'rows='+rows+' '
    call += 'fluxes='+fluxes+' '
    call += 'prfdir='+prfdir+' '
    call += 'interpolation='+interpolation+' '
    call += 'tolerance='+str(tolerance)+' '
    call += 'fittype='+str(fittype)+' '
    call += 'imscale='+imscale+' '
    call += 'colmap='+colmap+' '
    chatter = 'n'
    if (verbose): chatter = 'y'
    call += 'verbose='+chatter+' '
    call += 'logfile='+logfile
    kepmsg.log(logfile,call+'\n',verbose)

# test log file

    logfile = kepmsg.test(logfile)

# start time

    kepmsg.clock('KEPDELTAPIX started at',logfile,verbose)

# reference color map

    if colmap == 'browse':
        status = cmap_plot(cmdLine)

# open TPF FITS file

    if status == 0:
        try:
            kepid, channel, skygroup, module, output, quarter, season, \
                ra, dec, column, row, kepmag, xdim, ydim, barytime, status = \
                kepio.readTPF(infile,'TIME',logfile,verbose)
        except:
            message = 'ERROR -- KEPDELTAPIX: is %s a Target Pixel File? ' % infile
            status = kepmsg.err(logfile,message,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, tcorr, status = \
            kepio.readTPF(infile,'TIMECORR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, cadno, status = \
            kepio.readTPF(infile,'CADENCENO',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, fluxpixels, status = \
            kepio.readTPF(infile,'FLUX',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, errpixels, status = \
            kepio.readTPF(infile,'FLUX_ERR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, qual, status = \
            kepio.readTPF(infile,'QUALITY',logfile,verbose)

# print target data

    if status == 0 and verbose:
        print ''
        print '      KepID:  %s' % kepid
        print ' RA (J2000):  %s' % ra
        print 'Dec (J2000): %s' % dec
        print '     KepMag:  %s' % kepmag
        print '   SkyGroup:    %2s' % skygroup
        print '     Season:    %2s' % str(season)
        print '    Channel:    %2s' % channel
        print '     Module:    %2s' % module
        print '     Output:     %1s' % output
        print ''

# determine suitable PRF calibration file

    if status == 0:
        if int(module) < 10:
            prefix = 'kplr0'
        else:
            prefix = 'kplr'
        prfglob = prfdir + '/' + prefix + str(module) + '.' + str(output) + '*' + '_prf.fits'
        try:
            prffile = glob.glob(prfglob)[0]
        except:
            message = 'ERROR -- KEPDELTAPIX: No PRF file found in ' + prfdir
            status = kepmsg.err(logfile,message,verbose)

# read PRF images

    if status == 0:
        prfn = [0,0,0,0,0]
        crpix1p = numpy.zeros((5),dtype='float32')
        crpix2p = numpy.zeros((5),dtype='float32')
        crval1p = numpy.zeros((5),dtype='float32')
        crval2p = numpy.zeros((5),dtype='float32')
        cdelt1p = numpy.zeros((5),dtype='float32')
        cdelt2p = numpy.zeros((5),dtype='float32')
        for i in range(5):
            prfn[i], crpix1p[i], crpix2p[i], crval1p[i], crval2p[i], cdelt1p[i], cdelt2p[i], status \
                = kepio.readPRFimage(prffile,i+1,logfile,verbose)    

# choose rows in the TPF table at random

    if status == 0:
        i = 0
        rownum = []
        while i < nexp:
            work = int(random.random() * len(barytime))
            if numpy.isfinite(barytime[work]) and numpy.isfinite(fluxpixels[work,ydim*xdim/2]):
                rownum.append(work)
                i += 1

# construct input pixel image

    if status == 0:
        fscat = numpy.empty((len(fluxes),nexp),dtype='float32')
        xscat = numpy.empty((len(columns),nexp),dtype='float32')
        yscat = numpy.empty((len(rows),nexp),dtype='float32')
        for irow in range(nexp):
            flux = fluxpixels[rownum[irow],:]

# image scale and intensity limits of pixel data

            if status == 0:
                flux_pl, zminfl, zmaxfl = kepplot.intScale1D(flux,imscale)
                n = 0
                imgflux_pl = empty((ydim,xdim))
                for i in range(ydim):
                    for j in range(xdim):
                        imgflux_pl[i,j] = flux_pl[n]
                        n += 1
        
# fit PRF model to pixel data

            if status == 0:
                start = time.time()
                f,y,x,prfMod,prfFit,prfRes = kepfit.fitMultiPRF(flux,ydim,xdim,column,row,prfn,crval1p,
                     crval2p,cdelt1p,cdelt2p,interpolation,tolerance,fluxes,columns,rows,fittype,
                     verbose,logfile)
                if verbose:
                    print '\nConvergence time = %.1fs' % (time.time() - start)

# best fit parameters

            if status == 0:
                for i in range(len(f)):
                    fscat[i,irow] = f[i]
                    xscat[i,irow] = x[i]
                    yscat[i,irow] = y[i]

# replace starting guess with previous fit parameters

            if status == 0:
                fluxes = copy(f)
                columns = copy(x)
                rows = copy(y)

# mean and rms results

    if status == 0:
        fmean = []; fsig = []
        xmean = []; xsig = []
        ymean = []; ysig = []
        for i in range(len(f)):
            fmean.append(numpy.mean(fscat[i,:]))
            xmean.append(numpy.mean(xscat[i,:]))
            ymean.append(numpy.mean(yscat[i,:]))
            fsig.append(numpy.std(fscat[i,:]))
            xsig.append(numpy.std(xscat[i,:]))
            ysig.append(numpy.std(yscat[i,:]))
            txt = 'Flux = %10.2f e-/s ' % fmean[-1]
            txt += 'X = %7.4f +/- %6.4f pix ' % (xmean[-1], xsig[i])
            txt += 'Y = %7.4f +/- %6.4f pix' % (ymean[-1], ysig[i])
            kepmsg.log(logfile,txt,True)

# output results for kepprfphot

    if status == 0:
        txt1 = 'columns=0.0'
        txt2 = '   rows=0.0'
        for i in range(1,len(f)):
            txt1 += ',%.4f' % (xmean[i] - xmean[0])
            txt2 += ',%.4f' % (ymean[i] - ymean[0])
        kepmsg.log(logfile,'\nkepprfphot input fields:',True)
        kepmsg.log(logfile,txt1,True)
        kepmsg.log(logfile,txt2,True)
        
# image scale and intensity limits for PRF model image

    if status == 0:
        imgprf_pl, zminpr, zmaxpr = kepplot.intScale2D(prfMod,imscale)
        
# image scale and intensity limits for PRF fit image

    if status == 0:
        imgfit_pl, zminfi, zmaxfi = kepplot.intScale2D(prfFit,imscale)
        
# image scale and intensity limits for data - fit residual

    if status == 0:
        imgres_pl, zminre, zmaxre = kepplot.intScale2D(prfRes,imscale)
        
# plot style

    if status == 0:
        try:
            params = {'backend': 'png',
                      'axes.linewidth': 2.5,
                      'axes.labelsize': 24,
                      'axes.font': 'sans-serif',
                      'axes.fontweight' : 'bold',
                      'text.fontsize': 12,
                      'legend.fontsize': 12,
                      'xtick.labelsize': 10,
                      'ytick.labelsize': 10}
            pylab.rcParams.update(params)
        except:
            pass
        pylab.figure(figsize=[10,10])
        pylab.clf()
        plotimage(imgflux_pl,zminfl,zmaxfl,1,row,column,xdim,ydim,0.06,0.52,'flux',colmap)
        plotimage(imgfit_pl,zminfl,zmaxfl,3,row,column,xdim,ydim,0.06,0.06,'fit',colmap)
        plotimage(imgres_pl,zminfl,zmaxfl,4,row,column,xdim,ydim,0.52,0.06,'residual',colmap)
        plotimage(imgprf_pl,zminpr,zmaxpr*0.9,2,row,column,xdim,ydim,0.52,0.52,'model',colmap)
        for i in range(len(f)):        
            pylab.plot(xscat[i,:],yscat[i,:],'o',color='k')            
            
# Plot creep of target position over time, relative to the central source

#	barytime0 = float(int(barytime[0] / 100) * 100.0)
#	barytime -= barytime0
#        xlab = 'BJD $-$ %d' % barytime0
#	xmin = numpy.nanmin(barytime)
#	xmax = numpy.nanmax(barytime)
#	y1min = numpy.nanmin(data)
#	y1max = numpy.nanmax(data)
#	xr = xmax - xmin
#	yr = ymax - ymin
#        barytime = insert(barytime,[0],[barytime[0]]) 
#        barytime = append(barytime,[barytime[-1]])
#        data = insert(data,[0],[0.0]) 
#        data = append(data,0.0)
#
#        pylab.figure(2,figsize=[10,10])
#        pylab.clf()
#	ax = pylab.subplot(211)
#	pylab.subplots_adjust(0.1,0.5,0.88,0.42)
#        pylab.gca().xaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
#        pylab.gca().yaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
#        labels = ax.get_yticklabels()
#        setp(labels, 'rotation', 90, fontsize=ticksize)
#        for i in range(1,len(f)):
#            pylab.plot(rownum,xscat[i,:]-xscat[0,:],'o')
#        pylab.ylabel('$\Delta$Columns', {'color' : 'k'})
#	ax = pylab.subplot(211)
#	pylab.subplots_adjust(0.1,0.1,0.88,0.42)
#        pylab.gca().xaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
#        pylab.gca().yaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
#        labels = ax.get_yticklabels()
#        setp(labels, 'rotation', 90, fontsize=ticksize)
#        for i in range(1,len(f)):
#            pylab.plot(rownum,yscat[i,:]-yscat[0,:],'o')
#	pylab.xlim(xmin-xr*0.01,xmax+xr*0.01)
#	if ymin-yr*0.01 <= 0.0 or fullrange:
#            pylab.ylim(1.0e-10,ymax+yr*0.01)
#	else:
#            pylab.ylim(ymin-yr*0.01,ymax+yr*0.01)
#        pylab.ylabel('$\Delta$Rows', {'color' : 'k'})
#        pylab.xlabel(xlab, {'color' : 'k'})

# render plot

    if status == 0:
        if cmdLine: 
            pylab.show(block=True)
        else: 
            pylab.ion()
            pylab.plot([])
            pylab.ioff()
	
# stop time

    kepmsg.clock('\nKEPDELTAPIX ended at',logfile,verbose)

    return
Exemple #9
0
    def __init__(self,
                 infile,
                 rownum=0,
                 imscale='linear',
                 cmap='YlOrBr',
                 lcolor='k',
                 acolor='b',
                 query=True,
                 logfile='kepcrowd.log',
                 **kwargs):

        self.colrow = []
        self.fluxes = []
        self._text = []

        # hide warnings
        np.seterr(all="ignore")

        # test log file
        logfile = kepmsg.test(logfile)

        # info
        hashline = '----------------------------------------------------------------------------'
        kepmsg.log(logfile, hashline, False)
        call = 'KEPFIELD -- '
        call += 'infile=' + infile + ' '
        call += 'rownum=' + str(rownum)
        kepmsg.log(logfile, call + '\n', False)

        try:
            kepid, channel, skygroup, module, output, quarter, season, \
                ra, dec, column, row, kepmag, xdim, ydim, barytime, status = \
                kepio.readTPF(infile, 'TIME', logfile, False)
        except:
            message = 'ERROR -- KEPFIELD: is %s a Target Pixel File? ' % infile
            kepmsg.err(logfile, message, False)
            return "", "", "", None

        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, tcorr, status = \
            kepio.readTPF(infile,'TIMECORR',logfile,False)

        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, cadno, status = \
            kepio.readTPF(infile,'rownumNO',logfile,False)

        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, fluxpixels, status = \
            kepio.readTPF(infile,'FLUX',logfile,False)

        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, errpixels, status = \
            kepio.readTPF(infile,'FLUX_ERR',logfile,False)

        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, qual, status = \
            kepio.readTPF(infile,'QUALITY',logfile,False)

        # read mask defintion data from TPF file
        maskimg, pixcoord1, pixcoord2, status = kepio.readMaskDefinition(
            infile, logfile, False)

        # observed or simulated data?
        coa = False
        instr = pyfits.open(infile, mode='readonly', memmap=True)
        filever, status = kepkey.get(infile, instr[0], 'FILEVER', logfile,
                                     False)
        if filever == 'COA': coa = True

        # is this a good row with finite timestamp and pixels?
        if not np.isfinite(barytime[rownum - 1]) or not np.nansum(
                fluxpixels[rownum - 1, :]):
            message = 'ERROR -- KEPFIELD: Row ' + str(
                rownum) + ' is a bad quality timestamp'
            kepmsg.err(logfile, message, True)
            return "", "", "", None

        # construct input pixel image
        flux = fluxpixels[rownum - 1, :]

        # image scale and intensity limits of pixel data
        flux_pl, zminfl, zmaxfl = kepplot.intScale1D(flux, imscale)
        n = 0
        imgflux_pl = np.empty((ydim + 2, xdim + 2))
        for i in range(ydim + 2):
            for j in range(xdim + 2):
                imgflux_pl[i, j] = np.nan
        for i in range(ydim):
            for j in range(xdim):
                imgflux_pl[i + 1, j + 1] = flux_pl[n]
                n += 1

        # cone search around target coordinates using the MAST target search form
        dr = max([ydim + 2, xdim + 2]) * 4.0
        kepid, ra, dec, kepmag = MASTRADec(float(ra), float(dec), dr, query,
                                           logfile)

        # convert celestial coordinates to detector coordinates
        sx = np.array([])
        sy = np.array([])
        inf, status = kepio.openfits(infile, 'readonly', logfile, False)
        try:
            crpix1, crpix2, crval1, crval2, cdelt1, cdelt2, pc, status = \
                kepkey.getWCSs(infile,inf['APERTURE'],logfile,False)
            crpix1p, crpix2p, crval1p, crval2p, cdelt1p, cdelt2p, status = \
                kepkey.getWCSp(infile,inf['APERTURE'],logfile,False)
            for i in range(len(kepid)):
                dra = (ra[i] - crval1) * np.cos(np.radians(dec[i])) / cdelt1
                ddec = (dec[i] - crval2) / cdelt2
                if coa:
                    sx = np.append(
                        sx, -(pc[0, 0] * dra + pc[0, 1] * ddec) + crpix1 +
                        crval1p - 1.0)
                else:
                    sx = np.append(
                        sx, pc[0, 0] * dra + pc[0, 1] * ddec + crpix1 +
                        crval1p - 1.0)
                sy = np.append(
                    sy,
                    pc[1, 0] * dra + pc[1, 1] * ddec + crpix2 + crval2p - 1.0)
        except:
            message = 'ERROR -- KEPFIELD: Non-compliant WCS information within file %s' % infile
            kepmsg.err(logfile, message, True)
            return "", "", "", None

        # plot
        self.fig = pl.figure(figsize=[10, 10])
        pl.clf()

        # pixel limits of the subimage
        ymin = np.copy(float(row))
        ymax = ymin + ydim
        xmin = np.copy(float(column))
        xmax = xmin + xdim

        # plot limits for flux image
        ymin = float(ymin) - 1.5
        ymax = float(ymax) + 0.5
        xmin = float(xmin) - 1.5
        xmax = float(xmax) + 0.5

        # plot the image window
        ax = pl.axes([0.1, 0.11, 0.88, 0.82])
        pl.title('Select sources for fitting (KOI first)', fontsize=24)
        pl.imshow(imgflux_pl,
                  aspect='auto',
                  interpolation='nearest',
                  origin='lower',
                  vmin=zminfl,
                  vmax=zmaxfl,
                  extent=(xmin, xmax, ymin, ymax),
                  cmap=cmap)
        pl.gca().set_autoscale_on(False)
        labels = ax.get_yticklabels()
        pl.setp(labels, 'rotation', 90)
        pl.gca().xaxis.set_major_formatter(pl.ScalarFormatter(useOffset=False))
        pl.gca().yaxis.set_major_formatter(pl.ScalarFormatter(useOffset=False))
        pl.xlabel('Pixel Column Number', {'color': 'k'}, fontsize=24)
        pl.ylabel('Pixel Row Number', {'color': 'k'}, fontsize=24)

        # plot mask borders
        kepplot.borders(maskimg, xdim, ydim, pixcoord1, pixcoord2, 1, lcolor,
                        '--', 0.5)

        # plot aperture borders
        kepplot.borders(maskimg, xdim, ydim, pixcoord1, pixcoord2, 2, lcolor,
                        '-', 4.0)

        # list sources
        with open(logfile, 'a') as lf:
            print('Column    Row  RA J2000 Dec J2000    Kp    Kepler ID',
                  file=lf)
            print('----------------------------------------------------',
                  file=lf)
            for i in range(len(sx) - 1, -1, -1):
                if sx[i] >= xmin and sx[i] < xmax and sy[i] >= ymin and sy[
                        i] < ymax:
                    if kepid[i] != 0 and kepmag[i] != 0.0:
                        print('%6.1f %6.1f %9.5f  %8.5f %5.2f KIC %d' % \
                            (float(sx[i]),float(sy[i]),float(ra[i]),float(dec[i]),float(kepmag[i]),int(kepid[i])), file = lf)
                    elif kepid[i] != 0 and kepmag[i] == 0.0:
                        print('%6.1f %6.1f %9.5f  %8.5f       KIC %d' % \
                            (float(sx[i]),float(sy[i]),float(ra[i]),float(dec[i]),int(kepid[i])), file = lf)
                    else:
                        print('%6.1f %6.1f %9.5f  %8.5f' % (float(
                            sx[i]), float(sy[i]), float(ra[i]), float(dec[i])),
                              file=lf)

        # plot sources
        for i in range(len(sx) - 1, -1, -1):
            if kepid[i] != 0 and kepmag[i] != 0.0:
                size = max(
                    np.array([
                        80.0, 80.0 +
                        (2.5**(18.0 - max(12.0, float(kepmag[i])))) * 250.0
                    ]))
                pl.scatter(sx[i],
                           sy[i],
                           s=size,
                           facecolors='g',
                           edgecolors='k',
                           alpha=0.4)
            else:
                pl.scatter(sx[i],
                           sy[i],
                           s=80,
                           facecolors='r',
                           edgecolors='k',
                           alpha=0.4)

        # Sizes
        for tick in ax.xaxis.get_major_ticks():
            tick.label.set_fontsize(16)
        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(16)

        # render plot and activate source selection
        self.srcinfo = [kepid, sx, sy, kepmag]
        pl.connect('button_release_event', self.on_mouse_release)
        pl.show(block=True)
        pl.close()
Exemple #10
0
    def __init__(
        self,
        infile,
        rownum=0,
        imscale="linear",
        cmap="YlOrBr",
        lcolor="k",
        acolor="b",
        query=True,
        logfile="kepcrowd.log",
        **kwargs
    ):

        self.colrow = []
        self.fluxes = []
        self._text = []

        # hide warnings
        np.seterr(all="ignore")

        # test log file
        logfile = kepmsg.test(logfile)

        # info
        hashline = "----------------------------------------------------------------------------"
        kepmsg.log(logfile, hashline, False)
        call = "KEPFIELD -- "
        call += "infile=" + infile + " "
        call += "rownum=" + str(rownum)
        kepmsg.log(logfile, call + "\n", False)

        try:
            kepid, channel, skygroup, module, output, quarter, season, ra, dec, column, row, kepmag, xdim, ydim, barytime, status = kepio.readTPF(
                infile, "TIME", logfile, False
            )
        except:
            message = "ERROR -- KEPFIELD: is %s a Target Pixel File? " % infile
            kepmsg.err(logfile, message, False)
            return "", "", "", None

        kepid, channel, skygroup, module, output, quarter, season, ra, dec, column, row, kepmag, xdim, ydim, tcorr, status = kepio.readTPF(
            infile, "TIMECORR", logfile, False
        )

        kepid, channel, skygroup, module, output, quarter, season, ra, dec, column, row, kepmag, xdim, ydim, cadno, status = kepio.readTPF(
            infile, "rownumNO", logfile, False
        )

        kepid, channel, skygroup, module, output, quarter, season, ra, dec, column, row, kepmag, xdim, ydim, fluxpixels, status = kepio.readTPF(
            infile, "FLUX", logfile, False
        )

        kepid, channel, skygroup, module, output, quarter, season, ra, dec, column, row, kepmag, xdim, ydim, errpixels, status = kepio.readTPF(
            infile, "FLUX_ERR", logfile, False
        )

        kepid, channel, skygroup, module, output, quarter, season, ra, dec, column, row, kepmag, xdim, ydim, qual, status = kepio.readTPF(
            infile, "QUALITY", logfile, False
        )

        # read mask defintion data from TPF file
        maskimg, pixcoord1, pixcoord2, status = kepio.readMaskDefinition(infile, logfile, False)

        # observed or simulated data?
        coa = False
        instr = pyfits.open(infile, mode="readonly", memmap=True)
        filever, status = kepkey.get(infile, instr[0], "FILEVER", logfile, False)
        if filever == "COA":
            coa = True

        # is this a good row with finite timestamp and pixels?
        if not np.isfinite(barytime[rownum - 1]) or not np.nansum(fluxpixels[rownum - 1, :]):
            message = "ERROR -- KEPFIELD: Row " + str(rownum) + " is a bad quality timestamp"
            kepmsg.err(logfile, message, True)
            return "", "", "", None

        # construct input pixel image
        flux = fluxpixels[rownum - 1, :]

        # image scale and intensity limits of pixel data
        flux_pl, zminfl, zmaxfl = kepplot.intScale1D(flux, imscale)
        n = 0
        imgflux_pl = np.empty((ydim + 2, xdim + 2))
        for i in range(ydim + 2):
            for j in range(xdim + 2):
                imgflux_pl[i, j] = np.nan
        for i in range(ydim):
            for j in range(xdim):
                imgflux_pl[i + 1, j + 1] = flux_pl[n]
                n += 1

        # cone search around target coordinates using the MAST target search form
        dr = max([ydim + 2, xdim + 2]) * 4.0
        kepid, ra, dec, kepmag = MASTRADec(float(ra), float(dec), dr, query, logfile)

        # convert celestial coordinates to detector coordinates
        sx = np.array([])
        sy = np.array([])
        inf, status = kepio.openfits(infile, "readonly", logfile, False)
        try:
            crpix1, crpix2, crval1, crval2, cdelt1, cdelt2, pc, status = kepkey.getWCSs(
                infile, inf["APERTURE"], logfile, False
            )
            crpix1p, crpix2p, crval1p, crval2p, cdelt1p, cdelt2p, status = kepkey.getWCSp(
                infile, inf["APERTURE"], logfile, False
            )
            for i in range(len(kepid)):
                dra = (ra[i] - crval1) * np.cos(np.radians(dec[i])) / cdelt1
                ddec = (dec[i] - crval2) / cdelt2
                if coa:
                    sx = np.append(sx, -(pc[0, 0] * dra + pc[0, 1] * ddec) + crpix1 + crval1p - 1.0)
                else:
                    sx = np.append(sx, pc[0, 0] * dra + pc[0, 1] * ddec + crpix1 + crval1p - 1.0)
                sy = np.append(sy, pc[1, 0] * dra + pc[1, 1] * ddec + crpix2 + crval2p - 1.0)
        except:
            message = "ERROR -- KEPFIELD: Non-compliant WCS information within file %s" % infile
            kepmsg.err(logfile, message, True)
            return "", "", "", None

        # plot
        self.fig = pl.figure(figsize=[10, 10])
        pl.clf()

        # pixel limits of the subimage
        ymin = np.copy(float(row))
        ymax = ymin + ydim
        xmin = np.copy(float(column))
        xmax = xmin + xdim

        # plot limits for flux image
        ymin = float(ymin) - 1.5
        ymax = float(ymax) + 0.5
        xmin = float(xmin) - 1.5
        xmax = float(xmax) + 0.5

        # plot the image window
        ax = pl.axes([0.1, 0.11, 0.88, 0.82])
        pl.title("Select sources for fitting (KOI first)", fontsize=24)
        pl.imshow(
            imgflux_pl,
            aspect="auto",
            interpolation="nearest",
            origin="lower",
            vmin=zminfl,
            vmax=zmaxfl,
            extent=(xmin, xmax, ymin, ymax),
            cmap=cmap,
        )
        pl.gca().set_autoscale_on(False)
        labels = ax.get_yticklabels()
        pl.setp(labels, "rotation", 90)
        pl.gca().xaxis.set_major_formatter(pl.ScalarFormatter(useOffset=False))
        pl.gca().yaxis.set_major_formatter(pl.ScalarFormatter(useOffset=False))
        pl.xlabel("Pixel Column Number", {"color": "k"}, fontsize=24)
        pl.ylabel("Pixel Row Number", {"color": "k"}, fontsize=24)

        # plot mask borders
        kepplot.borders(maskimg, xdim, ydim, pixcoord1, pixcoord2, 1, lcolor, "--", 0.5)

        # plot aperture borders
        kepplot.borders(maskimg, xdim, ydim, pixcoord1, pixcoord2, 2, lcolor, "-", 4.0)

        # list sources
        with open(logfile, "a") as lf:
            print("Column    Row  RA J2000 Dec J2000    Kp    Kepler ID", file=lf)
            print("----------------------------------------------------", file=lf)
            for i in range(len(sx) - 1, -1, -1):
                if sx[i] >= xmin and sx[i] < xmax and sy[i] >= ymin and sy[i] < ymax:
                    if kepid[i] != 0 and kepmag[i] != 0.0:
                        print(
                            "%6.1f %6.1f %9.5f  %8.5f %5.2f KIC %d"
                            % (
                                float(sx[i]),
                                float(sy[i]),
                                float(ra[i]),
                                float(dec[i]),
                                float(kepmag[i]),
                                int(kepid[i]),
                            ),
                            file=lf,
                        )
                    elif kepid[i] != 0 and kepmag[i] == 0.0:
                        print(
                            "%6.1f %6.1f %9.5f  %8.5f       KIC %d"
                            % (float(sx[i]), float(sy[i]), float(ra[i]), float(dec[i]), int(kepid[i])),
                            file=lf,
                        )
                    else:
                        print(
                            "%6.1f %6.1f %9.5f  %8.5f" % (float(sx[i]), float(sy[i]), float(ra[i]), float(dec[i])),
                            file=lf,
                        )

        # plot sources
        for i in range(len(sx) - 1, -1, -1):
            if kepid[i] != 0 and kepmag[i] != 0.0:
                size = max(np.array([80.0, 80.0 + (2.5 ** (18.0 - max(12.0, float(kepmag[i])))) * 250.0]))
                pl.scatter(sx[i], sy[i], s=size, facecolors="g", edgecolors="k", alpha=0.4)
            else:
                pl.scatter(sx[i], sy[i], s=80, facecolors="r", edgecolors="k", alpha=0.4)

        # Sizes
        for tick in ax.xaxis.get_major_ticks():
            tick.label.set_fontsize(16)
        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(16)

        # render plot and activate source selection
        self.srcinfo = [kepid, sx, sy, kepmag]
        pl.connect("button_release_event", self.on_mouse_release)
        pl.show(block=True)
        pl.close()