def __init__(self, imagename, *args, **kwargs): """ Constructor Keyword arguments: imagename -- Str to casa image of primary beam """ super(MSPrimaryBeamModel, self).__init__(*args, **kwargs) self.imagename = imagename try: from taskinit import ia ia.open(imagename) self.cs = ia.coordsys() self.nx = ia.shape()[0] self.ny = ia.shape()[1] self.refpix_x = self.cs.referencepixel()['numeric'][0] self.refpix_y = self.cs.referencepixel()['numeric'][1] self.increment_x = self.cs.increment()['numeric'][0] self.increment_y = self.cs.increment()['numeric'][1] try: self.frequencyaxis = self.cs.findaxisbyname('frequency') self.nu0 = self.cs.referencevalue()['numeric'][ self.frequencyaxis] except Exception: self.nu0 = None print('Some stuff!') self.data = ia.getregion()[:, :, 0, 0] ia.done() except ImportError: from pyrap.images import image im = image(imagename) self.nx = im.shape()[-1] self.nx = im.shape()[-2] self.cs = im.coordinates() self.cs_dir = self.cs.get_coordinate('direction') self.refpix_x = self.cs_dir.get_referencepixel()[1] self.refpix_y = self.cs_dir.get_referencepixel()[0] self.increment_x = self.cs_dir.get_increment()[1] self.increment_y = self.cs_dir.get_increment()[0] try: self.nu0 = self.cs.get_coordinate( 'spectral').get_referencevalue() except Exception: self.nu0 = None print( 'Warning! No frequency information in primary beam model.') self.data = im.getdata()[0, 0]
def _getPixelCoords1ImSimpleProj(coords, imagename): from taskinit import ia from interval import interval ia.open(imagename) cs = ia.coordsys() imshape = ia.shape() ia.done() pixcoords = [] for coord in coords: p = cs.convert(coordin=[coord.x, coord.y, 0, 0], absin=[True] * 4, unitsin=[coords.unit, coords.unit, 'pix', 'pix'], absout=[True] * 4, unitsout=['pix'] * 4) x = p[0] y = p[1] if x in interval[0, imshape[0] - 1] and y in interval[0., imshape[1] - 1]: c = Coord(x, y) try: c.index = coord.index except AttributeError: pass pixcoords.append(c) return pixcoords
def maxfit_iter(imgfiles, box, imidx): from taskinit import ia, rg try: from astropy.io import fits as pyfits except: try: import pyfits except ImportError: raise ImportError( 'Neither astropy nor pyfits exists in this CASA installation') img = imgfiles[imidx] try: if (not ia.open(img)): raise Exception, "Cannot create image analysis tool using " + img print('Processing image: ' + img) hdr = pyfits.getheader(img) pols = DButil.polsfromfitsheader(hdr) freqs = DButil.freqsfromfitsheader(hdr) ndx, ndy, nchans, npols = ia.shape() blc, trc = [0, 0], [ndx, ndy] if 'box' in locals(): if box != '': blc[0], blc[1], trc[0], trc[1] = [ int(ll) for ll in box.split(',') ] results = {} for itpp in pols: results[itpp] = {'results': {}, 'converged': []} for ll in range(nchans): for pp, itpp in enumerate(pols): comp = 'component{}'.format(ll) r = rg.box(blc=[blc[0], blc[1], ll, pp], trc=[trc[0], trc[1], ll, pp]) iachan = ia.subimage(region=r, dropdeg=True) try: result_dict = iachan.maxfit(point=True, negfind=False) result_dict['component0']['converged'] = True result_dict['component0']['flux']['polarisation'] = itpp result_dict['component0']['spectrum']['frequency']['m0'][ 'value'] = float(freqs[ll]) results[itpp]['results'][comp] = result_dict['component0'] results[itpp]['converged'].append(True) except: results[itpp]['converged'].append(False) results[itpp]['results']['nelements'] = results[itpp]['results'].keys() # update timestamp timstr = hdr['date-obs'] return [True, timstr, img, results] except Exception, instance: casalog.post(str('*** Error in imfit ***') + str(instance)) # raise instance return [False, timstr, img, {}]
def _getPixelCoords1Im(coords, imagename): from interval import interval import math try: from taskinit import ia ia.open(imagename) cs = ia.coordsys() Nx = ia.shape()[0] Ny = ia.shape()[1] ia.done() x0 = cs.referencevalue()['numeric'][0] y0 = cs.referencevalue()['numeric'][1] x_pix_ref = cs.referencepixel()['numeric'][0] y_pix_ref = cs.referencepixel()['numeric'][1] x_pix_inc = cs.increment()['numeric'][0] y_pix_inc = cs.increment()['numeric'][1] # If we fail to load ia, we will use pyrap instead. # This probably means stacker was loaded from outside casapy. except ImportError: from pyrap.images import image im = image(imagename) cs = im.coordinates().get_coordinate('direction') dir_axis_index = im.coordinates().get_axes().index(cs.get_axes()) imshape = im.shape() try: x_axis_index = cs.get_axes().index('Right Ascension') except ValueError: raise ValueError('Could not find direction coordinate: '\ 'RightAscension') try: y_axis_index = cs.get_axes().index('Declination') except ValueError: raise ValueError('Could not find direction coordinate: '\ 'Declination') Nx = im.shape()[dir_axis_index + x_axis_index] Ny = im.shape()[dir_axis_index + y_axis_index] x0 = cs.get_referencevalue()[x_axis_index] y0 = cs.get_referencevalue()[y_axis_index] x_pix_ref = cs.get_referencepixel()[x_axis_index] y_pix_ref = cs.get_referencepixel()[y_axis_index] x_pix_inc = cs.get_increment()[x_axis_index] y_pix_inc = cs.get_increment()[y_axis_index] pixcoords = [] for coord in coords: dx = (coord.x - x0) * math.cos(coord.y) dy = math.asin(math.sin(coord.y) / math.cos(dx)) - y0 x = dx / x_pix_inc + x_pix_ref y = dy / y_pix_inc + y_pix_ref if x in interval[0, Nx - 1] and y in interval[0., Ny - 1]: # pixcoords.append(Coord(x,y, coord.weight)) c = Coord(x, y, coord.weight) try: c.index = coord.index except AttributeError: pass pixcoords.append(c) return pixcoords
def _allocate_buffers( imagenames, new_stampsize, nstackpos): import numpy as np try: from taskinit import ia dataread = 'casa' except ImportError: from pyrap.images import image dataread = 'pyrap' global skymap global data global oldimagenames global stampsize global imagesizes if dataread == 'casa': ia.open(imagenames[0]) cs = ia.coordsys() outnchans = ia.boundingbox()['trc'][2]+1 outnstokes = ia.boundingbox()['trc'][3]+1 ia.done() elif dataread == 'pyrap': im = image(imagenames[0]) cs = im.coordinates() outnchans = im.shape()[cs.get_axes().index(cs.get_coordinate('spectral').get_axes())] outnstokes = im.shape()[cs.get_axes().index(cs.get_coordinate('stokes').get_axes())] # To improve performance this module will keep buffers between run. # This following code resets these buffers if they have grown obsolete. if oldimagenames == []: oldimagenames = imagenames if oldimagenames != imagenames: oldimagenames = imagenames skymap = [] data = [] if stampsize == 0: stampsize = new_stampsize elif stampsize != new_stampsize: stampsize = new_stampsize data = [] skymap = [] if not(data == []) and nstackpos != data.shape[0]: data = [] # If there is no data buffer create one. # The data buffer is used to save the right stacking positions before stacking them. # During stacking this is where the full stack will actually be saved. if data == []: data = np.zeros((nstackpos, new_stampsize, new_stampsize, outnstokes, outnchans)) else: data = 0.*data # If there is no skymap buffer create one. # This is the data that is most important to buffer. # Reading a skymap from disk is a time consuming task and we don't want to do this too much. if skymap == []: for imagename in imagenames: if dataread == 'casa': ia.open(imagename) skymap.append(ia.getregion()) ia.done() elif dataread == 'pyrap': buff = im.getdata() dir_axis = cs.get_axes().index(cs.get_coordinate('direction').get_axes()) x_axis = dir_axis+cs.get_coordinate('direction').get_axes().index('Right Ascension') y_axis = dir_axis+cs.get_coordinate('direction').get_axes().index('Declination') specax = cs.get_axes().index(cs.get_coordinate('spectral').get_axes()) stokesax = cs.get_axes().index(cs.get_coordinate('stokes').get_axes()) axis_order = [x_axis, y_axis, stokesax, specax] for i in range(len(axis_order)-1): if axis_order[i] != i: target = axis_order.index(i) origin = i buff = buff.swapaxes(axis_order[origin], axis_order[target]) axis_order[origin], axis_order[target] =\ axis_order[target], axis_order[origin] skymap.append(buff) imagesizes = [] for imagename in imagenames: if dataread == 'casa': ia.open(imagename) imagesizes.append((ia.shape()[0], ia.shape()[1])) ia.done() elif dataread == 'pyrap': dir_axis = cs.get_axes().index(cs.get_coordinate('direction').get_axes()) x_axis_index = dir_axis+cs.get_coordinate('direction').get_axes().index('Right Ascension') y_axis_index = dir_axis+cs.get_coordinate('direction').get_axes().index('Declination') imagesizes.append((im.shape()[x_axis_index], im.shape()[y_axis_index]))
def stack(coords, outfile, stampsize = 32, imagenames= [], method = 'mean', weighting = None, maxmaskradius=None, psfmode = 'point', primarybeam = None): """ Performs stacking in the image domain. coords -- A coordList object of all target coordinates. outfile -- Target name for stacked image. stampsize -- size of target image in pixels imagenames -- Name of images to extract flux from. method -- 'mean' or 'median', will determined how pixels are calculated weighting -- only for method 'mean', if set to None will use weights in coords. maxmaskradius -- allows blanking of centre pixels in weight calculation psfmode -- Allows application of filters to stacking, currently not supported. primarybeam -- only applies if weighting='pb' returns: Estimate of stacked flux assuming point source. """ from ..interval import interval import os import shutil import numpy as np from taskinit import ia, casalog casalog.origin('stacker') casalog.post('#'*42,'INFO') casalog.post('#'*5 + ' {0: <31}'.format("Begin Task: Stacker")+'#'*5, 'INFO') global skymap global data global oldimagenames if coords.coord_type == 'physical': coords = stacker.getPixelCoords(coords, imagenames) # Important that len(coords) here is for the pixel coordinates, not physical! _allocate_buffers(coords.imagenames, stampsize, len(coords)) ia.open(coords.imagenames[0]) cs = ia.coordsys() outnchans = ia.boundingbox()['trc'][2]+1 outnstokes = ia.boundingbox()['trc'][3]+1 ia.done() for imagename in coords.imagenames: ia.open(imagename) if ia.shape()[2] != outnchans or ia.shape()[3] != outnstokes: print('Channels/polarisations do not match in all images! You probably want to stacking do stacking on continuum data and not on spectral cube.') return ia.done() _load_stack(coords, psfmode) if method == 'mean' and weighting == 'sigma2': coords = _calculate_sigma2_weights(coords, maxmaskradius) elif method == 'mean' and weighting == 'sigma': coords = _calculate_sigma_weights(coords, maxmaskradius) elif method == 'mean' and weighting == 'pb': coords = calculate_pb_weights(coords, primarybeam, imagenames) npos = len([c.weight for c in coords if c.weight > 1e-6]) casalog.post('Number of stacking positions: {0}'.format(npos), priority='INFO') stacked_im = _stack_stack(method, coords) _write_stacked_image(outfile, stacked_im, coords.imagenames[0], stampsize) casalog.post('#'*5 + ' {0: <31}'.format("End Task: stacker")+'#'*5) casalog.post('#'*42) return stacked_im[int(stampsize/2), int(stampsize/2),0,0]