Coverage for /home/warp/casa/atejeda/coverage/build/linux-x86_64/python/2.7/__casac__/image : 2%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# This file was automatically generated by SWIG (http://www.swig.org). # Version 2.0.4 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead.
from sys import version_info if version_info >= (2,6,0): def swig_import_helper(): from os.path import dirname import imp fp = None try: fp, pathname, description = imp.find_module('_image', [dirname(__file__)]) except ImportError: import _image return _image if fp is not None: try: _mod = imp.load_module('_image', fp, pathname, description) finally: fp.close() return _mod _image = swig_import_helper() del swig_import_helper else: import _image del version_info try: _swig_property = property except NameError: pass # Python < 2.2 doesn't have 'property'. def _swig_setattr_nondynamic(self,class_type,name,value,static=1): if (name == "thisown"): return self.this.own(value) if (name == "this"): if type(value).__name__ == 'SwigPyObject': self.__dict__[name] = value return method = class_type.__swig_setmethods__.get(name,None) if method: return method(self,value) if (not static): self.__dict__[name] = value else: raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value): return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name): if (name == "thisown"): return self.this.own() method = class_type.__swig_getmethods__.get(name,None) if method: return method(self) raise AttributeError(name)
def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
try: _object = object _newclass = 1 except AttributeError: class _object : pass _newclass = 0
class image(_object): """Proxy of C++ casac::image class""" __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, image, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, image, name) __repr__ = _swig_repr def __init__(self): """__init__(self) -> image""" this = _image.new_image() try: self.this.append(this) except: self.this = this __swig_destroy__ = _image.delete_image __del__ = lambda self : None; def newimage(self, *args, **kwargs): """ newimage(self, infile) -> image
Summary Construct a new image analysis tool using the specified image. (Also known as newimagefromfile.)
Description
This method is identical to ia.newimagefromfile(). The description of how it works is in the online help for that method.
Input Parameters: infile Input image file name
--------------------------------------------------------------------------------
""" return _image.image_newimage(self, *args, **kwargs)
def newimagefromfile(self, *args, **kwargs): """ newimagefromfile(self, infile) -> image
Summary Construct a new image analysis tool using the specified image. (Also known as newimage.)
Description
This method returns an image analysis tool associated with the specified image. Constructing a image analysis tool in addition to the default ia tool allows the user to operate on multiple images without having to close one before opening another. All ia.newimagefrom*() methods share this functionality.
The parameter infile may refer to a CASA image, a Miriad image, or a FITS image. FITS images of types Float, Double, Long, and Short are supported.
When finished with the newly created tool, the user should close it to free up system resources (eg memory).
ia.newimage() is an alias for this method.
Input Parameters: infile Input image file name
Example:
# This is one way to copy a FITS image into an already extant CASA image # of the same shape (ia.subimage() is more effecient, but this example is # meant to demonstrate ia.newimagefromfile()
# note that the ia tool is not attached to an image after the first command, # the fitsimage tool is fitsimage = ia.newimagefromfile('myimage.fits') # now attach the target CASA image to the ia tool ia.open('myimage.im') # copy pixel values ia.putchunk(fitsimage.getchunk()) # copy the coordinate system ia.setcoordsys(fitsimage.coordsys().torecord()) # copy other miscellaneous things ia.setbrightnessunit(fitsimage.getbrightnessunit()) ia.setmiscinfo(fitsimage.miscinfo()) # be sure to call done() on both tools to free up memory ia.done() fitsimage.done()
--------------------------------------------------------------------------------
""" return _image.image_newimagefromfile(self, *args, **kwargs)
def imagecalc(self, *args, **kwargs): """ imagecalc(self, outfile = string(""), pixels = string(""), overwrite = False) -> image
Summary Perform mathematical calculations on an image or images.
Description
This method is used to evaluate a mathematical expression involving existing images. It fully supports both float and complex valued images. The syntax of the expression supplied via the pixels parameter (in what is called the Lattice Expression Language, or LEL) is explained in detail in \htmladdnormallink{note 223}{http://aips2.nrao.edu/docs/notes/223/223.html}. This is a rich mathematical language with allows all manner of mathematical operations to be applied to images.
Any image files embedded in the expression may be native \casa\ or its\ (but not yet Miriad) images.
If successful, this method always returns an image analysis tool that references the image resulting from the calculation. This returned tool should always be captured and closed as soon as the user is done with it to free up system resources (eg, memory). The image analysis tool on which the method is called (eg the ia tool when one runs ia.imagecalc()) remains unaltered, eg it still refers to the same image it did prior to the imagecalc() call.
Values of the returned tool are evaluated 'on demand'. That is, only when a method is run on the returned tool are the necessary values computed. And in fact, the values have to be reevaluated for each operation (method call). This means that there is a small performance hit for using the returned tool rather than the image written to disk and that none of the images which were used in the expression should be deleted while the returned tool is in use because they must be accessed for calculating the expression each time an operation of the returned tool is performed. These limitations do not apply to the ouput image if one is specified with the outfile parameter; it is a genuine CASA image with numerical values. If outfile is blank, no ouput image is written (although the resulting image can still be accessed via the returned image analysis tool as described below).
Normally you should just write the image, close the returned tool, and open the results image with the default ia tool and operate on it. If you are interested in conserving disk space, you don't need to keep the result of the calculation around for very long, and/or you are only going to do a small number of operations on the result image, should you set outfile=''.
Input Parameters: outfile Output image file name. If blank the resulting image is not written, but it can still be accessed via the returned image analysis tool. pixels LEL expression. Must be specified. For example 'myimage1.im + myimage2.im'. overwrite Overwrite (unprompted) pre-existing output file? false
Example:
''' # Suppose aF and bF are images with single precision and we want # to determine the result of the following expression: # aF + min(float($\pi$, mean(bF)) # # In this case, the images aF and bF do not need to have the same shapes and # coordinates, because only the mean(bF) results in the mean of all pixel # values in bF. If aF has single precision pixel values, the resulting image # will as well. This expression first computes the scalar value of the minimum # of $\pi$ and the mean of the pixel values of bF. That scalar is then # added to the value of each pixel in aF. In the code below, the # result is written to image cF which can be accessed immediately # via the returned image analysis tool captured in the variable myim. # If the expression is masked, that mask will be copied to the new image.
# create images of different sizes to operate on ia.fromshape('aF',[10,10],overwrite=true) ia.fromshape('bF',[10,20,30],overwrite=true) # close the ia tool to free up resources ia.done() # at each pixel in bF, take the minimum of that pixel value and pi and add # the resulting value to the corresponding pixel in af # note that only the subset of pixels in bF that correspond to those in aF # are used; the resulting image has the same size as the smaller image, aF, # used in the input myim = ia.imagecalc(outfile='cF', pixels='aF + min(float(pi()), mean(bF))', overwrite=true) # confirm the resulting image has the same size as aF, should be [10, 10] myim.shape() # close the myim tool to free up system resources myim.done() '''
Example:
''' # The following example shows the use of the two min() LEL functions. One takes a # single argument and will return a scalar representing the minimum pixel value # of that entire image. The other takes two arguments (either an image and a # scalar or two images of conforming shapes) and returns an image for which # the minimum has been calculated on a pixel by pixel basis for the input # image(s).
# create an image to operate on ia.fromshape('aF',[10,10],overwrite=true) # give it interesting values ia.addnoise() # free up system resources ia.done() # do the calculation and write results to image cF myim=ia.imagecalc('cF', 'min(aF, (min(aF)+max(aF))/2)', overwrite=true) # do whatever stuff you want with myim and the close it to free # up system resources myim.done() '''
Example:
''' # Here's an example of a more complicated function. Currently # ia.fromshape() only creates real-valued images so the real() # function is not particularly exciting in this case but illustrates # possibilities. Trigonometric functions such as sin() assume the # pixel values are in radians. ia.fromshape('aD',[10,10],overwrite=true) ia.addnoise() ia.fromshape('aF',[10,10],overwrite=true) ia.addnoise() ia.fromshape('bF',[10,10],overwrite=true) ia.addnoise() ia.fromshape('aC',[10,10],overwrite=true) ia.addnoise() ia.done() myim = ia.imagecalc('eF', 'sin(aD)+(aF*2)+min(bF)+real(aC)', overwrite=true) myim.done() '''
--------------------------------------------------------------------------------
""" return _image.image_imagecalc(self, *args, **kwargs)
def collapse(self, *args, **kwargs): """ collapse(self, function = string(""), axes = initialize_variant("0"), outfile = string(""), region = initialize_variant(""), box = string(""), chans = string(""), stokes = string(""), mask = string(""), overwrite = False, stretch = False) -> image
Summary Collapse an image along a specified axis, computing a specified aggregate function of pixels along that axis.
Description
This method collapses an image along a specified axis or set of axes of length N pixels to a single pixel on each specified axis. Both float valued and complex valued images are supported. It computes a user-specified aggregate function for pixel values along the specified axes, and places those values in the single remaining plane of those axes in the output image. The method returns an image analysis tool containing the newly-created collapsed image. Valid choices of aggregate functions are: 'flux' (see below for constraitns), 'max', 'mean', 'median', 'min', 'rms', 'stdev', 'sum' and 'variance'. Minimal unique matching is supported for the function parameter (e.g. function = 'r' will compute the rms of the pixel values, 'med' will compute the median, etc.).
If one specifies function='flux', the following constraints must be true:
1. The image must have a direction coordinate, 2. The image must have at least one beam, 3. The specified axes must be exactly the direction coordinate axes, 4. Only one of the non-directional axes may be non-degenerate, 5. The iamge brightness unit must be conformant with x*yJy/beam, where x is an optional unit (such as km/s for moments images) and y is an optional SI prefix.
Axes may be specified as a single integer or an array of integers indicating the zero-based axes along which to collapse the image. Axes may also be specified as a single or array of strings which minimally and uniquely match (ignoring case) world axis names in the image (e.g. 'dec' for collapsing along the declination axis or ['ri', 'd'] for collapsing along both the right ascension and declination axes).
If outfile is not specified (or contains only whitespace characters), no image is written but the collapsed image is still accessible via the image analysis tool this method always returns (which references the collapsed image). If the returned object is not wanted, it should still be captured and destroyed via its done() method. If this is not done, there is no guarantee as to when the Python garbage collector will delete it. If the returned object is wanted, it should still be deleted as soon as possible for the same reasons, e.g.
collapsed\_image = ia.collapse(...) egin{verbatim} # do things (or not) with the collapsed_image and when finished working with the object, do nd{verbatim} collapsed\_image.done()
The reference pixel of the collapsed axis is set to 0 and its reference value is set to the mean of the the first and last values of that axis in the specified region of the input image. The reference value is the world coordinate value of the reference pixel. For instance, if an axis to be collapsed were to be the frequency axis, in the collapsed image, the reference value would be the mean value of the frequency range spanned, and would be stored in pixel 0.
If the input image has per plane beams, the beam at the origin of the subimage determined by the selected region is arbitrarily made the global beam of the output image. In general, the user should understand the pitfalls of collapsing images with multiple beams (i.e. that employing an aggregate function on pixels with varying beam sizes more often than not leads to ill-defined results). Convolution to a common beam is not performed automatically as part of the preprocessing before the actual rebinning occurs. In such cases, therefore, the user should probably first convolve the input image with a common restoring beam so that each plane has the same resolution, and/or use imsmooth to smooth the data to have the same beam.
Input Parameters: function Aggregate function to apply. This can be set one of flux, max, mean, median, min, rms, stdev, sum, variance. Must be specified. axes Zero-based axis number (specified as a list or integer) along which to collapse the specified image. Default value is 0. 0 outfile Output image file name. If left blank (the default), no image is written but a new image tool referencing the collapsed image is returned. region Region specification. See help par.region for more details. Default setting is to use the full image. box Box to use in position plane specified by four numbers 'blcx, blcy, trcx, trcy' ('bottom/top left/right corner x/y') chans Channels to use. See help par.chans for more details. Channels specified must be contiguous. Default setting is to use all channels. stokes Stokes planes to use. Planes specified must be contiguous. Default setting is to use all Stokes planes. mask Mask to use. See help par.mask for more details. Default setting is none. overwrite Overwrite (unprompted) pre-existing output file? Ignored if 'outfile' is left blank. false stretch Stretch the mask if necessary and possible? See help par.stretch. Default value is False. false
Example:
''' # myimage.im is a 512x512x128x4 (ra,dec,freq,stokes) image ia.open('myimage.im') # collapse a subimage of it along its spectral axis avoiding the 8 edge # channels at each end of the band, computing the mean value of the pixels # resulting image is 256x256x1x4 in size. collapsed = ia.collapse(outfile='collapse_spec_mean.im', function='mean', axes=2, box='127,127,383,383', chans='8~119') # manipulate collapsed collapsed.done()
'''
--------------------------------------------------------------------------------
""" return _image.image_collapse(self, *args, **kwargs)
def decimate(self, *args, **kwargs): """ decimate(self, outfile = string(""), axis = 0, factor = 1, method = string("copy"), region = initialize_variant(""), mask = string(""), overwrite = False, stretch = False) -> image
Summary Remove planes from an image.
Description
This application removes planes along the specified axis of an image. It supports both float valued and complex valued images. The factor parameter represents the factor by which to reduce the number of planes.
The method parameter represents how to calculate the pixel values of the output image. A value of method='copy' means that every factorth plane of the selected region in the input image will be directly copied to the corresponding plane in the output image. So, if one wanted to copy every third spectral plane in the input image to the output image, one would specify factor=3 and method='copy'. If the selected region along the specified axis had 11 planes, then there would be 4 output planes which would map to planes 0, 3, 6, and 9 of the specified region of input image. A value of method='mean' indicates that each of factor number of planes in the range starting at each factorth plane should be averaged to produce the corresponding output plane. So, if one specified factor=3 and method='mean' along an axis of the selected region of the input image which had 11 pixels, the corresponding axis in the output image would have three pixels and the pixel values for each of those output planes would corresponding to averaging along that axis planes 0-2, 3-5, and 6-8 of the selected region of the input image. Note that the remaining planes, 9 and 10, in the selected region of the input image would be ignored because the last interval must have exactly factor number of planes in order to be included in the output image.
The coordinate system of the output image takes into account the decimation; that is, along the decimated axis, the increment of the output image is factor times that of the input image, and the reference pixel of the output image is located at pixel 1/factor times the reference pixel in the input image.
This method returns an image analysis tool which references the output image. If this tool is not desired, one should capture it anyway and then close() it immediately to free up resources.
Images with multiple beams are not supported; please convolve a multi-beam image to a single resolution before running this application.
Input Parameters: outfile Output image file name. If empty, a persistent image is not created. axis Axis along which to remove planes. 0 factor Reduce number of planes by this factor. 1 method Method to use for calculating pixel values of output. Supported values are 'copy' or 'mean'. copy region Region specification. See help par.region for more details. Default setting is to use the full image. mask Mask to use. See help par.mask for more details. Default setting is none. overwrite Overwrite (unprompted) pre-existing output file? Ignored if 'outfile' is left blank. false stretch Stretch the mask if necessary and possible? See help par.stretch. Default value is False. false
Example:
# Copy verbatim every 5th plane of axis 2 of the input image ia.open('myim.im') decimated = ia.decimate('dec1.im', axis=2, factor=5, method='copy') # do stuff with decimated and then close it decimated.close()
# Decimte by averaging every 7 planes of the input image along axis 2 decimated = ia.decimate('dec2.im', axis=2, factor=7, method='mean') # do stuff with decimated and then close it decimated.close()
--------------------------------------------------------------------------------
""" return _image.image_decimate(self, *args, **kwargs)
def imageconcat(self, *args, **kwargs): """ imageconcat(self, outfile = string(""), infiles = initialize_variant(""), axis = -1, relax = False, tempclose = True, overwrite = False, reorder = False) -> image
Summary Construct a casa image by concatenating images
Description
This function is used to concatenate two or more input \casaimages into one output image. For example, if you have two image cubes which are contiguous along one axis (say a spectral axis) and you would like to glue them together along this axis, then this function is the appropriate thing to use.
The axis parameter is used to specify which zero-based axis the images should be concatenated along. A negative value indicates that the spectral axis should be used. If a negative value is given but there is no spectral axis, an exception will be thrown. The zero-based order of the axes of an image can be determined from ia.coordsys().names().
If successful, this method will return an image analysis tool referencing the concatenated image. Even if it is not wanted, the returned tool should be captured and closed as soon as the user is finished with it to free up system resources (eg memory).
If {\stfaf outfile} is given, the image is written to the specified disk file. If {\stfaf outfile} is unset, the on-the-fly Image oolcreated by the function actually references all of the input files. So if you deleted any of the input image disk files, it would render this ool\ useless. When you destroy this tool (with the done function) the reference connections are broken.
The input and output images must be of the same dimensionality. Therefore, if you wish to concatenate 2-D images into a 3-D image, the 2-D images must have a third axis (of length unity) so that the output image coordinates are known along the concatenation axis.
The input images are concatenated in the order in which they are listed unless the reorder parameter is set to True. If True, the images are reordered if necessary so that the world coordinate values along the selected axis monotonically increase or decrease. The direction of the increment is determined by the first listed image. If reorder=True, the world coordinate ranges of the images along the selected axis are not permitted to overlap, and the signs of the increments for this axis in all images must be the same. If reorder=False, the coordinate system of the first listed image is used as the coordinate system for the output image. If reorder=True, the coordinate system of the first image in the list of the reordered images is used as the coordinate system of the output image. Setting reorder=True can be especially useful if the infiles are specified using a wildcard character(s).
If relax=False, the input images are checked to see that they are contiguous along the concatenation axis and an error is generated if they are not. In addition, the coordinate descriptors (e.g. reference pixel, reference value etc) for the non-concatenation axes must be the same or an error will result.
The input disk image files may be in native \casa, its, or Miriad formats.
The contiguous criterion and coordinate descriptor equality criteria can be relaxed by setting {\stfaf relax=T} whereupon only warnings will be issued. Dimension and shape must still be the same though. When the concatenation axis is not contiguous (but still monotonically increasing or decreasing) and {\stfaf relax=T}, a tabular coordinate will be used to correctly describe the axis. But be aware that it means adjacent pixels are not regularly spaced. However, functions like toworld and topixel will correctly interconvert world and pixel coordinates.
In giving the input image names, the {\stfaf infiles} argument can be a single string if you wild card it with standard shell symbols. For example, {\stfaf infiles='cena\_???.*'}, where the ``?'' represents one character and ``*'' any number of characters.
Otherwise, you must input a vector of strings such as {\stfaf infiles='cena1 cena2 cena3'}. An input such as {\stfaf infiles='files1,file2'} will be interpreted as one string naming one file and you will get an error. The reason for this is that although the latter could be parsed to extract two file names by recognizing comma delimiters, it is not possible because an expression such as {\stfaf infiles='cena.\{a,b\}'} (meaning files of name ``cena.a'' and ``cena.b'') would confuse such parsing (you would get two files of name {\sff cena.\{a} and {\sff b\}}.
You can look at the coordinate system of the output image using the ia.summary() tool method to ensure it's correct.
The argument {\stfaf tempclose} is, by default, True. This means that all internal reference copies of the input images are kept closed until they are needed. Then they are opened temporarily and then closed again. This enables you to effectively concatenate as many images as you like without encountering any operating system open file number limits. However, it comes at some performance loss, because opening and closing all those files takes time. If you are concatenating a smallish number of files, you might use {\stfaf tempclose=F}. This will leave all internal reference copies permanently open, but performance, if you don't hit the file limit, will be better.
This method requires multiple images which are specified with the infiles parameter. Therefore calling ia.open() is not necessary, although calling imageconcat() using an already open image analysis tool will work and the state of that tool (eg the image it references) will not be changed.
Input Parameters: outfile Output image file name. Default is unset. infiles List of input \casa\ image files to concatenate; wild cards accepted. Default is empty string. axis Concatenation pixel axis. Use ia.coordsys().names() to get a list of axes. A negative value means use the spectral axis if there is one, if not an exception is thrown. -1 relax Relax constraints that axis coordinate descriptors match false tempclose Keep all lattices closed until needed true overwrite Overwrite (unprompted) pre-existing output file? false reorder Automatically reorder the images if necessary. false
Example:
''' # Create three images to concatenate together. ia.fromshape('im.1',[10,10,10],overwrite=T) ia.fromshape('im.2',[10,10,10],overwrite=T) ia.fromshape('im.3',[10,10,10],overwrite=T) ia.done() # now concatenate. # The three images have the same shape along the axes not to be # concatenated as they must. relax=T means that the contiguity # constraint along the concatenated axis is not imposed (if it were # the call would fail because the spectral axes of the input images # are not contiguous). bigim = ia.imageconcat(outfile='bigimage', infiles='im.1 im.2 im.3', axis=2, relax=T, tempclose=F, overwrite=T) # be sure to call done() on the return tool to free up system resources. bigim.done() '''
Example:
''' # # All images whose file names begin with {\sff im.} that reside in # the current directory are concatenated along the spectral axis if # there is one. All image coordinate descriptors must match. If any # input image does not have a spectral axis an error will # result. Because an oufile is not specified, the returned image analysis # tool captured in the variable named bigim just references the input images; # this call does not create a persistent result image. bigim = ia.imageconcat(infiles='im.*',relax=T) bigim.done() '''
--------------------------------------------------------------------------------
""" return _image.image_imageconcat(self, *args, **kwargs)
def fromarray(self, *args, **kwargs): """ fromarray(self, outfile = string(""), pixels = initialize_variant(""), csys = initialize_record(""), linear = False, overwrite = False, log = True) -> bool
Summary Construct a casa image from a numerical (integer or float) array
Description
This function converts a numerical (integer or float) numpy array of any size and dimensionality into a \casa\ image. It will create both float and complex valued images.
The image analysis tool on which this method is called will reference the created image; if this tool referenced another image before this call, that image will no longer be referenced by the tool after the creation of the new image. If you would rather have a new image analysis tool returned, keeping the one on which this method is called unaltered, use newimagefromarray() instead. If {\stfaf outfile} is given, the image is written to disk, if not, the image tool on which this method was called will reference a temporary image (either in memory or on disk, depending on its size) that will be deleted when the tool is closed.
Float valued images are produced from real-valued arrays. Complex-valued images are produced from complex-valued arrays.
The coordinate system, provided as a coordsys ool converted to a record is optional. If you provide it, it must have the same number of dimensions as the pixels array (see also coordsys). Call the naxes() method on the coordinate system tool to see how many dimensions the coordinate system has. A coordinate system can be created from scratch using the coordinate system (cs) tool and methods therein, but often users prefer to use a coordinate system from an already existing image. This can be gotten using ia.coordsys() which returns a coordinate system tool. A torecord() call on that tool will result in a python dictionary describing the coordinate system which is the necessary format for the csys input parameter of ia.fromarray().
If csys is not specified, a default coordinate system is created. If {\stfaf linear=F} (the default) the created coordinate system will have standard RA/DEC/Stokes/Spectral Coordinate axes depending upon the shape of the {\stfaf pixels} array (Stokes axis must be no longer than 4 pixels and you may find the spectral axis preceding the Stokes axis if say, {\cf shape=[64,64,32,4]}). Extra dimensions are given linear coordinates. If {\stfaf linear=T}, then all the resulting coordinates are linear with the axes represent lengths. In this case each axis will have a value of 0.0 at its center pixel. The increment of each axis will be 1.0 km.
The method returns True if creation of the image was successful, False otherwise, so you can check programmatically if the image creation was successful.
Input Parameters: outfile Output image file name. Default is unset. pixels Numeric array csys Coordinate System. Default is unset. linear Make a linear Coordinate System if csys not given false overwrite Overwrite (unprompted) pre-existing output file? false log Write image creation messages to logger true
Example:
''' # make an image with a default RA/Dec/Stokes/Frequency coordinate system # having all pixels set to 2.5. ary = ia.makearray(v=2.5, shape=[64, 64, 4, 128]) # the ia tool does not need to reference an image in this case (ie open() # need not have been called), if it does reference another image, that reference # will be lost and replaced with a reference to the newly created image. res = ia.fromarray(outfile='test.data', pixels=ary, overwrite=true) if res: # perform operations on the newly created image if desired and make sure # to close it when done to free up system resources (eg memory) ia.shape() ia.done() '''
Example:
'''
# create an image using the coordinate system from another image ia.open('myexistingimage.im')
mycs = ia.coordsys() # the number of dimensions in the array and the coordinate system must # be the same. For this example to work, mycs.naxes() must return 4. ia.done() ary = ia.makearray(v=2.5, shape=[64, 64, 4, 128]) res = ia.fromarray(pixels=ary, csys=mycs.torecord()) mycs.done() if (res): # do things with the newly created temporary image before closing it ia.shape() ia.done()
'''
--------------------------------------------------------------------------------
""" return _image.image_fromarray(self, *args, **kwargs)
def fromascii(self, *args, **kwargs): """ fromascii(self, outfile = string(""), infile = string(""), shape = initialize_vector(1, (int)-1), sep = string(":"), csys = initialize_record(""), linear = False, overwrite = False) -> bool
Summary This function converts a pre-existing ascii file into a casa image.
Description
This function is used to create a \casaimage from a pre-existing ASCII file. You might want to use this if you just want to create a quick image to use to see what various image analysis methods do. The image analysis tool on which the method is called will always reference the created image if this method is successful. Thus, calling open() on that tool is not necessary, but if the tool is already open, referencing another image, that reference will be silently destroyed and replaced with a reference to the image created by fromascii(). If {\stfaf outfile} is given, the image is also written to the specified disk file. If {\stfaf outfile} is unset, the image analysis tool on which this method was called references a temporary image. This temporary image may be in memory or on disk, depending on its size. When you close the image analysis ool\ (with the close function) the temporary image is deleted.
You must specify the shape of the image. The image must be stored in the ascii file. If the shape of the image having N axes is to be [s\_0, s\_1, s\_2, ..., s\_(N-1)], where s\_i is the integral number of pixels along axis number i, the file must have (s\_1 * s\_2 * ... * s\_(N-1)) rows and each row must have s\_0 numerical values delimited by the value specified by the sep parameter, or spaces if sep is not specified. Pixel locations are incremented by row number in such a way that the second axis changes fastest. As an example, say we want to create an image with shape=[3,4,2]. There must be 4*2 = 8 rows in the ascii file, and each row must have 3 space-delimited numerical values. The first row represents values of pixels [0, 0, 0], [1, 0, 0], and [2, 0, 0]. The second row represents values of pixels [0, 1, 0], [1, 1, 0], and [2, 1, 0]. The fifth row represents values of pixels [0, 0, 1], [1, 0, 1], and [2, 0, 1]. The sixth values of pixels [0, 1, 1], [1, 1, 1], and [2, 1, 1,]. And so on.
To further illustrate, say this is our file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
When read with ia.fromascii(), ary = ia.getchunk() would return the following array: ary[0, 0, 0] = 1 ary[1, 0, 0] = 2 ary[2, 0, 0] = 3 ary[0, 1, 0] = 4 ary[1, 1, 0] = 5 ary[2, 1, 0] = 6 ary[0, 2, 0] = 7 ary[1, 2, 0] = 8 ary[2, 2, 0] = 9 ary[0, 3, 0] = 10 ary[1, 3, 0] = 11 ary[2, 3, 0] = 12 ary[0, 0, 1] = 13 ary[1, 0, 1] = 14 ary[2, 0, 1] = 15 ary[0, 1, 1] = 16 ary[1, 1, 1] = 17 ary[2, 1, 1] = 18 ary[0, 2, 1] = 19 ary[1, 2, 1] = 20 ary[2, 2, 1] = 21 ary[0, 3, 1] = 22 ary[1, 3, 1] = 23 ary[2, 3, 1] = 24
The coordinate system, provided as a coordsys { ool} converted to a record with coordsys torecord, is optional. If you provide it, it must be dimensionally consistent with the pixels array you give (see also coordsys).
If you don't provide the coordinate system, a default coordinate system is made for you. If {\stfaf linear=F} (the default) then it is a standard RA/DEC/Stokes/Spectral Coordinate System depending exactly upon the shape of the {\stfaf pixels} array (Stokes axis must be no longer than 4 pixels and you may find the spectral axis coming out before the Stokes axis if say, {\cf shape=[64,64,32,4]}). Extra dimensions are given linear coordinates. If {\stfaf linear=T}, then all axes are linear in the resulting coordinate system.
Input Parameters: outfile Output image file name. Default is unset. infile Input ascii disk file name. Must be specified.. shape Shape of image. Must be specified. -1 sep Separator in ascii file. Default is space character. : csys Coordinate System record from coordsys torecord(). Default is unset. linear Make a linear Coordinate System if csys not given false overwrite Overwrite (unprompted) pre-existing output file? false
Example:
''' # say the above file presented above is stored in a file # named image.txt ia.fromascii(outfile='myimage.im', infile='image.txt', shape=[3,4,2], overwrite=true) # should return [3, 4, 2] ia.shape() # call other ia methods then close the tool ia.done() '''
--------------------------------------------------------------------------------
""" return _image.image_fromascii(self, *args, **kwargs)
def fromfits(self, *args, **kwargs): """ fromfits(self, outfile = string(""), infile = string(""), whichrep = 0, whichhdu = 0, zeroblanks = False, overwrite = False) -> bool
Summary Construct a casa image by conversion from a FITS image file
Description
This function is used to convert a FITS disk image file (Float, Double, Short, Long are supported) to an \casa\ \imagefile. If {\stfaf outfile} is given, the image is written to the specified disk file. If {\stfaf outfile} is unset, the Image ool\ is associated with a temporary image. This temporary image may be in memory or on disk, depending on its size. When you close the Image ool\ (with the close function) this temporary image is deleted.
This function reads from the FITS primary array (when the image is at the beginning of the FITS file; {\stfaf whichhdu=0}), or an image extension (when the image is elsewhere in the FITS file, {\stfaf whichhdu $\>$ 0}).
By default, any blanked pixels will be converted to a mask value which is false, and a pixel value that is NaN. If you set {\stfaf zeroblanks=T} then the pixel value will be zero rather than NaN. The mask will still be set to false. See the function replacemaskedpixels if you need to replace masked pixel values after you have created the image.
Input Parameters: outfile Output image file name. Default is unset. infile Input FITS disk file name. Must be specified. whichrep If this FITS file contains multiple coordinate representations, which one should we read (0-based) 0 whichhdu If this FITS file contains multiple images, which one should we read (0-based). 0 zeroblanks If there are blanked pixels, set them to zero instead of NaN false overwrite Overwrite (unprompted) pre-existing output file? false
Example:
''' # print ' ---- fromfits Ex 1 ----' datapath=pathname+'/data/demo/Images/imagetestimage.fits' ia.fromfits('./myimage', datapath, overwrite=true) print ia.summary() s = ia.miscinfo() print s.keys() # prints any unrecognized field names ia.close() # '''
The FITS image is converted to a \casa\ \imagefile\ and access is provided via the default \imagetool\ called {\stf ia}. Any FITS header keywords which were not recognized or used are put in the miscellaneous information bucket accessible with the miscinfo function. In the example we list the names of the fields in this record.
--------------------------------------------------------------------------------
""" return _image.image_fromfits(self, *args, **kwargs)
def fromimage(self, *args, **kwargs): """ fromimage(self, outfile = string(""), infile = string(""), region = initialize_variant(""), mask = initialize_variant(""), dropdeg = False, overwrite = False) -> bool
Summary Construct a (sub)image from a region of a casa image
Description
This function applies a region\ to an \imagefile, creates a new \imagefile\ containing the (sub)image, and associates the \imagetoolwith it.
The input image file may be in native \casa, its, or Miriad format. Look \htmlref{here}{IMAGES:FOREIGNIMAGES} for more information on foreign images.
If {\stfaf outfile} is given, the (sub)image is written to the specified disk file.
If {\stfaf outfile} is unset, the Image ool\ actually references the input image file. So if you deleted the input image disk file, it would render this ool\ useless. When you close this ool(with the close function) the reference connection is broken.
Sometimes it is useful to drop axes of length one (degenerate axes). Use the {\stfaf dropdeg} argument if you want to do this.
The output mask is the combination (logical OR) of the default input \pixelmask\ (if any) and the OTF mask. Any other input \pixelmaskswill not be copied. Use function maskhandler if you need to copy other masks too.
See also the subimage function.
Input Parameters: outfile Output sub-image file name. Default is unset. infile Input image file name. Must be specified. region The region of interest. See help par.region for details. Default is whole image. mask Mask to use. See help par.mask. Default is none. dropdeg Drop degenerate axes false overwrite Overwrite (unprompted) pre-existing output file? false
Example:
''' # print ' ---- fromimage Ex 1 ----' innerquarter = rg.box([0.25,0.25],[0.75,0.75],frac=true) ia.close() ia.fromimage(outfile='image.small', infile='test.data', region=innerquarter, overwrite=true) ia.close() # '''
The specified region\ takes a quarter by area of the first two axes of the image, and all pixels of other axes.
--------------------------------------------------------------------------------
""" return _image.image_fromimage(self, *args, **kwargs)
def fromshape(self, *args, **kwargs): """ fromshape(self, outfile = string(""), shape = initialize_vector(1, (int)0), csys = initialize_record(""), linear = False, overwrite = False, log = True, type = string("f")) -> bool
Summary Construct an empty casa image from a shape
Description
This function creates a \casa\ \imagefile\ with the specified shape. All the pixel values in the image are set to 0. One may create either an image with float valued pixels (type='f') or a complex valued image (type='c').
If {\stfaf outfile} is given, the image is written to the specified disk file. If {\stfaf outfile} is unset, the Image ool\ is associated with a temporary image. This temporary image may be in memory or on disk, depending on its size. When you close the Image ool\ (with the close function) this temporary image is deleted.
The Coordinate System, provided as a Coordsys ool, is optional. If you provide it, it must be dimensionally consistent with the shape that you specify (see also coordsys).
If you don't provide the Coordinate System, a default Coordinate System is made for you. If {\stfaf linear=F} (the default) then it is a standard RA/DEC/Stokes/Spectral Coordinate System depending exactly upon the shape (Stokes axis must be no longer than 4 pixels and you may find the spectral axis coming out before the Stokes axis if say, {\cf shape=[64,64,32,4]}). Extra dimensions are given linear coordinates. If {\stfaf linear=T} then you get a linear Coordinate System.
The method returns True if successful, False otherwise.
Input Parameters: outfile Name of output image file. Default is unset. shape Shape of image. Must be specified. 0 csys Coordinate System. Default is unset. linear Make a linear Coordinate System if csys not given? false overwrite Overwrite (unprompted) pre-existing output file? false log Write image creation messages to logger true type Type of image. 'f' means Float, 'c' means complex. f
Example:
''' # print ' ---- fromshape Ex 1 ----' ia.fromshape('test2.data', [64,64,128], overwrite=true) mycs = ia.coordsys(axes=[0,2]) ia.close() ia.fromshape(shape=[10, 20], csys=mycs.torecord()) mycs.done() ia.close() # '''
The first example creates a zero-filled \imagefile\ named {\sff test.data} of shape [64,64,128]. If you examine the header with {\stff ia.summary()} you will see the RA/DEC/Spectral coordinate information. In the second example, a Coordinate System describing the first and third axes of the image {\sff test.data} is created and used to create a 2D temporary image.
--------------------------------------------------------------------------------
""" return _image.image_fromshape(self, *args, **kwargs)
def maketestimage(self, *args, **kwargs): """ maketestimage(self, outfile = string(""), overwrite = False) -> bool
Summary Construct a casa image from a test FITS file
Description
This function converts a FITS file resident in the \casa\ system into a \casa\ image.
If outfile is given, the image is written to the specified disk file. If outfile is unset, the Image tool is associated with a temporary image. This temporary image may be in memory or on disk, depending on its size. When you close the Image tool (with the close function) this temporary image is deleted.
Input Parameters: outfile Output image file name. Default is unset. overwrite Overwrite (unprompted) pre-existing output file? false
Example:
''' # print ' ---- maketestimage Ex 1 ----' ia.maketestimage() # make virtual image ia.close() ia.maketestimage('tmp', overwrite=true) ia.close() # close to unlock disk image # '''
--------------------------------------------------------------------------------
""" return _image.image_maketestimage(self, *args, **kwargs)
def adddegaxes(self, *args, **kwargs): """ adddegaxes(self, outfile = string(""), direction = False, spectral = False, stokes = string(""), linear = False, tabular = False, overwrite = False, silent = False) -> image
Summary Add degenerate axes of the specified type to the image
Description
This method adds degenerate axes (i.e. axes of length 1) of the specified type. Sometimes this can be useful although you will generally need to modify the coordinate system of the added axis to give it the coordinate you want (do this with the Coordsys ool). This method supports both float and complex valued images.
You specify which type of axes you want to add. You can't add an axis type that already exists in the image. For the Stokes axis, the allowed value (a string such as I, Q, XX, RR) can be found in the Coordsys newcoordsys function documentation.
If {\stfaf outfile} is given, the image is written to the specified disk file. If {\stfaf outfile} is unset, the on-the-fly Image oolreturned by the function is associated with a temporary image. This temporary image may be in memory or on disk, depending on its size. When you destroy the generated Image ool\ (with the done function) this temporary image is deleted.
Input Parameters: outfile Output image file name. Default is unset. direction Add direction axes? false spectral Add spectral axis? false stokes Add Stokes axis? Default is empty string. linear Add linear axis? false tabular Add tabular axis? false overwrite Overwrite (unprompted) pre-existing output file? false silent Skip silently existing axes? false
Example:
''' # print ' ---- adddegaxes Ex 1 ----' ia.maketestimage() print ia.shape() #[113L, 76L] mycs=ia.coordsys() print mycs.axiscoordinatetypes() #['Direction', 'Direction'] mycs.done() im2 = ia.adddegaxes(spectral=T) print im2.shape() #[113L, 76L, 1L] mycs=im2.coordsys() print mycs.axiscoordinatetypes() ['Direction', 'Direction', 'Spectral'] mycs.done() im3 = im2.adddegaxes(stokes='Q') print im3.shape() #[113L, 76L, 1L, 1L] mycs = im3.coordsys() print mycs.axiscoordinatetypes() #['Direction', 'Direction', 'Spectral', 'Stokes'] mycs.done() im2.done() im3.done() ia.close() # '''
In this example, all the images are virtual (temporary images).
--------------------------------------------------------------------------------
""" return _image.image_adddegaxes(self, *args, **kwargs)
def addnoise(self, *args, **kwargs): """ addnoise(self, type = string("normal"), pars = initialize_vector(2,(double)0.0, (double)1.0), region = initialize_variant(""), zero = False) -> bool
Summary Add noise to the image
Description
This function adds noise to the image. You may zero the image first before the noise is added if you wish.
The noise can be drawn from one of many distributions.
For each distribution, you must supply the type via the {\stfaf type} argument (minimum match is active) and parameters via the {\stfaf pars} argument. Briefly:
egin{itemize}
\item {binomial} -- the binomial distribution models successfully drawing items from a pool. Specify two parameters, $n$ and $p$, respectively. $n$ is the number of items in the pool, and $p$, is the probability of each item being successfully drawn. It is required that $n \> 0$ and $0 \le p \le 1$.
\item {discreteuniform} -- models a uniform random variable over the closed interval. Specify two parameters, the low and high values, respectively. The low parameter is the lowest possible return value and the high parameter is the highest. It is required that $low \< high$.
\item {erlang} -- Specify two parameters, the mean and variance, respectively. It is required that the mean is non-zero and the variance is positive.
\item {geometric} -- Specify one parameter, the probability. It is required that $0 \le probability \< 1$.
\item {hypergeometric} -- Specify two parameters, the mean and the variance. It is required that the variance is positive and that the mean is non-zero and not bigger than the square-root of the variance.
\item {normal} -- Specify two parameters, the mean and the variance. It is required that the variance is positive.
\item {lognormal} -- Specify two parameters, the mean and the variance. It is required that the supplied variance is positive and that the mean is non-zero.
\item {negativeexponential} -- Supply one parameter, the mean.
\item {poisson} -- Specify one parameter, the mean. It is required that the mean is non-negative.
\item {uniform} -- Model a uniform random variable over a closed interval. Specify two parameters, the low and high values. The low parameter is the lowest possible return value and the high parameter can never be returned. It is required that $low \< high$.
\item {weibull} -- Specify two parameters, alpha and beta. It is required that the alpha parameter is not zero.
nd{itemize}
Input Parameters: type Type of distribution, normal normal pars Parameters of distribution 0.0 1.0 region Region of interest. See help par.region for details. Default is whole image. zero Zero image first? false
Example:
''' # print ' ---- addnoise Ex 1 ----' ia.maketestimage() # im1 = maketestimage() ia.addnoise(type='normal', pars=[0.5, 1], zero=T) ia.statistics() ia.close() # '''
A test image is created, zeroed, and noise of mean 0.5 and variance 1 from a normal distribution added.
--------------------------------------------------------------------------------
""" return _image.image_addnoise(self, *args, **kwargs)
def convolve(self, *args, **kwargs): """ convolve(self, outfile = string(""), kernel = initialize_variant(""), scale = -1.0, region = initialize_variant(""), mask = initialize_variant(""), overwrite = False, stretch = False, async = False) -> image
Summary Convolve image with an array or another image
Description
This function performs Fourier-based convolution of an \imagefile\ by the given kernel.
If {\stfaf outfile} is given, the image is written to the specified disk file. If {\stfaf outfile} is left unset, the on-the-fly Image oolgenerated by this function is associated with a temporary image. This temporary image may be stored in memory or on disk, depending on its size. When the user destroys the generated Image ool\ (with the done function) this temporary image is deleted.
The kernel is provided as a multi-dimensional array or as the filename of a disk-based \imagefile. The provided kernel can have fewer dimensions than the image being convolved. In this case, it will be padded with degenerate axes. An error will result if the kernel has more dimensions than the image. No additional scaling of the kernel is provided yet.
The scaling of the output image is determined by the argument {\stfaf scale}. If this is left unset, then the kernel is normalized to unit sum. If {\stfaf scale} is not left unset, then the convolution kernel will be scaled (multiplied) by this value.
Masked pixels will be assigned the value 0.0 before convolution.
The output mask is the combination (logical OR) of the default input \pixelmask\ (if any) and the OTF mask. Any other input \pixelmaskswill not be copied. The function maskhandler should be used if there is a need to copy other masks too.
See also the other convolution functions:
convolve2d, sepconvolve and hanning.
Input Parameters: outfile Output image file name. Default is unset. kernel Convolution kernel - An array or an image filename. Must be specified by the user. scale Scale factor. The default behavior is to autoscale (specified with -1.0). -1.0 region Region of interest. See help par.region for details. The default is the whole image. mask Mask to use. See help par.mask for more details. The default setting is none. overwrite Overwrite (unprompted) the pre-existing output file? false stretch Stretch the mask if necessary and possible? See help par.stretch for more details. false async Run asynchronously? false
Example:
''' # print ' ---- convolve Ex 1 ----' # This example presupposes the existence of an input image file, testdata, and a kernel image file, kerneldata. # Open the input image file: ia.open(infile='testdata') # Set up a region to be operated upon (in this case, the whole image): r1 = rg.box() # Perform the convolution: im2 = ia.convolve (outfile = 'convout', overwrite = true, region = r1, kernel = 'kerneldata') ia.close() im2.done()
# print ' ---- convolve Ex 2 ----' # This example uses an array as the convolution kernel, and presupposes the existence of an input image file, testdata, which we first open: ia.open(infile='testdata') # Next, create a Python array of some kind to use as a convolution kernel. For example: from numpy import arange kernelarray = arange(10)**3 # Set up a region to be operated upon (in this case, the whole image): r1 = rg.box() # Perform the convolution: im3 = ia.convolve (outfile = 'convout2', overwrite = true, region = r1, kernel = kernelarray) ia.close() im3.done() # '''
--------------------------------------------------------------------------------
""" return _image.image_convolve(self, *args, **kwargs)
def boundingbox(self, *args, **kwargs): """ boundingbox(self, region = initialize_variant("")) -> record
Summary Get the bounding box of the specified region
Description
This function finds the bounding box of a region of interest when it is applied to a particular image. Both float and complex valued images are supported. It is returned in a record which has fields {\cf `blc', `trc', `inc', `bbShape', `regionShape', `imageShape', `blcf'} and {\cf `trcf'} containing the bottom-left corner, the top-right corner (in absolute image pixel coordinates), the increment (stride) of the region, the shape of the boundingbox, the shape of the region, the shape of the image, the blc in formatted absolute world coordinates and the trc in formatted absolute world coordinates, respectively.
Note that the shape of the bounding box will be different from the shape of the region if a non-unit stride (increment) is involved (see the example below).
Note that the integer size of the elements in blc, trc, inc, regionShape, bbShape, and imageShape are 32 bits, even on a 64 bit machine. This means that, on 64 bit machines, you may have to convert them to 64 bit ints using eg numpy.int64, before being able to use them as direct input to other methods such as ia.getchunk().
Input Parameters: region The region of interest. See help par.region for details. Default is whole image.
Example:
''' # print ' ---- boundingbox Ex 1 ----' ia.maketestimage() # Create image tool x=['3pix','6pix','9pix','6pix','5pix','5pix','3pix'] # X vector in abs pixels y=['3pix','4pix','7pix','9pix','7pix','5pix','5pix'] # Y vector in abs pixels mycs = ia.coordsys() r1=rg.wpolygon(x=x,y=y,csys=mycs.torecord()) # Create polygonal world region mycs.done() bb = ia.boundingbox(r1) # Find bounding box print bb #{'regionShape': array([7, 7]), 'trc': array([9, 9]), # 'imageShape': array([113, 76]), # 'blcf': '00:00:27.733, -00.06.48.000', # 'trcf': '00:00:24.533, -00.05.36.000', 'bbShape': array([7, 7]), # 'blc': array([3, 3]), 'inc': array([1, 1])} ia.close() # '''
Example:
''' # print ' ---- boundingbox Ex 2 ----' ia.maketestimage() b = rg.box([10,10],[20,20],[2,3]) print ia.boundingbox(b) #{'regionShape': array([6, 4]), 'trc': array([20, 19]), # 'imageShape': array([113, 76]), # 'blcf': '00:00:24.000, -00.05.24.000', # 'trcf': '00:00:18.667, -00.03.36.000', 'bbShape': array([11, 10]), # 'blc': array([10, 10]), 'inc': array([2, 3])}
ia.close() # '''
In this example we see the difference between bbShape and regionShape because of the increment (stride). See also that the trc is modified by the increment.
--------------------------------------------------------------------------------
""" return _image.image_boundingbox(self, *args, **kwargs)
def boxcar(self, *args, **kwargs): """ boxcar(self, outfile = string(""), region = initialize_variant(""), mask = initialize_variant(""), axis = -1, width = 2, drop = True, dmethod = string("copy"), overwrite = False, stretch = False) -> image
Summary Convolve one axis of image with a boxcar kernel
Description
This application performs boxcar convolution of one axis of an image defined by
z[i] = (y[i] + y[i+i] + ... + y[i+w])/w
where z[i] is the value at pixel i in the box car smoothed image, y[k] is the pixel value of the input image at pixel k, and w is a postivie integer representing the width of the boxcar in pixels. Both float and complex valued images are supported. The length of the axis along which the convolution is to occur must be at least w pixels in the selected region, unless decimation using the mean function is chosen in which case the axis length must be at least 2*w (see below). Masked pixel values are set to zero prior to convolution. All nondefault pixel masks are ignored during the calculation. The convolution is done in the image domain (i.e., not with an FFT).
If drop=False (no decimation), the length of the output axis will be equal to the length of the input axis - w + 1. The pixel mask, ORed with the OTF mask if specified, is copied from the selected region of the input image to the output image. Thus for example, if the selected region in the input image has six planes along the convolution axis, if the specified boxcar width is 2, and if the pixel values, which are all unmasked, on a slice along this axis are [1, 2, 5, 10, 17, 26], then the corresponding output slice will be of length five and the output pixel values will be [1.5, 3.5, 7.5, 13.5, 21.5].
If drop=True and dmethod='copy', the output image is the image calculated if drop=True, except that only every wth plane is kept. Both the pixel and mask values of these planes are copied directly to the output image, without further processing. Thus for example, if the selected region in the input image has six planes along the convolution axis, the boxcar width is chosen to be 2, and if the pixel values, which are all unmasked, on a slice along this axis are [1, 2, 5, 10, 17, 26], the corresponding output pixel values will be [1.5, 7.5, 21.5].
If drop=True and dmethod='mean', first the image described in the drop=False case is calculated. Then, the ith plane of the output image is calculated by averaging the i*w to the (i+1)*w-1 planes of this intermediate image. Thus, for example, if the selected region in the input image has six planes along the convolution axis, the boxcar width is chosen to be 2, and if the pixel values, which are all unmasked, on a slice along this axis are [1, 2, 5, 10, 17, 26], then the corresponding output pixel values will be [2.5, 10.5]. Any pixels at the end of the plane of the intermediate image that do not fall into a complete bin of width w are ignored. Masked values are taken into consideration when forming this average, so if one of the values is masked, it is not used in the average. If at least one of the values in the intermediate image bin is not masked, the corresponding output pixel will not be masked.
The smoothed image is written to disk with name {\stfaf outfile}, if specified. If not, no image is written but the image is still accessible via the returned image analysis tool (see below).
This method always returns an image analysis tool which is attached to the smoothed image. This tool should always be captured and closed after any desired manipulations have been done. Closing the tool frees up system resources (eg memory), eg,
egin{verbatim} smoothedim = ia.boxcar(...) # do things (or not) with smoothedim ... # close the returned tool promptly upon finishing with it. smoothedim.done() nd{verbatim}
Input Parameters: outfile Output image file name. Default is none. region Dictionary or string specifying the region of interest. See help par.region. Default is whole image. mask Mask to use. See help par.mask. Default is none. axis Zero-based axis along which to convolve. ia.coordsys().names() gives the order of the axes in the image. Less than 0 means use the spectral axis if there is one, if not an exception is thrown. -1 width Width of the boxcar in pixels. 2 drop Drop every nth pixel on output, where n is the width of the boxcar? true dmethod If drop=True, method to use in plane decimation. 'copy': direct copy of every second plane, 'm(ean)': average planes n*i through n*(i+1) - 1 (inclusive) in the smoothed, non-decimated image to form plane i in the output image. copy overwrite Overwrite (unprompted) pre-existing output file? false stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false
Example:
ia.open('mynonsmoothed.im') # smooth the spectral axis by 3 pixels, say it's axis 2 and only # write every other pixel boxcar = ia.boxcar(outfile='myboxcarsmoothed.im', axis=2, drop=True, width=3, dmethod='c' overwrite=True) # done with input ia.done() # do something with the output image, get statistics say stats = boxcar.statistics() # close the result image boxcar.done()
--------------------------------------------------------------------------------
""" return _image.image_boxcar(self, *args, **kwargs)
def brightnessunit(self): """ brightnessunit(self) -> string
Summary Get the image brightness unit
Description
This function gets the image brightness unit. Both float and complex valued images are supported.
Example:
''' # print ' ---- brightnessunit Ex 1 ----' ia.maketestimage() print ia.brightnessunit() #Jy/beam ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_brightnessunit(self)
def calc(self, *args, **kwargs): """ calc(self, pixels, verbose = True) -> bool
Summary Image calculator
Description
This function is used to evaluate a mathematical expression involving \casa\ images, assigning the result to the current (already existing) image. Both float and complex valued images are supported, although the image which results from the calculation must have the same type of pixel values as the image already attached to the tool. That is, one cannot create a complex valued image using this method if the associated ia tool is currently attached to a float valued image. It complements the imagecalc function which returns a newly constructed on-the-fly image tool. See \htmladdnormallink{note 223}{../../notes/223/223.html} which describes the the syntax and functionality in detail.
If the expression, supplied via the {\stfaf pixels} argument, is not a scalar, the shapes and coordinates of the image and expression must conform.
If the image (that associated with the tool) has a \pixelmask, then only pixels for which that mask is good will be changed. See the function maskhandler for managing image \pixelmasks.
Note that when multiple image are used in the expression, there is no garauntee about which of those images will be used to create the header of the output image. Therefore, one may have to modify the output header as needed if the input headers differ.
See the related functions set and putregion.
Input Parameters: pixels LEL expression verbose Emit possibly useful messages. True
Example:
''' # print ' ---- calc Ex 1 ----' ia.maketestimage('aF', overwrite=true) ia.calc('min(aF, (min(aF)+max(aF))/2)') ia.calc('1.0') ia.close() # '''
The first example shows that there are 2 {\cf min} functions. One with a single argument returning the minimum value of that image. The other with 2 arguments returning an image containing ``aF'' data clipped at the value of the 2nd argument. The second example sets all good pixels to unity.
''' # print ' ---- calc Ex 2 ----' ia.maketestimage('aD', overwrite=true) # create some ia.close() ia.maketestimage('aF', overwrite=true) # image files ia.close() ia.maketestimage('bF', overwrite=true) # for use ia.close() ia.maketestimage('aC', overwrite=true) # in ia.close() ia.maketestimage() ia.calc('sin(aD)+(aF*2)+min(bF)+real(aC)') # the example ia.close() # '''
This shows a mixed type expression. The real part of the complex image ``aC'' is used in an expression that otherwise uses Float type.
--------------------------------------------------------------------------------
""" return _image.image_calc(self, *args, **kwargs)
def calcmask(self, *args, **kwargs): """ calcmask(self, mask = string(""), name = string(""), asdefault = True) -> bool
Summary Image mask calculator
Description
This method is used to create a new \pixelmask\ via a Boolean LEL expression. This gives you much more scope than the simple set and putregion functions. Both float and complex valued images are supported.
See \htmladdnormallink{note 223}{../../notes/223/223.html} which describes the the syntax and functionality of LEL in detail.
If the expression is not a scalar, the shapes and coordinates of the image and expression must conform. If the expression is a scalar then the entire \pixelmask\ will be set to that value.
By default (argument {\stfaf name}) the name of a new \pixelmask\ is made up for you. However, if you specify a \pixelmask\ name (use function summary or maskhandler to see the mask names) then it is used. If the \pixelmask\ already exists, it is overwritten.
You can specify whether the new \pixelmask\ should be the default mask or not. By default, it is made the default \pixelmask\ !
Input Parameters: mask Mask to use. See help par.mask. Default is none. name Mask name. Default is auto new name. asdefault Make specified mask the default mask? true
Example:
''' # print ' ---- calcmask Ex 1 ----' ia.maketestimage('zz', overwrite=true) subim = ia.subimage() # Make 'another' image ia.calcmask('T') # Specify 'True' mask as a string ia.calcmask('zz\>0') # Mask of zz ignored ia.calcmask('mask(zz) && zz\>0') # Mask of zz included ia.calcmask(subim.name(true)+'\>min('+subim.name(true)+')') # Use tool names ia.calcmask('zz\>min(zz:nomask)') # Mask of zz not used in scalar function subim.done() ia.close() # '''
The first calcmask example is the equivalent of {\cf ia.set(pixelmask=1)}. It sets the entire mask to True.
The second example creates a new \pixelmask\ which is True when the pixel values in image {\sff zz} are greater than 0.
Now for some subtlety. Read carefully ! Any LEL expression can be thought of as having a value and a mask. Usually the value is Float and the mask Boolean. In this case, because the expression is Boolean itself, the value is also Boolean. The expression mask would just be the mask of {\sff zz}. Now what {\stfaf calcmask} does is create a mask from the expression value (which is Boolean) and discards the expression mask. Therefore, the resulting mask is independent of any mask that {\sff zz} might have.
If you wish the mask of the expression be honoured as well, then you can do as in the third example. It says the output \pixelmask\ will be True if the current \pixelmask\ of {\sff zz} is True and the expression value is True.
The fourth example is like the second, except that we use the pixel values associated with the on-the-fly {\stf subim} Image tool disk file. Note one further subtlety here. When the scalar function {\cf min} evaluates a value from {\cf subim.name()}, which in this case is just {\cf zz}, the default mask of {\cf subim.name()} {\it will} be used. All the scalar functions look at the mask. If you didn't want the mask to be used you can use the special {\cf :nomask} syntax shown in the final example.
--------------------------------------------------------------------------------
""" return _image.image_calcmask(self, *args, **kwargs)
def close(self): """ close(self) -> bool
Summary Close the image tool
Description
This function closes the \imagetool. This means that it detaches the tool from its \imagefile\ (flushing all the changes first). The \imagetool\ is ``null'' after this change (it is not destroyed) and calling any oolfunction\ other than open will result in an error.
Example:
''' # print ' ---- close Ex 1 ----' ia.maketestimage('myimage',overwrite=true) # First create an image and attach the image tool to it. ia.close() # The Image tool is detached from the image using the close tool. print '!!!EXPECT ERROR HERE!!!' ia.summary() # The image is not open, so attempting to display summary information on the image results in an error. ia.open('myimage') # The image tool is reattached to the image using the open tool. ia.summary() # No error - the summary information is now displayed correctly. ia.close() # The Image tool is detached from the image again, using the close tool. # '''
--------------------------------------------------------------------------------
"""
def continuumsub(self, *args, **kwargs): """ continuumsub(self, outline = string(""), outcont = string("continuumsub.im"), region = initialize_variant(""), channels = initialize_vector(1, (int)-1), pol = string(""), fitorder = 0, overwrite = False) -> image
Summary Image plane continuum subtraction
Description
This function packages the relevant image tool functionality for simple specification and application of image plane continuum subtraction. All that is required of the input image is that it have a non-degenerate spectral axis.
The user specifies region, the region of the input image over which continuum subtraction is desired (otherwise the whole image will be treated); channels, the subset of channels on the spectral axis to use in the continuum estimation, specified as a vector; fitorder, the polynomial order to use in the estimation. Optionally, output line and continuum images may be written by specifying outline and outcont, respectively. If outline is not specified, a virtual image tool is all that is produced. If outcont is not specified, the output continuum image will be written in 'continuumsub.im'. Note that the pol parameter is no longer supported; one should use the region parameter if polarization selection is desired, in conformance with other ia tool methods.
Input Parameters: outline Output line image filename. Default is unset. outcont Output continuum image filename continuumsub.im region Region over which output is desired. See help par.region for details. Default is whole image. channels Channels to use for continuum estimation. Default is all. -1 pol THIS PARAMETER IS NO LONGER SUPPORTED. USE THE region PARAMETER TO CHOOSE WHICH POLARIZATIONS YOU WOULD LIKE TO PROCESS fitorder Polynomial order for continuum estimation 0 overwrite Auto-overwrite output files if they exist? false
Example:
''' # print ' ---- continuumsub Ex 1 ----' ia.fromarray(outfile='test.data', pixels=ia.makearray(0, [64, 64, 4, 128]), overwrite=true) #im1csub=ia.continuumsub(region=rg.quarter(), # channels=range(3,9)+range(54,61),fitorder=0); innerquarter= rg.box([0.25,0.25],[0.75,0.75],frac=true) im1csub=ia.continuumsub(region=innerquarter, channels=range(3,9)+range(54,61),fitorder=0); im1csub.done() # done the on-the-fly image tool ia.close() # '''
In this first example, the continuum emission in each pixel of the inner quarter of the input image is estimated by averaging (fitorder=0) channels 3-8 and 54-60, inclusive. (Python's range function includes the lower limit and excludes the upper limit.) im1csub is an image tool containing the result (only the inner quarter of the original image).
''' # print ' ---- continuumsub Ex 2 ----' ia.fromarray(outfile='test.data', pixels=ia.makearray(0, [64, 64, 4, 128]), overwrite=true) im2csub=ia.continuumsub(channels=range(3,9)+range(54,61),fitorder=2) im2csub.done() ia.close() # '''
In this second example, the Stokes I continuum emission in each pixel of the whole input image is estimated with a 2nd-order polynomial fit to channels 3-8 and 54-60. The output image tool (im2csub) contains only Stokes I, even if the original image had other stokes planes.
--------------------------------------------------------------------------------
""" return _image.image_continuumsub(self, *args, **kwargs)
def convertflux(self, *args, **kwargs): """ convertflux(self, value = initialize_variant("0Jy/beam"), major = initialize_variant("1arcsec"), minor = initialize_variant("1arcsec"), type = string("Gaussian"), topeak = True, channel = -1, polarization = -1) -> record
Summary Convert peak intensity to/from flux density for a 2D Gaussian.
Description
This function interconverts between peak intensity and flux density for a Gaussian component. The image must hold a restoring beam.
Input Parameters: value Flux density to convert. Must be specified. 0Jy/beam major Major axis of component. Must be specified. 1arcsec minor Minor axis of component. Must be specified. 1arcsec type Type of component. String from Gaussian, Disk. Gaussian topeak Convert to peak or integral flux desnity true channel Channel to use if and only if image has per plane beams. -1 polarization Zero-based polarization number to use for beam if and only if image has per plane beams. -1
Example:
''' # print ' ---- convertflux Ex 1 ----' ia.maketestimage('in.im', overwrite=true); p1 = qa.quantity('1mJy/beam') i1 = ia.convertflux(p1, major='30arcsec', minor='10arcsec', topeak=F); p2 = ia.convertflux(i1, major='30arcsec', minor='10arcsec', topeak=T) print 'peak, integral, peak = ', p1, i1, p2 #peak, integral, peak = {'value': 1.0, 'unit': 'mJy/beam'} # {'value': 0.00016396129551656742, 'unit': 'Jy'} # {'value': 0.0010000000000000002, 'unit': 'Jy/beam'}
ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_convertflux(self, *args, **kwargs)
def convolve2d(self, *args, **kwargs): """ convolve2d(self, outfile = string(""), axes = initialize_vector(2,(int)0, (int)1), type = string("gaussian"), major = initialize_variant("0deg"), minor = initialize_variant("0deg"), pa = initialize_variant("0deg"), scale = -1, region = initialize_variant(""), mask = initialize_variant(""), overwrite = False, stretch = False, targetres = False, beam = initialize_record("")) -> image
Summary Convolve image by a 2D kernel
Description
This function performs Fourier-based convolution of an \imagefileusing the provided 2D kernel.
If {\stfaf outfile} is left unset, the image is written to the specified disk file. If {\stfaf outfile} is not given, the newly constructed on-the-fly Image ool\ is associated with a temporary image. This temporary image may be stored in memory or on disk, depending on its size. When the user destroys the on-the-fly Image ool\ (with the done function) this temporary image is deleted.
The user specifies which 2 pixel axes of the image are to be convolved via the {\stfaf axes} argument. The pixels must be square or an error will result.
The user specifies the type of convolution kernel with {\stfaf type} (minimum match is supported); currently only {\cf 'gaussian'} is available.
The user specifies the parameters of the convolution kernel via the arguments {\stfaf major}, {\stfaf minor}, and {\stfaf pa}. These arguments can be specified in one of three ways:
egin{itemize}
\item Quantity - for example {\stfaf major=qa.quantity(1, 'arcsec')} Note that you pixel units can be used, viz. {\stfaf major=qa.quantity(1, 'pix')}, see below.
\item String - for example {\stfaf minor='1km'} (i.e. one that the Quanta quantity function accepts).
\item Numeric - for example {\stfaf major=10}. In this case, the units of {\stfaf major} and {\stfaf minor} are assumed to be in pixels. Using pixel units allows the user to convolve unlike axes (see one of the provided example for this use case). For the position angle, units of degrees are assumed.
nd{itemize}
The interpretation of {\stfaf major} and {\stfaf minor} depends upon the kernel type.
egin{itemize}
\item Gaussian - {\stfaf major} and {\stfaf minor} are the Full Width at Half Maximum (FWHM) of the major and minor axes of the Gaussian.
nd{itemize}
The position angle is measured North through East when a plane holding a celestial coordinate (the usual astronomical convention) is convolved. For other axis/coordinate combinations, a positive position angle is measured from +x to +y in the absolute pixel coordinate frame (x is the first axis that is specified, with argument {\stfaf axes}).
In the case of a Gaussian, the {\stfaf beam} parameter offers an alternate way of describing the convolving Gaussian. If used, neither {\stfaf major}, {stfaf minor}, nor {\stfaf pa} can be specified. The {\stfaf beam} parameter must have exactly three fields: 'major', 'minor', and 'pa' (or 'positionangle'). This is, not coincidentally, the record format for the output of ia.restoringbeam().
The scaling of the output image is determined by the argument {\stfaf scale}. If this is left unset then autoscaling will be invoked.
If the user is not convolving the sky, then autoscaling means that the convolution kernel will be normalized to have unit volume so as to conserve flux.
If the user is convolving the sky, then there are two cases for which autoscaling is useful:
Firstly, if the input image units are Jy/pixel, then the output image will have units of Jy/beam and be appropriately scaled. In addition, the restoring beam of the output image will be the same as the convolution kernel.
Secondly,if the input image units are Jy/beam, then the output image will also have units of Jy/beam and be appropriately scaled. In addition, the restoring beam of the output image will be the convolution of the input image restoring beam and the convolution kernel. In the case of an image with per-plane beams, for each plane, the kernel is convolved with the appropriate beam and the result is associated with that plane in the output image.
If the user sets a value for {\stfaf scale}, then the convolution kernel will be scaled by this value. Note that it has peak of unity before the application of this scale factor.
If targetres=True and type='gaussian' and the input image has a restoring beam, this method will interpret the values of major, minor, and pa as the resolution of the final image and will calculate the parameters of the Gaussian to use in the convolution so that this target resolution is achieved.
Masked pixels will be assigned the value 0.0 before convolution. The output mask is the combination (logical OR) of the default input \pixelmask\ (if any) and the OTF mask. Any other input \pixelmaskswill not be copied. The function maskhandler can be used if there is a need to copy other masks too.
See also the other convolution functions:
convolve, hanning, and sepconvolve.
Input Parameters: outfile Output image file name. The default value is unset. axes Axes to convolve. The default setting is [0,1]. 01 type Type of convolution kernel to be used. gaussian major Major axis, Quantity, string, numeric (e.g. 10arcsec, 20pix, 3km, etc.). This must be specified by the user. 0deg minor Minor axis, Quantity, string, numeric (e.g. 10arcsec, 20pix, 3km, etc.). This must be specified by the user. 0deg pa Position Angle, Quantity, string, numeric (e.g. 10deg). The default value is 0deg. 0deg scale Scale factor. The default setting (-1) is to autoscale. -1 region Region of interest. See help par.region for details. The default is the whole image. mask Mask to use. See help par.mask for more details. The default option is none. overwrite Overwrite (unprompted) the pre-existing output file? false stretch Stretch the mask if necessary and possible? See help par.stretch. false targetres If True and type='gaussian', major, minor, and pa are interpreted as the image resolution that the user wants to achieve. false beam Alternate way of describing a Gaussian. Must have fields 'major', 'minor', and 'pa' (or 'positionangle')
Example:
''' # print ' ---- convolve2d Ex 1 ----' ia.maketestimage('xy',overwrite=true) # Create a simple RA/DEC test image # Convolve axes 0 and 1 of the test image with a 20x10-arcsec, 45-degree Gaussian: im2 = ia.convolve2d(outfile='xy.con', axes=[0,1], type='gauss', major='20arcsec', minor='10arcsec', pa='45deg', overwrite=true); # Clean up, by destroying the im2 tool and close the image tool: im2.done() ia.close() #
ia.fromarray(outfile='xypf', pixels=ia.makearray(0, [64, 64, 4, 64]), overwrite=true) # Create a simple RA/DEC/Pol/Freq test dataset print '!!!EXPECT WARNING REGARDING INVALID SPATIAL RESTORING BEAM!!!' # Convolve axes 0 and 3 of the test dataset with a 20x10-pixel, 45-degree Gaussian: im2 = ia.convolve2d(outfile='xypf.con', axes=[0,3], type='gauss', major='20pix', minor='10pix', pa='45deg', overwrite=true); # Note that pixel units must be used in the above because axes 0 and 3 are unlike. # Clean up, by destroying the im2 tool and close the image tool: im2.done() ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_convolve2d(self, *args, **kwargs)
def coordsys(self, *args, **kwargs): """ coordsys(self, axes = initialize_vector(1, (int)-1)) -> casac::coordsys
Summary Get the Coordinate System of the image
Description
This function returns the Coordinate System of an image in a {\stf Coordsys} tool. Both float and complex valued images are supported.
By default, the Coordinate System describes all of the axes in the image. If you desire, you can select a subset of the axes, thus reducing the dimensionality of the Coordinate System. This may be useful if you are supplying a Coordinate System to the functions fromarray or fromshape.
Input Parameters: axes Axes to which the Coordinate System pertains. Default is all axes. -1
Example:
''' # print ' ---- coordsys Ex 1 ----' ia.maketestimage('hcn',overwrite=true) ia.summary() mycs = ia.coordsys([0,1]) imshape = ia.shape() ia.fromshape(outfile='test', shape=imshape, csys=mycs.torecord(), overwrite=true) ia.summary() mycs.done() ia.close() # '''
In this example, we create a Coordinate System pertaining to the first two axes of the image and then we create a new (empty) 2D image with this Coordinate System using the {\cf fromshape} function.
--------------------------------------------------------------------------------
"""
def coordmeasures(self, *args, **kwargs): """ coordmeasures(self, pixel = initialize_vector(1, (double)-1)) -> record
Summary Convert from pixel to world coordinate wrapped as Measures
Description
You can use this function to get the world coordinates for a specified absolute pixel coordinate in the image. You specify a pixel coordinate (0-rel) for each axis in the image.
If you supply fewer pixel values then there are axes in the image, your value will be padded out with the reference pixel for the missing axes. Excess values will be ignored.
The world coordinate is returned as a record of measures. This function is just a wrapper for the Coordsys tool toworld function (invoked with argument {\stfaf format='m'}). Please see its documentation for discussion about the formatting and meaning of the measures.
This Image ool\ function adds two additional fields to the return record.
The {\cf mask} field contains the value of the image \pixelmask\ at the specified position. It is either T (pixel is good) or F (pixel is masked as bad or the specified position was off the image).
The {\cf intensity} field contains the value of the image (at the nearest pixel to that given) and its units. This is actually stored as a Quantity. This field does not exist if the specified pixel coordinate is off the image.
Input Parameters: pixel Absolute pixel coordinate. Default is reference pixel. -1
Example:
''' # print ' ---- coordmeasures Ex 1 ----' ia.maketestimage('myimage',overwrite=true) s = ia.shape() for i in range(len(s)): s[i] = 0.5*s[i] meas = ia.coordmeasures(s) print meas.keys() # Get names of fields in record #['intensity', 'mask', 'measure'] print meas['intensity'] #{'value': 1.39924156665802, 'unit': 'Jy/beam'} print meas['measure']['direction'] #{'type': 'direction', # 'm1': {'value': 5.817764003289323e-05, 'unit': 'rad'}, # 'm0': {'value': -5.8177644130875234e-05, 'unit': 'rad'}, 'refer': 'J2000'} dir = meas['measure']['direction'] # Get direction coordinate me.doframe(me.observatory('ATCA')) # Set location on earth me.doframe(me.epoch('utc','16jun1999/12:30:20')) # Set epoch azel = me.measure(dir,'azel') # Convert to azimuth/elevation print 'az,el=', qa.angle(azel['m0']), qa.angle(azel['m1']) # Format nicely #az,el= +105.15.47 -024.22.57 meas2=ia.coordmeasures() # defaults to reference pixel print meas2['intensity'] #{'value': 2.5064315795898438, 'unit': 'Jy/beam'} print meas2['measure']['direction'] #{'type': 'direction', # 'm1': {'value': 0.0, 'unit': 'rad'}, # 'm0': {'value': 0.0, 'unit': 'rad'}, 'refer': 'J2000'} dir = meas2['measure']['direction'] # Get direction coordinate me.doframe(me.observatory('ATCA')) # Set location on earth me.doframe(me.epoch('utc','16jun1999/12:30:20')) # Set epoch azel = me.measure(dir,'azel') # Convert to azimuth/elevation print 'az,el=', qa.angle(azel['m0']), qa.angle(azel['m1']) #az,el= +105.16.05 -024.23.00 # '''
In this example we first find the world coordinates of the centre of the image. Then we use the Measures ool\ {\stf me} to convert the {\cf direction coordinate} field from J2000 to an azimuth and elevation at a particular location at a particular time.
--------------------------------------------------------------------------------
""" return _image.image_coordmeasures(self, *args, **kwargs)
def decompose(self, *args, **kwargs): """ decompose(self, region = initialize_variant(""), mask = initialize_variant(""), simple = False, threshold = -1, ncontour = 11, minrange = 1, naxis = 2, fit = True, maxrms = -1, maxretry = -1, maxiter = 256, convcriteria = 0.0001, stretch = False) -> record
Summary Separate a complex image into individual components
Description
This function is an image decomposition tool that performs several tasks, with the end result being that a strongly blended image is separated into components - both in the sense that it determines the parameters for each component (assuming a Gaussian model) and that it physically assigns each pixel in the image to an individual object. The products of these two operations are called the component list and the component map, respectively. The fitting process (which determines the component list) and the pixel-decomposition process (which determines the component map) are designed to work cooperatively to increase the efficiency and accuracy of both.
The algorithm behind the decomposition is based on the function clfind, described in Williams et al 1994, which uses a contouring procedure whereby a closed contour designates a separate component. The program first separates the image into clearly distint 'regions' of blended emission, then contours each region to determine the areas constituting each component and passes this information on to the fitter, which determines the component list.
The contour deblending can optionally be replaced with a simpler local maximum scan, and the fitting can be replaced with a moment-based estimation method to speed up calculations on very large images or if either primary method causes trouble, but in general this will impede the accuracy of the fit.
The function works with both two and three dimensional images.
The return value is a record (or dictionary) that has 3 keys: { t 'components', 'blc', 'trc'}.\ The { t 'components'} element is a matrix each row of which contains the gaussian parameters of the component fitted.\ The { t 'blc'} element is a matrix of the bottom left corners (blc) of the regions found. Each row correspond to a region blc.\ The { t 'trc'} element is a matrix of the top right corners (trc) of the regions found. Each row correspond to a region trc.\ {f Please Note} that the returned blc's and trc's are relative to { t region} defined by the user. A { t blc } of [0,0] implies the bottom left of the region selected and not the bottom left of the image. Obviously if no region is defined then it is the bottom left of the image.
Input Parameters: region Region of interest. See help par.region for details. Default is unset. mask Mask to use. See help par.mask. Default is none. simple Skip contour deblending and scan for local maxima false threshold Value of minimum positive contour. Must be set and nonnegative. -1 ncontour Number of contours to use in deblending (\>= 2) 11 minrange Minimum number of closed contours in a component (\> 0) 1 naxis Max number of perpendicular steps between contiguous pixels. Values of 1, 2 or 3 are allowed. 2 fit Fit to the components after deblending? true maxrms Maximum RMS of fit residuals to not retry fit (\> 0). Default is unset. -1 maxretry Maximum number of times to retry the fit (\>= 0). Default is unset. -1 maxiter Maximum number of iterations allowed in a single fit (\> 0) 256 convcriteria Criterion to establish convergence (\>=0) 0.0001 stretch Stretch the mask if necessary and possible? See help par.stretch. false
Example:
''' # print ' ---- decompose Ex 1 ----' ia.maketestimage() out=ia.decompose(threshold=2.5, maxrms=1.0) #Attempt 1: Converged after 21 iterations #Attempt 1: Converged after 15 iterations #1: Peak: 17.955 Mu: [0.000327928, 8.62573e-05] # Axes: [0.00175981, 0.00142841] Rotation: 1.29539 #2: Peak: 19.8093 Mu: [1.67927e-06, -0.000374393] # Axes: [0.00179054, 0.00132541] Rotation: 1.78404 #3: Peak: 10.1155 Mu: [6.28252, -7.09688e-05] # Axes: [0.00180877, 0.00104523] Rotation: 1.78847 print out['components'] #[[ 1.79549522e+01 3.27928370e-04 8.62573434e-05 1.75980886e-03 # 8.11686337e-01 1.29538655e+00] # [ 1.98093319e+01 1.67927124e-06 -3.74393392e-04 1.79054437e-03 # 7.40229547e-01 1.78403902e+00] # [ 1.01155214e+01 6.28252172e+00 -7.09688029e-05 1.80877140e-03 # 5.77867746e-01 1.78847444e+00]] print out['blc'] #[[37 31] # [47 25] # [67 33]] print out['trc'] #[[54 47] # [66 38] # [78 40]] ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_decompose(self, *args, **kwargs)
def deconvolvecomponentlist(self, *args, **kwargs): """ deconvolvecomponentlist(self, complist, channel = -1, polarization = -1) -> record
Summary Deconvolve a componentlist from the restoring beam
Description
This method deconvolves (a record representation of) a Componentlist tool from the restoring beam, returning (a record representation of) a new Componentlist tool. If there is no restoring beam, a fail is generated.
Currently, only deconvolution of Gaussian components is supported.
For images with per-plane beam, the user must choose which beam is used for the deconvolution by setting channel and/or polarization. Only a single beam is used to deconvolve all components.
See also functions setrestoringbeam and restoringbeam.
Input Parameters: complist Componentlist to deconvolve channel Zero-based channel number to use for beam for per plane images. Not used if the image has a single beam. -1 polarization Zero-based polarization number to use for beam for per plane images. Not used if the image has a single beam. -1
Example:
''' # print ' ---- deconvolvecomponentlist Ex 1 ----' ia.maketestimage() r = ia.fitcomponents() cl1 = r['results'] # cl1 and cl2 are record representations r = ia.fitcomponents() cl1 = r['results'] # cl1 and cl2 are record representations cl2 = ia.deconvolvecomponentlist(cl1) # of componentlists print cl1, cl2 cl.fromrecord(cl2) # set componentlist tool with record ia.close() cl.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_deconvolvecomponentlist(self, *args, **kwargs)
def deconvolvefrombeam(self, *args, **kwargs): """ deconvolvefrombeam(self, source = initialize_variant(""), beam = initialize_variant("")) -> record
Summary Helper function to deconvolve the given source Gaussian from a beam Gaussian to return a model Gaussian
Description
This is a helper function. It is to provide a way to deconvolve gaussians from other gaussians if that is what is needed for example removing a beam Gaussian from a Gaussian source. To run this function the tool need not be attached to an image.
The return value is a record that contains the fit param and the return value is a boolean which is set to true if fit model is a point source
Input Parameters: source Three quantities that define the source majoraxis, minoraxis and Position angle beam Three quantities that define the beam majoraxis, minoraxis and Position angle
Example:
''' # print ' ---- deconvolvefrombeam Ex 1 ----' ia.maketestimage() recout=ia.deconvolvefrombeam(source=['5arcmin', '3arcmin', '20.0deg'], beam=['50arcsec','30arcsec', '15deg']) ia.close() print 'Is pointsource ', recout['return'] print 'major=',recout['fit']['major'] print 'minor=',recout['fit']['minor'] print 'pa=',recout['fit']['pa']
'''
--------------------------------------------------------------------------------
""" return _image.image_deconvolvefrombeam(self, *args, **kwargs)
def beamforconvolvedsize(self, *args, **kwargs): """ beamforconvolvedsize(self, source = initialize_variant(""), convolved = initialize_variant("")) -> record
Summary Determine the size of the beam necessary to convolve with the given source to reach the given convolved (source+beam) size
Description
Determine the size of the beam necessary to convolve with the given source to reach the given convolved (source+beam) size. Because the problem is completely specified by the input parameters, no image needs to be attached to the associated tool; eg ia.open() need not be called prior to calling this method.
Input Parameters: source Three quantities that define the deconvolved source major axis, minor axis and position angle convolved Three quantities that define the convolved source (source+beam) major axis, minor axis and position angle. Do not specify if beam is specified.
Example:
# get the beam necessary to convolve the specified source with to achieve the target convolved source size (source convolved with beam). beam = ia.beamforconvolvedsize(source=['1arcsec', '1arcsec', '0deg'], convolved='3arcsec', '2arcsec', '45deg'])
--------------------------------------------------------------------------------
""" return _image.image_beamforconvolvedsize(self, *args, **kwargs)
def commonbeam(self): """ commonbeam(self) -> record
Summary Determine a beam to which all beams in an image can be convolved.
Description
Determine a beam to which all beams in an image can be convolved. If the image does not have a beam, an exception will be thrown. If the image has a single beam, that beam will be returned. If the image has multiple beams, this will be the beam with the largest area in the image beam set if all the other beams can be convolved to that beam. If not, this is guaranteed to be the minimum area beam to which all beams in the set can be convolved if all but one of the beams in the set can be convolved to the beam in the set with the largest area. Otherwise, the returned beam may or may not be the smallest possible beam to which all the beams in the set can be convolved.
Example:
ia.open('mymultibeamimage.im') cb = ia.commonbeam() # convolve all the planes in the image with that beam ia.convolve2d(outfile='myconvolvedimage.im', major=cb['major], minor=cb['minor'], pa=cb['pa'], targetres=T)
--------------------------------------------------------------------------------
""" return _image.image_commonbeam(self)
def remove(self, done = False, verbose = True): """ remove(self, done = False, verbose = True) -> bool
Summary Delete the image file associated with this image tool
Description
This function first closes the \imagetool\ which detaches it from its underlying \imagefile. It then deletes that \imagefile. If {\stfaf done=False}, the \imagetool\ is still viable, and can be used with function open to open a new \imagefile. Otherwise the \imagetool\ is destroyed. If {\stfaf verbose=True}, the logger will receive a progress report.
Input Parameters: done Destroy this tool after deletion false verbose Send a progress report to the logger. true
Example:
''' # print ' ---- remove Ex 1 ----' ia.maketestimage('myimage',overwrite=true) ia.close() ia.maketestimage('myotherimage',overwrite=true) ia.close() ia.open('myimage') # Attach to `myimage' ia.remove(F) # Close imagetool and delete `myimage' ia.open('myotherimage') # Open new imagefile `myotherimage' ia.remove() print '!!!EXPECT THE FOLLOWING TO GENERATE AN ERROR MESSAGE!!!' ia.open('myimage') # 'myimage' was deleted above ia.close() # '''
--------------------------------------------------------------------------------
"""
def removefile(self, *args, **kwargs): """ removefile(self, file) -> bool
Summary Delete an unattached image file from disk. Note: use remove() if the image file is attached to the image tool.
Description
This function deletes the specified image file.
Input Parameters: file Name of image file/directory to be removed. Must be specified.
Example:
''' # print ' ---- removefile Ex 1 ----' ia.maketestimage('myimage',overwrite=true) ia.close() ia.removefile('myimage') # remove image 'myimage' ia.maketestimage('myimage',overwrite=false) # error here if 'myimage' exists ia.close() ia.removefile('myimage') # '''
--------------------------------------------------------------------------------
""" return _image.image_removefile(self, *args, **kwargs)
def done(self, remove = False, verbose = True): """ done(self, remove = False, verbose = True) -> bool
Summary Destroy this image tool
Description
When the user no longer needs to use an \imagetool, calling this function will free up its resources. That is, it destroys the ool. This means that the user can no longer call any functions on the ool\ after it has been {\stff done}.
If the Image ool\ is associated with a disk file, then (unlike the {\stff close} function, the user can also choose to delete that by setting {\stfaf remove=true}. By default, any associated disk file is not deleted.
Note that this function is different from the {\stff close} function because the latter does not destroy the \imagetool. For example, the user can use the {\stff open} function straight after the {\stff close} function on the same ool.
Input Parameters: remove Delete the associated disk file as well? false verbose Send a progress report to the logger? true
Example:
''' # print ' ---- done Ex 1 ----' # Make a test image and create tool subim: ia.maketestimage('myfile',overwrite=true) subim = ia.subimage('myfile2',overwrite=true) # Check that subim exists as intended by attempting to display its summary: subim.summary() # This displays a summary of the dataset. # Use done to destroy the subim tool: subim.done() # Check that the subim tool has been detached as intended, by attempting to display its summary: subim.summary() # This should now throw an error. ia.summary() # This still works, though, as the ia tool is still open, and the dataset is still available. ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_done(self, remove, verbose)
def fft(self, *args, **kwargs): """ fft(self, real = string(""), imag = string(""), amp = string(""), phase = string(""), axes = initialize_vector(1, (int)-1), region = initialize_variant(""), mask = initialize_variant(""), stretch = False, complex = string("")) -> bool
Summary FFT the image
Description
This function fast Fourier Transforms the supplied image to the Fourier plane. Both float valued and complex valued images are supported. If the {\stfaf axes} parameter is left unset, then the sky plane of the image (if there is one) is transformed. Otherwise, the user can specify which axes are to be transformed. Note that if a sky axis is to be transformed, both of them must be specified.
The user specifies which form is desired in the result by specifying the desired output image file name(s).
Before the FFT is performed, any masked pixels are set to values of zero. The output mask is the combination (logical OR) of the default input \pixelmask\ (if any) and the OTF mask. Any other input \pixelmaskswill not be copied. The function maskhandler can be used if there is a need to copy other masks too.
Input Parameters: real Output real image file name. imag Output imaginary image file name. amp Output amplitude image file name. phase Output phase image file name. axes Specify the pixel axes that are to undergo the FFT. The default option (-1) is to transform the sky plane(s). -1 region The region of interest. See help par.region for details. The default setting is the whole image. mask The mask to be used. See 'help par.mask' for more details. The default option is none. stretch Stretch the mask if it is necessary and possible. See 'help par.stretch' for more details. false complex Output complex valued image file name.
Example:
''' # print ' ---- fft Ex 1 ----' # Create a test image: ia.maketestimage('gc.small', overwrite=true) # Perform an FFT on the sky plane of the test image, # writing out just the resulting real and amplitude images: ia.fft(real='r.im', amp='a.im') # Close the image tool when done: ia.close() # Lastly, clean up the example output files: ia.removefile('r.im') ia.removefile('a.im') # '''
Example:
''' # print ' ---- fft Ex 2 ----' # Create a zero-filled 3D test dataset and add noise to it: ia.fromshape('gc.small', [64,64,128], overwrite=true) ia.addnoise(type='normal', pars=[0.5, 1], zero=false) # The following transforms only the third axis of the image. # writing out only the amplitude and phase images. ia.fft(amp='amp.im', phase='p.im', axes=[2]) # Close the image tool when done: ia.close() # Lastly, clean up the example output files: ia.removefile('amp.im') ia.removefile('p.im') # '''
--------------------------------------------------------------------------------
""" return _image.image_fft(self, *args, **kwargs)
def findsources(self, *args, **kwargs): """ findsources(self, nmax = 20, cutoff = 0.1, region = initialize_variant(""), mask = initialize_variant(""), point = True, width = 5, negfind = False) -> record
Summary Find point sources in the sky
Description
This function finds strong point sources in the image. The sources are returned in a record that can be used by a Componentlist ool.
An efficient method is used to locate sources under the assumption that they are point-like and not too close to the noise. Only sources with a peak greater than the {\stfaf cutoff} fraction of the strongest source will be found. Only positive sources will be found, unless the {\stfaf negfind=T} whereupon positive and negative sources will be found.
After the list of point sources has been made, you may choose to make a Gaussian fit for each one ({\stfaf point=F}) so that shape information can be recovered as well. You can specify the half-width of the fitting grid with argument {\stfaf width} which defaults to 5 (fitting grid would then be [11,11] pixels). If you set {\stfaf width=0}, this is a signal that you would still like Gaussian components returned, but a default width should be used for the Gaussian shapes. The default is such that the component is circular with a FWHM of {\stfaf width} pixels.
Thus, if {\stfaf point=T}, the components in the returned Componentlist are Point components. If {\stfaf point=F} then Gaussian components are returned.
The region\ must be 2-dimensional and it must hold a region of the sky. Any degenerate trailing dimensions in the region are discarded.
See also the function fitcomponents (for which {\stff findsources} can provide an initial estimate).
Input Parameters: nmax Maximum number of sources to find, \> 0 20 cutoff Fractional cutoff level 0.1 region The 2-D region of interest to fit. See help par.region for details. Default is whole image. mask Mask to use. See help par.mask. Default is none. point Find only point sources? true width Half-width of fit grid when point=F 5 negfind Find negative sources as well as positive? false
Example:
''' # print ' ---- findsources Ex 1 ----' ia.maketestimage() clrec = ia.findsources(nmax=5, cutoff=0.5) print clrec # '''
All sources stronger than 0.5 of the strongest will be found. We use the Componentlist GUI to look at the strongest component.
--------------------------------------------------------------------------------
""" return _image.image_findsources(self, *args, **kwargs)
def fitprofile(self, *args, **kwargs): """ fitprofile(self, box = string(""), region = initialize_variant(""), chans = string(""), stokes = string(""), axis = -1, mask = initialize_variant(""), ngauss = 1, poly = -1, estimates = string(""), minpts = 1, multifit = False, model = string(""), residual = string(""), amp = string(""), amperr = string(""), center = string(""), centererr = string(""), fwhm = string(""), fwhmerr = string(""), integral = string(""), integralerr = string(""), stretch = False, logresults = True, pampest = initialize_variant(""), pcenterest = initialize_variant(""), pfwhmest = initialize_variant(""), pfix = initialize_variant(""), gmncomps = initialize_variant("0"), gmampcon = initialize_variant(""), gmcentercon = initialize_variant(""), gmfwhmcon = initialize_variant(""), gmampest = initialize_vector(1, (double)0.0), gmcenterest = initialize_vector(1, (double)0.0), gmfwhmest = initialize_vector(1, (double)0.0), gmfix = initialize_variant(""), spxtype = string(""), spxest = std::vector< double >(), spxfix = std::vector< bool >(), div = initialize_variant("0"), spxsol = string(""), spxerr = string(""), logfile = string(""), append = True, pfunc = initialize_variant(""), goodamprange = initialize_vector(1, (double)0.0), goodcenterrange = initialize_vector(1, (double)0.0), goodfwhmrange = initialize_vector(1, (double)0.0), sigma = initialize_variant(""), outsigma = string(""), planes = std::vector< int >()) -> record
Summary Fit gaussians and/or polynomials to a 1-dimensional profile.
Description
This application simultaneously fits any number of gaussian singlets, any number of lorentzian singlets, and any number of gaussian multiplets, and/or a polynomial to one dimensional profiles using the non-linear, least squares Levenberg-Marquardt algorithm. A description of the fitting algorithm may be found in AIPS++ Note 224 (http://www.astron.nl/casacore/trunk/casacore/doc/notes/224.html) and in Numerical Recipes by W.H. Press et al., Cambridge University Press. A gaussian/lorentzian singlet is a gaussian/lorentzian whose parameters (amplitude, center position, and width) are all independent from any other feature that may be simultaneously fit. A gaussian multiplet is a set of two or more gaussian lines in which at least one (and possibly two or three) parameter of each line is dependent on the parameter of another, single (reference) profile in the multiplet. For example, one can specify a doublet in which the amplitude of the first line is 0.6 times the amplitude of the zeroth line and/or the center of the first line is 20 pixels from the center of the zeroth line, and/or the fwhm of the first line is identical (in pixels) to that of the zeroth line. There is no limit to the number of components one can specify in a multiplet (except of course that the number of parameters to be fit should be significantly less than the number of data points), but there can be only a single reference profile in a multiplet to which to tie constraints of parameters of the other profiles in the set.
Additionally, a power logarithmic polynomial (plp) or a logarithmic tranformed polynomial (ltp) can be fit. In this case, each of these functions cannot be fit simultaneously with any other supported function. These functions are most often used for fitting the spectral index and higher order terms of a spectrum. A power logarithmic polynomial has the form
y = c0*x/div**(c1 + c2*ln(x/div) + c3*ln(x/div)**2 + ... + cn*ln(x/div)**(n - 1))
and a logarithmic transformed polynomial is simply the result of this equation after taking the natural log of both sides so that it has the form
ln(y) = c0 + c1*ln(x/div) + c2*ln(x/div)**2 + ... + cn*ln(x/div)**n
The coefficients of the two forms correspond with each other except that c0 in the second equation is equal to ln(c0) of the first. In the case of fitting a spectral index, the spectral index, traditionally represented as alpha, is equal to c1.
In both cases, div is a numerical value used to scale abscissa values so they are closer to unity when they are sent to the fitter. This generally improves the probability that the fit will converge. This parameter may be specified via the div parameter. A value of 0 (the default) indicates that the application should determine a reasonable value for div, which is determined via
div = 10**int(log10(sqrt(min(x)*max(x))))
where min(x) and max(x) are the minimum and maximum abscissa values, respectively.
So, for example, if S(nu) is proportional to nu**alpha and you expect alpha to be near -0.8 and the value of S(nu) is 1.5 at 1e9 Hz and your image(s) have spectral units of Hz, you would specify spxest=[1.5, -0.8] and div=1e9 when fitting a plp function, or spxest=[0.405, -0.8] and div=1e9 if fitting an ltp function.
More details of fitting all of these functions are described in following sections.
A CAUTIONARY NOTE Note that the likelihood of getting a reliable solution increases with the number of good data points as well as the goodness of the initial estimate. It is possible that the first solution found might not be the best one, and so, if a solution is found, it is recommended that the fit be repeated using the solution of the previous fit as the initial estimatE for the new fit. This process should be repeated until the solutions from one fit to the next differ only insignificantly. The convergent solution is very likely the best solution.
AXIS The axis parameter indicates on which axis profiles should be fit; a value \<0 indicates the spectral axis should be used, or if one does not exist, that the zeroth axis should be used.
MINIMUM NUMBER OF PIXELS The minpts parameter indicates the minimum number of unmasked pixels that must be present in order for a fit to be attempted. When multifit=T, positions with too few good points will be masked in any output images.
ONE FIT OF REGION AVERAGE OR PIXEL BY PIXEL FIT The multifit parameter indicates if profiles should be fit at each pixel in the selected region (true), or if the profiles in that region should be averaged and the fit done to that average profile (false).
POLYNOMIAL FITTING The order of the polynomial to fit is specified only via the poly parameter. If poly\<0, no polynomial will be fit. No initial estimates of coefficients can be specified; these are determined automatically.
GAUSSIAN SINGLET FITTING In the absence of an estimates file and no estimates being specified by the p*est parameters, and gmncomps=0 or is empty, the ngauss parameter indicates the maximum number of gaussian singlets that should be fit. The initial estimates of the parameters for these gaussians will be attempted automatically in this case. If it deems appropriate, the fitter will fit fewer than this number. In the case where an estimates file is supplied, ngauss is ignored (see below). ngauss is also ignored if the p*est parameters are specified or if gmncomps is not an empty array or, if an integer, is greater than zero. If estimates is not specified or the p*est parameters are not specified and ngauss=0, gmncomps is empty or 0, and poly\<0, an error will occur as this indicates there is nothing to fit.
One can specify initial estimates of gaussian singlet parameters via an estimates file or the pampest, pcenterest, pfwhmest, and optionally, the pfix parameters. The latter is the recommended way to specify these estimates as support for estimates files may be deprecated in the future. No matter which option is used, an amplitude initial estimate must always be nonzero. A negative fwhm estimate will be silently changed to positve.
SPECIFYING INITIAL ESTIMATES FOR GAUSSIAN AND LORENTZIAN SINGLETS (RECOMMENDED METHOD) One may specify initial estimates via the pampest, pcenterest, and pfwhmest parameters. In the case of a single gaussian or lorentzian singlet, these parameters can be numbers. pampest must be specified in image brightness units, pcenterest must be given in the number of pixels from the zeroth pixel, and pfwhmest must be given in pixels. Optionally pfix can be specified and in the case of a single gaussian or lorentzian singlet can be a string. In it is coded which parameters should be held constant during the fix. Any combination of 'p' (amplitude), 'c' (center), or 'f' (fwhm) is allowed; eg pfix='pc' means fix both the amplitude and center during the fit. In the case of more than one gaussian and/or lorentzian singlets, these parameters must be specified as arrays of numbers. The length of the arrays indicates the number of singlets to fit and must be the same for all the p*est parameters.
If no parameters are to be fixed for any of the singlets, pfix can be set to the empty string. However, if at least one parameter of one singlet is to be fixed, pfix must be an array of strings and have a length equal to the p*est arrays. Singlets which are not to have any parameters fixed should be represented as an empty string in the pfix array. So, for example, if one desires to fit three singlets and fix the fwhm of the middle one, one must specify pfix=['', 'f', ''], the empty strings indicating no parameters of the zeroth and second singlet should be held constant.
In the case of multifit=True, the initial estimates, whether from the p*est parameters or from a file (see below), will be applied to the location of the first fit. This is normally the bottom left corner of the region selected. If masked, not enough good points to perform a fit, or the attempted fit fails, the fitting proceeds to the next pixel with the pixel value of the lowest numbered axis changing the fastest. Once a successful fit has been performed, subsequent fits will use the results of a fit for a nearest pixel for which a previous fit was successful as the initial estimate for the parameters at the current location. The fixed parameter string will be honored for every fit performed when multifit=True.
One specifies what type of PCF profile to fit via the pfunc parameter. A PCF function is one that can be parameterized by a peak, center, and FWHM, as both gaussian and lorentzian singlets can. If all singlets to be fit are gaussians, one can set pfunc equal to the empty string and all snglets will be assumed to be gaussians. If at least one lorentzian is to be fit, pfunc must be specified as a string (in the case of a single singlet) or an array of strings (in the case of multiple singlets). The position of each string corresponds to the positions of the initial estimates in the p*est and pfix arrays. Minimal match ('g', 'G', 'l', or 'L') is supported. So, if one wanted to simultaneously fit two gaussian and two lorentzian singlets, the zeroth and last of which were lorentzians, one would specify pfunc=['L', 'G', 'G', 'L'].
ESTIMATES FILE FOR GAUSSIAN SINGLETS (NONRECOMMENDED METHOD) Initial estimates for gaussian singlets can be specified in an estimates file. Estimates files may be deprecated in the future in favor of the p*est parameters, so it is recommended users use those parameters instead. If an estimates file is desired to be used, the p*est parameters must be 0 or empty and mgncomps must be 0 or empty. Only gaussian singlets can be specified in an estimates file. If one desires to fit one or more gaussian multiplets and/or one or more lorentzian singlets simultaneously, the p*est parameters must be used to specify the initial parameters of all gaussian singlets to fit; one cannot use an estimates file in this case. If an estimates file is specified, a polynomial can be fit simultaneously by specifying the poly parameter. The estimates file must contain initial estimates of parameters for all gaussian singlets to be fit. The number of gaussian singlets to fit is gotten from the number of estimates in the file. The file can contain comments which are indicated by a '\#' at the beginning of a line. All non-comment lines will be interpreted as initial estimates. The format of such a line is
[peak intensity], [center], [fwhm], [optional fixed parameter string]
The first three values are required and must be numerical values. The peak intensity must be expressed in image brightness units, while the center must be specified in pixels offset from the zeroth pixel, and fwhm must be specified in pixels. The fourth value is optional and if present, represents the parameter(s) that should be held constant during the fit. Any combination of the characters 'p' (peak), 'c' (center), and 'f' (fwhm) are permitted, eg 'fc' means hold the fwhm and the center constant during the fit. Fixed parameters will have no error associated with them. Here is an example file:
egin{verbatim} # estimates file indicating that two gaussians should be fit # first guassian estimate, peak=40, center at pixel number 10.5, fwhm = 5.8 pixels, all parameters allowed to vary during # fit 40, 10.5, 5.8 # second gaussian, peak = 4, center at pixel number 90.2, fwhm = 7.2 pixels, hold fwhm constant 4, 90.2, 7.2, f # end file nd{verbatim}
GAUSSIAN MULTIPLET FITTING Any number of gaussian multiplets, each containing any number of two or more components, can be simultaneously fit, optionally with a polynomial and/or any number of gaussian and/or lorentzian singlets, the only caveat being that the number of parameters to be fit should be significantly less than the number of data points. The gmncomps parameter indicates the number of multiplets to fit and the number of components in each multiplet. In the case of a single multiplet, an integer (\>1) can be specified. For example, mgncomps=4 means fit a single quadruplet of gaussians. In the case of 2 or more multiplets, and array of integers (all \>1) must be specified. For example, gmncomps=[2, 4, 3] means 3 seperate multiples are to be fit, the zeroth being a doublet, the first being a quadruplet, and the second being a triplet.
Initial estimates of all gaussians in all multiplets are specified via the gm*est parameters which must be arrays of numbers. The order starts with the zeroth component of the zeroth multiplet to the last component of the zeroth multiplet, then the zeroth component of the first multiplet to the last compoenent of the first multiplet, etc to the zeroth component of the last multiplet to the last element of the last multiplet. The zeroth element of a multiplet is defined as the reference component of that multiplet and has the special significance that it is the profile to which all constraints of all other profiles in that multiplet are referenced (see below). So, in our example of gmncomps=[2, 4, 3], gmampest, gmcenterest, and gmfwhmest must each be nine (the total number of individual gaussian profiles summed over all multiplets) element arrays. The zeroth, second, and sixth elements represent parameters of the reference profiles in the zeroth, first, and second multiplet, respectively.
The fixed relationships between the non-reference profile(s) and the reference profile of a multiplet are specified via the gmampcon, gmcentercon, and gmfwhmcon parameters. At least one, and any combination, of constraints can be specified for any non-reference component of a multiplet. The amplitude ratio of a non-reference line to that of the reference line is set in gmampcon. The ratio of the fwhm of a non-reference line to that of the reference line is set in gmfwhmcon. The offset in pixels of the center position of a non-reference line to that of the reference line is set in gmcentercon. In the case where a parameter is not constrained for any non-reference line of any multiplet, the value of the associated parameter must be 0. In the case of a single doublet, a constraint may be specified as a number or an array of a single number. For example, mgncomps=2 and gmampcon=0.65 and gmcentercon=[32.4] means there is a single doublet to fit where the amplitude ratio of the first to the zeroth line is constained to be 0.65 and the center of the first line is constrained to be offset by 32.4 pixels from the center of the zeroth line. In cases of a total of three or more gaussians, the constraints parameters must be specified as arrays with lengths equal to the total number of gaussians summed over all multiplets minus the number of reference lines (one per multiplet, or just number of multiplets, since reference lines cannot be constrained by themselves). In the cases where an array must be specified but a component in that array does not have that constraint, 0 should be specified. Here's an example
gmncomps=[2, 4, 3] gmampcon= [ 0 , 0.2, 0 , 0.1, 4.5, 0 ] gcentercon=[24.2, 45.6, 92.7, 0 , -22.8, -33.5] gfwhmcon=''
In this case we have our previous example of one doublet, one quadruplet, and one triplet. The first component of the doublet has the constraint that its center is offset by 24.2 pixels from the zeroth (reference) component. The first component of the quadruplet is constrained to have an amplitude of 0.2 times that of the quadruplet's zeroth component and its center is constrained to be offset by 45.6 pixels from the reference component. The second component of the quadruplet is constained to have its center offset by 92.7 pixels from the associated reference component and the third component is constrained to have an amplitude of 0.1 times that of the associated reference component. The first component of the triplet is constrained to have an amplitude of 4.5 times that of its associated reference component and its center is constrained to be offset by -22.8 pixels from the reference component's center. The second component of the triplet is constrained to have its center offset by -33.5 pixels from the center of the reference component. No lines have FWHM constraints, so the empty string can be given for that parameter. Note that using 0 to indicate no constraint for line center means that one cannot specify a line centered at the same position as the reference component but having a different FWHM from the reference component. If you must specify this very unusual case, try using a very small positive (or even negative) value for the center constraint.
Note that when a parameter for a line is constrained, the corresponding value for that component in the corresponding gm*est array is ignored and the value of the constrained parameter is automatically used instead. So let's say, for our example above, we had specified the following estimates:
gmampest = [ 1, .2, 2, .1, .1, .5, 3, 2, 5] gmcenterest = [20, 10 , 30, 45.2, 609 , -233, 30, -859, 1]
Before any fitting is done, the constraints would be taken into account and these arrays would be implicitly rewritten as:
gmampest = [ 1, .2, 2, .4, .1, .2, 3, 13.5, 5 ] gmcenterest = [20, 44.2, 30, 75.6, 127.7, -233, 30, 7.2, -3.5]
The value of gmfwhmest would be unchanged since there are no FWHM constraints in this example.
In addition to be constrained by values of the reference component, parameters of individual components can be fixed. Fixed parameters are specified via the gmfix parameter. If no parameters are to be fixed, gmfix can be specified as the empty string or a zero element array. In the case where any parameter is to be fixed, gmfix must be specified as an array of strings with length equal to the total number of components summed over all multiplets. These strings encode which parameters to be fixed for the corresponding components. If a component is to have no parameters fixed, an empty string is used. In other cases one or more of any combination of parameters can be fixed using 'p', 'c', and/or 'f' described above for fixing singlet parameters. There are a couople of special cases to be aware of. In the case where a non-reference component parameter is constrained and the corresponding reference component parameter is set as fixed, that parameter in the non-reference parameter will automatically be fixed even if it was specified not to be fixed in the gmfix array. This is the only way the constraint can be honored afterall. In the converse case of when a constrained parameter of a non-reference component is specified as fixed, but the corresponding parameter in the reference component is not specified to be fixed, an error will occur. Fixing an unconstrained parameter in a non-reference component is always legal as is fixing any combination of parameters in a reference component (with the above caveat that corresponding constrained parameters in non-reference components will be silently held fixed as well).
The same rules that apply to singlets when multifit=True apply to multiplets.
LIMITING RANGES FOR SOLUTION PARAMETERS In cases of low (or no) signal to noise spectra, it is still possible for the fit to converge, but often to a nonsensical solution. The astronomer can use her knowledge of the source to filter out obviously bogus solutions. Any solution which contains a NaN value as a value or error in any one of its parameters is automatically marked as invalid.
One can also limit the ranges of solution parameters to known 'good' values via the goodamprange, goodcenterrange, and goodfwhmrange parameters. Any combination can be specified and the limit constraints will be ANDed together. The ranges apply to all PCF components that might be fit; choosing ranges on a component by component basis is not supported. If specified, an array of exactly two numerical values must be given to indicate the range of acceptable solution values for that parameter. goodamprange is expressed in terms of image brightness units. goodcenterrange is expressed in terms of pixels from the zeroth pixel in the specified region. goodfwhmrange is expressed in terms of pixels (only non-negative values should be given for FWHM range endpoints). In the case of a multiple-PCF fit, if any of the corresponding solutions are outside the specified ranges, the entire solution is considered to be invalid.
In addition, solutions for which the absolute value of the ratio of the amplitude error to the amplitude exceeds 100 or the ratio of the FWHM error to the FWHM exceeds 100 are automatically marked as invalid.
POWER LOGARITHMIC POLYNOMIAL AND LOGARITHMIC TRANSFORMED POLYNOMIAL FITTING Fitting of a sngle power logarithmic polynomial or a single logarithmic transformed polynomial function is supported. No other functions may be fit simultaneously with either of these; if parameters relating to other functions are supplied simultaneously with parameters relating to these functions, an exception will occur. For details of the functional forms, see the introduction of this document.
The set of c0 ... cn coefficients (as defined previously) can be solved for. Initial estimates for the c values should be supplied via the plpest or ltpest parameters, depending on which form is being fit. The number of values given in this array will be the number of coeffecients that are solved for. One may specify which coefficients should be held fixed during the fit in the plpfix or ltpfix array. If supplied, this array should have the same number of elements as its respective initial estimates array. A value of True means the corresponding coefficient will be held fixed during the fit. An empty array indicates that no parameters will be held fixed. This is the default.
Because the logarithm of the ordinate values must be taken before fitting a logarithmic transformed polynomial, all non-positive pixel values are effectively masked for the purposes of fitting.
INCLUDING STANDARD DEVIATIONS OF PIXEL VALUES If the standard deviations of the pixel values in the input image are known and they vary in the image (eg they are higher for pixels near the edge of the band), they can be included in the sigma parameter. This parameter takes either an array or an image name. The array or image must have one of three shapes: 1. the shape of the input image, 2. the same dimensions as the input image with the lengths of all axes being one except for the fit axis which must have length corresponding to its length in the input image, or 3. be one dimensional with lenght equal the the length of the fit axis in the input image. In cases 2 and 3, the array or pixels in sigma will be replicated such that the image that is ultimately used is the same shape as the input image. The values of sigma must be non-negative. It is only the relative values that are important. A value of 0 means that pixel should not be used in the fit. Other than that, if pixel A has a higher standard deviation than pixel B, then pixel A is noisier than pixel B and will receive a lower weight when the fit is done. The weight of a pixel is the usual
weight = 1/(sigma*sigma)
In the case of multifit=F, the sigma values at each pixel along the fit axis in the hyperplane perpendicular to the fit axis which includes that pixel are averaged and the resultant averaged standard deviation spectrum is the one used in the fit. Internally, sigma values are normalized such that the maximum value is 1. This mitigates a known overflow issue.
One can write the normalized standard deviation image used in the fit but specifying its name in outsigma. This image can then be used as sigma for subsequent runs.
RETURNED DICTIONARY STRUCTURE The returned dictionary has a (necessarily) complex structure. First, there are keys 'xUnit' and 'yUnit' whose values are the abscissa unit and the ordinate unit described by simple strings. Next there are arrays giving a broad overview of the fit quality. These arrays have the shape of the specified region collapsed along the fit axis with the axis corresponding to the fit axis having length of 1:
attempted: a boolean array indicating which fits were attempted (eg if too few unmasked points, a fit will not be attempted). converged: a boolean array indicating which fits converged. False if the fit was not attempted. valid: a boolean array indicating which solutions fall within the specified valid ranges of parameter space (see section LIMITING RANGES FOR SOLUTION PARAMETERS for details). niter: an int array indicating the number of iterations for each profile, \<0 if the fit did not converge ncomps: the number of components (gaussian singlets + lorentzian singlets + gaussian multiplets + polynomial) fit for the profile, \<0 if the fit did not converge direction: a string array containing the world direction coordinate for each profile
There is a 'type' array having number of dimensions equal to the number of dimensions in the above arrays plus one. The shape of the first n-1 dimensions is the same as the shape of the above arrays. The length of the last dimension is equal to the number of components fit. The values of this array are strings describing the components that were fit at each possition ('POLYNOMIAL', 'GAUSSIAN' in the case of gaussian singlets, 'LORENTZIAN' in the case of lorentzian singlets, and ''GAUSSIAN MULTPLET').
If any gaussian singlets were fit, there will be a subdictionary accessible via the 'gs' key which will have subkeys 'amp', 'ampErr', 'center', 'centerErr', 'fwhm', 'fwhmErr, 'integral', and 'integralErr'. Each of these arrays will have one more dimension than the overview arrays described above. The shape of the first n-1 dimensions will be the same as the shape of the arrays described above, while the final dimension will have length equal to the maximum number of gaussian singlets that were fit. Along this axis will be the corresponding fit result or associated error (depending on the array's associated key) of the fit for that singlet component number. In cases where the fit did not converge, or that particular component was excluded from the fit, a value of NAN will be present.
If any lorentzian singlets were fit, their solutions will be accessible via the 'ls' key. These arrays follow the same rules as the 'gs' arrays described above.
If any gaussian multiplets were fit, there will be subdictionaries accessible by keys 'gm0', 'gm1', ..., 'gm{n-1}' where n is the number of gaussian muliplets that were fit. Each of these dictionaries will have the same arrays described above for gaussian singlets. The last dimension will have length equal to the number of components in that particular multiplet. Each pixel along the last axis will be the parameter solution value or error for that component number in the multiplet, eg the zeroth pixel along that axis contains the parameter solution or error for the reference component of the multiplet.
The polynomial coefficient solutions and errors are not returned, although they are logged.
If a power logarithmic polynomial was fit, there will be a subdictionary accessible via the 'plp' key which will have subkeys 'soltuion' and 'error' which will each have an array value. Each of these arrays will have one more dimension than the overview arrays described above. The shape of the first n-1 dimensions will be the same as the shape of the overview arrays described above, while the final dimension will have length equal to the number of parameters that were fit. Along this axis will be the corresponding fit result or associated error (depending on the array's associated key) of the fit. In cases where the fit was not attempted or did not converge, a value of NAN will be present.
OUTPUT IMAGES In addition to the returned dictionary, optionally one or more of any combination of output images can be written. The model and residual parameters indicate the names of the model and residual images to be written; blank values inidcate that these images should not be written.
One can also write none, any or all of the solution and error images for gaussian singlet, lorentzian singlet, and gaussian multiplet fits via the parameters amp, amperr, center, centererr, fwhm, fwhmerr, integral, integralerr when doing multi-pixel fits. For a power logarithmic polynomial or a logarithmic transformed polynomial fit, plpsol or ltpsol and plperr or ltpsol are the names of the solution and error images to write, respectively.
These images simply contain the arrays described for the associated parameter solutions or errors described in previous sections. In the case of lorentzian singlets, '\_ls' is appended to the image names, in the case of gaussian multiplets, '\_gm0', '\_gm1', etc are appended to the image names to distinguish each multiplet. Pixels for which fits were not attempted or did not converge will be masked as bad. The last axis of these images is a linear axis and repesents component (or coeficient, depending on the funciton fit) number (and is named accordingly).
Writing analogous images for polynomial coefficients is not supported.
Input Parameters: box Rectangular box in direction coordinate blc, trc. Default: entire image (''). region Region of interest. See help par.region for details. Default is entire image. chans Channels to use. See 'help par.chans' for examples. Channels must be contigous. Default: all channels (''). stokes Stokes planes to use. Planes must be contiguous. Default: all stokes (''). axis The profile axis. Default: use the spectral axis if one exists, axis 0 otherwise (\<0). -1 mask Mask to use. See help par.mask. Default is none. ngauss Number of Gaussian elements. Default: 1. 1 poly Order of polynomial element. Default: do not fit a polynomial (\<0). -1 estimates Name of file containing initial estimates. Default: No initial estimates (''). minpts Minimum number of unmasked points necessary to attempt fit. 1 multifit If true, fit a profile along the desired axis at each pixel in the specified region. If false, average the non-fit axis pixels and do a single fit to that average profile. Default False. false model Name of model image. Default: do not write the model image (''). residual Name of residual image. Default: do not write the residual image (''). amp Prefix of name of amplitude solution image. Name of image will have gaussian component number appended. Default: do not write the image (''). amperr Prefix of name of amplitude error solution image. Name of image will have gaussian component number appended. Default: do not write the image (''). center Prefix of name of center solution image. Name of image will have gaussian component number appended. Default: do not write the image (''). centererr Prefix of name of center error solution image. Name of image will have gaussian component number appended. Default: do not write the image (''). fwhm Prefix of name of FWHM solution image. Name of image will have gaussian component number appended. Default: do not write the image (''). fwhmerr Prefix of name of FWHM error solution image. Name of image will have gaussian component number appended. Default: do not write the image (''). integral Prefix of name of integral solution image. Name of image will have gaussian component number appended. Default: do not write the image (''). integralerr Prefix of name of integral error solution image. Name of image will have gaussian component number appended. Default: do not write the image (''). stretch Stretch the mask if necessary and possible? See help par.stretch. false logresults Output results to logger? true pampest Initial estimate PCF profile amplitudes. pcenterest Initial estimate PCF profile centers, in pixels. pfwhmest Initial estimate PCF profile FWHMs, in pixels. pfix PCF parameters to fix during fit. Any combination of 'p', 'c', or 'f'. gmncomps Number of components in each gaussian multiplet to fit 0 gmampcon The amplitude ratio constraints for non-reference components to reference component in gaussian multiplets. gmcentercon The center offset constraints (in pixels) for non-reference components to reference component in gaussian multiplets. gmfwhmcon The FWHM ratio constraints for non-reference components to reference component in gaussian multiplets. gmampest Initial estimate of individual gaussian amplitudes in gaussian multiplets. 0.0 gmcenterest Initial estimate of individual gaussian centers in gaussian multiplets, in pixels. 0.0 gmfwhmest Initial estimate of individual gaussian FWHMss in gaussian multiplets, in pixels. 0.0 gmfix Parameters of individual gaussians in gaussian multiplets to fix during fit. spxtype Type of function to fit. 'plp' $=\>$ power logarithmic polynomial, 'ltp' $=\>$ logarithmic transformed polynomial. spxest REQUIRED. Initial estimates as array of numerical values for the spectral index function coefficients. eg [1.5, -0.8] if fitting a plp function thought to be close to 1.5*(x/div)**(-0.8) or [0.4055, -0.8] if fitting an lpt function thought to be close to ln(1.5) - 0.8*ln(x/div). spxfix Fix the corresponding spectral index function coefficients during the fit. True$=\>$hold fixed. div Divisor (numerical value or quantity) to use in the logarithmic terms of the plp or ltp function. 0 $=\>$ calculate a useful value on the fly. 0 spxsol Name of the spectral index function coefficient solution image to write. spxerr Name of the spectral index function coefficient error image to write. logfile File in which to log results. Default is not to write a logfile. append Append results to logfile? Logfile must be specified. Default is to append. False means overwrite existing file if it exists. true pfunc PCF singlet functions to fit. 'gaussian' or 'lorentzian' (minimal match supported). Unspecified means all gaussians. goodamprange Acceptable amplitude solution range. [0.0] $=\>$ all amplitude solutions are acceptable. 0.0 goodcenterrange Acceptable center solution range in pixels relative to region start. [0.0] $=\>$ all center solutions are acceptable. 0.0 goodfwhmrange Acceptable FWHM solution range in pixels. [0.0] $=\>$ all FWHM solutions are acceptable. 0.0 sigma Standard deviation array or image name. outsigma Name of output image used for standard deviations. Ignored if sigma is empty. planes Planes along fit axis to use in the fit. Empty means use all planes. All values must be non-negative.
Example:
''' ia.open('myspectrum.im') res = ia.fitprofile(ngauss=2, box='3,3,4,5', poly=2, multifit=true) '''
--------------------------------------------------------------------------------
""" return _image.image_fitprofile(self, *args, **kwargs)
def fitcomponents(self, *args, **kwargs): """ fitcomponents(self, box = string(""), region = initialize_variant(""), chans = initialize_variant(""), stokes = string(""), mask = initialize_variant(""), includepix = initialize_vector(1, (double)-1), excludepix = initialize_vector(1, (double)-1), residual = string(""), model = string(""), estimates = string(""), logfile = string(""), append = True, newestimates = string(""), complist = string(""), overwrite = False, dooff = False, offset = 0.0, fixoffset = False, stretch = False, rms = initialize_variant(""), noisefwhm = initialize_variant("")) -> record
Summary Fit 2-dimensional models to an image.
Description
OVERVIEW
This application is used to fit one or more two dimensional gaussians to sources in an image as well as an optional zero-level offset. Fitting is limited to a single polarization but can be performed over several contiguous spectral channels. If the image has a clean beam, the report and returned dictionary will contain both the convolved and the deconvolved fit results.
When dooff is False, the method returns a dictionary with three keys, 'converged', 'results', and 'deconvolved'. The value of 'converged' is a boolean array which indicates if the fit converged on a channel by channel basis. The value of 'results' is a dictionary representing a component list reflecting the fit results. In the case of an image containing beam information, the sizes and position angles in the 'results' dictionary are those of the source(s) convolved with the restoring beam, while the same parameters in the 'deconvolved' dictionary represent the source sizes deconvolved from the beam. In the case where the image does not contain a beam, 'deconvolved' will be absent. Both the 'results' and 'deconvolved' dictionaries can be read into a component list tool (default tool is named cl) using the fromrecord() method for easier inspection using tool methods, eg
cl.fromrecord(res['results'])
although this currently only works if the flux density units are conformant with Jy.
There are also values in each component subdictionary not used by cl.fromrecord() but meant to supply additional information. There is a 'peak' subdictionary for each component that provides the peak intensity of the component. It is present for both 'results' and 'deconvolved' components. There is also a 'sum' subdictionary for each component indicated the simple sum of pixel values in the the original image enclosed by the fitted ellipse. There is a 'channel' entry in the 'spectrum' subdictionary which provides the zero-based channel number in the input image for which the solution applies. In addtion, if the image has a beam(s), then there will be a 'beam' subdictionary associated with each component in both the 'results' and 'deconvolved' dictionaries. This subdictionary will have three keys: 'beamarcsec' will be a subdictionary giving the beam dimensions in arcsec, 'beampixels' will have the value of the beam area expressed in pixels, and 'beamster' will have the value of the beam area epressed in steradians. Also, if the image has a beam(s), in the component level dictionaries will be an 'ispoint' entry with an associated boolean value describing if the component is consistent with a point source.
If dooff is True, in addtion to the specified number of gaussians, a zero-level offset will also be fit. The initial estimate for this offset is specified using the offset parameter. Units are assumed to be the same as the image brightness units. The zero level offset can be held constant during the fit by specifying fixoffset=True. In the case of dooff=True, the returned dictionary contains two additional keys, 'zerooff' and 'zeroofferr', which are both dictionaries containing 'unit' and 'value' keys. The values associated with the 'value' keys are arrays containing the the fitted zero level offset value and its error, respectively, for each channel. In cases where the fit did not converge, these values are set to NaN. The value associated with 'unit' is just the image brightness unit.
The region can either be specified by a box(es) or a region. Ranges of pixel values can be included or excluded from the fit. If specified using the box parameter, multiple boxes can be given using the format box='blcx1, blcy1, trcx1, trcy1, blcx2, blcy2, trcx2, trcy2, ... , blcxN, blcyN, trcxN, trcyN' where N is the number of boxes. In this case, the union of the specified boxes will be used.
If specified, the residual and/or model images for successful fits will be written.
If an estimates file is not specified, an attempt is made to estimate initial parameters and fit a single Gaussian. If a multiple Gaussian fit is desired, the user must specify initial estimates via a text file (see below for details).
The user has the option of writing the result of the fit to a log file, and has the option of either appending to or overwriting an existing file.
The user has the option of writing the (convolved) parameters of a successful fit to a file which can be fed back to fitcomponents() as the estimates file for a subsequent run.
If specified and positive, the value of rms is used to calculate the parameter uncertainties, otherwise, the rms in the selected region in the relevant channel is used for these calculations.
The noisefwhm parameter represents the noise-correlation beam FWHM. If specified as a quantity, it should have angular units. If specified as a numerical value, it is set equal to that number of pixels. If specified and greater than or equal to the pixel size, it is used to calculate parameter uncertainties using the correlated noise equations (see below). If it is specified but less than a pixel width, the the uncorrelated noise equations (see below) are used to compute the parameter uncertainties. If it is not specified and the image has a restoring beam(s), the the correlated noise equations are used to compute parameter uncertainties using the geometric mean of the relevant beam major and minor axes as the noise-correlation beam FWHM. If noisefwhm is not specified and the image does not have a restoring beam, then the uncorrelated noise equations are used to compute the parameter uncertainties.
SUPPORTED UNITS
Currently only images with brightness units conformant with Jy/beam, Jy.km/s/beam, and K are fully supported for fitting. If your image has some other base brightness unit, that unit will be assumed to be equivalent to Jy/pixel and results will be calculated accordingly. In particular, the flux density (reported as Integrated Flux in the logger and associated with the 'flux' key in the returned component subdictionary(ies)) for such a case represents the sum of pixel values.
Note also that converting the returned results subdictionary to a component list via cl.fromrecord() currently only works properly if the flux density units in the results dictionary are conformant with Jy. If you need to be able to run cl.fromrecord() on the resulting dictionary you can first modify the flux density units by hand to be (some prefix)Jy and then run cl.fromrecord() on that dictionary, bearing in mind your unit conversion.
If the input image has units of K, the flux density of components will be reported in units of [prefix]K*rad*rad, where prefix is an SI prefix used so that the numerical value is between 1 and 1000. To convert to units of K*beam, determine the area of the appropriate beam, which is given by pi/(4*ln(2))*bmaj*bmin, where bmaj and bmin are the major and minor axes of the beam, and convert to steradians (=rad*rad). This value is included in the beam portion of the component subdictionary (key 'beamster'). Then divide the numerical value of the logged flux density by the beam area in steradians. So, for example
egin{verbatim} # run on an image with K brightness units res = imfit(...) # get the I flux density in K*beam of component 0 comp = res['results']['component0'] flux_density_kbeam = comp['flux']['value'][0]/comp['beam']['beamster'] nd{verbatim}
FITTING OVER MULTIPLE CHANNELS
For fitting over multiple channels, the result of the previous successful fit is used as the estimate for the next channel. The number of gaussians fit cannot be varied on a channel by channel basis. Thus the variation of source structure should be reasonably smooth in frequency to produce reliable fit results.
MASK SPECIFICATION
Mask specification can be done using an LEL expression. For example
mask = ''myimage'\>5' will use only pixels with values greater than 5.
INCLUDING AND EXCLUDING PIXELS
Pixels can be included or excluded from the fit based on their values using these parameters. Note that specifying both is not permitted and will cause an error. If specified, both take an array of two numeric values.
ESTIMATES
Initial estimates of fit parameters may be specified via an estimates text file. Each line of this file should contain a set of parameters for a single gaussian. Optionally, some of these parameters can be fixed during the fit. The format of each line is
peak intensity, peak x-pixel value, peak y-pixel value, major axis, minor axis, position angle, fixed
The fixed parameter is optional. The peak intensity is assumed to be in the same units as the image pixel values (eg Jy/beam). The peak coordinates are specified in pixel coordinates. The major and minor axes and the position angle are the convolved parameters if the image has been convolved with a clean beam and are specified as quantities. The fixed parameter is optional and is a string. It may contain any combination of the following characters 'f' (peak intensity), 'x' (peak x position), 'y' (peak y position), 'a' (major axis), 'b' (minor axis), 'p' (position angle).
In addition, lines in the file starting with a \# are considered comments.
An example of such a file is:
egin{verbatim} # peak intensity must be in map units 120, 150, 110, 23.5arcsec, 18.9arcsec, 120deg 90, 60, 200, 46arcsec, 23arcsec, 140deg, fxp nd{verbatim}
This is a file which specifies that two gaussians are to be simultaneously fit, and for the second gaussian the specified peak intensity, x position, and position angle are to be held fixed during the fit.
ERROR ESTIMATES
Error estimates are based on the work of Condon 1997, PASP, 109, 166. Key assumptions made are: * The given model (elliptical Gaussian, or elliptical Gaussian plus constant offset) is an adequate representation of the data * An accurate estimate of the pixel noise is provided or can be derived (see above). For the case of correlated noise (e.g., a CLEAN map), the fit region should contain many 'beams' or an independent value of rms should be provided. * The signal-to-noise ratio (SNR) or the Gaussian component is large. This is necessary because a Taylor series is used to linearize the problem. Condon (1997) states that the fractional bias in the fitted amplitude due to this assumption is of order 1/(S*S), where S is the overall SNR of the Gaussian with respect to the given data set (defined more precisely below). For a 5 sigma 'detection' of the Gaussian, this is a 4% effect. * All (or practically all) of the flux in the component being fit falls within the selected region. If a constant offset term is simultaneously fit and not fixed, the region of interest should be even larger. The derivations of the expressions summarized in this note assume an effectively infinite region.
Two sets of equations are used to calculate the parameter uncertainties, based on if the noise is correlated or uncorrelated. The rules governing which set of equations are used have been described above in the description of the noisefwhm parameter.
In the case of uncorrelated noise, the equations used are
f(A) = f(I) = f(M) = f(m) = k*s(x)/M = k*s(y)/m = (s(p)/sqrt(2))*((M*M - m*m)/(M*m)) = sqrt(2)/S
where s(z) is the uncertainty associated with parameter z, f(z) = s(z)/abs(z) is the fractional uncertainty associated with parameter z, A is the peak intensity, I is the flux density, M and m are the FWHM major and minor axes, p is the position angle of the component, and k = sqrt(8*ln(2)). s(x) and s(y) are the direction uncertainties of the component measured along the major and minor axes; the resulting uncertainties measured along the principle axes of the image direction coordinate are calculated by propagation of errors using the 2D rotation matrix which enacts the rotation through the position angle plus 90 degrees. S is the overall signal to noise ratio of the component, which, for the uncorrelated noise case is given by
S = (A/(k*h*r))*sqrt(pi*M*m)
where h is the pixel width of the direction coordinate and r is the rms noise (see the discussion above for the rules governing how the value of r is determined).
For the correlated noise case, the same equations are used to determine the uncertainties as in the uncorrelated noise case, except for the uncertainty in I (see below). However, S is given by
S = (A/(2*r*N)) * sqrt(M*m) * (1 + ((N*N/(M*M)))**(a/2)) * (1 + ((N*N/(m*m)))**(b/2))
where N is the noise-correlation beam FWHM (see discussion of the noisefwhm parameter for rules governing how this value is determined). '**' indicates exponentiation and a and b depend on which uncertainty is being calculated. For sigma(A), a = b = 3/2. For M and x, a = 5/2 and b = 1/2. For m, y, and p, a = 1/2 and b = 5/2. f(I) is calculated in the correlated noise case according to
f(I) = sqrt( f(A)*f(A) + (N*N/(M*m))*(f(M*f(M) + f(m)*f(m))) )
Note well the following caveats: * Fixing Gaussian component parameters will tend to cause the parameter uncertainties reported for free parameters to be overestimated. * Fitting a zero level offset that is not fixed will tend to cause the reported parameter uncertainties to be slightly underestimated. * The parameter uncertainties will be inaccurate at low SNR (a ~10% for SNR = 3). * If the fitted region is not considerably larger than the largest component that is fit, parameter uncertainties may be mis-estimated. * An accurate rms noise measurement, r, for the region in question must be supplied. Alternatively, a sufficiently large signal-free region must be present in the selected region (at least about 25 noise beams in area) to auto-derive such an estimate. * If the image noise is not statistically independent from pixel to pixel, a reasonably accurate noise correlation scale, N, must be provided. If the noise correlation function is not approximately Gaussian, the correlation length can be estimated using
N = sqrt(2*ln(2)/pi)* double-integral(dx dy C(x,y))/sqrt(double-integral(dx dy C(x, y) * C(x,y)))
where C(x,y) is the associated noise-smoothing function * If fitted model components have significan spatial overlap, the parameter uncertainties are likely to be mis-estimated (i.e., correlations between the parameters of separate components are not accounted for). * If the image being analyzed is an interferometric image with poor uv sampling, the parameter uncertainties may be significantly underestimated.
The deconvolved size and position angle errors are computed by taking the maximum of the absolute values of the differences of the best fit deconvolved value of the given parameter and the deconvolved size of the eight possible combinations of (FWHM major axis +/- major axis error), (FWHM minor axis +/- minor axis error), and (position andle +/- position angle error). If the source cannot be deconvolved from the beam (if the best fit convolved source size cannot be deconvolved from the beam), upper limits on the deconvolved source size are sometimes reported. These limits simply come from the maximum major and minor axes of the deconvolved gaussians taken from trying all eight of the aforementioned combinations. In the case none of these combinations produces a deconvolved size, no upper limit is reported.
EXAMPLE:
Here is how one might fit two gaussians to multiple channels of a cube using the fit from the previous channel as the initial estimate for the next. It also illustrates how one can specify a region in the associated continuum image as the region to use as the fit for the channel.
egin{verbatim} imagename = 'co_cube.im' # specify region using region from continuum region = 'continuum.im:source.rgn' chans = '2~20' # only use pixels with positive values in the fit excludepix = [-1e10,0] # estimates file contains initial parameters for two Gaussians in channel 2 estimates = 'initial_estimates.txt' logfile = 'co_fit.log' # append results to the log file for all the channels append = 'True' ia.open(imagename) ia.fitcomponents(region=region, chans=chans, excludepix=excludepix, estimates=estimates, logfile=logfile, append=append) nd{verbatim}
Input Parameters: box One or more boxes to use for fit region(s). Default is to use the entire plane. region The 2-D region of interest to fit. Default is entire plane. If both box and region are specified, box is used and region is not. chans Channels to use in the fit. See 'help par.chans' for examples. Default is 0 (first plane). stokes The polarization to use in the fit. Default is to use the first stokes plane. mask Mask to use. See help par.mask. Default is none. includepix Range of pixel values to include. Default is to include all pixels. -1 excludepix Range of pixel values to exclude. Default is to exclude no pixels. -1 residual Name of the residual image to write. Default is not to write the residual. model Name of the model image to write. Default is not to write the model. estimates Name of the input estimates file. Default is to auto-estimate in which case a single gaussian will be fit. logfile File in which to log results. Default is not to write a logfile. append Append results to logfile? Logfile must be specified. Default is to append. False means overwrite existing file if it exists. true newestimates File to which to write results in 'estimates' format suitable as estimates input for another run. Default is do not write an estimates file. complist Output component list table name. Default is do not write a component list table. overwrite Overwrite component list if it already exists. Default is False. false dooff Also fit a zero level offset? Default is False false offset Initial estimate of zero-level offset. Only used if doff is True. Default is 0.0 0.0 fixoffset Keep the zero level offset fixed during fit? Default is False false stretch Stretch the mask if necessary and possible? See help par.stretch. false rms RMS to use in calculation of uncertainties. Numeric or valid quantity (record or string). If numeric, it is given units of the input image. If quantity, units must conform to image units. If not positive, the rms of the residual image, in the region of the fit, is used. noisefwhm Noise correlation beam FWHM. If numeric value, interpreted as pixel widths. If quantity (dictionary, string), it must have angular units.
--------------------------------------------------------------------------------
""" return _image.image_fitcomponents(self, *args, **kwargs)
def fromrecord(self, *args, **kwargs): """ fromrecord(self, record, outfile = string("")) -> bool
Summary Generate an image from a record
Description
You can convert an associated image to a record (torecord) or imagepol tool functions will sometimes give you a record. This function (fromrecord) allows you to set the contents of an image tool to the content of the record
Input Parameters: record Record containing the image outfile The name of the diskfile to be created for image from record
Example:
''' # print ' ---- fromrecord Ex 1 ----' ia.maketestimage('image.large', overwrite=true) rec=ia.torecord() ia.close() ia.fromrecord(rec, 'testimage')
'''
--------------------------------------------------------------------------------
""" return _image.image_fromrecord(self, *args, **kwargs)
def getchunk(self, *args, **kwargs): """ getchunk(self, blc = initialize_vector(1, (int)-1), trc = initialize_vector(1, (int)-1), inc = initialize_vector(1, (int)1), axes = initialize_vector(1, (int)-1), list = False, dropdeg = False, getmask = False) -> variant
Summary Get the pixel values from a regular region of the image into an array
Description
This function returns the pixels (or optionally the pixel mask) from the \imagefile\ between {\stfaf blc} and {\stfaf trc} inclusively. Both float and complex valued images are supported. An increment may be specified with {\stfaf inc}. Note that if you retrieve too many pixels, you might cause swapping since the pixels are kept in memory.
Any illegal {\stfaf blc} values are set to zero. Any illegal {\stfaf trc} values are set to the end of the image. If any {\stfaf trc $\<$ blc}, you get the whole image for that axis. Any illegal {\stfaf inc} values are set to unity.
The argument {\stfaf axes} can be used to reduce the dimensionality of the output array. It specifies which pixel axes of the image to {f average} the data over. For example, consider a 3-D image. With {\stfaf axes=[0,1]} and all other arguments left at their defaults, the result would be a 1-D vector, a profile along the third axis, with the data averaged over the first two axes.
A related function is getregion which retrieves the pixels or \pixelmask\ from a potentially more complex region. Function {\stff getchunk} is retained because it is faster and therefore preferable for repeated operation in loops if the \pixelmask\ is not required and the region is a simple box.
If you set getmask=T, the return value is the 'pixelmask' rather than the 'pixel' image.
Input Parameters: blc Bottom-Left-Corner (beginning) of pixel section. Default is start of image. -1 trc Top-Right-Corner (end) of pixel section. Default is end of image. -1 inc increment (stride) along axes 1 axes Axes to average over. Default is none. -1 list List bounding box to logger? false dropdeg Drop degenerate axes? false getmask Get the pixel mask rather than the pixel values false
Example:
Suppose that we have a 3-dimensional image called {\sff im}. Then:
''' # print ' ---- getchunk Ex 1 ----' ia.fromshape(shape=[64,64,128]) pix = ia.getchunk() # all pixels ia.calcmask('T') # give image a mask pix = ia.getchunk([1,1,1], [10,10,1]) # 10 by 10 section of plane # 1 pix = ia.getchunk([1,1], [1,1]) # first spectrum pix = ia.getchunk(inc=[1,5]) # all planes, decimated by 5 in y mask = ia.getchunk(getmask=T) # Get pixelmask ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_getchunk(self, *args, **kwargs)
def getregion(self, *args, **kwargs): """ getregion(self, region = initialize_variant(""), axes = initialize_vector(1, (int)-1), mask = initialize_variant(""), list = False, dropdeg = False, getmask = False, stretch = False) -> variant
Summary Get pixels or mask from a region-of-interest of the image
Description
This function recovers the image pixel or \pixelmask\ values in the given region-of-interest. Regardless of the shape of the {\stfaf region} you have specified, the shape of the {\stfaf pixels} and {\stfaf pixelmask} arrays must necessarily be the bounding box of the specified region. If the region extends beyond the image, it is truncated.
Recall that the recovered \pixelmask\ will reflect both the \pixelmaskstored in the image, and the region\ (their masks are `anded') -- see the \htmlref{discussion}{IMAGE:MASKSANDREGIONS} in the introduction about this.
The argument {\stfaf axes} can be used to reduce the dimensionality of the output array. It specifies which pixel axes of the image to average the data over. For example, consider a 3-D image. With {\stfaf axes=[0,1]} and all other arguments left at their defaults, the result would be a 1-D vector, a profile along the third axis, with the data averaged over the first two axes.
This function differs in three ways from {\stff getchunk}. First, the region can be much more complex (e.g. a union of polygons) than the simple {\stfaf blc}, {\stfaf trc}, and {\stfaf inc} of {\stff getchunk} (although such a region can be created of course). Second, it can be used to recover the \pixelmask\ or the pixels. Third, it is less efficient than {\stff getchunk} for doing the same thing as {\stff getchunk}. So if you are interested in say, iterating through an image, getting a regular hyper-cube of pixels and doing something with them, then {\stff getchunk} will be faster. This would be especially noticeable if you iterated line by line through a large image.
Input Parameters: region The region of interest. See help par.region for details. Default is whole image. axes Axes to average over. Default is none. -1 mask Mask to use. See help par.mask. Default is none. list List the bounding box to the logger false dropdeg Drop degenerate axes false getmask Get the pixel mask rather than pixel values false stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false
Example:
Suppose that we have a 3-dimensional image called {\sff cube} and wish to recover the pixel from a simple regular region.
''' # print ' ---- getregion Ex 1 ----' ia.fromshape('cube', [64,64,64], overwrite=true) #r1=rg.box(blc=[10,10,10],trc=[30,40]) # Create region r1=rg.box([10,10,10],[30,40,40]) # Create region pixels=ia.getregion(r1) ia.close() # '''
Example:
''' # print ' ---- getregion Ex 2 ----' ia.fromshape('cube', [64,64,64], overwrite=true) pixels = ia.getregion() pixelmask = ia.getregion(getmask=T) # '''
In this example we recover first the pixels and then the pixel mask.
--------------------------------------------------------------------------------
""" return _image.image_getregion(self, *args, **kwargs)
def getprofile(self, *args, **kwargs): """ getprofile(self, axis = -1, function = string("mean"), region = initialize_variant(""), mask = string(""), unit = string(""), stretch = False, spectype = string("default"), restfreq = initialize_variant(""), frame = string("")) -> record
Summary Get values and mask for a one dimensional profile along a specified image axis by applying an aggregate function.
Description
This application returns information on a one-dimensional profile taken along a specified image axis. The region of interest is collapsed (a'la ia.collapse() along all axes orthogonal to the one specified, and) the specified aggregate function is applied to these pixels to generate the returned values.
The aggregate function must be one of the functions supported by ia.collapse; ie, 'flux', 'max', 'mean', 'median', 'min', 'rms', 'stdev', 'sum', and 'variance'. See the help for ia.collapse() for details regarding these functions. Minimum match and case insenstivity is supported.
One may specify the unit of the returned coordinate values. Unless axis is the spectral axis, unit must be conformant with the corresponding axis unit in the image coordinate system or it must be 'pixel' which signifies, pixel, rather than world, coordinate values should be calculated. If axis is the spectral axis, unit may be a velocity unit (assuming the coordinate system has a rest frequency or restfreq is specified) or a length unit. In these cases, the returned coordinate values will be converted to velocity or wavelength, respectively.
The parameter spectype may be used to specify the velocity or wavelength type for the returned coordinate values if profile is taken along spectral axis. Supported (minimum match, case insensitive) values) are 'relativistic velocity', 'beta', 'radio velocity', 'optical velocity', 'wavelength', 'air wavelength', 'default'. The 'default' value is equivalent to 'relativistic' if unit is a velocity unit or 'wavelength' if unit is a length unit.
The restfreq parameter allows one to set the rest frequency for the coordinates to be returned if axis is the spectral axis and unit is a velocity unit. If blank, the rest frequency associated with the image coordinate system is used.
The frame allows one to specify which kinematic reference frame that the returned coordinate values should be calculated in. It is only used if axis is the spectral axis and unit is unspecified or is specified and a frequency unit. If blank, the reference frame associated with the image coordinate system is used.
The returned dictionary contains the keys:
values: one-dimensional array along the specified axis containing values resulting from applying the specified aggregate function to corresponding pixels at the same location along that axis. mask: one-dimensional array of booleans of the resulting mask after applying the aggregate function, formed in the same way as that formed by ia.collapse. coords One-dimensional array of corresponding coordinate values along the specified axis in the specified unit (or the unit associated with the axis in the image coordinate system if unspecified). xUnit The unit used for calculating the values the coords array.
Input Parameters: axis Axis along which to determine profile. Must be specified -1 function Aggregate function to apply for collapse along axes orthogonal to specified axis. mean region The region of interest. See help par.region for details. Default is whole image. mask Mask to use. See help par.mask. Default is none. unit Unit of the returned abscissa values. Must either be 'pixel' or be conformant with image axis unit unless axis is the spectral axis. Default is the unit associated with axis in the image coordinate system. stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false spectype Velocity or wavelength type if profile taken along spectral axis. Supported (minimum match, case insensitive) values are 'relativistic velocity', 'beta', 'radio velocity', 'optical velocity', 'wavelength', 'air wavelength', 'default'. default restfreq Rest frequency to use when calculating coordinate values. Used only if axis is spectral axis and unit is not the unit associated with the axis in the coordinate system. Empty string means use the rest frequency associated with the image coordinate system frame Reference frame to use when calculating coordinate values. Used only if axis is spectral axis and unit is not the unit associated with the axis in the coordinate system. Empty string means use the reference frame associated with the image coordinate system
Example:
ia.open('myimage') # get the max pixel values along axis 2 res = ia.getprofile(axis=2, function='max')
# axis 2 is the spectral axis. Get the minimum pixel values along this axis # and specify that the returned coordinate values should be optical velocities # in km/s
res2 = ia.getprofile(axis=2, function='min', unit='km/s', spectype='optical')
ia.done()
--------------------------------------------------------------------------------
""" return _image.image_getprofile(self, *args, **kwargs)
def getslice(self, *args, **kwargs): """ getslice(self, x, y, axes = initialize_vector(2,(int)0, (int)1), coord = initialize_vector(1, (int)-1), npts = 0, method = string("linear")) -> record
Summary Get 1-D slice from the image
Description
This function returns a 1-D slice (the pixels and opionally the pixel mask) from the \imagefile. The slice is constrained to lie in a plane of two cardinal axes (e.g. XY or YZ). At some point this constraint will be relaxed. A range of interpolation schemes are available.
You specify the slice as a polyline giving the x ({\stfaf x}) and y ({\stfaf y}) coordinates and the axes of the plane holding that slice ({\stfaf axes}). As well, you must specify the absolute pixel coordinates of the other axes ({\stfaf coord}). This defaults to the first pixel (e.g. first plane).
The return value is a record with fields 'pixels' (interpolated intensity), 'mask' (interpolated mask), 'xpos' (x-location in absolute pixel coordinates), 'ypos' (y-location in absolute pixel coordinates), 'distance' (distance along slice in pixels), 'axes' (the x and y axes of slice).
Input Parameters: x Polyline x vertices in absolute pixel coordinates y Polyline y vertices in absolute pixel coordinates axes Pixel axes of plane holding slice. Default is first two axes. 01 coord Specify pixel coordinate for other axes. Default is first pixel. -1 npts Number of points in slice. Default is auto determination. 0 method The interpolation method, String from 'nearest', 'linear', 'cubic' linear
Example:
Suppose that we have a 2-dimensional image. Then:
''' # print ' ---- getslice Ex 1 ----' ia.maketestimage(); rec = ia.getslice (x=[1,20], y=[2,30]) # SLice from [1,2] -\> [20,30] print rec.keys() #['distance', 'xpos', 'axes', 'mask', 'ypos', 'pixel'] rec = ia.getslice (x=[1,20,25,11], y=[2,30,32,40]) # Polyline slice ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_getslice(self, *args, **kwargs)
def hanning(self, *args, **kwargs): """ hanning(self, outfile = string(""), region = initialize_variant(""), mask = initialize_variant(""), axis = -10, drop = True, overwrite = False, async = False, stretch = False, dmethod = string("copy")) -> image
Summary Convolve one axis of image with a Hanning kernel
Description
This application performs Hanning convolution of one axis of an image defined by
z[i] = 0.25*y[i-1] + 0.5*y[i] + 0.25*y[i+1] (equation 1)
where z[i] is the value at pixel i in the hanning smoothed image, and y[i-1], y[i], and y[i+1] are the values of the input image at pixels i-1, i, and i+1 respectively. It supports both float and complex valued images. The length of the axis along which the convolution is to occur must be at least three pixels in the selected region. Masked pixel values are set to zero prior to convolution. All nondefault pixel masks are ignored during the calculation.
The convolution is done in the image domain (i.e., not with an FFT).
If drop=False, the length of the output axis will be the same as that of the input axis. The output pixel values along the convolution axis will be related to those of the input values according to equation 1, except the first and last pixels. In that case,
z[0] = 0.5*(y[0] + y[1])
and,
z[N-1] = 0.5*(y[N-2] + y[N-1])
where N is the number of pixels along the convolution aixs. The pixel mask, ORed with the OTF mask if specified, is copied from the selected region of the input image to the output image. Thus for example, if the selected region in the input image has six planes along the convolution axis, and if the pixel values, which are all unmasked, on a slice along this axis are [1, 2, 5, 10, 17, 26], the corresponding output pixel values will be [1.5, 2.5, 5.5, 10.5, 17.5, 21.5].
If drop=True and dmethod='copy', the output image is the image calculated if drop=True, except that only the odd-numbered planes are kept. Furthermore, if the number of planes along the convolution axis in the selected region of the input image is even, the last odd number plane is also discarded. Thus, if the selected region has N pixels along the convolution axis in the input image, along the convolution axis the output image will have (N-1)/2 planes if N is odd, or (N-2)/2 planes if N is even. In this case, the pixel and mask values are copied directly, without further processing. Thus for example, if the selected region in the input image has six planes along the convolution axis, and if the pixel values, which are all unmasked, on a slice along this axis are [1, 2, 5, 10, 17, 26], the corresponding output pixel values will be [2.5, 10.5].
If drop=True and dmethod='mean', first the image described in the drop=False case is calculated. The first plane and last plane(s) of that image are then discarded as described in the drop=True, dmethod='copy' case. Then, the ith plane of the output image is calculated by averaging the (2*i)th and (2*i + 1)th planes of the intermediate image.Thus for example, if the selected region in the input image has six planes along the convolution axis, and if the pixel values, which are all unmasked, on a slice along this axis are [1, 2, 5, 10, 17, 26], the corresponding output pixel values will be [4.0, 14.0]. Masked values are taken into consideration when forming this average, so if one of the values is masked, it is not used in the average. If at least one of the values in the input pair is not masked, the corresponding output pixel will not be masked.
The hanning smoothed image is written to disk with name {\stfaf outfile}, if specified. If not, no image is written but the image is still accessible via the returned image analysis tool (see below).
This method always returns an image analysis tool which is attached to the hanning smoothed image. This tool should always be captured and closed after any desired manipulations have been done. Closing the tool frees up system resources (eg memory), eg,
hanning\_image = ia.hanning(...) egin{verbatim} # do things (or not) with hanning_image ... # close the returned tool promptly upon finishing with it. nd{verbatim} hanning\_image.done()
See also the other convolution functions convolve2d, sepconvolve and convolve.
Input Parameters: outfile Output image file name. Default is unset. region Region of interest. See help par.region for details. Default is whole image. mask Mask to use. See help par.mask. Default is none. axis Zero based axis to convolve. ia.coordsys().names() gives the order of the axes in the image. Less than 0 means use the spectral axis if there is one, if not an exception is thrown. -10 drop Drop every other pixel on output? true overwrite Overwrite (unprompted) pre-existing output file? false async Run asynchronously? false stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false dmethod If drop=True, method to use in plane decimation. 'c(opy)': direct copy of every second plane, 'm(ean)': average planes 2*i and 2*i+1 in the smoothed, non-decimated image to form plane i in the output image. copy
Example:
ia.open('mynonsmoothed.im') # smooth the spectral axis, say it's axis 2 and only write every other pixel hanning = ia.hanning(outfile='myhanningsmoothed.im', axis=2, drop=True, overwrite=True) # done with input ia.done() # do something with the output image, get statistics say stats = hanning.statistics() # close the result image hanning.done()
--------------------------------------------------------------------------------
""" return _image.image_hanning(self, *args, **kwargs)
def haslock(self): """ haslock(self) -> std::vector<(bool)>
Summary Does this image have any locks set?
Description
This function can be used to find out whether the image has a read or a write lock set. It is not of general user interest. It returns a vector of Booleans of length 2. Position 1 says whether a read lock is set, position 2 says whether a write lock is set.
In general locking is handled automatically, with a built in lock release cycle. However, this function can be useful in scripts when a file is being shared between more than one process. See also functions unlock and lock.
Example:
''' # print ' ---- haslock Ex 1 ----' ia.maketestimage('xx',overwrite=true) ia.lock(writelock=T) print ia.haslock() #[True, True] ia.unlock() print ia.haslock() #[False, False] ia.lock(F) print ia.haslock() #[True, False] ia.close() # '''
This example acquires a read/write lock on the file and then unlocks it and acquires just a read lock.
--------------------------------------------------------------------------------
""" return _image.image_haslock(self)
def histograms(self, *args, **kwargs): """ histograms(self, axes = initialize_vector(1, (int)-1), region = initialize_variant(""), mask = initialize_variant(""), nbins = 25, includepix = initialize_vector(1, (double)-1), gauss = False, cumu = False, log = False, list = True, force = False, disk = False, async = False, stretch = False) -> record
Summary Compute histograms from the image
Description
This function computes histograms of the pixel values in the \imagefile. You can retrieve them (into a record) for further analysis or display.
The chunk of the image over which you compute the histograms is specified by a vector of axis numbers (argument {\stfaf axes}). For example, consider a 3-dimensional image for which you specify {\stfaf axes=[0,2]}. The histograms would be computed for each XZ (axes 0 and 2) plane in the image. You could then examine those histograms as a function of the Y (axis 1) axis. Or perhaps you set {\stfaf axes=[2]}, whereupon you could examine the histogram for each Z (axis 2) profile as a function of X and Y location in the image.
You have control over the number of bins for each histogram ({\stfaf nbins}). The bin width is worked out automatically for each histogram and may vary from histogram to histogram (the range of pixel values is worked out for each chunk being histogrammed).
You have control over which pixels are included in the histograms via the {\stfaf includepix} argument. This vector specifies a range of pixel values to be included in the histograms. If you only give one value for this, say {\stfaf includepix=[b]}, then this is interpreted as {\stfaf includepix=[-abs(b),abs(b)]}. If you specify an inclusion range, then the range of pixel intensities over which the histograms are binned is given by this range too. This is a way to make the bin width the same for each histogram.
You have control over the form of the histogram; the ordinate can be linear or logarithmic ({\stfaf log=T}), and cumulative or non-cumulative ({\stfaf cumu=F}).
You can overlay a Gaussian on each histogram ({\stfaf gauss=T}). It has the same mean and standard deviation about the mean of the pixels that were binned and the same integral as the histogram.
You can list some additional statistical information about the data in each image chunk that is being histogrammed ({\stfaf list=T}).
You can retrieve the histograms into a record (the counts and the abcissa values for each histogram). The names of the fields in the record are {\cf `values'} and {\cf `counts'}. The shape of the first dimension of those arrays contained in those fields is {\stfaf nbins}. The number and shape of the remaining dimensions are those in the image for which you did not compute the histograms. For example, in the second example above, we set {\stfaf axes=[2]} and asked for histograms as a function of the remaining axes, in this case, the X and Y (axes 0 and 1) axes. The shape of each histogram array is then [nbins,nx,ny]. The form of the retrieved histograms is that specified by the {\stfaf cumu} and {\stfaf log} arguments.
This function generates ``storage'' images, into which the histograms and statistics are written. They are only regenerated when necessary. For example, if you run the function twice successively with identical arguments, the histograms will be directly retrieved from the storage image. However, you can force regeneration of the storage image if you set {\stfaf force=T}. The storage medium is either in memory or on disk, depending upon its size. You can force it to disk if you set {\stfaf disk=T}, otherwise it decides for itself.
Input Parameters: axes List of axes to compute histograms over. Default is all axes. -1 region Region of interest. See help par.region for details. Default is whole image. mask Mask to use. See help par.mask. Default is none. nbins Number of bins in histograms, \> 0 25 includepix Range of pixel values to include. Default is to include all pixels. -1 gauss If T overlay a Gaussian on each histogram false cumu If T plot cumulative histograms, otherwise plot non-cumulatively false log If T plot the ordinate logarithmically, otherwise plot linearly false list If T then list some statistics as well true force If T then force the stored statistical accumulations to be regenerated false disk If T then force the storage image to disk false async Run asynchronously? false stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false
Example:
''' # print ' ---- histograms Ex 1 ----' ia.maketestimage() ia.histograms() ia.close() # '''
In this example we obtain the histogram of the entire image.
Example:
''' # print ' ---- histograms Ex 2 ----' ia.fromshape(shape=[128,128,64]) #attach your 3-dim image instead r= ia.histograms(axes=[0,2],nbins=30,includepix=1e-3,cumu=T, gauss=T) print r.keys() #['return', 'histout'] ia.close() # '''
In this example, let us assume the image has 3 dimensions. We generate cumulative histograms of XZ (axes 0 and 2) planes for pixels with values in the range $-0.001$ to $0.001$ and plot them with Gaussian overlays as a function of Y-axis location. The histograms are retrieved into a record {\gvf r['histout']} for further use.
--------------------------------------------------------------------------------
""" return _image.image_histograms(self, *args, **kwargs)
def history(self, list = True): """ history(self, list = True) -> std::vector<(std::string)>
Summary Recover and/or list the history file
Description
This function allows you to access the history file.
If {\stfaf browse=F} and {\stfaf list=F}, the history is returned by the function as a vector of strings. If {\stfaf list=T}, the history is sent to the logger.
\casa\ tools that modify the MeasurementSet or an image file will save history information. Also, you can directly annotate the history file with the function sethistory. History from its\ file conversions is also stored and listable here.
Input Parameters: list List history to the logger? true
Example:
''' # print ' ---- history Ex 1 ----' ia.maketestimage() ia.history() # List history to logger h = ia.history(list=F) # Recover history in variable h ia.history(list=T, browse=F) # List history to logger # '''
--------------------------------------------------------------------------------
""" return _image.image_history(self, list)
def insert(self, *args, **kwargs): """ insert(self, infile = string(""), region = initialize_variant(""), locate = initialize_vector(1, (double)-1), verbose = False) -> bool
Summary Insert specified image into this image
Description
This function inserts the specified image (or part of it) into the image referenced by this tool. The specified image may be given via argument {\stfaf infile} as a disk file name (it may be in native \casa, its, or Miriad format; Look \htmlref{here}{IMAGES:FOREIGNIMAGES} for more information on foreign images).
If the {\stfaf locate} vector is not given, then the images are aligned (to an integer pixel shift) by their reference pixels.
If {\stfaf locate} vector is given, then those values that are given, give the absolute pixel in the output (this) image of the bottom left corner of the input (sub)image. For those values that are not given, the input image is symmetrically placed in the output image.
The image referenced by this tool is modified in place; no new image is created. The method returns True if successful.
Input Parameters: infile Name of image to be inserted. region The region of interest of the input image. See help par.region for details. Default is whole image. locate Location of input image in output image. Default is centrally located. -1 verbose Emit informational messages to logger? false
Example:
''' # print ' ---- insert Ex 1 ----' ia.maketestimage('myfile.insert',overwrite=true) ia.close() ia.fromshape(shape=[200,200]) ia.insert(infile='myfile.insert') # Align by reference pixel ia.newimagefromfile('myfile.insert') ia.insert(infile=im2.name(), locate=[]) # Align centrally # This time align axis 0 as given and axis 1 centrally ia.insert(infile='myfile.insert', locate=[20]) ia.close() # close default tool and '''
--------------------------------------------------------------------------------
""" return _image.image_insert(self, *args, **kwargs)
def isopen(self): """ isopen(self) -> bool
Summary Is this Image tool open?
Description
This function can be used to find out whether the Image oolis associated with an image or not.
Example:
''' # print ' ---- isopen Ex 1 ----' ia.maketestimage('zz',overwrite=true) print ia.isopen() #True ia.close() print ia.isopen() #False ia.open('zz') print ia.isopen() #True ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_isopen(self)
def ispersistent(self): """ ispersistent(self) -> bool
Summary Is the image persistent?
Description
This function can be used to find out whether the image is persistent on disk or not. There is a subtle difference from the image being virtual. For example, a virtual image which references another which is on disk is termed persistent.
Example:
''' # print ' ---- ispersistent Ex 1 ----' ia.fromshape(outfile='tmp', shape=[10,20], overwrite=true) print ia.ispersistent() #True ia.close() ia.fromimage(infile='tmp') print ia.ispersistent() #True im3 = ia.subimage() print im3.ispersistent() # Persistent virtual image ! #True im4 = ia.imagecalc(pixels='tmp+tmp') print im4.ispersistent() #False im3.done() im4.done() ia.close(remove=true) # '''
--------------------------------------------------------------------------------
""" return _image.image_ispersistent(self)
def lock(self, writelock = False, nattempts = 0): """ lock(self, writelock = False, nattempts = 0) -> bool
Summary Acquire a lock on the image
Description
This function can be used to acquire a Read or a Read/Write lock on the \imagefile. It is not of general user interest.
In general locking is handled automatically, with a built in lock release cycle. However, this function can be useful in scripts when a file is being shared between more than one process. See also functions unlock and haslock.
Input Parameters: writelock Acquire a read/write (T) or a readonly (F) lock false nattempts Number of attempts, \> 0. Default is unlimiited. 0
Example:
''' # print ' ---- lock Ex 1 ----' ia.maketestimage('xx', overwrite=true) ia.lock(writelock=T) ia.unlock() ia.lock(writelock=F) ia.close(remove=true) # '''
This acquires a read/write lock on the file. Then we unlock it and acquire a readonly lock.
--------------------------------------------------------------------------------
""" return _image.image_lock(self, writelock, nattempts)
def makecomplex(self, *args, **kwargs): """ makecomplex(self, outfile, imag, region = initialize_variant(""), overwrite = False) -> bool
Summary Make a complex image
Description
This function combines the current image with another image to make a complex image. The current image (i.e. that associated with this Image ool\ is assumed to be the Real image). You supply the Imaginary image; it must be disk-based at this time.
The output image cannot be associated with an Image ool\ (does not handle Complex images yet) and so the best you can do is write it to disk. The Viewer can view it.
Input Parameters: outfile Output Complex (disk) image file name imag Imaginary image file name region The region of interest. See help par.region for details. Default is whole image. overwrite Overwrite (unprompted) pre-existing output file? false
Example:
''' # print ' ---- makecomplex Ex 1 ----' ia.maketestimage('imag.im',overwrite=true) #imaginary image ia.close() ia.maketestimage('real.im',overwrite=true) #assoc. real image ia.makecomplex('complex.im', 'imag.im', overwrite=true) ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_makecomplex(self, *args, **kwargs)
def maskhandler(self, *args, **kwargs): """ maskhandler(self, op = string("default"), name = std::vector< string >(1, "")) -> std::vector<(std::string)>
Summary Handle pixel masks
Description
This function is used to manage or handle \pixelmasks\ . A \casa\ image may contain zero, one or more \pixelmasks. Any of these masks can be designated the default \pixelmask. The default mask is acted upon by \casa\ applications. For example, if you ask for statistics from an image, pixels which are masked as bad (F) will be excluded from the calculations.
This function has an argument ({\stfaf op}) that specifies the behaviour. In all cases, you can shorten the operation string to three characters. It is not the job of this function to modify the values of masks.
egin{itemize}
\item{default - } this retrieves the name of the default \pixelmaskas the return value of the function call.
\item{get - } this retrieves the name(s) of the existing \pixelmasksas the return value of the function call (string or vector of strings).
\item{set - } this lets you change the default \pixelmask\ to that given by the {\stfaf name} argument. If {\stfaf name} is empty, then the default mask is unset (i.e. an all good mask is effectively applied).
\item{delete - } this lets you delete the \pixelmasks\ specified by the {\stfaf name} argument. To delete more than one mask, {\stfaf name} can be a vector of strings. Any supplied \pixelmask\ name that does not exist is silently ignored.
\item{rename - } this lets you rename the mask specified by {\stfaf name[0]} to {\stfaf name[1]}. Thus the {\stfaf name} argument must be a vector of length 2.
\item{copy - } this lets you copy a mask to another in the same image, or copy a mask from another image into this image. Thus the {\stfaf name} argument must be a vector of length 2.
For the first case, the first element of {\stfaf name} must be the name of the mask to copy, and the second element must be the name of the \pixelmask\ to which it will be copied.
For the second case, the first element of {\stfaf name} must be the name of the input image and \pixelmask\ with a colon delimiter (e.g. {\cf hcn:mask2}). The second element must be the name of the \pixelmask\ to which the input \pixelmask\ will be copied.
nd{itemize}
Use the summary function to see the available \pixelmasks. You can do this either via the logger display, or via the returned record, which contains the mask names. In the logger display, any \pixelmask\ which is not the default mask is listed in square brackets. If a default mask is set, it is listed first, and is not enclosed in square brackets.
Input Parameters: op The operation. One of 'set', 'delete', 'rename', 'get', 'copy' or 'default' default name Name of mask or masks.
Example:
''' # print ' ---- maskhandler Ex 1 ----' ia.maketestimage('g1.app', overwrite=true) ia.calcmask('T', name='mask1') ia.close() ia.maketestimage('myimage', overwrite=true) ia.calcmask('T') # Create some masks ia.calcmask('T', name='mask1') ia.calcmask('T', name='mask2') names = ia.maskhandler('get') # Get the mask names print names #['mask0', 'mask1', 'mask2'] name = ia.maskhandler('default') # Get the default mask name print name #mask2 ia.maskhandler('set', ['mask1']) # Make 'mask1' the default mask ia.maskhandler('set', ['']) # Unset the default mask ia.maskhandler('delete', ['mask1']) # Delete 'mask1' ia.calcmask('T', name='mask1') # Make another 'mask1' ia.maskhandler('delete', ['mask0', 'mask1'])# Delete 'mask0' and 'mask1' ia.calcmask('T', name='mask1') ia.maskhandler('rename', ['mask1', 'mask0'])# Rename 'mask1' to 'mask0'
# Copy 'mask1' from image 'g1.app' to 'mask10' in image 'myimage' ia.maskhandler('copy', ['g1.app:mask1', 'mask10']) ia.removefile('g1.app') # Cleanup ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_maskhandler(self, *args, **kwargs)
def miscinfo(self): """ miscinfo(self) -> record
Summary Get the miscellaneous information record from an image
Description
A \casa\ \imagefile\ can accumulate miscellaneous information during its lifetime. This information is stored in a record called the {\stff miscinfo} record. For example, the its\ filler puts header keywords it doesn't otherwise use into the {\stff miscinfo} record. This {\stff miscinfo} record is not guaranteed to have any entries, so it's up to you to check for any fields that you require.
You can also put things into this record (see setmiscinfo) yourself, to keep information that the system might not otherwise store for you.
When the image is written out to its, the items in the {\stff miscinfo} record are written to the its\ file as keywords with the corresponding record field name.
Example:
''' # print ' ---- miscinfo Ex 1 ----' ia.maketestimage() print ia.miscinfo() # print the record ia.setmiscinfo('testing') print ia.miscinfo() header = ia.miscinfo() # capture the record for further use print header ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_miscinfo(self)
def modify(self, *args, **kwargs): """ modify(self, model, region = initialize_variant(""), mask = initialize_variant(""), subtract = True, list = True, async = False, stretch = False) -> bool
Summary Modify image with a model
Description
This function applies a model of the sky to the image. You can add or subtract the model which is contained in a Componentlist tool.
The pixel values are only changed where the total mask (combination of the default \pixelmask\ [if any] and the OTF mask) is good (True). If the computation fails for a particular pixel (e.g. coordinate undefined) that pixel will be masked bad.
Input Parameters: model Record representation of a ComponentList model region The 2-D region of interest. See help par.region for details. Default is whole image. mask Mask to use. See help par.mask. Default is none. subtract Subtract or add the model true list List informative messages to the logger true async Run asynchronously? false stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false
Example:
''' # print ' ---- modify Ex 1 ----' ia.maketestimage() clrec = ia.fitcomponents() ia.modify(clrec['results']) ia.close() # '''
In this example we subtract the model returned by the fitcomponents function.
--------------------------------------------------------------------------------
""" return _image.image_modify(self, *args, **kwargs)
def maxfit(self, *args, **kwargs): """ maxfit(self, region = initialize_variant(""), point = True, width = 5, negfind = False, list = True) -> record
Summary Find maximum and do parabolic fit in the sky
Description
This function finds the pixel with the maximum value in the region, and then uses function findsources to generate a Componentlist with one component. The component will be of type Point ({\stfaf point=T}) or Gaussian ({\stfaf point=F}).
If {\stfaf negfind=F} the maximum pixel value is found in the region and fit. If {\stfaf negfind=T} the absolute maximum pixel value is found in the region and fit.
See function findsources for a description of arguments {\stfaf point} and {\stfaf width}.
See also the function fitcomponents.
Input Parameters: region The 2-D region of interest to fit. See help par.region for details. Default is whole image. point Find only point sources? true width Half-width of fit grid when point=F 5 negfind Find negative sources as well as positive? false list List the fitted parameters to the logger? true
Example:
''' # print ' ---- maxfit Ex 1 ----' ia.maketestimage() clrec = ia.maxfit() print clrec # There is only one component ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_maxfit(self, *args, **kwargs)
def moments(self, *args, **kwargs): """ moments(self, moments = initialize_vector(1, (int)0), axis = -10, region = initialize_variant(""), mask = initialize_variant(""), method = std::vector< string >(1, ""), smoothaxes = initialize_vector(1, (int)-1), smoothtypes = initialize_variant(""), smoothwidths = initialize_vector(1, (double)0.0), includepix = initialize_vector(1, (double)-1), excludepix = initialize_vector(1, (double)-1), peaksnr = 3.0, stddev = 0.0, doppler = string("RADIO"), outfile = string(""), smoothout = string(""), overwrite = False, drop = True, stretch = False, async = False) -> image
Summary Compute moments from an image
Description
oindent{f Summary}
The primary goal of this function is to enable you to analyze a multi-dimensional image by generating moments of a specified axis. This is a time-honoured spectral-line analysis technique used for extracting information about spectral lines.
You can generate one or more output moment images. The return value of this function is an on-the-fly Image ool\ holding the {f first} of the output moment images.
The word `moment' is used loosely here. It refers to collapsing an axis (the moment axis) to one pixel and setting the value of that pixel (for all of the other non-collapsed axes) to something computed from the data values along the moment axis. For example, take an RA-DEC-Velocity cube, collapse the velocity axis by computing the mean intensity at each RA-DEC pixel. This function offers many different moments and a variety of automatic methods to compute them.
We try to make a distinction between a `moment' and a `method'. This boundary is a little blurred, but it claims to refer to the distinction between what you are computing, and how the pixels that were included in that computation were selected. For example, a `moment' would be the average value of some pixel values in a spectrum. A `method' for selecting those pixels would be a simple pixel value range specifying which pixels should be included.
There are many available moments, and you specify each one with an integer code as it would get rather cumbersome to refer to them via strings. In the list below, the value of the $i$th pixel of the spectrum is $I_i$, the coordinate of this pixel is $v_i$ (of course it may not be velocity), and there are $n$ pixels in the spectrum. The available moments are:
egin{itemize} \item{$-1$} -- the mean value of the spectrum egin{displaymath} { {1\over n} {\sum {I_i}}} nd{displaymath} \medskip
\item{0} -- the integrated value of the spectrum egin{displaymath} M_0 = \Delta v \sum I_i nd{displaymath}
where $\Delta v$ is the width (in world coordinate units) of a pixel along the moment axis \medskip
\item{1} -- the intensity weighted coordinate (this is traditionally used to get 'velocity fields')
egin{displaymath} M_1 = { {\sum {I_i v_i}} \over {M_0}} nd{displaymath} \medskip
\item{2} -- the intensity weighted dispersion of the coordinate (this is traditionally used to get 'velocity dispersion fields')
egin{displaymath} \sqrt{ { {\sum {I_i \left(v_i - M_1right)^2}} \over {M_0}}} nd{displaymath} \medskip
\item{3} -- the median of $I$ \medskip
\item{4} -- the median coordinate. Here we treat the spectrum as a probability distribution, generate the cumulative distribution, and then find the coordinate corresponding to the 50\% value. This moment is not very robust, but it is useful for quickly generating a velocity field in a way that is not sensitive to noise. However, it will only give sensible results under certain conditions. The generation of the cumulative distribution and the finding of the 50\% level really only makes sense if the cumulative distribution is monotonic. This essentially means only selecting pixels which are positive or negative. For this reason, this moment type is only supported with the basic method (see below -- i.e. no smoothing, no windowing, no fitting) with a pixel selection range that is either all positive, or all negative \medskip
\item{5} -- the standard deviation about the mean of the spectrum egin{displaymath} \sqrt{ {1\over {\left(n-1right)}} \sum{\left(I_i - ar{I}right)^2 }} nd{displaymath} \medskip
\item{6} -- the root mean square of the spectrum egin{displaymath} \sqrt{ {1 \over n} \sum{I_i^2}} nd{displaymath} \medskip
\item{7} -- the absolute mean deviation of the spectrum egin{displaymath} {1 \over n} \sum {|(I_i - ar{I})|} nd{displaymath} \medskip
\item{8} -- the maximum value of the spectrum \medskip \item{9} -- the coordinate of the maximum value of the spectrum \medskip \item{10} -- the minimum value of the spectrum \medskip \item{11} -- the coordinate of the minimum value of the spectrum \medskip nd{itemize}
igskip
oindent {Smoothing}
The purpose of the smoothing functionality is purely to provide a mask. Thus, you can smooth the input image, apply a pixel include or exclude range, and generate a smoothed mask which is then applied before the moments are generated. The smoothed data are not used to compute the actual moments; that is always done from the original data.
igskip
oindent{f Basic Method}
The basic method is to just compute moments directly from the pixel values. This can be modified by applying pixel value inclusion or exclusion ranges (arguments {\stfaf includepix} and {\stfaf excludepix}).
You can then also convolve the image (arguments {\stfaf smoothaxes}, {\stfaf smoothtypes}, and {\stfaf smoothwidths}) and find a mask based on the inclusion or exclusion ranges applied to the convolved image. This mask is then applied to the unsmoothed data for moment computation.
igskip
oindent{f Window Method}
The window method (invoked with argument {\stfaf method='window'}) does no pixel-value-based selection. Instead a window is found (hopefully surrounding the spectral line feature) and only the pixels in that window are used for computation. This window can be found from the convolved or unconvolved image (arguments {\stfaf smoothaxes}, {\stfaf smoothtypes}, and {\stfaf smoothwidths}).
The moments are always computed from the unconvolved data. The window can be found (for each spectrum) automatically. The automatic methods are via Bosma's converging mean algorithm ({\stfaf method='window'}) or by fitting Gaussians and taking $\pm 3\sigma$ as the window ({\stfaf method='window,fit'}).
In Bosma's algorithm, an initial guess for a range of pixels surrounding a spectral feature is refined by widening until the mean of the pixels outside of the range converges (to the noise).
igskip
oindent{f Fit Method}
The fit method ({\stfaf method='fit'}) fits Gaussians to spectral features automatically. The moments are then computed from the Gaussian fits (not the data themselves).
igskip
oindent{f Other Arguments}
egin{itemize}
\item {\stfaf outfile} - If you are creating just one moment image, and you specify {\stfaf outfile}, then the image is created on disk with this name. If you leave {\stfaf outfile} empty then a temporary image is created. In both cases, you can access this image with the returned Image ool. If you are making more than one moment image, then theses images are always created on disk. If you specify {\stfaf outfile} then this is the root for the output file names. If you don't specify it, then the input image name is used as the root.
\item {\stfaf smoothing} - If you smooth the image to generate a mask, you specify the kernel widths via the {\stfaf smoothwidths} argument in the same way as in the sepconvolve function. See it for details.
\item {\stfaf stddev} - Some of the automatic methods also require an estimate of the noise level in the image. This is used to assess whether a spectrum is purely noise or not, and whether there is any signal worth digging out. If you don't give it via the {\stfaf stddev} argument, it will be worked out automatically from a Gaussian fit to the bins above 25\% from a histogram of the entire image.
\item {\stfaf includepix, excludepix} - The vectors given by arguments {\stfaf includepix} and {\stfaf excludepix} specify a range of pixel values for which pixels are either included or excluded. They are mutually exclusive; you can specify one or the other, but not both. If you only give one value for either of these, say {\stfaf includepix=b}, then this is interpreted as {\stfaf includepix=[-abs(b),abs(b)]}.
The convolving point-spread function is normalized to have a volume of unity. This means that point sources are depressed in value, but extended sources that are large with respect to the PSF remain essentially on the same intensity scale; these are the structures you are trying to find with the convolution so this is what you want. If you convolve the image, then arguments like {\stfaf includepix} select based upon the convolved image pixel values. If you are having trouble getting these right, you can output the convolved image ({\stfaf smoothout}) and assess the validity of your pixel ranges. Note also that if you are Hanning convolving (usually used on a velocity axis), then the width for this kernel must be 3 pixels (triangular smoothing kernels of other widths have no valid theoretical basis).
\item {\stfaf doppler} - If you compute the moments along a spectral axis, it is conventional to compute the world coordinate (needed for moments 0, 1 and 2) along that axis in 'km/s'. The argument {\stfaf doppler} lets you specify what doppler convention the velocity will be calculated in. You can choose from {\stfaf doppler=radio, optical, true}. See function summary for the definitions of these codes. For other moment-axis types, the world coordinate is computed in the native units.
\item {\stfaf mask} - The total input mask is the combination of the default \pixelmask\ (if any) and the OTF mask. Once this mask has been established, then the moment method may make additional pixel selections.
\item {\stfaf drop} - If this is true (the default) then the moment axis is dropped from the output image. Otherwise, the output images have a moment axis of unit length and coordinate information that is the same as for the input image. This coordinate information may be totally meaningless for the moment images.
nd{itemize}
Finally, if you ask for a moment which requires the coordinate to be computed for each profile pixel (these are the intensity weighted mean coordinate [moment 1] and the intensity weighted dispersion of the coordinate [moment 2]), and the profile axis is not separable then there will be a performance loss. Examples of non-separable axes are RA and Dec. If the axis is separable (e.g. a spectral axis) there is no penalty. In the latter case, the vector of coordinates for one profile is the same as the vector for another profile, and it can be precomputed (once).
Note that this function has no ``virtual'' output file capability. All output files are written to disk. The output mask for these images is good (T) unless the moment method fails to generate a value (e.g. the total input pixel mask was all bad for the profile) in which case it will be bad (F).
If an image has multiple (per-channel beams) and the moment axis is equal to the spectral axis, each channel will be convolved with a beam that is equal to the beam having the largest area in the beamset prior to moment determination.
Input Parameters: moments List of moments that you would like to compute. Default is integrated spectrum. 0 axis The moment axis. Default is the spectral axis if there is one. -10 region Region specification. See help par.region for details. Default is entire image. mask Mask to use. See help par.mask. Default is none. method List of windowing and/or fitting functions you would like to invoke. Vector of strings from 'window', 'fit' and 'interactive'. The default is to not invoke the window or fit functions, and to not invoke any interactive functions. smoothaxes List of axes to smooth. Default is no smoothing. -1 smoothtypes List of smoothing kernel types, one for each axis to smooth. Vector of strings from 'gauss', 'boxcar', 'hanning'. Default is no smoothing. smoothwidths List of widths (full width for boxcar, full width at half maximum for gaussian, 3 for Hanning) in pixels for the smoothing kernels. Vector of numeric. Default is no smoothing. 0.0 includepix Range of pixel values to include. Vector of 1 or 2 doubles. Default is include all pixel. -1 excludepix Range of pixel values to exclude. Default is exclude no pixels. -1 peaksnr The SNR ratio below which the spectrum will be rejected as noise (used by the window and fit functions only) 3.0 stddev Standard deviation of the noise signal in the image (used by the window and fit functions only) 0.0 doppler Velocity doppler definition for velocity computations along spectral axes RADIO outfile Output image file name (or root for multiple moments). Default is input + an auto-determined suffix. smoothout Output file name for convolved image. Default is don't save the convolved image. overwrite Overwrite (unprompted) pre-existing output file? false drop Drop moments axis from output images? true stretch Stretch the mask if necessary and possible? false async Run asynchronously? false
Example:
''' # print ' ---- moments Ex 1 ----' ia.fromshape(shape=[32,32,32,32]) # replace with your own cube im2 = ia.moments(moments=[-1,1,2], axis=2, smoothaxes=[0,1,2], smoothtypes=['gauss','gauss','hann'], smoothwidths=[5.0,5.0,3], excludepix=[1e-3], smoothout='smooth', overwrite=true) im2.done() ia.close() # '''
In this example, standard moments (average intensity, weighted velocity and weighted velocity dispersion) are computed via the convolve (spatially convolved by gaussians and spectrally by a Hanning kernel) and clip method (we exclude any pixels with absolute value less than $0.001$). The output file names are automatically created for us and the convolved image is saved. The returned image tool holds the first moment image.
Example:
''' # print ' ---- moments Ex 2 ----' ia.fromshape(shape=[32,32,32,32]) im2 = ia.moments(moments=[3], method=['window']) im2.done() ia.close() # '''
In this example, the median of each spectrum is computed, after pixel selection by the automatic window method. The output image is temporary and accessed via the returned Image tool.
--------------------------------------------------------------------------------
""" return _image.image_moments(self, *args, **kwargs)
def name(self, strippath = False): """ name(self, strippath = False) -> string
Summary Name of the image file this tool is attached to
Description
This function returns the name of the \imagefile\ By default, this function returns the full absolute path of the \imagefile. You can strip this path off if you wish with the {\stfaf strippath} argument and just recover the \imagefile\ name itself.
Input Parameters: strippath Strip off the path before the actual file name? false
Example:
''' # print ' ---- name Ex 1 ----' ia.maketestimage('g1.app', overwrite=true) print ia.name(strippath=F) #/casa/code/xmlcasa/implement/images/scripts/g1.app print ia.name(strippath=T) #g1.app ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_name(self, strippath)
def open(self, *args, **kwargs): """ open(self, infile) -> bool
Summary Open a new image file with this image tool
Description
Use this function when you are finished analyzing the current \imagefile\ and want to attach to another one. This function detaches the \imagetool\ from the current \imagefile, and reattaches it (opens) to the new \imagefile.
The input image file may be in native \casa, its, or Miriad format. Look \htmlref{here}{IMAGES:FOREIGNIMAGES} for more information on foreign images. In the case of \casa images, both Float and Complex valued images are supported.
Input Parameters: infile image file name
Example:
''' # print ' ---- open Ex 1 ----' ia.maketestimage('anotherimage',overwrite=true) #first make 2nd image ia.close() ia.maketestimage('myimage',overwrite=true) #open image myimage ia.open('anotherimage') # attach tool to 'anotherimage' ia.close() # '''
The {\stff open} function first closes the old \imagefile.
--------------------------------------------------------------------------------
"""
def pad(self, *args, **kwargs): """ pad(self, outfile = string(""), npixels = 1, value = 0, padmask = False, overwrite = False, region = initialize_variant(""), box = string(""), chans = string(""), stokes = string(""), mask = string(""), stretch = False, wantreturn = True) -> image
Summary Pad the perimeter of the direction plane with a number of pixels of specified value and mask.
Description
This method pads the directional plane of an image with a specified number of pixels on each side. The numerical and mask values of the padding pixels may also be specified. If a region is selected, a subimage of that region is created and then padded with the specified pixel parameters. Thus, padding an image of shape (ra, dec, freq) = (512, 512, 10) specifying npixels = 3 results in an image of size (518, 518, 10), with the blc of the directional plane of the original pixel set corresponding to the directional pixel of (3, 3) in the output. If wantreturn is True, an image analysis tool attached to the output image is returned. If False, none is returned.
Input Parameters: outfile Output image name. If not specified, no persistent image is created. npixels Number of pixels with which to pad each side of the direction plane. 1 value Value given to the padding pixels. 0 padmask Value of the mask for the padding pixels. True$=\>$good (unmasked), False$=\>$bad (masked). false overwrite Overwrite the output if it exists? Default False false region The region to correct. Default is entire image. If this is specified neither box, chans, nor stokes may be specified. box Rectangular region in the directional plane to select. Default is to use the entire directional plane. chans Spectral selection. See 'help par.chans' for examples. Default is the entire spectral range. stokes Polarization selection. Default is all. mask Mask to use. See help par.mask. Default is none. stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false wantreturn Return an image analysis tool attached to the created subimage? true
Example:
ia.fromshape('',[50, 50, 10]) # pad it with 5 pixels of value 2.5 all unmasked padded = ia.pad(npixels=5, value=2.5, padmask=True) ia.done() # returns [60, 60, 10] paddedshape = padded.shape() padded.done()
--------------------------------------------------------------------------------
""" return _image.image_pad(self, *args, **kwargs)
def crop(self, *args, **kwargs): """ crop(self, outfile = string(""), axes = std::vector< int >(), overwrite = False, region = initialize_variant(""), box = string(""), chans = string(""), stokes = string(""), mask = string(""), stretch = False, wantreturn = True) -> image
Summary Crop masked pixels from the perimeter of an image.
Description
This method crops masked slices from the perimeter of an image. The axes parameter specifies which axes to consider. Axes not specified will not be cropped. An empty array implies that all axes should be considered. If wantreturn is True, an image analysis tool attached to the output image is returned. If False, none is returned.
Input Parameters: outfile Output image name. If not specified, no persistent image is created. axes Axes to crop. Empty array means consider all axes. overwrite Overwrite the output if it exists? Default False false region The region to correct. Default is entire image. If this is specified neither box, chans, nor stokes may be specified. box Rectangular region in the directional plane to select. Default is to use the entire directional plane. chans Spectral selection. See 'help par.chans' for examples. Default is the entire spectral range. stokes Polarization selection. Default is all. mask Mask to use. See help par.mask. Default is none. stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false wantreturn Return an image analysis tool attached to the created subimage? true
Example:
# myimage is of shape 20, 20, 20 with only the inner 16 x 14 x 12 pixels unmasked ia.open('myimage') # crop masked slices on all axes cropped = ia.crop() # returns [16, 14, 12] cropped.shape() cropped.done() # crop only the masked slices at the edges of the image along axis 1 cropped2 = ia.crop(outfile='', axes=[1]) ia.done() # returns [20, 14, 20] cropped2.shape() cropped2.done()
--------------------------------------------------------------------------------
""" return _image.image_crop(self, *args, **kwargs)
def pixelvalue(self, *args, **kwargs): """ pixelvalue(self, pixel = initialize_vector(1, (int)-1)) -> record
Summary Get value of image and mask at specified pixel coordinate
Description
This function gets the value of the image and the mask at the specified pixel coordinate. The values are returned in a record with fields 'value', 'mask' and 'pixel'. The value is returned as a quantity, the mask as a Bool (T is good). The 'pixel' field holds the actual pixel coordinate used.
If the specified pixel coordinate is off the image, '\{\}' is returned.
Excessive elements in {\stfaf pixel} are silently discarded. Missing elements are given the (nearest integer) value of the reference pixel. This is reflected in the output record 'pixel' field.
Input Parameters: pixel Pixel coordinate -1
Example:
''' # print ' ---- pixelvalue Ex 1 ----' ia.maketestimage(); ia.pixelvalue() #{'mask': True, # 'pixel': array([55, 37]), # 'value': {'unit': 'Jy/beam', 'value': 2.5064315795898438}} print ia.pixelvalue([-1,-1]) # {} print ia.pixelvalue([9]) #{'mask': True, # 'pixel': array([ 9, 37]), # 'value': {'unit': 'Jy/beam', 'value': 0.14012207090854645}} print ia.pixelvalue([9,9,9]) #{'mask': True, # 'pixel': array([9, 9]), # 'value': {'unit': 'Jy/beam', 'value': -0.45252728462219238}} ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_pixelvalue(self, *args, **kwargs)
def putchunk(self, *args, **kwargs): """ putchunk(self, pixels, blc = initialize_vector(1, (int)-1), inc = initialize_vector(1, (int)1), list = False, locking = True, replicate = False) -> bool
Summary Put pixels from an array into a regular region of the image
Description
This function puts an array into the \imagefile. If there is a default \pixelmask\ it is ignored in this process. It is the complement of the getchunk function. You can specify the {\stfaf blc} and {\stfaf inc} if desired. If they are unspecified, they default to the beginning of the image and an increment of one.
Any illegal {\stfaf blc} values are set to zero. Any illegal {\stfaf inc} values are set to unity.
An error will result if you attempt to put an array beyond the extent of the image (i.e., it is not truncated or decimated).
If there are fewer axes in the array than in the image, the array is assumed to have trailing axes of length unity. Thus, if you have a 2D array and want to put it in as the YZ plane rather than the XY plane, you must ensure that the shape of the array is [1,nx,ny].
However, the argument {\stfaf replicate} can be used to replicate the array throughout the image (from the blc to the trc). For example, if you provide a 2D array to a 3D image, you can replicate it through the third axis by setting {\stfaf replicate=T}. The replication is done from the specified {\stfaf blc} to the end of the image. Use function putregion if you want to terminate the replication at a {\stfaf trc} value.
The argument {\stfaf locking} controls two things. If True, then after the function is called, the image is unlocked (so some other process can acquire a lock) and it is indicated that the image has changed. The reason for having this argument is that the unlocking and updating processes are quite expensive. If you are repeatedly calling {\stff putchunk} in a for loop, you would be advised to use this switch.
A related function is putregion which puts the pixels and masks into a more complex region. Function {\stff putchunk} is retained because it is faster and therefore preferable for repeated operation in loops if the \pixelmask\ is not required.
See also the functions set and calc which can also change pixel values.
Input Parameters: pixels Numeric array. Required input. blc Bottom-Left-Corner (start) of location in image. Default is start of image. -1 inc increment (stride) along axes 1 list List bounding box to logger? false locking Unlock image after use? true replicate Replicate array through image false
Example:
We can clip all pixels to be { t <= } 5 as follows.
''' # print ' ---- putchunk Ex 1 ----' ia.fromshape(shape=[10,10]) # create an example image pix = ia.getchunk() # get pixels to modify from example image for i in range(len(pix)): pix[i] = list(pix[i]) # convert tuple to list so it can be modified for j in range(len(pix[i])): pix[i][j] = i*10 + j pix[i] = tuple(pix[i]) # convert list back to tuple ia.putchunk(pix) # put pixels back into example image print pix # pixels have values 0-99 pix2 = ia.getchunk() # get all pixels into an array (again) for i in range(len(pix2)): pix2[i] = list(pix2[i]) # convert tuple to list so it can be modified for j in range(len(pix2[i])): if pix2[i][j] \> 5: pix2[i][j] = 5 # clip values to 5 pix2[i] = tuple(pix2[i]) # convert list back to tuple ia.putchunk(pix2) # put array back into image print ia.getchunk() ia.close() # '''
The above example shows how you could clip an image to a value. If all the pixels didn't easily fit in memory, you would iterate through the image chunk by chunk to avoid exhausting virtual memory. Better would be to do this via LEL through function calc.
Suppose we wanted to set the fifth XY plane to 1.
We could do so as follows:
''' # print ' ---- putchunk Ex 2 ----' ia.fromshape(shape=[10,10,10]) imshape = ia.shape() pix = ia.makearray(1, [imshape[0],imshape[1]]) ia.putchunk(pix, blc=[0,0,4]) print ia.getchunk()[0:3] ia.close() # '''
Suppose we wanted to set the first YZ plane to 2.
''' # print ' ---- putchunk Ex 3 ----' ia.fromshape(shape=[10,10,10]) imshape = ia.shape() pix = ia.makearray(2, [1,imshape[1],imshape[2]]) ia.putchunk(pix) print ia.getchunk()[0:3] ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_putchunk(self, *args, **kwargs)
def putregion(self, *args, **kwargs): """ putregion(self, pixels = initialize_variant(""), pixelmask = initialize_variant(""), region = initialize_variant(""), list = False, usemask = True, locking = True, replicate = False) -> bool
Summary Put pixels and mask into a region-of-interest of the image
Description
This function replaces data and/or \pixelmask\ values in the image in the specified region. The {\stfaf pixels} and/or {\stfaf pixelmask} arrays must be the shape of the bounding box, and the whole bounding box is replaced in the image. The region\ is really only used to specify the bounding box. If the region extends beyond the image, it is truncated. If the {\stfaf pixels} or {\stfaf pixelmask} array shapes do not match the bounding box, an error will result.
When you put a \pixelmask, it either replaces the current default \pixelmask, or is created. The \pixelmask\ is put before the pixels.
The argument {\stfaf usemask} is only relevant when you are putting pixel values and there is a \pixelmask\ (meaning also the one you might have just put in place). If {\stfaf usemask=T} then only pixels for which the mask is good (T) are altered. If {\stfaf usemask=F} then all the pixels in the region are altered - the mask is ignored.
The argument {\stfaf replicate} can be used to replicate the array throughout the image (from the blc to the trc). For example, if you provide a 2D array to a 3D image, you can replicate it through the third axis by setting {\stfaf replicate=T}. The replication is done in the specified {\stfaf region}.
The argument {\stfaf locking} controls two things. If True, then after the function is called, the image is unlocked (so some other process can acquire a lock) and it is indicated that the image has changed. The reason for having this argument is that the unlocking and updating processes are quite expensive. If you are repeatedly calling {\stff putregion} in a for loop, you would be advised to use this switch (and to consider using {\stff putchunk}).
See the related functions putchunk, set and calc.
Input Parameters: pixels The pixel values. Default is none. pixelmask The pixel mask values. Default is none. region The region of interest. See help par.region for details. Default is whole image. list List the bounding box and any mask creation to the logger false usemask Honour the mask when putting pixels true locking Unlock image after use? true replicate Replicate array through image false
Example:
Suppose that we have a 2-dimensional image. First we recover the pixel and \pixelmask\ values from a polygonal region. Then we change the values in the array that are within the region to zero and replace the data.
''' # print ' ---- putregion Ex 1 ----' ia.maketestimage() # Attach an image to image tool x = ['3pix','6pix','9pix','6pix','5pix','5pix','3pix'] # X vector abs pixels y = ['3pix','4pix','7pix','9pix','7pix','5pix','3pix'] # Y vector abs pixels mycs = ia.coordsys() r1 = rg.wpolygon(x,y,csys=mycs.torecord()) # Create polygonal world region mycs.done() pixels = ia.getregion(r1) # Recover pixels pixelmask = ia.getregion(r1, getmask=T) # and mask for i in range(len(pixels)): pixels[i] = list(pixels[i]) # convert tuple to list for mods for j in range(len(pixels[i])): if pixelmask[i][j]: pixels[i][j] = 0 # Set pixels where mask is T to zero pixels[i] = tuple(pixels[i]) # convert list back to tuple ia.putregion(pixels=pixels, pixelmask=pixelmask, region=r1) # Replace pixels only ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_putregion(self, *args, **kwargs)
def rebin(self, *args, **kwargs): """ rebin(self, outfile, bin, region = initialize_variant(""), mask = initialize_variant(""), dropdeg = False, overwrite = False, async = False, stretch = False, crop = False) -> image
Summary Rebin an image by the specified integer factors
Description
This application rebins the current image by the specified integer binning factors for each axis. It supports both float valued and complex valued images. The corresponding output pixel value is the average of the input pixel values. The output pixel will be masked bad if there were no good input pixels. A polarization axis cannot be rebinned.
The binning factors array must contain at least one element and no more elements than the number of input image axes. If the number of elements specified is less than the number of image axes, then the remaining axes not specified are not rebinned. All specified values must be positive. A value of one indicates that no rebinning of the associated axis will occur.
Binning starts from the origin pixel of the bounding box of the selected region or the origin pixel of the input image if no region is specified. The value of crop is used to determine how to handle cases where there are pixels at the end of the axis that do not form a complete bin. If crop=True, extra pixels at the end of the axis are discarded. If crop=False, the remaining pixels are averaged into the final bin along that axis. Should the length of the axis to be rebinned be an integral multiple of the associated binning factor, the value of crop is irrelevant.
A value of dropdeg=True will result in the output image not containing axes that are degenerate in the specified region or in the input image if no region is specified. Note that, however, the binning factors array must still account for degenerate axes, and the binning factor associated with a degenerate axis must always be 1.
If {\stfaf outfile} is given, the image is written to the specified disk file. If {\stfaf outfile} is unset, the Image ool\ is associated with a temporary image. This temporary image may be in memory or on disk, depending on its size. When you destroy the on-the-fly Image ool\ returned by this function (with the done function) this temporary image is deleted.
Input Parameters: outfile Output image file name. Default is unset. bin Binning factors for each axis region The region of interest. See help par.region. Default is whole image. mask Mask to use. See help par.mask. Default is none. dropdeg Drop degenerate axes false overwrite Overwrite (unprompted) pre-existing output file? false async Run asynchronously? false stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false crop Remove pixels from the end of an axis to be rebinned if there are not enough to form an integral bin? false
Example:
''' # print ' ---- rebin Ex 1 ----' ia.maketestimage(); im2 = ia.rebin(bin=[2,3]); im2.done() ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_rebin(self, *args, **kwargs)
def regrid(self, *args, **kwargs): """ regrid(self, outfile = string(""), shape = initialize_vector(1, (int)-1), csys = initialize_record(""), axes = initialize_vector(1, (int)-1), region = initialize_variant(""), mask = initialize_variant(""), method = string("linear"), decimate = 10, replicate = False, doref = True, dropdeg = False, overwrite = False, force = False, asvelocity = False, async = False, stretch = False) -> image
Summary regrid this image to the specified Coordinate System
Description
This function regrids the current image onto a grid specified by the given Coordinate System. You can also specify the shape of the output image.
The Coordinate System must be given via a Coordsys ool\ (using coordsys.torecord()). It is optional; if not specified, the Coordinate System from the input image (i.e. the one to which you are applying the regrid function) is taken. The order of the coordinates and axes in the output image is always the same as the input image. It simply 'finds' the relevant coordinate in the supplied Coordinate System in order to figure out the regridding parameters. The supplied Coordinate System must have at least as many coordinates as are required to accomodate the axes you are regridding (e.g. if you regrid the first two axes, and these belong to a Direction Coordinate, you need one Direction Coordinate in the supplied Coordinate System). Coordinates pertaining to axes that are not being regridded are supplied from the input image, not the given Coordinate System.
Reference changes are handled (e.g. J2000 to B1950, LSR to TOPO). In general, the conversion machinery attempts to work out how sophisticated it needs to be (e.g. am I regridding LSR to LSR or LSR to TOPO). However, it errs on the side of conservatism so that it can be that the conversion machine requires more information than it actually needs. For full frame conversions, one needs to know things like location on earth (e.g. observatory), direction of observation, and time of observation.
If you get the above errors and you {f are} doing a frame conversion, then that means you must insert some extra information into the Coordinate System of your image. Most likely it's the time (coordsys.setepoch) and location (coordsys.settelescope) that are missing. If you get these errors and you {f know} that you are not specifying a frame change (e.g. regrid LSR to LSR) then try setting {\stfaf doref=F}. This will (silently) bypass all possible frame conversions. Note that if you {f are} requesting a frame conversion and you set {\stfaf doref=F} you are doing a bad thing (and you will get no warnings).
If you regrid a plane holding a Direction Coordinate and the units are Jy/pixel then the output is scaled to conserve flux (roughly; just one scale factor at the reference pixel is computed).
Regridding of complex-valued images is supported. The real and imaginary parts are regridded independently and the resulting regridded pixel values are combined to form the regridded, complex-valued image.
A variety of interpolation schemes are provided (you need only specify the first three characters to {\stfaf method}). The cubic interpolation is substantially slower than linear, and often the improvement is modest. By default you get linear interpolation.
You specify the shape of the output image ({\stfaf shape}) and which output axes you want to regrid ({\stfaf axes}). Note that a Stokes axis cannot be regridded (you will get a warning if you try).
The {\stfaf axes} argument cannot be used to discard axes from the output image; it can only be used to specify which {f output} axes are going to be regridded and which are not. Any axis that you are not regridding must have the same output shape as the input image shape for that axis.
The {\stfaf axes} argument can also be used to specify the order in which the {f output} axes are regridded. This may give you significant performance benefits. For example, imagine we are going to regrid a spectral-line cube of shape [512,512,1204] to shape [256,256,32]. If you specified {\stfaf axes=[0,1,2]} then first, the Direction axes would be regridded for each of the 1024 pixels (and stored in a temporary image). Then each profile at each spatial location in the temporary image would be regridded to 32 pixels. You could speed this process up significantly by setting {\stfaf axes=[2,0,1]}. In this case, first each profile would be regridded to 32 pixels, and then each plane of the 32 pixels would be regridded. Note that the order of {\stfaf axes} does not affect the order of the {\stfaf shape} argument. I.e. it should be given in the natural pixel axis order of the image {\stfaf [256,256,32]} in both cases.
You can also specify a region\ to be applied to the input image. If you do this, you need to be careful with the output shape for non-regridded axes (must match that of the region - use function boundingbox to find that out).
If {\stfaf outfile} is given, the image is written to the specified disk file. If {\stfaf outfile} is unset, the on-the-fly Image oolreturned by this function is associated with a temporary image. This temporary image may be in memory or on disk, depending on its size. When you destroy the on-the-fly Image ool\ (with the done function) this temporary image is deleted.
The argument {\stfaf replicate} can be used to simply replicate pixels rather than regridding them. Normally ({\stfaf replicate=F}), for every output pixel, its world coordinate is computed and the corresponding input pixel found (then a little interpolation grid is generated). If you set {\stfaf replicate=T}, then what happens is that for every output axis, a vector of regularly sampled input pixels is generated (based on the ratio of the output and input axis shapes). So this just means the pixels get replicated (by whatever interpolation scheme you use) rather than regridded in world coordinate space. This process is much faster, but its not a true world coordinate based regrid.
As decribed above, when {\stfaf replicate} is False, a coordinate is computed for each output pixel; this is an expensive operation. The argument {\stfaf decimate} allows you to decimate the computation of that coordinate grid to a sparse grid, which is then filled in via fast interpolation. The default for {\stfaf decimate} is 10. The number of pixels per axis in the sparse grid is the number of output pixels for that axis divided by the decimation factor. A factor of 10 does pretty well. You may find that for very non-linear coordinate systems (e.g. very close to the pole) that you have to reduce the decimation factor. You may also have to reduce the decimation factor if the number of pixels in the output image along an axis to be regridded is less than about 50, or the output image may be completely masked.
If one of the axes to be regridded is a spectral axis and asvelocity=T, the axis will be regridded to match the velocity, not the frequency, description of the template coordinate system. Thus the output pixel values will correspond only to the velocity, not the frequency, of the output axis.
Sometimes it is useful to drop axes of length one (degenerate axes). Use the {\stfaf dropdeg} argument if you want to do this. It will discard the axes from the input image. Therefore the output shape and Coordinate System that you supply must be consistent with the input image after the degenerate axes are dropped.
Argument {\stfaf force} can be used to force all specified axes to be regridded, even if the algorithm determines that they don't need to be (because the input and output coordinate information is identical).
There is a useful function setreferencelocation that you can use to keep a specific world coordinate in the center of an image when regridding (see example below).
The output \pixelmask\ will be good (T) unless the regridding failed to find a value for that output pixel in which case it will be bad (F). For example, if the total input mask (default input \pixelmask\ plus OTF mask) for all of the relevant input pixels were masked bad then the output pixel would be masked bad (F).
{f Multiple axis Coordinates limitation} -- Some cooordinates pertain to more than one axis. E.g. a Direction Coordinate holds longitude and latitude. A Linear Coordinate can also hold many axes. When you regrid *any* axis from a Coordinate which holds multiple axes, you must fully specify the coordinate information for all axes in that Coordinate in the Coordinate System that you provide. For example, you have a Linear Coordinate with two axes and you want to regrid axis one only. In the Coordinate System you provide, the coordinate information for axis two (not being regridded) must correctly be a copy from the input coordinate system (it won't be filled in for you).
If an image has per-plane beams and one attempts to regrid the spectral axis, an exception is thrown.
IMPORTANT NOTE ABOUT FLUX CONSERVATION in general regridding is inaccurate for images that the angular resolution is poorly sampled. A check is done for such cases and a warning message is emitted if a beam present. However, no such check is done if there is no beam present. To add a restoring beam to an image, use ia.setrestoringbeam().
Input Parameters: outfile Output image file name. Default is unset. shape Shape of output image. Default is input shape. -1 csys Coordinate System for output image. Default is input image coordinate system. axes The output pixel axes to regrid. Default is all. -1 region The region of interest. See help par.region for details. Default is the whole image. mask Mask to use. See help par.mask. Default is none. method The interpolation method. String from 'nearest', 'linear', 'cubic'. linear decimate Decimation factor for coordinate grid computation 10 replicate Replicate image rather than regrid? false doref Turn on reference frame changes true dropdeg Drop degenerate axes false overwrite Overwrite (unprompted) pre-existing output file? false force Force specified axes to be regridded false asvelocity Regrid spectral axis in velocity space rather than frequency space? false async Run asynchronously? false stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false
Example:
''' # print ' ---- regrid Ex 1 ----' ia.maketestimage('radio.image', overwrite=true) ia.maketestimage('optical.image', overwrite=true) mycs = ia.coordsys(); # get optical image co-ordinate system ia.open('radio.image') imrr = ia.regrid(outfile='radio.regridded', csys=mycs.torecord(), shape=ia.shape(), overwrite=true) #viewer() mycs.done() imrr.done() ia.close() # '''
In this example, we regrid a radio image onto the grid of an optical image - this probably (if the optical FITS image was correctly labelled !!) will involve a projection change (optical images are usually TAN projection, radio usually SIN).
Example:
''' # print ' ---- regrid Ex 2 ----' ia.maketestimage('radio.image',overwrite=true) mycs = ia.coordsys(); print mycs.referencecode('dir') #J2000 mycs.setreferencecode(value='B1950', type='dir', adjust=T) im3 = ia.regrid(outfile='radio.regridded', csys=mycs.torecord(), shape=ia.shape(), overwrite=true) mycs.done() im3.done() ia.close() # '''
In this example, we regrid a radio image from J2000 to B1950. This is accomplished by first recovering the Coordinate System into a Coordsys tool, manipulating the reference code with that ool, and then supplying the new Coordinate System to the regrid function.
Example:
''' # print ' ---- regrid Ex 3 ----' ia.maketestimage('zz', overwrite=true) mycs = ia.coordsys(); p = ia.shape() for i in range(len(p)): p[i] = p[i]/2.0 + 10 refval = ia.toworld(value=p, format='n') # Location of interest inc = mycs.increment() incx = inc['numeric'] for i in range(len(incx)): incx[i] = incx[i]/2.0 # Halve increment inc['numeric']=incx mycs.setincrement(value=inc) # Set increment shp = ia.shape() refpix=refval['numeric'][:] refpix=list(refpix) # numpy makes this necessary for i in range(len(shp)): shp[i] = shp[i] *2 # Double shape refpix[i] = int((shp[i]-1)/2.0 + 1); # New ref pix # Center image on location of interest mycs.setreferencelocation(pixel=refpix, world=refval) imr = ia.regrid(csys=mycs.torecord(), shape=shp, overwrite=true)# Regrid mycs.done() imr.done() ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_regrid(self, *args, **kwargs)
def transpose(self, *args, **kwargs): """ transpose(self, outfile = string(""), order = initialize_variant("")) -> image
Summary Transpose the image.
Description
This method transposes the axes in the input image to the specified order. The associated pixel and mask values and coordinate system are transposed.
If the outfile parameter is empty, only a temporary image is created; no output image is written to disk.
The order parameter describes the mapping of the input axes to the output axes. It can be one of three types: a non-negative integer, a string, or a list of strings. If a string or non-negative integer, it should contain zero-based digits describing the new order of the input axes. It must contain the same number of (unique) digits as the number of input axes. For example, specifying reorder='1032' or reorder=1032 for a four axes image maps input axes 1, 0, 3, 2 to output axes 0, 1, 2, 3. In the case of order being a nonnegative integer and the zeroth axis in the input being mapped to zeroth axis in the output, the zeroth digit is implicitly understood to be 0 so that to transpose an image where one would use a string order='0321', one could equivalently specify an int order=321. IMPORTANT: When specifying a non-negative integer and mapping the zeroth axis of the input to the zeroth axis of the output, do *not* explicitly specify the leading 0; eg, specify order=321 rather than order=0321. Python interprets an integer with a leading 0 as an octal number.
Because of ambiguity for axes numbers greater than nine, using string or integer order specifications cannot handle images containing more than 10 axes. The order parameter can also be specified as a list of strings which uniquely minimally match, ignoring case, the image axis names (ia.coordsys().names()). So to reorder an image with right ascension, declination, and frequency axes, one could specify order=['d', 'f', 'r'] or equivalently ['decl', 'frequ', 'right a']. Note that specifying 'ra' for the right ascension axis will result in an error because 'ra' does not match the first two characters of right ascension. Axes can be simultaneously inverted in cases where order is a string or an array of strings by specifying negative signs in front of the axis/axes to be inverted. So, in a 4-D image, order='-10-3-2' maps input axes 1, 0, 3, 2 to output axes 0, 1, 2, 3 and reverses the direction and values of input axes 1, 3, and 2.
Input Parameters: outfile Output image file name. Default is unset. order Zero-based order of axes in output image (eg '120' $=\>$ input$-\>$ output 0-$\>$2, 1-$\>$0, 2-$\>$1))
Example:
''' # swap stokes (axis 2) and spectral (axis 3) axes in a 4 dimensional image ia.open('myimage.fits') reordim = ia.transpose(outfile='my_reordered_image.im', order='0132') ia.done() '''
--------------------------------------------------------------------------------
""" return _image.image_transpose(self, *args, **kwargs)
def rotate(self, *args, **kwargs): """ rotate(self, outfile = string(""), shape = initialize_vector(1, (int)-1), pa = initialize_variant("0deg"), region = initialize_variant(""), mask = initialize_variant(""), method = string("cubic"), decimate = 0, replicate = False, dropdeg = False, overwrite = False, async = False, stretch = False) -> image
Summary rotate the direction coordinate axes attached to the image and regrid the image to the rotated Coordinate System
Description
This function rotates two axes of an image. These axes are either those associated with a Direction coordinate or with a Linear coordinate. The Direction coordinate takes precedence. If rotating a Linear coordinate, it must hold precisely two axes.
The method is that the Coordinate is rotated and then the input image is regridded to the rotated Coordinate System.
If the image brightness units are Jy/pixel then the output is scaled to conserve flux (roughly; just one scale factor at the reference pixel is computed).
A variety of interpolation schemes are provided (you need only specify the first three characters to {\stfaf method}). The cubic interpolation is substantially slower than linear. By default you get cubic interpolation.
You can specify the shape of the output image ({\stfaf shape}). However, all axis that are not regrided retain the same output shape as the input image shape for that axis. Only the direction coordinate axes are regridded.
You can also specify a region\ to be applied to the input image. If you do this, you need to be careful with the output shape for non-regridded axes (must match that of the region - use function boundingbox to find that out).
If {\stfaf outfile} is given, the image is written to the specified disk file. If {\stfaf outfile} is unset, the on-the-fly Image oolreturned by this function is associated with a temporary image. This temporary image may be in memory or on disk, depending on its size. When you destroy the on-the-fly Image ool\ (with the done function) this temporary image is deleted.
The argument {\stfaf replicate} can be used to simply replicate pixels rather than regridding them. Normally ({\stfaf replicate=F}), for every output pixel, its world coordinate is computed and the corresponding input pixel found (then a little interpolation grid is generated). If you set {\stfaf replicate=T}, then what happens is that for every output axis, a vector of regularly sampled input pixels is generated (based on the ratio of the output and input axis shapes). So this just means the pixels get replicated (by whatever interpolation scheme you use) rather than regridded in world coordinate space. This process is much faster, but its not a true world coordinate based regrid.
As decribed above, when {\stfaf replicate} is False, a coordinate is computed for each output pixel; this is an expensive operation. The argument {\stfaf decimate} allows you to decimate the computation of that coordinate grid to a sparse grid, which is then filled in via fast interpolation. The default for {\stfaf decimate} is 0 (no decimation). The number of pixels per axis in the sparse grid is the number of output pixels for that axis divided by the decimation factor. A factor of 10 does pretty well. You may find that for very non-linear coordinate systems (e.g. very close to the pole) that you have to reduce the decimation factor.
The output \pixelmask\ will be good (T) unless the regridding failed to find a value for that output pixel in which case it will be bad (F). For example, if the total input mask (default input \pixelmask\ plus OTF mask) for all of the relevant input pixels were masked bad then the output pixel would be masked bad (F).
Input Parameters: outfile Output image file name. Default is unset. shape Shape of output image. Default is shape of input image. -1 pa Angle by which to rotate. Default is no rotation. 0deg region The region of interest. See help par.region for details. Default is whole image. mask Mask to use. See help par.mask. Default is none. method The interpolation method. String from 'nearest', 'linear', or 'cubic'. cubic decimate Decimation factor for coordinate grid computation 0 replicate Replicate image rather than regrid? false dropdeg Drop degenerate axes false overwrite Overwrite (unprompted) pre-existing output file? false async Run asynchronously? false stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false
Example:
''' # print ' ---- rotate Ex 1 ----' ia.maketestimage(); imr=ia.rotate(pa='45deg'); imr.done() ia.close() # '''
In this example, we rotate the direction coordinate axes (RA/Dec) of a test image by 45 degress and regrid the image onto the axes.
--------------------------------------------------------------------------------
""" return _image.image_rotate(self, *args, **kwargs)
def rotatebeam(self, *args, **kwargs): """ rotatebeam(self, angle = initialize_variant("0deg")) -> bool
Summary rotate the image's beam(s) counterclockwise through the specified angle.
Description
This method rotates the attached image's beam(s) counterclockwise through the specified angle. This is the same thing as increasing the position angle(s) of the beam(s) by the specified angle. If the image does not have a beam, no changes to the image are made. If the image has multiple beams, all the beams are rotated through the same angle.
Input Parameters: angle Angle by which to rotate image's beam(s). Default is no rotation. 0deg
Example:
# rotate any and all beams in the image (increase their position angles) by 30 degrees. ia.open('my.im') ia.rotatebeam('30deg') ia.done()
--------------------------------------------------------------------------------
""" return _image.image_rotatebeam(self, *args, **kwargs)
def rename(self, *args, **kwargs): """ rename(self, name, overwrite = False) -> bool
Summary Rename the image file associated with this image tool
Description
This function renames the \imagefile\ associated with the \imagetool. If a file with name {\stfaf name} already exists, you can overwrite it with the argument {\stfaf overwrite}; otherwise a fail will result.
Input Parameters: name The new image file name overwrite Overwrite target file if it already exists false
Example:
''' # print ' ---- rename Ex 1 ----' ia.maketestimage('myimage',overwrite=T) print ia.name(strippath=T) #myimage ia.rename('newimage', overwrite=T) print ia.name(strippath=T) #newimage # '''
--------------------------------------------------------------------------------
""" return _image.image_rename(self, *args, **kwargs)
def replacemaskedpixels(self, *args, **kwargs): """ replacemaskedpixels(self, pixels, region = initialize_variant(""), mask = initialize_variant(""), update = False, list = False, stretch = False) -> bool
Summary replace the values of pixels which are masked bad
Description
This application replaces the values of all pixels whose total input mask (default input \pixelmask\ and OTF mask) is bad (F) with the specified value. It supports both float valued and compplex valued images.
If the argument {\stfaf update} is F (the default), the actual \pixelmaskis left unchanged. That is, masked pixels remain masked. However, if you set {\stfaf update=T} then the \pixelmask\ will be updated so that the \pixelmask\ will now be T (good) where the {f total} input mask was F (bad).
See maskhandler for information on how to set the default \pixelmask.
There are a few ways in which you can specify what to replace the masked pixel values by.
egin{itemize}
\item First, you can give the {\stfaf pixels} argument a simple numeric scalar (e.g. {\cf pixels=1.0}). Then, all masked values will be replaced by that value.
\item Second, you can give a scalar \htmladdnormallink{LEL}{../../notes/223/223.html} expression string (e.g. {\cf pixels='min(myimage)'}). Then, all masked values will be replaced by the scalar that results from the expression. If the scalar expression is illegal (e.g. in the expression {\cf pixels='min(myimage)'} there were no good pixels in {\sff myimage}) then the value 0 is used for replacement.
\item Third, you can give a \htmladdnormallink{LEL}{../../notes/223/223.html} expression string which has the same shape as the \imagefile\ you are applying the function to. For example, putting {\cf pixels='myotherimage'} means replace all masked pixels in this \imagefile\ with the equivalent pixel in the \imagefile\ called {\sff myotherimage}.
Your expression might be quite complex, and you can think of it as producing another masked lattice. However, in the replace process, the mask of that expression lattice is ignored. Thus, only the mask of the \imagefile\ you are replacing and the pixel values of the expression lattice are relevant.
The expression must conform with the subimage formed by applying the region\ to the image (i.e. that associated with this Image ool). If you use the {\stfaf mask} argument as well, the region\ is applied to it as well (see examples).
nd{itemize}
Input Parameters: pixels The new value(s), Numeric scalar or LEL expression region The region of interest. See help par.region for details. Default is whole image. mask Mask to use. See help par.mask. Default is none. update Update mask as well? false list List the bounding box to the logger false stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false
Example:
''' # print ' ---- replacemaskedpixels Ex 1 ----' ia.maketestimage('zz1',overwrite=true) ia.calcmask('zz1<0') ia.replacemaskedpixels(0.0) ia.replacemaskedpixels('min(zz1)') ia.close() # '''
These examples replace all masked pixels by the specified scalar. In the second case, the scalar comes from a LEL expression operating on {\sff zz1} (or it could be from an LEL expression operating on some other image).
Example:
''' # print ' ---- replacemaskedpixels Ex 2 ----' ia.maketestimage('zz2',overwrite=true) ia.close() ia.maketestimage('zz1',overwrite=true) #ia.calcmask('zz1<0') ia.replacemaskedpixels(0.0, mask='zz2\>0') ia.close() # '''
Let us say that {\sff zz1} has no mask. By using the {\stfaf mask} argument, we generate a transient mask which is T (good) when the pixel values are positive. This means that all non-positive values (when that mask is F [bad]) will be replaced with the value 0. If {\sff zz1} did have a mask it would be applied as well as the transient mask (the masks would be logically ORed).
Example:
''' # print ' ---- replacemaskedpixels Ex 3 ----' ia.maketestimage('zz1',overwrite=true) ia.calcmask('zz1<0') im2 = ia.subimage(outfile='zz2',overwrite=true) # r = rg.quarter() r=rg.box([0.25,0.25],[0.75,0.75],frac=true) ia.replacemaskedpixels(0.0, region=r, mask=im2.name(strippath=T)+'\>0') # same as ia.replacemaskedpixels(0.0, region=r, mask='zz2\>0') im2.done() ia.close() # '''
The specified region takes one quarter of the image by area centered on the image center. The region is applied to the {\stfaf mask} expression as well - this means that any images in the {\stfaf mask} expression must conform with the {\sff zz1} image. The replacement of the scalar is then done only within that region. Note that in the {\stfaf mask} expression we have specified the image with the Image tool {\stf im2} via im2.name() (rather than referring to its disk file name {\sff zz2}).
Example:
# print '\---- replacemaskedpixels Ex 4 ----' ia.maketestimage('zz3',overwrite=true) ia.maketestimage('zz2',overwrite=true) ia.maketestimage('zz1',overwrite=true) ia.calcmask('zz1<0') ia.replacemaskedpixels('zz2+zz3') ia.close() #
In this example, the replacement values are taken from a LEL expression adding two other images together. The expression must conform with the image {\sff zz1}.
--------------------------------------------------------------------------------
""" return _image.image_replacemaskedpixels(self, *args, **kwargs)
def restoringbeam(self, *args, **kwargs): """ restoringbeam(self, channel = -1, polarization = -1) -> record
Summary Get the restoring beam(s).
Description
This function gets the restoring beam(s), if any. If the image has a traditional restoring beam, that is returned no matter what channel and polarization are set to. If the image has per-plane beams and at least one of channel or polarization is set to a non-negative value, the beam for that particular plane is returned. In both these cases, the returned record contains fields 'major', 'minor' and 'postionangle'. Each of these fields contains a quantity.
If the image contains multiple beams and both channel and polarization are negative, a record containing all the beams is returned. This record contains three fields. 'nChannels' contains an integer value equal to the number of channels, 'nStokes' contains an integer value equal to the number of polarizations, and 'beams' contains a record of information for all beams. If the image has no polarization axis or no spectral axis, the fields in the 'beams' record run from '*0' to the number of spectral channels or number of polarizations less one, eg '*31' for an image with 32 channels. Each of these fields references a beam subrecord with the structure described above for a single beam.
If the image contains both a spectral axis and a polarization axis, the record returned contains fields running from '*0' to the number of spectral channels less one, eg '*31' for an image with 32 spectral channels. Each of these fields has an associated subrecord with fields running from '*0' to the number of polarizations less one, eg '*3' in an image with 4 polarizations. Each one of those fields is associated with a beam record for that corresponding channel and polarization. The beam record has a structure described above for a single beam.
If there is no restoring beam, this function returds an empty record.
You can set the restoring beam with function setrestoringbeam.
Input Parameters: channel The zero-based spectral channel number for a per-plane beam. Default -1 -1 polarization The zero-based polarization plane number for a per-plane beam. Default -1 -1
Example:
''' # print ' ---- restoringbeam Ex 1 ----' ia.maketestimage() print ia.restoringbeam() #{'major': {'unit': 'arcsec', 'value': 53.500004857778549}, # 'minor': {'unit': 'arcsec', 'value': 34.199998900294304}, # 'positionangle': {'unit': 'deg', 'value': 6.0}} ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_restoringbeam(self, *args, **kwargs)
def sepconvolve(self, *args, **kwargs): """ sepconvolve(self, outfile = string(""), axes = initialize_vector(1, (int)-1), types = std::vector< string >(1, ""), widths = initialize_variant(""), scale = -1, region = initialize_variant(""), mask = initialize_variant(""), overwrite = False, async = False, stretch = False) -> image
Summary Separable convolution
Description
This function does Fourier-based convolution of an \imagefile\ by a specified separable kernel.
If {\stfaf outfile} is given, the image is written to the specified disk file. If {\stfaf outfile} is unset, the on-the-fly Image oolreturned by this function is associated with a temporary image. This temporary image may be in memory or on disk, depending on its size. When you destroy the Image ool\ (with the done function) this temporary image is deleted.
You specify which axes of the image you wish to convolve, by what kernel of what width. The kernel types can be shortened to {\cf `gauss', `hann'} and {\cf `box'}.
You specify the widths of the convolution kernels via the argument {\stfaf widths}. The values can be specified as a vector of three different types.
egin{itemize}
\item Quantity - for example {\stfaf widths=qa.quantity('1arcsec 0.00001rad')}. Note that you can use pixel units, viz. {\stfaf widths=qa.quantity('10pix 0.00001rad')} see below.
\item String - for example {\stfaf widths='1km 2arcsec'} (i.e. a string that qa.quantity() accepts).
\item Numeric - for example {\stfaf widths=[10,20]}. In this case, the units of the widths are assumed to be in pixels.
nd{itemize}
The interpretation of {\stfaf widths} depends upon the kernel type.
egin{itemize}
\item Gaussian - the specified width is the full-width at half-maximum.
\item Boxcar (tophat) - the specified width is the full width.
\item Hanning - The kernel is $z[i] = 0.25*y[i-1] + 0.5*y[i] + 0.25*y[i+1]$. The width is always 3 pixels, regardless of what you give (but you still have to give it !).
nd{itemize}
The scaling of the output image is determined by the argument {\stfaf scale}. If you leave it unset, then autoscaling will be invoked which means that the convolution kernels will all be normalized to have unit volume to as to conserve flux.
If you do not leave {\stfaf scale} unset, then the convolution kernel will be scaled by this value (it has peak unity before application of this scale factor).
Masked pixels will be assigned the value 0.0 before convolution. The output mask is the combination (logical OR) of the default input \pixelmask\ (if any) and the OTF mask. Any other input \pixelmaskswill not be copied. Use function maskhandler if you need to copy other masks too.
See also the other convolution functions convolve2d, convolve and hanning.
Input Parameters: outfile Output image file name. Default is unset. axes Axes to convolve. Default is [0,1,...]. -1 types Type of convolution kernel. Vector of strings from 'boxcar', 'gaussian', and 'hanning'. Default is appropriately sized vector of 'gaussian'. widths Convolution kernel widths, Vector of numeric, quantity or string scale Scale factor. Default is autoscale. -1 region Region of interest. See help par.region for details. Default is whole image. mask Mask to use. See help par.mask. Default is none. overwrite Overwrite (unprompted) pre-existing output file? false async Run asynchronously? false stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false
Example:
''' # print ' ---- sepconvolve Ex 1 ----' ia.maketestimage('xyv',overwrite=true) im2 = ia.sepconvolve(outfile='xyv.con', axes=[0,1], types=['gauss','box'], widths=[10,20], overwrite=true) im2.done() ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_sepconvolve(self, *args, **kwargs)
def set(self, *args, **kwargs): """ set(self, pixels = initialize_variant(""), pixelmask = -1, region = initialize_variant(""), list = False) -> bool
Summary Set pixel and/or mask values with a scalar in a region-of-interest of the image
Description
This function replaces data and/or mask values within the image in the specified region. You can think of it as a simplified version of the image calculator.
Unlike the calc function, you can only set a scalar value for all pixels in the specified region. For example, it can be useful to set a whole image to one value, or a mask in a region\ to one value. Although you could do that with the related functions putregion and putchunk, you would have to make an array of the shape of the image and if that is large, it could be resource expensive.
The value for the pixels is specified with the {\stfaf pixels} argument. It can be given as either a Lattice Expression Language (or LEL) expression string or a simple numeric scalar. See \htmladdnormallink{note 223}{../../notes/223/223.html} for a detailed description of the LEL expression syntax. If you give a LEL expression it must be a scalar expression.
Note that any default mask is {m ignored} by this function when you set pixel values. This is different from calc where the extant mask is honoured.
The value for the pixel mask is specified with the {\stfaf pixelmask} argument ({\cf T, F, unset}). If it's {\cf unset} then the mask is not changed.
If you specify {\stfaf pixelmask=} T or F, then the mask that is affected is the current default mask (see maskhandler). If there is no mask, a mask is created for you and made the default mask.
Input Parameters: pixels The pixel value, LEL scalar expression or numeric scalar. Default is unset. pixelmask The pixel mask value. Either 0 or 1 if set. Default is unset. -1 region The region of interest. See help par.region for details. Default is whole image. list List the bounding box and any mask creation to the logger false
Example:
''' # print ' ---- set Ex 1 ----' ia.maketestimage('yy',overwrite=true) ia.fromshape('xx', [10,20], overwrite=true) r1 = rg.box([2,2],[6,8]) # Make a box region ia.set(pixels=1.0) # Set all pixels to 1 ia.set(pixels='2.0', region=r1) # Set all pixels to 2 in the region ia.set(pixels='min(yy)') # Set all pixels to minimum of image yy # Set pixels in region to minimum of image xx ia.set(pixels='min('+ia.name(strippath=T)+')', region=r1) ia.set(pixelmask=T) # Set mask to all T ia.set(pixels=0, pixelmask=F, region=r1) #Set pixels and mask in region ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_set(self, *args, **kwargs)
def setbrightnessunit(self, *args, **kwargs): """ setbrightnessunit(self, unit) -> bool
Summary Set the image brightness unit
Description
This function sets the image brightness unit. Both float and complex valued images are supported. You can get the brightness unit with function brightnessunit.
Input Parameters: unit New brightness unit
Example:
''' # print ' ---- setbrightnessunit Ex 1 ----' ia.fromshape(shape=[10,10]) ia.setbrightnessunit('km') print ia.brightnessunit() #km # '''
--------------------------------------------------------------------------------
""" return _image.image_setbrightnessunit(self, *args, **kwargs)
def setcoordsys(self, *args, **kwargs): """ setcoordsys(self, csys) -> bool
Summary Set new Coordinate System
Description
This function replaces the coordinate system in the image. It is supported for both float and complex valued images. Coordinate systems are manipulated with the cs ool. The coordinate system can be recovered from an image via the coordsys function.
Note that changing the cs ool\ has no effect on the original image, until it is replaced with this function; the value returned by coordsys() is a copy of, not a reference to, the image's coordinate system.
Input Parameters: csys Record describing new Coordinate System
Example:
''' # print ' ---- setcoordsys Ex 1 ----' ia.fromshape(shape=[10,20]) # Make image mycs = ia.coordsys(); # Recover Coordinate System incr = mycs.increment('n'); # Get increment as numeric vector incrn = incr['numeric'] for i in range(len(incrn)): incrn[i] = 2*incrn[i] incr['numeric']=incrn mycs.setincrement(value=incr); # Set new increment in Coordinate System ia.setcoordsys(mycs.torecord()); # Set new Coordinate System in image mycs.done() ia.close() # '''
--------------------------------------------------------------------------------
"""
def sethistory(self, *args, **kwargs): """ sethistory(self, origin = string(""), history = std::vector< string >(1, "")) -> bool
Summary Set the history for an image
Description
A \casa\ \imagefile\ can accumulate history information from an input its\ file or by you writing something into it explicitly with this function. Each element of the input vector is one line of history. The new history is appended to the old.
You can recover the history information with function history.
Input Parameters: origin Used to set message origin. Default is image::sethistory. history New history
Example:
''' # print ' ---- sethistory Ex 1 ----' ia.maketestimage('myfile',overwrite=true) h = ia.history() # Adds three lines, 'I', 'like' and 'fish' ia.sethistory(origin='sethistory', history=['I','like','fish']) ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_sethistory(self, *args, **kwargs)
def setmiscinfo(self, *args, **kwargs): """ setmiscinfo(self, info) -> bool
Summary Set the miscellaneous information record for an image
Description
A \casa\ \imagefile\ can accumulate miscellaneous information during its lifetime; it is stored in a record called the {\stff miscinfo} record. For example, the its\ reader (fromfits) puts header keywords it doesn't otherwise use into the {\stff miscinfo} record. The {\stff miscinfo} record is not guaranteed to have any entries, so it's up to you to check for any fields that you require.
This function sets the {\cf miscinfo} record of the \imagefile. Note that this function {m replaces} the record, it doesn't add to it, so if you want to augment the existing record, you should first capture it with the miscinfo function, add to the record, and then put it back. The its\ writer will attempt to write all the fields in the {\stff miscinfo} record to the its\ file. It can do so for scalars and 1-dimensional arrays. Records will be omitted, and multi-dimensional arrays will be flattened into 1-dimensional arrays.
Input Parameters: info Miscellaneous REPLACEMENT header
Example:
''' # print ' ---- setmiscinfo Ex 1 ----' ia.maketestimage('myfile',overwrite=true) info = ia.miscinfo() # capture the miscinfo record info['extra'] = 'a test entry' # add our information ia.setmiscinfo(info) # put it back into the image ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_setmiscinfo(self, *args, **kwargs)
def shape(self): """ shape(self) -> std::vector<(int)>
Summary Length of each axis in the image
Description
The shape of an image is a vector holding the length of each axis of the image. Although this information is also available in the summary function, it is so useful that it can be obtained directly. Both Float and Complex valued images are supported.
Example:
''' # print ' ---- shape Ex 1 ----' ia.fromshape(shape=[10,20,30]) imshape = ia.shape() print imshape #[10L, 20L, 30L] # npixels = imshape[0]*imshape[1]*...*imshape[n-1] npixels=1 for i in range(len(imshape)): npixels=npixels*imshape[i] ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_shape(self)
def setrestoringbeam(self, *args, **kwargs): """ setrestoringbeam(self, major = initialize_variant("1arcsec"), minor = initialize_variant("1arcsec"), pa = initialize_variant("0deg"), beam = initialize_record(""), remove = False, log = True, channel = -1, polarization = -1, imagename = string("")) -> bool
Summary Set the restoringbeam
Description
This function sets the restoring beam(s) for an image.
You may supply the beam in one of two ways.
First, you can use the argument {\stfaf beam} which you must assign to a record containing fields 'major', 'minor' and 'positionangle'. Each of these fields contains a quantity. This record is in the same format as one returned by function restoringbeam. If {\stfaf beam} is used, the arguments {\stfaf major, minor, \& pa} are ignored.
Second, you can use the arguments {\stfaf major}, {\stfaf minor} and {\stfaf pa}. Only the ones that you assign are used. Each argument should be assigned either a quantity or a float (units are implicitly those of the current beam - or if none, arcsec for the axes and degrees for the position angle). These parameters are only used if {\stfaf beam} is not specified.
An image must have exactly one of the following states:
1. An image can have a single 'traditional' beam. In that case, the beam applies to every channel and polarization in the image.
2. If an image has more than one spectral channel or more than one polarization, it can have a set of beams. In this case, each channel and/or polarization will have its own beam.
3. An image can have neither a traditional beam nor a beam set.
It is never permissible for an image to have both a traditional (global) beam and a set of per-plane beams. Task and method behavior is undefined in that case and any resulting products are considered corrupt.
RULES FOR BEAM MODIFICATION
If an image has no beams, a traditional (global) beam can be added by setting both channel and polarization to negative values.
If an image has no beams, a set of per-plane beams can be added by setting either or both channel and/or polarization to a non-negative value. In this case, a number of per-plane beams are added consistent with the image and they are all set to be the same with parameters equal to those specified by either the beam or major/minor/pa parameters.
If an image has a traditional beam, it can be modified by setting both channel and polarization to negative values. If one or both is not set to a negative value, an exception is thrown, and nothing is modified.
If an image has a set of per plane beams, one at a time of these can be modified by setting the appropriate channel number and/or polarization number. All the per-plane beams can be modified to the same values in one go by setting both channel and polarization to negative values. Also, in the case where an image has multiple channels, the beams associated with all channels for a given polarization can be modified to the same beam by setting polarization equal to the desired polarization plane number and by setting channel to a negative value. Similarly, in the case where an image has multiple polarizations, the beams associated with all polarizations for a given spectral channel can be modified to the same beam by setting channel equal to the desired spectral channel number and by setting polarization to a negative value.
A beam or set of beams can be copied from another image using the imagename parameter to specify that image's name. If both the current image and specified image have multiple beams, the current image shape must be consistent with the specified image beam set shape.
The traditional beam or a set of multiple beams can be deleted from an image by setting {\stfaf delete=T}. If set to true, all other parameters are then ignored; all existing beams will be irrevocably deleted.
Input Parameters: major Major axis FWHM, Quantity or float (e.g., 1arcsec). Default is unset. 1arcsec minor Minor axis FWHM, Quantity or float (e.g., 1arcsec). Default is unset. 1arcsec pa Position angle, Quantity or float (e.g., '5deg'). Default is unset. 0deg beam The complete restoring beam (output of restoringbeam()). Default is unset. remove Delete the restoring beam? false log Write new beam values to the logger? true channel Zero-based channel number for which to set a per plane beam. If the image has a traditional beam, set to less than zero. Default -1. -1 polarization Zero-based polarization number for which to set a per plane beam. If the image has a traditional beam, set to less than zero. Default -1. -1 imagename Copy the beam(s) from the specified image to this image. If multiple beams, the current image must be able to hold a beam set of the shape in the specified image.
Example:
'''
ia.maketestimage('hcn',overwrite=true) rb = ia.restoringbeam() # returns beam in record print rb #{'major': {'unit': 'arcsec', 'value': 53.500004857778549}, # 'minor': {'unit': 'arcsec', 'value': 34.199998900294304}, # 'positionangle': {'unit': 'deg', 'value': 6.0}} rb['minor']['value'] = 12.5 # new beam specified in record # NOTE This will not work for an image with multiple beams ia.setrestoringbeam(beam=rb) print ia.restoringbeam() #{'major': {'unit': 'arcsec', 'value': 53.500004857778549}, # 'minor': {'unit': 'arcsec', 'value': 12.5}, # 'positionangle': {'unit': 'deg', 'value': 6.0}}
# beam specified using parameter # NOTE This will only work for an image with a traditional beam ia.setrestoringbeam(major='36arcsec') print ia.restoringbeam() #{'major': {'unit': 'arcsec', 'value': 36.0}, # 'minor': {'unit': 'arcsec', 'value': 12.5}, # 'positionangle': {'unit': 'deg', 'value': 6.0}} ia.setrestoringbeam(remove=true) print ia.restoringbeam() #{} ia.setrestoringbeam(major='53.5arcsec',minor='34.2arcsec',pa='6deg') print ia.restoringbeam() #{'major': {'unit': 'arcsec', 'value': 53.5}, # 'minor': {'unit': 'arcsec', 'value': 34.200000000000003}, # 'positionangle': {'unit': 'deg', 'value': 6.0}} ia.close()
# Copy all beams from an image with multiple beams to another # image with the same number of channels and polarizations
ia.open('multibeam.im') ib = iatool() ib.open('target.im')
# ensure target has no beam(s) at start, not always necessary # but it doesn't hurt to do it. ib.setrestoringbeam(remove=True) # Now copy the beams. This only will work correctly if both images # have the same number of channels and polarizations. nchan is set to # the number of channels and npol is set to the number of polarizations for c in range(nchan): for p in range(npol): beam = ia.restoringbeam(channel=c, polarization=p) ib.setrestoringbeam(beam=beam, channel=c, polarization=p)
ia.done() ib.done()
'''
--------------------------------------------------------------------------------
""" return _image.image_setrestoringbeam(self, *args, **kwargs)
def statistics(self, *args, **kwargs): """ statistics(self, axes = initialize_vector(1, (int)-1), region = initialize_variant(""), mask = initialize_variant(""), includepix = initialize_vector(1, (double)-1), excludepix = initialize_vector(1, (double)-1), list = False, force = False, disk = False, robust = False, verbose = False, stretch = False, logfile = string(""), append = True, algorithm = string("classic"), fence = -1, center = string("mean"), lside = True, zscore = -1, maxiter = -1, clmethod = string("auto")) -> record
Summary Compute statistics from the image
Description
This function computes statistics from the pixel values in the image. You can then list them and retrieve them (into a record) for further analysis.
The chunk of the image over which you evaluate the statistics is specified by an array of axis numbers (argument {\stfaf axes}). For example, consider a 3-dimensional image for which you specify {\stfaf axes=[0,2]}. The statistics would be computed for each XZ (axes 0 and 2) plane in the image. You could then examine those statistics as a function of the Y (axis 1) axis. Or perhaps you set {\stfaf axes=[2]}, whereupon you could examine the statistics for each Z (axis 2) profile as a function of X and Y location in the image.
Each statistic is stored in an array in one named field in the returned record. The shape of that array is that of the axes which you did {f not} evaluate the statistics over. For example, in the second example above, we set {\stfaf axes=[2]} and asked for statistics as a function of the remaining axes, in this case, the X and Y (axes 0 and 1) axes. The shape of each statistics array is then [nx,ny].
The names of the fields in this record are the same as the names of the statistics that you can plot:
egin{itemize}
\item {\stfaf npts} - the number of unmasked points used
\item {\stfaf sum} - the sum of the pixel values: $\sum I_i$
\item {\stfaf flux} - flux or flux density, see below for details
\item {\stfaf sumsq} - the sum of the squares of the pixel values: $\sum I_i^2$
\item {\stfaf mean} - the mean of pixel values: $ar{I} = \sum I_i / n$
\item {\stfaf sigma} - the standard deviation about the mean: $\sigma^2 = (\sum I_i - ar{I})^2 / (n-1)$
\item {\stfaf rms} - the root mean square: $\sqrt {\sum I_i^2 / n}$
\item {\stfaf min} - minimum pixel value
\item {\stfaf max} - the maximum pixel value
\item {\stfaf median} - the median pixel value (if {\stfaf robust=T})
\item {\stfaf medabsdevmed} - the median of the absolute deviations from the median (if {\stfaf robust=T})
\item {\stfaf quartile} - the inter-quartile range (if {\stfaf robust=T}). Find the points which are 25\% largest and 75\% largest (the median is 50\% largest).
\item {\stfaf q1} - The first quartile. Reported only if robust=T.
\item {\stfaf q3} - The third quartile. Reported only if robust=T.
\item {\stfaf blc} - the absolute pixel coordinate of the bottom left corner of the bounding box of the region of interest. If 'region' is unset, this will be the bottom left corner of the whole image.
\item {\stfaf blcf} - the formatted absolute world coordinate of the bottom left corner of the bounding box of the region of interest.
\item {\stfaf trc} - the absolute pixel coordinate of the top right corner of the bounding box of the region of interest.
\item {\stfaf trcf} - the formatted absolute world coordinate of the top right corner of the bounding box of the region of interest.
\item {\stfaf minpos} - absolute pixel coordinate of minimum pixel value
\item {\stfaf maxpos} - absolute pixel coordinate of maximum pixel value
\item {\stfaf minposf} - formatted string of the world coordinate of the minimum pixel value
\item {\stfaf maxposf} - formatted string of the world coordinate of the maximum pixel value
nd{itemize}
The last four fields only appear if you evaluate the statistics over all axes in the image. As an example, if the returned record is captured in {\stfaf `mystats'}, then you could access the `mean' field via {\cf print mystats['mean']}.
If there are no good points (e.g. all pixels are masked bad in the region), then the length of these fields will be 0 (e.g. {\cf len(mystats['npts'])==0}).
You have no control over which statistics are listed to the logger, you always get the same selection. You can choose to list the statistics or not (argument {\stfaf list}).
As well as the simple (and faster to calculate) statistics like means and sums, you can also compute some robust (quantile-like) statistics. Currently these are the median, median absolute deviations from the median, the first and third quartiles, and the inner-quartile range. Because these are computationally expensive, they are only computed if robust=True.
Note that if the axes are set to all of the axes in the image (which is the default) there is just one value per statistic.
You have control over which pixels are included in the statistics computations via the {\stfaf includepix} and {\stfaf excludepix} arguments. These vectors specify a range of pixel values for which pixels are either included or excluded. They are mutually exclusive; you can specify one or the other, but not both. If you only give one value for either of these, say {\stfaf includepix=b}, then this is interpreted as {\stfaf includepix=[-abs(b),abs(b)]}.
This function generates a `storage' lattice, into which the statistics are written. It is only regenerated when necessary. For example, if you run the function twice with identical arguments, the statistics will be directly retrieved from the storage lattice the second time. However, you can force regeneration of the storage image if you set {\stfaf force=T}. The storage medium is either in memory or on disk, depending upon its size. You can force it to disk if you set {\stfaf disk=T}, otherwise it decides for itself.
ALGORITHMS
Several types of statistical algorithms are supported:
* classic: This is the familiar algorithm, in which all unmasked pixels, subject to any specified pixel ranges, are used. One may choose one of two methods, which vary only by performance, for computing classic statistics, via the clmethod parameter. The 'tiled' method is the old method and is fastest in cases where there are a large number of individual sets of statistics to be computed and a small number of data points per set. This can occur when one sets the axes parameter, which causes several individual sets of statistics to be computed. The 'framework' method uses the new statistics framework to compute statistics. This method is fastest in the regime where one has a small number of individual sets of statistics to calculate, and each set has a large number of points. For example, this method is fastest when computing statistics over an entire image in one go (no axes specified). A third option, 'auto', chooses which method to use by predicting which be faster based on the number of pixels in the image and the choice of the axes parameter.
* fit-half: This algorithm calculates statistics on a dataset created from real and virtual pixel values. The real values are determined by the input parameters center and lside. The parameter center tells the algorithm where the center value of the combined real+virtual dataset should be. Options are the mean or the median of the input image's pixel values, or at zero. The lside parameter tells the algorithm on which side of this center the real pixel values are located. True indicates that the real pixel values to be used are <= center. False indicates the real pixel values to be used are >= center. The virtual part of the dataset is then created by reflecting all the real values through the center value, to create a perfectly symmetric dataset composed of a real and a virtual component. Statistics are then calculated on this resultant dataset. These two parameters are ignored if algorithm is not 'fit-half'. Because the maximum value is virtual if lside is True and the minimum value is virtual if lside is False, the value of the maximum position (if lside=True) or minimum position (if lside=False) is not reported in the returned record.
* hinges-fences: This algorithm calculates statistics by including data in a range between Q1 - f*D and Q3 + f*D, inclusive, where Q1 is the first quartile of the distribution of unmasked data, subject to any specified pixel ranges, Q3 is the third quartile, D = Q3 - Q1 (the inner quartile range), and f is the user-specified fence factor. Negative values of f indicate that the full distribution is to be used (ie, the classic algorithm is used). Sufficiently large values of f will also be equivalent to using the classic algorithm. For f = 0, only data in the inner quartile range is used for computing statistics. The value of fence is silently ignored if algortihm is not 'hinges-fences'.
* chauvenet: The idea behind this algorithm is to eliminate outliers based on a maximum z-score value. A z-score is the number of standard deviations a point is from the mean of a distribution. This method thus is meant to be used for (nearly) normal distributions. In general, this is an iterative process, with successive iterations discarding additional outliers as the remaining points become closer to forming a normal distribution. Iterating stops when no additional points lie beyond the specified zscore value, or, if zscore is negative, when Chauvenet's criterion is met (see below). The parameter maxiter can be set to a non-negative value to prematurely abort this iterative process. When verbose=T, the 'N iter' column in the table that is logged represents the number of iterations that were executed.
Chauvenet's criterion allows the target z-score to decrease as the number of points in the distribution decreases on subsequent iterations. Essentially, the criterion is that the probability of having one point in a normal distribution at a maximum z-score of z_max must be at least 0.5. z_max is therefore a function of (only) the number of points in the distrbution and is given by
npts = 0.5/erfc(z_max/sqrt(2))
where erfc() is the complementary error function. As iterating proceeds, the number of remaining points decreases as outliers are discarded, and so z_max likewise decreases. Convergence occurs when all remaining points fall within a z-score of z_max. Below is an illustrative table of z_max values and their corresponding npts values. For example, it is likely that there will be a 5-sigma 'noise bump' in a perfectly noisy image with one million independent elements.
z_max npts 1.0 1 1.5 3 2.0 10 2.5 40 3.0 185 3.5 1,074 4.0 7,893 4.5 73,579 5.0 872,138 5.5 13,165,126 6.0 253,398,672 6.5 6,225,098,696 7.0 195,341,107,722
NOTES ON FLUX DENSITIES AND FLUXES
Fluxes and flux densities are not computed if any of the following conditions is met:
1. The image does not have a direction coordinate 2. The image does not have a intensity-like brightness unit. Examples of such units are Jy/beam (in which case the image must also have a beam) and K. 3. There are no direction axes in the cursor axes that are used. 4. If the (specified region of the) image has a non-degenerate spectral axis, and the image has a tablular spectral axis (axis with varying increments) 5. Any axis that is not a direction nor a spectral axis that is included in the cursor axes is not degenerate within in the specified region
Note that condition 4 may be removed in the future.
In cases where none of the above conditions is met, the flux density(ies) (intensities integrated over direction planes) will be computed if any of the following conditions are met:
1. The image has no spectral coordinate 2. The cursor axes do not include the spectral axis 3. The spectral axis in the chosen region is degenerate
In the case where there is a nondegenerate spectral axis that is included in the cursor axes, the flux (flux density integrated over spectral planes) will be computed. In this case, the spectral portion of the flux unit will be the velocity unit of the spectral coordinate if it has one (eg, if the brightness unit is Jy/beam and the velocity unit is km/s, the flux will have units of Jy.km/s). If not, the spectral portion of the flux unit will be the frequency unit of the spectral axis (eg, if the brightness unit is K and the frequency unit is Hz, the resulting flux unit will be K.arcsec2.Hz).
In both cases of flux density or flux being computed, the resulting numerical value is assigned to the 'flux' key in the output dictionary.
Input Parameters: axes List of axes to evaluate statistics over. Default is all axes. -1 region Region of interest. See help par.region for details. Default is whole image. mask Mask to use. See help par.mask. Default is none. includepix Range of pixel values to include. Vector of 1 or 2 doubles. Default is to include all pixels. -1 excludepix Range of pixel values to exclude. Vector of 1 or 2 doubles. Default is exclude no pixels. -1 list If True print bounding box and statistics to logger. false force If T then force the stored statistical accumulations to be regenerated false disk If T then force the storage image to disk false robust If T then compute robust statistics as well false verbose If T then log statistics false stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false logfile Name of file to which to write statistics. append Append results to logfile? Logfile must be specified. Default is to append. False means overwrite existing file if it exists. true algorithm Algorithm to use. Supported values are 'chauvenet', 'classic', 'fit-half', and 'hinges-fences'. Minimum match is supported. classic fence Fence value for hinges-fences. A negative value means use the entire data set (ie default to the 'classic' algorithm). Ignored if algorithm is not 'hinges-fences'. -1 center Center to use for fit-half. Valid choices are 'mean', 'median', and 'zero'. Ignored if algorithm is not 'fit-half'. mean lside For fit-half, real data are <=; center? If false, real data are >= center. Ignored if algorithm is not 'fit-half'. true zscore For chauvenet, this is the target maximum number of standard deviations data may have to be included. If negative, use Chauvenet's criterion. Ignored if algorithm is not 'chauvenet'. -1 maxiter For chauvenet, this is the maximum number of iterations to attempt. Iterating will stop when either this limit is reached, or the zscore criterion is met. If negative, iterate until the zscore criterion is met. Ignored if algortihm is not 'chauvenet'. -1 clmethod Method to use for calculating classical statistics. Supported methods are 'auto', 'tiled', and 'framework'. Ignored if algorithm is not 'classic'. auto
Example:
''' # print ' ---- statistics Ex 1 ----' ia.maketestimage() ia.statistics() ia.close() #
# evaluate statistics for each spectral plane in an ra x dec x frequency image ia.fromshape('', [20,30,40]) # give pixels non-zero values ia.addnoise() # These are the display axes, the calculation of statistics occurs # for each (hyper)plane along axes not listed in the axes parameter, # in this case axis 2 (the frequency axis) # display the rms for each frequency plane (your mileage will vary with # the values). stats = ia.statistics(axes=[0,1]) stats['rms'] Out[10]: array([ 0.99576014, 1.03813124, 0.97749186, 0.97587883, 1.04189885, 1.03784776, 1.03371549, 1.03153074, 1.00841606, 0.947155 , 0.97335404, 0.94389403, 1.0010221 , 0.97151822, 1.03942156, 1.01158476, 0.96957082, 1.04212773, 1.00589049, 0.98696715, 1.00451481, 1.02307892, 1.03102005, 0.97334671, 0.95209879, 1.02088714, 0.96999902, 0.98661619, 1.01039267, 0.96842754, 0.99464947, 1.01536798, 1.02466023, 0.96956468, 0.98090756, 0.9835844 , 0.95698935, 1.05487967, 0.99846411, 0.99634868])
'''
In this example, we ask to see statistics evaluated over the entire image.
Example:
''' # print ' ---- statistics Ex 2 ----' ia.maketestimage() stats = ia.statistics(axes=[1],plotstats=['sigma','rms'], includepix=[0,100],list=F) # '''
In this example, let us assume the image has 2 dimensions. We want the standard deviation about the mean and the rms of Y (axes 1) for pixels with values in the range 0 to 100 as a function of the X-axis location. The statistics are not listed to the logger but are saved in the record {\stfaf 'stats'}.
--------------------------------------------------------------------------------
""" return _image.image_statistics(self, *args, **kwargs)
def twopointcorrelation(self, *args, **kwargs): """ twopointcorrelation(self, outfile = string(""), region = initialize_variant(""), mask = initialize_variant(""), axes = initialize_vector(1, (int)-1), method = string("structurefunction"), overwrite = False, stretch = False) -> bool
Summary Compute two point correlation function from the image
Description
This function computes two-point auto-correlation functions from an image.
By default, the auto-correlation function is computed for the Sky axes. If there is no sky in the image, then the first two axes are used. Otherwise you can specify which axes the auto-correlation function lags are computed over with the {\stfaf axes} argument (must be of length 2).
Presently, only the Structure Function is implemented. This is defined as :
egin{displaymath} S(lx,ly) = \< (data(i,j) - data(i+lx,j+ly))^2 \> nd{displaymath}
where $lx, ly$ are integer lags in the x (0-axis) and y (1-axis) directions. The ensemble average is over all the values at the same lag pair. This process is extremely compute intensive and so you may have to be patient.
In an auto-correlation function image there are some symmetries. The first and third quadrants are symmetric, and the second and fourth are symmetric. So in principle, all the information is in the top or bottom half of the image. We just write it all out to look nice. The long lags don't have a lot of contributing values of course.
Input Parameters: outfile Output image file name. Default is unset. region The region of interest. See help par.region for details. Default is whole image. mask Mask to use. See help par.mask. Default is none. axes The pixel axes to compute structure function over. The default is sky or first two axes. -1 method The method of computation. String from 'structurefunction'. structurefunction overwrite Overwrite (unprompted) pre-existing output file? false stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false
Example:
''' # print ' ---- twopointcorrelation Ex 1 ----' ia.maketestimage(); # Output image is virtual ia.twopointcorrelation() # Output image is virtual # '''
--------------------------------------------------------------------------------
""" return _image.image_twopointcorrelation(self, *args, **kwargs)
def subimage(self, *args, **kwargs): """ subimage(self, outfile = string(""), region = initialize_variant(""), mask = initialize_variant(""), dropdeg = False, overwrite = False, list = True, stretch = False, wantreturn = True) -> image
Summary Create a (sub)image from a region of the image
Description
This function copies all or part of the image to another on-the-fly Image tool. Both float and complex valued images are supported.
If {\stfaf outfile} is given, the subimage is written to the specified disk file. If {\stfaf outfile} is unset, the returned Image ool\ actually references the input image file (i.e. that associated with the Image ool\ to which you are applying this function). So if you deleted the input image disk file, it would render this ool\ useless. When you destroy this ool\ (with the done function) the reference connection is broken.
Sometimes it is useful to drop axes of length one (degenerate axes). Use the {\stfaf dropdeg} argument if you want to do this.
The output mask is the combination (logical OR) of the default input \pixelmask\ (if any) and the OTF mask. Any other input \pixelmaskswill not be copied. Use function maskhandler if you need to copy other masks too.
If the mask has fewer dimensions than the image and if the shape of the dimensions the mask and image have in common are the same, the mask will automatically have the missing dimensions added so it conforms to the image.
If stretch is true and if the number of mask dimensions is less than or equal to the number of image dimensions and some axes in the mask are degenerate while the corresponding axes in the image are not, the mask will be stetched in the degenerate dimensions. For example, if the input image has shape [100, 200, 10] and the input mask has shape [100, 200, 1] and stretch is true, the mask will be stretched along the third dimension to shape [100, 200, 10]. However if the mask is shape [100, 200, 2], stretching is not possible and an error will result.
Input Parameters: outfile Output image file name. Default is unset. region Region of interest. Default is whole image. mask Mask to use. See help par.mask. Default is none. dropdeg Drop degenerate axes false overwrite Overwrite (unprompted) pre-existing output file? false list List informative messages to the logger true stretch Stretch the mask if necessary and possible? false wantreturn Return an image analysis tool attached to the created subimage true
Example:
''' # print ' ---- subimage Ex 1 ----' ia.maketestimage('myfile',overwrite=true) im2 = ia.subimage() # a complete copy r1 = rg.box([10,10],[30,40],[5,5]) # A strided pixel box region im3 = ia.subimage(outfile='/tmp/foo', region=r1, overwrite=true) # Explicitly named subimage im2.done() im3.done() ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_subimage(self, *args, **kwargs)
def summary(self, *args, **kwargs): """ summary(self, doppler = string("RADIO"), list = True, pixelorder = True, verbose = False) -> record
Summary Summarize basic information about the image
Description
This function summarizes miscellaneous information such as shape, Coordinate System, restoring beams, and masks.
If called without any arguments, this function displays a summary of the image header to the logger; where appropriate, values will be formatted nicely (e.g. HH:MM:SS.SS for the reference value of RA axes).
For spectral axes, the information is listed as a velocity as well as a frequency. The argument {\stfaf doppler} allows you to specify what velocity doppler convention it is listed in. You can choose from {\stfaf radio, optical} and {\stfaf true}. Alternative names are {\stfaf z} for {\stfaf optical}, and {\stfaf beta} or {\stfaf relativistic} for {\stfaf true}. The default is {\stfaf radio}. The definitions are
egin{itemize} \item radio: $1 - F$ \item optical: $-1 + 1/F$ \item true: $(1 - F^2)/(1 + F^2)$ nd{itemize} where $F = u/ u_0$ and $ u_0$ is the rest frequency. If the rest frequency has not been set in your image, you can set it via a Coordsys ool\ with the function setrestfrequency.
If the output of summary is saved to a variable, then the {\stfaf header} field (for instance, {\stfaf mysummary['header']}) has the following fields filled in:
egin{description} \item[ndim] Dimension of the image. \item[shape] Length of each axis in the image. \item[tileshape] Shape of the chunk which is most efficient for I/O. \item[axisnames] Name of each axis. \item[refpix] Reference pixel for each axis (0-relative) \item[refval] Reference value for each axis. \item[incr] Increment for each axis. \item[axisunits] Unit name for each axis. \item[unit] Brightness units for the pixels. \item[hasmask] True if the image has a mask. \item[defaultmask]The name of the mask which is applied by default. \item[masks] The names of all the masks stored in this image. \item[restoringbeam] The restoring beam(s) if present. \item[imagetype] The image type. nd{description}
For an image with multiple beams, the restoringbeam field is a dictionary of dictionaries with keys of names '*' followed by the channel number, if the image has a spectral coordinate, or the polarization number if it does not. That is, the keys have names '*0', '*1', '*2', etc. If the image has both a spectral and a polarization coordinate, each of these dictionaries is a dictionary with keys of the same form which range from 0 to the number of polarizations minus 1; '*0', '*1', ... The dictionaries pointed to by the channel and/or polarization number contain information for the beam at that position.
If you set {\stfaf list=F}, then the summary will not be written to the logger. The return value of the function, in the {\stfaf header} field is a vector string containing the formatted output that would normally have gone to the logger.
If verbose is True and the image contains multiple beams, the formatted output, whether it is written to the logger or placed in the output record, will have information on every beam in the dataset. If verbose=False and the image has multiple beams, only a summary of beams for each polarization is listed. In this case, the beams with the maximum area, the minimum area, and the median area for each polarization are listed. However, all the beams can still be found in the restoringbeam field of the returned dictionary. If the image does not have multiple beams, verbose is not used.
Input Parameters: doppler If there is a spectral axis, list velocity too, with this doppler definition RADIO list List the summary to the logger true pixelorder List axis descriptors in pixel or world axis order true verbose Give a full listing of beams or just a short summary? Only used when the image has multiple beams. false
Example:
''' # print ' ---- summary Ex 1 ----' ia.maketestimage('myim1', overwrite=true) ia.summary() # summarize to logging only s = ia.summary(list=F) # store header in record if s['header']['ndim'] == 2: # program using header values print s['header']['axisnames'] ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_summary(self, *args, **kwargs)
def tofits(self, *args, **kwargs): """ tofits(self, outfile = string(""), velocity = False, optical = True, bitpix = -32, minpix = 1, maxpix = -1, region = initialize_variant(""), mask = initialize_variant(""), overwrite = False, dropdeg = False, deglast = False, dropstokes = False, stokeslast = True, wavelength = False, airwavelength = False, async = False, stretch = False, history = True) -> bool
Summary Convert the image to a FITS file
Description
This function converts the image into a its\ file.
If the image has a rest frequency associated with it, it will always write velocity information into the its\ file. By default the frequency information will be primary as it is the internal native format. If you select {\stfaf velocity=T} then by default the velocity is written in the optical convention, but if {\stfaf optical=F} it will use the radio convention instead. Alternatively, if you use {\stfaf velocity=F} and {\stfaf wavelength=T}, the spectral axis will be written in wavelength.
The its\ definition demands equal increment pixels. Therefore, if you write wavelength or optical velocity information as primary, the increment is computed at the spectral reference pixel. If the bandwidth is large, this may incur non-negligible coordinate calculation errors far from the reference pixel if the spectral bins are not originally equidistant in wavelength. Images generated by the CASA clean task have spectral axes which are always equidistant in frequency.
By default the image is written as a floating point its\ file ({\stfaf bitpix= -32}). Under rare circumstances you might want to save space and write it as scaled 16 bit integers ({\stfaf bitpix = 16}). You can have {\stff tofits} calculate the scaling factors by using the default {\stfaf minpix} and {\stfaf maxpix}. If you set {\stfaf minpix} and {\stfaf maxpix}, values outside of that range will be truncated. This can be useful if all of the its\ images dynamic range is being used by a few high or low values and you are not interested in preserving those values exactly. Besides the factor of two space savings you get by using 16 instead of 32 bits, integer images usually also compress well (for example, with the standard GNU software facility { t gzip}).
If the specified region\ extends beyond the image, it is truncated.
The output mask is the combination (logical OR) of the default input \pixelmask\ (if any) and the OTF mask.
Sometimes it is useful to drop axes of length one (degenerate axes) because not all FITS readers can handle them. Use the {\stfaf dropdeg} argument if you want to do this. If you want to specifically only drop a degenerate Stokes axis, use the {\stfaf dropstokes} argument.
If you want to place degenerate axes last in the FITS header, use the {\stfaf deglast} argument. If you want to make sure that the Stokes axis is placed last in the FITS header, use the {\stfaf stokeslast} argument.
Input Parameters: outfile FITS file name. Default is input name + '.fits' velocity prefer velocity (rather than frequency) as primary spectral axis? false optical use the optical (rather than radio) velocity convention? true bitpix Bits per pixel, -32 (floating point) or 16 (integer) -32 minpix Minimum pixel value for BITPIX=16, Default is to autoscale if minpix \> maxpix. 1 maxpix Maximum pixel value for BITPIX=16, Default is to autoscale if maxpix \< minpix. -1 region The region of interest. See help par.region for details. Default is whole image. mask Mask to use. See help par.mask. Default is none. overwrite Overwrite (unprompted) pre-existing output file? false dropdeg Drop degenerate axes? false deglast Put degenerate axes last in header? false dropstokes Drop Stokes axis? false stokeslast Put Stokes axis last in header? true wavelength Write spectral axis in units of wavelength (instead of velocity or frequency)? false airwavelength When wirting the spectral axis in units of wavelength, use air wavelength instead of vacuum wavelength? false async Run asynchronously? false stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false history Write the image history to the FITS file? Default True true
Example:
''' # print ' ---- tofits Ex 1 ----' ia.maketestimage() ok = ia.tofits('MYFILE.FITS',overwrite=true) # write FITS image file ok = ia.tofits('MYFILE2.FITS', bitpix=16, overwrite=true) # Write as scaled 16 bit integers ia.close() # '''
--------------------------------------------------------------------------------
""" return _image.image_tofits(self, *args, **kwargs)
def toASCII(self, *args, **kwargs): """ toASCII(self, outfile, region = initialize_variant(""), mask = initialize_variant(""), sep = string(":"), format = string("\%e"), maskvalue = -999, overwrite = False, stretch = False) -> bool
Summary Convert the image to an ASCII file
Description
This function converts the image into an ascii file. The format is one image row per line (see fromascii).
The output mask is the combination (logical OR) of the default input \pixelmask\ (if any) and the OTF mask. Because the mask is not transferred to the ascii file, you must specify what data value to use if a pixel is masked. By default, the underlying data value in the image is used. But this could be anything (and often it's a NaN), so you could set, say, {\stfaf maskvalue=-10000} as a magic value.
Input Parameters: outfile ASCII file name. Default is input name + '.ascii'. region The region of interest. See help par.region for details. Default is whole image. mask Mask to use. See help par.mask. Default is none. sep Separator of data in ascii file. Default is space character. : format Format of data in ascii file \%e maskvalue Value to replace masked pixels by, -999 is no change. -999 overwrite Overwrite (unprompted) pre-existing output file? false stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false
Example:
''' # print ' ---- toASCII Ex 1 ----' ia.maketestimage() ok = ia.toASCII('myfile.ascii', overwrite=true) ia.close() ia.fromascii('image.im','myfile.ascii', shape=[113,76], overwrite=true) ia.toASCII('myfile2.ascii',overwrite=true) #!diff myfile.ascii myfile2.ascii # '''
--------------------------------------------------------------------------------
""" return _image.image_toASCII(self, *args, **kwargs)
def torecord(self): """ torecord(self) -> record
Summary Return a record containg the image associated with this tool
Description
You can convert an associated image to a record for manipulation or passing it to inputs of other function of other tools
Example:
''' # print ' ---- torecord Ex 1 ----' ia.maketestimage('image.large', overwrite=true) rec=ia.torecord() ia.close()
'''
--------------------------------------------------------------------------------
""" return _image.image_torecord(self)
def type(self): """ type(self) -> string
Summary Return the type of this tool
Description
This function returns the string `image'. It can be used in a script to make sure this variable is an Image ool.
--------------------------------------------------------------------------------
""" return _image.image_type(self)
def topixel(self, *args, **kwargs): """ topixel(self, value) -> record
Summary Convert from world to pixel coordinate
Description
This function converts from absolute world to pixel coordinate (0-rel). The world coordinate can be provided in many formats (numeric, string, quantum etc.) via the argument {\stfaf value}. These match the output formats of function toworld.
This function is just a wrapper for the Coordsys ool\ function topixel so see the documentation there for a description and more examples.
Input Parameters: value Absolute world coordinate, Numeric vector, vector of strings representing quantities, or record of format analogous to that produced by ia.toworld(). Default is reference value.
Example:
''' # print ' ---- topixel Ex 1 ----' ia.maketestimage(); w = ia.toworld([10,10], 'n') # Numeric vector ia.topixel(w) #{'ar_type': 'absolute', # 'numeric': array([10., 10.]), 'pw_type': 'pixel'} w = ia.toworld([10,10], 'm') # Record of measures ia.topixel(w) #{'ar_type': 'absolute', # 'numeric': array([10., 10.]), 'pw_type': 'pixel'} ia.close() # '''
Convert a pixel coordinate to world as floats and then back to pixel. Do the same with the world coordinate formatted as measures instead.
--------------------------------------------------------------------------------
""" return _image.image_topixel(self, *args, **kwargs)
def toworld(self, *args, **kwargs): """ toworld(self, value = initialize_variant(""), format = string("n")) -> record
Summary Convert from pixel to world coordinate
Description
This function converts between absolute pixel coordinate (0-rel) and world (physical coordinate).
This function is just a wrapper for the Coordsys ool\ function toworld so see the documentation there for a description of the arguments and more examples.
Input Parameters: value Absolute pixel coordinate. Numeric vector is allowed. Default is reference pixel. format What type of formatting? String from combination of 'n' (numeric), 'q' (quantity), 'm' (measure), 's' (string). n
Example:
''' # print ' ---- toworld Ex 1 ----' ia.maketestimage('hcn',overwrite=true) w = ia.toworld([10,10], 'n') print w #{'numeric': array([ 0.00174533, -0.0015708 ])} w = ia.toworld([10,10], 'nmq') print w #{'measure': {'direction': {'m0': {'unit': 'rad', # 'value': 0.0017453323593185704}, # 'm1': {'unit': 'rad', # 'value': -0.0015707969259645381}, # 'refer': 'J2000', # 'type': 'direction'}}, # 'numeric': array([ 0.00174533, -0.0015708 ]), # 'quantity': {'*1': {'unit': 'rad', 'value': 0.0017453323593185704}, # '*2': {'unit': 'rad', 'value': -0.0015707969259645381}}} ia.close() # '''
Convert to a vector of floats and then to a record holding a vector of floats, a vector of quantities and a subrecord of measures.
--------------------------------------------------------------------------------
""" return _image.image_toworld(self, *args, **kwargs)
def unlock(self): """ unlock(self) -> bool
Summary Release any lock on the image
Description
This function releases any lock set on the \imagefile\ (and also flushes any outstanding I/O to disk). It is not of general user interest. It can be useful in scripts when a file is being shared between more than one process. See also functions lock and haslock.
Example:
''' # print ' ---- unlock Ex 1 ----' ia.fromarray('xx', ia.makearray(0,[10,20]), overwrite=true) ia.unlock() ia.close() # '''
This releases the write lock on the \imagefile. Now some other process can gain immediate access to the \imagefile.
--------------------------------------------------------------------------------
""" return _image.image_unlock(self)
def newimagefromarray(self, *args, **kwargs): """ newimagefromarray(self, outfile = string(""), pixels = initialize_variant(""), csys = initialize_record(""), linear = False, overwrite = False, log = True) -> image
Summary Construct a casa image from an array
Description
This function converts an array of any size into a \casa\imagefile.
If {\stfaf outfile} is given, the image is written to the specified disk file. If {\stfaf outfile} is unset, the on-the-fly Image oolreturned by this function is associated with a temporary image. This temporary image may be in memory or on disk, depending on its size. When you destroy the on-the-fly Image ool\ (with the done function) this temporary image is deleted.
At present, no matter what type the {\stfaf pixels} array is, a real-valued image will be written (the input pixels will be converted to Float). In the future, Complex images will be supported.
The Coordinate System, provided as a record describing a Coordsys ool\ (via coordsys.torecord(), for instance) is optional. If you provide it, it must be dimensionally consistent with the pixels array you give (see also coordsys).
If you don't provide the Coordinate System (unset), a default Coordinate System is made for you. If {\stfaf linear=F} (the default) then it is a standard RA/DEC/Stokes/Spectral Coordinate System depending exactly upon the shape of the {\stfaf pixels} array (Stokes axis must be no longer than 4 pixels and you may find the spectral axis coming out before the Stokes axis if say, {\cf shape=[64,64,32,4]}). Extra dimensions are given linear coordinates. If {\stfaf linear=T} then you get a linear Coordinate System.
Input Parameters: outfile Output image file name. Default is unset. pixels A numeric array is required. csys Coordinate System. Default is unset. linear Make a linear Coordinate System if csys not given false overwrite Overwrite (unprompted) pre-existing output file? false log Write image creation messages to logger true
Example:
''' # print ' ---- newimagefromarray Ex 1 ----' im1=ia.newimagefromarray(outfile='test.data', pixels=ia.makearray(0, [64, 64, 4, 128]), overwrite=true) cs1 = im1.coordsys(axes=[0,1]) im1.done() im2 = ia.newimagefromarray(pixels=ia.makearray(1.0, [32, 64]), csys=cs1.torecord()) cs1.done() im2.done() # '''
The first example creates a zero-filled \imagefile\ named {\sff test.data} which is of shape [64,64,4,128]. If you examine the header with {\stff ia.summary()} you will see the default RA/DEC/Stokes/Frequency coordinate information. In the second example, a Coordinate System describing the first two axes of the image {\sff test.data} is created and used to create a 2D image temporary image.
--------------------------------------------------------------------------------
""" return _image.image_newimagefromarray(self, *args, **kwargs)
def newimagefromfits(self, *args, **kwargs): """ newimagefromfits(self, outfile = string(""), infile = string(""), whichrep = 0, whichhdu = 0, zeroblanks = False, overwrite = False) -> image
Summary Construct a casa image by conversion from a FITS image file
Description
This function is used to convert a FITS disk image file (Float, Double, Short, Long are supported) to an \casa\ \imagefile. If {\stfaf outfile} is given, the image is written to the specified disk file. If {\stfaf outfile} is unset, the on-the-fly Image oolreturned by this function is associated with a temporary image. This temporary image may be in memory or on disk, depending on its size. When you destroy the on-the-fly Image ool\ (with the done function) this temporary image is deleted.
This function reads from the FITS primary array (when the image is at the beginning of the FITS file; {\stfaf whichhdu=0}), or an image extension (when the image is elsewhere in the FITS file, {\stfaf whichhdu $\>$ 0}).
By default, any blanked pixels will be converted to a mask value which is false, and a pixel value that is NaN. If you set {\stfaf zeroblanks=T} then the pixel value will be zero rather than NaN. The mask will still be set to false. See the function replacemaskedpixels if you need to replace masked pixel values after you have created the image.
Input Parameters: outfile Output image file name. Default is unset. infile Input FITS disk file name. Required. whichrep If this FITS file contains multiple coordinate representations, which one should we read 0 whichhdu If this FITS file contains multiple images, which one should we read (0-based). 0 zeroblanks If there are blanked pixels, set them to zero instead of NaN false overwrite Overwrite (unprompted) pre-existing output file? false
Example:
''' # print ' ---- newimagefromfits Ex 1 ----' # Assume we can find test fits file using # CASAPATH environment variable pathname=os.environ.get('CASAPATH') pathname=pathname.split()[0] datapath=pathname+'/data/demo/Images/imagetestimage.fits' im1=ia.newimagefromfits('./myimage', datapath, overwrite=true) print im1.summary() print im1.miscinfo() print 'fields=', im1.miscinfo().keys() im1.done() # '''
The FITS image is converted to a \casa\ \imagefile\ and access is provided via the \imagetool\ called {\stf im1}. Any FITS header keywords which were not recognized or used are put in the miscellaneous information bucket accessible with the miscinfo function. In the example we list the names of the fields in this record.
--------------------------------------------------------------------------------
""" return _image.image_newimagefromfits(self, *args, **kwargs)
def newimagefromimage(self, *args, **kwargs): """ newimagefromimage(self, infile = string(""), outfile = string(""), region = initialize_variant(""), mask = initialize_variant(""), dropdeg = False, overwrite = False) -> image
Summary Construct an on-the-fly image tool from a region of a casa image file
Description
This function applies a region\ to a disk \imagefile, creates a new \imagefile\ containing the (sub)image, and associates a new \imagetoolwith it.
The input disk image file may be in native \casa, its (Float, Double, Short, Long are supported), or Miriad format. Look \htmlref{here}{IMAGES:FOREIGNIMAGES} for more information on foreign images.
If {\stfaf outfile} is given, the (sub)image is written to the specified disk file.
If {\stfaf outfile} is unset, the Image ool\ actually references the input image file. So if you deleted the input image disk file, it would render this ool\ useless. When you destroy this on-the-fly ool\ (with the done function) the reference connection is broken.
Sometimes it is useful to drop axes of length one (degenerate axes). Use the {\stfaf dropdeg} argument if you want to do this.
The output mask is the combination (logical OR) of the default input \pixelmask\ (if any) and the OTF mask. Any other input \pixelmaskswill not be copied. Use function maskhandler if you need to copy other masks too.
See also the subimage function.
Input Parameters: infile Input image file name. Required. outfile Output sub-image file name. Default is unset. region The region of interest. See help par.region for details. Default is the whole image. mask Mask to use. See help par.mask. Default is none. dropdeg Drop degenerate axes false overwrite Overwrite (unprompted) pre-existing output file? false
Example:
''' # print ' ---- newimagefromimage Ex 1 ----' ia.maketestimage('test1',overwrite=true) ia.maketestimage('test2',overwrite=true) print ia.name() #[...]test2 im1=ia.newimagefromimage('test1') print im1.name() #[...]test1 print im1.summary() im2=ia.newimagefromimage('test2') print im2.name() #[...]test2 print im1.name() #[...]test1 ia.close() im1.done() im2.done() # '''
--------------------------------------------------------------------------------
""" return _image.image_newimagefromimage(self, *args, **kwargs)
def newimagefromshape(self, *args, **kwargs): """ newimagefromshape(self, outfile = string(""), shape = initialize_vector(1, (int)0), csys = initialize_record(""), linear = False, overwrite = False, log = True, type = string("f")) -> image
Summary Construct an empty casa image from a shape
Description
This function creates a \casa\ \imagefile\ with the specified shape. All the pixel values in the image are set to 0. Both float valued and complex valued images are supported; the data type of the image is specified via the type parameter.
If {\stfaf outfile} is given, the image is written to the specified disk file. If {\stfaf outfile} is unset, the on-the-fly Image oolreturned by this function is associated with a temporary image. This temporary image may be in memory or on disk, depending on its size. When you destroy the on-the-fly Image ool\ (with the done function) this temporary image is deleted.
The Coordinate System, provided as a record describing a Coordsys ool\ (created via coordsys.torecord(), for instance), is optional. If you provide it, it must be dimensionally consistent with the pixels array you give (see also coordsys).
If you don't provide the Coordinate System, a default Coordinate System is made for you. If {\stfaf linear=F} (the default) then it is a standard RA/DEC/Stokes/Spectral Coordinate System depending exactly upon the shape (Stokes axis must be no longer than 4 pixels and you may find the spectral axis coming out before the Stokes axis if say, {\cf shape=[64,64,32,4]}). Extra dimensions are given linear coordinates. If {\stfaf linear=T} then you get a linear Coordinate System.
Input Parameters: outfile Name of output image file. Default is unset. shape Shape of image. Required. 0 csys Record describing Coordinate System. Default is unset. linear Make a linear Coordinate System if csys not given? false overwrite Overwrite (unprompted) pre-existing output file? false log Write image creation messages to logger true type Type of image. 'f' means Float, 'c' means complex. f
Example:
''' # print ' ---- newimagefromshape Ex 1 ----' im1=ia.newimagefromshape('test2.data', [64,64,128], overwrite=true) cs1 = im1.coordsys(axes=[0,2]) im1.done() im2 = ia.newimagefromshape(shape=[10, 20], csys=cs1.torecord()) cs1.done() im2.done() # '''
The first example creates a zero-filled \imagefile\ named {\sff test.data} of shape [64,64,128]. If you examine the header with {\stff ia.summary()} you will see the RA/DEC/Spectral coordinate information. In the second example, a Coordinate System describing the first and third axes of the image {\sff test2.data} is created and used to create a 2D temporary image.
--------------------------------------------------------------------------------
""" return _image.image_newimagefromshape(self, *args, **kwargs)
def pbcor(self, *args, **kwargs): """ pbcor(self, pbimage = initialize_variant(""), outfile = string(""), overwrite = False, box = string(""), region = initialize_variant(""), chans = string(""), stokes = string(""), mask = string(""), mode = string("divide"), cutoff = -1.0, stretch = False) -> image
Summary
Construct a primary beam corrected image from an image and a primary beam
Description
Correct an image for primary beam attenuation using an image of the primary beam pattern. The primary beam pattern can be provided as an image, in which case 1. it must have the same shape as the input image and its coordinate system must be the same, or 2. it must be a 2-D image in which case its coordinate system must consist of a (2-D) direction coordinate which is the same as the direction coordinate in the input image and its direction plane must be the same shape as that of the input image. Alternatively, pbimage can be an array of pixel values in which case the same dimensionality and shape constraints apply. An image tool referencing the corrected image is returned. The corrected image will also be written to disk if outfile is not empty (and overwrite=True if outfile already exists). One can choose between dividing the image by the primary beam pattern (mode='divide') or multiplying the image by the primary beam pattern (mode='multiply'). One can also choose to specify a cutoff limit for the primary beam pattern. For mode='divide', for all pixels below this cutoff in the primary beam pattern, the output image will be masked. In the case of mode='multiply', all pixels in the output will be masked corresponding to pixels with values greater than the cutoff in the primary beam pattern. A negative value for cutoff means that no cutoff will be applied, which is the default.
Input Parameters: pbimage Name of the primary beam image which must exist or array of values for the pb response. Default '' outfile Output image name. If empty, no image is written. Default '' overwrite Overwrite the output if it exists? Default False false box One or more boxes to use for fit region(s). Default is to use the entire directional plane. region The region to correct. Default is entire image. If both box and region are specified, box is used and region is not. chans The frequency planes to correct. See 'help par.chans' for examples. Default is all frequencies. stokes The correlations to correct. Default is all. mask Mask to use. See help par.mask. Default is none. mode Divide or multiply the image by the primary beam image. Minimal match supported. Default 'divide' divide cutoff PB cutoff. If mode is 'd', all values less than this will be masked. If 'm', all values greater will be masked. Less than 0, no cutoff. Default no cutoff -1.0 stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false
Example:
ia.open('attenuated.im') ia.pbcor(pbimage='mypb.im', outname='pbcorred.im', mode='divide', cutoff=0.1)
--------------------------------------------------------------------------------
""" return _image.image_pbcor(self, *args, **kwargs)
def pv(self, *args, **kwargs): """ pv(self, outfile = string(""), start = initialize_variant(""), end = initialize_variant(""), center = initialize_variant(""), length = initialize_variant(""), pa = initialize_variant(""), width = initialize_variant("1"), unit = string("arcsec"), overwrite = False, region = initialize_variant(""), chans = string(""), stokes = string(""), mask = string(""), stretch = False, wantreturn = True) -> image
Summary
Construct a position-velocity image between two points in the direction plane.
Description
Create a position-velocity image by specifying either two points between which a slice is taken in the direction coordinate or a center, position angle, and length describing the slice. The spectral extent of the resulting image will be that provided by the region specification or the entire spectral range of the input image if no region is specified. One may not specify a region in direction space; that is accomplished by specifying the start and end points or the center, length, and position angle of the slice. The parameters start and end may be specified as two element arrays of numerical values, in which case these values will be interpreted as pixel locations in the input image. Alternatively, they may be expressed as arrays of two strings each representing the direction. These strings can either represent quantities (eg ['40.5deg', '0.5rad') or be sexigesimal format (eg ['14h20m20.5s','-30d45m25.4s'], ['14:20:20.5s','-30.45.25.4']). In addition, they may be expressed as a single string containing the longitude and latitude values and optionally a reference frame value, eg 'J2000 14:20:20.5s -30.45.25.4'. The center parameter is specified in the same way. The length parameter may be specified as a single numerical value, in which case it is interpreted as the length in pixels, or a valid quantity, in which case it must have units conformant with the direction axes units. The pa (position angle) parameter must be specified as a valid quantity with angular units. The position angle is interpreted in the usual astronomical sense; ie measured from north through east. Either start/end or center/pa/length must be specified; if a parameter from one of these sets is specified, a parameter from the other set may not be specified. In either case, the end points of the segment must fail within the input image, and they both must be at least 2 pixels from the edge of the input image to facilite rotation (see below).
One may specify a width, which is the number of pixels centered along and perpendicular to the direction slice that are used for averaging along the slice. The width may be specified as an integer, in which case it must be positive and odd. Alternatively, it may be specified as a valid quantity string (eg, '4arcsec') or quantity record (eg qa.quantity('4arcsec'). In this case, units must be conformant to the direction axes units (usually angular units) and the specified quantity will be rounded up, if necessary, to the next highest equivalent odd integer number of pixels. The default value of 1 represents no averaging. A value of 3 means average one pixel on each side of the slice and the pixel on the slice. Note that this width is applied to pixels in the image after it has been rotated (see below for a description of the algorithm used). The end points of the specified segment must fail within the input image, and they both must be at least 2 pixels from the edge of the input image to facilite rotation (see below).
One may specify the unit for the angular offset axis.
A true value for the wantreturn parameter indicates that an image analysis tool attached to the created image should be returned. Nothing is returned if wantreturn is false, but then outfile should be specified (unless perhaps you are debugging).
Internally, the image is first rotated, padding first if necessary to include relevant pixels that would otherwise be excluded by the rotation operation, so that the slice is horizontal, with the starting pixel left of the ending pixel. Then, the pixels within the specified width of the slice are averaged and the resulting image is written and/or returned. The output image has a linear coordinate in place of the direction coordinate of the input image, and the corresponding axis represents angular offset with the center pixel having a value of 0.
The equivalent coordinate system, with a (usually) rotated direction coordinate (eg, RA and Dec) is written to the output image as a table record. It can be retrieved using the table tool as shown in the example below.
Input Parameters: outfile Output image name. If empty, no image is written. Default '' start The starting point in the direction plane (array of two values). If specified, end must also be specified and none of center, pa, nor length may be specified. end The ending point in the direction plane (array of two values). If specified, start must also be specified and none of center, pa, nor length may be specified. center The center point in the direction plane (array of two values). If specified, length and pa must also be specified and neither of start nor end may be specified. length The length of the segment in the direction plane. If specified, center and pa must also be specified and neither of start nor end may be specified. pa The position angle of the segment in the direction plane, measured from north through east. If specified, center and length must also be specified and neither of start nor end may be specified. width Width in pixels for averaging pixels perpendicular to the slice. Must be an odd integer \>= 1 (1 means only use the pixels along the slice), or a quantity which will be rounded up if necessary so it corresponds to the next highest odd number of pixels. 1 unit Unit for the offset axis in the resulting image. Must be a unit of angular measure. arcsec overwrite Overwrite the output if it exists? false region Region selection. See help par.region for details. Default is entire image. No selection is permitted in the direction plane. chans Channels to use. See 'help par.chans' for examples. Channels must be contiguous. Default is to use all channels. stokes Stokes planes to use. Planes must be contiguous. Default is to use all stokes. mask Mask to use. See help par.mask. Default is none. stretch Stretch the mask if necessary and possible? See help par.stretch. Default False false wantreturn Return an image analysis tool attached to the created image? true
Example:
ia.open('my_spectral_cube.im') # create a pv image with the position axis running from ra, dec pixel positions of [45, 50] to [100, 120] # in the input image mypv = ia.pv(outfile='pv.im', start=[45,50], end=[100,120], wantreturn=true) ia.done() # analyze the pv image, such as get statistics pvstats = mypv.statistics() # when done, close the tool to release system resources mypv.done()
# get the alternate coordinate system information tb.open('pv.im') alternate_csys_record = tb.getkeyword('misc')['secondary_coordinates'] tb.done()
--------------------------------------------------------------------------------
""" return _image.image_pv(self, *args, **kwargs)
def makearray(self, *args, **kwargs): """ makearray(self, v = 0.0, shape = initialize_vector(1, (int)0)) -> variant
Summary Construct an initialized multi-dimensional array.
Description
This function takes two arguments. The first argument is the initial value for the new array. The second is a vector giving the lengths of the dimensions of the array.
Input Parameters: v Value with which to initial array elements 0.0 shape Vector containing array dimensions. 0
Example:
A three dimensional array that is initialized to all zeros. Each of the three dimensions of the cube has a length of four.
''' # print ' ---- makearray Ex 1 ----' cube = ia.makearray(0,[4,4,4]) # '''
--------------------------------------------------------------------------------
""" return _image.image_makearray(self, *args, **kwargs)
def isconform(self, *args, **kwargs): """ isconform(self, other) -> bool
Summary Returns true of the shape, coordinate system, and axes order of the specified image matches this image.
Description
Returns True if the shape, coordinate system, and axes order of the specified image matches the current image.
Input Parameters: other name of image to test
Example:
ia.isconform('my_mystery.image')
--------------------------------------------------------------------------------
""" return _image.image_isconform(self, *args, **kwargs)
image_swigregister = _image.image_swigregister image_swigregister(image)
# This file is compatible with both classic and new-style classes.
|