Example #1
0
def generate_v_header(hdu, inhead, params):
    """
    """

    today = datetime.datetime.today()

    hdu.header = inhead.copy()

    hdu.header.set('ORIGIN', 'rmsynthesis.py', 'Origin of the data set')
    hdu.header.set('DATE', str(today), 'Date when the file was created')
    hdu.header.set('NAXIS', 3, 'Number of axes in the data array, must be 3')
    hdu.header.set('NAXIS3', params.nu.size, 'Length of the Frequency axis')
    # In FITS, the first pixel is 1, not 0!!!
    hdu.header.set('CRPIX3', 1, 'Reference pixel')
    hdu.header.set('CRVAL3', params.nu[0])
    hdu.header.set('CDELT3', params.dnu)
    hdu.header.add_history('RMSYNTH: Stokes V cube generated by ' +
                           'rmsynthesis.py version ' + str(VERSION) + '.')
    hdu.header.add_history('   WARNING! The frequency axis is not linear. ' +
                           'Look in the')
    hdu.header.add_history('   accompanying _freqlist.txt file for ' +
                           'frequency axis information')

    # Get the reference pixel for the new image
    cpix_ra = (params.ra_lim[1] - params.ra_lim[0]) / 2. + 1.
    cpix_dec = (params.dec_lim[1] - params.dec_lim[0]) / 2. + 1.
    # Get the index of the new reference pixel in the old image
    cpix_ra_old = params.ra_lim[0] + cpix_ra - 1
    cpix_dec_old = params.dec_lim[1] - cpix_dec + 1
    # Find its sky coordinate
    wcs = WCS(inhead)
    if inhead['NAXIS'] == 4:
        crval_ra = wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0, 0]],
                                   0)[0][0]
        crval_dec = wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0, 0]],
                                    0)[0][1]
    if inhead['NAXIS'] == 3:
        crval_ra = wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0]], 0)[0][0]
        crval_dec = wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0]], 0)[0][1]

    hdu.header.set('NAXIS1', params.ra_lim[1] - params.ra_lim[0])
    hdu.header.set('CRVAL1', crval_ra)
    hdu.header.set('CRPIX1', cpix_ra)
    hdu.header.set('NAXIS2', params.dec_lim[1] - params.dec_lim[0])
    hdu.header.set('CRVAL2', crval_dec)
    hdu.header.set('CRPIX2', cpix_dec)

    try:
        hdu.header.__delitem__('NAXIS4')
        hdu.header.__delitem__('CTYPE4')
        hdu.header.__delitem__('CRVAL4')
        hdu.header.__delitem__('CRPIX4')
        hdu.header.__delitem__('CDELT4')
        hdu.header.__delitem__('CUNIT4')
    except:
        pass
Example #2
0
def generate_v_header(hdu, inhead, params):
    """
    """

    today = datetime.datetime.today()

    hdu.header = inhead.copy()

    hdu.header.update('ORIGIN', 'rmsynthesis.py', 'Origin of the data set')
    hdu.header.update('DATE', str(today), 'Date when the file was created')
    hdu.header.update('NAXIS', 3,
                      'Number of axes in the data array, must be 3')
    hdu.header.update('NAXIS3', params.nu.size, 'Length of the Frequency axis')
    # In FITS, the first pixel is 1, not 0!!!
    hdu.header.update('CRPIX3', 1, 'Reference pixel')
    hdu.header.update('CRVAL3', params.nu[0])
    hdu.header.update('CDELT3', params.dnu)
    hdu.header.add_history('RMSYNTH: Stokes V cube generated by ' +
                           'rmsynthesis.py version ' +
                           str(VERSION) + '.')
    hdu.header.add_history('   WARNING! The frequency axis is not linear. ' +
                           'Look in the')
    hdu.header.add_history('   accompanying _freqlist.txt file for ' +
                           'frequency axis information')

    # Get the reference pixel for the new image
    cpix_ra = (params.ra_lim[1] - params.ra_lim[0]) / 2. + 1.
    cpix_dec = (params.dec_lim[1] - params.dec_lim[0]) / 2. + 1.
    # Get the index of the new reference pixel in the old image
    cpix_ra_old = params.ra_lim[0] + cpix_ra - 1
    cpix_dec_old = params.dec_lim[1] - cpix_dec + 1
    # Find its sky coordinate
    wcs = WCS(inhead)
    if inhead['NAXIS'] == 4:
        crval_ra = wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0, 0]], 0)[0][0]
        crval_dec= wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0, 0]], 0)[0][1]
    if inhead['NAXIS'] == 3:
        crval_ra = wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0]], 0)[0][0]
        crval_dec= wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0]], 0)[0][1]

    hdu.header.update('NAXIS1', params.ra_lim[1] - params.ra_lim[0])
    hdu.header.update('CRVAL1', crval_ra)
    hdu.header.update('CRPIX1', cpix_ra)
    hdu.header.update('NAXIS2', params.dec_lim[1] - params.dec_lim[0])
    hdu.header.update('CRVAL2', crval_dec)
    hdu.header.update('CRPIX2', cpix_dec)

    try:
       hdu.header.__delitem__('NAXIS4')
       hdu.header.__delitem__('CTYPE4')
       hdu.header.__delitem__('CRVAL4')
       hdu.header.__delitem__('CRPIX4')
       hdu.header.__delitem__('CDELT4')
       hdu.header.__delitem__('CUNIT4')
    except: pass
