Esempio n. 1
0
def timeCentroid(data, mask, xyGuess, niter, rad=20):
    print "timeCentroid: xyGuess=%3.0f, %3.0f; niter=%2d; rad=%3d;" % \
        (xyGuess[0], xyGuess[1], niter, rad),
    begTime = time.time()
    for ii in range(niter):
        PyGuide.centroid(
            data=data,
            mask=mask,
            satMask=None,
            xyGuess=xyGuess,
            rad=rad,
            thresh=Thresh,
            ccdInfo=CCDInfo,
        )
    dTime = time.time() - begTime
    print "time/iter=%.3f" % (dTime / niter, )
Esempio n. 2
0
 def centroid(self, xyPos, data):
     """check to see if there is valid signal at xpos, ypos, on image data
     if so return the centroid.
     """
     # default to 5 px search rad?
     return PyGuide.centroid(data, None, None, xyPos, rad = 3, #pixels
         ccdInfo = self.config.ccdInfo)
Esempio n. 3
0
def aligntocat(cube,catalogue):

    """ 

    Take a cube and compare the sources in the field to the positions in the reference 
    catalogue. Return offsets in ra/dec that can be used for re-projecting the cube

    This makes use of pyguide to find stars and centroid on them

    """
       
    import PyGuide
    import numpy as np
    from astropy import wcs

    print("Processing cube {} for offsets".format(cube))

    #first project the cube to create a white image with wcs
    img, var, wcsimg = cube2img(cube)

    #load the reference stars
    starcat=np.loadtxt(catalogue,dtype={'names': ('ra','dec'),'formats': ('f4', 'f4')})

    #loop on reference stars and centroid 
    nref=len(starcat['ra'])

    #space for offsets
    raoffcurrent=[]
    decoffcurrent=[]
       
    for sr in range(nref):
        #find first guess
        pix = wcsimg.wcs_world2pix(starcat['ra'][sr],starcat['dec'][sr],0)
        #centroid within 20 pixels 
        ccd=PyGuide.CCDInfo(0,0,1)
        
        #handle weird errors for bas pixels
        usethis=True
        try:
            centroid=PyGuide.centroid(img,None,None,[pix[0],pix[1]],20,ccd)
        except:        
            usethis=False

        #back to ra/dec if centroid is good
        if ((centroid.isOK) & (usethis)): 
            coord = wcsimg.wcs_pix2world(centroid.xyCtr[0],centroid.xyCtr[1],0)
            raoffcurrent.append(coord[0]-starcat['ra'][sr])
            decoffcurrent.append(coord[1]-starcat['dec'][sr])
                
    #stack offsets
    raoff=np.median(np.array(raoffcurrent))
    decoff=np.median(np.array(decoffcurrent))
     
    print("Offsets for cube {} RA: {} Dec: {}".format(cube,raoff*3600.,decoff*3600.))
    print("Error offsets for cube {} RA: {} Dec: {}".format(cube,np.std(np.array(raoffcurrent))*3600.,
                                                            np.std(np.array(decoffcurrent))*3600.))
                             
    return raoff,decoff
