Coverage for /wheeldirectory/casa-6.7.0-12-py3.10.el8/lib/py/lib/python3.10/site-packages/casatools/__casac__/image.py: 51%
298 statements
« prev ^ index » next coverage.py v7.6.4, created at 2024-10-31 17:39 +0000
« prev ^ index » next coverage.py v7.6.4, created at 2024-10-31 17:39 +0000
1# This file was automatically generated by SWIG (http://www.swig.org).
2# Version 3.0.12
3#
4# Do not make changes to this file unless you know what you are doing--modify
5# the SWIG interface file instead.
7from sys import version_info as _swig_python_version_info
8if _swig_python_version_info >= (2, 7, 0):
9 def swig_import_helper():
10 import importlib
11 pkg = __name__.rpartition('.')[0]
12 mname = '.'.join((pkg, '_image')).lstrip('.')
13 try:
14 return importlib.import_module(mname)
15 except ImportError:
16 return importlib.import_module('_image')
17 _image = swig_import_helper()
18 del swig_import_helper
19elif _swig_python_version_info >= (2, 6, 0):
20 def swig_import_helper():
21 from os.path import dirname
22 import imp
23 fp = None
24 try:
25 fp, pathname, description = imp.find_module('_image', [dirname(__file__)])
26 except ImportError:
27 import _image
28 return _image
29 try:
30 _mod = imp.load_module('_image', fp, pathname, description)
31 finally:
32 if fp is not None:
33 fp.close()
34 return _mod
35 _image = swig_import_helper()
36 del swig_import_helper
37else:
38 import _image
39del _swig_python_version_info
41try:
42 _swig_property = property
43except NameError:
44 pass # Python < 2.2 doesn't have 'property'.
46try:
47 import builtins as __builtin__
48except ImportError:
49 import __builtin__
51def _swig_setattr_nondynamic(self, class_type, name, value, static=1):
52 if (name == "thisown"):
53 return self.this.own(value)
54 if (name == "this"):
55 if type(value).__name__ == 'SwigPyObject':
56 self.__dict__[name] = value
57 return
58 method = class_type.__swig_setmethods__.get(name, None)
59 if method:
60 return method(self, value)
61 if (not static):
62 if _newclass:
63 object.__setattr__(self, name, value)
64 else:
65 self.__dict__[name] = value
66 else:
67 raise AttributeError("You cannot add attributes to %s" % self)
70def _swig_setattr(self, class_type, name, value):
71 return _swig_setattr_nondynamic(self, class_type, name, value, 0)
74def _swig_getattr(self, class_type, name):
75 if (name == "thisown"):
76 return self.this.own()
77 method = class_type.__swig_getmethods__.get(name, None)
78 if method:
79 return method(self)
80 raise AttributeError("'%s' object has no attribute '%s'" % (class_type.__name__, name))
83def _swig_repr(self):
84 try:
85 strthis = "proxy of " + self.this.__repr__()
86 except __builtin__.Exception:
87 strthis = ""
88 return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
90try:
91 _object = object
92 _newclass = 1
93except __builtin__.Exception:
94 class _object:
95 pass
96 _newclass = 0
98class image(_object):
99 """Proxy of C++ casac::image class."""
101 __swig_setmethods__ = {}
102 __setattr__ = lambda self, name, value: _swig_setattr(self, image, name, value)
103 __swig_getmethods__ = {}
104 __getattr__ = lambda self, name: _swig_getattr(self, image, name)
105 __repr__ = _swig_repr
107 def __init__(self):
108 """__init__(self) -> image"""
109 this = _image.new_image()
110 try:
111 self.this.append(this)
112 except __builtin__.Exception:
113 self.this = this
115 def newimage(self, *args, **kwargs):
116 """
117 newimage(self, _infile) -> image
121 Summary:
122 Construct a new image analysis tool using the specified image. (Also known as newimagefromfile.)
124 Description:
127 This method is identical to ia.newimagefromfile(). The description of how it works is in the help for that method.
129 Input Parameters:
130 infile Input image file name
132 --------------------------------------------------------------------------------
134 """
135 return _image.image_newimage(self, *args, **kwargs)
138 def newimagefromfile(self, *args, **kwargs):
139 """
140 newimagefromfile(self, _infile) -> image
144 Summary:
145 Construct a new image analysis tool using the specified image. (Also known as newimage.)
147 Description:
150 This method returns an image analysis tool associated with the specified image.
151 Constructing a image analysis tool in addition to the default ia tool allows the
152 user to operate on multiple images simultaneously. All ia.newimagefrom*()
153 methods share this behavior.
155 The parameter infile may refer to a CASA image, a Miriad image, or a FITS image.
156 FITS images of types Float are supported.
158 When finished with the newly created tool, the user should close it to free
159 up system resources (eg memory).
161 ia.newimage() is an alias for this method.
163 Input Parameters:
164 infile Input image file name
166 Example:
168 # This is one way to copy a FITS image into an already extant CASA image
169 # of the same shape (ia.subimage() is more effecient, but this example is
170 # meant to demonstrate ia.newimagefromfile()
172 # note that the ia tool is not attached to an image after the first command,
173 # the fitsimage tool is
174 fitsimage = ia.newimagefromfile('myimage.fits')
175 # now attach the target CASA image to the ia tool
176 ia.open('myimage.im')
177 # copy pixel values
178 ia.putchunk(fitsimage.getchunk())
179 # copy the coordinate system
180 ia.setcoordsys(fitsimage.coordsys().torecord())
181 # copy other miscellaneous things
182 ia.setbrightnessunit(fitsimage.getbrightnessunit())
183 ia.setmiscinfo(fitsimage.miscinfo())
184 # be sure to call done() on both tools to free up memory
185 ia.done()
186 fitsimage.done()
188 --------------------------------------------------------------------------------
190 """
191 return _image.image_newimagefromfile(self, *args, **kwargs)
194 def imagecalc(self, *args, **kwargs):
195 """
196 imagecalc(self, _outfile, _pixels, _overwrite, _imagemd, _prec) -> image
200 Summary:
201 Perform mathematical calculations on an image or images.
203 Description:
207 This method is used to evaluate a mathematical expression involving
208 existing images. It fully supports float, double, and complex float, and complex
209 double valued images.
210 The syntax of the expression supplied via the pixels
211 parameter (in what is called the Lattice Expression Language, or LEL) is
212 explained in detail in htmladdnormallink{note
213 223}{http://aips2.nrao.edu/docs/notes/223/223.html}. This is a rich
214 mathematical language with allows all manner of mathematical operations
215 to be applied to images.
217 Any image files embedded in the expression may be native casa or
218 fits (but not yet Miriad) images.
220 If successful, this method always returns an image analysis tool that
221 references the image resulting from the calculation. This returned tool
222 should always be captured and closed as soon as the user is done with it
223 to free up system resources (eg, memory). The image analysis tool on which
224 the method is called (eg the ia tool when one runs ia.imagecalc()) remains
225 unaltered, eg it still refers to the same image it did prior to the imagecalc()
226 call.
228 Values of the returned tool are evaluated 'on demand'. That is, only when a method
229 is run on the returned tool are the necessary values computed. And in fact, the
230 values have to be reevaluated for each operation (method call). This means that
231 there is a small performance hit for using the returned tool rather than the image
232 written to disk and that none of the images which were used in the expression
233 should be deleted while the returned tool is in use because they must be accessed
234 for calculating the expression each time an operation of the returned tool is
235 performed. These limitations do not apply to the ouput image if one is specified
236 with the outfile parameter; it is a genuine CASA image with
237 numerical values. If outfile is blank, no ouput image is written (although
238 the resulting image can still be accessed via the returned image analysis tool
239 as described below).
241 Normally you should just write the image, close the returned
242 tool, and open the results image with the default ia tool and operate on it. If
243 you are interested in conserving disk space, you don't need to keep the result of
244 the calculation around for very long, and/or you are only going to do a small
245 number of operations on the result image, should you set outfile=''.
247 Note that when multiple image are used in the expression, there is
248 no garauntee about which of those images will be used to create the metadata
249 of the output image, unless imagemd is specified. If imagemd is specified, the following
250 rules of metadata copying will be followed:
252 1. The pixel data type of the image specified by imagemd and the output image must
253 be the same.
254 2. The metadata copied include the coordinate system (and so of course the dimensionality of
255 the output image must correspond to the coordinate system to be copied), the image_info record
256 (which contains things like the beam(s)), the misc_info record (should one exist in the image
257 specified by imagemd), and the units.
258 3. If the output image is a spectral image, the brightness units are set to the empty string.
259 4. If the ouptut image is a polarization angle image, the brightness unit is set to 'deg' and
260 the stokes coordinate is set to have a single plane of type of Pangle.
262 The precision (float or double) of the output image pixels is determined by
263 the value specified by the prec parameter. The domain (real or complex) of
264 the output pixel values is determined from the expression.
268 Input Parameters:
269 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.
270 pixels LEL expression. Must be specified. For example 'myimage1.im + myimage2.im'.
271 overwrite Overwrite (unprompted) pre-existing output file?
272 imagemd The image from which metadata should be copied. Default means no gaurantee from which image is used.
273 prec Precision for the output image pixels. 'float' or 'double' (minimum match supported)
275 Example:
278 # Suppose aF and bF are images with single precision and we want
279 # to determine the result of the following expression:
280 # aF + min(float($pi$, mean(bF))
281 #
282 # In this case, the images aF and bF do not need to have the same shapes and
283 # coordinates, because only the mean(bF) results in the mean of all pixel
284 # values in bF. If aF has single precision pixel values, the resulting image
285 # will as well. This expression first computes the scalar value of the minimum
286 # of $pi$ and the mean of the pixel values of bF. That scalar is then
287 # added to the value of each pixel in aF. In the code below, the
288 # result is written to image cF which can be accessed immediately
289 # via the returned image analysis tool captured in the variable myim.
290 # If the expression is masked, that mask will be copied to the new image.
292 # create images of different sizes to operate on
293 ia.fromshape('aF',[10,10],overwrite=true)
294 ia.fromshape('bF',[10,20,30],overwrite=true)
295 # close the ia tool to free up resources
296 ia.done()
297 # at each pixel in bF, take the minimum of that pixel value and pi and add
298 # the resulting value to the corresponding pixel in af
299 # note that only the subset of pixels in bF that correspond to those in aF
300 # are used; the resulting image has the same size as the smaller image, aF,
301 # used in the input
302 myim = ia.imagecalc(outfile='cF', pixels='aF + min(float(pi()), mean(bF))',
303 overwrite=true)
304 # confirm the resulting image has the same size as aF, should be [10, 10]
305 myim.shape()
306 # close the myim tool to free up system resources
307 myim.done()
312 # The following example shows the use of the two min() LEL functions. One takes a
313 # single argument and will return a scalar representing the minimum pixel value
314 # of that entire image. The other takes two arguments (either an image and a
315 # scalar or two images of conforming shapes) and returns an image for which
316 # the minimum has been calculated on a pixel by pixel basis for the input
317 # image(s).
319 # create an image to operate on
320 ia.fromshape('aF',[10,10],overwrite=true)
321 # give it interesting values
322 ia.addnoise()
323 # free up system resources
324 ia.done()
325 # do the calculation and write results to image cF
326 myim=ia.imagecalc('cF', 'min(aF, (min(aF)+max(aF))/2)', overwrite=true)
327 # do whatever stuff you want with myim and the close it to free
328 # up system resources
329 myim.done()
333 # Here's an example of a more complicated function. Currently
334 # ia.fromshape() only creates real-valued images so the real()
335 # function is not particularly exciting in this case but illustrates
336 # possibilities. Trigonometric functions such as sin() assume the
337 # pixel values are in radians.
338 ia.fromshape('aD',[10,10],overwrite=true)
339 ia.addnoise()
340 ia.fromshape('aF',[10,10],overwrite=true)
341 ia.addnoise()
342 ia.fromshape('bF',[10,10],overwrite=true)
343 ia.addnoise()
344 ia.fromshape('aC',[10,10],overwrite=true)
345 ia.addnoise()
346 ia.done()
347 myim = ia.imagecalc('eF', 'sin(aD)+(aF*2)+min(bF)+real(aC)', overwrite=true)
348 myim.done()
351 --------------------------------------------------------------------------------
353 """
354 return _image.image_imagecalc(self, *args, **kwargs)
357 def collapse(self, *args, **kwargs):
358 """
359 collapse(self, _function, _axes, _outfile, _region, _box, _chans, _stokes, _mask, _overwrite, _stretch) -> image
363 Summary:
364 Collapse an image along a specified axis, computing a specified aggregate function of pixels along that axis.
366 Description:
370 This method collapses an image along a specified axis or set of axes of length N pixels to a single pixel on each
371 specified axis. Both float valued and complex valued images are supported. It computes a user-specified aggregate
372 function for pixel values along the specified axes, and places those values in the single remaining plane of
373 those axes in the output image. The method returns an image analysis tool containing the newly-created collapsed
374 image. Valid choices of aggregate functions are: 'flux' (see below for constraitns), 'madm' (median absolute
375 deviation from the median), 'max', 'mean', 'median', 'min', 'npts', 'rms', 'stddev', 'sum', 'variance' and 'xmadm'
376 (median absolute deviation from the median multipied by x, where x is the reciprocal of Phi^-1(3/4), where Phi^-1
377 is the reciprocal of the quantile function. Numerically, x = 1.482602218505602. See, eg,
378 https://en.wikipedia.org/wiki/Median_absolute_deviation#Relation_to_standard_deviation). Minimal unique matching is
379 supported for the function parameter (e.g. function = 'r' will compute the rms of the pixel values, 'med' will
380 compute the median, etc.).
382 If one specifies function='flux', the following constraints must be true:
384 1. The image must have a direction coordinate,
385 2. The image must have at least one beam,
386 3. The specified axes must be exactly the direction coordinate axes,
387 4. Only one of the non-directional axes may be non-degenerate,
388 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)
389 and y is an optional SI prefix.
391 Axes may be specified as a single integer or an array of integers indicating the zero-based
392 axes along which to collapse the image. Axes may also be specified as a single or array of strings which
393 minimally and uniquely match (ignoring case) world axis names in the image (e.g. 'dec' for
394 collapsing along the declination axis or ['ri', 'd'] for collapsing along both the right ascension and
395 declination axes).
397 If outfile is not specified (or contains only whitespace characters), no image is written but the
398 collapsed image is still accessible via the image analysis tool this method always returns (which
399 references the collapsed image). If the returned object is not wanted, it should still be
400 captured and destroyed via its done() method. If this is not done, there is no guarantee
401 as to when the Python garbage collector will delete it. If the returned object is wanted, it
402 should still be deleted as soon as possible for the same reasons, e.g.
404 collapsed_image = ia.collapse(...)
405 begin{verbatim}
406 # do things (or not) with the collapsed_image and when finished working with the object, do
407 end{verbatim}
408 collapsed_image.done()
410 The reference pixel of the collapsed axis is set to 0 and its reference value is set to the mean
411 of the the first and last values of that axis in the specified region of the input image. The
412 reference value is the world coordinate value of the reference pixel. For instance, if an axis
413 to be collapsed were to be the frequency axis, in the collapsed image, the reference value would
414 be the mean value of the frequency range spanned, and would be stored in pixel 0.
416 If the input image has per plane beams, the beam at the origin of the subimage determined by
417 the selected region is arbitrarily made the global beam of the output image. In general, the user
418 should understand the pitfalls of collapsing images with multiple beams (i.e. that employing an
419 aggregate function on pixels with varying beam sizes more often than not leads to ill-defined
420 results). Convolution to a common beam is not performed automatically as part of the preprocessing
421 before the actual rebinning occurs. In such cases, therefore, the user should probably first
422 convolve the input image with a common restoring beam so that each plane has the same resolution,
423 and/or use imsmooth to smooth the data to have the same beam.
427 Input Parameters:
428 function Aggregate function to apply. This can be set one of flux, madm, max, mean, median, min, npts, rms, stddev, sum, variance, xmadm. Must be specified.
429 axes Zero-based axis number (specified as a list or integer) along which to collapse the specified image. Default value is 0.
430 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.
431 region Region selection. Default is to use the full image.
432 box Rectangular region to select in direction plane. Default is to use the entire direction plane.
433 chans Channels to use. Channels must be contiguous. Default is to use all channels.
434 stokes Stokes planes to use. Planes specified must be contiguous. Default is to use all Stokes planes.
435 mask Mask to use. Default setting is none.
436 overwrite Overwrite (unprompted) pre-existing output file? Ignored if 'outfile' is left blank.
437 stretch Stretch the mask if necessary and possible? Default value is False.
439 Example:
442 # myimage.im is a 512x512x128x4 (ra,dec,freq,stokes) image
443 ia.open('myimage.im')
444 # collapse a subimage of it along its spectral axis avoiding the 8 edge
445 # channels at each end of the band, computing the mean value of the pixels
446 # resulting image is 256x256x1x4 in size.
447 collapsed = ia.collapse(outfile='collapse_spec_mean.im', function='mean', axes=2, box='127,127,383,383', chans='8~119')
448 # manipulate collapsed
449 collapsed.done()
453 --------------------------------------------------------------------------------
455 """
456 return _image.image_collapse(self, *args, **kwargs)
459 def decimate(self, *args, **kwargs):
460 """
461 decimate(self, _outfile, _axis, _factor, _method, _region, _mask, _overwrite, _stretch) -> image
465 Summary:
466 Remove planes from an image.
468 Description:
471 This application removes planes along the specified axis of an image. It supports both float valued and complex
472 valued images. The factor parameter represents the factor by which to reduce the number
473 of planes.
475 The method parameter represents how to calculate the pixel values of the output image. A
476 value of method='copy' means that every factorth plane of the selected region in the input
477 image will be directly copied to the corresponding plane in the output image. So, if one
478 wanted to copy every third spectral plane in the input image to the output image, one would
479 specify factor=3 and method='copy'. If the selected region along the specified axis had 11
480 planes, then there would be 4 output planes which would map to planes 0, 3, 6, and 9 of
481 the specified region of input image. A value of method='mean' indicates that each of
482 factor number of planes in the range starting at each factorth plane should be averaged to
483 produce the corresponding output plane. So, if one specified factor=3 and method='mean' along
484 an axis of the selected region of the input image which had 11 pixels, the corresponding axis
485 in the output image would have three pixels and the pixel values for each of those output
486 planes would corresponding to averaging along that axis planes 0-2, 3-5, and 6-8 of the
487 selected region of the input image. Note that the remaining planes, 9 and 10, in the selected
488 region of the input image would be ignored because the last interval must have exactly
489 factor number of planes in order to be included in the output image.
491 The coordinate system of the output image takes into account the decimation; that is, along the
492 decimated axis, the increment of the output image is factor times that of the input image, and
493 the reference pixel of the output image is located at pixel 1/factor times the reference pixel
494 in the input image.
496 This method returns an image analysis tool which references the output image. If this tool
497 is not desired, one should capture it anyway and then close() it immediately to free up
498 resources.
500 Images with multiple beams are not supported; please convolve a multi-beam image to a single
501 resolution before running this application.
504 Input Parameters:
505 outfile Output image file name. If empty, a persistent image is not created.
506 axis Axis along which to remove planes.
507 factor Reduce number of planes by this factor.
508 method Method to use for calculating pixel values of output. Supported values are 'copy' or 'mean'.
509 region Region selection. Default is to use the full image.
510 mask Mask to use. Default setting is none.
511 overwrite Overwrite (unprompted) pre-existing output file? Ignored if 'outfile' is left blank.
512 stretch Stretch the mask if necessary and possible? Default value is False.
514 Example:
516 # Copy verbatim every 5th plane of axis 2 of the input image
517 ia.open('myim.im')
518 decimated = ia.decimate('dec1.im', axis=2, factor=5, method='copy')
519 # do stuff with decimated and then close it
520 decimated.close()
522 # Decimate by averaging every 7 planes of the input image along axis 2
523 decimated = ia.decimate('dec2.im', axis=2, factor=7, method='mean')
524 # do stuff with decimated and then close it
525 decimated.close()
526 # close input ia tool
527 ia.close()
529 --------------------------------------------------------------------------------
531 """
532 return _image.image_decimate(self, *args, **kwargs)
535 def dohistory(self, *args, **kwargs):
536 """
537 dohistory(self, _enable) -> bool
541 Summary:
542 Enable/disable tool methods from writing to history.
544 Description:
547 This allows control over if tool methods record history of what parameters they were called
548 with to the input and/or output image. By default, tool methods will write to the image
549 history. By explicitly disabling history writing, tool methods will not write to the history.
550 When created, an ia tool will have history writing enabled. Note that the setting is specific
551 to the individual tool, and that methods such as open(), close(), done(), fromshape(), etc do
552 not implicitly change the internal state of whether or not history writing by methods is
553 enabled. One can explicitly enable/disable history writing even if the tool is not yet attached
554 to an image. In the case where a method returns a new ia tool, the method will not write history
555 to the output image, but the returned tool will have history writing enabled, so that running
556 methods on the returned tool will cause history to be written to the image attached to that
557 tool, or any new image created by running methods on that tool, unless dohistory(False) is
558 explicitly run on that tool prior to running other methods.
560 IMPORTANT NOTE: This setting will not affect the behavior of ia.sethistory(); this tool
561 method will always write to the history, no matter if ia.dohistory(False) was run prior.
564 Input Parameters:
565 enable Enable history writing of tool methods? True means yes, False means no.
567 --------------------------------------------------------------------------------
569 """
570 return _image.image_dohistory(self, *args, **kwargs)
573 def imageconcat(self, *args, **kwargs):
574 """
575 imageconcat(self, _outfile, _infiles, _axis, _relax, _tempclose, _overwrite, _reorder, _mode) -> image
579 Summary:
580 Construct a casa image by concatenating images
582 Description:
586 This application is used to concatenate two or more input CASA
587 images into one output image. For example, if you have two image cubes
588 which are contiguous along one axis (say a spectral axis) and you would
589 like to glue them together along this axis, then this function is the
590 appropriate thing to use.
592 The axis parameter is used to specify which zero-based axis the images
593 should be concatenated along. A negative value indicates that the
594 spectral axis should be used. If a negative value is given but there is no
595 spectral axis, an exception will be thrown. The zero-based order of the
596 axes of an image can be determined from ia.coordsys().names().
598 If successful, this method will return an image analysis tool referencing
599 the concatenated image. Even if it is not wanted, the returned tool should
600 be captured and closed as soon as the user is finished with it to free up
601 system resources (eg memory).
603 If outfile is given, the image is written to the specified
604 disk file. If outfile is unset, the on-the-fly image tool
605 created by the method actually references all of the input files.
606 So if you deleted any of the input image disk files, it would render
607 this tool useless. Note that a blank outfile name may only be given
608 in the case where mode='p' (see below). When you destroy this tool
609 done() method, the reference connections are broken.
611 The input and output images must be of the same dimensionality. Therefore,
612 if you wish to concatenate 2-D images into a 3-D image, the 2-D images
613 must have a third axis (of length unity) so that the output image
614 coordinates are known along the concatenation axis.
616 The input images are concatenated in the order in which they are listed unless
617 the reorder parameter is set to True. If True, the images are reordered if necessary
618 so that the world coordinate values along the selected axis monotonically increase
619 or decrease. The direction of the increment is determined by the first listed image.
620 If reorder=True, the world coordinate ranges of the images along the selected axis
621 are not permitted to overlap, and the signs of the increments for this axis in all
622 images must be the same. If reorder=False, the coordinate system of the first listed
623 image is used as the coordinate system for the output image. If reorder=True, the
624 coordinate system of the first image in the list of the reordered images is used
625 as the coordinate system of the output image. Setting reorder=True can be especially
626 useful if the infiles are specified using a wildcard character(s).
628 If relax=False, the input images are checked to see that they are
629 contiguous along the concatenation axis and an exception is thrown if
630 they are not. In addition, the coordinate descriptors (e.g. reference
631 pixel, reference value etc) for the non-concatenation axes must be the
632 same or an error will result.
634 The input disk image files may be in native (CASA or FITS) formats.
636 The contiguous criterion and coordinate descriptor equality criteria can
637 be relaxed by setting relax=True whereupon only warnings will be
638 issued. Dimension and shape must still be the same though. When the
639 concatenation axis is not contiguous (but still monotonically increasing
640 or decreasing) and relax=True, a tabular coordinate will be used
641 to correctly describe the axis. But be aware that it means adjacent
642 pixels are not regularly spaced. However, methods like toworld() and
643 topixel() will correctly interconvert world and pixel coordinates.
645 In giving the input image names, the infiles argument can be a
646 single string if you wild card it with standard shell symbols. For
647 example, infiles='cena_???.*', where the '?' represents one
648 character and '*' any number of characters.
650 Otherwise, you must input a vector of strings such as
651 infiles='cena1 cena2 cena3'. An input such as infiles='files1,file2'
652 will be interpreted as one string naming one file and an exception will
653 be thrown. The reason for this is that although the latter could be
654 parsed to extract two file names by recognizing comma delimiters, it
655 is not possible because an expression such as infiles='cena.{a,b}'
656 (meaning files of name 'cena.a' and 'cena.b') would confuse such
657 parsing (you would get two files of name cena.{a} and {sff b}.
659 You can look at the coordinate system of the output image using the
660 ia.summary() method to ensure it's correct.
662 The parameter tempclose is, by default, True. This means that
663 all internal reference copies of the input images are kept closed until
664 they are needed. Then they are opened temporarily and then closed again.
665 This enables you to effectively concatenate as many images as you like
666 without encountering any operating system open file number limits.
667 However, it comes at some performance loss, because opening and closing
668 all those files takes time. If you are concatenating a smallish number
669 of files, you might use tempclose=False. This will leave all internal
670 reference copies permanently open, but performance, if you don't hit the
671 file limit, will be better.
673 The mode parameter controls the format of the output image. If mode='p',
674 then a 'paged' (normal persistent CASA format) image in which all the
675 pixel values and metadata are copied to a single image is created. All
676 the other modes will create a 'virtual concat' image. In this format,
677 a directory, named outfile, is created to store metadata about each image.
678 The metadata are placed in a file in this directory named imageconcat.json,
679 which is a plain text file in JSON format. In the json file are pointers
680 to the actual disk images that make up the virtual concat image. In the
681 case of mode='c' (copy), alll the disk images are copied to the outfile
682 directory and the json file references the images in the outfile directory.
683 In the case of mode='m' (move), the disk images are instead moved to the
684 outfile directory, and again the json file references the images in the
685 outfile directory. These two modes make it simple to deal with the
686 virtual concat image as a single unit, for example, if the user needs
687 to move the image or tar it up, the resulting moved image or untarred file
688 will be accessible by the image tool as a valid image. The final option,
689 mode='n' (no copy) means the output directory only contains the json file
690 and references the input image paths as given. In this case, moving the
691 outfile directory without moving the reference images will normally cause
692 problems, especially if the input images were given using relative path
693 names. So, one must think carefully if mode='n' will be the correct option
694 for their use case in the long run.
696 This method requires multiple images which are specified with the infiles
697 parameter. Therefore calling ia.open() is not necessary, although calling
698 imageconcat() using an already open image analysis tool will work and the
699 state of that tool (eg the image it references) will not be changed.
701 Input Parameters:
702 outfile Output image file name. Default is unset.
703 infiles List of input casa image files to concatenate; wild cards accepted. Default is empty string.
704 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.
705 relax Relax constraints that axis coordinate descriptors match
706 tempclose Keep all lattices closed until needed
707 overwrite Overwrite (unprompted) pre-existing output file?
708 reorder Automatically reorder the images if necessary.
709 mode Type of output image. 'paged', 'movevirtual', 'nomoveevirtual', 'copyvirtual'. Minimal match supported.
711 Example:
714 # Create three images to concatenate together.
715 ia.fromshape('im.1',[10,10,10],overwrite=True)
716 ia.fromshape('im.2',[10,10,10],overwrite=True)
717 ia.fromshape('im.3',[10,10,10],overwrite=True)
718 ia.done()
719 # now concatenate.
720 # The three images have the same shape along the axes not to be
721 # concatenated as they must. relax=True means that the contiguity
722 # constraint along the concatenated axis is not imposed (if it were
723 # the call would fail because the spectral axes of the input images
724 # are not contiguous).
725 bigim = ia.imageconcat(outfile='bigimage', infiles='im.1 im.2 im.3',
726 axis=2, relax=True, tempclose=False, overwrite=True)
727 # be sure to call done() on the return tool to free up system resources.
728 bigim.done()
734 #
735 # All images whose file names begin with {sff im.} that reside in
736 # the current directory are concatenated along the spectral axis if
737 # there is one. All image coordinate descriptors must match. If any
738 # input image does not have a spectral axis an error will
739 # result. Because an oufile is not specified, the returned image analysis
740 # tool captured in the variable named bigim just references the input images;
741 # this call does not create a persistent result image.
742 bigim = ia.imageconcat(infiles='im.*',relax=True)
743 bigim.done()
746 --------------------------------------------------------------------------------
748 """
749 return _image.image_imageconcat(self, *args, **kwargs)
752 def fromarray(self, *args, **kwargs):
753 """
754 fromarray(self, _outfile, _pixels, _csys, _linear, _overwrite, _log, _type) -> bool
758 Summary:
759 Construct a casa image from a numerical numpy array
761 Description:
765 This application converts a numerical numpy array of any size and dimensionality
766 into a CASA image. It will create float, double, complex-float, and complex-double
767 valued images.
769 The image analysis tool on which this method is called will reference the created
770 image; if this tool referenced another image before this call, that image will no
771 longer be referenced by the tool after the creation of the new image. If you
772 would rather have a new image analysis tool returned, keeping the one on which
773 this method is called unaltered, use newimagefromarray() instead. If outfile is
774 specified, a persistent image is written to disk, if not, the image tool on
775 which this method was called will reference a temporary image (either in memory
776 or on disk, depending on its size) that will be deleted when the tool is closed.
778 The type parameter controls the data type/precision of the pixel values of the
779 created image. 'f' indicates that float precision point (32 bit precision) pixel
780 values should be writted. 'd' indicates that double precision (64 bit precision)
781 pixel values should be written. If the input array has complex (as opposed to
782 real) values, then complex pixel values, with each of the real and imaginary
783 parts having the specified precision, will be written. Array values will be cast
784 automatically to the specified precision, so that the precision of the input
785 array values may be increased, decreased, or unchanged depending on the input
786 array type.
788 The coordinate system, provided as a a dictionary (use eg, cs.torecord() to do
789 that), is optional. If specified, it must have the same number of dimensions
790 as the pixels array. Call the naxes() method on the coordinate system tool to
791 see how many dimensions the coordinate system has. A coordinate system can be
792 created from scratch using the coordinate system (cs) tool and methods therein,
793 but often users prefer to use a coordinate system from an already existing image.
794 This can be gotten using ia.coordsys() which returns a coordinate system tool.
795 A torecord() call on that tool will result in a python dictionary describing
796 the coordinate system which is the necessary format for the csys input parameter
797 of ia.fromarray().
799 If csys is not specified, a default coordinate system will be created. If
800 linear=False (the default), the created coordinate system will have standard
801 RA/DEC/Stokes/Spectral Coordinate axes depending upon the shape of the pixels
802 array (Stokes axis must be no longer than 4 pixels and the spectral axis may
803 precede the Stokes axis if eg, shape=[64,64,32,4]. Extra dimensions are given
804 linear coordinates. If linear=True, then all the resulting coordinates
805 are linear with the axes represent lengths. In this case each axis will have a
806 value of 0.0 at its center pixel. The increment of each axis will be 1.0 km.
808 The method returns True if creation of the image was successful, False otherwise,
809 so a check can be made programmatically if the image creation was successful.
811 Input Parameters:
812 outfile Output image file name. Default is unset.
813 pixels Numeric array
814 csys Coordinate System. Default is to construct an appropriate coordinate system given the array shape.
815 linear Make a linear Coordinate System if csys not given
816 overwrite Overwrite the output image if it already exists?
817 log Write image creation messages to logger
818 type Pixel data type to write. 'f' (float precision) or 'd' (double precision)
820 Example:
823 # make an image with a default RA/Dec/Stokes/Frequency coordinate system
824 # having all pixels set to 2.5.
825 ary = ia.makearray(v=2.5, shape=[64, 64, 4, 128])
826 # the ia tool does not need to reference an image in this case (ie open()
827 # need not have been called), if it does reference another image, that reference
828 # will be lost and replaced with a reference to the newly created image.
829 res = ia.fromarray(outfile='test.data', pixels=ary, overwrite=true)
830 if res:
831 # perform operations on the newly created image if desired and make sure
832 # to close it when done to free up system resources (eg memory)
833 ia.shape()
834 ia.done()
840 # create an image using the coordinate system from another image
841 ia.open('myexistingimage.im')
843 mycs = ia.coordsys()
844 # the number of dimensions in the array and the coordinate system must
845 # be the same. For this example to work, mycs.naxes() must return 4.
846 ia.done()
847 ary = ia.makearray(v=2.5, shape=[64, 64, 4, 128])
848 res = ia.fromarray(pixels=ary, csys=mycs.torecord())
849 mycs.done()
850 if (res):
851 # do things with the newly created temporary image before closing it
852 ia.shape()
853 ia.done()
857 --------------------------------------------------------------------------------
859 """
860 return _image.image_fromarray(self, *args, **kwargs)
863 def fromcomplist(self, *args, **kwargs):
864 """
865 fromcomplist(self, _outfile, _shape, _cl, _csys, _overwrite, _log, _cache) -> bool
869 Summary:
870 Create a new ComponentListImage from a component list
872 Description:
875 This method allows one to create an image based on a component list. A component list
876 is a list of simple models (point sources, Gaussians, disks, etc) that describe the
877 sky brightness (cf the component list (cl) tool). Images that can be described in this
878 way normally require significantly less space to store than traditional images in which
879 all the pixel values are stored. For a component list image, pixel values are computed
880 'on the fly'. Pixel values can be cached by specifying cache=True (the default value)
881 while the image is attached to an image tool, which permits faster access to them after
882 they are computed the first time. The trade off to caching is that resources such as
883 memory and disk space must be used to cache the pixel values.
885 The image is constrained to have two, three, or four dimensions. One must specify an
886 image shape (the dimensionality of which must adhere to this constraint). One may also
887 supply a coordinate system specification using the csys parameter. If a coordinate system
888 is not specified, a default coordinate system is used. If specified, the coordinate system
889 must have a direction coordinate which has two pixel axes. It can also have a spectral
890 and/or polarization coordinate. The maximum length of the polarization coordinate is four
891 pixels, and the world coordinate values of the polarization coordinate are constrained to
892 be in the set of stokes parameters I, Q, U, and V.
894 As is common with image creation methods, specifying an empty string for the outfile parameter
895 results in a tempoary image being created that will be deleted when either the done() or
896 close() method is run on the tool. By specifying a non-empty string, the image is saved to
897 disk and can be opened with the open() method later. A persistent component list image is
898 composed of a component list table that has metadata describing the image-related information,
899 such as the coordinate system and the shape, as well as a history (log) table.
901 Because pixel values are computed from the component models, altering pixel values is not
902 supported. So methods such as putchunk(), putregion(), and addnoise() will fail on component
903 list images when trying to modify pixel values. However, persistent image masks and on the fly
904 masks are fully supported.
906 The brightness unit of a component list image is constrained to be 'Jy/pixel'. Attempts to
907 modify this value using setbrightnessunit() will fail.
909 Component list images do not support synthesized beams; attempting to run setrestoringbeam() on
910 a component list image to add a beam(s) will fail.
912 One can easily create an image in which the pixel values are persistently stored from a
913 component list image by running methods such as fromimage(), subimage(), tofits(), etc. In
914 general, any method run on a component list image that creates a new image will create a
915 non-component list image (eg, a traditional CASA Paged image or Temporary image) in which the
916 pixel values are explicitly stored.
918 DISK MODELS
920 Pixels with centers inside the disk will have the same values, even if a pixel straddles the
921 edge of the disk. Pixels with straddle the edge of the disk which have centers outside the
922 disk are given values of zero. Thus, one should not expect the flux density of the disk to
923 be exactly the provided value to the component list; for a given size disk, the computed flux
924 density will be closer to the expected value for images with smaller pixels.
928 Input Parameters:
929 outfile Name of output image file. Default is unset.
930 shape Shape of image. Must be specified and have either two, three, or four elements.
931 cl Component list as a dictionary or name of component list table. Must be specified
932 csys Coordinate System. Default uses a four dimensional 'standard' RA/Dec/Stokes/Freq coordinate system.
933 overwrite Overwrite (unprompted) pre-existing output file?
934 log Write image creation messages to logger
935 cache Cache pixel values for use while image is in use?
937 Example:
939 # use an existing component list and the coordinate system from an existing image
940 # to create a component list image. To prevent the size of the files associated with
941 # the component list from increasing, open the list read only
942 cl.open('mymodel.cl', nomodify=True)
943 clrec = cl.torecord()
944 cl.done()
945 # say this image has axes RA x Dec x Stokes x Freq
946 ia.open('myimage.im')
947 csys = ia.coordsys().torecord()
948 ia.done()
949 ia.fromcomplist(outfile='mycomplist.im', shape=[512, 512, 4, 20], cl=clrec,
950 csys=csys, cache=True)
951 # get statistics
952 stats = ia.statistics()
953 # do other operations, like convolving the image
954 im2 = ia.convolve2d(outfile='convolved.im', axes=[0,1], type='gauss', '
955 major='20arcsec', minor='10arces', pa='45deg')
956 # be sure to close the image tools when done with them
957 ia.done()
958 im2.done()
960 --------------------------------------------------------------------------------
962 """
963 return _image.image_fromcomplist(self, *args, **kwargs)
966 def fromfits(self, *args, **kwargs):
967 """
968 fromfits(self, _outfile, _infile, _whichrep, _whichhdu, _zeroblanks, _overwrite) -> bool
972 Summary:
973 Construct a casa image by conversion from a FITS image file
975 Description:
979 This function is used to convert a FITS disk image file (Float,
980 Double, Short, Long are supported) to an
981 casa imagefile. If {stfaf outfile} is given, the image is written
982 to the specified disk file. If {stfaf outfile} is unset, the Image
983 tool is associated with a temporary image. This temporary image may
984 be in memory or on disk, depending on its size. When you close the
985 Image tool (with the close function) this
986 temporary image is deleted.
988 This function reads from the FITS primary array (when the image is at
989 the beginning of the FITS file; {stfaf whichhdu=0}), or an image
990 extension (when the image is elsewhere in the FITS file, {stfaf
991 whichhdu $>$ 0}).
993 By default, any blanked pixels will be converted to a mask value which
994 is false, and a pixel value that is NaN. If you set {stfaf
995 zeroblanks=T} then the pixel value will be zero rather than NaN. The
996 mask will still be set to false. See the function
997 replacemaskedpixels if you
998 need to replace masked pixel values after you have created the image.
1000 Input Parameters:
1001 outfile Output image file name. Default is unset.
1002 infile Input FITS disk file name. Must be specified.
1003 whichrep If this FITS file contains multiple coordinate representations, which one should we read (0-based)
1004 whichhdu If this FITS file contains multiple images, which one should we read (0-based).
1005 zeroblanks If there are blanked pixels, set them to zero instead of NaN
1006 overwrite Overwrite (unprompted) pre-existing output file?
1008 Example:
1011 #
1012 print 't----t fromfits Ex 1 t----'
1013 datapath=pathname+'/data/demo/Images/imagetestimage.fits'
1014 ia.fromfits('./myimage', datapath, overwrite=true)
1015 print ia.summary()
1016 s = ia.miscinfo()
1017 print s.keys() # prints any unrecognized field names
1018 ia.close()
1019 #
1023 The FITS image is converted to a casa imagefile and access is
1024 provided via the default imagetool called {stf ia}. Any FITS
1025 header keywords which were not recognized or used are put in the
1026 miscellaneous information bucket accessible with the miscinfo function. In
1027 the example we list the names of the fields in this record.
1029 --------------------------------------------------------------------------------
1031 """
1032 return _image.image_fromfits(self, *args, **kwargs)
1035 def fromimage(self, *args, **kwargs):
1036 """
1037 fromimage(self, _outfile, _infile, _region, _mask, _dropdeg, _overwrite) -> bool
1041 Summary:
1042 Construct a (sub)image from a region of a casa image
1044 Description:
1048 This function applies a region to an imagefile, creates a new
1049 imagefile containing the (sub)image, and associates the imagetool
1050 with it.
1052 The input image file may be in native casa, fits, or Miriad
1053 format. Look htmlref{here}{IMAGES:FOREIGNIMAGES} for more
1054 information on foreign images.
1056 If {stfaf outfile} is given, the (sub)image is written to the specified
1057 disk file.
1059 If {stfaf outfile} is unset, the Image tool actually references
1060 the input image file. So if you deleted the input image disk file, it
1061 would render this tool useless. When you close this tool
1062 (with the close function)
1063 the reference connection is broken.
1065 Sometimes it is useful to drop axes of length one (degenerate axes).
1066 Use the {stfaf dropdeg} argument if you want to do this.
1068 The output mask is the combination (logical OR) of the default input
1069 pixelmask (if any) and the OTF mask. Any other input pixelmasks
1070 will not be copied. Use function
1071 maskhandler if you need to copy other
1072 masks too.
1074 See also the subimage function.
1076 Input Parameters:
1077 outfile Output sub-image file name. Default is unset.
1078 infile Input image file name. Must be specified.
1079 region Region selection. Default is to use the full image.
1080 mask Mask to use. Default is none.
1081 dropdeg Drop degenerate axes
1082 overwrite Overwrite (unprompted) pre-existing output file?
1084 Example:
1087 #
1088 print 't----t fromimage Ex 1 t----'
1089 innerquarter = rg.box([0.25,0.25],[0.75,0.75],frac=true)
1090 ia.close()
1091 ia.fromimage(outfile='image.small', infile='test.data', region=innerquarter, overwrite=true)
1092 ia.close()
1093 #
1096 The specified region takes a quarter by area of the first two axes
1097 of the image, and all pixels of other axes.
1099 --------------------------------------------------------------------------------
1101 """
1102 return _image.image_fromimage(self, *args, **kwargs)
1105 def fitsheader(self, *args, **kwargs):
1106 """
1107 fitsheader(self, _retstr, _exclude) -> variant *
1111 Summary:
1112 Construct a record of FITS keywords from this image
1114 Description:
1117 This method constructs a FITS header dictionary which describes the current image. The
1118 exclude parameter can either be a string or a list of strings. It indicates FITS header
1119 keywords to exclude. This may be useful for the HISTORY keyword because the HISTORY can
1120 be very long. If the retstr parameter is set to True, then a string will be returned
1121 representing the FITS header. The exculde parameter has no effect when the header
1122 information is returned as a single string. An new IMAGENME keyword is added to the
1123 header. The value for IMAGENME is the string returned by name method, but the name is
1124 truncated to the maximum size for a FITS header value, 68 characters. The image name
1125 is truncated from the beginning of the string to reduce it to 68 characters, so the
1126 value will contain either the full name or the final 68 characters of the name.
1128 Input Parameters:
1129 retstr return a string representing the FITS header instead of a record
1130 exclude Header fields to exclude from the return record. Fields cannot be excluded when ``retstr=True``.
1132 --------------------------------------------------------------------------------
1134 """
1135 return _image.image_fitsheader(self, *args, **kwargs)
1138 def fromshape(self, *args, **kwargs):
1139 """
1140 fromshape(self, _outfile, _shape, _csys, _linear, _overwrite, _log, _type) -> bool
1144 Summary:
1145 Construct an empty casa image from a shape
1147 Description:
1151 This function creates a CASA image with the specified shape. All the pixel
1152 values in the image are set to 0. One may create an image with float precision
1153 pixels (type='f'), complex float precision pixels (type='c'), double precision
1154 pixels (type='d'), or complex double precision pixels ('cd'). To use a numpy
1155 array of values to create an image, use ia.fromarray(). To make a 2-D image from
1156 a packaged FITS file, use ia.maketestimage().
1158 If outfile is given, the image is written to the specified disk file. If
1159 outfile is unset, the image analysis tool is associated with a temporary image.
1160 This temporary image may be in memory or on disk, depending on its size. When
1161 you close the image analysis tool (with the ia.close() method, the temporary
1162 image is deleted.
1164 The coordinate system, provided as a coordinate system tool record, is optional.
1165 If provided, it must be dimensionally consistent with the specified shape.
1167 If the coordinate system is not provided, a default coordinate system will be
1168 created. If linear=False (the default), then it is a
1169 standard RA/DEC/Stokes/Spectral coordinate system depending exactly upon the
1170 shape (the Stokes axis must be no longer than 4 pixels and spectral axis may
1171 occur prior to the Stokes axis if eg, shape=[64,64,32,4]. Extra dimensions are
1172 given linear coordinates. If linear=True, then the coordinate system will have
1173 linear coordinates.
1175 The method returns True if successful, False otherwise.
1177 Input Parameters:
1178 outfile Name of output image file. Default is unset.
1179 shape Shape of image. Must be specified.
1180 csys Coordinate System. Default is unset.
1181 linear Make a linear Coordinate System if csys not given?
1182 overwrite Overwrite (unprompted) pre-existing output file?
1183 log Write image creation messages to logger
1184 type Data type of image pixels. 'f' (float), 'c' (complex float), 'd' (double), 'cd' (complex double).
1186 Example:
1189 # Create a 64 x 64 x 128 RA-Dec-Frequency image
1190 ia.fromshape('test2.data', [64,64,128], overwrite=True)
1191 mycs = ia.coordsys(axes=[0,1])
1192 ia.close()
1193 # create temporary image using first and third axes of
1194 # previously created image
1195 ia.fromshape(shape=[10, 20], csys=mycs.torecord())
1196 mycs.done()
1197 ia.close()
1200 The first example creates a zero-filled imagefile named {sff
1201 test2.data} of shape [64,64,128]. If you examine the header with {stff
1202 ia.summary()} you will see the RA/DEC/Spectral coordinate information.
1203 In the second example, a Coordinate System describing the first and second axes
1204 of the image {sff test.data} is created and used to create a 2D temporary image.
1206 # create a 4-D image populated with noise with some interesting metadata
1207 ia.fromshape('noisy.im', [100, 100, 4, 20])
1208 # add the noise
1209 ia.addnoise()
1210 # add a beam
1211 ia.setrestoringbeam(major='4arcmin', minor='3arcmin', pa='20deg')
1212 # add brightness unit
1213 ia.setbrightnessunit('Jy/beam')
1214 ia.done()
1215 # set an interesting object name
1216 imd.open('noisy.im')
1217 imd.set('object','thor')
1218 imd.done()
1220 --------------------------------------------------------------------------------
1222 """
1223 return _image.image_fromshape(self, *args, **kwargs)
1226 def maketestimage(self, *args, **kwargs):
1227 """
1228 maketestimage(self, _outfile, _overwrite) -> bool
1232 Summary:
1233 Construct a casa image from a test FITS file
1235 Description:
1238 This function converts a FITS file resident in the casa system into
1239 a casa image.
1241 If outfile is given, the image is written to the specified disk
1242 file. If outfile is unset, the Image tool is associated with a
1243 temporary image. This temporary image may be in memory or on disk,
1244 depending on its size. When you close the Image tool (with the close
1245 function) this temporary image is deleted.
1247 Input Parameters:
1248 outfile Output image file name. Default is unset.
1249 overwrite Overwrite (unprompted) pre-existing output file?
1251 Example:
1254 #
1255 print 't----t maketestimage Ex 1 t----'
1256 ia.maketestimage() # make virtual image
1257 ia.close()
1258 ia.maketestimage('tmp', overwrite=true)
1259 ia.close() # close to unlock disk image
1260 #
1263 --------------------------------------------------------------------------------
1265 """
1266 return _image.image_maketestimage(self, *args, **kwargs)
1269 def deviation(self, *args, **kwargs):
1270 """
1271 deviation(self, _outfile, _region, _mask, _overwrite, _stretch, _grid, _anchor, _xlength, _ylength, _interp, _stattype, _statalg, _zscore, _maxiter) -> image
1275 Summary:
1276 Make an image based on a statistic from the input image's pixel values, which in some cases can represent a deviation image of the original.
1278 Description:
1282 This application creates an image that reflects the statistics of the input image. The output image has
1283 the same dimensions and coordinate system as the (selected region in) input image. The grid parameter
1284 describes how many pixels apart 'grid' pixels are. Statistics are computed around each grid pixel. Grid
1285 pixels are limited to the direction plane only; independent statistics are computed for each direction plane
1286 (ie at each frequency/stokes pixel should the input image happen to have such additional axes). Using the
1287 xlength and ylength parameters, one may specify either a rectangular or circular region around each grid
1288 point that defines which surrounding pixels are used in the statistic computation for individual grid points.
1289 If the ylength parameter is the empty string, then a circle of diameter provided by xlength centered on
1290 the grid point is used. If ylength is not empty, then a rectangular box of dimensions xlength x ylength centered
1291 on the grid pixel is used. These two parameters may be specified in pixels, using either numerical values or
1292 valid quantities with 'pix' as the unit (eg '4pix'). Otherwise, they must be specified as valid angular
1293 quantities, with recognized units (eg '4arcsec'). As with other region selections in CASA, full pixels are
1294 included in the computation even if the specified region includes only a fraction of that pixel. BEWARE OF
1295 MACHINE PRECISION ISSUES, because you may get a smaller number of pixels included in a region than you
1296 expect if you specify, eg, an integer number of pixels. In such cases, you probably want to specify that
1297 number plus a small epsilon value (eg '2.0001pix' rather than '2pix') to mitigate machine precision issues
1298 when computing region extents.
1300 The output image is formed by putting the statistics calculated at each grid point at the corresponding
1301 grid point in the output image. Interpolation of these output values is then used to compute values at
1302 non-grid-point pixels. The user may specify which interpolation algorithm to use for this computation
1303 using the interp parameter.
1305 The input image pixel mask is copied to the output image. If interpolation is performed, output pixels are
1306 masked where the interpolation fails.
1308 ANCHORING THE GRID
1310 The user may choose at which pixel to 'anchor' the grid. For example, if one specifies grid=[4,4] and
1311 anchor=[0,0], grid points will be located at pixels [0,0], [0,4], [0,8] ... [4,0], [4,4], etc. This
1312 is exactly the same grid that would be produced if the user specified anchor=[4,4] or anchor=[20,44].
1313 If the user specifies anchor=[1, 2] and grid=[4,4], then the grid points will be at pixels [1,2], [5,2],
1314 [9,2]... [5,2], [5,6], etc. and the resulting grid is the same as it would be if the user specified eg
1315 anchor=[9,10] or anchor=[21, 18]. The value 'ref', which is the default, indicates that the reference
1316 pixel of the input image should be used to anchor the grid. The x and y values of this pixel will be
1317 rounded to the nearest integer if necessary.
1319 SUPPORTED STATISTICS AND STATISTICS ALGORITHMS
1321 One may specify which statistic should be represented using the stattype parameter. The following values
1322 are recognized (minimum match supported):
1324 +--------------------+-------------------------------------------------------------------------------------------------------+
1325 | iqr | inner quartile range (q3 - q1) |
1326 +--------------------+-------------------------------------------------------------------------------------------------------+
1327 | max | maximum |
1328 +--------------------+-------------------------------------------------------------------------------------------------------+
1329 | mean | mean |
1330 +--------------------+-------------------------------------------------------------------------------------------------------+
1331 | medabsdevmed, madm | median absolute deviation from the median |
1332 +--------------------+-------------------------------------------------------------------------------------------------------+
1333 | median | median |
1334 +--------------------+-------------------------------------------------------------------------------------------------------+
1335 | min | minimum |
1336 +--------------------+-------------------------------------------------------------------------------------------------------+
1337 | npts | number of points |
1338 +--------------------+-------------------------------------------------------------------------------------------------------+
1339 | q1 | first quartile |
1340 +--------------------+-------------------------------------------------------------------------------------------------------+
1341 | q3 | third quartile |
1342 +--------------------+-------------------------------------------------------------------------------------------------------+
1343 | rms | rms |
1344 +--------------------+-------------------------------------------------------------------------------------------------------+
1345 | sigma, std | standard deviation |
1346 +--------------------+-------------------------------------------------------------------------------------------------------+
1347 | sumsq | sum of squares |
1348 +--------------------+-------------------------------------------------------------------------------------------------------+
1349 | sum | sum |
1350 +--------------------+-------------------------------------------------------------------------------------------------------+
1351 | var | variance |
1352 +--------------------+-------------------------------------------------------------------------------------------------------+
1353 | xmadm | median absolute deviation from the median multipied by x, where x is the reciprocal of Phi^-1(3/4), |
1354 | | where Phi^-1 is the reciprocal of the quantile function. Numerically, x = 1.482602218505602. See, eg, |
1355 | | https://en.wikipedia.org/wiki/Median_absolute_deviation#Relation_to_standard_deviation |
1356 +--------------------+-------------------------------------------------------------------------------------------------------+
1358 Using the statalg parameter, one may also select whether to use the Classical or Chauvenet/ZScore statistics algorithm to
1359 compute the desired statistic (see the help for ia.statistics() or imstat for a full description of these algorithms).
1363 Input Parameters:
1364 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.
1365 region Region selection. Default is to use the full image.
1366 mask Mask to use. Default setting is none.
1367 overwrite Overwrite (unprompted) pre-existing output file? Ignored if 'outfile' is left blank.
1368 stretch Stretch the mask if necessary and possible? Default value is False.
1369 grid x,y grid spacing. Array of exactly two positive integers.
1370 anchor x,y anchor pixel location. Either 'ref' to use the image reference pixel, or an array of exactly two integers.
1371 xlength Either x coordinate length of box, or diameter of circle. Circle is used if ylength is empty string.
1372 ylength y coordinate length of box. Use a circle if ylength is empty string.
1373 interp Interpolation algorithm to use. One of 'nearest', 'linear', or 'cubic'. Minimum match supported.
1374 stattype Statistic to compute. See full description for supported statistics.
1375 statalg Statistics computation algorithm to use. Supported values are 'chauvenet' and 'classic', Minimum match is supported.
1376 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'.
1377 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'.
1379 Example:
1381 # compute standard deviations in circles of diameter 10arcsec around
1382 # grid pixels spaced every 4 x 5 pixels and anchored at pixel [30, 40],
1383 # and use linear interpolation to compute values at non-grid-pixels
1384 ia.open('my.im')
1385 zz = ia.deviation('sigma.im', grid=[4, 5], anchor=[30, 40], xlength='10arcsec', stattype='sigma', interp='lin', statalg='cl')
1387 # compute median of the absolute deviations from the median values using
1388 # the z-score/Chauvenet algorithm, by fixing the maximum z-score to determine outliers to 5.
1389 # Use cubic interpolation to compute values for non-grid-point pixels. Use a rectangular region
1390 # of dimensions 5arcsec x 20arcsec centered on each grid point as the region in which to include
1391 # pixels for the computation of stats for that grid point.
1392 zz = ia.deviation('madm.im', grid=[4, 5], anchor=[30, 40], xlength='5arcsec', ylength='20arcsec, stattype='madm', interp='cub', statalg='ch', zscore=5)
1394 --------------------------------------------------------------------------------
1396 """
1397 return _image.image_deviation(self, *args, **kwargs)
1400 def adddegaxes(self, *args, **kwargs):
1401 """
1402 adddegaxes(self, _outfile, _direction, _spectral, _stokes, _linear, _tabular, _overwrite, _silent) -> image
1406 Summary:
1407 Add degenerate axes of the specified type to the image
1409 Description:
1413 This method adds degenerate axes (i.e.
1414 axes of length 1) of the specified type. Sometimes this can be useful
1415 although you will generally need to modify the coordinate system of the
1416 added axis to give it the coordinate you want (do this with the
1417 Coordsys tool). This method supports
1418 both float and complex valued images.
1420 You specify which type of axes you want to add. You can't add
1421 an axis type that already exists in the image. For the Stokes axis,
1422 the allowed value (a string such as I, Q, XX, RR) can be found in the
1423 Coordsys newcoordsys function documentation.
1425 If {stfaf outfile} is given, the image is written to the specified
1426 disk file. If {stfaf outfile} is unset, the on-the-fly Image tool
1427 returned by the function is associated with a temporary image. This
1428 temporary image may be in memory or on disk, depending on its size.
1429 When you destroy the generated Image tool (with the done function) this
1430 temporary image is deleted.
1432 Input Parameters:
1433 outfile Output image file name. Default is unset.
1434 direction Add direction axes?
1435 spectral Add spectral axis?
1436 stokes Add Stokes axis? Default is empty string.
1437 linear Add linear axis?
1438 tabular Add tabular axis?
1439 overwrite Overwrite (unprompted) pre-existing output file?
1440 silent Skip silently existing axes?
1442 Example:
1445 #
1446 print 't----t adddegaxes Ex 1 t----'
1447 ia.maketestimage()
1448 print ia.shape()
1449 #[113L, 76L]
1450 mycs=ia.coordsys()
1451 print mycs.axiscoordinatetypes()
1452 #['Direction', 'Direction']
1453 mycs.done()
1454 im2 = ia.adddegaxes(spectral=True)
1455 print im2.shape()
1456 #[113L, 76L, 1L]
1457 mycs=im2.coordsys()
1458 print mycs.axiscoordinatetypes()
1459 ['Direction', 'Direction', 'Spectral']
1460 mycs.done()
1461 im3 = im2.adddegaxes(stokes='Q')
1462 print im3.shape()
1463 #[113L, 76L, 1L, 1L]
1464 mycs = im3.coordsys()
1465 print mycs.axiscoordinatetypes()
1466 #['Direction', 'Direction', 'Spectral', 'Stokes']
1467 mycs.done()
1468 im2.done()
1469 im3.done()
1470 ia.close()
1471 #
1474 In this example, all the images are virtual (temporary images).
1476 --------------------------------------------------------------------------------
1478 """
1479 return _image.image_adddegaxes(self, *args, **kwargs)
1482 def addnoise(self, *args, **kwargs):
1483 """
1484 addnoise(self, _type, _pars, _region, _zero, _seeds) -> bool
1488 Summary:
1489 Add noise to the image
1491 Description:
1495 This function adds noise to the image. You may zero the image first
1496 before the noise is added if you wish.
1498 The noise can be drawn from one of many distributions.
1500 For each distribution, you must supply the type via the {stfaf type}
1501 argument (minimum match is active) and parameters via the {stfaf
1502 pars} argument. Briefly:
1504 begin{itemize}
1506 item {binomial} -- the binomial distribution models successfully drawing
1507 items from a pool. Specify two parameters, $n$ and $p$, respectively.
1508 $n$ is the number of items in the pool, and $p$, is the probability of
1509 each item being successfully drawn. It is required that $n > 0$ and
1510 $0 le p le 1$.
1512 item {discreteuniform} -- models a uniform random variable over the closed interval. Specify
1513 two parameters, the low and high values, respectively.
1514 The low parameter is the lowest possible return value and
1515 the high parameter is the highest. It is required that $low < high$.
1517 item {erlang} -- Specify two parameters, the mean and variance,
1518 respectively. It is required that the mean is non-zero and the variance
1519 is positive.
1521 item {geometric} -- Specify one parameter, the probability.
1522 It is required that $0 le probability < 1$.
1524 item {hypergeometric} -- Specify two parameters, the mean and the variance.
1525 It is required that the variance is positive and that the mean is non-zero
1526 and not bigger than the square-root of the variance.
1528 item {normal} -- Specify two parameters, the mean and the variance.
1529 It is required that the variance is positive.
1531 item {lognormal} -- Specify two parameters, the mean and the variance.
1532 It is required that the supplied variance is positive and that the mean is non-zero.
1534 item {negativeexponential} -- Supply one parameter, the mean.
1536 item {poisson} -- Specify one parameter, the mean.
1537 It is required that the mean is non-negative.
1539 item {uniform} -- Model a uniform random variable over a closed
1540 interval. Specify two parameters, the low and high values. The low
1541 parameter is the lowest possible return value and the high parameter can
1542 never be returned. It is required that $low < high$.
1544 item {weibull} -- Specify two parameters, alpha and beta.
1545 It is required that the alpha parameter is not zero.
1547 The random number generator seeds may be specified as an array of integers. Only the first
1548 two values are used. If none or a single value is provided, the necessary remaining value(s)
1549 are generated based on the current time, using the algorithm
1550 begin{verbatim}
1551 seedBase = 1e7*MJD
1552 seed[1] = (Int)seedBase;
1553 # and if seed[0] is also not supplied
1554 seed[0] = (Int)((1e7*(seedBase - seed[1])))
1555 end{verbatim}
1557 where MJD is the Modidfied Julian Day.
1559 end{itemize}
1561 Input Parameters:
1562 type Type of distribution, normal
1563 pars Parameters of distribution
1564 region Region selection. Default is to use the full image.
1565 zero Zero image first?
1566 seeds Seeds to use for the random number generator. If not specified, seeds are created based on the current time.
1568 Example:
1571 ia.maketestimage()
1572 ia.addnoise(type='normal', pars=[0.5, 1], zero=True, seeds=[1,2])
1573 ia.statistics()
1574 ia.close()
1577 A test image is created, zeroed, and noise of mean 0.5 and variance 1
1578 from a normal distribution added. Specifying the same combination of seeds
1579 ensures the same random number sequence is created each time addnoise is called.
1580 To have different sequences created during the same casapy session, use the default
1581 value (which is an empty list).
1583 --------------------------------------------------------------------------------
1585 """
1586 return _image.image_addnoise(self, *args, **kwargs)
1589 def convolve(self, *args, **kwargs):
1590 """
1591 convolve(self, _outfile, _kernel, _scale, _region, _mask, _overwrite, _stretch) -> image
1595 Summary:
1596 Convolve image with an array or another image
1598 Description:
1602 This function performs Fourier-based convolution of an image by the specified
1603 kernel. The input image must have real-valued pixels.
1605 If outfile is specified, a persistent image is written to the specified disk
1606 file. If outfile is left set to the empty string, the on-the-fly image analysis
1607 tool generated by this function is associated with a temporary image. This
1608 temporary image may be stored in memory or on disk, depending on its size.
1609 When the user destroys the generated image analysis tool with the close() or
1610 done() method, the temporary image is deleted.
1612 The kernel is provided as a multi-dimensional array or as the filename of a
1613 persistent image. The provided kernel can have fewer dimensions than the image
1614 being convolved. In this case, it will be padded with degenerate axes. An
1615 exception will be thrown if the kernel has more dimensions than the image. No
1616 additional scaling of the kernel is provided.
1618 The scaling of the output image is determined by the value of the scale
1619 parameter. If this is left unset, then the kernel is normalized to unit sum.
1620 If scale is not left unset, then the convolution kernel will be scaled
1621 (multiplied) by this value.
1623 Masked pixels will be assigned the value 0.0 before convolution.
1625 The output mask is the logical AND of the input image's default pixel mask (if
1626 any) and the OTF mask. Any other pixel masks associated with the input image
1627 will not be copied. The maskhandler method should be used if there is a need to
1628 copy other masks too.
1630 See also the other convolution methods convolve2d(), sepconvolve(), and
1631 hanning() for more specialized convolution algorithms.
1633 Input Parameters:
1634 outfile Output image file name. Default is unset.
1635 kernel Convolution kernel - An array or an image filename. Must be specified by the user.
1636 scale Scale factor. The default behavior is to autoscale (specified with -1.0).
1637 region Region selection. Default is to use the full image.
1638 mask Mask to use. The default setting is none.
1639 overwrite Overwrite (unprompted) the pre-existing output file?
1640 stretch Stretch the mask if necessary and possible?
1642 Example:
1645 #
1646 print 't----t convolve Ex 1 t----'
1647 # This example presupposes the existence of an input image file, testdata, and a kernel image file, kerneldata.
1648 # Open the input image file:
1649 ia.open(infile='testdata')
1650 # Set up a region to be operated upon (in this case, the whole image):
1651 r1 = rg.box()
1652 # Perform the convolution:
1653 im2 = ia.convolve (outfile = 'convout', overwrite = true, region = r1, kernel = 'kerneldata')
1654 ia.close()
1655 im2.done()
1657 #
1658 print 't----t convolve Ex 2 t----'
1659 # This example uses an array as the convolution kernel, and presupposes the existence of an input image file, testdata, which we first open:
1660 ia.open(infile='testdata')
1661 # Next, create a Python array of some kind to use as a convolution kernel. For example:
1662 from numpy import arange
1663 kernelarray = arange(10)**3
1664 # Set up a region to be operated upon (in this case, the whole image):
1665 r1 = rg.box()
1666 # Perform the convolution:
1667 im3 = ia.convolve (outfile = 'convout2', overwrite = true, region = r1, kernel = kernelarray)
1668 ia.close()
1669 im3.done()
1670 #
1673 --------------------------------------------------------------------------------
1675 """
1676 return _image.image_convolve(self, *args, **kwargs)
1679 def boundingbox(self, *args, **kwargs):
1680 """
1681 boundingbox(self, _region) -> record *
1685 Summary:
1686 Get the bounding box of the specified region
1688 Description:
1692 This function finds the bounding box of a
1693 region of interest when it is applied to a particular image. Both
1694 float and complex valued images are supported. It is
1695 returned in a record which has fields {cf 'blc', 'trc', 'inc',
1696 'bbShape', 'regionShape', 'imageShape', 'blcf'} and {cf 'trcf'}
1697 containing the bottom-left corner, the top-right corner (in absolute
1698 image pixel coordinates), the increment (stride) of the region, the
1699 shape of the boundingbox, the shape of the region, the shape of the
1700 image, the blc in formatted absolute world coordinates and the trc in
1701 formatted absolute world coordinates, respectively.
1703 Note that the shape of the bounding box will be different from the shape
1704 of the region if a non-unit stride (increment) is involved (see the example
1705 below).
1707 Note that the integer size of the elements in blc, trc, inc, regionShape,
1708 bbShape, and imageShape are 32 bits, even on a 64 bit machine. This means that,
1709 on 64 bit machines, you may have to convert them to 64 bit ints using eg
1710 numpy.int64, before being able to use them as direct input to other
1711 methods such as ia.getchunk().
1713 Input Parameters:
1714 region Region selection. Default is to use the full image.
1716 Example:
1719 #
1720 print 't----t boundingbox Ex 1 t----'
1721 ia.maketestimage() # Create image tool
1722 x=['3pix','6pix','9pix','6pix','5pix','5pix','3pix'] # X vector in abs pixels
1723 y=['3pix','4pix','7pix','9pix','7pix','5pix','5pix'] # Y vector in abs pixels
1724 mycs = ia.coordsys()
1725 r1=rg.wpolygon(x=x,y=y,csys=mycs.torecord()) # Create polygonal world region
1726 mycs.done()
1727 bb = ia.boundingbox(r1) # Find bounding box
1728 print bb
1729 #{'regionShape': array([7, 7]), 'trc': array([9, 9]),
1730 # 'imageShape': array([113, 76]),
1731 # 'blcf': '00:00:27.733, -00.06.48.000',
1732 # 'trcf': '00:00:24.533, -00.05.36.000', 'bbShape': array([7, 7]),
1733 # 'blc': array([3, 3]), 'inc': array([1, 1])}
1734 ia.close()
1735 #
1741 #
1742 print 't----t boundingbox Ex 2 t----'
1743 ia.maketestimage()
1744 b = rg.box([10,10],[20,20],[2,3])
1745 print ia.boundingbox(b)
1746 #{'regionShape': array([6, 4]), 'trc': array([20, 19]),
1747 # 'imageShape': array([113, 76]),
1748 # 'blcf': '00:00:24.000, -00.05.24.000',
1749 # 'trcf': '00:00:18.667, -00.03.36.000', 'bbShape': array([11, 10]),
1750 # 'blc': array([10, 10]), 'inc': array([2, 3])}
1752 ia.close()
1753 #
1756 In this example we see the difference between bbShape and regionShape because
1757 of the increment (stride). See also that the trc is modified by
1758 the increment.
1760 --------------------------------------------------------------------------------
1762 """
1763 return _image.image_boundingbox(self, *args, **kwargs)
1766 def boxcar(self, *args, **kwargs):
1767 """
1768 boxcar(self, _outfile, _region, _mask, _axis, _width, _drop, _dmethod, _overwrite, _stretch) -> image
1772 Summary:
1773 Convolve one axis of image with a boxcar kernel
1775 Description:
1779 This application performs boxcar convolution of one axis of an image
1780 defined by
1782 z[i] = (y[i] + y[i+i] + ... + y[i+w-1])/w
1784 where z[i] is the value at pixel i in the box car smoothed image, y[k]
1785 is the pixel value of the input image at pixel k, and w is a postivie integer
1786 representing the width of the boxcar in pixels. Both float and complex
1787 valued images are supported. The length of the axis along which the
1788 convolution is to occur must be at least w pixels in the selected region,
1789 unless decimation using the mean function is chosen in which case the axis
1790 length must be at least 2*w (see below). Masked pixel values are set to
1791 zero prior to convolution. All nondefault pixel masks are ignored during
1792 the calculation. The convolution is done in the image domain (i.e., not
1793 with an FFT).
1795 If drop=False (no decimation), the length of the output axis will be equal
1796 to the length of the input axis - w + 1. The pixel mask, ORed with the OTF mask
1797 if specified, is copied from the selected region of the input image to the
1798 output image. Thus for example, if the selected region in the input image has
1799 six planes along the convolution axis, if the specified boxcar width is 2,
1800 and if the pixel values, which are all unmasked, on a slice along this axis
1801 are [1, 2, 5, 10, 17, 26], then the corresponding output slice will be of
1802 length five and the output pixel values will be [1.5, 3.5, 7.5, 13.5, 21.5].
1804 If drop=True and dmethod='copy', the output image is the image calculated
1805 if drop=True, except that only every wth plane is kept. Both the pixel and mask
1806 values of these planes are copied directly to the output image, without further
1807 processing. Thus for example, if the selected region in the input image has six
1808 planes along the convolution axis, the boxcar width is chosen to be 2, and if
1809 the pixel values, which are all unmasked, on a slice along this axis are [1, 2,
1810 5, 10, 17, 26], the corresponding output pixel values will be [1.5, 7.5, 21.5].
1812 If drop=True and dmethod='mean', first the image described in the drop=False
1813 case is calculated. Then, the ith plane of the output image is calculated by
1814 averaging the i*w to the (i+1)*w-1 planes of this intermediate image. Thus, for
1815 example, if the selected region in the input image has six planes along the
1816 convolution axis, the boxcar width is chosen to be 2, and if the pixel values,
1817 which are all unmasked, on a slice along this axis are [1, 2, 5, 10, 17, 26],
1818 then the corresponding output pixel values will be [2.5, 10.5]. Any pixels at the
1819 end of the plane of the intermediate image that do not fall into a complete bin of
1820 width w are ignored. Masked values are taken into consideration when forming this
1821 average, so if one of the values is masked, it is not used in the average. If at
1822 least one of the valuesin the intermediate image bin is not masked, the
1823 corresponding output pixel will not be masked.
1825 The smoothed image is written to disk with name {stfaf outfile}, if specified.
1826 If not, no image is written but the image is still accessible via the returned
1827 image analysis tool (see below).
1829 This method always returns an image analysis tool which is attached to the smoothed
1830 image. This tool should always be captured and closed after any desired manipulations
1831 have been done. Closing the tool frees up system resources (eg memory), eg,
1833 begin{verbatim}
1834 smoothedim = ia.boxcar(...)
1835 # do things (or not) with smoothedim
1836 ...
1837 # close the returned tool promptly upon finishing with it.
1838 smoothedim.done()
1839 end{verbatim}
1842 Input Parameters:
1843 outfile Output image file name. Default is none.
1844 region Region selection. Default is to use the full image.
1845 mask Mask to use. Default is none.
1846 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.
1847 width Width of the boxcar in pixels.
1848 drop Drop every nth pixel on output, where n is the width of the boxcar?
1849 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.
1850 overwrite Overwrite (unprompted) pre-existing output file?
1851 stretch Stretch the mask if necessary and possible? See help par.stretch. Default False
1853 Example:
1855 ia.open('mynonsmoothed.im')
1856 # smooth the spectral axis by 3 pixels, say it's axis 2 and only
1857 # write every other pixel
1858 boxcar = ia.boxcar(outfile='myboxcarsmoothed.im', axis=2, drop=True,
1859 width=3, dmethod='c' overwrite=True)
1860 # done with input
1861 ia.done()
1862 # do something with the output image, get statistics say
1863 stats = boxcar.statistics()
1864 # close the result image
1865 boxcar.done()
1867 --------------------------------------------------------------------------------
1869 """
1870 return _image.image_boxcar(self, *args, **kwargs)
1873 def brightnessunit(self):
1874 """
1875 brightnessunit(self) -> string
1879 Summary:
1880 Get the image brightness unit
1882 Description:
1886 This function gets the image brightness unit. Both float and complex
1887 valued images are supported.
1889 Example:
1892 #
1893 print 't----t brightnessunit Ex 1 t----'
1894 ia.maketestimage()
1895 print ia.brightnessunit()
1896 #Jy/beam
1897 ia.close()
1898 #
1901 --------------------------------------------------------------------------------
1903 """
1904 return _image.image_brightnessunit(self)
1907 def calc(self, *args, **kwargs):
1908 """
1909 calc(self, _pixels, _verbose) -> bool
1913 Summary:
1914 Image calculator
1916 Description:
1920 This function is used to evaluate a mathematical expression involving
1921 casa images, assigning the result to the current (already existing)
1922 image. Both float and complex valued images are supported, although the
1923 image which results from the calculation must have the same type of pixel
1924 values as the image already attached to the tool. That is, one cannot
1925 create a complex valued image using this method if the associated ia tool
1926 is currently attached to a float valued image. It complements the imagecalc
1927 function which returns a newly constructed on-the-fly image tool. See htmladdnormallink{note 223}{../../notes/223/223.html}
1928 which describes the the syntax and functionality in detail.
1930 If the expression, supplied via the {stfaf pixels} argument, is not a
1931 scalar, the shapes and coordinates of the image and expression must
1932 conform.
1934 If the image (that associated with the tool) has a pixelmask, then only
1935 pixels for which that mask is good will be changed. See the function
1936 maskhandler for managing image pixelmasks.
1938 Note that when multiple image are used in the expression, there is no garauntee about which of
1939 those images will be used to create the header of the output image. Therefore, one may have
1940 to modify the output header as needed if the input headers differ.
1942 See the related functions set and
1943 putregion.
1945 Input Parameters:
1946 pixels LEL expression
1947 verbose Emit possibly useful messages.
1949 Example:
1952 #
1953 print 't----t calc Ex 1 t----'
1954 ia.maketestimage('aF', overwrite=true)
1955 ia.calc('min(aF, (min(aF)+max(aF))/2)')
1956 ia.calc('1.0')
1957 ia.close()
1958 #
1962 The first example shows that there are 2 {cf min} functions. One with a
1963 single argument returning the minimum value of that image. The other
1964 with 2 arguments returning an image containing ``aF'' data clipped at
1965 the value of the 2nd argument. The second example sets all good
1966 pixels to unity.
1970 #
1971 print 't----t calc Ex 2 t----'
1972 ia.maketestimage('aD', overwrite=true) # create some
1973 ia.close()
1974 ia.maketestimage('aF', overwrite=true) # image files
1975 ia.close()
1976 ia.maketestimage('bF', overwrite=true) # for use
1977 ia.close()
1978 ia.maketestimage('aC', overwrite=true) # in
1979 ia.close()
1980 ia.maketestimage()
1981 ia.calc('sin(aD)+(aF*2)+min(bF)+real(aC)') # the example
1982 ia.close()
1983 #
1986 This shows a mixed type expression. The real part of the complex image
1987 ``aC'' is used in an expression that otherwise uses Float type.
1989 --------------------------------------------------------------------------------
1991 """
1992 return _image.image_calc(self, *args, **kwargs)
1995 def calcmask(self, *args, **kwargs):
1996 """
1997 calcmask(self, _mask, _name, _asdefault) -> bool
2001 Summary:
2002 Image mask calculator
2004 Description:
2008 This method is used to create a new pixel mask via a boolean LEL expression.
2010 See http://casa.nrao.edu/aips2_docs/notes/223/index.shtml which describes the
2011 the syntax and functionality of LEL in detail. Also in this document is a
2012 description of ways to escape image names that contain certain non-alphanumeric
2013 characters so they are compatible with LEL syntax.
2015 If the expression is not a scalar, the shapes and coordinates of the image and
2016 expression must conform. If the expression is a scalar then the entire pixel
2017 mask will be set to that value.
2019 By specifying the name parameter to be an empty string, the method automatically
2020 determines the name of the output mask. Otherwise, the output mask is named the
2021 value specified by the name parameter. If a mask by that name already exists,
2022 it is overwritten. Use method ia.summary() to view existing mask names.
2024 The asdefault parameter specifies if the new mask should be set as the default
2025 pixel mask of the image. This value is set to True by default.
2027 Input Parameters:
2028 mask Mask to use. Default is none.
2029 name Mask name. Default is auto new name.
2030 asdefault Make specified mask the default mask?
2032 Example:
2035 #
2036 print 't----t calcmask Ex 1 t----'
2037 ia.maketestimage('zz', overwrite=true)
2038 subim = ia.subimage() # Make 'another' image
2039 ia.calcmask('T') # Specify 'True' mask as a string
2040 ia.calcmask('zz>0') # Mask of zz ignored
2041 ia.calcmask('mask(zz) && zz>0') # Mask of zz included
2042 ia.calcmask(subim.name(true)+'>min('+subim.name(true)+')') # Use tool names
2043 ia.calcmask('zz>min(zz:nomask)') # Mask of zz not used in scalar function
2044 subim.done()
2045 ia.close()
2046 #
2050 The first calcmask example is the equivalent of {cf
2051 ia.set(pixelmask=1)}. It sets the entire mask to True.
2053 The second example creates a new pixelmask which is True when
2054 the pixel values in image {sff zz} are greater than 0.
2056 Now for some subtlety. Read carefully ! Any LEL expression can be
2057 thought of as having a value and a mask. Usually the value is Float and
2058 the mask Boolean. In this case, because the expression is Boolean
2059 itself, the value is also Boolean. The expression mask would just be
2060 the mask of {sff zz}. Now what {stfaf calcmask} does is create a mask
2061 from the expression value (which is Boolean) and discards the expression
2062 mask. Therefore, the resulting mask is independent of any mask
2063 that {sff zz} might have.
2065 If you wish the mask of the expression be honoured as well,
2066 then you can do as in the third example. It says the output pixelmask
2067 will be True if the current pixelmask of {sff zz} is True and the expression
2068 value is True.
2070 The fourth example is like the second, except that we use the pixel
2071 values associated with the on-the-fly {stf subim} Image tool disk file. Note one further
2072 subtlety here. When the scalar function {cf min} evaluates a value
2073 from {cf subim.name()}, which in this case is just {cf zz}, the default
2074 mask of {cf subim.name()} {it will} be used. All the scalar
2075 functions look at the mask. If you didn't want the mask to be used
2076 you can use the special {cf :nomask} syntax shown in the final
2077 example.
2079 --------------------------------------------------------------------------------
2081 """
2082 return _image.image_calcmask(self, *args, **kwargs)
2085 def close(self):
2086 """
2087 close(self) -> bool
2091 Summary:
2092 Close the image tool
2094 Description:
2098 This function closes the imagetool. This means that it detaches the
2099 tool from its imagefile (flushing all the changes first). The
2100 imagetool is ``null'' after this change (it is not destroyed) and
2101 calling any toolfunction other than open
2102 will result in an error.
2104 Example:
2107 #
2108 print 't----t close Ex 1 t----'
2109 ia.maketestimage('myimage',overwrite=true) # First create an image and attach the image tool to it.
2110 ia.close() # The Image tool is detached from the image using the close tool.
2111 print '!!!EXPECT ERROR HERE!!!'
2112 ia.summary() # The image is not open, so attempting to display summary information on the image results in an error.
2113 ia.open('myimage') # The image tool is reattached to the image using the open tool.
2114 ia.summary() # No error - the summary information is now displayed correctly.
2115 ia.close() # The Image tool is detached from the image again, using the close tool.
2116 #
2119 --------------------------------------------------------------------------------
2121 """
2122 return _image.image_close(self)
2125 def continuumsub(self, *args, **kwargs):
2126 """
2127 continuumsub(self, _outline, _outcont, _region, _channels, _pol, _fitorder, _overwrite) -> image
2131 Summary:
2132 Image plane continuum subtraction
2134 Description:
2138 This function packages the relevant image tool functionality for simple
2139 specification and application of image plane continuum subtraction. All
2140 that is required of the input image is that it have a non-degenerate
2141 spectral axis.
2143 The user specifies region, the region of the input image over which
2144 continuum subtraction is desired (otherwise the whole image will be
2145 treated); channels, the subset of channels on the spectral axis to use
2146 in the continuum estimation, specified as a vector;
2147 fitorder, the polynomial order to use in the
2148 estimation. Optionally, output line and continuum images may be written
2149 by specifying outline and outcont, respectively. If outline is not
2150 specified, a virtual image tool is all that is produced. If outcont is
2151 not specified, the output continuum image will be written in
2152 'continuumsub.im'. Note that the pol parameter is no longer supported; one
2153 should use the region parameter if polarization selection is desired, in
2154 conformance with other ia tool methods.
2156 Input Parameters:
2157 outline Output line image filename. Default is unset.
2158 outcont Output continuum image filename
2159 region Region selection. Default is to use the full image.
2160 channels Channels to use for continuum estimation. Default is all.
2161 pol THIS PARAMETER IS NO LONGER SUPPORTED. USE THE region PARAMETER TO CHOOSE WHICH POLARIZATIONS YOU WOULD LIKE TO PROCESS
2162 fitorder Polynomial order for continuum estimation
2163 overwrite Auto-overwrite output files if they exist?
2165 Example:
2167 Fit a second order polynomial (fitorder=2) to channels 3-8 and 54-60 (python's
2168 range function includes the lower limit and excludes the upper limit)
2169 to an RA x Dec x Frequency x Stokes cube.
2171 ia.open('myimage.im')
2173 # select stokes plane 1 on which to perform the fit, as well
2174 # as a box of pixels with blc=25,25 and trc=75,75 in the direction
2175 # plane, and channels 0 to 100. This will be the portion of the cube
2176 # from which the fit is subtracted
2177 reg = rb.box(blc=[25, 25, 0, 1], trc=[75, 75, 100, 1])
2178 csub = ia.continuumsub(region=reg, channels=range(3,9)+range(54,61), fitorder=2)
2180 # do stuff with original image (ia) and csub image tools as necessary and
2181 # finally close them
2182 ia.done()
2183 csub.done()
2185 --------------------------------------------------------------------------------
2187 """
2188 return _image.image_continuumsub(self, *args, **kwargs)
2191 def convertflux(self, *args, **kwargs):
2192 """
2193 convertflux(self, _value, _major, _minor, _type, _topeak, _channel, _polarization) -> record *
2197 Summary:
2198 Convert peak intensity to/from flux density for a 2D Gaussian.
2200 Description:
2204 This function interconverts between peak intensity and flux density for a
2205 Gaussian component. The image must hold a restoring beam.
2207 Input Parameters:
2208 value Flux density to convert. Must be specified.
2209 major Major axis of component. Must be specified.
2210 minor Minor axis of component. Must be specified.
2211 type Type of component. String from Gaussian, Disk.
2212 topeak Convert to peak or integral flux desnity
2213 channel Channel to use if and only if image has per plane beams.
2214 polarization Zero-based polarization number to use for beam if and only if image has per plane beams.
2216 Example:
2219 #
2220 print 't----t convertflux Ex 1 t----'
2221 ia.maketestimage('in.im', overwrite=true);
2222 p1 = qa.quantity('1mJy/beam')
2223 i1 = ia.convertflux(p1, major='30arcsec', minor='10arcsec', topeak=False);
2224 p2 = ia.convertflux(i1, major='30arcsec', minor='10arcsec', topeak=True)
2225 print 'peak, integral, peak = ', p1, i1, p2
2226 #peak, integral, peak = {'value': 1.0, 'unit': 'mJy/beam'}
2227 # {'value': 0.00016396129551656742, 'unit': 'Jy'}
2228 # {'value': 0.0010000000000000002, 'unit': 'Jy/beam'}
2230 ia.close()
2231 #
2234 --------------------------------------------------------------------------------
2236 """
2237 return _image.image_convertflux(self, *args, **kwargs)
2240 def convolve2d(self, *args, **kwargs):
2241 """
2242 convolve2d(self, _outfile, _axes, _type, _major, _minor, _pa, _scale, _region, _mask, _overwrite, _stretch, _targetres, _beam) -> image
2246 Summary:
2247 Convolve image by a 2D kernel
2249 Description:
2253 This function performs Fourier-based convolution of an imagefile
2254 using the provided 2D kernel.
2256 If {stfaf outfile} is left unset, the image is written to the specified
2257 disk file. If {stfaf outfile} is not given, the newly constructed
2258 on-the-fly Image tool is associated with a temporary image. This
2259 temporary image may be stored in memory or on disk, depending on its size.
2260 When the user destroys the on-the-fly Image tool (with the done function) this
2261 temporary image is deleted.
2263 The user specifies which 2 pixel axes of the image are to be convolved
2264 via the {stfaf axes} argument. The pixels must be square or an error will result.
2266 The user specifies the type of convolution kernel with {stfaf type} (minimum
2267 match is supported); currently only {cf 'gaussian'} is available.
2269 The user specifies the parameters of the convolution kernel via the arguments
2270 {stfaf major}, {stfaf minor}, and {stfaf pa}. These arguments can
2271 be specified in one of three ways:
2273 begin{itemize}
2275 item Quantity - for example {stfaf major=qa.quantity(1, 'arcsec')}
2276 Note that you pixel units can be used, viz. {stfaf major=qa.quantity(1, 'pix')},
2277 see below.
2279 item String - for example {stfaf minor='1km'} (i.e. one that the
2280 Quanta quantity function accepts).
2282 item Numeric - for example {stfaf major=10}. In this case, the units
2283 of {stfaf major} and {stfaf minor} are assumed to be in pixels. Using
2284 pixel units allows the user to convolve unlike axes (see one of the provided
2285 example for this use case). For the position angle, units of degrees are assumed.
2287 end{itemize}
2289 The interpretation of {stfaf major} and {stfaf minor} depends upon the
2290 kernel type.
2292 begin{itemize}
2294 item Gaussian - {stfaf major} and {stfaf minor} are
2295 the Full Width at Half Maximum (FWHM) of the major and minor
2296 axes of the Gaussian.
2298 end{itemize}
2300 The position angle is measured North through East when a
2301 plane holding a celestial coordinate (the usual astronomical
2302 convention) is convolved. For other axis/coordinate combinations,
2303 a positive position angle is measured from +x to +y in the
2304 absolute pixel coordinate frame (x is the first axis that is
2305 specified, with argument {stfaf axes}).
2307 In the case of a Gaussian, the {stfaf beam} parameter offers an alternate way of
2308 describing the convolving Gaussian. If used, neither {stfaf major}, {stfaf minor},
2309 nor {stfaf pa} can be specified. The {stfaf beam} parameter must have exactly three
2310 fields: 'major', 'minor', and 'pa' (or 'positionangle'). This is, not coincidentally,
2311 the record format for the output of ia.restoringbeam().
2313 The scaling of the output image is determined by the argument {stfaf scale}.
2314 If this is left unset then autoscaling will be invoked.
2316 If the user is not convolving the sky, then autoscaling means that the convolution
2317 kernel will be normalized to have unit volume so as to conserve flux.
2319 If the user is convolving the sky, then there are two cases
2320 for which autoscaling is useful:
2322 Firstly, if the input image units are Jy/pixel, then the output image
2323 will have units of Jy/beam and be appropriately scaled. In addition,
2324 the restoring beam of the output image will be the same as the
2325 convolution kernel.
2327 Secondly,if the input image units are Jy/beam, then the output
2328 image will also have units of Jy/beam and be appropriately
2329 scaled. In addition, the restoring beam of the output image
2330 will be the convolution of the input image restoring beam and the
2331 convolution kernel. In the case of an image with per-plane beams, for
2332 each plane, the kernel is convolved with the appropriate beam and the
2333 result is associated with that plane in the output image.
2335 If the user sets a value for {stfaf scale}, then the convolution kernel
2336 will be scaled by this value. Note that it has peak of unity before the
2337 application of this scale factor.
2339 If the units on the original image include Jy/beam, the units on the
2340 output image will be rescaled by the ratio of the input and output
2341 beams as well as rescaling by the area of convolution kernel.
2343 If the units on the original image include K, then only the image
2344 convolution kernel rescaling is done.
2346 If targetres=True and type='gaussian' and the input image has a restoring beam,
2347 this method will interpret the values of major, minor, and pa as the resolution
2348 of the final image and will calculate the parameters of the Gaussian to use
2349 in the convolution so that this target resolution is achieved.
2351 Masked pixels will be assigned the value 0.0 before convolution.
2352 The output mask is the intersection (logical AND) of the default input
2353 pixelmask (if any) and the OTF mask. Any other input pixelmasks
2354 will not be copied. The function
2355 maskhandler
2356 can be used if there is a need to copy other masks too.
2358 See also the other convolution functions:
2360 convolve,
2361 hanning, and
2362 sepconvolve.
2364 Input Parameters:
2365 outfile Output image file name. The default value is unset.
2366 axes Axes to convolve. The default setting is [0,1].
2367 type Type of convolution kernel to be used.
2368 major Major axis, Quantity, string, numeric (e.g. 10arcsec, 20pix, 3km, etc.). This must be specified by the user.
2369 minor Minor axis, Quantity, string, numeric (e.g. 10arcsec, 20pix, 3km, etc.). This must be specified by the user.
2370 pa Position Angle, Quantity, string, numeric (e.g. 10deg). The default value is 0deg.
2371 scale Scale factor. The default setting (-1) is to autoscale.
2372 region Region selection. Default is to use the full image.
2373 mask Mask to use. The default option is none.
2374 overwrite Overwrite (unprompted) the pre-existing output file?
2375 stretch Stretch the mask if necessary and possible?
2376 targetres If True and type='gaussian', major, minor, and pa are interpreted as the image resolution that the user wants to achieve.
2377 beam Alternate way of describing a Gaussian. Must have fields 'major', 'minor', and 'pa' (or 'positionangle')
2379 Example:
2382 #
2383 print 't----t convolve2d Ex 1 t----'
2384 ia.maketestimage('xy',overwrite=true) # Create a simple RA/DEC test image
2385 # Convolve axes 0 and 1 of the test image with a 20x10-arcsec, 45-degree Gaussian:
2386 im2 = ia.convolve2d(outfile='xy.con', axes=[0,1], type='gauss',
2387 major='20arcsec', minor='10arcsec', pa='45deg',
2388 overwrite=true);
2389 # Clean up, by destroying the im2 tool and close the image tool:
2390 im2.done()
2391 ia.close()
2392 #
2394 ia.fromarray(outfile='xypf', pixels=ia.makearray(0, [64, 64, 4, 64]),
2395 overwrite=true) # Create a simple RA/DEC/Pol/Freq test dataset
2396 print '!!!EXPECT WARNING REGARDING INVALID SPATIAL RESTORING BEAM!!!'
2397 # Convolve axes 0 and 3 of the test dataset with a 20x10-pixel, 45-degree Gaussian:
2398 im2 = ia.convolve2d(outfile='xypf.con', axes=[0,3], type='gauss',
2399 major='20pix', minor='10pix', pa='45deg',
2400 overwrite=true);
2401 # Note that pixel units must be used in the above because axes 0 and 3 are unlike.
2402 # Clean up, by destroying the im2 tool and close the image tool:
2403 im2.done()
2404 ia.close()
2405 #
2408 --------------------------------------------------------------------------------
2410 """
2411 return _image.image_convolve2d(self, *args, **kwargs)
2414 def coordsys(self, *args, **kwargs):
2415 """
2416 coordsys(self, _axes) -> casac::coordsys *
2420 Summary:
2421 Get the Coordinate System of the image
2423 Description:
2427 This function returns the Coordinate System of an image in a {stf
2428 Coordsys} tool. Both float and complex valued images are supported.
2430 By default, the Coordinate System describes all of the axes in the
2431 image. If you desire, you can select a subset of the axes, thus
2432 reducing the dimensionality of the Coordinate System. This may be
2433 useful if you are supplying a Coordinate System to the
2434 functions fromarray or
2435 fromshape.
2437 Input Parameters:
2438 axes Axes to which the Coordinate System pertains. Default is all axes.
2440 Example:
2443 #
2444 print 't----t coordsys Ex 1 t----'
2445 ia.maketestimage('hcn',overwrite=true)
2446 ia.summary()
2447 mycs = ia.coordsys([0,1])
2448 imshape = ia.shape()
2449 ia.fromshape(outfile='test', shape=imshape, csys=mycs.torecord(), overwrite=true)
2450 ia.summary()
2451 mycs.done()
2452 ia.close()
2453 #
2457 In this example, we create a Coordinate System pertaining to the first
2458 two axes of the image and then we create a new (empty) 2D image with
2459 this Coordinate System using the {cf fromshape} function.
2461 --------------------------------------------------------------------------------
2463 """
2464 return _image.image_coordsys(self, *args, **kwargs)
2467 def coordmeasures(self, *args, **kwargs):
2468 """
2469 coordmeasures(self, _pixel, _dframe, _sframe) -> record *
2473 Summary:
2474 Convert from pixel to world coordinate wrapped as Measures
2476 Description:
2480 You can use this function to get the world coordinates for a specified
2481 absolute pixel coordinate in the image. You specify a pixel coordinate
2482 (0-rel) for each axis in the image.
2484 If you supply fewer pixel values then there are axes in the image, your
2485 value will be padded out with the reference pixel for the missing axes.
2486 Excess values will be ignored.
2488 The parameters dframe and sframe allow one to specify to which reference frame
2489 the direction and spectral measures, respectively, should be converted. These
2490 values are case-insensitive. 'native' means use the native reference frame of
2491 the coordinate in question. 'cl' means use the conversion layer frame if one
2492 exists (if not, the native frame will be used).
2494 The world coordinate is returned as a record of measures. This
2495 function is just a wrapper for the Coordsys tool toworld function
2496 (invoked with argument {stfaf format='m'}). Please see its
2497 documentation for discussion about the formatting and meaning of the
2498 measures.
2500 This Image tool function adds two additional fields to the return record.
2502 The {cf mask} field contains the value of the image pixelmask at the
2503 specified position. It is either T (pixel is good) or F (pixel is masked
2504 as bad or the specified position was off the image).
2506 The {cf intensity} field contains the value of the image (at the
2507 nearest pixel to that given) and its units. This is actually stored
2508 as a Quantity. This field does not exist
2509 if the specified pixel coordinate is off the image.
2511 Input Parameters:
2512 pixel Absolute pixel coordinate. Default is reference pixel.
2513 dframe Direction reference frame to which to convert the direction data. Case insensitive. 'cl' means use the conversion layer, if present, of the image direction coordinate. 'native' means use the native native direction frame of the image. Other examples are 'J2000', 'B1950', 'GALACTIC', etc.
2514 sframe Spectral reference frame to which to convert the spectral data. Case insensitive. 'cl' means use the conversion layer, if present, of the image spectral coordinate. 'native' means use the native spectral reference frame of the image. Other examples are 'LSRK', 'CMB', 'LGROUP', etc.
2516 Example:
2519 #
2520 print 't----t coordmeasures Ex 1 t----'
2521 ia.maketestimage('myimage',overwrite=true)
2522 s = ia.shape()
2523 for i in range(len(s)):
2524 s[i] = 0.5*s[i]
2525 meas = ia.coordmeasures(s)
2526 print meas.keys() # Get names of fields in record
2527 #['intensity', 'mask', 'measure']
2528 print meas['intensity']
2529 #{'value': 1.39924156665802, 'unit': 'Jy/beam'}
2530 print meas['measure']['direction']
2531 #{'type': 'direction',
2532 # 'm1': {'value': 5.817764003289323e-05, 'unit': 'rad'},
2533 # 'm0': {'value': -5.8177644130875234e-05, 'unit': 'rad'}, 'refer': 'J2000'}
2534 dir = meas['measure']['direction'] # Get direction coordinate
2535 me.doframe(me.observatory('ATCA')) # Set location on earth
2536 me.doframe(me.epoch('utc','16jun1999/12:30:20')) # Set epoch
2537 azel = me.measure(dir,'azel') # Convert to azimuth/elevation
2538 print 'az,el=', qa.angle(azel['m0']), qa.angle(azel['m1']) # Format nicely
2539 #az,el= +105.15.47 -024.22.57
2540 meas2=ia.coordmeasures() # defaults to reference pixel
2541 print meas2['intensity']
2542 #{'value': 2.5064315795898438, 'unit': 'Jy/beam'}
2543 print meas2['measure']['direction']
2544 #{'type': 'direction',
2545 # 'm1': {'value': 0.0, 'unit': 'rad'},
2546 # 'm0': {'value': 0.0, 'unit': 'rad'}, 'refer': 'J2000'}
2547 dir = meas2['measure']['direction'] # Get direction coordinate
2548 me.doframe(me.observatory('ATCA')) # Set location on earth
2549 me.doframe(me.epoch('utc','16jun1999/12:30:20')) # Set epoch
2550 azel = me.measure(dir,'azel') # Convert to azimuth/elevation
2551 print 'az,el=', qa.angle(azel['m0']), qa.angle(azel['m1'])
2552 #az,el= +105.16.05 -024.23.00
2553 #
2557 In this example we first find the world coordinates of the centre of the
2558 image. Then we use the Measures tool {stf me} to convert the
2559 {cf direction coordinate} field from J2000 to an azimuth and elevation
2560 at a particular location at a particular time.
2562 --------------------------------------------------------------------------------
2564 """
2565 return _image.image_coordmeasures(self, *args, **kwargs)
2568 def decompose(self, *args, **kwargs):
2569 """
2570 decompose(self, _region, _mask, _simple, _threshold, _ncontour, _minrange, _naxis, _fit, _maxrms, _maxretry, _maxiter, _convcriteria, _stretch) -> record *
2574 Summary:
2575 Separate a complex image into individual components
2577 Description:
2580 This function is an image decomposition tool that performs several tasks,
2581 with the end result being that a strongly blended image is separated into
2582 components - both in the sense that it determines the parameters for each
2583 component (assuming a Gaussian model) and that it physically assigns each
2584 pixel in the image to an individual object. The products of these two
2585 operations are called the component list and the component map,
2586 respectively. The fitting process (which determines the component list) and
2587 the pixel-decomposition process (which determines the component map) are
2588 designed to work cooperatively to increase the efficiency and accuracy of
2589 both.
2591 The algorithm behind the decomposition is based on the function clfind,
2592 described in Williams et al 1994, which uses a contouring procedure whereby
2593 a closed contour designates a separate component. The program first
2594 separates the image into clearly distint 'regions' of blended emission, then
2595 contours each region to determine the areas constituting each component and
2596 passes this information on to the fitter, which determines the component
2597 list.
2599 The contour deblending can optionally be replaced with a simpler local maximum
2600 scan, and the fitting can be replaced with a moment-based estimation method to
2601 speed up calculations on very large images or if either primary method causes
2602 trouble, but in general this will impede the accuracy of the fit.
2604 The function works with both two and three dimensional images.
2606 The return value is a record (or dictionary) that has 3 keys: {tt 'components', 'blc', 'trc'}.
2607 The {tt 'components'} element is a matrix each row of which contains the gaussian parameters of the component fitted.
2608 The {tt 'blc'} element is a matrix of the bottom left corners (blc) of the regions found. Each row correspond to a region blc.
2609 The {tt 'trc'} element is a matrix of the top right corners (trc) of the regions found. Each row correspond to a region trc.
2610 {bf Please Note} that the returned blc's and trc's are relative to {tt region} defined by the user. A {tt 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.
2613 Input Parameters:
2614 region Region selection. Default is to use the full image.
2615 mask Mask to use. Default is none.
2616 simple Skip contour deblending and scan for local maxima
2617 threshold Value of minimum positive contour. Must be set and nonnegative.
2618 ncontour Number of contours to use in deblending (>= 2)
2619 minrange Minimum number of closed contours in a component (> 0)
2620 naxis Max number of perpendicular steps between contiguous pixels. Values of 1, 2 or 3 are allowed.
2621 fit Fit to the components after deblending?
2622 maxrms Maximum RMS of fit residuals to not retry fit (> 0). Default is unset.
2623 maxretry Maximum number of times to retry the fit (>= 0). Default is unset.
2624 maxiter Maximum number of iterations allowed in a single fit (> 0)
2625 convcriteria Criterion to establish convergence (>=0)
2626 stretch Stretch the mask if necessary and possible?
2628 Example:
2631 #
2632 print 't----t decompose Ex 1 t----'
2633 ia.maketestimage()
2634 out=ia.decompose(threshold=2.5, maxrms=1.0)
2635 #Attempt 1: Converged after 21 iterations
2636 #Attempt 1: Converged after 15 iterations
2637 #1: Peak: 17.955 Mu: [0.000327928, 8.62573e-05]
2638 # Axes: [0.00175981, 0.00142841] Rotation: 1.29539
2639 #2: Peak: 19.8093 Mu: [1.67927e-06, -0.000374393]
2640 # Axes: [0.00179054, 0.00132541] Rotation: 1.78404
2641 #3: Peak: 10.1155 Mu: [6.28252, -7.09688e-05]
2642 # Axes: [0.00180877, 0.00104523] Rotation: 1.78847
2643 print out['components']
2644 #[[ 1.79549522e+01 3.27928370e-04 8.62573434e-05 1.75980886e-03
2645 # 8.11686337e-01 1.29538655e+00]
2646 # [ 1.98093319e+01 1.67927124e-06 -3.74393392e-04 1.79054437e-03
2647 # 7.40229547e-01 1.78403902e+00]
2648 # [ 1.01155214e+01 6.28252172e+00 -7.09688029e-05 1.80877140e-03
2649 # 5.77867746e-01 1.78847444e+00]]
2650 print out['blc']
2651 #[[37 31]
2652 # [47 25]
2653 # [67 33]]
2654 print out['trc']
2655 #[[54 47]
2656 # [66 38]
2657 # [78 40]]
2658 ia.close()
2659 #
2662 --------------------------------------------------------------------------------
2664 """
2665 return _image.image_decompose(self, *args, **kwargs)
2668 def deconvolvecomponentlist(self, *args, **kwargs):
2669 """
2670 deconvolvecomponentlist(self, _complist, _channel, _polarization) -> record *
2674 Summary:
2675 Deconvolve a componentlist from the restoring beam
2677 Description:
2681 This method deconvolves (a
2682 record representation of) a Componentlist tool from the restoring
2683 beam, returning (a record representation of) a new Componentlist tool.
2684 If there is no restoring beam, a fail is generated.
2686 Currently, only deconvolution of Gaussian components is supported.
2688 For images with per-plane beam, the user must choose which beam is used for
2689 the deconvolution by setting channel and/or polarization. Only a single beam
2690 is used to deconvolve all components.
2692 See also functions setrestoringbeam and
2693 restoringbeam.
2695 Input Parameters:
2696 complist Componentlist to deconvolve
2697 channel Zero-based channel number to use for beam for per plane images. Not used if the image has a single beam.
2698 polarization Zero-based polarization number to use for beam for per plane images. Not used if the image has a single beam.
2700 Example:
2703 #
2704 print 't----t deconvolvecomponentlist Ex 1 t----'
2705 ia.maketestimage()
2706 r = ia.fitcomponents()
2707 cl1 = r['results'] # cl1 and cl2 are record representations
2708 r = ia.fitcomponents()
2709 cl1 = r['results'] # cl1 and cl2 are record representations
2710 cl2 = ia.deconvolvecomponentlist(cl1) # of componentlists
2711 print cl1, cl2
2712 cl.fromrecord(cl2) # set componentlist tool with record
2713 ia.close()
2714 cl.close()
2715 #
2718 --------------------------------------------------------------------------------
2720 """
2721 return _image.image_deconvolvecomponentlist(self, *args, **kwargs)
2724 def deconvolvefrombeam(self, *args, **kwargs):
2725 """
2726 deconvolvefrombeam(self, _source, _beam) -> record *
2730 Summary:
2731 Helper function to deconvolve the given source Gaussian from a beam Gaussian to return a model Gaussian
2733 Description:
2737 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.
2739 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
2741 Input Parameters:
2742 source Three quantities that define the source majoraxis, minoraxis and Position angle
2743 beam Three quantities that define the beam majoraxis, minoraxis and Position angle
2745 Example:
2748 #
2749 print 't----t deconvolvefrombeam Ex 1 t----'
2750 ia.maketestimage()
2751 recout=ia.deconvolvefrombeam(source=['5arcmin', '3arcmin', '20.0deg'], beam=['50arcsec','30arcsec', '15deg'])
2752 ia.close()
2753 print 'Is pointsource ', recout['return']
2754 print 'major=',recout['fit']['major']
2755 print 'minor=',recout['fit']['minor']
2756 print 'pa=',recout['fit']['pa']
2763 --------------------------------------------------------------------------------
2765 """
2766 return _image.image_deconvolvefrombeam(self, *args, **kwargs)
2769 def beamforconvolvedsize(self, *args, **kwargs):
2770 """
2771 beamforconvolvedsize(self, _source, _convolved) -> record *
2775 Summary:
2776 Determine the size of the beam necessary to convolve with the given source to reach the given convolved (source+beam) size
2778 Description:
2781 Determine the size of the beam necessary to convolve with the given source to reach the
2782 given convolved (source+beam) size. Because the problem is completely specified by the
2783 input parameters, no image needs to be attached to the associated tool; eg ia.open() need
2784 not be called prior to calling this method.
2786 Input Parameters:
2787 source Three quantities that define the deconvolved source major axis, minor axis and position angle
2788 convolved Three quantities that define the convolved source (source+beam) major axis, minor axis and position angle. Do not specify if beam is specified.
2790 Example:
2792 # get the beam necessary to convolve the specified source with to achieve the target convolved source size (source convolved with beam).
2793 beam = ia.beamforconvolvedsize(source=['1arcsec', '1arcsec', '0deg'], convolved='3arcsec', '2arcsec', '45deg'])
2795 --------------------------------------------------------------------------------
2797 """
2798 return _image.image_beamforconvolvedsize(self, *args, **kwargs)
2801 def commonbeam(self):
2802 """
2803 commonbeam(self) -> record *
2807 Summary:
2808 Determine a beam to which all beams in an image can be convolved.
2810 Description:
2813 Determine a beam to which all beams in an image can be convolved.
2814 If the image does not have a beam, an exception will be thrown.
2815 If the image has a single beam, that beam will be returned.
2816 If the image has multiple beams, this will be the beam with the largest area in the image
2817 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
2818 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
2819 largest area. Otherwise, the returned beam may or may not be the smallest possible beam to which all the beams in the set
2820 can be convolved.
2823 Example:
2825 ia.open('mymultibeamimage.im')
2826 cb = ia.commonbeam()
2827 # convolve all the planes in the image with that beam
2828 ia.convolve2d(outfile='myconvolvedimage.im', major=cb['major], minor=cb['minor'], pa=cb['pa'], targetres=True)
2830 --------------------------------------------------------------------------------
2832 """
2833 return _image.image_commonbeam(self)
2836 def remove(self, *args, **kwargs):
2837 """
2838 remove(self, _done, _verbose) -> bool
2842 Summary:
2843 Delete the image file associated with this image tool
2845 Description:
2849 This function first closes the
2850 imagetool which detaches it from its underlying imagefile. It then
2851 deletes that imagefile. If {stfaf done=False}, the imagetool is still
2852 viable, and can be used with function open
2853 to open a new imagefile. Otherwise the imagetool is destroyed. If {stfaf verbose=True}, the logger will receive a progress report.
2855 Input Parameters:
2856 done Destroy this tool after deletion
2857 verbose Send a progress report to the logger.
2859 Example:
2862 #
2863 print 't----t remove Ex 1 t----'
2864 ia.maketestimage('myimage',overwrite=true)
2865 ia.close()
2866 ia.maketestimage('myotherimage',overwrite=true)
2867 ia.close()
2868 ia.open('myimage') # Attach to 'myimage'
2869 ia.remove(F) # Close imagetool and delete 'myimage'
2870 ia.open('myotherimage') # Open new imagefile 'myotherimage'
2871 ia.remove()
2872 print '!!!EXPECT THE FOLLOWING TO GENERATE AN ERROR MESSAGE!!!'
2873 ia.open('myimage') # 'myimage' was deleted above
2874 ia.close()
2875 #
2878 --------------------------------------------------------------------------------
2880 """
2881 return _image.image_remove(self, *args, **kwargs)
2884 def removefile(self, *args, **kwargs):
2885 """
2886 removefile(self, _file) -> bool
2890 Summary:
2891 Delete an unattached image file from disk. Note: use remove() if the image file is attached to the image tool.
2893 Description:
2896 This function deletes the specified image file.
2898 Input Parameters:
2899 file Name of image file/directory to be removed. Must be specified.
2901 Example:
2904 #
2905 print 't----t removefile Ex 1 t----'
2906 ia.maketestimage('myimage',overwrite=true)
2907 ia.close()
2908 ia.removefile('myimage') # remove image 'myimage'
2909 ia.maketestimage('myimage',overwrite=false) # error here if 'myimage' exists
2910 ia.close()
2911 ia.removefile('myimage')
2912 #
2915 --------------------------------------------------------------------------------
2917 """
2918 return _image.image_removefile(self, *args, **kwargs)
2921 def done(self, *args, **kwargs):
2922 """
2923 done(self, _remove, _verbose) -> bool
2927 Summary:
2928 Destroy this image tool
2930 Description:
2934 When the user no longer needs to use an imagetool, calling this function
2935 will free up its resources. That is, it destroys the tool. This means
2936 that the user can no longer call any functions on the tool after it
2937 has been {stff done}.
2939 If the Image tool is associated with a disk file, then (unlike the
2940 {stff close} function, the user can also choose to delete that by
2941 setting {stfaf remove=true}. By default, any associated disk file is
2942 not deleted.
2944 Note that this function is different from the {stff close} function
2945 because the latter does not destroy the imagetool. For example, the
2946 user can use the {stff open} function straight after the {stff close}
2947 function on the same tool.
2949 Input Parameters:
2950 remove Delete the associated disk file as well?
2951 verbose Send a progress report to the logger?
2953 Example:
2956 #
2957 print 't----t done Ex 1 t----'
2958 # Make a test image and create tool subim:
2959 ia.maketestimage('myfile',overwrite=true)
2960 subim = ia.subimage('myfile2',overwrite=true)
2961 # Check that subim exists as intended by attempting to display its summary:
2962 subim.summary() # This displays a summary of the dataset.
2963 # Use done to destroy the subim tool:
2964 subim.done()
2965 # Check that the subim tool has been detached as intended, by attempting to display its summary:
2966 subim.summary() # This should now throw an error.
2967 ia.summary() # This still works, though, as the ia tool is still open, and the dataset is still available.
2968 ia.close()
2969 #
2972 --------------------------------------------------------------------------------
2974 """
2975 return _image.image_done(self, *args, **kwargs)
2978 def fft(self, *args, **kwargs):
2979 """
2980 fft(self, _real, _imag, _amp, _phase, _axes, _region, _mask, _stretch, _complex) -> bool
2984 Summary:
2985 FFT the image
2987 Description:
2991 This method fast Fourier Transforms the supplied image to the Fourier plane.
2992 If the axes parameter is left unset, then the direction plane of the image (if
2993 there is one) is transformed. Otherwise, the user can specify which axes are
2994 to be transformed. Note that if the direction plane is to be transformed, both
2995 axes associated with it must be specified.
2997 The user specifies which form is desired in the result by specifying the
2998 desired output image file name(s).
3000 Before the FFT is performed, any masked pixels are set to values of zero. The
3001 output mask is the result of ANDing the default input pixel mask (if any) and
3002 the OTF mask. Any other input pixel masks will not be copied. The method
3003 maskhandler() can be used if there is a need to copy other masks.
3005 The following rules are used to set the brightness units of the output images.
3006 1. The phase image always has units of radians.
3007 For the other output images,
3008 2. if the input image has units of Jy/beam or Jy/pixel
3009 (ie it is an image-plane image), the output (uv-plane) images will have units
3010 of Jy. In the case of the input image having a synthesized beam, the beam
3011 will be copied to the output images (which is important for transforming back).
3012 3. If the input image has units of Jy (ie is a uv-plane image), the output
3013 images will have either units of Jy/beam or Jy/pixel, depending on if the
3014 input image has a beam or not.
3016 For some transformations (e.g., UV domain to image domain transforms), it is
3017 not possible to automatically generate an expected coordinate system for
3018 the output image(s); only the FFT numerics are performed and the coordinate
3019 system is generated using generic conventions.
3021 Input Parameters:
3022 real Output real image file name.
3023 imag Output imaginary image file name.
3024 amp Output amplitude image file name.
3025 phase Output phase image file name.
3026 axes Specify the pixel axes that are to undergo the FFT. The default option (-1) is to transform the sky plane(s).
3027 region Region selection. Default is to use the full image.
3028 mask The mask to be used. The default option is none.
3029 stretch Stretch the mask if it is necessary and possible.
3030 complex Output complex valued image file name.
3032 Example:
3035 #
3036 print 't----t fft Ex 1 t----'
3037 # Create a test image:
3038 ia.maketestimage('gc.small', overwrite=true)
3039 # Perform an FFT on the sky plane of the test image,
3040 # writing out just the resulting real and amplitude images:
3041 ia.fft(real='r.im', amp='a.im')
3042 # Close the image tool when done:
3043 ia.close()
3044 # Lastly, clean up the example output files:
3045 ia.removefile('r.im')
3046 ia.removefile('a.im')
3047 #
3053 #
3054 print 't----t fft Ex 2 t----'
3055 # Create a zero-filled 3D test dataset and add noise to it:
3056 ia.fromshape('gc.small', [64,64,128], overwrite=true)
3057 ia.addnoise(type='normal', pars=[0.5, 1], zero=false)
3058 # The following transforms only the third axis of the image.
3059 # writing out only the amplitude and phase images.
3060 ia.fft(amp='amp.im', phase='p.im', axes=[2])
3061 # Close the image tool when done:
3062 ia.close()
3063 # Lastly, clean up the example output files:
3064 ia.removefile('amp.im')
3065 ia.removefile('p.im')
3066 #
3069 --------------------------------------------------------------------------------
3071 """
3072 return _image.image_fft(self, *args, **kwargs)
3075 def findsources(self, *args, **kwargs):
3076 """
3077 findsources(self, _nmax, _cutoff, _region, _mask, _point, _width, _negfind) -> record *
3081 Summary:
3082 Find point sources in the sky
3084 Description:
3088 This function finds strong point sources in
3089 the image. The sources are returned in a record that can be used by a
3090 Componentlist tool.
3092 An efficient method is used to locate sources under the assumption that
3093 they are point-like and not too close to the noise. Only sources with a
3094 peak greater than the {stfaf cutoff} fraction of the strongest source
3095 will be found. Only positive sources will be found, unless the {stfaf
3096 negfind=T} whereupon positive and negative sources will be found.
3098 After the list of point sources has been made, you may choose to make a
3099 Gaussian fit for each one ({stfaf point=F}) so that shape information
3100 can be recovered as well. You can specify the half-width of the
3101 fitting grid with argument {stfaf width} which defaults to 5 (fitting
3102 grid would then be [11,11] pixels). If you set {stfaf width=0}, this is
3103 a signal that you would still like Gaussian components returned, but a
3104 default width should be used for the Gaussian shapes. The default is
3105 such that the component is circular with a FWHM of {stfaf width}
3106 pixels.
3108 Thus, if {stfaf point=T}, the components in the returned Componentlist
3109 are Point components. If {stfaf point=F} then Gaussian components are
3110 returned.
3112 The region must be 2-dimensional and it must hold a region of the sky.
3113 Any degenerate trailing dimensions in the region are discarded.
3115 See also the function fitcomponents (for which {stff
3116 findsources} can provide an initial estimate).
3118 Input Parameters:
3119 nmax Maximum number of sources to find, > 0
3120 cutoff Fractional cutoff level
3121 region Region selection. Default is to use the full image.
3122 mask Mask to use. Default is none.
3123 point Find only point sources?
3124 width Half-width of fit grid when point=F
3125 negfind Find negative sources as well as positive?
3127 Example:
3130 #
3131 print 't----t findsources Ex 1 t----'
3132 ia.maketestimage()
3133 clrec = ia.findsources(nmax=5, cutoff=0.5)
3134 print clrec
3135 #
3139 All sources stronger than 0.5 of the strongest will be found.
3140 We use the Componentlist GUI to look at the strongest component.
3142 --------------------------------------------------------------------------------
3144 """
3145 return _image.image_findsources(self, *args, **kwargs)
3148 def fitprofile(self, *args, **kwargs):
3149 """
3150 fitprofile(self, _box, _region, _chans, _stokes, _axis, _mask, _ngauss, _poly, _estimates, _minpts, _multifit, _model, _residual, _amp, _amperr, _center, _centererr, _fwhm, _fwhmerr, _integral, _integralerr, _stretch, _logresults, _pampest, _pcenterest, _pfwhmest, _pfix, _gmncomps, _gmampcon, _gmcentercon, _gmfwhmcon, _gmampest, _gmcenterest, _gmfwhmest, _gmfix, _spxtype, _spxest, _spxfix, _div, _spxsol, _spxerr, _logfile, _append, _pfunc, _goodamprange, _goodcenterrange, _goodfwhmrange, _sigma, _outsigma, _planes) -> record *
3154 Summary:
3155 Fit gaussians and/or polynomials to a 1-dimensional profile.
3157 Description:
3160 This application simultaneously fits any number of gaussian singlets, any number of lorentzian singlets, and any number of gaussian multiplets,
3161 and/or a polynomial to one dimensional profiles using the non-linear, least squares Levenberg-Marquardt algorithm. A description of the
3162 fitting algorithm may be found in AIPS++ Note 224 (http://www.astron.nl/casacore/trunk/casacore/doc/notes/224.html) and in Numerical Recipes
3163 by W.H. Press et al., Cambridge University Press. A gaussian/lorentzian singlet is a gaussian/lorentzian whose parameters (amplitude,
3164 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
3165 more gaussian lines in which at least one (and possibly two or three) parameter of each line is dependent on the parameter of another,
3166 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
3167 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
3168 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
3169 (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
3170 a single reference profile in a multiplet to which to tie constraints of parameters of the other profiles in the set.
3172 Additionally, a power logarithmic polynomial (plp) or a logarithmic tranformed polynomial (ltp) can be fit. In this case, each of these functions
3173 cannot be fit simultaneously with any other supported function. These functions are most often used for fitting the spectral index and
3174 higher order terms of a spectrum. A power logarithmic polynomial has the form
3176 y = c0*x/div**(c1 + c2*ln(x/div) + c3*ln(x/div)**2 + ... + cn*ln(x/div)**(n - 1))
3178 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
3180 ln(y) = c0 + c1*ln(x/div) + c2*ln(x/div)**2 + ... + cn*ln(x/div)**n
3182 The coefficients of the two forms correspond with each other except that c0 in the second equation is equal to
3183 ln(c0) of the first. In the case of fitting a spectral index, the spectral index, traditionally represented as alpha, is
3184 equal to c1.
3186 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
3187 improves the probability that the fit will converge. This parameter may be specified via the div parameter. A value of 0
3188 (the default) indicates that the application should determine a reasonable value for div, which is determined via
3190 div = 10**int(log10(sqrt(min(x)*max(x))))
3192 where min(x) and max(x) are the minimum and maximum abscissa values, respectively.
3194 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
3195 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,
3196 or spxest=[0.405, -0.8] and div=1e9 if fitting an ltp function.
3198 More details of fitting all of these functions are described in following sections.
3200 A CAUTIONARY NOTE
3201 Note that the likelihood of getting a reliable solution increases with the number of good data points as well as the goodness
3202 of the initial estimate. It is possible that the first solution found might not be the best one, and
3203 so, if a solution is found, it is recommended that the fit be repeated using the solution of the previous fit as the
3204 initial estimatE for the new fit. This process should be repeated until the solutions from one fit to the next differ only insignificantly.
3205 The convergent solution is very likely the best solution.
3207 AXIS
3208 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,
3209 that the zeroth axis should be used.
3211 MINIMUM NUMBER OF PIXELS
3212 The minpts parameter indicates the minimum number of unmasked pixels that must be present in order for a fit
3213 to be attempted. When multifit=True, positions with too few good points will be masked in any output images.
3215 ONE FIT OF REGION AVERAGE OR PIXEL BY PIXEL FIT
3216 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
3217 averaged and the fit done to that average profile (false).
3219 POLYNOMIAL FITTING
3220 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
3221 coefficients can be specified; these are determined automatically.
3223 GAUSSIAN SINGLET FITTING
3224 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
3225 indicates the maximum number of gaussian singlets that should be fit. The initial estimates of the parameters for these gaussians will be attempted
3226 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,
3227 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,
3228 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,
3229 an error will occur as this indicates there is nothing to fit.
3231 One can specify initial estimates of gaussian singlet parameters via an estimates file or the pampest, pcenterest, pfwhmest, and optionally, the
3232 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
3233 which option is used, an amplitude initial estimate must always be nonzero. A negative fwhm estimate will be silently changed to positve.
3235 SPECIFYING INITIAL ESTIMATES FOR GAUSSIAN AND LORENTZIAN SINGLETS (RECOMMENDED METHOD)
3236 One may specify initial estimates via the pampest, pcenterest, and pfwhmest parameters. In the case of a single gaussian or lorentzian singlet,
3237 these parameters can be numbers. pampest must be specified in image brightness units, pcenterest must be given in the number of pixels from the
3238 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
3239 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'
3240 (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
3241 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
3242 the same for all the p*est parameters.
3244 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
3245 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
3246 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
3247 one, one must specify pfix=['', 'f', ''], the empty strings indicating no parameters of the zeroth and second singlet should be held constant.
3249 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
3250 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
3251 attempted fit fails, the fitting proceeds to the next pixel with the pixel value of the lowest numbered axis changing the fastest. Once a
3252 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
3253 initial estimate for the parameters at the current location. The fixed parameter string will be honored for every fit performed when multifit=True.
3255 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,
3256 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
3257 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
3258 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
3259 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
3260 singlets, the zeroth and last of which were lorentzians, one would specify pfunc=['L', 'G', 'G', 'L'].
3262 ESTIMATES FILE FOR GAUSSIAN SINGLETS (NONRECOMMENDED METHOD)
3263 Initial estimates for gaussian singlets can be specified in an estimates file. Estimates files may be deprecated in the future in favor of the
3264 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
3265 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
3266 more gaussian multiplets and/or one or more lorentzian singlets simultaneously, the p*est parameters must be used to specify the initial parameters
3267 of all gaussian singlets to fit; one cannot use an estimates file in this case. If an estimates file is specified, a polynomial
3268 can be fit simultaneously by specifying the poly parameter. The estimates file must contain initial estimates of parameters
3269 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
3270 comments which are indicated by a '#' at the beginning of a line. All non-comment lines will be interpreted as initial estimates. The
3271 format of such a line is
3273 [peak intensity], [center], [fwhm], [optional fixed parameter string]
3275 The first three values are required and must be numerical values. The peak intensity must be expressed in image brightness units, while the
3276 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,
3277 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
3278 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
3279 example file:
3281 begin{verbatim}
3282 # estimates file indicating that two gaussians should be fit
3283 # first guassian estimate, peak=40, center at pixel number 10.5, fwhm = 5.8 pixels, all parameters allowed to vary during
3284 # fit
3285 40, 10.5, 5.8
3286 # second gaussian, peak = 4, center at pixel number 90.2, fwhm = 7.2 pixels, hold fwhm constant
3287 4, 90.2, 7.2, f
3288 # end file
3289 end{verbatim}
3291 GAUSSIAN MULTIPLET FITTING
3292 Any number of gaussian multiplets, each containing any number of two or more components, can be simultaneously fit, optionally with a
3293 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
3294 significantly less than the number of data points. The gmncomps parameter indicates the number of multiplets to fit and the number of
3295 components in each multiplet. In the case of a single multiplet, an integer (>1) can be specified. For example, mgncomps=4 means fit a
3296 single quadruplet of gaussians. In the case of 2 or more multiplets, and array of integers (all >1) must be specified. For example,
3297 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
3298 being a triplet.
3300 Initial estimates of all gaussians in all multiplets are specified via the gm*est parameters which must be arrays of numbers. The order
3301 starts with the zeroth component of the zeroth multiplet to the last component of the zeroth multiplet, then the zeroth component of
3302 the first multiplet to the last compoenent of the first multiplet, etc to the zeroth component of the last multiplet to the last
3303 element of the last multiplet. The zeroth element of a multiplet is defined as the reference component of that multiplet and has the special
3304 significance that it is the profile to which all constraints of all other profiles in that multiplet are referenced (see below). So,
3305 in our example of gmncomps=[2, 4, 3], gmampest, gmcenterest, and gmfwhmest must each be nine (the total number of individual gaussian
3306 profiles summed over all multiplets) element arrays. The zeroth, second, and sixth elements represent parameters of the reference profiles
3307 in the zeroth, first, and second multiplet, respectively.
3309 The fixed relationships between the non-reference profile(s) and the reference profile of a multiplet are specified via the gmampcon,
3310 gmcentercon, and gmfwhmcon parameters. At least one, and any combination, of constraints can be specified for any non-reference
3311 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
3312 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
3313 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
3314 non-reference line of any multiplet, the value of the associated parameter must be 0. In the case of
3315 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
3316 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
3317 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
3318 of a total of three or more gaussians, the constraints parameters must be specified as arrays with lengths equal to the total number
3319 of gaussians summed over all multiplets minus the number of reference lines (one per multiplet, or just number of multiplets, since
3320 reference lines cannot be constrained by themselves). In the cases where an array must be specified but a component in that array
3321 does not have that constraint, 0 should be specified. Here's an example
3323 gmncomps=[2, 4, 3]
3324 gmampcon= [ 0 , 0.2, 0 , 0.1, 4.5, 0 ]
3325 gcentercon=[24.2, 45.6, 92.7, 0 , -22.8, -33.5]
3326 gfwhmcon=''
3328 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
3329 that its center is offset by 24.2 pixels from the zeroth (reference) component. The first component of the quadruplet is constrained to have
3330 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
3331 reference component. The second component of the quadruplet is constained to have its center offset by 92.7 pixels from the associated
3332 reference component and the third component is constrained to have an amplitude of 0.1 times that of the associated reference component.
3333 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
3334 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
3335 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
3336 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
3337 position as the reference component but having a different FWHM from the reference component. If you must specify this very unusual case,
3338 try using a very small positive (or even negative) value for the center constraint.
3340 Note that when a parameter for a line is constrained, the corresponding value for that component in the corresponding gm*est array is
3341 ignored and the value of the constrained parameter is automatically used instead. So let's say, for our example above, we had specified
3342 the following estimates:
3344 gmampest = [ 1, .2, 2, .1, .1, .5, 3, 2, 5]
3345 gmcenterest = [20, 10 , 30, 45.2, 609 , -233, 30, -859, 1]
3347 Before any fitting is done, the constraints would be taken into account and these arrays would be implicitly rewritten as:
3349 gmampest = [ 1, .2, 2, .4, .1, .2, 3, 13.5, 5 ]
3350 gmcenterest = [20, 44.2, 30, 75.6, 127.7, -233, 30, 7.2, -3.5]
3352 The value of gmfwhmest would be unchanged since there are no FWHM constraints in this example.
3354 In addition to be constrained by values of the reference component, parameters of individual components can be fixed. Fixed parameters
3355 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
3356 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
3357 components summed over all multiplets. These strings encode which parameters to be fixed for the corresponding components. If
3358 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
3359 be fixed using 'p', 'c', and/or 'f' described above for fixing singlet parameters. There are a couople of special cases
3360 to be aware of. In the case where a non-reference component parameter is constrained and the corresponding reference component parameter is
3361 set as fixed, that parameter in the non-reference parameter will automatically be fixed even if it was specified not to be fixed in
3362 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
3363 non-reference component is specified as fixed, but the corresponding parameter in the reference component is not specified to be fixed,
3364 an error will occur. Fixing an unconstrained parameter in a non-reference component is always legal as is fixing any combination of
3365 parameters in a reference component (with the above caveat that corresponding constrained parameters in non-reference components will
3366 be silently held fixed as well).
3368 The same rules that apply to singlets when multifit=True apply to multiplets.
3370 LIMITING RANGES FOR SOLUTION PARAMETERS
3371 In cases of low (or no) signal to noise spectra, it is still possible for the fit to converge, but often to a
3372 nonsensical solution. The astronomer can use her knowledge of the source to filter out obviously bogus solutions.
3373 Any solution which contains a NaN value as a value or error in any one of its parameters is automatically marked as
3374 invalid.
3376 One can also limit the ranges of solution parameters to known 'good' values via the goodamprange, goodcenterrange, and goodfwhmrange
3377 parameters. Any combination can be specified and the limit constraints will be ANDed together. The ranges apply to all PCF components
3378 that might be fit; choosing ranges on a component by component basis is not supported. If specified,
3379 an array of exactly two numerical values must be given to indicate the range of acceptable solution values for
3380 that parameter. goodamprange is expressed in terms of image brightness units. goodcenterrange is expressed in terms of pixels
3381 from the zeroth pixel in the specified region. goodfwhmrange is expressed in terms of pixels (only non-negative values should be
3382 given for FWHM range endpoints). In the case of a multiple-PCF fit, if any of the corresponding solutions are outside the specified
3383 ranges, the entire solution is considered to be invalid.
3385 In addition, solutions for which the absolute value of the ratio of the amplitude error to the amplitude exceeds 100 or the
3386 ratio of the FWHM error to the FWHM exceeds 100 are automatically marked as invalid.
3388 POWER LOGARITHMIC POLYNOMIAL AND LOGARITHMIC TRANSFORMED POLYNOMIAL FITTING
3389 Fitting of a sngle power logarithmic polynomial or a single logarithmic transformed polynomial function is supported.
3390 No other functions may be fit simultaneously with either of these; if parameters relating to other functions are supplied
3391 simultaneously with parameters relating
3392 to these functions, an exception will occur. For details of the functional forms, see the introduction of this
3393 document.
3395 The set of c0 ... cn coefficients (as defined previously) can
3396 be solved for. Initial estimates for the c values should be supplied via the plpest or ltpest parameters, depending on which
3397 form is being fit. The number of values given
3398 in this array will be the number of coeffecients that are solved for. One may specify which coefficients should be held
3399 fixed during the fit in the plpfix or ltpfix array. If supplied, this array should have the same number of elements as its respective
3400 initial estimates array. A value
3401 of True means the corresponding coefficient will be held fixed during the fit. An empty array indicates that no
3402 parameters will be held fixed. This is the default.
3404 Because the logarithm of the ordinate values must be taken before fitting a logarithmic transformed polynomial,
3405 all non-positive pixel values are effectively masked for the purposes of fitting.
3407 INCLUDING STANDARD DEVIATIONS OF PIXEL VALUES
3408 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
3409 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
3410 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
3411 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
3412 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
3413 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.
3414 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
3415 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.
3416 The weight of a pixel is the usual
3418 weight = 1/(sigma*sigma)
3420 In the case of multifit=False, the sigma values at each pixel along the fit axis in the hyperplane perpendicular to the fit axis which includes
3421 that pixel are averaged and the resultant averaged standard deviation spectrum is the one used in the fit. Internally, sigma values are normalized
3422 such that the maximum value is 1. This mitigates a known overflow issue.
3424 One can write the normalized standard deviation image used in the fit but specifying its name in outsigma. This image can then be
3425 used as sigma for subsequent runs.
3428 RETURNED DICTIONARY STRUCTURE
3429 The returned dictionary has a (necessarily) complex structure. First, there are keys 'xUnit' and 'yUnit' whose values are
3430 the abscissa unit and the ordinate unit described by simple strings. Next there are arrays giving a broad overview of the
3431 fit quality. These arrays have the shape of the specified region collapsed along the fit axis with the axis corresponding to the fit
3432 axis having length of 1:
3434 attempted: a boolean array indicating which fits were attempted (eg if too few unmasked points, a fit will not be attempted).
3435 converged: a boolean array indicating which fits converged. False if the fit was not attempted.
3436 valid: a boolean array indicating which solutions fall within the specified valid ranges of parameter space (see
3437 . section LIMITING RANGES FOR SOLUTION PARAMETERS for details).
3438 niter: an int array indicating the number of iterations for each profile, <0 if the fit did not converge
3439 ncomps: the number of components (gaussian singlets + lorentzian singlets + gaussian multiplets + polynomial) fit for the profile,
3440 . <0 if the fit did not converge
3441 direction: a string array containing the world direction coordinate for each profile
3443 There is a 'type' array having number of dimensions equal to the number of dimensions in the above arrays plus one. The shape of
3444 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
3445 components fit. The values of this array are strings describing the components that were fit at each possition ('POLYNOMIAL',
3446 'GAUSSIAN' in the case of gaussian singlets, 'LORENTZIAN' in the case of lorentzian singlets, and ''GAUSSIAN MULTPLET').
3448 If any gaussian singlets were fit, there will be a subdictionary accessible via the 'gs' key which will have subkeys 'amp', 'ampErr', 'center',
3449 'centerErr', 'fwhm', 'fwhmErr, 'integral', and 'integralErr'. Each of these arrays will have one more dimension than the overview arrays described
3450 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
3451 have length equal to the maximum number of gaussian singlets that were fit. Along this axis will be the
3452 corresponding fit result or associated error (depending on the array's associated key) of the fit for that singlet component number. In cases where
3453 the fit did not converge, or that particular component was excluded from the fit, a value of NAN will be present.
3455 If any lorentzian singlets were fit, their solutions will be accessible via the 'ls' key. These arrays follow the same rules
3456 as the 'gs' arrays described above.
3458 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
3459 muliplets that were fit. Each of these dictionaries will have the same arrays described above for gaussian singlets. The last dimension
3460 will have length equal to the number of components in that particular multiplet. Each pixel along the last axis will be the parameter solution
3461 value or error for that component number in the multiplet, eg the zeroth pixel along that axis contains
3462 the parameter solution or error for the reference component of the multiplet.
3464 The polynomial coefficient solutions and errors are not returned, although they are logged.
3466 If a power logarithmic polynomial was fit, there will be a subdictionary accessible via the 'plp' key which will have
3467 subkeys 'soltuion' and 'error' which will each have an array value. Each of these arrays will have one more dimension than the overview arrays
3468 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
3469 final dimension will have length equal to the number of parameters that were fit. Along this axis will be the
3470 corresponding fit result or associated error (depending on the array's associated key) of the fit. In cases where
3471 the fit was not attempted or did not converge, a value of NAN will be present.
3473 OUTPUT IMAGES
3474 In addition to the returned dictionary, optionally one or more of any combination of output images can be written.
3475 The model and residual parameters indicate the names of the model and residual images to be written; blank values inidcate that these images
3476 should not be written.
3478 One can also write none, any or all of the solution and error images for gaussian singlet, lorentzian singlet, and gaussian multiplet fits
3479 via the parameters amp, amperr, center, centererr, fwhm, fwhmerr, integral, integralerr when doing multi-pixel fits. For a power logarithmic
3480 polynomial or a logarithmic transformed polynomial fit, plpsol or ltpsol and plperr or ltpsol are the names of the solution and error
3481 images to write, respectively.
3483 These images contain the arrays described for the associated parameter solutions or errors described in previous sections. Each
3484 component is written to a different image, and each image is distiguished by the component it represents by its name ending
3485 in an uderscore and the relevant component number ('_0', '_1', etc). In the case of Gaussian multiplets, the image name ends
3486 with the number of the mulitplet group followed by the number of the component in that group (eg '_3_4' represents component
3487 4 in multiplet group 3). In the case of lorentzian singlets, '_ls' is appended to the image names (but before the
3488 identifying component number), in the case of gaussian multiplets. Similarly '_gm' is included in the name of Gaussian multiplet
3489 images. Pixels for which fits were not attempted, did not converge, or converged but have values of NaN (not a number) or
3490 INF (infinity) will be masked as bad.
3492 Writing analogous images for polynomial coefficients is not supported.
3496 Input Parameters:
3497 box Rectangular region to select in direction plane. Default is to use the entire direction plane.
3498 region Region selection. Default is to use the full image.
3499 chans Channels to use. Channels must be contiguous. Default is to use all channels..
3500 stokes Stokes planes to use. Planes must be contiguous. Default is to use all stokes planes.
3501 axis The profile axis. Default: use the spectral axis if one exists, axis 0 otherwise (<0).
3502 mask Mask to use. Default is none.
3503 ngauss Number of Gaussian elements. Default: 1.
3504 poly Order of polynomial element. Default: do not fit a polynomial (<0).
3505 estimates Name of file containing initial estimates. Default: No initial estimates ('').
3506 minpts Minimum number of unmasked points necessary to attempt fit.
3507 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.
3508 model Name of model image. Default: do not write the model image ('').
3509 residual Name of residual image. Default: do not write the residual image ('').
3510 amp Prefix of name of amplitude solution image. Name of image will have gaussian component number appended. Default: do not write the image ('').
3511 amperr Prefix of name of amplitude error solution image. Name of image will have gaussian component number appended. Default: do not write the image ('').
3512 center Prefix of name of center solution image. Name of image will have gaussian component number appended. Default: do not write the image ('').
3513 centererr Prefix of name of center error solution image. Name of image will have gaussian component number appended. Default: do not write the image ('').
3514 fwhm Prefix of name of FWHM solution image. Name of image will have gaussian component number appended. Default: do not write the image ('').
3515 fwhmerr Prefix of name of FWHM error solution image. Name of image will have gaussian component number appended. Default: do not write the image ('').
3516 integral Prefix of name of integral solution image. Name of image will have gaussian component number appended. Default: do not write the image ('').
3517 integralerr Prefix of name of integral error solution image. Name of image will have gaussian component number appended. Default: do not write the image ('').
3518 stretch Stretch the mask if necessary and possible?
3519 logresults Output results to logger?
3520 pampest Initial estimate PCF profile amplitudes.
3521 pcenterest Initial estimate PCF profile centers, in pixels.
3522 pfwhmest Initial estimate PCF profile FWHMs, in pixels.
3523 pfix PCF parameters to fix during fit. Any combination of 'p', 'c', or 'f'.
3524 gmncomps Number of components in each gaussian multiplet to fit
3525 gmampcon The amplitude ratio constraints for non-reference components to reference component in gaussian multiplets.
3526 gmcentercon The center offset constraints (in pixels) for non-reference components to reference component in gaussian multiplets.
3527 gmfwhmcon The FWHM ratio constraints for non-reference components to reference component in gaussian multiplets.
3528 gmampest Initial estimate of individual gaussian amplitudes in gaussian multiplets.
3529 gmcenterest Initial estimate of individual gaussian centers in gaussian multiplets, in pixels.
3530 gmfwhmest Initial estimate of individual gaussian FWHMss in gaussian multiplets, in pixels.
3531 gmfix Parameters of individual gaussians in gaussian multiplets to fix during fit.
3532 spxtype Type of function to fit. 'plp' $=>$ power logarithmic polynomial, 'ltp' $=>$ logarithmic transformed polynomial.
3533 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).
3534 spxfix Fix the corresponding spectral index function coefficients during the fit. True$=>$hold fixed.
3535 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.
3536 spxsol Name of the spectral index function coefficient solution image to write.
3537 spxerr Name of the spectral index function coefficient error image to write.
3538 logfile File in which to log results. Default is not to write a logfile.
3539 append Append results to logfile? Logfile must be specified. Default is to append. False means overwrite existing file if it exists.
3540 pfunc PCF singlet functions to fit. 'gaussian' or 'lorentzian' (minimal match supported). Unspecified means all gaussians.
3541 goodamprange Acceptable amplitude solution range. [0.0] $=>$ all amplitude solutions are acceptable.
3542 goodcenterrange Acceptable center solution range in pixels relative to region start. [0.0] $=>$ all center solutions are acceptable.
3543 goodfwhmrange Acceptable FWHM solution range in pixels. [0.0] $=>$ all FWHM solutions are acceptable.
3544 sigma Standard deviation array or image name.
3545 outsigma Name of output image used for standard deviations. Ignored if sigma is empty.
3546 planes Planes along fit axis to use in the fit. Empty means use all planes. All values must be non-negative.
3548 Example:
3551 ia.open('myspectrum.im')
3552 res = ia.fitprofile(ngauss=2, box='3,3,4,5', poly=2, multifit=true)
3555 --------------------------------------------------------------------------------
3557 """
3558 return _image.image_fitprofile(self, *args, **kwargs)
3561 def fitcomponents(self, *args, **kwargs):
3562 """
3563 fitcomponents(self, _box, _region, _chans, _stokes, _mask, _includepix, _excludepix, _residual, _model, _estimates, _logfile, _append, _newestimates, _complist, _overwrite, _dooff, _offset, _fixoffset, _stretch, _rms, _noisefwhm, _summary) -> record *
3567 Summary:
3568 Fit 2-dimensional models to an image.
3570 Description:
3574 OVERVIEW
3576 This application is used to fit one or more two dimensional gaussians to sources in an image as
3577 well as an optional zero-level offset. Fitting is limited to a single polarization
3578 but can be performed over several contiguous spectral channels.
3579 If the image has a clean beam, the report and returned dictionary will contain both the convolved
3580 and the deconvolved fit results.
3582 When dooff is False, the method returns a dictionary with keys named 'converged', 'pixelsperarcsec',
3583 'results', and 'deconvolved'. The value of 'converged' is a boolean array which indicates if the
3584 fit converged on a channel by channel basis. The value of 'pixelsperarcsec' is a two element double
3585 array with the absolute values of the direction coordinate pixel increments (longitude-like and
3586 latitude-like coordinate, respectively) in arcsec. The value of 'results' is a dictionary
3587 representing a component list reflecting the fit results. In the case of an image containing beam
3588 information, the sizes and position angles in the 'results' dictionary are those of the source(s)
3589 convolved with the restoring beam, while the same parameters in the 'deconvolved' dictionary
3590 represent the source sizes deconvolved from the beam. In the case where the image does not
3591 contain a beam, 'deconvolved' will be absent. Both the 'results' and 'deconvolved' dictionaries can
3592 be read into a component list tool (default tool is named cl) using the fromrecord() method for
3593 easier inspection using tool methods, eg
3595 cl.fromrecord(res['results'])
3597 although this only works if the flux density units are conformant with Jy.
3599 There are also values in each component subdictionary not used by cl.fromrecord() but meant to
3600 supply additional information. There is a 'peak' subdictionary for each component that provides the
3601 peak intensity of the component. It is present for both 'results' and 'deconvolved' components.
3602 There is also a 'sum' subdictionary for each component indicated the simple sum of pixel values in
3603 the the original image enclosed by the fitted ellipse. There is a 'channel' entry in the 'spectrum'
3604 subdictionary which provides the zero-based channel number in the input image for which the solution
3605 applies. In addtion, if the image has a beam(s), then there will be a 'beam' subdictionary associated
3606 with each component in both the 'results' and 'deconvolved' dictionaries. This subdictionary will
3607 have three keys: 'beamarcsec' will be a subdictionary giving the beam dimensions in arcsec,
3608 'beampixels' will have the value of the beam area expressed in pixels, and 'beamster' will have the
3609 value of the beam area epressed in steradians. Also, if the image has a beam(s), in the component level
3610 dictionaries will be an 'ispoint' entry with an associated boolean value describing if the component
3611 is consistent with a point source. Each component level dictionary will have a 'pixelcoords' entry
3612 which has the value of a two element numeric array which provides the direction pixel coordinates
3613 of the fitted position.
3615 If dooff is True, in addtion to the specified number of
3616 gaussians, a zero-level offset will also be fit. The initial estimate for this
3617 offset is specified using the offset parameter. Units are assumed to be the
3618 same as the image brightness units. The zero level offset can be held constant during
3619 the fit by specifying fixoffset=True. In the case of dooff=True, the returned
3620 dictionary contains two additional keys, 'zerooff' and 'zeroofferr', which are both
3621 dictionaries containing 'unit' and 'value' keys. The values associated with the 'value'
3622 keys are arrays containing the the fitted zero level offset value and its error, respectively,
3623 for each channel. In cases where the fit did not converge, these values are set to NaN.
3624 The value associated with 'unit' is just the image brightness unit.
3626 The region can either be specified by a box(es) or a region.
3627 Ranges of pixel values can be included or excluded from the fit. If specified using
3628 the box parameter, multiple boxes can be given using the format
3629 box='blcx1, blcy1, trcx1, trcy1, blcx2, blcy2, trcx2, trcy2, ... , blcxN, blcyN, trcxN, trcyN'
3630 where N is the number of boxes. In this case, the union of the specified boxes will be used.
3632 If specified, the residual and/or model images for successful fits will be written.
3634 If an estimates file is not specified, an attempt is made to estimate
3635 initial parameters and fit a single Gaussian. If a multiple Gaussian fit
3636 is desired, the user must specify initial estimates via a text file
3637 (see below for details).
3639 The user has the option of writing the result of the fit to a log file,
3640 and has the option of either appending to or overwriting an existing file.
3642 The user has the option of writing the (convolved) parameters of a successful
3643 fit to a file which can be fed back to fitcomponents() as the estimates file for a
3644 subsequent run.
3646 The user has the option of writing the fit results in tabular format to a file whose
3647 name is specified using the summary parameter.
3649 If specified and positive, the value of rms is used to calculate the parameter uncertainties,
3650 otherwise, the rms in the selected region in the relevant channel is used for these calculations.
3652 The noisefwhm parameter represents the noise-correlation beam FWHM. If specified as a quantity,
3653 it should have angular units. If specified as a numerical value, it is set equal to that number
3654 of pixels. If specified and greater than or equal to the pixel size, it is used to calculate
3655 parameter uncertainties using the correlated noise equations (see below). If it is specified but
3656 less than a pixel width, the the uncorrelated noise equations (see below) are used to
3657 compute the parameter uncertainties. If it is not specified and the image has a restoring beam(s),
3658 the the correlated noise equations are used to compute parameter uncertainties using the
3659 geometric mean of the relevant beam major and minor axes as the noise-correlation beam FWHM. If
3660 noisefwhm is not specified and the image does not have a restoring beam, then the uncorrelated
3661 noise equations are used to compute the parameter uncertainties.
3663 SUPPORTED UNITS
3665 Currently only images with brightness units conformant with Jy/beam, Jy.km/s/beam, and K are fully
3666 supported for fitting. If your image has some other base brightness unit, that unit will be assumed
3667 to be equivalent to Jy/pixel and results will be calculated accordingly. In particular,
3668 the flux density (reported as Integrated Flux in the logger and associated with the 'flux' key
3669 in the returned component subdictionary(ies)) for such a case represents the sum of pixel values.
3671 Note also that converting the returned results subdictionary to a component list via cl.fromrecord() currently
3672 only works properly if the flux density units in the results dictionary are conformant with Jy.
3673 If you need to be able to run cl.fromrecord() on the resulting dictionary you can first modify the
3674 flux density units by hand to be (some prefix)Jy and then run cl.fromrecord() on that dictionary,
3675 bearing in mind your unit conversion.
3677 If the input image has units of K, the flux density of components will be reported in units
3678 of [prefix]K*rad*rad, where prefix is an SI prefix used so that the numerical value is between
3679 1 and 1000. To convert to units of K*beam, determine the area of the appropriate beam,
3680 which is given by pi/(4*ln(2))*bmaj*bmin, where bmaj and bmin are the major and minor axes
3681 of the beam, and convert to steradians (=rad*rad). This value is included in the beam portion
3682 of the component subdictionary (key 'beamster'). Then divide the numerical value of the
3683 logged flux density by the beam area in steradians. So, for example
3685 begin{verbatim}
3686 # run on an image with K brightness units
3687 res = imfit(...)
3688 # get the I flux density in K*beam of component 0
3689 comp = res['results']['component0']
3690 flux_density_kbeam = comp['flux']['value'][0]/comp['beam']['beamster']
3691 end{verbatim}
3693 FITTING OVER MULTIPLE CHANNELS
3695 For fitting over multiple channels, the result of the previous successful fit is used as
3696 the estimate for the next channel. The number of gaussians fit cannot be varied on a channel
3697 by channel basis. Thus the variation of source structure should be reasonably smooth in
3698 frequency to produce reliable fit results.
3700 MASK SPECIFICATION
3702 Mask specification can be done using an LEL expression. For example
3704 mask = ''myimage'>5' will use only pixels with values greater than 5.
3706 INCLUDING AND EXCLUDING PIXELS
3708 Pixels can be included or excluded from the fit based on their values
3709 using these parameters. Note that specifying both is not permitted and
3710 will cause an error. If specified, both take an array of two numeric
3711 values.
3713 ESTIMATES
3715 Initial estimates of fit parameters may be specified via an estimates
3716 text file. Each line of this file should contain a set of parameters for
3717 a single gaussian. Optionally, some of these parameters can be fixed during
3718 the fit. The format of each line is
3720 peak intensity, peak x-pixel value, peak y-pixel value, major axis, minor axis, position angle, fixed
3722 The fixed parameter is optional. The peak intensity is assumed to be in the
3723 same units as the image pixel values (eg Jy/beam). The peak coordinates are specified
3724 in pixel coordinates. The major and minor axes and the position angle are the convolved
3725 parameters if the image has been convolved with a clean beam and are specified as quantities.
3726 The fixed parameter is optional and is a string. It may contain any combination of the
3727 following characters 'f' (peak intensity), 'x' (peak x position), 'y' (peak y position),
3728 'a' (major axis), 'b' (axial ratio, R = (major axis FWHM)/(minor axis FWHM)),
3729 'p' (position angle). NOTE: One cannot hold the minor axis fixed without holding the major
3730 axis fixed. If the major axis is not fixed, specifying 'b' in the fixed string will hold
3731 the axial ratio fixed during the fit.
3733 In addition, lines in the file starting with a # are considered comments.
3735 An example of such a file is:
3737 begin{verbatim}
3738 # peak intensity must be in map units
3739 120, 150, 110, 23.5arcsec, 18.9arcsec, 120deg
3740 90, 60, 200, 46arcsec, 23arcsec, 140deg, fxp
3741 end{verbatim}
3743 This is a file which specifies that two gaussians are to be simultaneously fit,
3744 and for the second gaussian the specified peak intensity, x position, and position angle
3745 are to be held fixed during the fit.
3747 ERROR ESTIMATES
3749 Error estimates are based on the work of Condon 1997, PASP, 109, 166. Key assumptions made are:
3751 - The given model (elliptical Gaussian, or elliptical Gaussian plus constant offset) is an
3752 adequate representation of the data
3753 - An accurate estimate of the pixel noise is provided or can be derived (see above). For the
3754 case of correlated noise (e.g., a CLEAN map), the fit region should contain many 'beams' or
3755 an independent value of rms should be provided.
3756 - The signal-to-noise ratio (SNR) or the Gaussian component is large. This is necessary because
3757 a Taylor series is used to linearize the problem. Condon (1997) states that the fractional
3758 bias in the fitted amplitude due to this assumption is of order 1/(S*S), where S is the overall
3759 SNR of the Gaussian with respect to the given data set (defined more precisely below). For a 5
3760 sigma 'detection' of the Gaussian, this is a 4% effect.
3761 - All (or practically all) of the flux in the component being fit falls within the selected region.
3762 If a constant offset term is simultaneously fit and not fixed, the region of interest should be
3763 even larger. The derivations of the expressions summarized in this note assume an effectively
3764 infinite region.
3766 Two sets of equations are used to calculate the parameter uncertainties, based on if
3767 the noise is correlated or uncorrelated. The rules governing which set of equations are
3768 used have been described above in the description of the noisefwhm parameter.
3770 In the case of uncorrelated noise, the equations used are
3772 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))
3773 = sqrt(2)/S
3775 where s(z) is the uncertainty associated with parameter z, f(z) = s(z)/abs(z) is the
3776 fractional uncertainty associated with parameter z, A is the peak intensity, I is the flux
3777 density, M and m are the FWHM major and minor axes, p is the position angle of the
3778 component, and k = sqrt(8*ln(2)). s(x) and s(y) are the direction
3779 uncertainties of the component measured along the major and minor axes; the resulting
3780 uncertainties measured along the principle axes of the image direction coordinate are
3781 calculated by propagation of errors using the 2D rotation matrix which enacts the rotation through
3782 the position angle plus 90 degrees. S is the overall signal to noise ratio of the component,
3783 which, for the uncorrelated noise case is given by
3785 S = (A/(k*h*r))*sqrt(pi*M*m)
3787 where h is the pixel width of the direction coordinate and r is the rms noise (see the
3788 discussion above for the rules governing how the value of r is determined).
3790 For the correlated noise case, the same equations are used to determine the uncertainties
3791 as in the uncorrelated noise case, except for the uncertainty in I (see below). However,
3792 S is given by
3794 S = (A/(2*r*N)) * sqrt(M*m) * (1 + ((N*N/(M*M)))**(a/2)) * (1 + ((N*N/(m*m)))**(b/2))
3796 where N is the noise-correlation beam FWHM (see discussion of the noisefwhm parameter for
3797 rules governing how this value is determined). '**' indicates exponentiation and a and b
3798 depend on which uncertainty is being calculated. For sigma(A), a = b = 3/2. For M and x,
3799 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
3800 correlated noise case according to
3802 f(I) = sqrt( f(A)*f(A) + (N*N/(M*m))*(f(M*f(M) + f(m)*f(m))) )
3804 Note well the following caveats:
3805 - Fixing Gaussian component parameters will tend to cause the parameter uncertainties reported for free
3806 parameters to be overestimated.
3807 - Fitting a zero level offset that is not fixed will tend to cause the reported parameter
3808 uncertainties to be slightly underestimated.
3809 - The parameter uncertainties will be inaccurate at low SNR (a ~10% for SNR = 3).
3810 - If the fitted region is not considerably larger than the largest component that is fit,
3811 parameter uncertainties may be mis-estimated.
3812 - An accurate rms noise measurement, r, for the region in question must be supplied.
3813 Alternatively, a sufficiently large signal-free region must be present in the selected region
3814 (at least about 25 noise beams in area) to auto-derive such an estimate.
3815 - If the image noise is not statistically independent from pixel to pixel, a reasonably accurate noise
3816 correlation scale, N, must be provided. If the noise correlation function is not approximately Gaussian,
3817 the correlation length can be estimated using
3819 N = sqrt(2*ln(2)/pi)* double-integral(dx dy C(x,y))/sqrt(double-integral(dx dy C(x, y) * C(x,y)))
3821 where C(x,y) is the associated noise-smoothing function
3822 - If fitted model components have significan spatial overlap, the parameter uncertainties are likely to
3823 be mis-estimated (i.e., correlations between the parameters of separate components are not accounted
3824 for).
3825 - If the image being analyzed is an interferometric image with poor uv sampling, the parameter
3826 uncertainties may be significantly underestimated.
3828 The deconvolved size and position angle errors are computed by taking the maximum of the absolute values of the
3829 differences of the best fit deconvolved value of the given parameter and the deconvolved size of the eight
3830 possible combinations of (FWHM major axis +/- major axis error), (FWHM minor axis +/- minor axis error),
3831 and (position andle +/- position angle error). If the source cannot be deconvolved from the beam (if the best
3832 fit convolved source size cannot be deconvolved from the beam), upper limits on the deconvolved source size
3833 are sometimes reported. These limits simply come from the maximum major and minor axes of the deconvolved
3834 gaussians taken from trying all eight of the aforementioned combinations. In the case none of these combinations
3835 produces a deconvolved size, no upper limit is reported.
3837 EXAMPLE:
3839 Here is how one might fit two gaussians to multiple channels of a cube using the fit
3840 from the previous channel as the initial estimate for the next. It also illustrates
3841 how one can specify a region in the associated continuum image as the region to use
3842 as the fit for the channel.
3844 begin{verbatim}
3845 imagename = 'co_cube.im'
3846 # specify region using region from continuum
3847 region = 'continuum.im:source.rgn'
3848 chans = '2~20'
3849 # only use pixels with positive values in the fit
3850 excludepix = [-1e10,0]
3851 # estimates file contains initial parameters for two Gaussians in channel 2
3852 estimates = 'initial_estimates.txt'
3853 logfile = 'co_fit.log'
3854 # append results to the log file for all the channels
3855 append = 'True'
3856 ia.open(imagename)
3857 ia.fitcomponents(region=region, chans=chans, excludepix=excludepix, estimates=estimates, logfile=logfile, append=append)
3858 end{verbatim}
3860 Input Parameters:
3861 box Rectangular region(s) to select in direction plane. Default is to use the entire direction plane.
3862 region Region selection. Default is to use the full image.
3863 chans Channels to use. Default is 0 (first plane).
3864 stokes The stokes planes to use. Default is to use the first stokes plane.
3865 mask Mask to use. Default is none.
3866 includepix Range of pixel values to include. Default is to include all pixels.
3867 excludepix Range of pixel values to exclude. Default is to exclude no pixels.
3868 residual Name of the residual image to write. Default is not to write the residual.
3869 model Name of the model image to write. Default is not to write the model.
3870 estimates Name of the input estimates file. Default is to auto-estimate in which case a single gaussian will be fit.
3871 logfile File in which to log results. Default is not to write a logfile.
3872 append Append results to logfile? Logfile must be specified. Default is to append. False means overwrite existing file if it exists.
3873 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.
3874 complist Output component list table name. Default is do not write a component list table.
3875 overwrite Overwrite component list if it already exists. Default is False.
3876 dooff Also fit a zero level offset? Default is False
3877 offset Initial estimate of zero-level offset. Only used if doff is True. Default is 0.0
3878 fixoffset Keep the zero level offset fixed during fit? Default is False
3879 stretch Stretch the mask if necessary and possible?
3880 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.
3881 noisefwhm Noise correlation beam FWHM. If numeric value, interpreted as pixel widths. If quantity (dictionary, string), it must have angular units.
3882 summary File name to which to write table of fit parameters.
3884 --------------------------------------------------------------------------------
3886 """
3887 return _image.image_fitcomponents(self, *args, **kwargs)
3890 def fromrecord(self, *args, **kwargs):
3891 """
3892 fromrecord(self, _record, _outfile) -> bool
3896 Summary:
3897 Generate an image from a record
3899 Description:
3902 You can convert an associated image to a record
3903 (torecord) or imagepol tool functions will sometimes give you a record. This function
3904 (fromrecord) allows you to set the contents of an image tool to the content of the record.
3905 This and torecord are used for deserialization and serialization.
3907 Input Parameters:
3908 record Record containing the image
3909 outfile The name of the diskfile to be created for image from record
3911 Example:
3914 #
3915 print 't----t fromrecord Ex 1 t----'
3916 ia.maketestimage('image.large', overwrite=true)
3917 rec=ia.torecord()
3918 ia.close()
3919 ia.fromrecord(rec, 'testimage')
3924 --------------------------------------------------------------------------------
3926 """
3927 return _image.image_fromrecord(self, *args, **kwargs)
3930 def getchunk(self, *args, **kwargs):
3931 """
3932 getchunk(self, _blc, _trc, _inc, _axes, _list, _dropdeg, _getmask) -> variant *
3936 Summary:
3937 Get the pixel values from a regular region of the image into an array
3939 Description:
3943 This function returns the pixels (or optionally the pixel mask) from the
3944 attached image between blc and trc, inclusive. Images with float, complex
3945 float, double, and complex double precision pixel values are supported.
3946 An increment may be specified with inc. Note that if too many pixel values
3947 are retrieved, swapping may occur, result in a decrease in performance,
3948 since the pixel values are stored in memory.
3950 Any illegal blc values are set to zero. Any illegal trc values are set to
3951 the end of the image. If any trc values are less than corresponding blc
3952 values, all the pixel values for that axis are returned. Any illegal inc
3953 values are set to unity.
3955 The axes parameter can be used to reduce the dimensionality of the output
3956 array. It specifies which pixel axes of the image over which to average
3957 the data. For example, consider a 3-D image, with axes=[0,1] and all
3958 other parameters set to their defaults. The result would be a 1-D vector,
3959 a profile along the third axis, with the data averaged over the first two
3960 axes.
3962 A related function is getregion(), which retrieves the pixel values or
3963 pixel mask from a potentially more complex region. Method getchunk() is
3964 retained because it is faster and therefore preferable for repeated
3965 operations in loops if the pixel mask is not required and the region is a
3966 simple box.
3968 If getmask=True, the return value is the pixel mask values, rather than
3969 the pixel values.
3971 Input Parameters:
3972 blc Bottom-Left-Corner (beginning) of pixel section. Default is start of image.
3973 trc Top-Right-Corner (end) of pixel section. Default is end of image.
3974 inc increment (stride) along axes
3975 axes Axes to average over. Default is none.
3976 list List bounding box to logger?
3977 dropdeg Drop degenerate axes?
3978 getmask Get the pixel mask rather than the pixel values
3980 Example:
3982 Suppose that we have a 3-dimensional image called {sff im}. Then:
3985 #
3986 print 't----t getchunk Ex 1 t----'
3987 ia.fromshape(shape=[64,64,128])
3988 pix = ia.getchunk() # all pixels
3989 ia.calcmask('T') # give image a mask
3990 pix = ia.getchunk([1,1,1], [10,10,1]) # 10 by 10 section of plane # 1
3991 pix = ia.getchunk([1,1], [1,1]) # first spectrum
3992 pix = ia.getchunk(inc=[1,5]) # all planes, decimated by 5 in y
3993 mask = ia.getchunk(getmask=True) # Get pixelmask
3994 ia.close()
3995 #
3998 --------------------------------------------------------------------------------
4000 """
4001 return _image.image_getchunk(self, *args, **kwargs)
4004 def getregion(self, *args, **kwargs):
4005 """
4006 getregion(self, _region, _axes, _mask, _list, _dropdeg, _getmask, _stretch) -> variant *
4010 Summary:
4011 Get pixels or mask from a region-of-interest of the image
4013 Description:
4017 This function recovers the image pixel or pixel mask values in the given region
4018 of interest. Regardless of the shape of the specified, the shape of the pixels and
4019 pixelmask arrays must necessarily be the bounding box of the specified region. If
4020 the region extends beyond the image, it is truncated.
4022 Recall that the recovered pixelmask will reflect both the pixelmask stored in the
4023 image, and the region (their masks are 'anded' together).
4025 The argument axes can be used to reduce the dimensionality of the output array. It
4026 specifies which pixel axes of the image to average the data over. For example,
4027 consider a 3-D image. With axes=[0,1] and all other arguments left at their
4028 defaults, the result would be a 1-D vector, a profile along the third axis, with
4029 the data averaged over the first two axes.
4031 This method differs in a couple of ways from the getchunk() method. For example,
4032 the specified region can be much more complex (eg, a union of polygons) than the
4033 limited, simple regions that can be specified in getchunk(), which must be
4034 rectangular. On the other hand, getregion() is less effective than getchunk()
4035 for the same region specification. So if one is interested in say, iterating
4036 through an image, getting a regular hyper-cube of pixels and doing something
4037 with them, then getchunk() will be faster. This would be especially noticeable if
4038 you iterated line by line through a large image (and of course, in both cases,
4039 retrieving very large regions will become very resource intensive, as these
4040 returned arrays are completely stored in memory).
4042 Input Parameters:
4043 region Region selection. Default is to use the full image.
4044 axes Axes to average over. Default is none.
4045 mask Mask to use. Default is none.
4046 list List the bounding box to the logger
4047 dropdeg Drop degenerate axes
4048 getmask Get the pixel mask rather than pixel values
4049 stretch Stretch the mask if necessary and possible? Default False
4051 Example:
4053 Suppose that we have a 3-dimensional image called {sff cube} and wish
4054 to recover the pixel from a simple regular region.
4057 #
4058 print 't----t getregion Ex 1 t----'
4059 ia.fromshape('cube', [64,64,64], overwrite=true)
4060 #r1=rg.box(blc=[10,10,10],trc=[30,40]) # Create region
4061 r1=rg.box([10,10,10],[30,40,40]) # Create region
4062 pixels=ia.getregion(r1)
4063 ia.close()
4064 #
4070 #
4071 print 't----t getregion Ex 2 t----'
4072 ia.fromshape('cube', [64,64,64], overwrite=true)
4073 pixels = ia.getregion()
4074 pixelmask = ia.getregion(getmask=True)
4075 #
4078 In this example we recover first the pixels and then the pixel mask.
4080 --------------------------------------------------------------------------------
4082 """
4083 return _image.image_getregion(self, *args, **kwargs)
4086 def getprofile(self, *args, **kwargs):
4087 """
4088 getprofile(self, _axis, _function, _region, _mask, _unit, _stretch, _spectype, _restfreq, _frame, _logfile) -> record *
4092 Summary:
4093 Get values and mask for a one dimensional profile along a specified image axis by applying an aggregate function.
4095 Description:
4098 This application returns information on a one-dimensional profile taken along a specified image axis.
4099 The region of interest is collapsed (a'la ia.collapse() along all axes orthogonal to the one specified, and)
4100 the specified aggregate function is applied to these pixels to generate the returned values.
4102 The aggregate function must be one of the functions supported by ia.collapse; ie, 'flux', 'madm', 'max', 'mean',
4103 'median', 'min', 'rms', 'stdev', 'sum', 'variance', and 'xmadm'. See the help for ia.collapse() for details regarding
4104 these functions. Minimum match and case insenstivity is supported. In addition, single binary (addition,
4105 subtraction, multiplication, and division) operations of these functions are supported, eg function='max*min'
4106 will return data that is the product of the maximum and the mininum for each plane along the specified
4107 axis.
4109 One may specify the unit of the returned coordinate values. Unless axis is the spectral axis, unit must be
4110 conformant with the corresponding axis unit in the image coordinate system or it must be 'pixel' which signifies,
4111 pixel, rather than world, coordinate values should be calculated. If axis is the spectral axis, unit may be a
4112 velocity unit (assuming the coordinate system has a rest frequency or restfreq is specified) or a length unit.
4113 In these cases, the returned coordinate values will be converted to velocity or wavelength, respectively.
4115 The parameter spectype may be used to specify the velocity or wavelength type for the returned coordinate values
4116 if profile is taken along spectral axis. Supported (minimum match, case insensitive) values) are 'relativistic
4117 velocity', 'beta', 'radio velocity', 'optical velocity', 'wavelength', 'air wavelength', 'default'. The 'default'
4118 value is equivalent to 'relativistic' if unit is a velocity unit or 'wavelength' if unit is a length unit.
4120 The restfreq parameter allows one to set the rest frequency for the coordinates to be returned if axis is the
4121 spectral axis and unit is a velocity unit. If blank, the rest frequency associated with the image coordinate
4122 system is used.
4124 The frame allows one to specify which kinematic reference frame that the returned coordinate values should be
4125 calculated in. It is only used if axis is the spectral axis and unit is unspecified or is specified and a
4126 frequency unit. If blank, the reference frame associated with the image coordinate system is used.
4128 The returned dictionary
4129 contains the keys:
4131 values: one-dimensional array along the specified axis containing values resulting from applying the specified
4132 aggregate function to corresponding pixels at the same location along that axis.
4133 mask: one-dimensional array of booleans of the resulting mask after applying the aggregate function, formed in the
4134 same way as that formed by ia.collapse.
4135 coords One-dimensional array of corresponding coordinate values along the specified axis in the specified unit
4136 (or the unit associated with the axis in the image coordinate system if unspecified).
4137 xUnit The unit used for calculating the values the coords array.
4139 Input Parameters:
4140 axis Axis along which to determine profile. Must be specified
4141 function Aggregate function to apply for collapse along axes orthogonal to specified axis.
4142 region Region selection. Default is to use the full image.
4143 mask Mask to use. Default is none.
4144 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.
4145 stretch Stretch the mask if necessary and possible? Default False
4146 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'.
4147 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
4148 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
4149 logfile File to which to write profile.
4151 Example:
4153 ia.open('myimage')
4154 # get the max pixel values along axis 2
4155 res = ia.getprofile(axis=2, function='max')
4157 # axis 2 is the spectral axis. Get the minimum pixel values along this axis
4158 # and specify that the returned coordinate values should be optical velocities
4159 # in km/s
4160 res2 = ia.getprofile(axis=2, function='min', unit='km/s', spectype='optical')
4162 # get the result of the maximum and the median of the absolute deviation from the median
4163 # along this axis
4164 res3 = ia.getprofile(axis=2, function='max/madm')
4166 ia.done()
4168 --------------------------------------------------------------------------------
4170 """
4171 return _image.image_getprofile(self, *args, **kwargs)
4174 def getslice(self, *args, **kwargs):
4175 """
4176 getslice(self, _x, _y, _axes, _coord, _npts, _method) -> record *
4180 Summary:
4181 Get 1-D slice from the image
4183 Description:
4187 This function returns a 1-D slice (the pixels and opionally the pixel mask) from
4188 the attached image. The slice is constrained to lie in a plane of two cardinal
4189 axes (e.g. XY or YZ). Interpolation is permitted between pixels, and a set of
4190 interpolation schemes is available.
4192 The slice is specified as a polyline giving the x and y coordinates and the axes
4193 of the plane holding that slice. The absolute pixel coordinates of the other
4194 axes may be specified using the coord parameter. If not specified, these values
4195 default to pixel 0 on the relevant axes.
4197 The npts parameter allows the number of values to be returned.
4199 The method parameter allows specification of the interpolation method to be
4200 used. Allowed values are 'nearest', 'linear', and 'cubic'. In the case of an
4201 image with complex valued pixels, the interpolation is done independently on the
4202 real and imaginary values. For example, the linearly interpolated value midway
4203 between pixels with values of 1 + 5j and 2 + 7j would be 1.5 + 6j.
4205 The return value is a dictionary with keys 'pixels' (interpolated pixel values),
4206 'mask' (interpolated mask), 'xpos' (x-location in absolute pixel coordinates),
4207 'ypos' (y-location in absolute pixel coordinates), 'distance' (distance along
4208 slice in pixels), and 'axes' (the x and y axes of slice).
4210 Input Parameters:
4211 x Polyline x vertices in absolute pixel coordinates
4212 y Polyline y vertices in absolute pixel coordinates
4213 axes Pixel axes of plane holding slice. Default is first two axes.
4214 coord Specify pixel coordinate for other axes. Default is first pixel.
4215 npts Number of points in slice. Default is auto determination.
4216 method The interpolation method, String from 'nearest', 'linear', 'cubic'
4218 Example:
4220 Suppose that we have a 2-dimensional image. Then:
4223 #
4224 print 't----t getslice Ex 1 t----'
4225 ia.maketestimage();
4226 rec = ia.getslice (x=[1,20], y=[2,30]) # SLice from [1,2] -> [20,30]
4227 print rec.keys()
4228 #['distance', 'xpos', 'axes', 'mask', 'ypos', 'pixel']
4229 rec = ia.getslice (x=[1,20,25,11], y=[2,30,32,40]) # Polyline slice
4230 ia.close()
4231 #
4234 --------------------------------------------------------------------------------
4236 """
4237 return _image.image_getslice(self, *args, **kwargs)
4240 def hanning(self, *args, **kwargs):
4241 """
4242 hanning(self, _outfile, _region, _mask, _axis, _drop, _overwrite, _stretch, _dmethod) -> image
4246 Summary:
4247 Convolve one axis of image with a Hanning kernel
4249 Description:
4253 This application performs Hanning convolution of one axis of an image defined by
4255 z[i] = 0.25*y[i-1] + 0.5*y[i] + 0.25*y[i+1] (equation 1)
4257 where z[i] is the value at pixel i in the hanning smoothed image, and
4258 y[i-1], y[i], and y[i+1] are the values of the input image at pixels i-1,
4259 i, and i+1 respectively. It supports both float and complex valued images.
4260 The length of the axis along which the convolution is to occur must be at least
4261 three pixels in the selected region. Masked pixel values are set to zero prior to
4262 convolution. All nondefault pixel masks are ignored during the calculation.
4264 The convolution is done in the image domain (i.e., not with an FFT).
4266 If drop=False, the length of the output axis will be the same as that of the input
4267 axis. The output pixel values along the convolution axis will be related to those
4268 of the input values according to equation 1, except the first and last pixels. In that
4269 case,
4271 z[0] = 0.5*(y[0] + y[1])
4273 and,
4275 z[N-1] = 0.5*(y[N-2] + y[N-1])
4277 where N is the number of pixels along the convolution aixs.
4278 The pixel mask, ORed with the OTF mask if specified, is copied from the selected
4279 region of the input image to the output image. Thus for example, if the selected
4280 region in the input image has six planes along the convolution axis, and if the pixel
4281 values, which are all unmasked, on a slice along this axis are [1, 2, 5, 10, 17, 26],
4282 the corresponding output pixel values will be [1.5, 2.5, 5.5, 10.5, 17.5, 21.5].
4284 If drop=True and dmethod='copy', the output image is the image calculated if
4285 drop=True, except that only the odd-numbered planes are kept. Furthermore, if the
4286 number of planes along the convolution axis in the selected region of the input image
4287 is even, the last odd number plane is also discarded. Thus, if the selected region
4288 has N pixels along the convolution axis in the input image, along the convolution
4289 axis the output image will have (N-1)/2 planes if N is odd, or (N-2)/2 planes if N
4290 is even. In this case, the pixel and mask values are copied directly, without further
4291 processing. Thus for example, if the selected region in the input image has six planes
4292 along the convolution axis, and if the pixel values, which are all unmasked, on a slice
4293 along this axis are [1, 2, 5, 10, 17, 26], the corresponding output pixel values will be
4294 [2.5, 10.5].
4296 If drop=True and dmethod='mean', first the image described in the drop=False case
4297 is calculated. The first plane and last plane(s) of that image are then discarded as
4298 described in the drop=True, dmethod='copy' case. Then, the ith plane of the output
4299 image is calculated by averaging the (2*i)th and (2*i + 1)th planes of the intermediate
4300 image.Thus for example, if the selected region in the input image has six planes
4301 along the convolution axis, and if the pixel values, which are all unmasked, on a slice
4302 along this axis are [1, 2, 5, 10, 17, 26], the corresponding output pixel values will be
4303 [4.0, 14.0]. Masked values are taken into consideration when forming this average, so if
4304 one of the values is masked, it is not used in the average. If at least one of the values
4305 in the input pair is not masked, the corresponding output pixel will not be masked.
4307 The hanning smoothed image is written to disk with name {stfaf outfile}, if
4308 specified. If not, no image is written but the image is still accessible via
4309 the returned image analysis tool (see below).
4311 This method always returns an image analysis tool which is attached to the
4312 hanning smoothed image. This tool should always be captured and closed after
4313 any desired manipulations have been done. Closing the tool frees up system
4314 resources (eg memory), eg,
4316 hanning_image = ia.hanning(...)
4317 begin{verbatim}
4318 # do things (or not) with hanning_image
4319 ...
4320 # close the returned tool promptly upon finishing with it.
4321 end{verbatim}
4322 hanning_image.done()
4324 See also the other convolution functions
4325 convolve2d,
4326 sepconvolve and
4327 convolve.
4329 Input Parameters:
4330 outfile Output image file name. Default is unset.
4331 region Region selection. Default is to use the full image.
4332 mask Mask to use. Default is none.
4333 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.
4334 drop Drop every other pixel on output?
4335 overwrite Overwrite (unprompted) pre-existing output file?
4336 stretch Stretch the mask if necessary and possible? Default False
4337 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.
4339 Example:
4341 ia.open('mynonsmoothed.im')
4342 # smooth the spectral axis, say it's axis 2 and only write every other pixel
4343 hanning = ia.hanning(outfile='myhanningsmoothed.im', axis=2, drop=True, overwrite=True)
4344 # done with input
4345 ia.done()
4346 # do something with the output image, get statistics say
4347 stats = hanning.statistics()
4348 # close the result image
4349 hanning.done()
4351 --------------------------------------------------------------------------------
4353 """
4354 return _image.image_hanning(self, *args, **kwargs)
4357 def haslock(self):
4358 """
4359 haslock(self) -> std::vector< bool >
4363 Summary:
4364 Does this image have any locks set?
4366 Description:
4370 This function can be used to find out whether the image has a read or a
4371 write lock set. It is not of general user interest. It returns
4372 a vector of Booleans of length 2. Position 1 says whether
4373 a read lock is set, position 2 says whether a write lock is set.
4375 In general locking is handled automatically, with a built in lock
4376 release cycle. However, this function can be useful in scripts when a
4377 file is being shared between more than one process. See also functions
4378 unlock and
4379 lock.
4381 Example:
4384 #
4385 print 't----t haslock Ex 1 t----'
4386 ia.maketestimage('xx',overwrite=true)
4387 ia.lock(writelock=True)
4388 print ia.haslock()
4389 #[True, True]
4390 ia.unlock()
4391 print ia.haslock()
4392 #[False, False]
4393 ia.lock(F)
4394 print ia.haslock()
4395 #[True, False]
4396 ia.close()
4397 #
4400 This example acquires a read/write lock on the file and then unlocks it
4401 and acquires just a read lock.
4403 --------------------------------------------------------------------------------
4405 """
4406 return _image.image_haslock(self)
4409 def histograms(self, *args, **kwargs):
4410 """
4411 histograms(self, _axes, _region, _mask, _nbins, _includepix, _cumu, _log, _stretch) -> record *
4415 Summary:
4416 Compute histograms from the image
4418 Description:
4422 This method computes histograms of the pixel values in the image.
4423 The values are returned in a dictionary.
4425 The chunk of the image over which you compute the histograms is
4426 specified by a vector of axis numbers (argument {stfaf axes}). For
4427 example, consider a 3-dimensional image for which you specify {stfaf
4428 axes=[0,2]}. The histograms would be computed for each XZ (axes 0 and
4429 2) plane in the image. You could then examine those histograms as a
4430 function of the Y (axis 1) axis. Or perhaps you set {stfaf axes=[2]},
4431 whereupon you could examine the histogram for each Z (axis 2) profile as
4432 a function of X and Y location in the image.
4434 You have control over the number of bins for each histogram ({stfaf
4435 nbins}). The bin width is worked out automatically for each histogram
4436 and may vary from histogram to histogram (the range of pixel values is
4437 worked out for each chunk being histogrammed).
4439 You have control over which pixels are included in the histograms via
4440 the {stfaf includepix} argument. This vector specifies a range of
4441 pixel values to be included in the histograms. If you only give one
4442 value for this, say {stfaf includepix=[b]}, then this is interpreted as
4443 {stfaf includepix=[-abs(b),abs(b)]}. If you specify an inclusion
4444 range, then the range of pixel intensities over which the histograms are
4445 binned is given by this range too. This is a way to make the bin width
4446 the same for each histogram.
4448 You can control if the histogram is cumulative or non-cumulative via the
4449 cumu parameter.
4451 You have countrol over how the bin counts are returned. If log = false,
4452 the actual counts are returned. If true, the values returned are the log10
4453 values of the actual counts.
4455 The results are returned as a dictionary. The counts (field 'counts') and
4456 the abscissa values (field 'values') for all bins in each histogram are returned.
4457 The shape of the first dimension of those arrays contained in those fields is {stfaf nbins}.
4458 The number and shape of the remaining dimensions are those of the display axes(the
4459 axes in the image for which you did not compute the histograms). For example, if one
4460 has a three dimensional image and sets {stfaf axes=[2]}, the display axes are 0 and 1,
4461 so the shape of each counts and values array is then [nbins,nx,ny], where nx and ny
4462 are the length of the zeroth and first axes, respectively.
4464 In addition, the mean (field 'mean') and standard deviation (field 'sigma') computed
4465 using the data in each histogram is returned. The shape of these arrays is equal to
4466 the shape of the display axes. So,
4468 Input Parameters:
4469 axes List of axes to compute histograms over. Default is all axes.
4470 region Region selection. Default is to use the full image.
4471 mask Mask to use. Default is none.
4472 nbins Number of bins in histograms, > 0
4473 includepix Range of pixel values to include. Default is to include all pixels.
4474 cumu If T the bin values are cumulative.
4475 log If true, the returned counts values will be the log10 values of the actual counts, if false, the actual counts will be returned.
4476 stretch Stretch the mask if necessary and possible? Default False
4478 Example:
4480 # obtain a histogram using the entire image
4481 ia.maketestimage()
4482 res = ia.histograms()
4483 ia.close()
4485 # obtain histograms for each plane along axis 1 with each
4486 # histogram having 30 bins. Only pixel values in the range
4487 # -0.001 to 0.001 are used in computing the histograms and the
4488 # statistics. The counts in the returned data structure represent
4489 # the cumulative number of data points in the current bin and in
4490 # bins less than the current bin.
4491 ia.open('myimage.im')
4492 r = ia.histograms(axes=[0,2],nbins=30,includepix=1e-3,cumu=True)
4493 ia.close()
4495 --------------------------------------------------------------------------------
4497 """
4498 return _image.image_histograms(self, *args, **kwargs)
4501 def history(self, *args, **kwargs):
4502 """
4503 history(self, _list) -> std::vector< std::string >
4507 Summary:
4508 Recover and/or list the history file
4510 Description:
4514 This method interogates the history of an image.
4516 The history is returned as an array of strings, where each element represents
4517 an individual history entry. If True, the list parameter will also cause the
4518 history to be emitted by the logger.
4520 Note that entries can be permanently added to the image history by using the
4521 ia.sethistory() method.
4523 Input Parameters:
4524 list List history to the logger?
4526 Example:
4529 #
4530 print 't----t history Ex 1 t----'
4531 ia.maketestimage()
4532 ia.history() # List history to logger
4533 h = ia.history(list=False) # Recover history in variable h
4534 ia.history(list=True, browse=False) # List history to logger
4535 #
4538 --------------------------------------------------------------------------------
4540 """
4541 return _image.image_history(self, *args, **kwargs)
4544 def insert(self, *args, **kwargs):
4545 """
4546 insert(self, _infile, _region, _locate, _verbose) -> bool
4550 Summary:
4551 Insert specified image into this image
4553 Description:
4557 This function inserts the specified image (or part of it) into the image
4558 referenced by this tool.
4559 The specified image may be given via argument {stfaf infile}
4560 as a disk file name (it may be in native casa, fits, or Miriad
4561 format; Look htmlref{here}{IMAGES:FOREIGNIMAGES} for more
4562 information on foreign images).
4564 If the {stfaf locate} vector is not given, then the images are
4565 aligned (to an integer pixel shift) by their reference pixels.
4567 If {stfaf locate} vector is given, then those values that are given,
4568 give the absolute pixel in the output (this) image of the bottom left
4569 corner of the input (sub)image. For those values that are not given,
4570 the input image is symmetrically placed in the output image.
4572 The image referenced by this tool is modified in place; no new image
4573 is created. The method returns True if successful.
4575 Input Parameters:
4576 infile Name of image to be inserted.
4577 region Region selection. Default is to use the full image.
4578 locate Location of input image in output image. Default is centrally located.
4579 verbose Emit informational messages to logger?
4581 Example:
4584 #
4585 print 't----t insert Ex 1 t----'
4586 ia.maketestimage('myfile.insert',overwrite=true)
4587 ia.close()
4588 ia.fromshape(shape=[200,200])
4589 ia.insert(infile='myfile.insert') # Align by reference pixel
4590 ia.newimagefromfile('myfile.insert')
4591 ia.insert(infile=im2.name(), locate=[]) # Align centrally
4592 # This time align axis 0 as given and axis 1 centrally
4593 ia.insert(infile='myfile.insert', locate=[20])
4594 ia.close() # close default tool and
4597 --------------------------------------------------------------------------------
4599 """
4600 return _image.image_insert(self, *args, **kwargs)
4603 def isopen(self):
4604 """
4605 isopen(self) -> bool
4609 Summary:
4610 Is this Image tool open?
4612 Description:
4616 This method returns True if the image tool has an attached image.
4618 Example:
4621 #
4622 print 't----t isopen Ex 1 t----'
4623 ia.maketestimage('zz',overwrite=true)
4624 print ia.isopen()
4625 #True
4626 ia.close()
4627 print ia.isopen()
4628 #False
4629 ia.open('zz')
4630 print ia.isopen()
4631 #True
4632 ia.close()
4633 #
4636 --------------------------------------------------------------------------------
4638 """
4639 return _image.image_isopen(self)
4642 def ispersistent(self):
4643 """
4644 ispersistent(self) -> bool
4648 Summary:
4649 Is the image persistent?
4651 Description:
4655 This function can be used to find out whether the image is persistent on
4656 disk or not. There is a subtle difference from the image being
4657 virtual. For example, a virtual image which references another
4658 which is on disk is termed persistent.
4660 Example:
4663 #
4664 print 't----t ispersistent Ex 1 t----'
4665 ia.fromshape(outfile='tmp', shape=[10,20], overwrite=true)
4666 print ia.ispersistent()
4667 #True
4668 ia.close()
4669 ia.fromimage(infile='tmp')
4670 print ia.ispersistent()
4671 #True
4672 im3 = ia.subimage()
4673 print im3.ispersistent() # Persistent virtual image !
4674 #True
4675 im4 = ia.imagecalc(pixels='tmp+tmp')
4676 print im4.ispersistent()
4677 #False
4678 im3.done()
4679 im4.done()
4680 ia.close(remove=true)
4681 #
4684 --------------------------------------------------------------------------------
4686 """
4687 return _image.image_ispersistent(self)
4690 def lock(self, *args, **kwargs):
4691 """
4692 lock(self, _writelock, _nattempts) -> bool
4696 Summary:
4697 Acquire a lock on the image
4699 Description:
4703 This function can be used to acquire a Read or a Read/Write lock
4704 on the imagefile. It is not of general user interest.
4706 In general locking is handled automatically, with a built in lock
4707 release cycle. However, this function can be useful in scripts when a
4708 file is being shared between more than one process. See also functions
4709 unlock and haslock.
4711 Input Parameters:
4712 writelock Acquire a read/write (T) or a readonly (F) lock
4713 nattempts Number of attempts, > 0. Default is unlimiited.
4715 Example:
4718 #
4719 print 't----t lock Ex 1 t----'
4720 ia.maketestimage('xx', overwrite=true)
4721 ia.lock(writelock=True)
4722 ia.unlock()
4723 ia.lock(writelock=False)
4724 ia.close(remove=true)
4725 #
4728 This acquires a read/write lock on the file. Then we unlock it
4729 and acquire a readonly lock.
4731 --------------------------------------------------------------------------------
4733 """
4734 return _image.image_lock(self, *args, **kwargs)
4737 def makecomplex(self, *args, **kwargs):
4738 """
4739 makecomplex(self, _outfile, _imag, _region, _overwrite) -> bool
4743 Summary:
4744 Make a complex image
4746 Description:
4750 This function combines the current image with another image to make
4751 a complex image. The current image (i.e. that associated with this
4752 Image must have real valued pixels). The image used for generating the
4753 imaginary part of the pixel values is specified using the imag parameter, and
4754 it must persistent. The image attached to this tool and the image specified
4755 using the imag parameter must have the same precision, or else an exception
4756 will be thrown. If both are float precision, the resulting image will have
4757 float precision pixel values. If both are double precision, the resulting image
4758 will have double precision pixel values. The coordinate systems of the two
4759 input images must be conformant. The metadata written to the resulting image is
4760 copied from the image attached to this tool.
4762 Input Parameters:
4763 outfile Output Complex (disk) image file name
4764 imag Imaginary image file name
4765 region Region selection. Default is to use the full image.
4766 overwrite Overwrite (unprompted) pre-existing output file?
4768 Example:
4771 #
4772 print 't----t makecomplex Ex 1 t----'
4773 ia.maketestimage('imag.im',overwrite=true) #imaginary image
4774 ia.close()
4775 ia.maketestimage('real.im',overwrite=true) #assoc. real image
4776 ia.makecomplex('complex.im', 'imag.im', overwrite=true)
4777 ia.close()
4778 #
4781 --------------------------------------------------------------------------------
4783 """
4784 return _image.image_makecomplex(self, *args, **kwargs)
4787 def maskhandler(self, *args, **kwargs):
4788 """
4789 maskhandler(self, _op, _name) -> std::vector< std::string >
4793 Summary:
4794 Handle pixel masks
4796 Description:
4800 This method is used to manage or handle pixel masks . A CASA image may contain
4801 zero, one, or more pixel masks. Any of these masks can be designated the
4802 default pixel mask assoicated with the given image. The default mask is acted
4803 upon and/or used by CASA applications. For example, if ia.statistics() will
4804 exclude pixels which are masked as bad (False) from the calculations.
4806 This method does not modify the individual boolean values of any masks.
4808 The op parameter is used to specify the behaviour. In all cases, the specified
4809 operation can be specified by a three character string. Supported values of the
4810 op parameter are:
4812 'default': Retrieve the name of the default pixel mask associated with the
4813 image. A one element array containing the empty string is returned if the image
4814 has no default mask.
4816 'get': Retrieve the name(s) of all the existing pixel masks. Note that the
4817 ia.summary() method may also be used to view the pixel masks associated with an
4818 image.
4820 'set': Set the default pixel mask to the value specified by the name parameter.
4821 If the value of the name parameter is the empty string, then the default mask is
4822 unset (ie, all the pixels will be treated as being unmasked).
4824 'delete': Delete the pixel mask(s) specified by the name parameter. To delete
4825 more than one mask, the name parameter can be an array of strings. Any supplied
4826 pixel mask name that does not exist is silently ignored.
4828 'rename': Rename the mask specified as the first element of the name array
4829 parameter (name[0]) to the value specified in the second element of the name
4830 array parameter (name[1]]. In this case, the name array parameter must have
4831 exactly two elements.
4833 'copy': Copy the mask specified in the first element of the name array
4834 parameter (name[0]) to the a mask name specified in the second element of the
4835 name array parameter (name[1]]. In this case, the name array parameter must have
4836 exactly two elements. A mask from another image can be copied by using the
4837 imagename:maskname syntax for the first element in the name array, eg,
4838 'myimage:mask2'.
4840 Input Parameters:
4841 op The operation. One of 'set', 'delete', 'rename', 'get', 'copy' or 'default'
4842 name Name of mask or masks.
4844 Example:
4847 #
4848 print 't----t maskhandler Ex 1 t----'
4849 ia.maketestimage('g1.app', overwrite=true)
4850 ia.calcmask('T', name='mask1')
4851 ia.close()
4852 ia.maketestimage('myimage', overwrite=true)
4853 ia.calcmask('T') # Create some masks
4854 ia.calcmask('T', name='mask1')
4855 ia.calcmask('T', name='mask2')
4856 names = ia.maskhandler('get') # Get the mask names
4857 print names
4858 #['mask0', 'mask1', 'mask2']
4859 name = ia.maskhandler('default') # Get the default mask name
4860 print name
4861 #mask2
4862 ia.maskhandler('set', ['mask1']) # Make 'mask1' the default mask
4863 ia.maskhandler('set', ['']) # Unset the default mask
4864 ia.maskhandler('delete', ['mask1']) # Delete 'mask1'
4865 ia.calcmask('T', name='mask1') # Make another 'mask1'
4866 ia.maskhandler('delete', ['mask0', 'mask1'])# Delete 'mask0' and 'mask1'
4867 ia.calcmask('T', name='mask1')
4868 ia.maskhandler('rename', ['mask1', 'mask0'])# Rename 'mask1' to 'mask0'
4870 # Copy 'mask1' from image 'g1.app' to 'mask10' in image 'myimage'
4871 ia.maskhandler('copy', ['g1.app:mask1', 'mask10'])
4872 ia.removefile('g1.app') # Cleanup
4873 ia.close()
4874 #
4877 --------------------------------------------------------------------------------
4879 """
4880 return _image.image_maskhandler(self, *args, **kwargs)
4883 def miscinfo(self):
4884 """
4885 miscinfo(self) -> record *
4889 Summary:
4890 Get the miscellaneous information record from an image
4892 Description:
4896 A casa imagefile can accumulate miscellaneous information
4897 during its lifetime. This information is stored in a record called the {stff
4898 miscinfo} record. For example, the fits filler puts header keywords
4899 it doesn't otherwise use into the {stff miscinfo} record. This {stff
4900 miscinfo} record is not guaranteed to have any entries, so it's up to
4901 you to check for any fields that you require.
4903 You can also put things into this record (see
4904 setmiscinfo) yourself, to keep
4905 information that the system might not otherwise store for you.
4907 When the image is written out to fits, the items in the
4908 {stff miscinfo} record are written to the fits file
4909 as keywords with the corresponding record field name.
4911 Example:
4914 #
4915 print 't----t miscinfo Ex 1 t----'
4916 ia.maketestimage()
4917 print ia.miscinfo() # print the record
4918 ia.setmiscinfo('testing')
4919 print ia.miscinfo()
4920 header = ia.miscinfo() # capture the record for further use
4921 print header
4922 ia.close()
4923 #
4926 --------------------------------------------------------------------------------
4928 """
4929 return _image.image_miscinfo(self)
4932 def modify(self, *args, **kwargs):
4933 """
4934 modify(self, _model, _region, _mask, _subtract, _list, _stretch) -> bool
4938 Summary:
4939 Modify image with a model
4941 Description:
4945 This function applies a model of the sky to the image. You can add or
4946 subtract the model which is contained in a
4947 Componentlist tool.
4949 The pixel values are only changed where the total mask
4950 (combination of the default pixel mask [if any] and the OTF mask)
4951 is good (True). If the computation fails for a particular
4952 pixel (e.g. coordinate undefined) that pixel will be
4953 masked bad.
4955 DISK MODELS
4957 Pixels with centers inside the disk will have the same values, even if a pixel straddles the
4958 edge of the disk. Pixels with straddle the edge of the disk which have centers outside the
4959 disk are given values of zero. Thus, one should not expect the flux density of the disk to
4960 be exactly the provided value to the component list; for a given size disk, the computed flux
4961 density will be closer to the expected value for images with smaller pixels.
4963 Input Parameters:
4964 model Record representation of a ComponentList model
4965 region Region selection. Default is to use the full image.
4966 mask Mask to use. Default is none.
4967 subtract Subtract or add the model
4968 list List informative messages to the logger
4969 stretch Stretch the mask if necessary and possible? Default False
4971 Example:
4974 #
4975 print 't----t modify Ex 1 t----'
4976 ia.maketestimage()
4977 clrec = ia.fitcomponents()
4978 ia.modify(clrec['results'])
4979 ia.close()
4980 #
4986 In this example we subtract the model returned by the fitcomponents function.
4988 --------------------------------------------------------------------------------
4990 """
4991 return _image.image_modify(self, *args, **kwargs)
4994 def maxfit(self, *args, **kwargs):
4995 """
4996 maxfit(self, _region, _point, _width, _negfind, _list) -> record *
5000 Summary:
5001 Find maximum and do parabolic fit in the sky
5003 Description:
5007 This function finds the pixel with the maximum value in the region, and
5008 then uses function findsources
5009 to generate a Componentlist with one component. The component
5010 will be of type Point ({stfaf point=T}) or Gaussian ({stfaf point=F}).
5012 If {stfaf negfind=F} the maximum pixel value is found in the region and fit.
5013 If {stfaf negfind=T} the absolute maximum pixel value is found in the region
5014 and fit.
5016 See function findsources for
5017 a description of arguments {stfaf point} and {stfaf width}.
5019 See also the function fitcomponents.
5021 Input Parameters:
5022 region Region selection. Default is to use the full image.
5023 point Find only point sources?
5024 width Half-width of fit grid when point=F
5025 negfind Find negative sources as well as positive?
5026 list List the fitted parameters to the logger?
5028 Example:
5031 #
5032 print 't----t maxfit Ex 1 t----'
5033 ia.maketestimage()
5034 clrec = ia.maxfit()
5035 print clrec # There is only one component
5036 ia.close()
5037 #
5040 --------------------------------------------------------------------------------
5042 """
5043 return _image.image_maxfit(self, *args, **kwargs)
5046 def moments(self, *args, **kwargs):
5047 """
5048 moments(self, _moments, _axis, _region, _mask, _method, _smoothaxes, _smoothtypes, _smoothwidths, _includepix, _excludepix, _peaksnr, _stddev, _doppler, _outfile, _smoothout, _overwrite, _drop, _stretch) -> image
5052 Summary:
5053 Compute moments from an image
5055 Description:
5059 noindent{bf Summary}
5061 The primary goal of this function is to enable you to analyze a
5062 multi-dimensional image by generating moments of a specified axis.
5063 This is a time-honoured spectral-line analysis technique used for
5064 extracting information about spectral lines.
5066 You can generate one or more output moment images. The return value
5067 of this function is an on-the-fly Image tool holding the {bf first}
5068 of the output moment images.
5070 The word 'moment' is used loosely here. It refers to collapsing an axis
5071 (the moment axis) to one pixel and setting the value of that pixel (for
5072 all of the other non-collapsed axes) to something computed from the data
5073 values along the moment axis. For example, take an RA-DEC-Velocity
5074 cube, collapse the velocity axis by computing the mean intensity at each
5075 RA-DEC pixel. This function offers many different moments and a variety
5076 of automatic methods to compute them.
5078 We try to make a distinction between a 'moment' and a 'method'. This
5079 boundary is a little blurred, but it claims to refer to the distinction
5080 between what you are computing, and how the pixels that were included in
5081 that computation were selected. For example, a 'moment' would be the
5082 average value of some pixel values in a spectrum. A 'method' for
5083 selecting those pixels would be a simple pixel value range specifying
5084 which pixels should be included.
5086 There are many available moments, and you specify each one with an
5087 integer code as it would get rather cumbersome to refer to them via
5088 strings. In the list below, the value of the $i$th pixel of the
5089 spectrum is $I_i$, the coordinate of this pixel is $v_i$ (of course it
5090 may not be velocity), and there are $n$ pixels in the spectrum. The
5091 available moments are:
5093 begin{itemize}
5094 item{$-1$} -- the mean value of the spectrum
5095 begin{displaymath}
5096 { {1over n} {sum {I_i}}}
5097 end{displaymath}
5098 medskip
5100 item{0} -- the integrated value of the spectrum
5101 begin{displaymath}
5102 M_0 = Delta v sum I_i
5103 end{displaymath}
5105 where $Delta v$ is the width (in world coordinate units) of a pixel
5106 along the moment axis
5107 medskip
5109 item{1} -- the intensity weighted coordinate (this is
5110 traditionally used to get 'velocity fields')
5112 begin{displaymath}
5113 M_1 = { {sum {I_i v_i}} over {M_0}}
5114 end{displaymath}
5115 medskip
5117 item{2} -- the intensity weighted dispersion of the coordinate
5118 (this is traditionally used to get 'velocity dispersion fields')
5120 begin{displaymath}
5121 sqrt{ { {sum {I_i left(v_i - M_1right)^2}} over {M_0}}}
5122 end{displaymath}
5123 medskip
5125 item{3} -- the median of $I$
5126 medskip
5128 item{4} -- the median coordinate. Here we treat the spectrum as a
5129 probability distribution, generate the cumulative distribution, and then
5130 find the coordinate corresponding to the 50% value. This moment is not
5131 very robust, but it is useful for quickly generating a velocity field in
5132 a way that is not sensitive to noise. However, it will only give
5133 sensible results under certain conditions. The generation of the
5134 cumulative distribution and the finding of the 50% level really only
5135 makes sense if the cumulative distribution is monotonic. This
5136 essentially means only selecting pixels which are positive or negative.
5137 For this reason, this moment type is only supported with the basic
5138 method (see below -- i.e. no smoothing, no windowing, no fitting) with
5139 a pixel selection range that is either all positive, or all negative
5140 medskip
5142 item{5} -- the standard deviation about the mean of the spectrum
5143 begin{displaymath}
5144 sqrt{ {1over {left(n-1right)}} sum{left(I_i - bar{I}right)^2 }}
5145 end{displaymath}
5146 medskip
5148 item{6} -- the root mean square of the spectrum
5149 begin{displaymath}
5150 sqrt{ {1 over n} sum{I_i^2}}
5151 end{displaymath}
5152 medskip
5154 item{7} -- the absolute mean deviation of the spectrum
5155 begin{displaymath}
5156 {1 over n} sum {|(I_i - bar{I})|}
5157 end{displaymath}
5158 medskip
5160 item{8} -- the maximum value of the spectrum
5161 medskip
5162 item{9} -- the coordinate of the maximum value of the spectrum
5163 medskip
5164 item{10} -- the minimum value of the spectrum
5165 medskip
5166 item{11} -- the coordinate of the minimum value of the spectrum
5167 medskip
5168 end{itemize}
5170 bigskip
5171 noindent {Smoothing}
5173 The purpose of the smoothing functionality is purely to provide
5174 a mask. Thus, you can smooth the input image, apply a pixel
5175 include or exclude range, and generate a smoothed mask which is then
5176 applied before the moments are generated. The smoothed data
5177 are not used to compute the actual moments; that is always done
5178 from the original data.
5180 bigskip
5181 noindent{bf Basic Method}
5183 The basic method is to just compute moments directly from the pixel
5184 values. This can be modified by applying pixel value inclusion or
5185 exclusion ranges (arguments {stfaf includepix} and {stfaf excludepix}).
5187 You can then also convolve the image (arguments {stfaf smoothaxes}, {stfaf
5188 smoothtypes}, and {stfaf smoothwidths}) and find a mask based on the inclusion
5189 or exclusion ranges applied to the convolved image. This mask is then
5190 applied to the unsmoothed data for moment computation.
5192 bigskip
5193 noindent{bf Window Method}
5195 The window method (invoked with argument {stfaf method='window'}) does
5196 no pixel-value-based selection. Instead a window is found (hopefully
5197 surrounding the spectral line feature) and only the pixels in that
5198 window are used for computation. This window can be found from the
5199 convolved or unconvolved image (arguments {stfaf smoothaxes}, {stfaf
5200 smoothtypes}, and {stfaf smoothwidths}).
5202 The moments are always computed from the unconvolved data. The window
5203 can be found (for each spectrum) automatically. The
5204 automatic methods are via Bosma's converging mean algorithm ({stfaf
5205 method='window'}) or by fitting Gaussians and taking $pm 3sigma$ as
5206 the window ({stfaf method='window,fit'}).
5207 In Bosma's algorithm, an initial guess for a range of pixels surrounding
5208 a spectral feature is refined by widening until the mean of the pixels
5209 outside of the range converges (to the noise).
5211 bigskip
5212 noindent{bf Fit Method}
5214 The fit method ({stfaf method='fit'}) fits Gaussians to spectral
5215 features automatically. The moments are then computed from the
5216 Gaussian fits (not the data themselves).
5218 bigskip
5219 noindent{bf Other Arguments}
5221 begin{itemize}
5223 item {stfaf outfile} - If you are creating just one moment image,
5224 and you specify {stfaf outfile}, then the image is created
5225 on disk with this name. If you leave {stfaf outfile} empty
5226 then a temporary image is created. In both cases, you can
5227 access this image with the returned Image tool. If you are
5228 making more than one moment image, then theses images are always
5229 created on disk. If you specify {stfaf outfile} then this is
5230 the root for the output file names. If you don't specify it,
5231 then the input image name is used as the root.
5233 item {stfaf smoothing} - If you smooth the image to generate a
5234 mask, you specify the kernel widths via the {stfaf smoothwidths}
5235 argument in the same way as in the
5236 sepconvolve function. See it for
5237 details.
5239 item {stfaf stddev} - Some of the automatic methods also require an
5240 estimate of the noise level in the image. This is used to assess
5241 whether a spectrum is purely noise or not, and whether there is any
5242 signal worth digging out. If you don't give it via the {stfaf stddev}
5243 argument, it will be worked out automatically from a Gaussian fit to the
5244 bins above 25% from a histogram of the entire image.
5246 item {stfaf includepix, excludepix} - The vectors given by arguments
5247 {stfaf includepix} and {stfaf excludepix} specify a range of pixel
5248 values for which pixels are either included or excluded. They are
5249 mutually exclusive; you can specify one or the other, but not both. If
5250 you only give one value for either of these, say {stfaf includepix=b},
5251 then this is interpreted as {stfaf includepix=[-abs(b),abs(b)]}.
5253 The convolving point-spread function is normalized to have a volume of
5254 unity. This means that point sources are depressed in value, but
5255 extended sources that are large with respect to the PSF remain
5256 essentially on the same intensity scale; these are the structures you
5257 are trying to find with the convolution so this is what you want.
5258 If you convolve the image, then arguments like {stfaf includepix} select
5259 based upon the convolved image pixel values. If you are having trouble
5260 getting these right, you can output the convolved image ({stfaf smoothout})
5261 and assess the validity of your pixel ranges. Note also that if you are
5262 Hanning convolving (usually used on a velocity axis), then the width for
5263 this kernel must be 3 pixels (triangular smoothing kernels of other
5264 widths have no valid theoretical basis).
5266 item {stfaf doppler} - If you compute the moments along a spectral
5267 axis, it is conventional to compute the world coordinate (needed for
5268 moments 0, 1 and 2) along that axis in 'km/s'. The argument {stfaf
5269 doppler} lets you specify what doppler convention the velocity will be
5270 calculated in. You can choose from {stfaf doppler=radio, optical,
5271 true}. See function summary for the
5272 definitions of these codes. For other moment-axis types, the world coordinate
5273 is computed in the native units.
5275 item {stfaf mask} - The total input mask is the combination of the
5276 default pixelmask (if any) and the OTF mask. Once this mask
5277 has been established, then the moment method may make additional
5278 pixel selections.
5280 item {stfaf drop} - If this is true (the default) then the moment axis
5281 is dropped from the output image. Otherwise, the output images have a
5282 moment axis of unit length and coordinate information that is the same
5283 as for the input image. This coordinate information may be totally
5284 meaningless for the moment images.
5286 end{itemize}
5288 Finally, if you ask for a moment which requires the coordinate to be
5289 computed for each profile pixel (these are the intensity weighted mean
5290 coordinate [moment 1] and the intensity weighted dispersion of the
5291 coordinate [moment 2]), and the profile axis is not separable then there
5292 will be a performance loss. Examples of non-separable axes are RA and
5293 Dec. If the axis is separable (e.g. a spectral axis) there is no
5294 penalty. In the latter case, the vector of coordinates for one profile
5295 is the same as the vector for another profile, and it can be precomputed
5296 (once).
5298 Note that this function has no ``virtual'' output file capability. All
5299 output files are written to disk. The output mask for these images is
5300 good (T) unless the moment method fails to generate a value (e.g. the
5301 total input pixel mask was all bad for the profile) in which case it will be bad (F).
5303 If an image has multiple (per-channel beams) and the moment axis is equal to the
5304 spectral axis, each channel will be convolved with a beam that is equal to the beam
5305 having the largest area in the beamset prior to moment determination.
5307 Input Parameters:
5308 moments List of moments that you would like to compute. Default is integrated spectrum.
5309 axis The moment axis. Default is the spectral axis if there is one.
5310 region Region selection. Default is to use the full image.
5311 mask Mask to use. Default is none.
5312 method List of windowing and/or fitting functions you would like to invoke. Vector of strings from 'window' and 'fit'. The default is to not invoke the window or fit functions.
5313 smoothaxes List of axes to smooth. Default is no smoothing.
5314 smoothtypes List of smoothing kernel types, one for each axis to smooth. Vector of strings from 'gauss', 'boxcar', 'hanning'. Default is no smoothing.
5315 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.
5316 includepix Range of pixel values to include. Vector of 1 or 2 doubles. Default is include all pixel.
5317 excludepix Range of pixel values to exclude. Default is exclude no pixels.
5318 peaksnr The SNR ratio below which the spectrum will be rejected as noise (used by the window and fit functions only)
5319 stddev Standard deviation of the noise signal in the image (used by the window and fit functions only)
5320 doppler Velocity doppler definition for velocity computations along spectral axes
5321 outfile Output image file name (or root for multiple moments). Default is input + an auto-determined suffix.
5322 smoothout Output file name for convolved image. Default is don't save the convolved image.
5323 overwrite Overwrite (unprompted) pre-existing output file?
5324 drop Drop moments axis from output images?
5325 stretch Stretch the mask if necessary and possible?
5327 Example:
5330 #
5331 print 't----t moments Ex 1 t----'
5332 ia.fromshape(shape=[32,32,32,32]) # replace with your own cube
5333 im2 = ia.moments(moments=[-1,1,2], axis=2, smoothaxes=[0,1,2],
5334 smoothtypes=['gauss','gauss','hann'],
5335 smoothwidths=[5.0,5.0,3], excludepix=[1e-3],
5336 smoothout='smooth', overwrite=true)
5337 im2.done()
5338 ia.close()
5339 #
5343 In this example, standard moments (average intensity, weighted velocity
5344 and weighted velocity dispersion) are computed via the convolve (spatially
5345 convolved by gaussians and spectrally by a Hanning kernel) and clip
5346 method (we exclude any pixels with absolute value less than $0.001$).
5347 The output file names are automatically created for us and
5348 the convolved image is saved. The returned image tool holds the first
5349 moment image.
5354 #
5355 print 't----t moments Ex 2 t----'
5356 ia.fromshape(shape=[32,32,32,32])
5357 im2 = ia.moments(moments=[3], method=['window'])
5358 im2.done()
5359 ia.close()
5360 #
5364 In this example, the median of each spectrum is computed, after pixel
5365 selection by the automatic window method. The output
5366 image is temporary and accessed via the returned Image tool.
5368 --------------------------------------------------------------------------------
5370 """
5371 return _image.image_moments(self, *args, **kwargs)
5374 def name(self, *args, **kwargs):
5375 """
5376 name(self, _strippath) -> string
5380 Summary:
5381 Name of the image file this tool is attached to
5383 Description:
5387 This function returns the name of the imagefile By default, this
5388 function returns the full absolute path of the imagefile. You can
5389 strip this path off if you wish with the {stfaf strippath} argument and
5390 just recover the imagefile name itself.
5392 Input Parameters:
5393 strippath Strip off the path before the actual file name?
5395 Example:
5398 #
5399 print 't----t name Ex 1 t----'
5400 ia.maketestimage('g1.app', overwrite=true)
5401 print ia.name(strippath=False)
5402 #/casa/code/xmlcasa/implement/images/scripts/g1.app
5403 print ia.name(strippath=True)
5404 #g1.app
5405 ia.close()
5406 #
5409 --------------------------------------------------------------------------------
5411 """
5412 return _image.image_name(self, *args, **kwargs)
5415 def open(self, *args, **kwargs):
5416 """
5417 open(self, _infile, _cache) -> bool
5421 Summary:
5422 Open a new image file with this image tool
5424 Description:
5428 This method detaches from the current image (if an image is attached to the tool), and
5429 reattaches it (opens) to the new image.
5431 The input image file may be in native CASA, FITS, or Miriad format. In the case
5432 of CASA images, images with float, complex float, double, and complex double
5433 valued pixels are supported. Note that only FITS images with float valued pixels
5434 are supported.
5436 The cache parameter applies only to component list images and indicates if pixel
5437 values should be cached after they are computed for faster retrieval. It is not
5438 used for other image types.
5440 Input Parameters:
5441 infile image file name
5442 cache Cache pixel values for use while image is in use? Ignored if image being opened is not a ComponentListImage.
5444 Example:
5447 #
5448 print 't----t open Ex 1 t----'
5449 ia.maketestimage('anotherimage',overwrite=true) #first make 2nd image
5450 ia.close()
5451 ia.maketestimage('myimage',overwrite=true) #open image myimage
5452 ia.open('anotherimage') # attach tool to 'anotherimage'
5453 ia.close()
5454 #
5457 The {stff open} function first closes the old imagefile.
5459 --------------------------------------------------------------------------------
5461 """
5462 return _image.image_open(self, *args, **kwargs)
5465 def pad(self, *args, **kwargs):
5466 """
5467 pad(self, _outfile, _npixels, _value, _padmask, _overwrite, _region, _box, _chans, _stokes, _mask, _stretch, _wantreturn) -> image
5471 Summary:
5472 Pad the perimeter of the direction plane with a number of pixels of specified value and mask.
5474 Description:
5477 This method pads the directional plane of an image with a specified number of pixels on each side. The
5478 numerical and mask values of the padding pixels may also be specified. If a region is selected, a subimage
5479 of that region is created and then padded with the specified pixel parameters. Thus, padding an image of
5480 shape (ra, dec, freq) = (512, 512, 10) specifying npixels = 3 results in an image of size (518, 518, 10), with
5481 the blc of the directional plane of the original pixel set corresponding to the directional pixel of (3, 3)
5482 in the output.
5483 If wantreturn is True, an image analysis tool attached to the output image is returned. If False, none is
5484 returned.
5487 Input Parameters:
5488 outfile Output image name. If not specified, no persistent image is created.
5489 npixels Number of pixels with which to pad each side of the direction plane.
5490 value Value given to the padding pixels.
5491 padmask Value of the mask for the padding pixels. True$=>$good (unmasked), False$=>$bad (masked).
5492 overwrite Overwrite the output if it exists? Default False
5493 region Region selection. Default is to use the full image.
5494 box Rectangular region to select in direction plane. Default is to use the entire direction plane.
5495 chans Channels to use. Default is to use all channels.
5496 stokes Stokes planes to use. Default is to use all stokes planes.
5497 mask Mask to use. Default is none.
5498 stretch Stretch the mask if necessary and possible? Default False
5499 wantreturn Return an image analysis tool attached to the created subimage?
5501 Example:
5503 ia.fromshape('',[50, 50, 10])
5504 # pad it with 5 pixels of value 2.5 all unmasked
5505 padded = ia.pad(npixels=5, value=2.5, padmask=True)
5506 ia.done()
5507 # returns [60, 60, 10]
5508 paddedshape = padded.shape()
5509 padded.done()
5511 --------------------------------------------------------------------------------
5513 """
5514 return _image.image_pad(self, *args, **kwargs)
5517 def crop(self, *args, **kwargs):
5518 """
5519 crop(self, _outfile, _axes, _overwrite, _region, _box, _chans, _stokes, _mask, _stretch, _wantreturn) -> image
5523 Summary:
5524 Crop masked pixels from the perimeter of an image.
5526 Description:
5529 This method crops masked slices from the perimeter of an image. The axes parameter specifies which axes to
5530 consider. Axes not specified will not be cropped. An empty array implies that all axes should be considered.
5531 If wantreturn is True, an image analysis tool attached to the output image is returned. If False, none is
5532 returned.
5535 Input Parameters:
5536 outfile Output image name. If not specified, no persistent image is created.
5537 axes Axes to crop. Empty array means consider all axes.
5538 overwrite Overwrite the output if it exists? Default False
5539 region Region selection. Default is to use the full image.
5540 box Rectangular region to select in direction plane. Default is to use the entire direction plane.
5541 chans Channels to use. Default is to use all channels.
5542 stokes Polarization selection. Default is all.
5543 mask Mask to use. Default is none.
5544 stretch Stretch the mask if necessary and possible? Default False
5545 wantreturn Return an image analysis tool attached to the created subimage?
5547 Example:
5549 # myimage is of shape 20, 20, 20 with only the inner 16 x 14 x 12 pixels unmasked
5550 ia.open('myimage')
5551 # crop masked slices on all axes
5552 cropped = ia.crop()
5553 # returns [16, 14, 12]
5554 cropped.shape()
5555 cropped.done()
5556 # crop only the masked slices at the edges of the image along axis 1
5557 cropped2 = ia.crop(outfile='', axes=[1])
5558 ia.done()
5559 # returns [20, 14, 20]
5560 cropped2.shape()
5561 cropped2.done()
5563 --------------------------------------------------------------------------------
5565 """
5566 return _image.image_crop(self, *args, **kwargs)
5569 def pixelvalue(self, *args, **kwargs):
5570 """
5571 pixelvalue(self, _pixel) -> record *
5575 Summary:
5576 Get value of image and mask at specified pixel coordinate
5578 Description:
5582 This function gets the value of the image and the mask at the specified
5583 pixel coordinate. The values are returned in a record with fields
5584 'value', 'mask' and 'pixel'. The value is returned as a quantity, the mask
5585 as a Bool (T is good). The 'pixel' field holds the actual
5586 pixel coordinate used.
5588 If the specified pixel coordinate is off the image, '{}' is returned.
5590 Excessive elements in {stfaf pixel} are silently discarded.
5591 Missing elements are given the (nearest integer) value of the reference pixel.
5592 This is reflected in the output record 'pixel' field.
5594 Input Parameters:
5595 pixel Pixel coordinate
5597 Example:
5600 #
5601 print 't----t pixelvalue Ex 1 t----'
5602 ia.maketestimage();
5603 ia.pixelvalue()
5604 #{'mask': True,
5605 # 'pixel': array([55, 37]),
5606 # 'value': {'unit': 'Jy/beam', 'value': 2.5064315795898438}}
5607 print ia.pixelvalue([-1,-1])
5608 # {}
5609 print ia.pixelvalue([9])
5610 #{'mask': True,
5611 # 'pixel': array([ 9, 37]),
5612 # 'value': {'unit': 'Jy/beam', 'value': 0.14012207090854645}}
5613 print ia.pixelvalue([9,9,9])
5614 #{'mask': True,
5615 # 'pixel': array([9, 9]),
5616 # 'value': {'unit': 'Jy/beam', 'value': -0.45252728462219238}}
5617 ia.close()
5618 #
5621 --------------------------------------------------------------------------------
5623 """
5624 return _image.image_pixelvalue(self, *args, **kwargs)
5627 def putchunk(self, *args, **kwargs):
5628 """
5629 putchunk(self, _pixels, _blc, _inc, _list, _locking, _replicate) -> bool
5633 Summary:
5634 Put pixels from an array into a regular region of the image
5636 Description:
5640 This method puts an array into the image (which must be writable, eg it
5641 will fail on FITS images). If there is a default pixel mask, it is
5642 ignored. It is the complement of the getchunk() method. The blc, trc,
5643 and increment (inc) may be specified. If they are unspecified, they
5644 default to the beginning of the image and an increment of one.
5646 Any illegal blc values are set to zero. Any illegal inc values are set
5647 to unity.
5649 An error will result if an attempt is made to put an array the extends
5650 beyond the image edge (i.e., it is not truncated or decimated).
5652 If there are fewer axes in the array than in the image, the array is
5653 assumed to have trailing axes of length unity. Thus, if you have a 2D
5654 array and want to put it in as the YZ plane rather than the XY plane,
5655 you must ensure that the shape of the array is [1,nx,ny].
5657 However, the replicate parameter can be used to replicate the array
5658 throughout the image (from the blc to the trc). For example, if a 2D
5659 array is provided for a 3D image, it can be replicated along the third
5660 axis by setting replicate=True. The replication is done from the
5661 specified blc to the end of the image. Method putregion() can be used
5662 to terminate the replication at a trc value.
5664 The locking parameter controls two aspects. If True, then after the
5665 method is called, the image is unlocked (so some other process can
5666 acquire a lock) and it is indicated that the image has
5667 changed. The reason for having this argument is that the unlocking and
5668 updating processes are quite expensive. If putchunk() is called
5669 repeatedly in eg, a loop, it is advisable to set this parameter to True.
5671 A related function is putregion(), which supports putting the pixel and
5672 mask values into a more complex region. Method putchunk() is faster and
5673 therefore preferable for repeated operation in loops if the pixel mask
5674 is not required.
5676 See also the methods set() and calc() which can also be used to change
5677 pixel values.
5679 Input Parameters:
5680 pixels Numeric array. Required input.
5681 blc Bottom-Left-Corner (start) of location in image. Default is start of image.
5682 inc increment (stride) along axes
5683 list List bounding box to logger?
5684 locking Unlock image after use?
5685 replicate Replicate array through image
5687 Example:
5689 We can clip all pixels to be {tt <= } 5 as follows.
5692 #
5693 print 't----t putchunk Ex 1 t----'
5694 ia.fromshape(shape=[10,10]) # create an example image
5695 pix = ia.getchunk() # get pixels to modify from example image
5696 for i in range(len(pix)):
5697 pix[i] = list(pix[i]) # convert tuple to list so it can be modified
5698 for j in range(len(pix[i])):
5699 pix[i][j] = i*10 + j
5700 pix[i] = tuple(pix[i]) # convert list back to tuple
5701 ia.putchunk(pix) # put pixels back into example image
5702 print pix # pixels have values 0-99
5703 pix2 = ia.getchunk() # get all pixels into an array (again)
5704 for i in range(len(pix2)):
5705 pix2[i] = list(pix2[i]) # convert tuple to list so it can be modified
5706 for j in range(len(pix2[i])):
5707 if pix2[i][j] > 5:
5708 pix2[i][j] = 5 # clip values to 5
5709 pix2[i] = tuple(pix2[i]) # convert list back to tuple
5710 ia.putchunk(pix2) # put array back into image
5711 print ia.getchunk()
5712 ia.close()
5713 #
5717 The above example shows how you could clip an image to a value. If
5718 all the pixels didn't easily fit in memory, you would iterate through
5719 the image chunk by chunk to avoid exhausting virtual memory. Better
5720 would be to do this via LEL through function calc.
5722 Suppose we wanted to set the fifth XY plane to 1.
5724 We could do so as follows:
5727 #
5728 print 't----t putchunk Ex 2 t----'
5729 ia.fromshape(shape=[10,10,10])
5730 imshape = ia.shape()
5731 pix = ia.makearray(1, [imshape[0],imshape[1]])
5732 ia.putchunk(pix, blc=[0,0,4])
5733 print ia.getchunk()[0:3]
5734 ia.close()
5735 #
5739 Suppose we wanted to set the first YZ plane to 2.
5743 #
5744 print 't----t putchunk Ex 3 t----'
5745 ia.fromshape(shape=[10,10,10])
5746 imshape = ia.shape()
5747 pix = ia.makearray(2, [1,imshape[1],imshape[2]])
5748 ia.putchunk(pix)
5749 print ia.getchunk()[0:3]
5750 ia.close()
5751 #
5754 --------------------------------------------------------------------------------
5756 """
5757 return _image.image_putchunk(self, *args, **kwargs)
5760 def putregion(self, *args, **kwargs):
5761 """
5762 putregion(self, _pixels, _pixelmask, _region, _list, _usemask, _locking, _replicate) -> bool
5766 Summary:
5767 Put pixels and mask into a region-of-interest of the image
5769 Description:
5773 This function replaces data and/or pixel mask values in the image in the
5774 specified region. The pixels and/or pixelmask arrays must be the shape of
5775 the bounding box, and the whole bounding box is replaced in the image. The
5776 region is only used to specify the bounding box. If the region extends
5777 beyond the image, it is truncated. If the pixels or pixelmask array shapes
5778 do not match the bounding box, an error will result. Values in the pixels
5779 array must share the same domain as the pixel values in the image. If the
5780 pixels array contains real values and the image pixels contain complex
5781 values (or vice versa), an exception will be thrown.
5783 When you put a pixel mask, it either replaces the current default pixel mask,
5784 or is created.
5786 The usemask parameter is only relevant when you are putting pixel values and
5787 there is a pixel mask (meaning also the one you might have just put in place).
5788 If usemask=True, then only pixels for which the mask is good (True) are
5789 altered. If usemask=False, then all the pixels in the region are altered.
5791 The replicate parameter can be used to replicate the array throughout the
5792 image (from the blc to the trc). For example, if a two dimensional array is
5793 provided for a three dimensional image, it can be replicated along the third
5794 axis by setting replicate=True. The replication is done in the specified
5795 region.
5797 The locking parameter controls two things. If True, then after the method
5798 is called, the image is unlocked (so some other process can acquire a lock)
5799 and it is indicated that the image has changed. The reason for this
5800 parameter is that the unlocking and updating processes are quite expensive.
5801 If putregion() is being called multiple times, in a for loop, for example,
5802 it is recommended to set locking=True (and to consider using putchunk()
5803 instead).
5805 See the related functions putchunk, set and calc.
5807 Input Parameters:
5808 pixels The pixel values. Default is none.
5809 pixelmask The pixel mask values. Default is none.
5810 region Region selection. Default is to use the full image.
5811 list List the bounding box and any mask creation to the logger
5812 usemask Honour the mask when putting pixels
5813 locking Unlock image after use?
5814 replicate Replicate array through image
5816 Example:
5818 Suppose that we have a 2-dimensional image. First we recover the pixel
5819 and pixelmask values from a polygonal region. Then we change the values in
5820 the array that are within the region to zero and replace the data.
5824 #
5825 print 't----t putregion Ex 1 t----'
5826 ia.maketestimage() # Attach an image to image tool
5827 x = ['3pix','6pix','9pix','6pix','5pix','5pix','3pix'] # X vector abs pixels
5828 y = ['3pix','4pix','7pix','9pix','7pix','5pix','3pix'] # Y vector abs pixels
5829 mycs = ia.coordsys()
5830 r1 = rg.wpolygon(x,y,csys=mycs.torecord()) # Create polygonal world region
5831 mycs.done()
5832 pixels = ia.getregion(r1) # Recover pixels
5833 pixelmask = ia.getregion(r1, getmask=True) # and mask
5834 for i in range(len(pixels)):
5835 pixels[i] = list(pixels[i]) # convert tuple to list for mods
5836 for j in range(len(pixels[i])):
5837 if pixelmask[i][j]:
5838 pixels[i][j] = 0 # Set pixels where mask is T to zero
5839 pixels[i] = tuple(pixels[i]) # convert list back to tuple
5840 ia.putregion(pixels=pixels, pixelmask=pixelmask,
5841 region=r1) # Replace pixels only
5842 ia.close()
5843 #
5846 --------------------------------------------------------------------------------
5848 """
5849 return _image.image_putregion(self, *args, **kwargs)
5852 def rebin(self, *args, **kwargs):
5853 """
5854 rebin(self, _outfile, _bin, _region, _mask, _dropdeg, _overwrite, _stretch, _crop) -> image
5858 Summary:
5859 Rebin an image by the specified integer factors
5861 Description:
5865 This application rebins the current image by the specified integer binning
5866 factors for each axis. It supports both float valued and complex valued images.
5867 The corresponding output pixel value is the average of the
5868 input pixel values. The output pixel will be masked bad if there
5869 were no good input pixels. A polarization axis cannot be rebinned.
5871 The binning factors array must contain at least one element and no more
5872 elements than the number of input image axes. If the number of elements
5873 specified is less than the number of image axes, then the remaining axes
5874 not specified are not rebinned. All specified values must be positive. A
5875 value of one indicates that no rebinning of the associated axis will occur.
5877 Binning starts from the origin pixel of the bounding box of the selected region or
5878 the origin pixel of the input image if no region is specified. The value of crop
5879 is used to determine how to handle cases where there are pixels
5880 at the end of the axis that do not form a complete bin. If crop=True,
5881 extra pixels at the end of the axis are discarded. If crop=False, the remaining
5882 pixels are averaged into the final bin along that axis. Should the length
5883 of the axis to be rebinned be an integral multiple of the associated binning
5884 factor, the value of crop is irrelevant.
5886 A value of dropdeg=True will result in the output image not containing
5887 axes that are degenerate in the specified region or in the input image if no
5888 region is specified. Note that, however, the binning
5889 factors array must still account for degenerate axes, and the binning
5890 factor associated with a degenerate axis must always be 1.
5892 If {stfaf outfile} is given, the image is written to the specified
5893 disk file. If {stfaf outfile} is unset, the Image tool is
5894 associated with a temporary image. This temporary image may be in
5895 memory or on disk, depending on its size. When you destroy the
5896 on-the-fly Image tool returned by this function (with the done function) this
5897 temporary image is deleted.
5899 Input Parameters:
5900 outfile Output image file name. Default is unset.
5901 bin Binning factors for each axis
5902 region Region selection. Default is to use the full image.
5903 mask Mask to use. Default is none.
5904 dropdeg Drop degenerate axes
5905 overwrite Overwrite (unprompted) pre-existing output file?
5906 stretch Stretch the mask if necessary and possible? Default False
5907 crop Remove pixels from the end of an axis to be rebinned if there are not enough to form an integral bin?
5909 Example:
5912 #
5913 print 't----t rebin Ex 1 t----'
5914 ia.maketestimage();
5915 im2 = ia.rebin(bin=[2,3]);
5916 im2.done()
5917 ia.close()
5918 #
5921 --------------------------------------------------------------------------------
5923 """
5924 return _image.image_rebin(self, *args, **kwargs)
5927 def regrid(self, *args, **kwargs):
5928 """
5929 regrid(self, _outfile, _shape, _csys, _axes, _region, _mask, _method, _decimate, _replicate, _doref, _dropdeg, _overwrite, _force, _asvelocity, _stretch) -> image
5933 Summary:
5934 regrid this image to the specified Coordinate System
5936 Description:
5940 This function regrids the current image onto a grid specified by the given
5941 coordinate system. The shape of the output image may also be specified.
5943 The coordinate system must be specified via a cs tool (using cs.torecord()). It
5944 is optional; if not specified, the coordinate system from the input image (ie,
5945 the one to which you are applying the regrid function) is used. The order of the
5946 coordinates and axes in the output image is always the same as the input image.
5947 It simply finds the relevant coordinate in the supplied coordinate system in
5948 order to determine the regridding parameters. The supplied coordinate system
5949 must have at least as many coordinates as are required to accomodate the axes
5950 that are to be regridded (eg, if the first two axes are to be regridded, and
5951 these belong to a direction coordinate, one direction coordinate in the supplied
5952 coordinate system is required). Coordinates pertaining to axes that are not
5953 being regridded are supplied from the input image, not the specified coordinate
5954 system.
5956 Reference changes are handled (eg, J2000 to B1950, LSR to TOPO). In general, the
5957 conversion machinery attempts to work out how sophisticated it needs to be (eg,
5958 is the regridding being done from LSR to LSR or from LSR to TOPO). However, it
5959 errs on the side of caution if the conversion machine requires more information
5960 than it actually needs. For full frame conversions, one needs to know things
5961 like the position on the earth's surface where the observation occurred,
5962 direction (celestial coordinates) of observation, and time of observation.
5964 If you get such errors and you are doing a frame conversion, then that means you
5965 must insert some extra information into the coordinate system of your image.
5966 Most likely it's the time (in which case you can use cs.setepoch()) and/or
5967 position (in which case you can use cs.settelescope()) that are missing. If you
5968 get these errors and you are certain that you are not specifying a frame change
5969 (eg, regrid LSR to LSR) then try setting doref=False. This will (silently)
5970 bypass all possible frame conversions. Note that if you are requesting a frame
5971 conversion and you set doref=False, no warnings will be emitted and the output
5972 image will likely be nonsensical.
5974 If you regrid a plane holding a direction coordinate and the units are Jy/pixel,
5975 then the output is scaled to conserve flux (roughly; just one scale factor at
5976 the reference pixel is computed).
5978 Regridding of complex-valued images is supported. The real and imaginary parts
5979 are regridded independently and the resulting regridded pixel values are
5980 combined to form the regridded, complex-valued image.
5982 A variety of interpolation schemes are provided (you need only specify the first
5983 three characters to the method parameter). The cubic interpolation is
5984 substantially slower than linear, and often the improvement is modest. By
5985 default, linear interpolation is used.
5987 You specify the shape of the output image using the shape parameter and which
5988 output axes you want to regrid. Note that a Stokes axis cannot be regridded
5989 (you will get a warning if you try).
5991 The axes parameter cannot be used to discard axes from the output image; it can
5992 only be used to specify which output axes are going to be regridded and which
5993 are not. Any axis that you are not regridding must have the same output shape as
5994 the input image shape for that axis.
5996 The axes parameter can also be used to specify the order in which the output
5997 axes are regridded. This may give you significant performance benefits. For
5998 example, imagine we are going to regrid a spectral-line cube of shape
5999 [512,512,1204] to shape [256,256,32]. If you specified axes=[0,1,2] then first,
6000 the direction axes would be regridded for each of the 1024 pixels (and stored in
6001 a temporary image). Then each spectral profile at each spatial location in the
6002 temporary image would be regridded to 32 pixels. You could speed this process
6003 up significantly by setting axes=[2,0,1]. In this case, first each spectral
6004 profile would be regridded to 32 pixels, and then each plane of the 32 pixels
6005 would be regridded. Note that the order of axes does not affect the order of the
6006 shape parameter; ie, it should be given in the natural pixel axis order of the
6007 image ()[256,256,32] in both cases of this example).
6009 You can also specify a region to be applied to the input image. If you do this,
6010 you need to be careful with the output shape for non-regridded axes (must match
6011 that of the region - use function ia.boundingbox() to determine that).
6013 If the outfile parameter is specified, the image is written to the specified
6014 disk file. If this parameter is unset, the on-the-fly image analysis tool
6015 returned by this method is associated with a temporary image. This temporary
6016 image may be in memory or on disk, depending on its size. When you destroy the
6017 on-the-fly image analysis tool (with either the ia.close() or ia.done()
6018 methods), this temporary image is deleted.
6020 The replicate parameter can be used to simply replicate pixels rather than
6021 regridding them. Normally replicate=False, for every output pixel, its world
6022 coordinate is computed and the corresponding input pixel found (then a little
6023 interpolation grid is generated). If replicate=True, then for every output
6024 axis, a vector of regularly sampled input pixels is generated (based on the
6025 ratio of the output and input axis shapes). So this just means the pixels get
6026 replicated (by whatever interpolation scheme you use) rather than regridded in
6027 world coordinate space. This process is much faster, but its not a true world
6028 coordinate based regrid.
6030 As decribed above, when replicate=False, a coordinate is computed for each
6031 output pixel; this is an expensive operation. The decimate parameter allows you
6032 to decimate the computation of that coordinate grid to a sparse grid, which is
6033 then filled in via fast interpolation. The default is decimate=10. The number
6034 of pixels per axis in the sparse grid is the number of output pixels for that
6035 axis divided by the decimation factor. A factor of 10 does pretty well. You may
6036 find that for very non-linear coordinate systems (e.g. very close to the pole)
6037 that you have to reduce the decimation factor. You may also have to reduce the
6038 decimation factor if the number of pixels in the output image along an axis to
6039 be regridded is less than about 50, or the output image may be completely
6040 masked.
6042 If one of the axes to be regridded is a spectral axis and asvelocity=True, the
6043 axis will be regridded to match the velocity, not the frequency, description of
6044 the template spectral coordinate. Thus the output pixel values will correspond
6045 only to the velocity, not the frequency, of the output axis.
6047 Sometimes it is useful to drop axes of length one (degenerate axes). Setting
6048 the dropdeg parameter to True will do that. It will discard the axes from the
6049 input image. Therefore the output shape and coordinate system that you supply
6050 must be consistent with the input image after the degenerate axes are dropped.
6052 The force parameter can be used to force all specified axes to be regridded,
6053 even if the algorithm determines that they don't need to be (because the input
6054 and output coordinate information is identical).
6056 The cs tool has a useful method, cs.setreferencelocation(), that can be used to
6057 keep a specific world coordinate in the center of an image when regridding (see
6058 example below).
6060 The output pixel mask will be True (good) unless the regridding failed to find a
6061 value for that output pixel in which case it will be False. For example, if the
6062 total input mask (default input pixel mask plus OTF mask) for all of the
6063 relevant input pixels were masked bad then the output pixel would be masked
6064 (False).
6066 MULTIPLE AXIS COORDINATES LIMITATION
6067 Some cooordinates contain multiple axes. For example, a direction coordinate
6068 contains both longitude-like and latitude-like axes. A linear coordinate can
6069 also contain multiple axes. When you regrid *any* axis from a coordinate which
6070 contains multiple axes, you must fully specify the coordinate information for
6071 all axes in that coordinate in the coordinate system that you provide. For
6072 example, if you have a linear coordinate with two axes and you want to regrid
6073 axis one only. In the coordinate system you provide, the coordinate information
6074 for axis two (not being regridded) must correctly be a copy from the input
6075 coordinate system (it won't be filled in for you).
6077 If an image has per-plane beams and one attempts to regrid the spectral axis,
6078 an exception is thrown.
6080 IMPORTANT NOTE ABOUT FLUX CONSERVATION
6081 in general regridding is inaccurate for images that the angular resolution is
6082 poorly sampled. A check is done for such cases and a warning message is emitted
6083 if a beam present. However, no such check is done if there is no beam present.
6084 To add a restoring beam to an image, use ia.setrestoringbeam().
6086 Input Parameters:
6087 outfile Output image file name. Default is unset.
6088 shape Shape of output image. Default is input shape.
6089 csys Coordinate System for output image. Default is input image coordinate system.
6090 axes The output pixel axes to regrid. Default is all.
6091 region Region selection. Default is to use the full image.
6092 mask Mask to use. Default is none.
6093 method The interpolation method. String from 'nearest', 'linear', 'cubic'.
6094 decimate Decimation factor for coordinate grid computation
6095 replicate Replicate image rather than regrid?
6096 doref Turn on reference frame changes
6097 dropdeg Drop degenerate axes
6098 overwrite Overwrite (unprompted) pre-existing output file?
6099 force Force specified axes to be regridded
6100 asvelocity Regrid spectral axis in velocity space rather than frequency space?
6101 stretch Stretch the mask if necessary and possible? Default False
6103 Example:
6106 #
6107 print 't----t regrid Ex 1 t----'
6108 ia.maketestimage('radio.image', overwrite=true)
6109 ia.maketestimage('optical.image', overwrite=true)
6110 mycs = ia.coordsys(); # get optical image co-ordinate system
6111 ia.open('radio.image')
6112 imrr = ia.regrid(outfile='radio.regridded', csys=mycs.torecord(),
6113 shape=ia.shape(), overwrite=true)
6114 #viewer()
6115 mycs.done()
6116 imrr.done()
6117 ia.close()
6118 #
6122 In this example, we regrid a radio image onto the grid of an optical
6123 image - this probably (if the optical FITS image was correctly labelled
6124 !!) will involve a projection change (optical images are usually TAN
6125 projection, radio usually SIN).
6129 #
6130 print 't----t regrid Ex 2 t----'
6131 ia.maketestimage('radio.image',overwrite=true)
6132 mycs = ia.coordsys();
6133 print mycs.referencecode('dir')
6134 #J2000
6135 mycs.setreferencecode(value='B1950', type='dir', adjust=True)
6136 im3 = ia.regrid(outfile='radio.regridded', csys=mycs.torecord(),
6137 shape=ia.shape(), overwrite=true)
6138 mycs.done()
6139 im3.done()
6140 ia.close()
6141 #
6145 In this example, we regrid a radio image from J2000 to B1950. This is
6146 accomplished by first recovering the Coordinate System into a
6147 Coordsys tool, manipulating the reference code
6148 with that tool, and then supplying the new Coordinate System to the
6149 regrid function.
6153 #
6154 print 't----t regrid Ex 3 t----'
6155 ia.maketestimage('zz', overwrite=true)
6156 mycs = ia.coordsys();
6157 p = ia.shape()
6158 for i in range(len(p)):
6159 p[i] = p[i]/2.0 + 10
6160 refval = ia.toworld(value=p, format='n') # Location of interest
6161 inc = mycs.increment()
6162 incx = inc['numeric']
6163 for i in range(len(incx)):
6164 incx[i] = incx[i]/2.0 # Halve increment
6165 inc['numeric']=incx
6166 mycs.setincrement(value=inc) # Set increment
6167 shp = ia.shape()
6168 refpix=refval['numeric'][:]
6169 refpix=list(refpix) # numpy makes this necessary
6170 for i in range(len(shp)):
6171 shp[i] = shp[i] *2 # Double shape
6172 refpix[i] = int((shp[i]-1)/2.0 + 1); # New ref pix
6173 # Center image on location of interest
6174 mycs.setreferencelocation(pixel=refpix, world=refval)
6175 imr = ia.regrid(csys=mycs.torecord(), shape=shp, overwrite=true)# Regrid
6176 mycs.done()
6177 imr.done()
6178 ia.close()
6179 #
6182 --------------------------------------------------------------------------------
6184 """
6185 return _image.image_regrid(self, *args, **kwargs)
6188 def transpose(self, *args, **kwargs):
6189 """
6190 transpose(self, _outfile, _order) -> image
6194 Summary:
6195 Transpose the image.
6197 Description:
6200 This method transposes the axes in the input image to the specified
6201 order. The associated pixel and mask values and coordinate system are transposed.
6203 If the outfile parameter is empty, only a temporary image is created; no output image
6204 is written to disk.
6206 The order parameter describes the mapping of the input axes to the output axes.
6207 It can be one of three types: a non-negative integer, a string, or a list of
6208 strings. If a string or non-negative integer, it should contain
6209 zero-based digits describing the new order of the input axes. It must
6210 contain the same number of (unique) digits as the number of input axes. For example,
6211 specifying reorder='1032' or reorder=1032 for a four axes image maps input axes
6212 1, 0, 3, 2 to output axes 0, 1, 2, 3. In the case of order being a nonnegative integer
6213 and the zeroth axis in the input being mapped to zeroth axis in the output, the zeroth
6214 digit is implicitly understood to be 0 so that to transpose an image where one would
6215 use a string order='0321', one could equivalently specify an int order=321.
6216 IMPORTANT: When specifying a non-negative integer and mapping the zeroth axis of
6217 the input to the zeroth axis of the output, do *not* explicitly specify the leading
6218 0; eg, specify order=321 rather than order=0321. Python interprets an integer with
6219 a leading 0 as an octal number.
6221 Because of ambiguity for axes numbers greater than nine, using string or integer order
6222 specifications cannot handle images containing more than 10 axes.
6223 The order parameter can also be specified as a list of strings which uniquely minimally match,
6224 ignoring case, the image axis names (ia.coordsys().names()).
6225 So to reorder an image with right ascension, declination, and frequency axes, one could
6226 specify order=['d', 'f', 'r'] or equivalently ['decl', 'frequ', 'right a']. Note that
6227 specifying 'ra' for the right ascension axis will result in an error because 'ra' does
6228 not match the first two characters of right ascension.
6229 Axes can be simultaneously inverted in cases where order is a string or an array of
6230 strings by specifying negative signs in front of the axis/axes to be inverted. So,
6231 in a 4-D image, order='-10-3-2' maps input axes 1, 0, 3, 2 to output axes 0, 1, 2, 3
6232 and reverses the direction and values of input axes 1, 3, and 2.
6235 Input Parameters:
6236 outfile Output image file name. Default is unset.
6237 order Zero-based order of axes in output image (eg '120' $=>$ input$->$ output 0-$>$2, 1-$>$0, 2-$>$1))
6239 Example:
6242 # swap stokes (axis 2) and spectral (axis 3) axes in a 4 dimensional image
6243 ia.open('myimage.fits')
6244 reordim = ia.transpose(outfile='my_reordered_image.im', order='0132')
6245 ia.done()
6248 --------------------------------------------------------------------------------
6250 """
6251 return _image.image_transpose(self, *args, **kwargs)
6254 def rotate(self, *args, **kwargs):
6255 """
6256 rotate(self, _outfile, _shape, _pa, _region, _mask, _method, _decimate, _replicate, _dropdeg, _overwrite, _stretch) -> image
6260 Summary:
6261 rotate the direction coordinate axes attached to the image and regrid the image to the rotated Coordinate System
6263 Description:
6267 This function rotates two axes of an image. These axes are either
6268 those associated with a Direction coordinate or with a Linear
6269 coordinate. The Direction coordinate takes precedence.
6270 If rotating a Linear coordinate, it must hold precisely two axes.
6272 The method is that the Coordinate is rotated and then the input
6273 image is regridded to the rotated Coordinate System.
6275 If the image brightness units are Jy/pixel then the output is scaled to
6276 conserve flux (roughly; just one scale factor at the reference pixel is
6277 computed).
6279 A variety of interpolation schemes are provided (you need only specify
6280 the first three characters to {stfaf method}). The cubic
6281 interpolation is substantially slower than linear. By default you get
6282 cubic interpolation.
6284 You can specify the shape of the output image ({stfaf shape}).
6285 However, all axis that are not regrided retain the same output shape
6286 as the input image shape for that axis. Only the direction coordinate
6287 axes are regridded.
6289 You can also specify a region to be applied to the input image. If
6290 you do this, you need to be careful with the output shape for
6291 non-regridded axes (must match that of the region - use function
6292 boundingbox to find that out).
6294 If {stfaf outfile} is given, the image is written to the specified
6295 disk file. If {stfaf outfile} is unset, the on-the-fly Image tool
6296 returned by this function is associated with a temporary image. This
6297 temporary image may be in memory or on disk, depending on its size.
6298 When you destroy the on-the-fly Image tool (with the done function) this
6299 temporary image is deleted.
6301 The argument {stfaf replicate} can be used to simply replicate pixels
6302 rather than regridding them. Normally ({stfaf replicate=F}), for every
6303 output pixel, its world coordinate is computed and the corresponding
6304 input pixel found (then a little interpolation grid is generated). If
6305 you set {stfaf replicate=T}, then what happens is that for every output
6306 axis, a vector of regularly sampled input pixels is generated (based on
6307 the ratio of the output and input axis shapes). So this just means the
6308 pixels get replicated (by whatever interpolation scheme you use) rather
6309 than regridded in world coordinate space. This process is much faster,
6310 but its not a true world coordinate based regrid.
6312 As decribed above, when {stfaf replicate} is False, a coordinate is
6313 computed for each output pixel; this is an expensive operation. The
6314 argument {stfaf decimate} allows you to decimate the computation of
6315 that coordinate grid to a sparse grid, which is then filled in via
6316 fast interpolation. The default for {stfaf decimate} is 0 (no
6317 decimation). The number of pixels per axis in the sparse grid is the
6318 number of output pixels for that axis divided by the decimation
6319 factor. A factor of 10 does pretty well. You may find that for very
6320 non-linear coordinate systems (e.g. very close to the pole) that you
6321 have to reduce the decimation factor.
6323 The output pixelmask will be good (T) unless the regridding failed to
6324 find a value for that output pixel in which case it will be bad (F).
6325 For example, if the total input mask (default input pixelmask plus OTF
6326 mask) for all of the relevant input pixels were masked bad
6327 then the output pixel would be masked bad (F).
6329 Input Parameters:
6330 outfile Output image file name. Default is unset.
6331 shape Shape of output image. Default is shape of input image.
6332 pa Angle by which to rotate. Default is no rotation.
6333 region Region selection. Default is to use the full image.
6334 mask Mask to use. Default is none.
6335 method The interpolation method. String from 'nearest', 'linear', or 'cubic'.
6336 decimate Decimation factor for coordinate grid computation
6337 replicate Replicate image rather than regrid?
6338 dropdeg Drop degenerate axes
6339 overwrite Overwrite (unprompted) pre-existing output file?
6340 stretch Stretch the mask if necessary and possible? Default False
6342 Example:
6345 ia.maketestimage()
6346 imr=ia.rotate(outfile='rotated.im', pa='45deg')
6347 imr.done()
6348 ia.close()
6351 In this example, we rotate the direction coordinate axes (RA/Dec) of a
6352 test image by 45 degress and regrid the image onto the axes.
6354 --------------------------------------------------------------------------------
6356 """
6357 return _image.image_rotate(self, *args, **kwargs)
6360 def rotatebeam(self, *args, **kwargs):
6361 """
6362 rotatebeam(self, _angle) -> bool
6366 Summary:
6367 rotate the image's beam(s) counterclockwise through the specified angle.
6369 Description:
6372 This method rotates the attached image's beam(s) counterclockwise through the specified angle.
6373 This is the same thing as increasing the position angle(s) of the beam(s) by the specified angle.
6374 If the image does not have a beam, no changes to the image are made. If the image has multiple
6375 beams, all the beams are rotated through the same angle.
6377 Input Parameters:
6378 angle Angle by which to rotate image's beam(s). Default is no rotation.
6380 Example:
6382 # rotate any and all beams in the image (increase their position angles) by 30 degrees.
6383 ia.open('my.im')
6384 ia.rotatebeam('30deg')
6385 ia.done()
6387 --------------------------------------------------------------------------------
6389 """
6390 return _image.image_rotatebeam(self, *args, **kwargs)
6393 def rename(self, *args, **kwargs):
6394 """
6395 rename(self, _name, _overwrite) -> bool
6399 Summary:
6400 Rename the image file associated with this image tool
6402 Description:
6406 This function renames the imagefile associated with the imagetool.
6407 If a file with name {stfaf name} already exists, you can overwrite it
6408 with the argument {stfaf overwrite}; otherwise a fail will
6409 result.
6411 Input Parameters:
6412 name The new image file name
6413 overwrite Overwrite target file if it already exists
6415 Example:
6418 Example:
6419 #
6420 print ' ---- rename Ex 1, rename a new image ----'
6421 ia.maketestimage('myimage',overwrite=True)
6422 print ia.name(strippath=True)
6423 #myimage
6424 ia.rename('newimage', overwrite=True)
6425 print ia.name(strippath=True)
6426 #newimage
6427 #
6428 print ' ---- rename Ex 2, rename an existing image ----'
6429 ia.open('originalimage',overwrite=True)
6430 ia.rename('newimage', overwrite=True)
6431 ia.close()
6432 #
6435 --------------------------------------------------------------------------------
6437 """
6438 return _image.image_rename(self, *args, **kwargs)
6441 def replacemaskedpixels(self, *args, **kwargs):
6442 """
6443 replacemaskedpixels(self, _pixels, _region, _mask, _update, _list, _stretch) -> bool
6447 Summary:
6448 replace the values of pixels which are masked bad
6450 Description:
6454 This application replaces the values of all pixels whose total input mask
6455 (default input pixelmask and OTF mask) is bad (F) with the specified
6456 value. It supports both float valued and compplex valued images.
6458 If the argument {stfaf update} is F (the default), the actual pixelmask
6459 is left unchanged. That is, masked pixels remain masked. However, if
6460 you set {stfaf update=T} then the pixelmask will be updated so that the
6461 pixelmask will now be T (good) where the {bf total} input mask was F
6462 (bad).
6464 See maskhandler for information
6465 on how to set the default pixelmask.
6467 There are a few ways in which you can specify what to replace the
6468 masked pixel values by.
6470 begin{itemize}
6472 item First, you can give the {stfaf pixels} argument a simple numeric
6473 scalar (e.g. {cf pixels=1.0}). Then, all masked values will be
6474 replaced by that value.
6476 item Second, you can give a scalar
6477 htmladdnormallink{LEL}{../../notes/223/223.html} expression string
6478 (e.g. {cf pixels='min(myimage)'}). Then, all masked values will be
6479 replaced by the scalar that results from the expression. If the scalar expression
6480 is illegal (e.g. in the expression {cf pixels='min(myimage)'} there
6481 were no good pixels in {sff myimage}) then the value 0 is used for
6482 replacement.
6484 item Third, you can give a
6485 htmladdnormallink{LEL}{../../notes/223/223.html} expression string
6486 which has the same shape as the imagefile you are applying the
6487 function to. For example, putting {cf pixels='myotherimage'} means
6488 replace all masked pixels in this imagefile with the equivalent pixel
6489 in the imagefile called {sff myotherimage}.
6491 Your expression might be quite complex, and you can think of it as
6492 producing another masked lattice. However, in the replace process, the
6493 mask of that expression lattice is ignored. Thus, only the mask of
6494 the imagefile you are replacing and the pixel values of the expression
6495 lattice are relevant.
6497 The expression must conform with the subimage formed by applying the
6498 region to the image (i.e. that associated with this Image tool). If
6499 you use the {stfaf mask} argument as well, the region is applied to
6500 it as well (see examples).
6502 end{itemize}
6504 Input Parameters:
6505 pixels The new value(s), Numeric scalar or LEL expression
6506 region Region selection. Default is to use the full image.
6507 mask Mask to use. Default is none.
6508 update Update mask as well?
6509 list List the bounding box to the logger
6510 stretch Stretch the mask if necessary and possible? Default False
6512 Example:
6515 #
6516 print 't----t replacemaskedpixels Ex 1 t----'
6517 ia.maketestimage('zz1',overwrite=true)
6518 ia.calcmask('zz1<0')
6519 ia.replacemaskedpixels(0.0)
6520 ia.replacemaskedpixels('min(zz1)')
6521 ia.close()
6522 #
6526 These examples replace all masked pixels by the specified scalar. In
6527 the second case, the scalar comes from a LEL expression operating on
6528 {sff zz1} (or it could be from an LEL expression operating on some
6529 other image).
6534 #
6535 print 't----t replacemaskedpixels Ex 2 t----'
6536 ia.maketestimage('zz2',overwrite=true)
6537 ia.close()
6538 ia.maketestimage('zz1',overwrite=true)
6539 #ia.calcmask('zz1<0')
6540 ia.replacemaskedpixels(0.0, mask='zz2>0')
6541 ia.close()
6542 #
6546 Let us say that {sff zz1} has no mask. By using the {stfaf mask}
6547 argument, we generate a transient mask which is T (good) when the pixel
6548 values are positive. This means that all non-positive values (when that
6549 mask is F [bad]) will be replaced with the value 0. If {sff zz1} did
6550 have a mask it would be applied as well as the transient mask (the masks
6551 would be logically ORed).
6556 #
6557 print 't----t replacemaskedpixels Ex 3 t----'
6558 ia.maketestimage('zz1',overwrite=true)
6559 ia.calcmask('zz1<0')
6560 im2 = ia.subimage(outfile='zz2',overwrite=true)
6561 # r = rg.quarter()
6562 r=rg.box([0.25,0.25],[0.75,0.75],frac=true)
6563 ia.replacemaskedpixels(0.0, region=r, mask=im2.name(strippath=True)+'>0')
6564 # same as ia.replacemaskedpixels(0.0, region=r, mask='zz2>0')
6565 im2.done()
6566 ia.close()
6567 #
6571 The specified region takes one quarter of the image by area centered on
6572 the image center. The region is applied to the {stfaf mask} expression
6573 as well - this means that any images in the {stfaf mask} expression
6574 must conform with the {sff zz1} image. The replacement of the
6575 scalar is then done only within that region. Note that in
6576 the {stfaf mask} expression we have specified the image with
6577 the Image tool {stf im2} via im2.name() (rather than referring
6578 to its disk file name {sff zz2}).
6583 #
6584 print '----t replacemaskedpixels Ex 4 t----'
6585 ia.maketestimage('zz3',overwrite=true)
6586 ia.maketestimage('zz2',overwrite=true)
6587 ia.maketestimage('zz1',overwrite=true)
6588 ia.calcmask('zz1<0')
6589 ia.replacemaskedpixels('zz2+zz3')
6590 ia.close()
6591 #
6595 In this example, the replacement values are taken
6596 from a LEL expression adding two other images
6597 together. The expression must conform with the
6598 image {sff zz1}.
6600 --------------------------------------------------------------------------------
6602 """
6603 return _image.image_replacemaskedpixels(self, *args, **kwargs)
6606 def beamarea(self, *args, **kwargs):
6607 """
6608 beamarea(self, _channel, _polarization) -> record *
6612 Summary:
6613 Get the beam area.
6615 Description:
6618 Get the area of the image's restoring beam. If a non-negative channel and non-negative polarization
6619 are specified, the area for the beam associated with that channel and polarization will be
6620 returned. The return value will be a dictionary containing the keys 'arcsec2' and 'pixels', and
6621 the associated values will be the beam area in arcsec2 and in pixels, respectively. If both
6622 channel and polarization are set to negative values, then a dictionary with the same keys will
6623 be returned, and the values will be either scalars (if the image has a single traditional
6624 beam) or arrays if the image has multiple beams. In the latter case, the arrays will have
6625 shapes indicative of the number of channels and number of polarizations. If the image has
6626 a spectral axis but not a polarization axis, the returned arrays will be one dimensional and
6627 have a length equal to the number of channels. Similarly, if the image has a polarization
6628 axis but not a spectral axis, the arrays will be one dimensional and have a lenghts equal
6629 to the number of polarizations. If the image has both a spectral and polarization axis,
6630 the returned arrays will be two dimensional with shape (m, n) where m is the length
6631 of the first channel or polarization axis, and n is the length of the second channel or
6632 polarization axis. So, if an image has shape [200, 200, 10, 4] with 10 channels and
6633 4 stokes, the returned arrays will have shapes of (10, 4) representing the spectral
6634 axis as the first axis and the polarization axis as the second. If, instead, the image
6635 shape is [200, 200, 4, 10] again with 10 channels and 4 stokes, the shape of the
6636 returned arrays will be (4, 10) since the polarization axis precedes the spectral
6637 axis.
6640 Input Parameters:
6641 channel The zero-based spectral channel number for a per-plane beam. Default -1
6642 polarization The zero-based polarization plane number for a per-plane beam. Default -1
6644 --------------------------------------------------------------------------------
6646 """
6647 return _image.image_beamarea(self, *args, **kwargs)
6650 def restoringbeam(self, *args, **kwargs):
6651 """
6652 restoringbeam(self, _channel, _polarization, _mbret) -> record *
6656 Summary:
6657 Get the restoring beam(s).
6659 Description:
6663 This function returns the restoring beam(s), if any, of the attached image.
6665 If mbret='matrix' (or 'm'), an exception will be thrown if the attached image
6666 does not have per-plane beams, or if channel or polarization is specified to be
6667 non-negative. See below for more information on the mbret parameter.
6669 If mbret='list' (or 'l') and the attached image has no restoring beam(s), an
6670 empty dictionary is returned.
6672 If the image has a single traditional restoring beam and mbret='list',
6673 the beam is returned as a dictionary no matter what channel and polarization
6674 values are specified. This dictionary has keys 'major',
6675 'minor', andi 'positionangle', and each of these fields
6676 contains a dictionary with 'value' and 'unit' keys which
6677 provide the quantity associated with each beam parameter.
6679 If mbret='list', and if the image has per-plane beams, and the image
6680 has both spectral and polarization axes, and if both channel and polarization
6681 are set to non-negative values that are less than the number of planes along
6682 each parameter's representative axis, the beam for that particular
6683 channel/polarization pair is returned. If at least one of these values is set
6684 to greater or equal to the number of planes along that parameter's
6685 representative axis, and that axis exists and is not degenerate, then an
6686 exception will be thrown. In the case of a non-extant axis or a degenerate axis,
6687 the parameter associated with that axis can be set to any value and a beam will
6688 be returned, because in that case there is exactly one beam for each plane
6689 along the other parameter's representative axis, and so there is no ambiguity
6690 regarding which beam to return. In the case where both spectral and polarization
6691 axes exist and are not degenerate, an exception will be thrown if one of channel
6692 or polarization is set to a non-negative value and the other is set to a
6693 negative value. In the above cases in which a beam is returned, the returned
6694 dictionary will have the same structure as that previously described in the
6695 single beam case.
6697 If the image contains multiple beams and both channel and polarization are
6698 specified to be negative, the structure of the returned dictionary depends on
6699 the specified value of mbret. Supported values of this parameter are
6700 'list' and 'matrix' (case insensitive, mimimum match
6701 supported). In both cases, the returned dictionary will contain the keys
6702 'nChannels', which contains an integer value equal to the number of
6703 channels, and 'nStokes', which contains an integer value equal to the
6704 number of polarizations. In the case where one axis doesn't exist, the
6705 associated value will be 1.
6707 In the case of mbret='list', the returned dictionary will contain the
6708 key 'beams', which contains a sub-dictionary of information for all
6709 beams. This subdictionary contains keys '*0' through
6710 '*(c-1)', where c is the value associated with the
6711 'nChannels' key. Each of these keys has an associated value which is a
6712 subdictionary containing keys '*0' through '*(p-1)', where p
6713 is the value associated associated with the 'nStokes' key. Each
6714 of these keys has an assciated value of a beam dictionary, the structure of
6715 which is the same as described previously for a single beam image, which is
6716 associated with that particular channel/polarization pair.
6718 In the case of mbret='matrix', the returned dictionary will have keys
6719 'major', 'minor', and 'pa' which hold values
6720 representing the major axes, the minor axes, and the position angle,
6721 respectively, of all beams. Each of these fields contains a dictionary which
6722 represents a quantity with keys 'unit' and 'value'. The
6723 'unit' field contains a string representing the unit of the
6724 associated value. The 'value' field contains a matrix with values
6725 corresponding to the associated parameter for the associated beam. In the case
6726 where an image does not have both a spectral and polarization axis, these
6727 matrices will have shape (n, 1), where n is the number of planes on the extant
6728 axis. In the case where an image has both spectral and polarization axes, the
6729 matrices will have shape (m, n) where m is the number of channels if the
6730 spectral axis precedes the polarization axis, or the number of polarization
6731 planes otherwise, and n is the number of planes on the axis not represented by
6732 m. So, an image with a spectral axis that has 5 channels and precedes the
6733 polarization axis that has 4 planes, the returned matrix shape will be (5, 4).
6734 In the case where the number of spectral and polarization planes are the same
6735 as in the previous example, but the polarization axis precedes the spectral
6736 axis, the matrix shape will be (4, 5). Thus, the matrix shape pair follows the
6737 order of the image spectral and polarization axes. This mode is useful for
6738 returning to the python UI the major axes, minor axes, and position angles
6739 directly as numpy arrays.
6741 The restoring beam(s) of an image may be set with image tool method
6742 setrestoringbeam.
6744 Input Parameters:
6745 channel The zero-based spectral channel number for a per-plane beam. Default -1
6746 polarization The zero-based polarization plane number for a per-plane beam. Default -1
6747 mbret Determines the format of the dictionary returned if there are multiple beams and both channel and polarization are negative. Supported values are 'list' and 'matrix' (case insensitive, minimum match supported).
6749 Example:
6752 #
6753 print 't----t restoringbeam Ex 1 t----'
6754 ia.maketestimage()
6755 print ia.restoringbeam()
6756 #{'major': {'unit': 'arcsec', 'value': 53.500004857778549},
6757 # 'minor': {'unit': 'arcsec', 'value': 34.199998900294304},
6758 # 'positionangle': {'unit': 'deg', 'value': 6.0}}
6759 ia.close()
6760 #
6763 --------------------------------------------------------------------------------
6765 """
6766 return _image.image_restoringbeam(self, *args, **kwargs)
6769 def sepconvolve(self, *args, **kwargs):
6770 """
6771 sepconvolve(self, _outfile, _axes, _types, _widths, _scale, _region, _mask, _overwrite, _stretch) -> image
6775 Summary:
6776 Separable convolution
6778 Description:
6782 This function does Fourier-based
6783 convolution of an imagefile by a specified separable kernel.
6785 If {stfaf outfile} is given, the image is written to the specified
6786 disk file. If {stfaf outfile} is unset, the on-the-fly Image tool
6787 returned by this function is associated with a temporary image. This
6788 temporary image may be in memory or on disk, depending on its size.
6789 When you destroy the Image tool (with the done function) this
6790 temporary image is deleted.
6792 You specify which axes of the image you wish to convolve, by what kernel
6793 of what width. The kernel types can be shortened to {cf 'gauss',
6794 'hann'} and {cf 'box'}.
6796 You specify the widths of the convolution kernels via the argument
6797 {stfaf widths}. The values can be specified as a vector of three
6798 different types.
6800 begin{itemize}
6802 item Quantity - for example {stfaf widths=qa.quantity('1arcsec 0.00001rad')}.
6803 Note that you can use pixel units, viz. {stfaf widths=qa.quantity('10pix 0.00001rad')}
6804 see below.
6806 item String - for example {stfaf widths='1km 2arcsec'} (i.e. a string that
6807 qa.quantity() accepts).
6811 item Numeric - for example {stfaf widths=[10,20]}. In this case,
6812 the units of the widths are assumed to be in pixels.
6814 end{itemize}
6816 The interpretation of {stfaf widths} depends upon the kernel type.
6818 begin{itemize}
6820 item Gaussian - the specified width is the full-width at
6821 half-maximum.
6823 item Boxcar (tophat) - the specified width is
6824 the full width.
6826 item Hanning - The kernel is $z[i] = 0.25*y[i-1] + 0.5*y[i] +
6827 0.25*y[i+1]$. The width is always 3 pixels, regardless of what
6828 you give (but you still have to give it !).
6830 end{itemize}
6832 The scaling of the output image is determined by the argument {stfaf scale}.
6833 If you leave it unset, then autoscaling will be invoked which means that
6834 the convolution kernels will all be normalized to have unit volume
6835 to as to conserve flux.
6837 If you do not leave {stfaf scale} unset, then the convolution kernel
6838 will be scaled by this value (it has peak unity before application
6839 of this scale factor).
6841 Masked pixels will be assigned the value 0.0 before convolution.
6842 The output mask is the combination (logical OR) of the default input
6843 pixelmask (if any) and the OTF mask. Any other input pixelmasks
6844 will not be copied. Use function
6845 maskhandler if you need to copy other
6846 masks too.
6848 See also the other convolution functions
6849 convolve2d,
6850 convolve and
6851 hanning.
6853 Input Parameters:
6854 outfile Output image file name. Default is unset.
6855 axes Axes to convolve. Default is [0,1,...].
6856 types Type of convolution kernel. Vector of strings from 'boxcar', 'gaussian', and 'hanning'. Default is appropriately sized vector of 'gaussian'.
6857 widths Convolution kernel widths, Vector of numeric, quantity or string
6858 scale Scale factor. Default is autoscale.
6859 region Region selection. Default is to use the full image.
6860 mask Mask to use. Default is none.
6861 overwrite Overwrite (unprompted) pre-existing output file?
6862 stretch Stretch the mask if necessary and possible? Default False
6864 Example:
6867 #
6868 print 't----t sepconvolve Ex 1 t----'
6869 ia.maketestimage('xyv',overwrite=true)
6870 im2 = ia.sepconvolve(outfile='xyv.con', axes=[0,1], types=['gauss','box'], widths=[10,20], overwrite=true)
6871 im2.done()
6872 ia.close()
6873 #
6876 --------------------------------------------------------------------------------
6878 """
6879 return _image.image_sepconvolve(self, *args, **kwargs)
6882 def set(self, *args, **kwargs):
6883 """
6884 set(self, _pixels, _pixelmask, _region, _list) -> bool
6888 Summary:
6889 Set pixel and/or mask values with a scalar in a region-of-interest of the image
6891 Description:
6895 This function replaces data and/or mask values within the image in the
6896 specified region. You can think of it as a simplified version of the
6897 image calculator.
6899 Unlike the calc function, you can
6900 only set a scalar value for all pixels in the specified region. For
6901 example, it can be useful to set a whole image to one value, or a mask
6902 in a region to one value. Although you could do that with the related
6903 functions putregion and
6904 putchunk, you would have to make an
6905 array of the shape of the image and if that is large, it could be
6906 resource expensive.
6908 The value for the pixels is specified with the {stfaf pixels} argument. It can
6909 be given as either a Lattice Expression Language (or LEL) expression
6910 string or a simple numeric scalar. See htmladdnormallink{note
6911 223}{../../notes/223/223.html} for a detailed description of the LEL
6912 expression syntax. If you give a LEL expression it must be a scalar
6913 expression.
6915 Note that any default mask is {em ignored} by this function when you
6916 set pixel values. This is different from
6917 calc where the extant mask is
6918 honoured.
6920 The value for the pixel mask is specified with the {stfaf pixelmask}
6921 argument ({cf T, F, unset}). If it's {cf unset} then the mask is not
6922 changed.
6924 If you specify {stfaf pixelmask=} T or F, then the mask that is affected is
6925 the current default mask (see
6926 maskhandler). If there is no mask, a
6927 mask is created for you and made the default mask.
6929 Input Parameters:
6930 pixels The pixel value, LEL scalar expression or numeric scalar. Default is unset.
6931 pixelmask The pixel mask value. Either 0 or 1 if set. Default is unset.
6932 region Region selection. Default is to use the full image.
6933 list List the bounding box and any mask creation to the logger
6935 Example:
6938 #
6939 print 't----t set Ex 1 t----'
6940 ia.maketestimage('yy',overwrite=true)
6941 ia.fromshape('xx', [10,20], overwrite=true)
6942 r1 = rg.box([2,2],[6,8]) # Make a box region
6943 ia.set(pixels=1.0) # Set all pixels to 1
6944 ia.set(pixels='2.0', region=r1) # Set all pixels to 2 in the region
6945 ia.set(pixels='min(yy)') # Set all pixels to minimum of image yy
6946 # Set pixels in region to minimum of image xx
6947 ia.set(pixels='min('+ia.name(strippath=True)+')', region=r1)
6948 ia.set(pixelmask=True) # Set mask to all T
6949 ia.set(pixels=0, pixelmask=False, region=r1) #Set pixels and mask in region
6950 ia.close()
6951 #
6954 --------------------------------------------------------------------------------
6956 """
6957 return _image.image_set(self, *args, **kwargs)
6960 def setbrightnessunit(self, *args, **kwargs):
6961 """
6962 setbrightnessunit(self, _unit) -> bool
6966 Summary:
6967 Set the image brightness unit
6969 Description:
6973 This function sets the image brightness unit. Both float and complex
6974 valued images are supported.
6975 You can get the brightness unit with function
6976 brightnessunit.
6978 Input Parameters:
6979 unit New brightness unit
6981 Example:
6984 #
6985 print 't----t setbrightnessunit Ex 1 t----'
6986 ia.fromshape(shape=[10,10])
6987 ia.setbrightnessunit('km')
6988 print ia.brightnessunit()
6989 #km
6990 #
6993 --------------------------------------------------------------------------------
6995 """
6996 return _image.image_setbrightnessunit(self, *args, **kwargs)
6999 def setcoordsys(self, *args, **kwargs):
7000 """
7001 setcoordsys(self, _csys) -> bool
7005 Summary:
7006 Set new Coordinate System
7008 Description:
7012 This method replaces the coordinate system in the image. Coordinate systems are
7013 manipulated with the cs (coordintate system) tool. The coordinate system can be
7014 recovered from an image via the coordsys() method of the image analysis (ia)
7015 tool.
7017 Note that changing the coordinate system using the cs tool has no effect on the
7018 original image, until it is replaced with this method; the value returned
7019 by coordsys() is a copy of, not a reference to, the image's coordinate system.
7021 Input Parameters:
7022 csys Record describing new Coordinate System
7024 Example:
7027 #
7028 print 't----t setcoordsys Ex 1 t----'
7029 ia.fromshape(shape=[10,20]) # Make image
7030 mycs = ia.coordsys(); # Recover Coordinate System
7031 incr = mycs.increment('n'); # Get increment as numeric vector
7032 incrn = incr['numeric']
7033 for i in range(len(incrn)):
7034 incrn[i] = 2*incrn[i]
7035 incr['numeric']=incrn
7036 mycs.setincrement(value=incr); # Set new increment in Coordinate System
7037 ia.setcoordsys(mycs.torecord()); # Set new Coordinate System in image
7038 mycs.done()
7039 ia.close()
7040 #
7043 --------------------------------------------------------------------------------
7045 """
7046 return _image.image_setcoordsys(self, *args, **kwargs)
7049 def sethistory(self, *args, **kwargs):
7050 """
7051 sethistory(self, _origin, _history) -> bool
7055 Summary:
7056 Set the history for an image
7058 Description:
7062 A casa imagefile can accumulate history information
7063 from an input fits file or by you writing something into
7064 it explicitly with this function. Each element of
7065 the input vector is one line of history. The new
7066 history is appended to the old.
7069 You can recover the history information with function
7070 history.
7072 Input Parameters:
7073 origin Used to set message origin. Default is image::sethistory.
7074 history New history
7076 Example:
7079 #
7080 print 't----t sethistory Ex 1 t----'
7081 ia.maketestimage('myfile',overwrite=true)
7082 h = ia.history()
7083 # Adds three lines, 'I', 'like' and 'fish'
7084 ia.sethistory(origin='sethistory', history=['I','like','fish'])
7085 ia.close()
7086 #
7089 --------------------------------------------------------------------------------
7091 """
7092 return _image.image_sethistory(self, *args, **kwargs)
7095 def setmiscinfo(self, *args, **kwargs):
7096 """
7097 setmiscinfo(self, _info) -> bool
7101 Summary:
7102 Set the miscellaneous information record for an image
7104 Description:
7108 A CASA image can include user-specified or miscellaneous metadata. This metadata
7109 is stored in a data structure referred to as a miscinfo record. For example, the
7110 FITS reader ia.fromfits() puts header keywords it doesn't otherwise use into
7111 such a record. The miscinfo record is not required to be populated, though.
7113 This method sets the miscinfo record of an image. Note that this method will
7114 overwrite, not add to, an existing miscinfo record. Thus if the user wishes
7115 to augment an existing record, they must first capture the existing record using
7116 the ia.miscinfo() method, modify the captured record, and then replace the
7117 record in the image using setmiscinfo() by passing it the modified record. The
7118 FITS writer will attempt to write all the fields in the miscinfo record to the
7119 FITS file it creates. It can do so for scalars and 1-dimensional arrays. Records
7120 will be omitted, and multi-dimensional arrays will be flattened into
7121 one dimensional arrays.
7123 Input Parameters:
7124 info Miscellaneous REPLACEMENT header
7126 Example:
7129 #
7130 print 't----t setmiscinfo Ex 1 t----'
7131 ia.maketestimage('myfile',overwrite=true)
7132 info = ia.miscinfo() # capture the miscinfo record
7133 info['extra'] = 'a test entry' # add our information
7134 ia.setmiscinfo(info) # put it back into the image
7135 ia.close()
7136 #
7139 --------------------------------------------------------------------------------
7141 """
7142 return _image.image_setmiscinfo(self, *args, **kwargs)
7145 def shape(self):
7146 """
7147 shape(self) -> std::vector< long >
7151 Summary:
7152 Length of each axis in the image
7154 Description:
7158 The shape of an image is a vector holding the length of each axis of
7159 the image. Although this information is also available in the summary function, it is
7160 so useful that it can be obtained directly. Both Float and Complex valued
7161 images are supported.
7163 Example:
7166 #
7167 print 't----t shape Ex 1 t----'
7168 ia.fromshape(shape=[10,20,30])
7169 imshape = ia.shape()
7170 print imshape
7171 #[10L, 20L, 30L]
7172 # npixels = imshape[0]*imshape[1]*...*imshape[n-1]
7173 npixels=1
7174 for i in range(len(imshape)):
7175 npixels=npixels*imshape[i]
7176 ia.close()
7177 #
7180 --------------------------------------------------------------------------------
7182 """
7183 return _image.image_shape(self)
7186 def setrestoringbeam(self, *args, **kwargs):
7187 """
7188 setrestoringbeam(self, _major, _minor, _pa, _beam, _remove, _log, _channel, _polarization, _imagename) -> bool
7192 Summary:
7193 Set the restoringbeam
7195 Description:
7199 This method sets the restoring beam(s) for an image or removes an existing beam(s).
7201 An image must have exactly one of the following states:
7203 1. An image can have a single 'traditional' or global beam. In that case, the
7204 beam applies to every channel and polarization in the image.
7206 2. If an image has more than one spectral channel or more than one polarization,
7207 it can have a set of beams. In this case, each channel and/or polarization will
7208 have its own beam.
7210 3. An image can have neither a global beam nor a beam set.
7212 It is never permissible for an image to have both a traditional (global) beam
7213 and a set of per-plane beams. Task and method behavior is undefined in that case
7214 and any resulting products are considered corrupt.
7216 RULES FOR BEAM MODIFICATION
7218 1. If remove=true, any existing beam(s) are removed.
7220 2. Else if imagename is specified, the beam(s) from the specified image will
7221 be copied to the image being accessed by the image tool. Multiple beams
7222 may be copied, but the two images must have the same number of frequency
7223 channels and polarization planes. If not, an exception is thrown.
7225 3. Else if the beam parameter is specified, it will be used. It must be fully
7226 specified. It must have exactly three items with keys 'major',
7227 'minor', and 'positionangle'. Each of these keys
7228 must be a proper quantity dictionary with keys 'value' and
7229 'unit'. The units for all three items should be angular. The
7230 'major' and 'minor' items must have non-negative values.
7231 If any of these conditions is not met, an exception will be thrown.
7233 4. Else the 'major', 'minor', and 'pa'
7234 parameters must be specified. Any or all of these may be a quantity string
7235 (eg, '2arcsec', a quantity dictionary with keys 'value'
7236 and 'unit'. or a numerical value. 'major' and
7237 'minor' must have non-negative values. If any of these conditions
7238 is not met, an exception will be thrown. In the case of a quantity
7239 being specified the 'unit' should be an angular unit or no unit.
7240 In the case of no unit or a numerical value specified, if the image already
7241 has a beam then the corresponding unit for that parameter in the current beam
7242 will be used. If the image has no beam, then 'arcsec' is used for
7243 'major' and 'minor', and 'deg' is used for
7244 'pa'.
7246 If an image has no beams, a traditional (global) beam can be added by setting
7247 both channel and polarization to negative values.
7249 If an image has no beams, a set of per-plane beams can be added by setting
7250 either or both channel and/or polarization to a non-negative value. In this
7251 case, a number of per-plane beams are added consistent with the image and they
7252 are all set to be the same with parameters equal to those specified by either
7253 the beam or major/minor/pa parameters.
7255 If an image has a traditional beam, it can be modified by setting both channel
7256 and polarization to negative values. If one or both is not set to a negative
7257 value, an exception is thrown, and nothing is modified.
7259 If an image has a set of per plane beams, one at a time of these can be modified
7260 by setting the appropriate channel number and/or polarization number. All the
7261 per-plane beams can be modified to the same values in one go by setting both
7262 channel and polarization to negative values. Also, in the case where an image
7263 has multiple channels, the beams associated with all channels for a given
7264 polarization can be modified to the same beam by setting polarization equal to
7265 the desired polarization plane number and by setting channel to a negative
7266 value. Similarly, in the case where an image has multiple polarizations, the
7267 beams associated with all polarizations for a given spectral channel can be
7268 modified to the same beam by setting channel equal to the desired spectral
7269 channel number and by setting polarization to a negative value.
7271 Input Parameters:
7272 major Major axis FWHM, Quantity or float (e.g., 1arcsec). Default is unset.
7273 minor Minor axis FWHM, Quantity or float (e.g., 1arcsec). Default is unset.
7274 pa Position angle, Quantity or float (e.g., '5deg'). Default is unset.
7275 beam The complete restoring beam (output of restoringbeam()). Default is unset.
7276 remove Delete the restoring beam?
7277 log Write new beam values to the logger?
7278 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.
7279 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.
7280 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.
7282 Example:
7286 ia.maketestimage('hcn',overwrite=true)
7287 rb = ia.restoringbeam() # returns beam in record
7288 print rb
7289 #{'major': {'unit': 'arcsec', 'value': 53.500004857778549},
7290 # 'minor': {'unit': 'arcsec', 'value': 34.199998900294304},
7291 # 'positionangle': {'unit': 'deg', 'value': 6.0}}
7292 rb['minor']['value'] = 12.5
7293 # new beam specified in record
7294 # NOTE This will not work for an image with multiple beams
7295 ia.setrestoringbeam(beam=rb)
7296 print ia.restoringbeam()
7297 #{'major': {'unit': 'arcsec', 'value': 53.500004857778549},
7298 # 'minor': {'unit': 'arcsec', 'value': 12.5},
7299 # 'positionangle': {'unit': 'deg', 'value': 6.0}}
7301 # beam specified using parameter
7302 # NOTE This will only work for an image with a traditional beam
7303 ia.setrestoringbeam(major='36arcsec')
7304 print ia.restoringbeam()
7305 #{'major': {'unit': 'arcsec', 'value': 36.0},
7306 # 'minor': {'unit': 'arcsec', 'value': 12.5},
7307 # 'positionangle': {'unit': 'deg', 'value': 6.0}}
7308 ia.setrestoringbeam(remove=true)
7309 print ia.restoringbeam()
7310 #{}
7311 ia.setrestoringbeam(major='53.5arcsec',minor='34.2arcsec',pa='6deg')
7312 print ia.restoringbeam()
7313 #{'major': {'unit': 'arcsec', 'value': 53.5},
7314 # 'minor': {'unit': 'arcsec', 'value': 34.200000000000003},
7315 # 'positionangle': {'unit': 'deg', 'value': 6.0}}
7316 ia.close()
7318 # Copy all beams from an image with multiple beams to another
7319 # image with the same number of channels and polarizations
7321 ia.open('multibeam.im')
7322 ib = iatool()
7323 ib.open('target.im')
7325 # ensure target has no beam(s) at start, not always necessary
7326 # but it doesn't hurt to do it.
7327 ib.setrestoringbeam(remove=True)
7328 # Now copy the beams. This only will work correctly if both images
7329 # have the same number of channels and polarizations. nchan is set to
7330 # the number of channels and npol is set to the number of polarizations
7331 for c in range(nchan):
7332 for p in range(npol):
7333 beam = ia.restoringbeam(channel=c, polarization=p)
7334 ib.setrestoringbeam(beam=beam, channel=c, polarization=p)
7336 ia.done()
7337 ib.done()
7342 --------------------------------------------------------------------------------
7344 """
7345 return _image.image_setrestoringbeam(self, *args, **kwargs)
7348 def statistics(self, *args, **kwargs):
7349 """
7350 statistics(self, _axes, _region, _mask, _includepix, _excludepix, _list, _force, _disk, _robust, _verbose, _stretch, _logfile, _append, _algorithm, _fence, _center, _lside, _zscore, _maxiter, _clmethod, _niter) -> record *
7354 Summary:
7355 Compute statistics from the image
7357 Description:
7361 This method computes statistics from the pixel values in the image. You can
7362 then list them and retrieve them (into a record) for further analysis. This
7363 method supports only real valued images.
7365 The names of the fields in the returned record are summarized below:
7367 - npts: the number of unmasked points used
7369 - sum: the sum of the pixel values: $sum I_i$
7371 - flux: flux or flux density, see below for details
7373 - sumsq: the sum of the squares of the pixel values: $sum I_i^2$
7375 - mean: the mean of pixel values: $bar{I} = sum I_i / n$
7377 - sigma: the standard deviation about the
7378 mean: $sigma^2 = (sum I_i - bar{I})^2 / (n-1)$
7380 - rms: the root mean square: $sqrt {sum I_i^2 / n}$
7382 - min: minimum pixel value
7384 - max: the maximum pixel value
7386 - median: the median pixel value (if {stfaf robust=T})
7388 - medabsdevmed: the median of the absolute deviations from the median
7389 (if {stfaf robust=T})
7391 - quartile: the inter-quartile range (if {stfaf
7392 robust=T}). Find the points which are 25% largest and 75% largest
7393 (the median is 50% largest).
7395 - q1: The first quartile. Reported only if robust=T.
7397 - q3: The third quartile. Reported only if robust=T.
7399 - blc: the absolute pixel coordinate of the bottom left
7400 corner of the bounding box of the region of interest. If 'region' is
7401 unset, this will be the bottom left corner of the whole image.
7403 - blcf: the formatted absolute world coordinate of the bottom left corner of the bounding box of the region of interest.
7405 - trc: the absolute pixel coordinate of the top right corner of the bounding box of the region of interest.
7407 - trcf: the formatted absolute world coordinate of the top right corner of the bounding box of the region of interest.
7409 - minpos: absolute pixel coordinate of minimum pixel value
7411 - maxpos: absolute pixel coordinate of maximum pixel value
7413 - minposf: formatted string of the world coordinate of
7414 the minimum pixel value
7416 - maxposf: formatted string of the world coordinate of
7417 the maximum pixel value
7420 The last four fields only appear if you evaluate the statistics over all
7421 axes in the image. As an example, if the returned record is captured in
7422 {stfaf 'mystats'}, then you could access the 'mean' field via
7423 {cf print mystats['mean']}.
7425 If there are no good points (e.g. all pixels are masked bad in the
7426 region), then the length of these fields will be 0 (e.g. {cf
7427 len(mystats['npts'])==0}).
7429 You have no control over which statistics are listed to the logger,
7430 you always get the same selection. You can choose to list the
7431 statistics or not (argument {stfaf list}).
7433 As well as the simple (and faster to calculate) statistics like means
7434 and sums, you can also compute some robust (quantile-like) statistics. Currently
7435 these are the median, median absolute deviations from the median,
7436 the first and third quartiles, and the inner-quartile range. Because these are computationally
7437 expensive, they are only computed if robust=True.
7439 Note that if the axes are set to all of the axes in the image (which is
7440 the default) there is just one value per statistic.
7442 You have control over which pixels are included in the statistics computations
7443 via the {stfaf includepix} and {stfaf excludepix} arguments. These vectors
7444 specify a range of pixel values for which pixels are either included or
7445 excluded. They are mutually exclusive; you can specify one or the
7446 other, but not both. If you only give one value for either of these,
7447 say {stfaf includepix=b}, then this is interpreted as {stfaf
7448 includepix=[-abs(b),abs(b)]}.
7450 This function generates a 'storage' lattice, into which the statistics
7451 are written as a means to improve performance on successive identical runs.
7452 After the initial execution of this method, it is only regenerated as
7453 necessary. For example, if you run the method twice with
7454 identical arguments, the statistics will be directly retrieved from the
7455 storage lattice the second time, and the statistics will not be recomputed.
7456 However, you can force regeneration of the statistics if you set force=True.
7457 VERY IMPORTANT NOTE. If you have an open image tool on which you've run
7458 statistics(), and
7459 change the pixel values of the opened image via another tool or a task, the
7460 opened image tool has no knowledge that pixel values have been changed, and
7461 so if you run ia.statistics() again with that tool, you will very likely
7462 get incorrect results since they come from the statistics stored from a previous
7463 run. First of all, it is highly discouraged that you do anything like this.
7464 Tools maintain state that only they know about internally; if you change
7465 an image that is already opened with another image tool or task, the general
7466 outcome will be undefined when you run methods on the already opened tool.
7467 However, if for some reason you must do this,
7468 first consider changing your algorithm because there should be no reason
7469 to have to do this. But, if you decide to continue down that path that will
7470 likely lead you over the edge of a cliff, then you can set force=True to
7471 ensure statistics are always recomputed.
7473 The storage medium is either in memory or on disk,
7474 depending upon its size. You can force it to disk if you set {stfaf
7475 disk=T}, otherwise it decides for itself.
7477 CURSOR AXES
7478 The axes parameter allows one to set the cursor axes over which statistics
7479 are computed. For example, consider a 3-dimensional image for which axes=[0,2].
7480 The statistics would be computed for each XZ (axes 0 and 2) plane in the
7481 image. One could then examine those statistics as a function of the Y
7482 (axis 1) axis.
7484 Each statistic is stored in an array in its own field in the returned dictionary.
7485 The dimensionality of these arrays is equal to the number of axes over which the
7486 statistics were not evaluated (called the display axes). For example, if the input
7487 image has four axes, and axes=[0], the output statistic arrays will have three dimensions.
7488 If axes=[0, 1], the output statistic arrays will have two dimensions.
7490 The shape of the output arrays when axes has a positive number of elements is based on
7491 the region selection. If there is no region selection, the shape of the statistic arrays
7492 is just the shape of the image along the display (non-cursor) axes. For example, if the
7493 input image has dimensions of 300x400x4x80 and axes=[0, 1], in the absence of a region
7494 selection, the shape of the output statistic arrays will be 4x80. If there is a region
7495 selection, the shape of the output statistic arrays will be determined by the number of
7496 planes along the display axes chosen in the region selection. For example, continuing with
7497 our example, if axes=[0,1] and region=rg.box([0, 0, 1, 20], [299,399, 2, 60]), the output
7498 statistic arrays will have shapes of 2x41. Only the selected planes will be displayed in the
7499 logger output if verbose=True.
7501 In the case where the image has a pixel mask, and/or the mask parameter is specified, and because
7502 of this specification a plane is entirely masked, this element is included in the statistic arrays
7503 (usually with a value of 0). It is not included in the logger output if verbose=True. One can
7504 exclude such elements from computations on the output arrays by using the numpy.extract() method.
7505 For example, to compute the minimum rms value, not including any fully masked planes, one could
7506 use
7508 stats = ia.statistics(...)
7509 rmsmin = numpy.min(numpy.extract(stats['npts']>0, stats['rms']))
7511 Thus in the computation of rmsmin, only the rms elements are considered which have
7512 associated values of npts that are not zero.
7514 ALGORITHMS
7516 Several types of statistical algorithms are supported:
7518 - classic: This is the familiar algorithm, in which all unmasked pixels, subject to any
7519 specified pixel ranges, are used. One may choose one of two methods, which vary only by
7520 performance, for computing classic statistics, via the clmethod parameter. The 'tiled'
7521 method is the old method and is fastest in cases where there are a large number of
7522 individual sets of statistics to be computed and a small number of data points per set.
7523 This can occur when one sets the axes parameter, which causes several individual sets of
7524 statistics to be computed. The 'framework' method uses the new statistics framework to
7525 compute statistics. This method is fastest in the regime where one has a small number of
7526 individual sets of statistics to calculate, and each set has a large number of points.
7527 For example, this method is fastest when computing statistics over an entire image in one
7528 go (no axes specified). A third option, 'auto', chooses which method to use by predicting
7529 which be faster based on the number of pixels in the image and the choice of the axes
7530 parameter.
7532 - fit-half: This algorithm calculates statistics on a dataset created from real and virtual pixel values.
7533 The real values are determined by the input parameters center and lside. The parameter center
7534 tells the algorithm where the center value of the combined real+virtual dataset should be. Options
7535 are the mean or the median of the input image's pixel values, or at zero. The lside parameter tells
7536 the algorithm on which side of this center the real pixel values are located. True indicates that
7537 the real pixel values to be used are <= center. False indicates the real pixel values to be used
7538 are >= center. The virtual part of the dataset is then created by reflecting all the real values
7539 through the center value, to create a perfectly symmetric dataset composed of a real and a virtual
7540 component. Statistics are then calculated on this resultant dataset. These two parameters are
7541 ignored if algorithm is not 'fit-half'. Because the maximum value is virtual if lside is True and the
7542 minimum value is virtual if lside is False, the value of the maximum position (if lside=True) or
7543 minimum position (if lside=False) is not reported in the returned record.
7545 - hinges-fences: This algorithm calculates statistics by including data in a range
7546 between Q1 - f*D and Q3 + f*D, inclusive, where Q1 is the first quartile of the distribution
7547 of unmasked data, subject to any specified pixel ranges, Q3 is the third quartile, D = Q3 - Q1
7548 (the inner quartile range), and f is the user-specified fence factor. Negative values of f
7549 indicate that the full distribution is to be used (ie, the classic algorithm is used). Sufficiently
7550 large values of f will also be equivalent to using the classic algorithm. For f = 0, only data
7551 in the inner quartile range is used for computing statistics. The value of fence is silently
7552 ignored if algortihm is not 'hinges-fences'.
7554 - chauvenet: The idea behind this algorithm is to eliminate outliers based on a maximum z-score value.
7555 A z-score is the number of standard deviations a point is from the mean of a distribution. This
7556 method thus is meant to be used for (nearly) normal distributions. In general, this is an iterative
7557 process, with successive iterations discarding additional outliers as the remaining points become
7558 closer to forming a normal distribution. Iterating stops when no additional points lie beyond the
7559 specified zscore value, or, if zscore is negative, when Chauvenet's criterion is met (see below).
7560 The parameter maxiter can be set to a non-negative value to prematurely abort this iterative
7561 process. When verbose=True, the 'N iter' column in the table that is logged represents the number
7562 of iterations that were executed.
7564 Chauvenet's criterion allows the target z-score to decrease as the number of points in the
7565 distribution decreases on subsequent iterations. Essentially, the criterion is that the probability
7566 of having one point in a normal distribution at a maximum z-score of z_max must be at least 0.5.
7567 z_max is therefore a function of (only) the number of points in the distrbution and is given by
7569 npts = 0.5/erfc(z_max/sqrt(2))
7571 where erfc() is the complementary error function. As iterating proceeds, the number of remaining
7572 points decreases as outliers are discarded, and so z_max likewise decreases. Convergence occurs when
7573 all remaining points fall within a z-score of z_max. Below is an illustrative table of z_max values
7574 and their corresponding npts values. For example, it is likely that there will be a 5-sigma 'noise
7575 bump' in a perfectly noisy image with one million independent elements.
7577 z_max npts
7578 1.0 1
7579 1.5 3
7580 2.0 10
7581 2.5 40
7582 3.0 185
7583 3.5 1,074
7584 4.0 7,893
7585 4.5 73,579
7586 5.0 872,138
7587 5.5 13,165,126
7588 6.0 253,398,672
7589 6.5 6,225,098,696
7590 7.0 195,341,107,722
7592 - biweight: The biweight algorithm is a robust iterative algorithm that computes two
7593 quantities called the 'location' and the 'scale', which are analogous to the mean
7594 and the standard deviation. In this case, the only keys present in the returned
7595 dictionary are 'mean' (location), 'sigma' (scale), 'npts', 'min', and 'max'. The
7596 last three represent the values using the entire distribution. Note that the
7597 biweight algorithm does not support computation of quantile-like values (median,
7598 madm, q1, q3, and iqr), so setting robust=True will cause a warning message to
7599 be logged regarding that, and the computation will proceed.
7601 Important equations for the biweight algorithm are
7603 A. How to compute u_i values, which are related to the weights w_i = (1 - u_i*u_i),
7604 using the
7605 equation
7607 ``u_i = (x_i - c_bi)/(6.0*s_bi) (1)``
7609 where x_i are the data values, c_bi is the biweight location and s_bi is the
7610 biweight scale. For the initial computation of the u_i values, c_bi is set
7611 equal to the median of the distribution and s_bi is set equal to
7612 the normalized median of the absolute deviation about the median (that is the
7613 median of the absolute deviation about the median multiplied by the value of
7614 the probit function at 0.75).
7616 B. The location, c_bi, is computed from
7618 ``c_bi = sum(x_i * w_i^2)/sum(w_i^2) (2)``
7620 where only values of u_i which satisfy abs(u_i) < 1 (w_i > 0) are used in the sums.
7622 C. The scale value is computed using::
7624 . n * sum((x_i - c_bi)^2 * w_i^4)
7625 . s_bi^2 = _______________________________ (3)
7626 . p * max(1, p - 1)
7628 where n is the number of points for the entire distribution (which includes all
7629 the data, even for which abs(u_i) >= 1) and p is given by::
7631 p = abs(sum((w_i) * (5*w_i - 4)))
7633 Again, the sums include only data for which abs(u_i) < 1.
7635 The algorithm proceeds as follows.
7636 1. Compute initial u_i values (and hence w_i values) from equation (1), setting
7637 c_bi equal to the median of the distribution and s_bi equal to the normalized
7638 median of the absolute deviation about the median.
7639 2. Compute the initial value of the scale using the w_i values computed in
7640 step 1. using equation 3.
7641 3. Recompute u_i/w_i values using the most recent previous scale and location
7642 values.
7643 4. Compute the location using the u_i.w_i values from step 3 and equation (2).
7644 5. Recompute u_i/w_i values using the most recent previous scale and location
7645 values.
7646 6. Compute the new scale value using the the u_i/w_i values computed in
7647 step 5 and the value of the location computed in step 4.
7648 7. Steps 3. - 6. are repeated until convergence occurs or the maximum number of
7649 iterations (specified in the niter parameter) is reached. The convergence
7650 criterion is given by
7652 abs(s_bi - s_bi,prev) < 0.03 * sqrt(0.5/(n - 1))
7654 where s_bi,prev is the value of the scale computed in the previous iteration.
7656 In the special case where niter is specified to be negative, the faster,
7657 non-iterative algorithm proceeds as follows:
7659 1. Compute u_i/w_i values using the median for the location and the normalized
7660 median of the absolute deviation about the median as the scale
7661 2. Compute the location and scale (which can be carried out simultaneously)
7662 using the u_i/w_i values computed in step 1. The value of the location is
7663 just the median that is used in equation (3) to compute the scale
7665 NOTES ON FLUX DENSITIES AND FLUXES
7667 Fluxes and flux densities are not computed if any of the following conditions is met:
7669 1. The image does not have a direction coordinate
7670 2. The image does not have a intensity-like brightness unit. Examples of such units
7671 are Jy/beam (in which case the image must also have a beam) and K.
7672 3. There are no direction axes in the cursor axes that are used.
7673 4. If the (specified region of the) image has a non-degenerate spectral axis,
7674 and the image has a tablular spectral axis (axis with varying increments)
7675 5. Any axis that is not a direction nor a spectral axis that is included in the cursor
7676 axes is not degenerate within in the specified region
7678 Note that condition 4 may be removed in the future.
7680 In cases where none of the above conditions is met, the flux density(ies) (intensities
7681 integrated over direction planes) will be computed if any of the following conditions
7682 are met:
7684 1. The image has no spectral coordinate
7685 2. The cursor axes do not include the spectral axis
7686 3. The spectral axis in the chosen region is degenerate
7688 In the case where there is a nondegenerate spectral axis that is included in the cursor
7689 axes, the flux (flux density integrated over spectral planes) will be computed. In this
7690 case, the spectral portion of the flux unit will be the velocity unit of the spectral
7691 coordinate if it has one (eg, if the brightness unit is Jy/beam and the velocity unit is
7692 km/s, the flux will have units of Jy.km/s). If not, the spectral portion of the flux unit
7693 will be the frequency unit of the spectral axis (eg, if the brightness unit is K and the
7694 frequency unit is Hz, the resulting flux unit will be K.arcsec2.Hz).
7696 In both cases of flux density or flux being computed, the resulting numerical value is
7697 assigned to the 'flux' key in the output dictionary.
7699 If the image has units of Jy/beam, the flux density is just the mean intensity multiplied
7700 by the number of beam areas included in the region. The beam area is defined as the volume
7701 of the elliptical Gaussian defined by the synthesized beam, divided by the maximum of
7702 that function, which is equivalent to
7704 pi/(4*ln(2)) * major * minor
7706 where ln() is the natural logarithm and major and minor are the major and minor FWHM axes
7707 of the beam, respectively.
7709 Input Parameters:
7710 axes List of axes to evaluate statistics over. Default is all axes.
7711 region Region selection. Default is to use the full image.
7712 mask Mask to use. Default is none.
7713 includepix Range of pixel values to include. Vector of 1 or 2 doubles. Default is to include all pixels.
7714 excludepix Range of pixel values to exclude. Vector of 1 or 2 doubles. Default is exclude no pixels.
7715 list If True print bounding box and statistics to logger.
7716 force If True then force the stored statistical accumulations to be regenerated
7717 disk If T then force the storage image to disk
7718 robust If T then compute robust statistics as well
7719 verbose If T then log statistics
7720 stretch Stretch the mask if necessary and possible? Default False
7721 logfile Name of file to which to write statistics.
7722 append Append results to logfile? Logfile must be specified. Default is to append. False means overwrite existing file if it exists.
7723 algorithm Algorithm to use. Supported values are 'biweight', 'chauvenet', 'classic', 'fit-half', and 'hinges-fences'. Minimum match is supported.
7724 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'.
7725 center Center to use for fit-half. Valid choices are 'mean', 'median', and 'zero'. Ignored if algorithm is not 'fit-half'.
7726 lside For fit-half, real data are <=; center? If false, real data are >= center. Ignored if algorithm is not 'fit-half'.
7727 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'.
7728 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 algorithm is not 'chauvenet'.
7729 clmethod Method to use for calculating classical statistics. Supported methods are 'auto', 'tiled', and 'framework'. Ignored if algorithm is not 'classic'.
7730 niter For biweight, 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, do a fast, simple computation (see description). Ignored if the algorithm is not 'chauvenet'.
7732 Example:
7735 #
7736 print 't----t statistics Ex 1 t----'
7737 ia.maketestimage()
7738 ia.statistics()
7739 ia.close()
7740 #
7742 # evaluate statistics for each spectral plane in an ra x dec x frequency image
7743 ia.fromshape('', [20,30,40])
7744 # give pixels non-zero values
7745 ia.addnoise()
7746 # These are the display axes, the calculation of statistics occurs
7747 # for each (hyper)plane along axes not listed in the axes parameter,
7748 # in this case axis 2 (the frequency axis)
7749 # display the rms for each frequency plane (your mileage will vary with
7750 # the values).
7751 stats = ia.statistics(axes=[0,1])
7752 stats['rms']
7753 Out[10]:
7754 array([ 0.99576014, 1.03813124, 0.97749186, 0.97587883, 1.04189885,
7755 1.03784776, 1.03371549, 1.03153074, 1.00841606, 0.947155 ,
7756 0.97335404, 0.94389403, 1.0010221 , 0.97151822, 1.03942156,
7757 1.01158476, 0.96957082, 1.04212773, 1.00589049, 0.98696715,
7758 1.00451481, 1.02307892, 1.03102005, 0.97334671, 0.95209879,
7759 1.02088714, 0.96999902, 0.98661619, 1.01039267, 0.96842754,
7760 0.99464947, 1.01536798, 1.02466023, 0.96956468, 0.98090756,
7761 0.9835844 , 0.95698935, 1.05487967, 0.99846411, 0.99634868])
7766 In this example, we ask to see statistics evaluated over the
7767 entire image.
7771 #
7772 print 't----t statistics Ex 2 t----'
7773 ia.maketestimage()
7774 stats = ia.statistics(axes=[1],plotstats=['sigma','rms'],
7775 includepix=[0,100],list=False)
7776 #
7780 In this example, let us assume the image has 2 dimensions. We want
7781 the standard deviation about the mean and the rms of Y (axes 1) for
7782 pixels with values in the range 0 to 100 as a function of the X-axis
7783 location. The statistics are not listed to the logger but are saved
7784 in the record {stfaf 'stats'}.
7786 --------------------------------------------------------------------------------
7788 """
7789 return _image.image_statistics(self, *args, **kwargs)
7792 def twopointcorrelation(self, *args, **kwargs):
7793 """
7794 twopointcorrelation(self, _outfile, _region, _mask, _axes, _method, _overwrite, _stretch) -> bool
7798 Summary:
7799 Compute two point correlation function from the image
7801 Description:
7805 This function computes
7806 two-point auto-correlation functions from an image.
7808 By default, the auto-correlation function is computed for the Sky axes.
7809 If there is no sky in the image, then the first two axes are used.
7810 Otherwise you can specify which axes the auto-correlation function lags
7811 are computed over with the {stfaf axes} argument (must be of length 2).
7813 Presently, only the Structure Function is implemented. This is defined as :
7815 begin{displaymath}
7816 S(lx,ly) = < (data(i,j) - data(i+lx,j+ly))^2 >
7817 end{displaymath}
7819 where $lx, ly$ are integer lags in the x (0-axis) and y (1-axis)
7820 directions. The ensemble average is over all the values at the same
7821 lag pair. This process is extremely compute intensive and so you may
7822 have to be patient.
7824 In an auto-correlation function image there are some symmetries. The
7825 first and third quadrants are symmetric, and the second and fourth are
7826 symmetric. So in principle, all the information is in the top or bottom
7827 half of the image. We just write it all out to look nice. The long
7828 lags don't have a lot of contributing values of course.
7830 Input Parameters:
7831 outfile Output image file name. Default is unset.
7832 region Region selection. Default is to use the full image.
7833 mask Mask to use. Default is none.
7834 axes The pixel axes to compute structure function over. The default is sky or first two axes.
7835 method The method of computation. String from 'structurefunction'.
7836 overwrite Overwrite (unprompted) pre-existing output file?
7837 stretch Stretch the mask if necessary and possible? Default False
7839 Example:
7842 ia.maketestimage('test.image')
7843 ia.twopointcorrelation('2pt.image')
7844 ia.done()
7847 --------------------------------------------------------------------------------
7849 """
7850 return _image.image_twopointcorrelation(self, *args, **kwargs)
7853 def subimage(self, *args, **kwargs):
7854 """
7855 subimage(self, _outfile, _region, _mask, _dropdeg, _overwrite, _list, _stretch, _wantreturn, _keepaxes) -> image
7859 Summary:
7860 Create a (sub)image from a region of the image
7862 Description:
7866 This function copies all or part of the image to another on-the-fly Image tool.
7867 Both float and complex valued images are supported.
7869 If {stfaf outfile} is given, the subimage is written to the specified
7870 disk file. If {stfaf outfile} is unset, the returned Image tool actually
7871 references the input image file (i.e. that associated with the Image
7872 tool to which you are applying this function). So if you deleted the
7873 input image disk file, it would render this tool useless. When you
7874 destroy this tool (with the done function)
7875 the reference connection is broken.
7877 Sometimes it is useful to drop axes of length one (degenerate axes).
7878 Use the {stfaf dropdeg} argument if you want to do this. Further control
7879 is provided via the keepaxes parameter. If dropdeg=True, you may specify
7880 a list of degenerate axes to keep in the keep axes parameter. This allows
7881 you to drop only a subset of degenerate axes. This parameter is ignored if
7882 dropdeg=False. If dropdeg=True, all degenerate axes are dropped if keepaxes
7883 is set to an empty list (this is the default behavior). Nondegenerate
7884 axes are implicitly kept, even if they are included in the keepaxes list.
7886 The output mask is the combination (logical OR) of the default input
7887 pixelmask (if any) and the OTF mask. Any other input pixelmasks
7888 will not be copied. Use function maskhandler if you
7889 need to copy other masks too.
7891 If the mask has fewer dimensions than the image and if the shape
7892 of the dimensions the mask and image have in common are the same,
7893 the mask will automatically have the missing dimensions added so
7894 it conforms to the image.
7896 If stretch is true and if the number of mask dimensions is less than
7897 or equal to the number of image dimensions and some axes in the
7898 mask are degenerate while the corresponding axes in the image are not,
7899 the mask will be stetched in the degenerate dimensions. For example,
7900 if the input image has shape [100, 200, 10] and the input
7901 mask has shape [100, 200, 1] and stretch is true, the mask will be
7902 stretched along the third dimension to shape [100, 200, 10]. However if
7903 the mask is shape [100, 200, 2], stretching is not possible and an
7904 error will result.
7906 Input Parameters:
7907 outfile Output image file name. Default is unset.
7908 region Region selection. Default is to use the full image.
7909 mask Mask to use. Default is none.
7910 dropdeg Drop degenerate axes
7911 overwrite Overwrite (unprompted) pre-existing output file?
7912 list List informative messages to the logger
7913 stretch Stretch the mask if necessary and possible?
7914 wantreturn Return an image analysis tool attached to the created subimage
7915 keepaxes If dropdeg=True, these are the degenerate axes to keep. Nondegenerate axes are implicitly always kept.
7917 Example:
7920 #
7921 print 't----t subimage Ex 1 t----'
7922 ia.maketestimage('myfile',overwrite=true)
7923 im2 = ia.subimage() # a complete copy
7924 r1 = rg.box([10,10],[30,40],[5,5]) # A strided pixel box region
7925 im3 = ia.subimage(outfile='/tmp/foo', region=r1, overwrite=true)
7926 # Explicitly named subimage
7927 im2.done()
7928 im3.done()
7929 ia.close()
7930 #
7933 # As an example of the usage of the keepaxes parameter, consider an image
7934 # that has axes RA, Dec, Stokes, and Freq. The Stokes and Freq axes are both
7935 # degenerate while the RA and Dec axes are not, and it is desired to make a
7936 # subimage in which the Stokes axis is discarded. The following command will
7937 # accomplish that.
7938 ia.open('my.im')
7939 subim = ia.subimage(outfile='discarded_stokes.im', dropdeg=True, keepaxes=[3])
7940 ia.done()
7941 subim.done()
7943 --------------------------------------------------------------------------------
7945 """
7946 return _image.image_subimage(self, *args, **kwargs)
7949 def summary(self, *args, **kwargs):
7950 """
7951 summary(self, _doppler, _list, _pixelorder, _verbose) -> record *
7955 Summary:
7956 Summarize metadata from the image
7958 Description:
7962 This function summarizes various metadata such as shape, Coordinate System,
7963 restoring beams, and masks.
7965 If called without any arguments, this function displays a summary of the image
7966 metadata to the logger; where appropriate, values will be formatted nicely (e.g.
7967 HH:MM:SS.SS for the reference value of RA axes).
7969 For spectral axes, the information is listed in both the velocity and frequency
7970 domains. The doppler parameter allows one to specify what velocity doppler
7971 convention it is listed in. Supported values are: 'radio', 'optical', and
7972 'true'. Alternative values are 'z' for 'optical', and 'beta' or 'relativistic'
7973 for true. The default is 'radio'. The definitions are
7975 begin{itemize}
7976 item radio: $1 - F$
7977 item optical: $-1 + 1/F$
7978 item true: $(1 - F^2)/(1 + F^2)$
7979 end{itemize}
7980 where $F = nu/nu_0$ and $nu_0$ is the rest frequency. If the rest frequency
7981 has not been set in your image, you can set it via a coordinate system (cs) tool
7982 using the setrestfrequency() method().
7984 The keys of the returned dictionary are
7986 begin{itemize}
7987 item ndim: Dimension of the image.
7988 item shape: Length of each axis in the image.
7989 item tileshape: Shape of the chunk which is most efficient for I/O.
7990 item axisnames: Name of each axis.
7991 item refpix: Reference pixel for each axis (0-relative)
7992 item refval: Reference value for each axis.
7993 item incr: Increment for each axis.
7994 item axisunits: Unit name for each axis.
7995 item unit: Brightness units for the pixels.
7996 item hasmask: True if the image has a mask.
7997 item defaultmask: The name of the mask which is applied by default.
7998 item masks: The names of all the masks stored in this image.
7999 item restoringbeam: The restoring beam(s) if present.
8000 item imagetype: The image type.
8001 end{itemize}
8003 For an image with multiple beams, the restoringbeam field is a dictionary of
8004 dictionaries with keys of names '*' followed by the channel number, if the image
8005 has a spectral coordinate, or the polarization number if it does not. That is,
8006 the keys have names '*0', '*1', '*2', etc. If the image has both a spectral and
8007 a polarization coordinate, each of these dictionaries is a dictionary with keys
8008 of the same form which range from 0 to the number of polarizations minus 1;
8009 '*0', '*1', ... The dictionaries pointed to by the channel and/or polarization
8010 number contain information for the beam at that position.
8012 If the list parameter is set to False, then the summary will not be written to
8013 the logger. The return value of the method, in the 'header' field is a vector
8014 string containing the formatted output that would have been logged in the
8015 list=True case.
8017 If verbose is True and the image contains multiple beams, the formatted output,
8018 whether it is written to the logger or placed in the output record, will have
8019 information on every beam in the dataset. If verbose=False and the image has
8020 multiple beams, only a summary of beams for each polarization is listed. In this
8021 case, the beams with the maximum area, the minimum area, and the median area for
8022 each polarization are listed. However, all the beams can still be found in the
8023 restoringbeam field of the returned dictionary. If the image does not have
8024 multiple beams, verbose is not used.
8026 Input Parameters:
8027 doppler If there is a spectral axis, list velocity too, with this doppler definition
8028 list List the summary to the logger
8029 pixelorder List axis descriptors in pixel or world axis order
8030 verbose Give a full listing of beams or just a short summary? Only used when the image has multiple beams.
8032 Example:
8035 #
8036 print 't----t summary Ex 1 t----'
8037 ia.maketestimage('myim1', overwrite=true)
8038 ia.summary() # summarize to logging only
8039 s = ia.summary(list=False) # store header in record
8040 if s['header']['ndim'] == 2: # program using header values
8041 print s['header']['axisnames']
8042 ia.close()
8043 #
8046 --------------------------------------------------------------------------------
8048 """
8049 return _image.image_summary(self, *args, **kwargs)
8052 def tofits(self, *args, **kwargs):
8053 """
8054 tofits(self, _outfile, _velocity, _optical, _bitpix, _minpix, _maxpix, _region, _mask, _overwrite, _dropdeg, _deglast, _dropstokes, _stokeslast, _wavelength, _airwavelength, _stretch, _history) -> bool
8058 Summary:
8059 Convert the image to a FITS file
8061 Description:
8065 This function converts the image into a fits file.
8068 If the image has a rest frequency associated with it, it will always
8069 write velocity information into the fits file. By default the
8070 frequency information will be primary as it is the internal native format.
8071 If you select {stfaf velocity=T} then by default
8072 the velocity is written in the optical convention, but if {stfaf
8073 optical=F} it will use the radio convention instead.
8074 Alternatively, if you use {stfaf velocity=F} and {stfaf wavelength=T},
8075 the spectral axis will be written in wavelength.
8077 The fits definition demands equal increment pixels. Therefore, if you
8078 write wavelength or optical velocity information as primary, the increment
8079 is computed at the spectral reference pixel.
8080 If the bandwidth is large, this may incur non-negligible coordinate
8081 calculation errors far from the reference pixel if the spectral
8082 bins are not originally equidistant in wavelength.
8083 Images generated by the CASA clean task have spectral axes which
8084 are always equidistant in frequency.
8086 By default the image is written as a floating point fits file
8087 ({stfaf bitpix= -32}). Under rare circumstances you might want to
8088 save space and write it as scaled 16 bit integers ({stfaf bitpix =
8089 16}). You can have {stff tofits} calculate the scaling factors by
8090 using the default {stfaf minpix} and {stfaf maxpix}. If you set
8091 {stfaf minpix} and {stfaf maxpix}, values outside of that range will
8092 be truncated. This can be useful if all of the fits images dynamic
8093 range is being used by a few high or low values and you are not
8094 interested in preserving those values exactly. Besides the factor of
8095 two space savings you get by using 16 instead of 32 bits, integer
8096 images usually also compress well (for example, with the standard GNU
8097 software facility {tt gzip}).
8099 If the specified region extends beyond the image, it is truncated.
8101 The output mask is the combination (logical OR) of the default input
8102 pixelmask (if any) and the OTF mask.
8104 Sometimes it is useful to drop axes of length one (degenerate axes)
8105 because not all FITS readers can handle them. Use the {stfaf dropdeg}
8106 argument if you want to do this.
8107 If you want to specifically only drop a degenerate Stokes axis, use the {stfaf dropstokes}
8108 argument.
8110 If you want to place degenerate axes last in the FITS header,
8111 use the {stfaf deglast} argument.
8112 If you want to make sure that the Stokes axis is placed last in the FITS header,
8113 use the {stfaf stokeslast} argument.
8115 Input Parameters:
8116 outfile FITS file name. Default is input name + '.fits'
8117 velocity prefer velocity (rather than frequency) as primary spectral axis?
8118 optical use the optical (rather than radio) velocity convention?
8119 bitpix Bits per pixel, -32 (floating point) or 16 (integer)
8120 minpix Minimum pixel value for BITPIX=16, Default is to autoscale if minpix > maxpix.
8121 maxpix Maximum pixel value for BITPIX=16, Default is to autoscale if maxpix < minpix.
8122 region Region selection. Default is to use the full image.
8123 mask Mask to use. Default is none.
8124 overwrite Overwrite (unprompted) pre-existing output file?
8125 dropdeg Drop degenerate axes?
8126 deglast Put degenerate axes last in header?
8127 dropstokes Drop Stokes axis?
8128 stokeslast Put Stokes axis last in header?
8129 wavelength Write spectral axis in units of wavelength (instead of velocity or frequency)?
8130 airwavelength When wirting the spectral axis in units of wavelength, use air wavelength instead of vacuum wavelength?
8131 stretch Stretch the mask if necessary and possible? Default False
8132 history Write the image history to the FITS file? Default True
8134 Example:
8137 #
8138 print 't----t tofits Ex 1 t----'
8139 ia.maketestimage()
8140 ok = ia.tofits('MYFILE.FITS',overwrite=true)
8141 # write FITS image file
8142 ok = ia.tofits('MYFILE2.FITS', bitpix=16, overwrite=true)
8143 # Write as scaled 16 bit integers
8144 ia.close()
8145 #
8148 --------------------------------------------------------------------------------
8150 """
8151 return _image.image_tofits(self, *args, **kwargs)
8154 def torecord(self):
8155 """
8156 torecord(self) -> record *
8160 Summary:
8161 Return a record containg the image associated with this tool
8163 Description:
8167 You can convert an associated image to a record for manipulation or passing it
8168 to inputs of other methods of other tools. This method and fromrecord() are used
8169 for serialization and deserialization.
8171 Example:
8174 #
8175 print 't----t torecord Ex 1 t----'
8176 ia.maketestimage('image.large', overwrite=true)
8177 rec=ia.torecord()
8178 ia.close()
8184 --------------------------------------------------------------------------------
8186 """
8187 return _image.image_torecord(self)
8190 def type(self):
8191 """
8192 type(self) -> string
8196 Summary:
8197 Return the type of this tool
8199 Description:
8203 This function returns the string 'image'. It can be used in
8204 a script to make sure this variable is an Image
8205 tool.
8207 --------------------------------------------------------------------------------
8209 """
8210 return _image.image_type(self)
8213 def topixel(self, *args, **kwargs):
8214 """
8215 topixel(self, _value) -> record *
8219 Summary:
8220 Convert from world to pixel coordinate
8222 Description:
8226 This method converts from world to pixel coordinates. The world coordinate can
8227 be provided in many formats (numeric, string, quantum etc.) via the value
8228 parameter. These match the output of the toworld() method.
8230 This function is just a wrapper for the coordsys tool method of the same name,
8231 so see that documentation for a description and more examples.
8233 Input Parameters:
8234 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.
8236 Example:
8239 #
8240 print 't----t topixel Ex 1 t----'
8241 ia.maketestimage();
8242 w = ia.toworld([10,10], 'n') # Numeric vector
8243 ia.topixel(w)
8244 #{'ar_type': 'absolute',
8245 # 'numeric': array([10., 10.]), 'pw_type': 'pixel'}
8246 w = ia.toworld([10,10], 'm') # Record of measures
8247 ia.topixel(w)
8248 #{'ar_type': 'absolute',
8249 # 'numeric': array([10., 10.]), 'pw_type': 'pixel'}
8250 ia.close()
8251 #
8254 Convert a pixel coordinate to world as floats and then
8255 back to pixel. Do the same with the world coordinate
8256 formatted as measures instead.
8258 --------------------------------------------------------------------------------
8260 """
8261 return _image.image_topixel(self, *args, **kwargs)
8264 def toworld(self, *args, **kwargs):
8265 """
8266 toworld(self, _value, _format, _dovelocity) -> record *
8270 Summary:
8271 Convert from pixel to world coordinate
8273 Description:
8277 This method converts between pixel and world coordinates. A variety of return
8278 formats is supported. If format='n', numerical values are returned.
8279 If format='q', values formatted as quantities are returned. If format='s',
8280 values formatted as strings are returned. If format='m', values formatted as
8281 measures are returned. If format='m', one can choose to have the corresponding
8282 velcocites of an extant spectral coordinate computed as well by specifyting
8283 dovelocity=True (dovelocity is ignored if format is not equal to 'm' or if the
8284 image does not have a spectral coordinate).
8286 Input Parameters:
8287 value Absolute pixel coordinate. Numeric vector is allowed. Default is reference pixel.
8288 format What type of formatting? String from combination of 'n' (numeric), 'q' (quantity), 'm' (measure), 's' (string).
8289 dovelocity Compute corresponding spectral velocities if format='m'?
8291 Example:
8294 #
8295 print 't----t toworld Ex 1 t----'
8296 ia.maketestimage('hcn',overwrite=true)
8297 w = ia.toworld([10,10], 'n')
8298 print w
8299 #{'numeric': array([ 0.00174533, -0.0015708 ])}
8300 w = ia.toworld([10,10], 'nmq')
8301 print w
8302 #{'measure': {'direction': {'m0': {'unit': 'rad',
8303 # 'value': 0.0017453323593185704},
8304 # 'm1': {'unit': 'rad',
8305 # 'value': -0.0015707969259645381},
8306 # 'refer': 'J2000',
8307 # 'type': 'direction'}},
8308 # 'numeric': array([ 0.00174533, -0.0015708 ]),
8309 # 'quantity': {'*1': {'unit': 'rad', 'value': 0.0017453323593185704},
8310 # '*2': {'unit': 'rad', 'value': -0.0015707969259645381}}}
8311 ia.close()
8312 #
8315 Convert to a vector of floats and then to a record
8316 holding a vector of floats, a vector of quantities
8317 and a subrecord of measures.
8319 --------------------------------------------------------------------------------
8321 """
8322 return _image.image_toworld(self, *args, **kwargs)
8325 def unlock(self):
8326 """
8327 unlock(self) -> bool
8331 Summary:
8332 Release any lock on the image
8334 Description:
8338 This function releases any lock set on the imagefile (and also flushes
8339 any outstanding I/O to disk). It is not of general user interest. It
8340 can be useful in scripts when a file is being shared between more than
8341 one process. See also functions lock and
8342 haslock.
8344 Example:
8347 #
8348 print 't----t unlock Ex 1 t----'
8349 ia.fromarray('xx', ia.makearray(0,[10,20]), overwrite=true)
8350 ia.unlock()
8351 ia.close()
8352 #
8356 This releases the write lock on the imagefile. Now some
8357 other process can gain immediate access to the imagefile.
8359 --------------------------------------------------------------------------------
8361 """
8362 return _image.image_unlock(self)
8365 def newimagefromarray(self, *args, **kwargs):
8366 """
8367 newimagefromarray(self, _outfile, _pixels, _csys, _linear, _overwrite, _log, _type) -> image
8371 Summary:
8372 Construct a casa image from an array
8374 Description:
8378 This application converts a numpy array of any size into a CASA image.
8380 If outfile is specified, the image is written to the specified
8381 (persistent) disk file. If outfile is unset, the returned image tool
8382 is associated with a temporary image. This temporary image may be in
8383 memory or on disk, depending on its size. In this case, when the
8384 close() or done() method is called on the returned image tool, the
8385 associated temporary image is deleted.
8387 The type parameter controls the data type/precision of the pixel values of the
8388 created image. 'f' indicates that float precision point (32 bit precision) pixel
8389 values should be writted. 'd' indicates that double precision (64 bit precision)
8390 pixel values should be written. If the input array has complex (as opposed to
8391 real) values, then complex pixel values, with each of the real and imaginary
8392 parts having the specified precision, will be written. Array values will be cast
8393 automatically to the specified precision, so that the precision of the input
8394 array values may be increased, decreased, or unchanged depending on the input
8395 array type.
8397 The coordinate system, provided as a a dictionary (use eg, cs.torecord() to do
8398 that), is optional. If specified, it must have the same number of dimensions
8399 as the pixels array. Call the naxes() method on the coordinate system tool to
8400 see how many dimensions the coordinate system has. A coordinate system can be
8401 created from scratch using the coordinate system (cs) tool and methods therein,
8402 but often users prefer to use a coordinate system from an already existing image.
8403 This can be gotten using ia.coordsys() which returns a coordinate system tool.
8404 A torecord() call on that tool will result in a python dictionary describing
8405 the coordinate system which is the necessary format for the csys input parameter
8406 of ia.fromarray().
8408 If csys is not specified, a default coordinate system will be created. If
8409 linear=False (the default), the created coordinate system will have standard
8410 RA/DEC/Stokes/Spectral Coordinate axes depending upon the shape of the pixels
8411 array (Stokes axis must be no longer than 4 pixels and the spectral axis may
8412 precede the Stokes axis if eg, shape=[64,64,32,4]. Extra dimensions are given
8413 linear coordinates. If linear=True, then all the resulting coordinates
8414 are linear with the axes represent lengths. In this case each axis will have a
8415 value of 0.0 at its center pixel. The increment of each axis will be 1.0 km.
8417 Input Parameters:
8418 outfile Output image file name. Default is unset.
8419 pixels A numeric array is required.
8420 csys Coordinate System. Default is unset.
8421 linear Make a linear Coordinate System if csys not given
8422 overwrite Overwrite (unprompted) pre-existing output file?
8423 log Write image creation messages to logger
8424 type Pixel data type to write. 'f' (float precision) or 'd' (double precision)
8426 Example:
8429 #
8430 print 't----t newimagefromarray Ex 1 t----'
8431 im1=ia.newimagefromarray(outfile='test.data',
8432 pixels=ia.makearray(0, [64, 64, 4, 128]),
8433 overwrite=true)
8434 cs1 = im1.coordsys(axes=[0,1])
8435 im1.done()
8436 im2 = ia.newimagefromarray(pixels=ia.makearray(1.0, [32, 64]),
8437 csys=cs1.torecord())
8438 cs1.done()
8439 im2.done()
8440 #
8444 The first example creates a zero-filled imagefile named {sff
8445 test.data} which is of shape [64,64,4,128]. If you examine the header
8446 with {stff ia.summary()} you will see the default
8447 RA/DEC/Stokes/Frequency coordinate information. In the second
8448 example, a Coordinate System describing the first two axes of the
8449 image {sff test.data} is created and used to create a 2D image
8450 temporary image.
8452 --------------------------------------------------------------------------------
8454 """
8455 return _image.image_newimagefromarray(self, *args, **kwargs)
8458 def newimagefromfits(self, *args, **kwargs):
8459 """
8460 newimagefromfits(self, _outfile, _infile, _whichrep, _whichhdu, _zeroblanks, _overwrite) -> image
8464 Summary:
8465 Construct a casa image by conversion from a FITS image file
8467 Description:
8471 This function is used to convert a FITS disk image file (Float,
8472 Double, Short, Long are supported) to an casa imagefile. If
8473 {stfaf outfile} is given, the image is written to the specified disk
8474 file. If {stfaf outfile} is unset, the on-the-fly Image tool
8475 returned by this function is associated with a temporary image. This
8476 temporary image may be in memory or on disk, depending on its size.
8477 When you destroy the on-the-fly Image tool (with the done function) this
8478 temporary image is deleted.
8480 This function reads from the FITS primary array (when the image is at
8481 the beginning of the FITS file; {stfaf whichhdu=0}), or an image
8482 extension (when the image is elsewhere in the FITS file, {stfaf
8483 whichhdu $>$ 0}).
8485 By default, any blanked pixels will be converted to a mask value which
8486 is false, and a pixel value that is NaN. If you set {stfaf
8487 zeroblanks=T} then the pixel value will be zero rather than NaN. The
8488 mask will still be set to false. See the function
8489 replacemaskedpixels if you
8490 need to replace masked pixel values after you have created the image.
8492 Input Parameters:
8493 outfile Output image file name. Default is unset.
8494 infile Input FITS disk file name. Required.
8495 whichrep If this FITS file contains multiple coordinate representations, which one should we read
8496 whichhdu If this FITS file contains multiple images, which one should we read (0-based).
8497 zeroblanks If there are blanked pixels, set them to zero instead of NaN
8498 overwrite Overwrite (unprompted) pre-existing output file?
8500 Example:
8503 #
8504 print 't----t newimagefromfits Ex 1 t----'
8505 # Assume we can find test fits file using
8506 # CASAPATH environment variable
8507 pathname=os.environ.get('CASAPATH')
8508 pathname=pathname.split()[0]
8509 datapath=pathname+'/data/demo/Images/imagetestimage.fits'
8510 im1=ia.newimagefromfits('./myimage', datapath, overwrite=true)
8511 print im1.summary()
8512 print im1.miscinfo()
8513 print 'fields=', im1.miscinfo().keys()
8514 im1.done()
8515 #
8519 The FITS image is converted to a casa imagefile and access is
8520 provided via the imagetool called {stf im1}. Any FITS header
8521 keywords which were not recognized or used are put in the
8522 miscellaneous information bucket accessible with the miscinfo function. In
8523 the example we list the names of the fields in this record.
8525 --------------------------------------------------------------------------------
8527 """
8528 return _image.image_newimagefromfits(self, *args, **kwargs)
8531 def newimagefromimage(self, *args, **kwargs):
8532 """
8533 newimagefromimage(self, _infile, _outfile, _region, _mask, _dropdeg, _overwrite) -> image
8537 Summary:
8538 Construct an on-the-fly image tool from a region of a casa image file
8540 Description:
8544 This function applies a region to a disk imagefile, creates a new
8545 imagefile containing the (sub)image, and associates a new imagetool
8546 with it.
8548 The input disk image file may be in native casa, fits (Float,
8549 Double, Short, Long are supported), or Miriad format. Look
8550 htmlref{here}{IMAGES:FOREIGNIMAGES} for more information on foreign
8551 images.
8553 If {stfaf outfile} is given, the (sub)image is written to the specified
8554 disk file.
8556 If {stfaf outfile} is unset, the Image tool actually references the
8557 input image file. So if you deleted the input image disk file, it
8558 would render this tool useless. When you destroy this on-the-fly
8559 tool (with the done
8560 function) the reference connection is broken.
8562 Sometimes it is useful to drop axes of length one (degenerate axes).
8563 Use the {stfaf dropdeg} argument if you want to do this.
8565 The output mask is the combination (logical OR) of the default input
8566 pixelmask (if any) and the OTF mask. Any other input pixelmasks
8567 will not be copied. Use function
8568 maskhandler if you need to copy other
8569 masks too.
8571 See also the subimage function.
8573 Input Parameters:
8574 infile Input image file name. Required.
8575 outfile Output sub-image file name. Default is unset.
8576 region Region selection. Default is to use the full image.
8577 mask Mask to use. Default is none.
8578 dropdeg Drop degenerate axes
8579 overwrite Overwrite (unprompted) pre-existing output file?
8581 Example:
8584 #
8585 print 't----t newimagefromimage Ex 1 t----'
8586 ia.maketestimage('test1',overwrite=true)
8587 ia.maketestimage('test2',overwrite=true)
8588 print ia.name()
8589 #[...]test2
8590 im1=ia.newimagefromimage('test1')
8591 print im1.name()
8592 #[...]test1
8593 print im1.summary()
8594 im2=ia.newimagefromimage('test2')
8595 print im2.name()
8596 #[...]test2
8597 print im1.name()
8598 #[...]test1
8599 ia.close()
8600 im1.done()
8601 im2.done()
8602 #
8605 --------------------------------------------------------------------------------
8607 """
8608 return _image.image_newimagefromimage(self, *args, **kwargs)
8611 def newimagefromshape(self, *args, **kwargs):
8612 """
8613 newimagefromshape(self, _outfile, _shape, _csys, _linear, _overwrite, _log, _type) -> image
8617 Summary:
8618 Construct an empty casa image from a shape
8620 Description:
8624 This function creates a CASA image with the specified shape. It is similar to
8625 ia.fromshape(), but instead returns a new image analysis tool attached to the
8626 new image, rather than attaching the new image to the current tool. All the
8627 pixel values in the image are set to 0. One may create an image with float
8628 precision pixels (type='f'), complex float precision pixels (type='c'), double
8629 precision pixels (type='d'), or complex double precision pixels ('cd'). To use a
8630 numpy array of values to create an image, use ia.(newimage)fromarray(). To make
8631 a 2-D image from a packaged FITS file, use ia.maketestimage().
8633 If outfile is given, the image is written to the specified disk file. If
8634 outfile is unset, the image analysis tool is associated with a temporary image.
8635 This temporary image may be in memory or on disk, depending on its size. When
8636 you close the image analysis tool (with the ia.close() method, the temporary
8637 image is deleted.
8639 The coordinate system, provided as a coordinate system tool record, is optional.
8640 If provided, it must be dimensionally consistent with the specified shape.
8642 If the coordinate system is not provided, a default coordinate system will be
8643 created. If linear=False (the default), then it is a
8644 standard RA/DEC/Stokes/Spectral coordinate system depending exactly upon the
8645 shape (the Stokes axis must be no longer than 4 pixels and spectral axis may
8646 occur prior to the Stokes axis if eg, shape=[64,64,32,4]. Extra dimensions are
8647 given linear coordinates. If linear=True, then the coordinate system will have
8648 linear coordinates.
8650 Input Parameters:
8651 outfile Name of output image file. Default is unset.
8652 shape Shape of image. Required.
8653 csys Record describing Coordinate System. Default is unset.
8654 linear Make a linear Coordinate System if csys not given?
8655 overwrite Overwrite (unprompted) pre-existing output file?
8656 log Write image creation messages to logger
8657 type Type of image. 'f' means Float, 'c' means complex.
8659 Example:
8662 #
8663 print 't----t newimagefromshape Ex 1 t----'
8664 im1=ia.newimagefromshape('test2.data', [64,64,128], overwrite=true)
8665 cs1 = im1.coordsys(axes=[0,2])
8666 im1.done()
8667 im2 = ia.newimagefromshape(shape=[10, 20], csys=cs1.torecord())
8668 cs1.done()
8669 im2.done()
8670 #
8674 The first example creates a zero-filled imagefile named {sff
8675 test.data} of shape [64,64,128]. If you examine the header with
8676 {stff ia.summary()} you will see the RA/DEC/Spectral coordinate
8677 information. In the second example, a Coordinate System describing
8678 the first and third axes of the image {sff test2.data} is created and
8679 used to create a 2D temporary image.
8681 --------------------------------------------------------------------------------
8683 """
8684 return _image.image_newimagefromshape(self, *args, **kwargs)
8687 def pbcor(self, *args, **kwargs):
8688 """
8689 pbcor(self, _pbimage, _outfile, _overwrite, _box, _region, _chans, _stokes, _mask, _mode, _cutoff, _stretch) -> image
8693 Summary:
8694 Construct a primary beam corrected image from an image and a primary beam
8696 Description:
8699 Correct an image for primary beam attenuation using an image of the primary beam pattern.
8700 The primary beam pattern can be provided as an image, in which case 1. it must have the same
8701 shape as the input image and its coordinate system must be the same, or 2. it must
8702 be a 2-D image in which case its coordinate system must consist of a (2-D) direction
8703 coordinate which is the same as the direction coordinate in the input image and
8704 its direction plane must be the same shape as that of the input image. Alternatively,
8705 pbimage can be an array of pixel values in which case the same dimensionality and
8706 shape constraints apply.
8707 An image tool referencing the corrected image is returned. The corrected image will also
8708 be written to disk if outfile is not empty (and overwrite=True if outfile already exists).
8709 One can choose between dividing the image by the primary beam pattern (mode='divide') or
8710 multiplying the image by the primary beam pattern (mode='multiply'). One can also choose
8711 to specify a cutoff limit for the primary beam pattern. For mode='divide', for all pixels
8712 below this cutoff in the primary beam pattern, the output image will be masked. In the
8713 case of mode='multiply', all pixels in the output will be masked corresponding to pixels
8714 with values greater than the cutoff in the primary beam pattern. A negative value for
8715 cutoff means that no cutoff will be applied, which is the default.
8718 Input Parameters:
8719 pbimage Name of the primary beam image which must exist or array of values for the pb response. Default ''
8720 outfile Output image name. If empty, no image is written. Default ''
8721 overwrite Overwrite the output if it exists? Default False
8722 box Rectangular region(s) to select in direction plane. Default is to use the entire direction plane.
8723 region Region selection. Default is to use the full image.
8724 chans Channels to use. Default is to use all channels.
8725 stokes Stokes planes to use. Default is to use all stokes planes.
8726 mask Mask to use. Default is none.
8727 mode Divide or multiply the image by the primary beam image. Minimal match supported. Default 'divide'
8728 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
8729 stretch Stretch the mask if necessary and possible? Default False
8731 Example:
8733 ia.open('attenuated.im')
8734 pbia = ia.pbcor(pbimage='mypb.im', outname='pbcorred.im', mode='divide', cutoff=0.1)
8735 ia.done()
8736 # do stuff with ia tool attached to pb image and close it
8737 pbia.done()
8739 --------------------------------------------------------------------------------
8741 """
8742 return _image.image_pbcor(self, *args, **kwargs)
8745 def pixeltype(self):
8746 """
8747 pixeltype(self) -> string
8751 Summary:
8752 Get the pixel data type of the attached image
8754 Description:
8757 This application returns the data type of the pixels of the attached image as a string.
8758 The possible values are: 'float' which indicates real valued, floating point, 32 bit pixel
8759 values, 'complex' which indicates complex valued, floating point, 32 bit (for each of the
8760 real and imaginary parts) pixel values, 'double' which indicates real valued, floating
8761 point, 64 bit pixel values, and 'dcomplex' which indicates complex valued, floating point,
8762 64 bit (for each of the real and imaginary parts) pixel values.
8765 --------------------------------------------------------------------------------
8767 """
8768 return _image.image_pixeltype(self)
8771 def pv(self, *args, **kwargs):
8772 """
8773 pv(self, _outfile, _start, _end, _center, _length, _pa, _width, _unit, _overwrite, _region, _chans, _stokes, _mask, _stretch, _wantreturn) -> image
8777 Summary:
8778 Construct a position-velocity image between two points in the direction plane.
8780 Description:
8783 Create a position-velocity image by specifying either two points between which a slice is taken in the direction
8784 coordinate or a center, position angle, and length describing the slice. The spectral extent of the resulting image
8785 will be that provided by the region specification or the entire spectral range of the input image if no region is
8786 specified. One may not specify a region in direction space; that is accomplished by specifying the start and end
8787 points or the center, length, and position angle of the slice. The parameters start and end may be specified as two
8788 element arrays of numerical values, in which case these values will be interpreted as pixel locations in the input
8789 image. Alternatively, they may be expressed as arrays of two strings each representing the direction. These strings
8790 can either represent quantities (eg ['40.5deg', '0.5rad') or be sexigesimal format (eg ['14h20m20.5s','-30d45m25.4s'],
8791 ['14:20:20.5s','-30.45.25.4']). In addition, they may be expressed as a single string containing the longitude and
8792 latitude values and optionally a reference frame value, eg 'J2000 14:20:20.5s -30.45.25.4'. The center parameter is
8793 specified in the same way. The length parameter may be specified as a single numerical value, in which case it is
8794 interpreted as the length in pixels, or a valid quantity, in which case it must have units conformant with the direction
8795 axes units. The pa (position angle) parameter must be specified as a valid quantity with angular units. The position
8796 angle is interpreted in the usual astronomical sense; ie measured from north through east. Either start/end or
8797 center/pa/length must be specified; if a parameter from one of these sets is specified, a parameter from the other set may
8798 not be specified. In either case, the end points of the segment must fail within the input image, and they both must be at
8799 least 2 pixels from the edge of the input image to facilite rotation (see below).
8801 One may specify a width, which is the number of pixels centered along and perpendicular
8802 to the direction slice that are used for averaging along the slice. The width may be specified as an integer, in which
8803 case it must be positive and odd. Alternatively, it may be specified as a valid quantity string (eg, '4arcsec') or
8804 quantity record (eg qa.quantity('4arcsec'). In this case, units must be conformant to the direction axes units (usually
8805 angular units) and the specified quantity will be rounded up, if necessary, to the next highest equivalent odd integer number
8806 of pixels. The default value of 1 represents no averaging.
8807 A value of 3 means average one pixel on each side of the slice and the pixel on the slice.
8808 Note that this width is applied to pixels in the image after it has been rotated (see below for a description
8809 of the algorithm used). The end points of the specified segment must fail within the input
8810 image, and they both must be at least 2 pixels from the edge of the input image to facilite rotation (see below).
8812 One may specify the unit for the angular offset axis.
8814 A true value for the wantreturn parameter indicates that an image analysis tool attached to the created
8815 image should be returned. Nothing is returned if wantreturn is false, but then outfile should be specified
8816 (unless perhaps you are debugging).
8818 Internally, the image is first rotated, padding first if necessary to include relevant pixels that would otherwise
8819 be excluded by the rotation operation, so that the slice is horizontal, with the starting pixel left of the
8820 ending pixel. Then, the pixels within the specified width of the slice are averaged and the resulting image is
8821 written and/or returned. The output image has a linear coordinate in place of the direction coordinate of the
8822 input image, and the corresponding axis represents angular offset with the center pixel having a value of 0.
8824 The equivalent coordinate system, with a (usually) rotated direction coordinate (eg, RA and Dec) is written
8825 to the output image as a table record. It can be retrieved using the table tool as shown in the example below.
8828 Input Parameters:
8829 outfile Output image name. If empty, no image is written. Default ''
8830 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.
8831 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.
8832 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.
8833 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.
8834 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.
8835 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.
8836 unit Unit for the offset axis in the resulting image. Must be a unit of angular measure.
8837 overwrite Overwrite the output if it exists?
8838 region Region selection. Default is to use the full image. No selection is permitted in the direction plane.
8839 chans Channels to use. Channels must be contiguous. Default is to use all channels.
8840 stokes Stokes planes to use. Planes must be contiguous. Default is to use all stokes planes.
8841 mask Mask to use. Default is none.
8842 stretch Stretch the mask if necessary and possible? Default False
8843 wantreturn Return an image analysis tool attached to the created image?
8845 Example:
8847 ia.open('my_spectral_cube.im')
8848 # create a pv image with the position axis running from ra, dec pixel positions of [45, 50] to [100, 120]
8849 # in the input image
8850 mypv = ia.pv(outfile='pv.im', start=[45,50], end=[100,120], wantreturn=true)
8851 ia.done()
8852 # analyze the pv image, such as get statistics
8853 pvstats = mypv.statistics()
8854 # when done, close the tool to release system resources
8855 mypv.done()
8857 # get the alternate coordinate system information
8858 tb.open('pv.im')
8859 alternate_csys_record = tb.getkeyword('misc')['secondary_coordinates']
8860 tb.done()
8862 --------------------------------------------------------------------------------
8864 """
8865 return _image.image_pv(self, *args, **kwargs)
8868 def makearray(self, *args, **kwargs):
8869 """
8870 makearray(self, _v, _shape) -> variant *
8874 Summary:
8875 Construct an initialized multi-dimensional array.
8877 Description:
8880 This function takes two arguments. The first argument is the initial
8881 value for the new array. The second is a vector giving the lengths of
8882 the dimensions of the array.
8884 Input Parameters:
8885 v Value with which to initial array elements
8886 shape Vector containing array dimensions.
8888 Example:
8890 A three dimensional array that is initialized to all zeros. Each of
8891 the three dimensions of the cube has a length of four.
8894 #
8895 print 't----t makearray Ex 1 t----'
8896 cube = ia.makearray(0,[4,4,4])
8897 #
8900 --------------------------------------------------------------------------------
8902 """
8903 return _image.image_makearray(self, *args, **kwargs)
8906 def isconform(self, *args, **kwargs):
8907 """
8908 isconform(self, _other) -> bool
8912 Summary:
8913 Returns true of the shape, coordinate system, and axes order of the specified image matches this image.
8915 Description:
8918 Returns True if the shape, coordinate system, and axes order of the specified image
8919 matches the current image.
8921 Input Parameters:
8922 other name of image to test
8924 Example:
8926 ia.isconform('my_mystery.image')
8928 --------------------------------------------------------------------------------
8930 """
8931 return _image.image_isconform(self, *args, **kwargs)
8933 __swig_destroy__ = _image.delete_image
8934 __del__ = lambda self: None
8935image_swigregister = _image.image_swigregister
8936image_swigregister(image)
8938# This file is compatible with both classic and new-style classes.