def main(srcMaps=None,
         expCube=None,
         binnedExpMap=None,
         outname=None,
         IRFs='CALDB',
         index=2):
    if srcMaps is None:
        srcMaps = env['ccube']
        expCube = env['lvtime']
        binnedExpMap = env['bexpcube']
        outname = env.get('mdlmap',
                          'modelcube.fits').replace('.fits', '_ps.fits')
        IRFs = env.get('irfs', 'CALDB')

    obs = BinnedObs(srcMaps=srcMaps,
                    expCube=expCube,
                    binnedExpMap=binnedExpMap,
                    irfs=IRFs)

    with pyfits.open(srcMaps) as f:
        w = WCS(f[0].header)
        cpix = int(f[0].header['NAXIS1']) / 2
    RA, DEC, e = w.wcs_pix2sky([[cpix, cpix, 0]], 0)[0]

    xmlfile = outname.replace('.fits', '') + '.xml'

    with open(xmlfile, 'w') as f:
        f.write(content_xml % (index, RA, DEC))

    like1 = BinnedAnalysis(obs, xmlfile, optimizer='')
    os.remove(xmlfile)

    print 'creating Model Map...'
    like1.writeModelMap(outname)

    print 'Done!'
Example #4
0
def generate_header(hdu, inhead, params):
    """
    """

    today = datetime.datetime.today()
    hdu.header = inhead.copy()

    hdu.header.set('ORIGIN', 'rmsynthesis.py', 'Origin of the data set')
    hdu.header.set('DATE', str(today), 'Date when the file was created')
    hdu.header.set('NAXIS', 3, 'Number of axes in the data array, must be 3')
    hdu.header.set('NAXIS3', params.nphi, 'Length of the Faraday depth axis')
    hdu.header.set('CTYPE3', 'Phi', 'Axis type')
    hdu.header.set('CUNIT3', 'rad/m/m', 'Axis units')
    # In FITS, the first pixel is 1, not 0!!!
    hdu.header.set('CRPIX3', 1, 'Reference pixel')
    hdu.header.set('CRVAL3', params.phi_min, 'Reference value')
    hdu.header.set('CDELT3', params.dphi, 'Size of pixel bin')

    # Get the reference pixel for the new image
    cpix_ra = (params.ra_lim[1] - params.ra_lim[0]) / 2. + 1.
    cpix_dec = (params.dec_lim[1] - params.dec_lim[0]) / 2. + 1.
    # Get the index of the new reference pixel in the old image
    cpix_ra_old = params.ra_lim[0] + cpix_ra - 1
    cpix_dec_old = params.dec_lim[1] - cpix_dec + 1
    # Find its sky coordinate
    wcs = WCS(inhead)
    if inhead['NAXIS'] == 4:
        crval_ra = wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0, 0]],
                                   0)[0][0]
        crval_dec = wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0, 0]],
                                    0)[0][1]
    if inhead['NAXIS'] == 3:
        crval_ra = wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0]], 0)[0][0]
        crval_dec = wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0]], 0)[0][1]

    hdu.header.set('CRVAL1', crval_ra)
    hdu.header.set('CRPIX1', cpix_ra)
    hdu.header.set('NAXIS1', params.ra_lim[1] - params.ra_lim[0])
    hdu.header.set('CRVAL2', crval_dec)
    hdu.header.set('CRPIX2', cpix_dec)
    hdu.header.set('NAXIS2', params.dec_lim[1] - params.dec_lim[0])

    C2 = 8.98755179e16
    nus = numpy.sort(params.nu)
    dnu = params.dnu
    delta_l2 = C2 * (nus[0]**(-2) - nus[len(nus) - 1]**(-2))
    l2min = 0.5 * C2 * ((nus[len(nus) - 1] + dnu)**(-2) +
                        (nus[len(nus) - 1] - dnu)**(-2))

    rmsf = 2. * math.sqrt(3) / delta_l2
    maxscale = numpy.pi / l2min

    hdu.header.set('TFFWHM', round(rmsf, 2),
                   'Theoretical FWHM of the RMSF ' + ', rad/m/m')
    hdu.header.set('MAXSCL', round(maxscale, 2),
                   'Maximum scale in ' + 'Faraday depth rad/m/m')

    hdu.header.add_history('RMSYNTH: RM Synthesis performed by ' +
                           'rmsynthesis.py version ' + str(VERSION) + '.')
    if params.do_clean:
        hdu.header.add_history('   RM Clean performed. niter=' +
                               str(params.niter) + ', gain=' +
                               str(params.gain) + ', cutoff=' +
                               str(params.cutoff))
    else:
        hdu.header.add_history('   No RM Clean performed.')
    hdu.header.add_history('   See the accompanying _rmsf.txt for ' +
                           'RMSF information.')
    try:
        hdu.header.__delitem__('NAXIS4')
        hdu.header.__delitem__('CTYPE4')
        hdu.header.__delitem__('CRVAL4')
        hdu.header.__delitem__('CRPIX4')
        hdu.header.__delitem__('CDELT4')
        hdu.header.__delitem__('CUNIT4')
    except:
        pass