Esempio n. 4
0
def aligntocat(cube,catalogue):

    """ 

    Take a cube and compare the sources in the field to the positions in the reference 
    catalogue. Return offsets in ra/dec that can be used for re-projecting the cube

    This makes use of pyguide to find stars and centroid on them

    """
       
    import PyGuide
    import numpy as np
    from astropy import wcs

    print "Processing cube {} for offsets".format(cube)

    #first project the cube to create a white image with wcs
    img, var, wcsimg = cube2img(cube)

    #load the reference stars
    starcat=np.loadtxt(catalogue,dtype={'names': ('ra','dec'),'formats': ('f4', 'f4')})

    #loop on reference stars and centroid 
    nref=len(starcat['ra'])

    #space for offsets
    raoffcurrent=[]
    decoffcurrent=[]
       
    for sr in range(nref):
        #find first guess
        pix = wcsimg.wcs_world2pix(starcat['ra'][sr],starcat['dec'][sr],0)
        #centroid within 20 pixels 
        ccd=PyGuide.CCDInfo(0,0,1)
        
        #handle weird errors for bas pixels
        usethis=True
        try:
            centroid=PyGuide.centroid(img,None,None,[pix[0],pix[1]],20,ccd)
        except:        
            usethis=False

        #back to ra/dec if centroid is good
        if ((centroid.isOK) & (usethis)): 
            coord = wcsimg.wcs_pix2world(centroid.xyCtr[0],centroid.xyCtr[1],0)
            raoffcurrent.append(coord[0]-starcat['ra'][sr])
            decoffcurrent.append(coord[1]-starcat['dec'][sr])
                
    #stack offsets
    raoff=np.median(np.array(raoffcurrent))
    decoff=np.median(np.array(decoffcurrent))
     
    print "Offsets for cube {} RA: {} Dec: {}".format(cube,raoff*3600.,decoff*3600.)
    print "Error offsets for cube {} RA: {} Dec: {}".format(cube,np.std(np.array(raoffcurrent))*3600.,
                                                            np.std(np.array(decoffcurrent))*3600.)
                             
    return raoff,decoff
def centroidImage(image,xyguess,radiusOfSearch = 6,doDS9=True,usePsfFit=False):
    '''
    ABW
    This function finds the centroid of a star in the image
    '''
    #remove any undefined values
    image[np.invert(np.isfinite(image))]=0.
    #Assume anywhere with 0 counts is a dead pixel
    deadMask = 1.0*(image==0)
    #ignore saturated mask
    satMask = np.zeros((len(deadMask),len(deadMask[0])))

    # Specify CCDInfo (bias,readNoise,ccdGain,satLevel)
    ccd = pg.CCDInfo(0,0.00001,1,2500)
    

    xyguessPyguide = np.subtract(xyguess,(0.5,0.5)) #account for how pyguide puts pixel coordinates
    pyguide_output = pg.centroid(image,deadMask,satMask,xyguess,radiusOfSearch,ccd,0,False,verbosity=0, doDS9=doDS9)     #Added by JvE May 31 2013
    # Use PyGuide centroid positions, if algorithm failed, use xy guess center positions instead
    try:
        xycenterGuide = [float(pyguide_output.xyCtr[0]),float(pyguide_output.xyCtr[1])]
        np.add(xycenterGuide,(0.5,0.5))#account for how pyguide puts pixel coordinates
        flag = 0
    except TypeError:
        xycenterGuide = xyguess
        flag = 1
    xycenter=xycenterGuide

    if usePsfFit:
        psfPhot = PSFphotometry(image,centroid=[xycenterGuide],verbose=True)
        psfDict = psfPhot.PSFfit(aper_radius=radiusOfSearch)
        xycenterPsf = [psfDict['parameters'][2],psfDict['parameters'][3]]
        if psfDict['flag'] == 0:
            xycenter = xycenterPsf
            flag = 0
        else:
            print 'PSF fit failed with flag: ', psfDict['flag']
            #xycenter = xycenterGuide 
            flag = 1
            
    outDict = {'xycenter':xycenter,'flag':flag}
    if usePsfFit:
        outDict['xycenterGuide'] = xycenterGuide
        outDict['xycenterPsf'] = xycenterPsf
    return outDict
