casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
test_immoments.py
Go to the documentation of this file.
00001 ########################################################################
00002 #  immoment_test.py
00003 #
00004 #
00005 # Copyright (C) 2008, 2009
00006 # Associated Universities, Inc. Washington DC, USA.
00007 #
00008 # This scripts free software; you can redistribute it and/or modify it
00009 # under the terms of the GNU Library General Public License as published by
00010 # the Free Software Foundation; either version 2 of the License, or (at your
00011 # option) any later version.
00012 #
00013 # This library is distributed in the hope that it will be useful, but WITHOUT
00014 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
00015 # FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
00016 # License for more details.
00017 #
00018 # You should have received a copy of the GNU Library General Public License
00019 # along with this library; if not, write to the Free Software Foundation,
00020 # Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
00021 #
00022 # Correspondence concerning AIPS++ should be adressed as follows:
00023 #        Internet email: aips2-request@nrao.edu.
00024 #        Postal address: AIPS++ Project Office
00025 #                        National Radio Astronomy Observatory
00026 #                        520 Edgemont Road
00027 #                        Charlottesville, VA 22903-2475 USA
00028 #
00029 # <author>
00030 # Shannon Jaeger (University of Calgary)
00031 # </author>
00032 #
00033 # <summary>
00034 # Test suite for the CASA immoments Task
00035 # </summary>
00036 #
00037 # <reviewed reviwer="" date="" tests="" demos="">
00038 # </reviewed
00039 #
00040 # <etymology>
00041 # immoments_test stands for image momemnts test
00042 # </etymology>
00043 #
00044 # <synopsis>
00045 # immoments_test.py is a Python script that tests the correctness
00046 # of the immoments task in CASA.
00047 #
00048 # The tests include:
00049 #    1. Incorrect input for each paramter.  Incorrect input includes
00050 #       one input of the incorrect data type, out-of-bounds (where
00051 #       applicable, and correct data type but non-sensical.
00052 #    2. Calculating one example of each type of moment.
00053 #    3. Using the include/exclude pix parameter
00054 #    4. Calculating moments with region selection on the sky,
00055 #       channels, and stokes values, as well as using an input
00056 #       region file.
00057 #    5.Calculating moments with a mask either from the image
00058 #      itself or another image.
00059 # for generating momements along a user specified axis on a CASA image.
00060 # This is a time-honoured spectral-line analysis technique for discovering
00061 # spectral line information.
00062 #
00063 # In this task, moment, refers to collapsing an axis of the image,
00064 # the moment axis, to a single pixel.
00065 #
00066 # The various moments that can be calculated are described in detail
00067 # at http://casa.nrao.edu/docs/casaref/image.moments.html#x59-590001.1.1
00068 # 
00069 # </synopsis> 
00070 #
00071 # <example>
00072 # # This test was designed to run in the automated CASA test system.
00073 # # This exmple shows who to run it manually from with casapy.
00074 # runUnitTest.main(['test_imhead'])
00075 #
00076 # or outside casapy like this:
00077 # casapy -c runUnitTest.py test_imhead
00078 #
00079 # </example>
00080 #
00081 # <motivation>
00082 # To provide a test standard to the immoments task to try and ensure
00083 # coding changes do not break the 
00084 # </motivation>
00085 #
00086 # <todo>
00087 # Almost everything!
00088 # </todo>
00089 
00090 import random
00091 import os
00092 import shutil
00093 import numpy
00094 import casac
00095 import math
00096 from tasks import *
00097 from taskinit import *
00098 import unittest
00099 
00100     #
00101     # To make things a little more interesting, I've used the
00102     # lyrics to song for debug msgs, guess which song and you win
00103     # a prize! If only I could get it to play at the same time!.
00104     #
00105     # To turn them off just set debugMsgs=False
00106     
00107 debug_msgs={}
00108 debug_msgs[0]= "This time I wonder what it feels like"
00109 debug_msgs[1]= "To find the one in this life"
00110 debug_msgs[2]= "The one we all dream of"
00111 debug_msgs[3]= "but dreams just aren't enough"
00112 debug_msgs[4]= "So I'll be waiting for the real thing"
00113 debug_msgs[5]= "I'll know it by the feeling"
00114 debug_msgs[6]= "The moment when we're meeting"
00115 debug_msgs[7]= "Will play out like a scene"
00116 debug_msgs[8]= "right off the silver screen."
00117 debug_msgs[9]= "So I'll be holdin' my breath"
00118 debug_msgs[10]= 'Until that moment when'
00119 debug_msgs[11]= "I find the one that I'll spend forever with!"
00120 
00121 debug_msgs[12]= 'Cause nobody wants to be the last one there'
00122 debug_msgs[13]= "'Cause everyone wants to feel like somone cares"
00123 debug_msgs[14]= 'Somone to love with my life in their hands'
00124 debug_msgs[15]= "There's gotta be somebody for me like that"
00125 
00126 debug_msgs[16]= " 'Cause nobody wants to go it on their own"
00127 debug_msgs[17]= "And everyone wants to know they're not alone"
00128 debug_msgs[18]= "There's somebody else that feels the same somewhere"
00129 debug_msgs[19]= "There's gotta be somebody for me out there"
00130 
00131 debug_msgs[20]= "Tonight, out on the street out in the moonlight"
00132 debug_msgs[21]= "And dammit this feels too right"
00133 debug_msgs[22]= "It's just like Deja Vu"
00134 debug_msgs[23]= "Me standin$(B!G(B here with you"
00135 debug_msgs[24]= "So I'll be holdin`my own breath"
00136 debug_msgs[25]= "Could this be the end?"
00137 debug_msgs[26]= "Is it that moment when"
00138 debug_msgs[27]= "I find the one that I'll spend forever with?"
00139 
00140 debug_msgs[28]= " 'Cause nobody wants to be the last one there"
00141 debug_msgs[29]= " 'Cause everyone wants to feel like someone cares."
00142 debug_msgs[30]= "Someone to love with my life in their hands."
00143 debug_msgs[31]= "There's gotta be somebody for me like that."
00144 
00145 debug_msgs[32]= "'Cause nobody wants to do it on their own"
00146 debug_msgs[33]= "And everyone wants to know theyN4re not alone."
00147 debug_msgs[34]= "There's somebody else that feels the same somewhere"
00148 debug_msgs[35]= "There`s gotta be somebody for me out there."
00149 
00150 debug_msgs[36]= "You can't give up!"
00151 debug_msgs[37]= "Lookin' for that diamond in the rough"
00152 debug_msgs[38]= "You never know but when it shows up"
00153 debug_msgs[39]= "Make sure you're holdin` on"
00154 debug_msgs[40]= "'Cause it could be the one, the one you're waiting on"
00155 
00156 debug_msgs[41]= "'Cause nobody wants to be the last one there."
00157 debug_msgs[42]= "And everyone wants to feel like someone cares."
00158 debug_msgs[43]= "Someone to love with my life in their hands."
00159 debug_msgs[44]= "There has gotta be somebody for me"
00160 debug_msgs[45]= "Ohhhhhh."
00161 
00162 debug_msgs[46]= "Nobody wants to do it on their own"
00163 debug_msgs[47]= "And everyone wants to know they're not alone."
00164 debug_msgs[48]= "Is there somebody else that feels the same somewhere?"
00165 debug_msgs[49]= "There`s gotta be somebody for me out there."
00166 
00167 debug_msgs[50]= "Nobody wants to be the last one there"
00168 debug_msgs[51]= "'Cause everyone wants to feel like someone cares."
00169 debug_msgs[52]= "Is there somebody else that feels the same somewhere?"
00170 debug_msgs[53]= "There has gotta be somebody for me out there."
00171 
00172 debugMsgs = False
00173 def _momentTest_debug_msg( msgNum=0 ):
00174     if ( not debugMsgs ):
00175         return
00176     idx = msgNum % 54
00177     print str(msgNum)+":  "+debug_msgs[idx]
00178     return
00179 
00180 # input files
00181 list1=['n1333_both.image','n1333_both.image.rgn']
00182 list2=['n1333_both.image','n1333_both.src.tmom0.all','n1333_both.image.rgn', 
00183        'immoment_image', 'first_moment.im']
00184 #list=['n1333_both.image', 'n1333_both.src.tmom0.blu', 'n1333_both.src.tmom0.red', 
00185 #       'n1333_both.src.tmom0.all', 'n1333_both.src.tmom1.all', 'n1333_both.image.rgn', 
00186 #       'immoment_image', 'first_moment.im']
00187 
00188 def make_gauss2d(shape, xfwhm, yfwhm):
00189     fac = 4*math.log(2)
00190     values = numpy.empty(shape, dtype=float)
00191     for i in range(shape[0]):
00192         x = shape[0]/2 - i
00193         for j in range(shape[1]):
00194             y = shape[1]/2 - j
00195             xfac = x*x*fac/(xfwhm*xfwhm)
00196             yfac = y*y*fac/(yfwhm*yfwhm)
00197             values[i, j] = math.exp(-(xfac + yfac));
00198     return values
00199 
00200 ####################################################################
00201 # Incorrect inputs to parameters.  The parameters are:
00202 #    imagename
00203 #    moments
00204 #    axis
00205 #    region
00206 #    box
00207 #    chans
00208 #    stokes
00209 #    mask
00210 #    includepix
00211 #    excludepix
00212 #    outfile
00213 #
00214 # Returns True if successful, and False if it has failed.
00215 ####################################################################
00216 class immoment_test1(unittest.TestCase):
00217     
00218     def setUp(self):
00219         if(os.path.exists(list1[0])):
00220             for file in list1:
00221                 os.system('rm -rf ' +file)
00222         
00223 #        datapath = os.environ.get('CASAPATH').split()[0]+'/data/regression/ngc1333/reference/ngc1333_regression/'
00224         datapath = os.environ.get('CASAPATH').split()[0]+'/data/regression/immoment/'
00225         for file in list1:
00226             os.system('cp -RL ' +datapath + file +' ' + file)
00227 
00228 
00229     def tearDown(self):
00230         for file in list1:
00231             os.system('rm -rf ' +file)
00232             os.system('rm -rf input_test*')
00233             os.system('rm -rf moment_test*')
00234         
00235         
00236     def test_input(self):
00237         '''Immoment: Test input/output parameters'''
00238         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00239         casalog.post( "Starting immoments INPUT/OUTPUT tests.", 'NORMAL2' )
00240     
00241     
00242         #######################################################################
00243         # Testing the imagename parameter.
00244         #    1. Bad file name should throw and exception
00245         #    2. Good file name, a file should be
00246         #######################################################################
00247 #        _momentTest_debug_msg( 5 )
00248         results = None
00249         results = immoments( 'n1333_both', moments=[0], outfile='input_test_1' )
00250         if ( results != None ):
00251             retValue['success']=False
00252             retValue['error_msgs']=retValue['error_msgs']\
00253                  +"\nError: Badfile, 'n1333_both', was not reported as bad."
00254             
00255 #        _momentTest_debug_msg( 6 )
00256         results=None
00257         try:
00258             results=immoments( 'n1333_both.image', moments=[0], outfile='input_test_1' )
00259         except:
00260             retValue['success']=False
00261             retValue['error_msgs']=retValue['error_msgs']\
00262                        +"\nError: Unable to create moment 0 on n133_both.image"
00263         if ( not os.path.exists( 'input_test_1' ) or results == None ):
00264             retValue['success']=False
00265             retValue['error_msgs']=retValue['error_msgs']\
00266                        +"\nError: Moment file, 'input_test_1', was not created."
00267     
00268             
00269         #######################################################################
00270         # Testing MOMENTS parameter, valid values are -1 to 11
00271         #    1. Below valid range: -2, and -10
00272         #    2. Above valid range: 12 and 21
00273         #    3. Within range: -1,5, 11
00274         #######################################################################
00275         casalog.post( "The moment parameter tests will cause errors to occur, do not be alarmed", 'WARN' )
00276 #        _momentTest_debug_msg( 7 )
00277         results=None
00278         try:
00279             results= immoments( 'n1333_both.image', moments=[-2], outfile='moment_test' )
00280         except:
00281             no_op='noop'
00282         else:
00283             if ( results != None ):
00284                 retValue['success']=False
00285                 retValue['error_msgs']=retValue['error_msgs']\
00286                        +"\nError: No exception thrown for bad moment value (-2)"
00287                  
00288 #        _momentTest_debug_msg( 8 )
00289         results=None    
00290         try:
00291             results=immoments( 'n1333_both.image', moments=[-10], outfile='moment_test' )
00292         except:
00293             no_op='noop'
00294         else:
00295             if ( results != None and results!=True ):
00296                 retValue['success']=False
00297                 retValue['error_msgs']=retValue['error_msgs']\
00298                        +"\nError: No exception thrown for bad moment value (-10)"
00299                 
00300 #        _momentTest_debug_msg( 9 )
00301         results=None    
00302         try:
00303             results=immoments( 'n1333_both.image', moments=[12], outfile='moment_test' )
00304         except:
00305             no_op='noop'
00306         else:
00307             if ( results != None and results!=True ):
00308                 retValue['success']=False
00309                 retValue['error_msgs']=retValue['error_msgs']\
00310                      +"\nError: No exception thrown for bad moment value (12)"\
00311                      +"\n\t REULTS: "+str(results)
00312                 
00313                 
00314     
00315 #        _momentTest_debug_msg( 10 )
00316         results=None
00317         try:
00318             results=immoments( 'n1333_both.image', moments=[21], outfile='moment_test' )
00319         except:
00320             no_op='noop'
00321         else:
00322             if ( results != None ):
00323                 retValue['success']=False
00324                 retValue['error_msgs']=retValue['error_msgs']\
00325                        +"\nError: No exception thrown for bad moment value (21)  "+str(type(results))
00326     
00327     
00328         # The remaining tests should succeed.
00329 #        _momentTest_debug_msg( 11 )
00330         results=None
00331         try:    
00332             results=immoments( 'n1333_both.image', moments=[-1], axis='spec', outfile='moment_test_2_1' )
00333         except Exception, err:
00334             retValue['success']=False
00335             retValue['error_msgs']=retValue['error_msgs']\
00336                        +"\nError: Unable to create moment -1 on n133_both.image\n"\
00337                        +str(err)
00338         if ( not os.path.exists( 'moment_test_2_1' ) or not isinstance( results, object) ):
00339             retValue['success']=False
00340             retValue['error_msgs']=retValue['error_msgs']\
00341                        +"\nError: Moment file, 'moment_test_2_1', was not created."
00342             
00343 #        _momentTest_debug_msg( 12 )
00344         results=None    
00345         try:    
00346             results=immoments( 'n1333_both.image', moments=[5], axis='spec', outfile='moment_test_2_5' )
00347         except Exception, err:
00348             retValue['success']=False
00349             retValue['error_msgs']=retValue['error_msgs']\
00350                        +"\nError: Unable to create moment 5 on n133_both.image\n"\
00351                        +str(err)
00352         if ( not os.path.exists( 'moment_test_2_5' ) or not isinstance( results, object) ):
00353             retValue['success']=False
00354             retValue['error_msgs']=retValue['error_msgs']\
00355                        +"\nError: Moment file, 'moment_test_2_5', was not created."
00356             
00357 #        _momentTest_debug_msg( 13 )
00358         results=None    
00359         try:    
00360             results=immoments( 'n1333_both.image', moments=[11], axis='spec', outfile='moment_test_2_11' )
00361         except Exception, err:
00362             retValue['success']=False
00363             retValue['error_msgs']=retValue['error_msgs']\
00364                        +"\nError: Unable to create moment 11 on n133_both.image\n"\
00365                        +str(err)
00366         if ( not os.path.exists( 'moment_test_2_11' ) or not isinstance( results, object) ):
00367             retValue['success']=False
00368             retValue['error_msgs']=retValue['error_msgs']\
00369                        +"\nError: Moment file, 'moment_test_2_11', was not created."
00370             
00371         #######################################################################
00372         # Testing AXIS parameter, valid values are spec, stokes, ra, dec,
00373         #    as well as 0,1,2,3 ... (depending on the number of axes)
00374         #######################################################################
00375 #        _momentTest_debug_msg( 14 )
00376         results=None    
00377         try:    
00378             results=immoments( 'n1333_both.image', moments=[0], axis='ra', outfile='input_test_axis_ra' )
00379         except Exception, err:
00380             retValue['success']=False
00381             retValue['error_msgs']=retValue['error_msgs']\
00382                        +"\nError: Unable to create moment 0 on axis ra on n133_both.image\n"\
00383                        +str(err)
00384         if ( not os.path.exists( 'input_test_axis_ra' ) or not isinstance( results, object) ):
00385             retValue['success']=False
00386             retValue['error_msgs']=retValue['error_msgs']\
00387                        +"\nError: Moment file, 'input_test_axis_ra', was not created."
00388     
00389 #        _momentTest_debug_msg( 15 )
00390         results=None
00391         try:
00392             results=immoments( 'n1333_both.image', moments=[0], axis=1, outfile='input_test_axis_dec' )
00393         except Exception, err:
00394             retValue['success']=False
00395             retValue['error_msgs']=retValue['error_msgs']\
00396                        + "\nError: Unable to create moment 0 on axis spec on n133_both.image\n"\
00397                        +str(err)
00398     
00399         if ( not os.path.exists( 'input_test_axis_dec' ) or not isinstance( results, object) ):
00400             retValue['success']=False
00401             retValue['error_msgs']=retValue['error_msgs']\
00402                  +"\nError: Moment file, 'input_test_axis_dec', was not created."
00403     
00404 #        _momentTest_debug_msg( 16 )
00405         results=None    
00406         try:    
00407             results=immoments( 'n1333_both.image', moments=[0], axis='spec', outfile='input_test_axis_spec' )
00408         except Exception, err:
00409             retValue['success']=False
00410             retValue['error_msgs']=retValue['error_msgs']\
00411                        +"\nError: Unable to create moment 0 on axis spec on n133_both.image\n"\
00412                        +str(err)
00413         if ( not os.path.exists( 'input_test_axis_spec' ) or not isinstance( results, object) ):
00414             retValue['success']=False
00415             retValue['error_msgs']=retValue['error_msgs']\
00416                        +"\nError: Moment file, 'input_test_axis_spec', was not created."
00417     
00418 #        _momentTest_debug_msg( 17 )
00419         results=None    
00420         try:    
00421             results=immoments( 'n1333_both.image', moments=[0], axis='stokes', outfile='input_test_axis_stokes' )
00422         except Exception, err:
00423             retValue['success']=False
00424             retValue['error_msgs']=retValue['error_msgs']\
00425                        +"\nError: Unable to create moment 0 on axis stokes on n133_both.image\n"\
00426                        +str(err)
00427     #    if ( not os.path.exists( 'input_test_axis_stokes' ) or not isinstance( results, object) ):
00428     #        retValue['success']=False
00429     #        retValue['error_msgs']=retValue['error_msgs']\
00430     #                   +"\nError: Moment file, 'input_test_axis_stokes', was not created."
00431     
00432         casalog.post( "The axis parameter tests will cause errors to occur, do not be alarmed", 'WARN' )
00433 #        _momentTest_debug_msg( 18 )
00434         results = None
00435         results = immoments( 'n1333_both.image', moments=[0], axis=-1, outfile='input_test_bad_axis' )
00436         if ( results == None ):
00437             retValue['success']=False
00438             retValue['error_msgs']=retValue['error_msgs']\
00439                  +"\nError: Bad axis value, '-1', was not reported as bad."
00440     
00441 #        _momentTest_debug_msg( 19 )
00442         results = None
00443         results = immoments( 'n1333_both.image', moments=[0], axis=4, outfile='input_test_bad_axis' )
00444         if ( results != None ):
00445             retValue['success']=False
00446             retValue['error_msgs']=retValue['error_msgs']\
00447                  +"\nError: Bad axis value, '4', was not reported as bad."
00448     
00449 #        _momentTest_debug_msg( 20 )
00450         results = None
00451         results = immoments( 'n1333_both.image', moments=[0], axis='whatever', outfile='input_test_bad_axis' )
00452         if ( results != None ):
00453             retValue['success']=False
00454             retValue['error_msgs']=retValue['error_msgs']\
00455                  +"\nError: Bad axis value, 'whatever', was not reported as bad."
00456     
00457         #######################################################################
00458         # Testing REGION parameter
00459         # Expects a file containing a region record, as created by the viewer.
00460         # Tests include bad file name, file with bad content, and good file.
00461         ####################################################################### 
00462         casalog.post( "The axis parameter tests will cause errors to occur, do not be alarmed", 'WARN' )
00463 #        _momentTest_debug_msg( 21 )
00464         results = None
00465         results = immoments( 'n1333_both.image', region=3, outfile='input_test_bad_rgn' )
00466         if ( results ):
00467             retValue['success']=False
00468             retValue['error_msgs']=retValue['error_msgs']\
00469                  +"\nError: Bad region file, 3, was not reported as bad."
00470     
00471 #        _momentTest_debug_msg( 22 )
00472         results = None
00473         results = immoments( 'n1333_both.image', region='garbage.rgn', outfile='input_test_bad_rgn' )
00474         if ( results != None ):
00475             retValue['success']=False
00476             retValue['error_msgs']=retValue['error_msgs']\
00477                  +"\nError: Bad region file, 'garbage.rgn', was not reported as missing."
00478     
00479 #        _momentTest_debug_msg( 23 )
00480         fp=file( 'garbage.rgn', 'w' )
00481         fp.write('This file does NOT contain a valid CASA region specification')
00482         fp.close()
00483         results = None
00484         results = immoments( 'n1333_both.image', region='garbage.rgn', outfile='input_test_bad_rgn' )
00485         if ( results != None ):
00486             retValue['success']=False
00487             retValue['error_msgs']=retValue['error_msgs']\
00488                  +"\nError: Bad region file, 'garbage.rgn', was not reported as bad."
00489 #        _momentTest_debug_msg( 24 )
00490         results=None
00491         try:
00492             results=immoments( 'n1333_both.image', moments=[0], region='n1333_both.image.rgn', outfile='input_test_rgn_1' )
00493         except:
00494             retValue['success']=False
00495             retValue['error_msgs']=retValue['error_msgs']\
00496                        +"\nError: Unable to create moment 0 on n133_both.image with region file n133_both.image.rgn"
00497         if ( not os.path.exists( 'input_test_rgn_1' ) or results == None ):
00498             retValue['success']=False
00499             retValue['error_msgs']=retValue['error_msgs']\
00500                        +"\nError: Moment file, 'input_test_rgn_1', was not created."
00501     
00502         #######################################################################
00503         # Testing BOX parameter
00504         # The input file has pixel values ranging from
00505         #   0-799, 0-799
00506         # Tests include -3, -1, 0, 1 random valid value, 799, 800, 820
00507         #   for both the x, and y coords
00508         #######################################################################
00509         casalog.post( "The BOX parameter tests will cause errors to occur, do not be alarmed", 'WARN' )
00510         
00511 #        _momentTest_debug_msg( 34 )
00512         results = None
00513         results = immoments( 'n1333_both.image', box='-3,0,799,799', outfile='input_test_bad_box' )
00514         if ( results != None and results!=True ):
00515             retValue['success']=False
00516             retValue['error_msgs']=retValue['error_msgs']\
00517                  +"\nError: Bad box value, 'x=-3', was not reported as missing."
00518     
00519 #        _momentTest_debug_msg( 26 )
00520         results = None
00521         results = immoments( 'n1333_both.image', box='0,-3,799,799', outfile='input_test_bad_box' )
00522         if ( results != None ):
00523             retValue['success']=False
00524             retValue['error_msgs']=retValue['error_msgs']\
00525                  +"\nError: Bad box value, 'y=-3', was not reported as missing."
00526     
00527     
00528 #        _momentTest_debug_msg( 27 )
00529         results = None
00530         results = immoments( 'n1333_both.image', box='-2,0,798,798', outfile='input_test_bad_box' )
00531         if ( results!=None or results==True ):
00532             retValue['success']=False
00533             retValue['error_msgs']=retValue['error_msgs']\
00534                  +"\nError: Bad box value, 'x=-2', was not reported."
00535     
00536 #        _momentTest_debug_msg( 28 )
00537         results = None
00538         results = immoments( 'n1333_both.image', box='0,-2,799,799', outfile='input_test_bad_box' )
00539         if ( results != None and results!=True ):
00540             retValue['success']=False
00541             retValue['error_msgs']=retValue['error_msgs']\
00542                  +"\nError: Bad box value, 'y=-2', was not reported as missing."
00543     
00544 #        _momentTest_debug_msg( 29 )
00545         results = None
00546         results = immoments( 'n1333_both.image', box='0,0,800,799', outfile='input_test_bad_box' )
00547         if ( results != None ):
00548             retValue['success']=False
00549             retValue['error_msgs']=retValue['error_msgs']\
00550                  +"\nError: Bad box value, 'x=', was not reported as missing."
00551     
00552 #        _momentTest_debug_msg( 30 )
00553         results = None
00554         results = immoments( 'n1333_both.image', box='0,0,799,800', outfile='input_test_bad_box' )
00555         if ( results != None ):
00556             retValue['success']=False
00557             retValue['error_msgs']=retValue['error_msgs']\
00558                  +"\nError: Bad box value, 'y=800', was not reported as missing."
00559     
00560 #        _momentTest_debug_msg( 31 )
00561         results = None
00562         results = immoments( 'n1333_both.image', box='0, 0,820,799', outfile='input_test_bad_box' )
00563         if ( results != None ):
00564             retValue['success']=False
00565             retValue['error_msgs']=retValue['error_msgs']\
00566                  +"\nError: Bad box value, 'x=820', was not reported as missing."
00567     
00568 #        _momentTest_debug_msg( 32 )
00569         results = None
00570         results = immoments( 'n1333_both.image', box='0,0,799,820', outfile='input_test_bad_box' )
00571         if ( results != None ):
00572             retValue['success']=False
00573             retValue['error_msgs']=retValue['error_msgs']\
00574                  +"\nError: Bad box value, 'y=820', was not reported as missing."
00575     
00576         x1=random.randint(0,799)
00577         x2=random.randint(x1,799)
00578         y1=random.randint(0,799)
00579         y2=random.randint(y1,799)
00580         boxstr=str(x1)+','+str(y1)+','+str(x2)+','+str(y2)
00581 #        _momentTest_debug_msg( 33 )
00582         results = None
00583         try:
00584             results = immoments( 'n1333_both.image', box=boxstr, outfile='input_test_box_1' )
00585         except:
00586             retValue['success']=False
00587             retValue['error_msgs']=retValue['error_msgs']\
00588                        +"\nError: Unable to create moment with box="+boxstr
00589         if ( not os.path.exists( 'input_test_box_1' ) or results == None ):
00590             retValue['success']=False
00591             retValue['error_msgs']=retValue['error_msgs']\
00592                      +"\nError: Moment file, 'input_test_box_1', was not "\
00593                      +"created at "+boxstr
00594     
00595     
00596         #######################################################################
00597         # Testing CHANS parameter: valid values 0-17 for our image
00598         # Values used for testing, -5,-1,0,2~5, 17,18,32
00599         #######################################################################
00600         casalog.post( "The CHANS parameter tests will cause errors to occur, do not be alarmed", 'WARN' )
00601         
00602 #        _momentTest_debug_msg( 34 )
00603         results = None
00604         results = immoments( 'n1333_both.image', chans='-5', outfile='input_test_bad_chans' )
00605         if ( results!=None and results!=True ):
00606             retValue['success']=False
00607             retValue['error_msgs']=retValue['error_msgs']\
00608                  +"\nError: Bad channel value, '-5', was not reported."
00609     
00610 #        _momentTest_debug_msg( 35 )
00611         results = None
00612         results = immoments( 'n1333_both.image', chans='-2', outfile='input_test_bad_chans' )
00613         if ( results!=None and results!=True ):
00614             retValue['success']=False
00615             retValue['error_msgs']=retValue['error_msgs']\
00616                  +"\nError: Bad channel value, '-2', was not reported."\
00617                  +"\n\tRESULTS: "+str(results)
00618     
00619 #        _momentTest_debug_msg( 36 )
00620         results = None
00621         results = immoments( 'n1333_both.image', chans='18', outfile='input_test_bad_chans' )
00622         if ( results!=None and results!=True ):
00623             retValue['success']=False
00624             retValue['error_msgs']=retValue['error_msgs']\
00625                  +"\nError: Bad channel value of -18 was not reported."
00626     
00627 #        _momentTest_debug_msg( 37 )
00628         results = None
00629         results = immoments( 'n1333_both.image', chans='32', outfile='input_test_bad_chans' )
00630         if ( results!=None and results!=True ):
00631             retValue['success']=False
00632             retValue['error_msgs']=retValue['error_msgs']\
00633                  +"\nError: Bad channel value of 32 was not reported."
00634     
00635 #        _momentTest_debug_msg( 38 )
00636         results = None
00637         try:
00638             results = immoments( 'n1333_both.image', chans='0~17', outfile='input_test_chans_1' )
00639         except:
00640             retValue['success']=False
00641             retValue['error_msgs']=retValue['error_msgs']\
00642                        +"\nError: Unable to create moment wit chans=0~17"
00643         if ( not os.path.exists( 'input_test_chans_1' ) or results == None ):
00644             retValue['success']=False
00645             retValue['error_msgs']=retValue['error_msgs']\
00646                      +"\nError: Moment file, 'input_test_chan_1', was not created."
00647     
00648 #        _momentTest_debug_msg( 39 )
00649         results = None
00650         try:
00651             results = immoments( 'n1333_both.image', chans='2~5', outfile='input_test_chans_2' )
00652         except:
00653             retValue['success']=False
00654             retValue['error_msgs']=retValue['error_msgs']\
00655                        +"\nError: Unable to create moment wit chans=2~5"
00656         if ( not os.path.exists( 'input_test_chans_2' ) or results == None ):
00657             retValue['success']=False
00658             retValue['error_msgs']=retValue['error_msgs']\
00659                      +"\nError: Moment file, 'input_test_chan_2', was not created."
00660     
00661             
00662         #######################################################################
00663         # Testing STOKES parameter, valid values: 'I'
00664         #    Tests are 'Q', 'yellow' (invalid) and 'I'
00665         #######################################################################
00666         casalog.post( "The STOKES parameter tests will cause errors to occur, do not be alarmed", 'WARN' )
00667 #        _momentTest_debug_msg( 41 )
00668         results = None
00669         results = immoments( 'n1333_both.image', stokes='Q', outfile='input_test_bad_stokes' )
00670         if ( results!=None and results!=True ):
00671             retValue['success']=False
00672             retValue['error_msgs']=retValue['error_msgs']\
00673                  +"\nError: Bad stokes value, 'Q', was not reported."
00674     
00675 #        _momentTest_debug_msg( 42 )
00676         results = None
00677         results = immoments( 'n1333_both.image', stokes='yellow', outfile='input_test_bad_stokess' )
00678         if ( results!=None and results!=True ):
00679             retValue['success']=False
00680             retValue['error_msgs']=retValue['error_msgs']\
00681                  +"\nError: Bad stokes value, 'yellow', was not reported."
00682     
00683 #        _momentTest_debug_msg( 43 )
00684         results = None
00685         try:
00686             results = immoments( 'n1333_both.image', stokes='I', outfile='input_test_stokes_1' )
00687         except:
00688             retValue['success']=False
00689             retValue['error_msgs']=retValue['error_msgs']\
00690                        +"\nError: Unable to create moment with stokes=Q"
00691         if ( not os.path.exists( 'input_test_stokes_1' ) or results == None ):
00692             retValue['success']=False
00693             retValue['error_msgs']=retValue['error_msgs']\
00694                      +"\nError: Moment file, 'input_test_stokes_1', was not created."\
00695                      +"\n RESULTS: "+str(results)
00696             
00697     
00698         #######################################################################
00699         # Testing MASK parameter:
00700         # There are many, many valid mask values.
00701         # See AIPS++ Note 223
00702         #    http://www.astron.nl/aips++/docs/notes/223/223.html
00703         # The test file n1333 has a mask alread, 'mask0' we will use this
00704         # for testing.
00705         # Invalid tests: 'blarg', 'n1333_both.image:mask1', 'bad_file:mask0'
00706         # Valid tests: n1333_both.image:nomask, n133_both.image:mask0, '<0.5'
00707         #######################################################################
00708         casalog.post( "The MASK parameter tests will cause errors to occur, do not be alarmed", 'WARN' )
00709     
00710 #        _momentTest_debug_msg( 44 )
00711         results = None
00712         results = immoments( 'n1333_both.image', mask='blarg', outfile='input_test_bad_mask' )
00713         if ( results!=None and results!=True ):
00714             retValue['success']=False
00715             retValue['error_msgs']=retValue['error_msgs']\
00716                  +"\nError: Bad mask value, 'blarg', was not reported."
00717     
00718     
00719 #        _momentTest_debug_msg( 45 )
00720         results = None
00721         results = immoments( 'n1333_both.image', mask='n133_both.image:mask1', outfile='input_test_bad_mask' )
00722         if ( results!=None and results!=True ):
00723             retValue['success']=False
00724             retValue['error_msgs']=retValue['error_msgs']\
00725                  +"\nError: Bad mask value, 'n133_both.image:mask1', was not reported."
00726     
00727 #        _momentTest_debug_msg( 46 )
00728         results = None
00729         results = immoments( 'n1333_both.image', mask='bad_files.image:mask', outfile='input_test_bad_mask' )
00730         if ( results!=None and results!=True ):
00731             retValue['success']=False
00732             retValue['error_msgs']=retValue['error_msgs']\
00733                  +"\nError: Bad mask value, 'bad_file.image:mask1', was not reported."
00734     
00735         # COMMENTED OUT BECAUSE THIS FEATURE OF LEL DOESN"T SEEM TO
00736         # WORK
00737 #        _momentTest_debug_msg( 47 )
00738         results = None
00739         #try:
00740         #    results = immoments( 'n1333_both.image', mask='n1333_both.image:nomask', outfile='input_test_mask_1' )
00741         #except:
00742         #    retValue['success']=False
00743         #    retValue['error_msgs']=retValue['error_msgs']\
00744         #               +"\nError: Unable to create moment with mask='nomask'"
00745         #if ( not os.path.exists( 'input_test_mask_1' ) or results == None ):
00746         #    retValue['success']=False
00747         #    retValue['error_msgs']=retValue['error_msgs']\
00748         #             +"\nError: Moment file, 'input_test_mask_1', was not created."\
00749         #             +"\nRESULTS: "+str(results)
00750     
00751 #        _momentTest_debug_msg( 48 )
00752         results = None
00753         try:
00754             results = immoments( 'n1333_both.image', mask='mask(n1333_both.image:mask0)', outfile='input_test_mask_2' )
00755         except:
00756             retValue['success']=False
00757             retValue['error_msgs']=retValue['error_msgs']\
00758                        +"\nError: Unable to create moment with mask='mask0'"
00759         if ( not os.path.exists( 'input_test_mask_2' ) or results == None ):
00760             retValue['success']=False
00761             retValue['error_msgs']=retValue['error_msgs']\
00762                      +"\nError: Moment file, 'input_test_mask_2', was not created."
00763         
00764     
00765         #######################################################################
00766         # Testing includepix parameter: Valid values are a vector of two or
00767         #    1 float values, indicating a single value or a range of values.
00768         #    values in our test image range from -0.04201228 to 0.04867625
00769         # Invalid tests: ['bad']
00770         # Valid test:    [-0.1,0.1], [-6,-5] (this is valid, but creates an
00771         #                                     array of NaNs)
00772         #######################################################################
00773         casalog.post( "The INCLUDEPIX parameter tests will cause errors to occur, do not be alarmed", 'WARN' )
00774     
00775 #        _momentTest_debug_msg( 49 )
00776         results = None
00777         results = immoments( 'n1333_both.image', includepix='bad', outfile='input_test_bad_incpix' )
00778         if ( results ):
00779             retValue['success']=False
00780             retValue['error_msgs']=retValue['error_msgs']\
00781                  +"\nError: Bad includepix value, 'bad', was not reported."
00782     
00783 #        _momentTest_debug_msg( 50 )
00784         results = None
00785         try:
00786             results = immoments( 'n1333_both.image', includepix=[-0.1,0.1], outfile='input_test_incpix_2' )
00787         except:
00788             retValue['success']=False
00789             retValue['error_msgs']=retValue['error_msgs']\
00790                        +"\nError: Unable to create moment with includepix=[-0.1,0.1]"
00791         if ( not os.path.exists( 'input_test_incpix_2' ) or results == None ):
00792             retValue['success']=False
00793             retValue['error_msgs']=retValue['error_msgs']\
00794                      +"\nError: Moment file, 'input_test_incpix_2', was not created."
00795         
00796         
00797     
00798         #######################################################################
00799         # Testing excludepix parameter: Valid values are a vector of two or
00800         #    1 float values, indicating a single value or a range of values.
00801         #    values in our test image range from -0.04201228 to 0.04867625
00802         # Invalid tests: ['badpix']
00803         # Valid test:    [0.1,-0.1], [6,5] (this is valid, but creates an
00804         #                                     array of NaNs)
00805         #######################################################################
00806         casalog.post( "The EXCLUDEPIX parameter tests will cause errors to occur, do not be alarmed", 'WARN' )
00807     
00808 #        _momentTest_debug_msg( 51 )
00809         results = None
00810         results = immoments( 'n1333_both.image', excludepix='badpix', outfile='input_test_bad_expix' )
00811         if ( results ):
00812             retValue['success']=False
00813             retValue['error_msgs']=retValue['error_msgs']\
00814                  +"\nError: Bad excludepix value, 'bad', was not reported."
00815     
00816 #        _momentTest_debug_msg( 52 )
00817         results = None
00818         try:
00819             results = immoments( 'n1333_both.image', excludepix=[0.1,-0.1], outfile='input_test_expix_2' )
00820         except:
00821             retValue['success']=False
00822             retValue['error_msgs']=retValue['error_msgs']\
00823                        +"\nError: Unable to create moment with excludepix=[0.1,-0.1]"
00824         if ( not os.path.exists( 'input_test_expix_2' ) or results == None ):
00825             retValue['success']=False
00826             retValue['error_msgs']=retValue['error_msgs']\
00827                      +"\nError: Moment file, 'input_test_expix_2', was not created."
00828         
00829         #######################################################################
00830         # Testing outfile parameter
00831         # Expects a file containing a region record, as created by the viewer.
00832         # Tests include bad file name (one writing in a read only aread and
00833         # one rewriting on an existing file., and good file.
00834         #######################################################################
00835 #        _momentTest_debug_msg( 53 )
00836         results = None
00837         try:
00838             results = immoments( 'n1333_both.image', outfile='input_test_outfile_1' )
00839         except:
00840             retValue['success']=False
00841             retValue['error_msgs']=retValue['error_msgs']\
00842                        +"\nError: Unable to create moments in file 'input_test_outfile_1'"
00843         if ( not os.path.exists( 'input_test_outfile_1' ) or results == None ):
00844             retValue['success']=False
00845             retValue['error_msgs']=retValue['error_msgs']\
00846                      +"\nError: Moment file, 'input_test_outfile_`', was not created."
00847     
00848         results = None
00849         results = immoments( 'n1333_both.image', outfile='input_test_outfile_1' )
00850         if ( results!=None and results!=True ):
00851             retValue['success']=False
00852             retValue['error_msgs']=retValue['error_msgs']\
00853                  +"\nError: Bad outfile value, 'input_test_outfile_1', was not reported."
00854     
00855     
00856 #        _momentTest_debug_msg( 55 )
00857         results = None
00858         results = immoments( 'n1333_both.image', outfile='/usr/input_test_outfile_2' )
00859         if ( results!=None and results!=True ):
00860             retValue['success']=False
00861             retValue['error_msgs']=retValue['error_msgs']\
00862                  +"\nError: Bad outfile name, '/usr/input_test_outfile_2', was not reported."
00863     
00864         
00865         casalog.post( "Done immoments INPUT/OUTPUT tests.", 'NORMAL2' )
00866         print "RETURNING", retValue
00867         self.assertTrue(retValue['success'],retValue['error_msgs'])
00868 
00869 
00870 class immoment_test2(unittest.TestCase):    
00871 
00872     def setUp(self):
00873         if(os.path.exists(list2[1])):
00874             for file in list2:
00875                 os.system('rm -rf ' +file)
00876         
00877 #        datapath = os.environ.get('CASAPATH').split()[0]+'/data/regression/ngc1333/reference/ngc1333_regression/'
00878         datapath = os.environ.get('CASAPATH').split()[0]+'/data/regression/immoment/'
00879         for file in list2:
00880             os.system('cp -RL ' +datapath + file +' ' + file)
00881 
00882 
00883     def tearDown(self):
00884         for file in list2:
00885             os.system('rm -rf ' +file)
00886             os.system('rm -rf mask_test*')
00887             os.system('rm -rf moment_test*')
00888     
00889     ####################################################################
00890     # Testing calculation of each type of moment
00891     #
00892     # Notes: Size of input image is 800 x 800 (sky pixels), 1 stokes
00893     #        value, 18 channels.
00894     #
00895     # TODO: moments -1, 2-11
00896     ####################################################################
00897     def test_moments(self):
00898         '''Immoment: Testing calculation of each type of moment'''
00899         casalog.post( "Starting MOMENT CALCULATION tests", 'NORMAL2' )
00900         retValue = {'success': True, \
00901                     'msgs': '', \
00902                     'error_msgs': "" }
00903         
00904         # Calculate the "0" moment and compare with previous results
00905         # using imval to check a few data points in the image.
00906         #
00907         # Note: that the images we are comparing with come from the
00908         #       ngc1333_regression.py so when this changes, these
00909         #       test will also need to change.
00910 #        _momentTest_debug_msg( 56 )
00911         results = None
00912         try:
00913             results=immoments( 'n1333_both.image', moments=[0], axis='spec', chans='2~15', includepix=[0.003,100.0],excludepix=[-1],outfile = 'moment_test.mom0' )
00914         except Exception, e:
00915             retValue['success']=False
00916             retValue['error_msgs']=retValue['error_msgs']\
00917                        +"\nError: Unable to very moment 0.\n"\
00918                        + str( e )
00919         else:
00920             if ( not os.path.exists( 'moment_test.mom0' ) or results == None ):
00921                 retValue['success']=False
00922                 retValue['error_msgs']=retValue['error_msgs']\
00923                           +"\nError: Moment file, 'moment_test.mom0', was not created."
00924     
00925         # Output some stats on the moment file created.  Just for
00926         # debugging purposes.  This part could be commented out if
00927         # its felt to be not needed.
00928 #        _momentTest_debug_msg( 57 )
00929         stats = imstat( 'moment_test.mom0' )
00930         casalog.post( str(stats), 'NORMAL3' )
00931     
00932         # Check 1% of the data points in the image to see if
00933         # they match.
00934         err_margin=0.17  # Needs to take into acct. the noise of the image
00935                          # no bigger then the value of 1 sigma on the source.
00936         for i in range( int( (800+800+1+1)*.01 ) ):
00937             x = random.randint( 0, 799 )
00938             y = random.randint( 0, 799 )
00939             sky=str(x)+','+str(y)
00940             stokes = 'I'
00941             chan = 0
00942             current = imval( 'moment_test.mom0', box=sky, stokes=stokes, chans=str(chan) )
00943             orig    = imval( 'n1333_both.src.tmom0.all', box=sky, stokes=stokes, chans=str(chan) )
00944             #print "CURRENT VLUE: ", current
00945             #print "ORIG VaLUE:    ", orig
00946             if ( abs(current['data'][0]-orig['data'][0]) > err_margin ):
00947                 retValue['success']=False
00948                 retValue['error_msgs']=retValue['error_msgs']\
00949                           +"\nError: Moment test 0 values differ at "+str(x)\
00950                           +','+str(y)+',I,0.\nThe values are '+str(current)\
00951                           +" and "+str(orig)
00952     
00953         # Find the residual of the original 0th moment and the one
00954         # we just calculated.  Checking the min/max values to see
00955         # if they are within our error margin.
00956         immath( outfile='moment_test.resid0', expr='"moment_test.mom0"-"n1333_both.src.tmom0.all"' )
00957         resid0_stats=imstat( 'moment_test.resid0' )
00958         resid0_max   = float(resid0_stats['max'][0])
00959         resid0_min   = float(resid0_stats['min'][0])
00960         if ( (resid0_max > 0 and resid0_max > err_margin ) or \
00961              (resid0_min < 0 and resid0_min < (-1*err_margin) ) ):
00962                 retValue['success']=False
00963                 retValue['error_msgs']=retValue['error_msgs']\
00964                           +"\nError: Moment test 0 residual file varies too"\
00965                           +" much. Values range from "\
00966                           +str(float(resid0_stats['min'][0]))+" to "\
00967                           +str(float(resid0_stats['max'][0]))                                                                                     
00968                 
00969         # Calculate the 1st moment and compare with previous results
00970         # using imval to check a few data points in the image.
00971         #
00972 #        _momentTest_debug_msg( 58 )
00973         err_margin=0.95  # Needs to take into acct. the noise of the image
00974                          # no bigger then the value of 1 sigma on the source.
00975         infile = "immoment_image"
00976         expected = "first_moment.im"
00977         got = "moment_test.mom1"
00978         difference = "first_moment_diff"
00979         try:
00980             results=immoments( infile, moments=[1], axis='spec', chans='2~15', includepix=[0.02,100.0],excludepix=[-1],outfile = got )
00981         except Exception, e:
00982             retValue['success']=False
00983             retValue['error_msgs']=retValue['error_msgs']\
00984                        +"\nError: Unable to very moment 1.\n"\
00985                        + str( e )
00986         else:
00987             if ( not os.path.exists( got ) or results == None ):
00988                 retValue['success']=False
00989                 retValue['error_msgs']=retValue['error_msgs']\
00990                           +"\nError: Moment file, " + got + ", was not created."
00991         
00992         immath( outfile=difference, expr='"' + got + '"-"' + expected + '"' )
00993         myia = iatool()
00994         myia.open(difference)
00995         stats = myia.statistics()
00996         myia.close()
00997         casalog.post("moment 1 difference image stats " + str(stats))
00998         if (stats['sumsq'][0] != 0):
00999             retValue['error_msgs'] += "\nError: first moment test did not produce expected image"
01000             retValue['success']=False
01001 
01002         # Cleanup
01003         os.system('rm -rf first_moment_diff')
01004         self.assertTrue(retValue['success'],retValue['error_msgs'])
01005     
01006     ####################################################################
01007     # Testing the correctness of the include/exclude pix parameters
01008     ####################################################################
01009     def test_pixel_set(self):
01010         '''Immoment: Testing the correctness of the include/exclude pix parameters'''
01011         print "starting PIXEL selection tests"
01012         retValue = {'success': True, \
01013                     'msgs': '', \
01014                     'error_msgs': "Pixel selection test NOT implemented yet." }
01015         
01016         self.assertTrue(retValue['success'],retValue['error_msgs'])
01017     
01018     ####################################################################
01019     # Testing the correctness of the region selection with moment calcs.
01020     ####################################################################
01021     def test_region(self):
01022         '''Immoment: Testing the correctness of the region selection with moment calcs'''
01023         print "starting REGION selection tests"
01024         retValue = {'success': True, \
01025                     'msgs': '', \
01026                     'error_msgs': "region selection test NOT implemented yet." }
01027     
01028     
01029         self.assertTrue(retValue['success'],retValue['error_msgs'])
01030     
01031     ####################################################################
01032     # Testing the correctness of mask usage with moment creation
01033     #
01034     # We've already tested valid input and output to the maks
01035     # parameter so we do not duplicate this testing here. In
01036     # this function we are more interested in the correctness of
01037     # the tests, ie. checking the data produced and also testing
01038     # simple to complex mask specifications.
01039     #
01040     # Note: http://www.astron.nl/aips++/docs/notes/223/223.html
01041     #       contains the legal syntax for masks
01042     #
01043     # Test mask is set to and all on n1333_both.image:
01044     #    n1333_both.image:nomask   - use no mask
01045     #    n1333_both.image:mask0    - only mask defined in the image.
01046     #    n1333_both.image>0.1      - all points >0.1
01047     #    test_image>0.1            - all points >0.1 i test image.
01048     #
01049     # TODO create orig images to compare the results too.
01050     #
01051     ####################################################################
01052     def test_mask(self):
01053         '''Immoment: Testing the correctness of mask usage with moment creation'''
01054         casalog.post( "Starting MASK tests", 'NORMAL2' )
01055         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
01056     
01057         results = None
01058         try:
01059             results = immoments( 'n1333_both.image', mask='mask(n1333_both.image:nomask)', outfile='mask_test_1' )
01060         except:
01061             retValue['success']=False
01062     
01063             retValue['error_msgs']=retValue['error_msgs']\
01064                        +"\nError: Unable to create moment 0 with mask set as no mssk'"
01065         if ( not os.path.exists( 'mask_test_1' ) or results == None ):
01066             retValue['success']=False
01067             retValue['error_msgs']=retValue['error_msgs']\
01068                      +"\nError: Mask test failed, 'mask_test_1`', was not created."
01069     
01070     
01071         results = None
01072         try:
01073             results = immoments( 'n1333_both.image', mask='mask(n1333_both.image:mask0)',  outfile='mask_test_2' )
01074         except:
01075             retValue['success']=False
01076             retValue['error_msgs']=retValue['error_msgs']\
01077                        +"\nError: Unable to create moments with mask0'"
01078         if ( not os.path.exists( 'mask_test_2' ) or results == None ):
01079             retValue['success']=False
01080             retValue['error_msgs']=retValue['error_msgs']\
01081                      +"\nError: Mask test failed, 'mask_test_2', was not created."
01082                      
01083     
01084         results = None
01085         try:
01086             results = immoments( 'n1333_both.image', mask='n1333_both.image>0.1', outfile='mask_test_3' )
01087         except:
01088             retValue['success']=False
01089             retValue['error_msgs']=retValue['error_msgs']\
01090                        +"\nError: Unable to create moments with mask-'"
01091         if ( not os.path.exists( 'mask_test_3' ) or results == None ):
01092             retValue['success']=False
01093             retValue['error_msgs']=retValue['error_msgs']\
01094                      +"\nError: Mask test failed, 'mask_test_3', was not created."
01095              
01096             
01097         try:
01098             ia.open( 'n1333_both.image' )
01099             csys=ia.coordsys()
01100             ia.done()
01101             ia.fromshape( 'test.image', shape=[800,800,1,18], csys=csys.torecord(), overwrite=True, log=True )
01102             ia.addnoise()
01103             stats=ia.statistics()
01104             ia.done()
01105             # pick a place that is slightly bigger then the mid value
01106             # range for doing the mask, just for fun.
01107             maskPt=float((stats['max'][0]+stats['min'][0])/2.0)-1.5
01108             maskStr='test.image>'+str(maskPt)
01109                                       
01110             results=None
01111             results = immoments( 'n1333_both.image', mask=maskStr, outfile='mask_test_4' )
01112         except Exception, e:
01113             retValue['success']=False
01114             retValue['error_msgs']=retValue['error_msgs']\
01115                        +"\nError: Unable to create moment with mask from a 2nd file"\
01116                        +"\n"+str(e)
01117         if ( not os.path.exists( 'mask_test_4' ) or results == None ):
01118             retValue['success']=False
01119             retValue['error_msgs']=retValue['error_msgs']\
01120                      +"\nError: Moment file, 'mask_test_4', was not created."
01121     
01122         casalog.post( "Done MASK tests", 'NORMAL2' )
01123         self.assertTrue(retValue['success'],retValue['error_msgs'])
01124     
01125     def test_CAS2943(self):
01126         """Test the stretch parameter"""
01127         myia = iatool()
01128         myia.fromshape("myim.im", [10, 20, 4, 40])
01129         myia.done()
01130         myia.fromshape("mask1.im", [10, 20, 4, 40])
01131         myia.done()
01132         myia.fromshape("mask2.im", [10, 20, 1, 1])
01133         myia.done()
01134         myia.fromshape("mask3.im", [10, 20, 4, 2])
01135         myia.done()
01136         for i in range(4):
01137             outfile = ""
01138             mask = ""
01139             stretch = False
01140             exp = []
01141             atype = True
01142             if (i == 0):
01143                 outfile = "out1.im"
01144                 mask = "mask1.im > 5"
01145                 stretch = False
01146                 exp = [10, 20, 4, 1]
01147                 atype = True
01148             if (i == 1):
01149                 outfile = "out2.im"
01150                 mask="mask2.im > 5"
01151                 stretch=False
01152                 atype = False
01153             if (i == 2):
01154                 outfile = "out3.im"
01155                 mask = "mask2.im > 5"
01156                 stretch = True
01157                 exp = [10, 20, 4, 1]
01158                 atype = True
01159             if (i == 3):
01160                 outfile = "out4.im"
01161                 mask = "mask3.im > 5"
01162                 stretch = False
01163                 atype = False
01164             ret = True
01165             func = ""
01166             for j in [0, 1]:
01167                 if j == 0:
01168                     ret = immoments(
01169                         imagename="myim.im", outfile=outfile,
01170                         mask=mask, stretch=stretch
01171                     )
01172                 if j == 1:
01173                     myia.open("myim.im")
01174                     ret = True
01175                     try:
01176                         myia.moments(
01177                             outfile=outfile, mask=mask,
01178                             stretch=stretch, drop=False
01179                         )
01180                         myia.done()
01181                     except:
01182                         ret = False
01183                 myia.open(outfile)
01184                 if (atype):
01185                     self.assertTrue(myia.shape().tolist() == exp)
01186                 else:
01187                     self.assertFalse(ret)
01188                 myia.done()
01189                 if os.path.exists(outfile):
01190                     shutil.rmtree(outfile)
01191         
01192     def test_CAS_4400(self):
01193         """Verify feature addtion to preconvolve with largest beam when multiple varying beams."""
01194         myia = iatool()
01195         shape = [100, 100, 1, 3]
01196         myia.fromshape("", shape)
01197         myia = myia.subimage("exp", dropdeg=True)
01198         aa = make_gauss2d([shape[0], shape[1]], 10, 10)
01199         for i in range(shape[3]):
01200             myia.putchunk(pixels=aa, blc=[0, 0, i])
01201         myia.setbrightnessunit("Jy/pixel")
01202         moments = [0, 1, 2, 3]
01203         ret = myia.moments(moments=moments, axis=2)
01204         ret.done()
01205         myia.done()
01206         myia.fromshape("", shape)
01207         myia = myia.subimage("got", dropdeg=True)
01208         myia.setbrightnessunit("Jy/beam")
01209         for i in range(shape[3]):
01210             fwhm = 6 + 2*i
01211             aa = make_gauss2d([shape[0], shape[1]], fwhm, fwhm)
01212             myia.putchunk(pixels=aa, blc=[0, 0, i])
01213             f = str(fwhm) + "arcmin"
01214             myia.setrestoringbeam(major=f, minor=f, pa="0deg", channel=i)
01215         ret = myia.moments(moments=moments, axis=2)
01216         ret.done()
01217         myia.done()
01218         got = iatool()
01219         exp = iatool()
01220         mask = iatool()
01221         mask.open("exp")
01222         mask = mask.subimage(
01223             "mymask", region=rg.box(blc=[0, 0, 0], trc=[99, 99,0]),
01224             dropdeg=True
01225         )
01226         cc = mask.getchunk()
01227         for i in range(shape[0]):
01228             for j in range(shape[1]):
01229                 if cc[i,j] < 0.01:
01230                     cc[i,j] = 0
01231                 else:
01232                     cc[i,j] = 1
01233         for im in [
01234             "integrated", "median", "weighted_coord" ,
01235             "weighted_dispersion_coord"
01236         ]:
01237             got.open("Temporary_Image." + im)
01238             exp.open("exp." + im)
01239             shape = got.shape()
01240             gotpix = got.getchunk() * cc
01241             print "min got " + str(gotpix.min())
01242             exppix = exp.getchunk() * cc
01243             print "min exp " + str(exppix.min())
01244             got.done()
01245             exp.done()
01246             if (im == "weighted_dispersion_coord"):
01247                 epsilon = 3e-3
01248             else:
01249                 epsilon = 1e-5
01250             
01251             if (im == "weighted_coord"):                
01252                 mymax = abs((gotpix+1e-6)/(exppix+1e-6) - 1).max()
01253                 print "max " + str(mymax)
01254                 self.assertTrue(mymax < epsilon)
01255             else:
01256                 mymax = abs(gotpix - exppix).max()
01257                 print "max " + str(mymax)
01258                 self.assertTrue(mymax < epsilon)
01259 
01260     def test_CAS4526(self):
01261         """Verify CAS-4526 fix"""
01262         myia = iatool()
01263         myia.fromshape("", [100, 100, 1, 10])
01264         myia.addnoise()
01265         myia.setbrightnessunit("Jy/beam")
01266         for i in range(10):
01267             bmaj = str(4+i) + "arcmin"
01268             bmin = str(3+i) + "arcmin"
01269             bpa = "60deg"
01270             myia.setrestoringbeam(major=bmaj, minor=bmin, pa=bpa, channel=i, polarization=0)
01271         self.assertTrue(myia.moments(moments=[0], axis=3))
01272         self.assertTrue(myia.moments(moments=[0]))
01273 
01274         
01275             
01276 def suite():
01277     return [immoment_test1,immoment_test2]        
01278     
01279