Example #5
0
def generate_header(hdu, inhead, params):
    """
    """

    today = datetime.datetime.today()
    hdu.header = inhead.copy()

    hdu.header.set('ORIGIN', 'rmsynthesis.py', 'Origin of the data set')
    hdu.header.set('DATE', str(today), 'Date when the file was created')
    hdu.header.set('NAXIS', 3,
                      'Number of axes in the data array, must be 3')
    hdu.header.set('NAXIS3', params.nphi,
                      'Length of the Faraday depth axis')
    hdu.header.set('CTYPE3', 'Phi', 'Axis type')
    hdu.header.set('CUNIT3', 'rad/m/m', 'Axis units')
    # In FITS, the first pixel is 1, not 0!!!
    hdu.header.set('CRPIX3', 1, 'Reference pixel')
    hdu.header.set('CRVAL3', params.phi_min, 'Reference value')
    hdu.header.set('CDELT3', params.dphi, 'Size of pixel bin')
    
    # Get the reference pixel for the new image
    cpix_ra = (params.ra_lim[1] - params.ra_lim[0]) / 2. + 1.
    cpix_dec = (params.dec_lim[1] - params.dec_lim[0]) / 2. + 1.
    # Get the index of the new reference pixel in the old image
    cpix_ra_old = params.ra_lim[0] + cpix_ra - 1
    cpix_dec_old = params.dec_lim[1] - cpix_dec + 1
    # Find its sky coordinate
    wcs = WCS(inhead)
    if inhead['NAXIS'] == 4:
        crval_ra = wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0, 0]], 0)[0][0]
        crval_dec= wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0, 0]], 0)[0][1]
    if inhead['NAXIS'] == 3:
        crval_ra = wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0]], 0)[0][0]
        crval_dec= wcs.wcs_pix2sky([[cpix_ra_old, cpix_dec_old, 0]], 0)[0][1]

    hdu.header.set('CRVAL1', crval_ra)
    hdu.header.set('CRPIX1', cpix_ra)
    hdu.header.set('NAXIS1', params.ra_lim[1] - params.ra_lim[0])
    hdu.header.set('CRVAL2', crval_dec)
    hdu.header.set('CRPIX2', cpix_dec)
    hdu.header.set('NAXIS2', params.dec_lim[1] - params.dec_lim[0])

    C2 = 8.98755179e16
    nus = numpy.sort(params.nu)
    dnu = params.dnu
    delta_l2 = C2 * (nus[0] ** (-2) - nus[len(nus) - 1] ** (-2))
    l2min = 0.5 * C2 * ((nus[len(nus) - 1] + dnu) ** (-2)
                        + (nus[len(nus) - 1] - dnu) ** (-2))

    rmsf = 2. * math.sqrt(3) / delta_l2
    maxscale = numpy.pi / l2min

    hdu.header.set('TFFWHM', round(rmsf,2), 'Theoretical FWHM of the RMSF ' +
        ', rad/m/m')
    hdu.header.set('MAXSCL', round(maxscale, 2), 'Maximum scale in ' +
        'Faraday depth rad/m/m')

    hdu.header.add_history('RMSYNTH: RM Synthesis performed by ' +
                           'rmsynthesis.py version ' + str(VERSION) + '.')
    if params.do_clean:
        hdu.header.add_history('   RM Clean performed. niter=' +
                               str(params.niter) +
                               ', gain=' + str(params.gain) + ', cutoff=' +
                               str(params.cutoff))
    else:
        hdu.header.add_history('   No RM Clean performed.')
    hdu.header.add_history('   See the accompanying _rmsf.txt for ' +
                           'RMSF information.')
    try:
       hdu.header.__delitem__('NAXIS4')
       hdu.header.__delitem__('CTYPE4')
       hdu.header.__delitem__('CRVAL4')
       hdu.header.__delitem__('CRPIX4')
       hdu.header.__delitem__('CDELT4')
       hdu.header.__delitem__('CUNIT4')
    except: pass