Esempio n. 6
0
        def presskey(self, event):
            """ Do stuff when press  key  """

            #quit on q
            if (event.key == "q"):
                self.OnExit()

            #centroid on c
            elif (event.key == "c"):
                ccd = PyGuide.CCDInfo(0, 0, 1)
                centroid = PyGuide.centroid(self.fitimg, None, None,
                                            [event.xdata, event.ydata], 20,
                                            ccd)
                self.starx.append(centroid.xyCtr[0])
                self.stary.append(centroid.xyCtr[1])
                thisra, thisdec = self.wcs.wcs_pix2world(
                    centroid.xyCtr[0], centroid.xyCtr[1], 1)
                self.starra.append(thisra)
                self.stardec.append(thisdec)
                self.starid.append(self.find_id(thisra, thisdec))
                self.nstars = self.nstars + 1
                self.update_twodimage(update=True)

            #store bottom left corner on L
            elif (event.key == "n"):
                try:
                    check = float(event.xdata) + float(event.ydata)
                    self.boxlx.append(event.xdata)
                    self.boxly.append(event.ydata)
                    self.warning.set("STATUS: Now mark top/right corner!")
                except:
                    self.boxlx.append(event.xdata)
                    self.boxly.append(event.ydata)
                    self.warning.set(
                        "STATUS: Missed data region... try again!")
            elif (event.key == "m"):
                try:
                    check = float(event.xdata) + float(event.ydata)
                    self.boxrx.append(event.xdata)
                    self.boxry.append(event.ydata)
                    self.nbox = self.nbox + 1
                    self.update_twodimage(update=True)
                    self.warning.set("STATUS: All good!")
                except:
                    self.warning.set(
                        "STATUS: Missed data region... try again!")

            elif (event.key == "d"):
                if (self.nbox > 0):
                    self.boxlx = self.boxlx[0:-1]
                    self.boxly = self.boxly[0:-1]
                    self.boxrx = self.boxrx[0:-1]
                    self.boxry = self.boxry[0:-1]
                    self.nbox = self.nbox - 1
                if (self.nstars > 0):
                    self.starra = self.starra[0:-1]
                    self.stardec = self.stardec[0:-1]
                    self.starid = self.starid[0:-1]
                    self.starx = self.starx[0:-1]
                    self.stary = self.stary[0:-1]
                    self.nstars = self.nstars - 1
                self.update_twodimage(update=True)
            rad2.append(float(larr[4]))
        elif rtype[i] == 'circle':
            xcen.append(float(larr[1]))
            ycen.append(float(larr[2]))
            rad.append(float(larr[3]))
            rad2.append(float(larr[3] * numpy.sqrt(2)))
        else:
            print "Error: region type is not recognized (or possibly you are specifying an unrecognized coordinate system)"
        if float(rad2[i]) > float(rad[i]):
            outerrad = rad2[i]
        else: 
            outerrad = float(rad[i])*numpy.sqrt(2)
#        subimage = image[:,ycen[i]-rad[i]:ycen[i]+rad[i],xcen[i]-rad[i]:xcen[i]+rad[i]]
        subimage = image[:,ycen[i]-outerrad:ycen[i]+outerrad,xcen[i]-outerrad:xcen[i]+outerrad]
#        center = PyGuide.centroid(subimage[0],None,None,[outerrad,outerrad],rad[i],ccdinf)
        center = PyGuide.centroid(subimage[0],None,None,[rad[i],rad[i]],rad[i],ccdinf,thresh=1,verbosity=0,smooth=0)
        innerradius = PyGuide.starShape(subimage[0],None,center.xyCtr,rad[i]).fwhm
        outerradius = innerradius * numpy.sqrt(2)
        if center.isOK:
            (newxcen,newycen)=center.xyCtr
#            print "%s  %s" % (str(center.xyCtr),str(center.xyErr))
        else: 
            print "Error: %s.  Using the point you selected instead of the star center." % str(center.msgStr)
            (newxcen,newycen)=[outerrad,outerrad]
        inner = core(subimage,newxcen,newycen,innerradius)
        equalarea = core(subimage,newxcen,newycen,outerradius) - inner
        vspec = inner - equalarea
        for j in xrange(1,vspec.shape[0]):
            print "%f %f" % (j,vspec[j]) 
        break
        i=i+1