Example #6
0
 def dg_coords(self, hdr):
     pw = WCS(header=hdr)
     _x, _y = pw.wcs_pix2sky(self.xlist, self.ylist, 1)
     return zip(list(_x), list(_y))
Example #7
0
 def dg_coords(self,hdr):
     pw = WCS(header=hdr)
     _x, _y = pw.wcs_pix2sky(self.xlist, self.ylist, 1)
     return zip(list(_x), list(_y))
def main(options):
    
    # Some filenames used within the script
    maskedImFile       = 'maskedFD.FITS'
    validPixelFileName = 'validPixelList.txt'
    maskedRMErrMap     = 'maskedRMErrorMap.FITS'
    plotValsFromC      = 'plotPoints.txt'
    
    # Remove all temp files from previous execution
    print 'INFO: Cleaning up the workspace'
    os.system('rm {} {} {} {}'.format(maskedImFile, validPixelFileName, maskedRMErrMap, plotValsFromC))
    
    if options.fdImage == '':
        raise Exception('Faraday Depth image was not specified.')
    if options.rmError == '':
        raise Exception('An RM Error map must be specified.')
    if options.threshold == '' or options.polInt == '':
        print 'INFO: A valid mask was not specified.'
        print 'INFO: All pixels will be included for computing structure function.'
        # Read in the Faraday depth image
        try: 
            fdImage = pf.open(options.fdImage)
            errImage= pf.open(options.rmError)
        except: raise Exception('Unable to read the input image.')
        fdArray = np.squeeze(fdImage[0].data)
        errArray= np.squeeze(errImage[0].data)
        header  = fdImage[0].header
        fdImage.close()
        # Loop over each pixel and get the sky coordinates
        wcs     = WCS(header)
        decSize, raSize = fdArray.shape
        tempRA = []; dec = []; RM = []; errRM = []
        for j in range(raSize):
            for i in range(decSize):
            	# Do not include blanked pixels. Pywcs reads them as nan
            	if str(fdArray[i,j]) == 'nan': continue
            	else:
                    tempRA.append(wcs.wcs_pix2sky([[j,i,0]], 0)[0][0])
                    dec.append   (wcs.wcs_pix2sky([[j,i,0]], 0)[0][1])
                    RM.append    (fdArray[i,j])
                    errRM.append (errArray[i,j])
        nValidPixels = len(dec)
    else:
        # Use Pol Int image to select valid pixels
        try:
            fdImage = pf.open(options.fdImage)
            iImage  = pf.open(options.polInt)
            errImage= pf.open(options.rmError)
        except: raise Exception('Unable to read the input images')
        fdArray = np.squeeze(fdImage[0].data)
        iArray  = np.squeeze(iImage[0].data)
        errArray= np.squeeze(errImage[0].data)
        header  = fdImage[0].header
        print fdArray.shape
        #Initialize a new array which will be updated as per the mask
        maskedIm= np.squeeze(fdImage[0].data)
        maskerrRM = np.squeeze(errImage[0].data)
        print maskedIm.shape
        # Check if the input images have the same shape
        if fdArray.shape != iArray.shape:
            raise Exception('Input images have different shape')
        wcs    = WCS(header)
        decSize, raSize = fdArray.shape
        tempRA = []; dec = []; RM = []; errRM = []
        nValidPixels = 0
        for j in range(raSize):
            for i in range(decSize):
                if iArray[i,j] < float(options.threshold):
                    maskedIm[i,j] = np.nan
                    maskerrRM[i,j] = np.nan
                elif str(fdArray[i,j]) == 'nan': continue
                else:
                    tempRA.append(wcs.wcs_pix2sky([[j,i,0]], 0)[0][0])
                    dec.append   (wcs.wcs_pix2sky([[j,i,0]], 0)[0][1])
                    RM.append    (fdArray[i,j])
                    errRM.append (errArray[i,j])
                    nValidPixels += 1
        print 'INFO: Selected {:} of {:} pixels'.format(nValidPixels, raSize*decSize)
        # Write out the masked image to disk
        print 'INFO: Writing out the masked to disk'
        hdu = pf.PrimaryHDU(data=maskedIm, header=header)
        hdu.writeto(maskedImFile)
        hdu = pf.PrimaryHDU(data=maskerrRM, header=header)
        hdu.writeto(maskedRMErrMap)
    # If this data set is from WSRT, add 360 to RA
    if options.isWSRT:
        ra = [val+360. for val in tempRA]
    else:
        ra = tempRA
    
    # Write (ra, dec, RM, eRM) to disk
    tempFile = open(validPixelFileName, 'w')
    for i in range(len(ra)):
        tempFile.write('{:.5f} {:.5f} {:.5f} {:.5f}\n'.format(ra[i], dec[i], RM[i], errRM[i]))
    tempFile.close()
    
    # Get the resolution of the input images
    bmaj = float(header['BMAJ'])*3600.
    bmin = float(header['BMIN'])*3600.
    print 'INFO: Resolution of the input image: {:.2f} arcsec by {:.2f} arcsec'.format(bmaj, bmin)
    
    # Pass the pixel list and the number of entries to the C code
    os.system('./computeStructureFunction {:} {:} {} {} {} {}'.format(\
              validPixelFileName, nValidPixels, options.binStart,  \
              options.nBins, options.binSize, plotValsFromC))

    # Read the plot points returned by C
    xVal = []; diffVal = []; rmVal = []; eRMVal = []
    for line in open(plotValsFromC, "r"):
    	xVal.append   (float(line.split()[0]))
    	rmVal.append  (float(line.split()[1]))
    	eRMVal.append (float(line.split()[2]))
    xVal   = np.asarray(xVal)
    rmVal  = np.asarray(rmVal)
    eRMVal = np.asarray(eRMVal)
    diffVal= np.absolute(np.subtract(rmVal, eRMVal))
    
    # Plot
    plt.plot(xVal, np.log10(diffVal), 'bo', label="My code")
    plt.xlabel('Angular distance (deg)')
    plt.ylabel('Structure function')
    plt.savefig('output.png')
    plt.show()
Example #9
0
w.wcs.crpix = [(nxpix + 1) / 2., (nypix + 1) / 2.]
w.wcs.cdelt = np.array([-delta, delta])
w.wcs.crval = [ra, dec]

w.wcs.ctype = ['RA---%s' % proj, 'DEC--%s' % proj]
w.wcs.equinox = 2000.0

head = w.to_header()

x = np.array([Npix * (i + 0.5) - 0.5 for i in range(nxpix / Npix)])
y = np.array([Npix * (i + 0.5) - 0.5 for i in range(nypix / Npix)])
XX, YY = np.meshgrid(x, y)

NN = nxpix * nypix / Npix**2
RA, DEC = w.wcs_pix2sky(XX.reshape(NN), YY.reshape(NN), 0)
RA = RA.reshape((nxpix / Npix, nypix / Npix))
DEC = DEC.reshape((nxpix / Npix, nypix / Npix))

lockdir = 'tslock'
filedir = 'tsfile'

if not os.path.isdir(lockdir):
    os.mkdir(lockdir)
if not os.path.isdir(filedir):
    os.mkdir(filedir)

if env.get('SKIP') is None or env.get('SKIP') == '':

    for i in range(nxpix / Npix):
        for j in range(nypix / Npix):