Esempio n. 8
0
                actCtr = numpy.random.uniform(
                    -fwhm / 2.0, fwhm / 2.0, size=(2, )) + nomCtr

                cleanData = PyGuide.FakeData.fakeStar(imShape, actCtr, sigma,
                                                      ampl)
                data = PyGuide.FakeData.addNoise(
                    data=cleanData,
                    sky=Sky,
                    ccdInfo=CCDInfo,
                )

                ctrData = PyGuide.centroid(
                    data=data,
                    mask=mask,
                    satMask=None,
                    xyGuess=nomCtr,
                    rad=fwhm * 3.0,
                    ccdInfo=CCDInfo,
                    thresh=Thresh,
                    doSmooth=DoSmooth,
                )
                if not ctrData.isOK:
                    print "%s   %s  %s  NaN NaN NaN NaN NaN NaN NaN %s  %r" % (
                        fwhm,
                        ampl,
                        maskWidth,
                        ctrData.rad,
                        ctrData.msgStr,
                    )
                    nBad += 1
                    continue
    for y in range(grid_height):
        for x in range(grid_width):
            badMask[y][x] = mask[y][x][t]
	    for i in range(integration_time):
                pltmat[y][x]+=flux_cube[y][x][int(t*integration_time+i)]/integration_time
    map.ax = map.fig.add_subplot(111)
    map.ax.set_title('Object 1')
    map.ax.matshow(pltmat,cmap = plt.cm.gray, origin = 'lower')
    map.connect()
    plt.show()
    try:
    	xyguess = map.xyguess
    except AttributeError:
	pass
    print 'Guess = ' + str(xyguess)
    pyguide_output = pg.centroid(pltmat,badMask,satMask,xyguess,3,ccd,0,False)
    try:
        xycenter = [float(pyguide_output.xyCtr[0]),float(pyguide_output.xyCtr[1])]
        print 'Calculated = ' + str((xycenter))
    except TypeError:
        print 'Cannot centroid, using guess'
        xycenter = xyguess
    
    map = MouseMonitor()
    map.fig = plt.figure()
    pltmat = np.zeros((grid_height,grid_width))
    for y in range(grid_height):
        for x in range(grid_width):
	    for i in range(integration_time):
                pltmat[y][x]+=flux_cube[y][x][int(t*integration_time+i)]/integration_time
    map.ax = map.fig.add_subplot(111)
Esempio n. 10
0
def doCentroid(
    imName = None,
    maskName = None,
    satMaskName = None,
    xyGuess = None,
    invertMask = False,
    **kargs
):
    """Centroid and shape-fit a star
    
    Inputs:
    - all the arguments for loadFiles plus most values shown by showDef
    """
    global im, imFits, mask, maskFits, satMask, satMaskFits, isSat, sd
    im, mask, satMask = loadFiles(imName, maskName, satMaskName, invertMask)
    if xyGuess is None:
        print("xyGuess is required")
        return
    
    # check keyword arguments
    for paramName in kargs:
        if paramName not in CentroidParamNames:
            raise RuntimeError("Invalid argument: %s" % (paramName,))
    
    # fill in defaults
    globalDict = globals()
    for paramName in CentroidParamNames:
        if paramName not in kargs:
            kargs[paramName] = globalDict[paramName]
    
    # split off ccd info
    ccdInfoDict = {}
    for paramName in CCDInfoNames:
        ccdInfoDict[paramName] = kargs.pop(paramName)
    ccdInfo = PyGuide.CCDInfo(**ccdInfoDict)
    
    if kargs["rad"] is None:
        print("rad argument is required because the default is presently None")
        return
    
    verbosity = kargs["verbosity"]
    
    # centroid
    ctrData = PyGuide.centroid(
        data = im,
        mask = mask,
        satMask = satMask,
        xyGuess = xyGuess,
        ccdInfo = ccdInfo,
    **kargs)

    if not ctrData.isOK:
        print("centroid failed:", ctrData.msgStr)
        return

    shapeData = PyGuide.starShape(
        data = im,
        mask = mask,
        xyCtr = ctrData.xyCtr,
        rad = ctrData.rad,
        verbosity = verbosity,
    )
    # print results
    printStarHeader()
    printStarData(ctrData, shapeData)

    if not shapeData.isOK:
        print("starShape failed:", shapeData.msgStr)
            for ii in range(NumTries):
                xyCtr = numpy.random.uniform(-fwhm/2.0, fwhm/2.0, size=(2,)) + nomCtr

                cleanData = PyGuide.FakeData.fakeStar(imShape, xyCtr, sigma, ampl)
                data = PyGuide.FakeData.addNoise(
                    data = cleanData,
                    sky = Sky,
                    ccdInfo = CCDInfo,
                )
                
                if DoCentroid:
                    ctrData = PyGuide.centroid(
                        data = data,
                        mask = mask,
                        satMask = None,
                        xyGuess = nomCtr,
                        rad = fwhm * 3.0,
                        ccdInfo = CCDInfo,
                        thresh = Thresh,
                    )
                    if not ctrData.isOK:
                        print "%.1f %.1f    %.1f    %.2f    %.2f    %.2f    NaN NaN NaN NaN NaN NaN NaN NaN NaN %r" % (
                            fwhm, ampl, bkgnd,
                            xyCtr[0], xyCtr[1], maskWidth,
                            ctrData.msgStr,
                        )
                        nBadCtr += 1
                        continue
                else:
                    ctrData = PyGuide.CentroidData(
                        isOK = True,
Esempio n. 12
0
"""it's a test, ok?
"""

import pyfits
import numpy
import PyGuide

import autoPhot
from autoPhot.config import flareCam

ccdInfo = PyGuide.CCDInfo(0, flareCam.readNoise, flareCam.ccdGain)
img = pyfits.open('/Users/csayres/data/arcsat/GJ1243/gFilter/oneNight/ccs20120520.00001139.LUMINANCE.FIT')
data = img[0].data
img.close()
coord1 = numpy.array([197.66827757,  209.33221882])
coord2 = numpy.array([ 343.39379969,  210.25893067])
cent1 = PyGuide.centroid(data, None, None, coord1, rad = 2, #pixels
            ccdInfo = ccdInfo)
cent2 = PyGuide.centroid(data, None, None, coord2, rad = 2, #pixels
            ccdInfo = ccdInfo)
diff1 =

Esempio n. 13
0
def muse_combine(pixtab,cubes,wcslist,lmin=4600,lmax=10000):


    """ 
    Take a list of reduced pixel table and cubes and combine them. 
   
    pixtab   = reduced pixel table for alignment  
    wcslist  = list of ra dec of bright sources in the field for centroid
               that can be used for relative source alignment. 
    cubes    = reduced cubes, which are not directly combined, but they are used to compute alignemnt 
    lmin,lmax = min max wave interval for combining 

    Make sure filter list is in working directory

    """
    
    import astropy 
    from astropy.table import Table
    from astropy.io import fits
    import PyGuide
    import numpy as np
    from astropy import wcs
    from astropy.coordinates import SkyCoord
    import subprocess

    #load the wcs
    wcstab = Table.read(wcslist,format='ascii')

    raoff=[]
    decoff=[]

    #loop over the pixel table to compute the offsets
    for cb in cubes:
        
        print "Processing cube {} for offsets".format(cb)

        #project a cube
        header=''
        fov=project_cube(cb,[4800,8000],False)
        
        #load the wcs
        w = wcs.WCS(fov['header'])
        
        raoffcurrent=[]
        decoffcurrent=[]
        
        #loop over reference stars 
        for sr in range(len(wcstab)):

            #go to pixels 
            pix = w.wcs_world2pix(wcstab['col1'][sr],wcstab['col2'][sr],0,1)
            #centroid
            ccd=PyGuide.CCDInfo(0,0,1)
            centroid=PyGuide.centroid(fov["img"],None,None,[pix[0],pix[1]],20,ccd)
            #back to ra/dec
            if centroid.isOK: 
                coord = w.wcs_pix2world(centroid.xyCtr[0],centroid.xyCtr[1],0,1)
                raoffcurrent.append(coord[0]-wcstab['col1'][sr])
                decoffcurrent.append(coord[1]-wcstab['col2'][sr])
                
        #stack offsets
        thisdra=np.mean(np.array(raoffcurrent))
        thisdde=np.mean(np.array(decoffcurrent))
        raoff.append(thisdra)
        decoff.append(thisdde)

        print "Offsets for this cube RA: {} Dec: {}".format(thisdra,thisdde)
                                                            

    #print offsets
    print "All Delta RA ", raoff
    print "All Delta Dec ", decoff

    rastring = ','.join(str(e) for e in raoff)
    decstring = ','.join(str(e) for e in decoff)

    #now prepare script for stacking and run the pipeline 
    sof=open("combine.sof","w")
    for pxtb in pixtab:
        sof.write(pxtb+' PIXTABLE_REDUCED\n') 
    sof.write('filter_list.fits FILTER_LIST') 
    sof.close()

    #Write the command file 
    scr=open("make_combine.sh","w")
    scr.write('MUSE_XCOMBINE_RA_OFFSETS="'+rastring+'"\n')
    scr.write('MUSE_XCOMBINE_DEC_OFFSETS="'+decstring+'"\n')
    scr.write("esorex --log-file=exp_combine.log muse_exp_combine --lambdamin={0:f} --lambdamax={1:f} combine.sof".format(lmin,lmax))
    scr.close()
    
    #Run pipeline 
    subprocess.call(["sh", "make_combine.sh"])
    
    return
Esempio n. 14
0
    cleanData = PyGuide.FakeData.fakeStar(arrShape, actCtr, sigma, ampl)
    numpy.random.seed(1)
    data = PyGuide.FakeData.addNoise(
        cleanData,
        sky = Sky,
        ccdInfo = CCDInfo,
    )

    print("\nactual center = %6.2f, %6.2f, sigma = %.2f, scanRad = %d" % (actCtr[0], actCtr[1], sigma, scanRad))
    mask = None
    ctrData = PyGuide.centroid(
        data = data,
        mask = mask,
        satMask = None,
        xyGuess = xyGuess,
        rad = scanRad,
        ccdInfo = CCDInfo,
        doSmooth = DoSmooth,
    )
    
    if not ctrData.isOK:
        print("centroid failed: %s" % (ctrData.msgStr,))
        continue
    
    measCtr = ctrData.xyCtr
    nCounts = ctrData.counts
    nPts = ctrData.pix
    print("meas err   = %6.2f, %6.2f; est err = %.2f, %.2f; nCounts = %.0f; nPts = %d" %
        (measCtr[0] - actCtr[0], measCtr[1] - actCtr[1], ctrData.xyErr[0], ctrData.xyErr[1], nCounts, nPts))
    mask = numpy.zeros(arrShape, numpy.bool)
    def performCentroiding(self):
        '''
        # Function for converting arcseconds to radians.
        def arcsec_to_radians(total_arcsec):
            total_degrees = total_arcsec/3600.0
            total_radians = total_degrees*d2r
            return total_radians

        # Function for converting radians to arcseconds.
        def radians_to_arcsec(total_radians):
            total_degrees = total_radians*r2d
            total_arcsec = total_degrees*3600.0
            return total_arcsec

        print 'Not currently implemented...'

        d2r = np.pi/180.0
        r2d = 180.0/np.pi

        # Load data out of display stack h5 file
        centroid_RA = self.headerInfo[self.headerTitles.index('RA')]
        centroid_DEC = self.headerInfo[self.headerTitles.index('Dec')]
        original_lst = self.headerInfo[self.headerTitles.index('lst')]
        exptime = self.headerInfo[self.headerTitles.index('exptime')]
        integrationTime = self.headerInfo[self.headerTitles.index('integrationTime')]
        deadPixelFilename = self.headerInfo[self.headerTitles.index('deadPixFileName')]
        HA_offset = self.headerInfo[self.headerTitles.index('HA_offset')]
        nRow = self.headerInfo[self.headerTitles.index('nRow')]
        nCol = self.headerInfo[self.headerTitles.index('nCol')]

        centroid_RA_radians = ephem.hours(centroid_RA).real
        centroid_RA_arcsec = radians_to_arcsec(centroid_RA_radians)
    
        centroid_DEC_radians = ephem.degrees(centroid_DEC).real
        centroid_DEC_arcsec = radians_to_arcsec(centroid_DEC_radians)
    
        original_lst_radians = ephem.hours(original_lst).real
        original_lst_seconds = radians_to_arcsec(original_lst_radians)/15.0

        '''

        # Load up dead pixel mask.  Invert for PyGuide format.
        #deadFile = np.load(self.deadPixelFilename)
        #deadMask = deadFile['deadMask']
        #deadMask = -1*deadMask + 1
        
        # Saturated pixels already taken care of by hot pixel code.
        satMask = np.zeros((46,44))

        # Specify CCDInfo (bias,readNoise,ccdGain,satLevel)
        ccd = pg.CCDInfo(0,0.00001,1,2500)

        # Initialize arrays that will be saved in h5 file. 1 array element per centroid frame.
        timeList=[]
        xPositionList=[]
        yPositionList=[]
        hourAngleList=[]
        flagList=[]
    
        flag=0
    
        print 'Centroiding a total of ' + str(self.totalFrames) + ' frames...'

        for iFrame in range(self.totalFrames):
            apertureRadius = self.apertureRadii[iFrame]
            image = np.array(self.stackData[:,:,iFrame])
            nanMask = np.isnan(image)
            image[nanMask] = 0.
        
            deadMask = np.zeros((self.nRow,self.nCol))
            deadMask[np.where(image==0)] = 1

            xyguess = np.array(self.centerPositions[iFrame])
            pyguide_output = pg.centroid(image,deadMask,satMask,xyguess,apertureRadius,ccd,0,False,verbosity=2, doDS9=True)  
             # Use PyGuide centroid positions, if algorithm failed, use xy guess center positions instead
            print pyguide_output
            try:
                xycenter = [float(pyguide_output.xyCtr[0]),float(pyguide_output.xyCtr[1])]
                print 'Frame ' + str(iFrame) +': Calculated [x,y] center = ' + str((xycenter)) + '.'
                flag = 0
            except TypeError:
                print 'Cannot centroid frame' + str(iFrame) + ', using guess instead'
                xycenter = xyguess
                flag = 1


            # Calculate lst for a given frame, at midpoint of frame
            current_lst_seconds = self.original_lst_seconds + (iFrame+0.5)*self.integrationTime
            current_lst_radians = self.arcsec_to_radians(current_lst_seconds*15.0)
            # Calculate hour angle for a given frame. Include a constant offset for instrumental rotation.
            HA_variable = current_lst_radians - self.centroid_RA_radians
            HA_static = self.HA_offset*self.d2r
            HA_current = HA_variable + HA_static
            # Make lists to save to h5 file
            timeList.append((iFrame+0.5)*self.integrationTime)
            xPositionList.append(xycenter[0])
            yPositionList.append(xycenter[1])
            hourAngleList.append(HA_current)
            flagList.append(flag)

        self.objectIdentifier = self.loadStackName[0:self.loadStackName.index('ImageStacks/ImageStack_')]
        self.obsIdentifier = self.loadStackName[self.loadStackName.rindex('ImageStacks/ImageStack_') + len('ImageStacks/ImageStack_'):-3]
        fullCentroidListFileName = self.objectIdentifier + 'CentroidLists/Centroid_' + self.obsIdentifier + '.h5'
        print 'Saving to ' + fullCentroidListFileName

        # Write data to new h5 file
        centroidListFile = tables.openFile(fullCentroidListFileName,mode='w')

        centroidHeaderGroupName = 'header'
        centroidHeaderTableName = 'header'
        centroidDataGroupName = 'centroidlist'


        centroidDataGroup = centroidListFile.createGroup(centroidListFile.root,centroidDataGroupName,'Table of times, x positions, y positions, hour angles, and flags')
    

        #paramstable = tables.Array(centroidgroup,'params', object=paramsList, title = 'Object and array params')
        timestable = tables.Array(centroidDataGroup,'times',object=timeList,title='Times at which centroids were calculated')
        xpostable = tables.Array(centroidDataGroup,'xPositions',object=xPositionList,title='X centroid positions')
        ypostable = tables.Array(centroidDataGroup,'yPositions',object=yPositionList,title='Y centroid positions')
        hatable = tables.Array(centroidDataGroup,'hourAngles',object=hourAngleList,title='Hour angles at specified times')
        flagtable = tables.Array(centroidDataGroup,'flags',object=flagList,title='Flags whether or not guess had to be used, 1 for guess used')


        # Should probably just copy original header information over, more info this way!!!
        centroidHeaderGroup = centroidListFile.createGroup("/", centroidHeaderGroupName, 'Header')
        centroidHeaderTable = centroidListFile.createTable(centroidHeaderGroup, centroidHeaderTableName, DisplayStack.DisplayStack.headerDescription,
                                            'Header Info')


        centroidHeader = centroidHeaderTable.row

        for iItem in range(len(self.headerInfo)):
            centroidHeader[self.headerTitles[iItem]] = self.headerInfo[iItem]

        centroidHeader.append()

        centroidListFile.flush()
        centroidListFile.close()
  
        print 'Done performing centroiding...'
Esempio n. 16
0
def doCentroid(imName=None,
               maskName=None,
               satMaskName=None,
               xyGuess=None,
               invertMask=False,
               **kargs):
    """Centroid and shape-fit a star
    
    Inputs:
    - all the arguments for loadFiles plus most values shown by showDef
    """
    global im, imFits, mask, maskFits, satMask, satMaskFits, isSat, sd
    im, mask, satMask = loadFiles(imName, maskName, satMaskName, invertMask)
    if xyGuess is None:
        print("xyGuess is required")
        return

    # check keyword arguments
    for paramName in kargs:
        if paramName not in CentroidParamNames:
            raise RuntimeError("Invalid argument: %s" % (paramName, ))

    # fill in defaults
    globalDict = globals()
    for paramName in CentroidParamNames:
        if paramName not in kargs:
            kargs[paramName] = globalDict[paramName]

    # split off ccd info
    ccdInfoDict = {}
    for paramName in CCDInfoNames:
        ccdInfoDict[paramName] = kargs.pop(paramName)
    ccdInfo = PyGuide.CCDInfo(**ccdInfoDict)

    if kargs["rad"] is None:
        print("rad argument is required because the default is presently None")
        return

    verbosity = kargs["verbosity"]

    # centroid
    ctrData = PyGuide.centroid(data=im,
                               mask=mask,
                               satMask=satMask,
                               xyGuess=xyGuess,
                               ccdInfo=ccdInfo,
                               **kargs)

    if not ctrData.isOK:
        print("centroid failed:", ctrData.msgStr)
        return

    shapeData = PyGuide.starShape(
        data=im,
        mask=mask,
        xyCtr=ctrData.xyCtr,
        rad=ctrData.rad,
        verbosity=verbosity,
    )
    # print results
    printStarHeader()
    printStarData(ctrData, shapeData)

    if not shapeData.isOK:
        print("starShape failed:", shapeData.msgStr)