casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
test_immath.py
Go to the documentation of this file.
00001 #######################################################################3
00002 #  immath_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 immath Task
00035 # </summary>
00036 #
00037 # <reviewed reviwer="" date="" tests="" demos="">
00038 # </reviewed
00039 #
00040 # <prerequisite>
00041 # <ul>
00042 #   <li> <linkto class="immath.py:description">immath</linkto> 
00043 # </ul>
00044 # </prerequisite>
00045 #
00046 # <etymology>
00047 # immath_test stands for image math test
00048 # </etymology>
00049 #
00050 # <synopsis>
00051 # immath_test.py is a Python script that tests the correctness
00052 # of the immath task in CASA.
00053 #
00054 # The tests include:
00055 #   ????
00056 #
00057 # In the immath task ????
00058 #
00059 #
00060 #
00061 # </synopsis> 
00062 #
00063 # <example>
00064 # # This test was designed to run in the automated CASA test system.
00065 # # This example shows who to run it manually from with casapy.
00066 # runUnitTest.main(['test_immath'])
00067 #
00068 # or outside casapy like this:
00069 # casapy -c runUnitTest.py test_immath
00070 #
00071 # </example>
00072 #
00073 # <motivation>
00074 # To provide a test standard to the immath task to try and ensure
00075 # coding changes do not break the 
00076 # </motivation>
00077 #
00078 # <todo>
00079 # mode input/output parameter test
00080 # varnames input/output parameter test
00081 # polariziation/spectral mode tests.
00082 # </todo>
00083 ########################################################################3
00084 
00085 import sys
00086 import traceback
00087 import os
00088 import shutil
00089 import random
00090 import time
00091 import casac
00092 import numpy
00093 import glob
00094 import struct
00095 from tasks import *
00096 from taskinit import *
00097 import unittest
00098 
00099 sep = os.sep
00100 datapath=os.environ.get('CASAPATH').split()[0] + sep + 'data' + sep\
00101     + 'regression' + sep + 'unittest' + sep + 'immath' + sep
00102 
00103 cas1452_1_im = 'CAS-1452-1.im'
00104 cas1910_im = 'CAS-1910.im'
00105 cas1830_im = 'ngc5921.demo.cleanimg.image'
00106 n5921im = 'ngc5921.clean.image'
00107 n1333im = 'n1333_both.image'
00108 n1333rgn = 'n1333_both.image.rgn'
00109 c129bcim = '3C129BC.clean.image'
00110 im0im = 'immath0.im'
00111 im1im = 'immath1.im'
00112 im2im = 'immath2.im'
00113 im3im = 'immath3.im'
00114 im4im = 'immath4.im'
00115 im5im = 'immath5.im'
00116 im6im = 'immath6.im'
00117 im7im = 'immath7.im'
00118 im8im = 'immath8.im'
00119 im9im = 'immath9.im'
00120 im10im = 'immath10.im'
00121 
00122 IQU_im = '3C129IQU.im'
00123 IQUV_im = '3C129IQUV.im' 
00124 POLA_im = '3C129_POLA.im'
00125 POLL_im = '3C129_POLL.im'  
00126 POLT_im = '3C129_POLT.im'  
00127 Q_im = '3C129Q.im'
00128 QU_im = '3C129QU.im'
00129 U_im = '3C129U.im'  
00130 UV_im = '3C129UV.im'  
00131 V_im = '3C129V.im'
00132 thresh_mask = '30uJy_thresh_mask.tbl'
00133 
00134 imageList =['ngc5921.clean.image', 'n1333_both.image', 'n1333_both.image.rgn', '3C129BC.clean.image']
00135 
00136 imageList2 =['ngc5921.clean.image', 'n1333_both.image', 'n1333_both.image.rgn', '3C129BC.clean.image',
00137 cas1910_im,cas1452_1_im, cas1830_im]
00138 
00139 imageList3 =['immath0.im', 'immath1.im', 'immath2.im', 'immath3.im', 'immath4.im', 'immath5.im',
00140 'immath6.im', 'immath7.im', 'immath8.im', 'immath9.im','immath10.im']
00141 
00142 imageList4 = [IQU_im, IQUV_im, POLA_im, POLL_im, POLT_im, Q_im, QU_im, U_im, UV_im, V_im, thresh_mask]
00143 
00144 
00145 ################      HELPER FUNCTIONS      ###################
00146 
00147 # Retrieve the pixel value at a particular postion in an image.
00148 def _getPixelValue( imageName, point ):
00149     ia.open( imageName );
00150     retValue = ia.pixelvalue( point );
00151     ia.close();
00152     
00153     if len( retValue ) < 1 :
00154         # Create an exception
00155         msg = str( "Unable to obtain value at: " ) + str(point) + str( " from file " ) + imageName
00156         raise ValueError, str
00157     else:
00158         retValue = retValue['value']['value']
00159 
00160     return retValue
00161 
00162 def _exceptionInfo( maxLevel=5 ):
00163     cla, exc, trbk = sys.exc_info()
00164     excName = cla.__name__
00165     try:
00166         excArgs = exc.__dict__["args"]
00167     except KeyError:
00168         excArgs = "<no args>"
00169     excTb = traceback.format_tb(trbk, maxLevel)
00170     return(excName, excArgs, excTb)
00171 
00172 
00173 ################      THE TESTS         ###################
00174 
00175 
00176 ####################################################################
00177 # Valid/Invalid Input to parameters.  The parameters are:
00178 #    imagename
00179 #    outfile
00180 #    mode
00181 #    mask
00182 #    region
00183 #    box
00184 #    chans
00185 #    stokes
00186 #
00187 # Returns a dictionary contain two keywords as follows:
00188 #        success:     set to True if all tests passed
00189 #        error_msgs:  detailed message(s) of any error(s) that occured.
00190 ####################################################################
00191 
00192 class immath_test1(unittest.TestCase):
00193     
00194     def setUp(self):
00195         if(os.path.exists(imageList[0])):
00196             for img in imageList:
00197                 os.system('rm -rf ' +img)
00198             
00199         for img in imageList:
00200             os.system('cp -RL ' +datapath + img +' ' + img)
00201             
00202 
00203     def tearDown(self):
00204         for img in imageList:
00205             os.system('rm -rf ' +img)
00206             os.system('rm -rf input_test*')
00207                        
00208 
00209     def test_input2(self):
00210         '''Immath 2: Test bad input file'''
00211         #######################################################################
00212         # Testing the imagename parameter.
00213         #    1. Bad file name should throw and exception
00214         #    2. Good file name, a file should be
00215         #    3. List with bad file in it.
00216         #    4. List with good files in it.
00217         #######################################################################
00218         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00219         casalog.post( "The IMAGENAME parameter tests will cause errors to occur, do not be alarmed", 'WARN' )
00220     
00221         result = None
00222         try:
00223             results = immath( 'junk', outfile='input_test1' )
00224         except:
00225             pass
00226         else:
00227             if ( ( results != None and  not isinstance(results, bool) )\
00228                or  results==True ):
00229                 retValue['success']=False
00230                 retValue['error_msgs']=retValue['error_msgs']\
00231                      +"\nError: Badfile, 'junk', was not reported as missing."\
00232                      + "\n RESULTS: "+str(results)
00233 
00234         self.assertTrue(retValue['success'],retValue['error_msgs'])
00235 
00236     def test_input3(self):
00237         '''Immath 3: test good input file'''
00238         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00239         results = None
00240         try:
00241             results = immath( imageList[0], outfile='input_test2', expr='IM0' )
00242         except:
00243             retValue['success']=False
00244             retValue['error_msgs']=retValue['error_msgs']\
00245                     +"\nError: Unable to do math on "+imageList[0]
00246             
00247         if (  not os.path.exists( 'input_test2' ) or results == None ):
00248             retValue['success']=False
00249             retValue['error_msgs']=retValue['error_msgs']\
00250                     +"\nError: outfile 'input_test2' was not created."
00251 
00252         self.assertTrue(retValue['success'],retValue['error_msgs'])
00253 
00254     def test_input4(self):
00255         '''Immath 4: Test bad list of input files'''
00256         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00257         result = None
00258         try:
00259             results = immath( [imageList[0],3,imageList[2]], outfile='input_test3')
00260         except:
00261             pass
00262         else:
00263             if ( ( results != None and  not isinstance(results, bool) )\
00264                or  results==True ):
00265                 retValue['success']=False
00266                 retValue['error_msgs']=retValue['error_msgs']\
00267                      +"\nError: Badfile, '3', was not reported."
00268 
00269         self.assertTrue(retValue['success'],retValue['error_msgs'])
00270 
00271     def test_input5(self):
00272         '''Immath 5: test list with good input files'''
00273         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00274         results=None
00275         try:
00276             results = immath( imageList, outfile='input_test4', expr='IM0' )
00277         except:
00278             retValue['success']=False
00279             retValue['error_msgs']=retValue['error_msgs']\
00280                     +"\nError: Unable to do math on image "+imageList[0]
00281             
00282         if (  not os.path.exists( 'input_test4' ) or results == None ):
00283             retValue['success']=False
00284             retValue['error_msgs']=retValue['error_msgs']\
00285                     +"\nError: 'input_test4' output file was not created."
00286     
00287     
00288         #######################################################################
00289         # Testing the outfile parameter.
00290         #    1. Bad file, file already exists, exception should be thrown
00291         #    2. Non-string value
00292         #    3. Good file name, a file should be
00293         #######################################################################
00294         casalog.post( "The OUTFILE parameter tests will cause errors to occur, do not be alarmed", 'WARN' )
00295     
00296         results = None
00297         try:
00298             results = immath( imageList[0], outfile='input_test4', expr='IM0*1' )
00299         except:
00300             pass
00301         else:
00302             if ( ( results != None and  not isinstance(results, bool) )\
00303                or  results==True ):
00304                 retValue['success']=False
00305                 retValue['error_msgs']=retValue['error_msgs']\
00306                       +"\nError: Bad outfile, 'input_test4', was not reported as already existing."
00307 
00308         self.assertTrue(retValue['success'],retValue['error_msgs'])
00309 
00310 
00311     def test_input7(self):
00312         '''Immath 7: test outfile'''
00313         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00314         results = None
00315         try:
00316             results = immath( imageList[0], outfile='input_test5', expr='IM0*1' )
00317         except:
00318             retValue['success']=False
00319             retValue['error_msgs']=retValue['error_msgs']\
00320                        +"\nError: Unable to create image 'input_test5'"
00321         if ( not os.path.exists( 'input_test5' ) or results == None ):
00322             retValue['success']=False
00323             retValue['error_msgs']=retValue['error_msgs']\
00324                        +"\nError: output file, 'input_test5', was not created."
00325 
00326         self.assertTrue(retValue['success'],retValue['error_msgs'])
00327     
00328         #######################################################################
00329         # Testing the mode parameter.
00330         #    TODO
00331         #    Valid modes are: evalexpr, spix, pola, poli
00332         #    Invalid ???
00333         #######################################################################
00334     
00335     
00336     
00337         
00338     def test_input8(self):
00339         '''Immath 8: Test bad region parameter'''
00340         #######################################################################
00341         # Testing REGION parameter
00342         # Expects a file containing a region record, as created by the viewer.
00343         # Tests include bad file name, file with bad content, and good file.
00344         ####################################################################### 
00345         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00346         casalog.post( "The REGION parameter tests will cause errors to occur, do not be alarmed", 'WARN' )
00347 
00348         # First remove the default results file
00349         try:
00350             shutil.rmtree( 'immath_results.im' )
00351         except:
00352             pass
00353         
00354         results=None    
00355         try:
00356             results = immath( imageList[1], region='garbage.rgn' )
00357         except:
00358             #We want this to fail
00359             pass
00360         else:
00361             if ( ( results != None and  not isinstance(results, bool) )\
00362                or  results==True ):
00363                 retValue['success']=False
00364                 retValue['error_msgs']=retValue['error_msgs']\
00365                               +"\nError: Bad region file, 'garbage.rgn', was not reported as missing."+"\nREsults: "+str(results)
00366     
00367         try:
00368             filename = os.getcwd() + sep + 'garbage.rgn'
00369             fp=open( filename, 'w' )
00370             fp.writelines('This file does NOT contain a valid CASA region specification\n')
00371             fp.close()
00372     
00373             results=None
00374             # First remove the default results file
00375             try:
00376                 shutil.rmtree( 'immath_results.im' )
00377             except:
00378                 pass        
00379             try:
00380                 results = immath( imageList[1], region=filename )
00381             except:
00382                 pass
00383             else:
00384                 if ( ( results != None and not isinstance(results, bool) )\
00385                        or results==True ):
00386                     retValue['success']=False
00387                     retValue['error_msgs']=retValue['error_msgs']\
00388                               + "\nError: Bad region file, 'garbage.rgn',"\
00389                               + " was not reported as bad."+str(results)
00390         except Exception, err:
00391             retValue['success']=False
00392             retValue['error_msgs']=retValue['error_msgs']\
00393                      +"\nError: Unable to create bad region file.\n\t"
00394             raise Exception, err
00395 
00396         self.assertTrue(retValue['success'],retValue['error_msgs'])
00397     
00398     def test_input9(self):
00399         '''Immath 9: Test good region parameter'''
00400         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00401         results = None
00402         print "ARG"
00403         print "immath( imagename="+imageList[1]+", expr='IM0', "\
00404                         +"region="+imageList[2]+", outfile='input_test12' )"
00405         try:
00406             rec = rg.fromfiletorecord(imageList[2])
00407             results=immath( imagename=imageList[1], expr='IM0', \
00408                         region=imageList[2], outfile='input_test12' )
00409         except:
00410             retValue['success']=False
00411             retValue['error_msgs']=retValue['error_msgs']\
00412                  +"\nError: Unable to do math with region file "+imageList[1]
00413             
00414         if ( not os.path.exists('input_test12') or results==None or results==False ):
00415             retValue['success']=False
00416             retValue['error_msgs']=retValue['error_msgs']\
00417                   +"\nError: output file 'input_test12', was not created."\
00418                   +"\n  RESULTS "+str(results)
00419     
00420         self.assertTrue(retValue['success'],retValue['error_msgs'])            
00421     
00422     def test_input10(self):
00423         '''Immath 10: Test bad x and y box values'''
00424         #######################################################################
00425         # Testing BOX parameter
00426         # The input, imageList[0]=ngc5921.clean.image, file has pixel
00427         # values ranging from:
00428         #   0-255, 0-255
00429         # Tests include -3, -1, 0, 1 random valid value, 254, 255, 256
00430         #   for both the x, and y coords
00431         #
00432         # Note: -1 is a special case implying use the full range, so to
00433         #       be out of bounds we need -2 or less.
00434         #######################################################################
00435         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00436         casalog.post( "The BOX parameter tests will cause errors to occur, do not be alarmed", 'WARN' )
00437         
00438         results = None
00439         # First remove the default results file
00440         try:
00441             shutil.rmtree( 'immath_results.im' )
00442         except:
00443             pass    
00444         try:
00445             results = immath( imageList[0], box='-3,0,254,254', expr='IM0' )
00446         except:
00447             pass
00448         else:
00449             if ( results != None and  not ( isinstance(results, bool) )\
00450                  or results==True ):
00451                 retValue['success']=False
00452                 retValue['error_msgs']=retValue['error_msgs']\
00453                      +"\nError: Bad box value, 'x=-3', was not reported as bad."
00454     
00455         results = None
00456         # First remove the default results file
00457         try:
00458             shutil.rmtree( 'immath_results.im' )
00459         except:
00460             pass
00461         try:
00462             results = immath( imageList[0], box='0,-3,254,254', expr='IM0' )
00463         except:
00464             pass
00465         else:
00466             if ( results != None and  not ( isinstance(results, bool) ) \
00467                  or results==True ):
00468                 retValue['success']=False
00469                 retValue['error_msgs']=retValue['error_msgs']\
00470                      +"\nError: Bad box value, 'y=-3', was not reported as bad."
00471     
00472         results = None
00473         # First remove the default results file
00474         try:
00475             shutil.rmtree( 'immath_results.im' )
00476         except:
00477             pass
00478         try:
00479             results = immath( imageList[0], box='-2,0,254,254', expr='IM0' )
00480         except:
00481             pass
00482         else:
00483             if ( results != None and  not ( isinstance(results, bool) ) \
00484                  or results==True ):
00485                 retValue['success']=False
00486                 retValue['error_msgs']=retValue['error_msgs']\
00487                      +"\nError: Bad box value, 'x=-2', was not reported."\
00488                      +"\n\tRESULTS: "+str(results)
00489     
00490         results = None
00491         # First remove the default results file
00492         try:
00493             shutil.rmtree( 'immath_results.im' )
00494         except:
00495             pass    
00496         try:
00497             results = immath( imageList[0], box='0,-2,254,254', expr='IM0' )
00498         except:
00499             pass
00500         else:
00501             if ( results != None and  not ( isinstance(results, bool) ) \
00502                  or results==True ):
00503                 retValue['success']=False
00504                 retValue['error_msgs']=retValue['error_msgs']\
00505                      +"\nError: Bad box value, 'y=-2', was not reported as bad."
00506 
00507 
00508         results = None
00509         # First remove the default results file
00510         try:
00511             shutil.rmtree( 'immath_results.im' )
00512         except:
00513             pass    
00514         try:
00515             results = immath( imageList[0], box='0,0,256,254', expr='IM0' )
00516         except:
00517             pass
00518         else:
00519             if ( results != None and  not ( isinstance(results, bool) ) \
00520                  or results==True ):
00521                 retValue['success']=False
00522                 retValue['error_msgs']=retValue['error_msgs']\
00523                    +"\nError: Bad box value, 'x=256', was not reported as bad."
00524     
00525         results = None
00526         # First remove the default results file
00527         try:
00528             shutil.rmtree( 'immath_results.im' )
00529         except:
00530             pass    
00531         try:
00532             results = immath( imageList[0], box='0,0,254,256', expr='IM0' )
00533         except:
00534             pass
00535         else:
00536             if ( results != None and  not ( isinstance(results, bool) ) \
00537                  or results==True ):
00538                 retValue['success']=False
00539                 retValue['error_msgs']=retValue['error_msgs']\
00540                     +"\nError: Bad box value, 'y=256', was not reported as bad."
00541 
00542 
00543         results = None
00544         # First remove the default results file
00545         try:
00546             shutil.rmtree( 'immath_results.im' )
00547         except:
00548             pass    
00549         try:
00550             results = immath( imageList[0], box='0, 0,266,200', expr='IM0' )
00551         except:
00552             pass
00553         else:
00554             if ( results != None and not ( isinstance(results, bool) )
00555                  or results==True ):
00556                 retValue['success']=False
00557                 retValue['error_msgs']=retValue['error_msgs']\
00558                     +"\nError: Bad box value, 'x=266', was not reported as bad."
00559     
00560     
00561         results = None
00562         # First remove the default results file
00563         try:
00564             shutil.rmtree( 'immath_results.im' )
00565         except:
00566             pass    
00567         try:
00568             results = immath( imageList[0], box='0,0,254,266', expr='IM0' )
00569         except:
00570             pass
00571         else:
00572             if ( results != None and  not ( isinstance(results, bool) ) \
00573                  or results==True ):
00574                 retValue['success']=False
00575                 retValue['error_msgs']=retValue['error_msgs']\
00576                     +"\nError: Bad box value, 'y=266', was not reported as bad."
00577     
00578         self.assertTrue(retValue['success'],retValue['error_msgs'])
00579 
00580     def test_input12(self):
00581         '''Immath 12: Test bad values of channels'''
00582         #######################################################################
00583         # Testing CHANS parameter: valid values 0-39 for our image
00584         # Values used for testing, -5,-2,0,22~35, 44,45,46
00585         #
00586         # NOTE: a coord value of -1 indicates use all, so -1 is a valid
00587         #       coordinate.
00588         #######################################################################
00589         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00590         casalog.post( "The CHANS parameter tests will cause errors to occur, do not be alarmed", 'WARN' )
00591         
00592         results = None
00593         # First remove the default results file
00594         try:
00595             shutil.rmtree( 'immath_results.im' )
00596         except:
00597             pass    
00598         try: 
00599             results = immath( imageList[0], chans='-5', expr='IM0' )
00600         except:
00601             pass
00602         else:
00603             if ( results != None and  not ( isinstance(results, bool) ) \
00604                  or results==True ):
00605                 retValue['success']=False
00606                 retValue['error_msgs']=retValue['error_msgs']\
00607                      +"\nError: Bad channel value, '-5', was not reported."
00608     
00609         results = None
00610         # First remove the default results file
00611         try:
00612             shutil.rmtree( 'immath_results.im' )
00613         except:
00614             pass    
00615         try:
00616             results = immath( imageList[0], chans='-2', expr='IM0' )
00617         except:
00618             pass
00619         else:
00620             if ( results != None and  not ( isinstance(results, bool) ) \
00621                  or results==True ):
00622                 retValue['success']=False
00623                 retValue['error_msgs']=retValue['error_msgs']\
00624                        +"\nError: Bad channel value, '-2', was not reported."\
00625                        +"\n\tRESULTS: "+str(results)
00626     
00627         results = None
00628         # First remove the default results file
00629         try:
00630             shutil.rmtree( 'immath_results.im' )
00631         except:
00632             pass    
00633         try:
00634             results = immath( imageList[0], chans='-18', expr='IM0' )
00635         except:
00636             pass
00637         else:
00638             if ( results != None and  not ( isinstance(results, bool) ) \
00639                  or results==True ):
00640                 retValue['success']=False
00641                 retValue['error_msgs']=retValue['error_msgs']\
00642                         +"\nError: Bad channel value of -18 was not reported."
00643     
00644         results = None
00645         # First remove the default results file
00646         try:
00647             shutil.rmtree( 'immath_results.im' )
00648         except:
00649             pass
00650         try:
00651             results = immath( imageList[0], chans='47', expr='IM0' )
00652         except:
00653             pass
00654         else:
00655             if ( results != None and  not ( isinstance(results, bool) ) \
00656                  or results==True ):
00657                 retValue['success']=False
00658                 retValue['error_msgs']=retValue['error_msgs']\
00659                         +"\nError: Bad channel value of 47 was not reported."
00660     
00661         results = None
00662         # First remove the default results file
00663         try:
00664             shutil.rmtree( 'immath_results.im' )
00665         except:
00666             pass    
00667         try:
00668             results = immath( imageList[0], chans='46', expr='IM0' )
00669         except:
00670             pass
00671         else:
00672             if ( results != None and  not ( isinstance(results, bool) ) \
00673                  or results==True ):
00674                 retValue['success']=False
00675                 retValue['error_msgs']=retValue['error_msgs']\
00676                          +"\nError: Bad channel value of 46 was not reported."
00677 
00678         self.assertTrue(retValue['success'],retValue['error_msgs'])
00679 
00680     def test_input13(self):
00681         '''Immath 12: Test selection of channels'''
00682         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00683         results = None            
00684         try:
00685             print "immath( imagename="+imageList[0]+", varnames='A', expr='A', chans='22~35', outfile='input_test14' )"
00686             results = immath( imagename=imageList[0], chans='22~35', expr='A', varnames='A', outfile='input_test14' )
00687         except:
00688             retValue['success']=False
00689             retValue['error_msgs']=retValue['error_msgs']\
00690                        +"\nError: Unable to do image math on chans=22~35 only "
00691         if ( not os.path.exists( 'input_test14' ) or results==None or results==False ): 
00692             retValue['success']=False
00693             retValue['error_msgs']=retValue['error_msgs']\
00694                      +"\nError: output file, 'input_test14', was not created."\
00695                      +"\n\tResults: "+str(results)
00696         
00697         results = None
00698         try:
00699             results = immath( imageList[0], expr='IM0', chans='0', outfile='input_test15' )
00700         except:
00701             retValue['success']=False
00702             retValue['error_msgs']=retValue['error_msgs']\
00703                        +"\nError: Unable to do image math with chans=0 only"
00704         if ( not os.path.exists( 'input_test15' ) or results==None or results==False ): 
00705             retValue['success']=False
00706             retValue['error_msgs']=retValue['error_msgs']\
00707                      +"\nError: output file 'input_test15`' was not created."\
00708                      +"\nRESULT: "+str(results)
00709     
00710         results=None
00711         try:
00712             results = immath( imageList[0], chans='39', expr='IM0', outfile='input_test16' )
00713         except:
00714             retValue['success']=False
00715             retValue['error_msgs']=retValue['error_msgs']\
00716                        +"\nError: Unable to do image math with chans=39 only"
00717         if ( not os.path.exists( 'input_test16' ) or results==None or results==False ): 
00718             retValue['success']=False
00719             retValue['error_msgs']=retValue['error_msgs']\
00720                      +"\nError: output file 'input_test16' was not created."
00721 
00722         self.assertTrue(retValue['success'],retValue['error_msgs'])    
00723 
00724     def test_input14(self):
00725         '''Immath 13: Test STOKES parameter, values: I, Q, yellow'''
00726         #######################################################################
00727         # Testing STOKES parameter, valid values: 'I'
00728         #    Tests are 'Q', 'yellow' (invalid) and 'I'
00729         #######################################################################
00730         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00731         casalog.post( "The STOKES parameter tests will cause errors to occur, do not be alarmed", 'WARN' )
00732         
00733         results=None
00734         # First remove the default results file
00735         try:
00736             shutil.rmtree( 'immath_results.im' )
00737         except:
00738             pass    
00739         try:
00740             results = immath( imageList[0], stokes='Q', expr='IM0' )
00741         except:
00742             pass
00743         else:
00744             if ( results != None and  not ( isinstance(results, bool) ) \
00745                  or results==True ):
00746                 retValue['success']=False
00747                 retValue['error_msgs']=retValue['error_msgs']\
00748                        +"\nError: Bad stokes value, 'Q', was not reported."
00749                 
00750         results=None
00751         # First remove the default results file
00752         try:
00753             shutil.rmtree( 'immath_results.im' )
00754         except:
00755             pass    
00756         try:
00757             results = immath( imageList[0], stokes='yellow', expr='IM0' )
00758         except:
00759             pass
00760         else:
00761             if ( results != None and  not ( isinstance(results, bool) ) \
00762                  or results==True ):
00763                 retValue['success']=False
00764                 retValue['error_msgs']=retValue['error_msgs']\
00765                      +"\nError: Bad stokes value, 'yellow', was not reported."
00766     
00767         results = None
00768         try:
00769             results = immath( imageList[0], stokes='I', outfile='input_test17', expr='IM0' )
00770         except:
00771             retValue['success']=False
00772             retValue['error_msgs']=retValue['error_msgs']\
00773                        +"\nError: Image math failed with stokes=I"
00774         if ( not os.path.exists( 'input_test17' ) or results==None or results==False ):
00775             retValue['success']=False
00776             retValue['error_msgs']=retValue['error_msgs']\
00777                      +"\nError: output file 'input_test17' was not created."
00778     
00779     
00780         self.assertTrue(retValue['success'],retValue['error_msgs'])    
00781     
00782 
00783 class immath_test2(unittest.TestCase):   
00784 
00785     def setUp(self):
00786         if(os.path.exists(imageList2[0])):
00787             for img in imageList2:
00788                 shutil.rmtree(img)
00789                 
00790         # FIXME: add links to repository
00791         for img in imageList2:
00792             if os.path.isdir(datapath + img):
00793                 shutil.copytree(datapath + img, img)
00794             else:
00795                 shutil.copy(datapath + img, img)
00796 
00797 
00798     def tearDown(self):
00799         for img in imageList2:
00800             if os.path.isdir(img):
00801                 shutil.rmtree(img)
00802             else:
00803                 os.remove(img)
00804         for img in glob.glob("pol_test*"):
00805             if os.path.isdir(img):
00806                 shutil.rmtree(img)
00807             else:
00808                 os.remove(img)
00809                        
00810     def copy_img(self):
00811         '''Copy images to local disk'''
00812         for img in imageList3:
00813             os.system('cp -r ' +datapath + img +' ' + img)
00814 
00815     def rm_img(self):
00816         '''Remove images from disk'''
00817         for img in imageList3:
00818             os.system('rm -rf ' +img)
00819         
00820     ####################################################################
00821     # Testing various math expression.
00822     #
00823     # These tests use ngc5921 which is 256x256x1x46
00824     #
00825     # Returns a dictionary contain two keywords as follows:
00826     #        success:     set to True if all tests passed
00827     #        error_msgs:  detailed message(s) of any error(s) that occured.
00828     ####################################################################
00829     def test_expr1(self):
00830         '''Immath expr1: Testing various math expressions'''
00831         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00832         casalog.post( "Starting immath INPUT/OUTPUT tests.", 'NORMAL2' )            
00833         
00834         ################        TEST 1          ###################
00835         # Test to see if all the points of a single image are doubled.
00836         # Note that we a few values from the input and output images to see
00837         # if we truly doubled each value.
00838     
00839         casalog.post( "Testing the doubling of every value in an image.", 'NORMAL2' )
00840         results=None
00841         try:
00842             results=immath( imagename=imageList2[0], outfile='expr_test1', expr='IM0 * 2' );
00843         except Exception, e:
00844             casalog.post( "Exception occured doubling image ... "+str(e), 'DEBUG1')
00845             retValue['success']=False
00846             retValue['error_msgs']=retValue['error_msgs']\
00847                      +'\nError: Failed to create "doubled image" on '+imageList2[0]
00848             
00849         if (  not os.path.exists( 'expr_test1' ) or results == None ):
00850             retValue['success']=False
00851             retValue['error_msgs']=retValue['error_msgs']\
00852                     +"\nError: outfile 'expr_test1' was not created."
00853         else:
00854             myia = iatool()
00855             myia.open(imageList2[0])
00856             expected = 2*myia.getchunk()
00857             myia.done()
00858             myia.open("expr_test1")
00859             got = myia.getchunk()
00860             myia.done()
00861             self.assertTrue((expected == got).all(), "got not equal to expected for doubling pixel values")
00862             
00863 
00864         self.assertTrue(retValue['success'],retValue['error_msgs'])
00865                 
00866 
00867     def test_expr2(self):
00868         '''Immath expr2: Test extraction of single plane'''
00869         ################        TEST 2          ###################
00870         # Test to see if we can grab a single plane out of the image.
00871         # Then use this single plane and add it to the whole image.
00872         # In this case we want the plane at channel 5.  NOTE: We can't
00873         # do this with LEL at the moment, but will be able to in the
00874         # future.  The commented out immath() calls use LEL
00875         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00876         casalog.post( "**** Testing extraction of a single plane.", 'NORMAL2' )
00877     
00878         # First test that we can extract a plane from the bigger image.
00879         # Checking the size of the resulting image and a few of the
00880         # points to make sure they are from the correct plane.
00881         outimage='expr_test2'
00882         results=None
00883         try:    
00884             results=immath( imagename=imageList2[0], outfile=outimage, \
00885                          expr='IM0', chans='5',  );
00886             #immath( outimage, 'evalexpr', str('"')+image1+str('"[INDEXIN(4,[5])]' ) );
00887         except Exception, e:
00888             casalog.post( "Exception occured getting image slice ... "+str(e), 'DEBUG1')        
00889             retValue['success']=False
00890             retValue['error_msgs']=retValue['error_msgs']\
00891                      +'\nError: Failed to create image" slice on '+imageList2[0]
00892             
00893         if (  not os.path.exists( outimage ) or results == None ):
00894             retValue['success']=False
00895             retValue['error_msgs']=retValue['error_msgs']\
00896                     +"\nError: outfile '"+outimage+"' was not created."
00897         else:
00898             # Verify the size of the output image, and check to make sure
00899             # the values are copied over correctly
00900             ia.open( outimage );
00901             size = ia.shape();
00902             ia.close()
00903             if ( len(size) < 4 or size[0]!=256 or size[1]!=256 or \
00904                     size[2]!=1 or size[3]!=1 ):
00905                 retValue['success']=False
00906                 retValue['error_msgs']=retValue['error_msgs']\
00907                        +'\nError: Size of subimage is incorrect: '\
00908                        + size + ".\nExpected the resulting image to"\
00909                        + "be 256x256x1x1 pixels."
00910             else:
00911                 myia = iatool()
00912                 myia.open(imageList2[0])
00913                 expected = myia.getchunk()[:,:,:,5:5]
00914                 myia.done()
00915                 myia.open(outimage)
00916                 got = myia.getchunk()
00917                 myia.done()
00918                 self.assertTrue((got == expected).all()) 
00919                 
00920         self.assertTrue(retValue['success'],retValue['error_msgs'])
00921     
00922     def test_expr3(self):
00923         '''Immath expr3: Add plane to an image'''
00924         # We know how to make a subimage so now lets actually add this plane
00925         # to the whole image.
00926         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00927         casalog.post( "Adding slice to a cube image.", 'NORMAL2' )
00928         outimage="expr_test3"
00929     
00930         results=None
00931         try:
00932             results = immath( mode='evalexpr', outfile=outimage,  \
00933                     imagename=[ 'expr_test2', imageList2[0] ], \
00934                     expr='IM0+IM1' )
00935         except Exception, e:
00936             casalog.post( "Exception occured getting image slice ... "+str(e), 'DEBUG1')
00937             retValue['success']=False
00938             retValue['error_msgs']=retValue['error_msgs']\
00939                +"\nError: Unable to add a image slice to an image cube."
00940     
00941     
00942         if (  not os.path.exists( outimage ) or results == None ):
00943             retValue['success']=False
00944             retValue['error_msgs']=retValue['error_msgs']\
00945                     +"\nError: outfile '"+outimage+"' was not created."
00946         else:
00947             # Now do some value checks
00948             # of these images and from that get their sizes with the topixel
00949             # function, however, we are assuming that its a 256x256x1x46 image.
00950             size=[]
00951             try:
00952                 ia.open( outimage )
00953                 size=ia.shape()
00954                 ia.close()
00955             except Exception, e:
00956                 casalog.post( "Expception occured getting image shape ... "+str(e), 'DEBUG1')
00957                 retValue['success']=False
00958                 retValue['error_msgs']=retValue['error_msgs']\
00959                         +"\nError: Unable to get shape of image "+outimage
00960             
00961             if ( not (size == [256, 256, 1, 46]).all()):
00962                 retValue['success']=False
00963                 retValue['error_msgs']=retValue['error_msgs']\
00964                       +"\nError: Size of output plane is incorrect: "+str(size)\
00965                       +"\n       Excepted a shape of 256x256x1x46"
00966             else:
00967                 myia = iatool()
00968                 myia.open("expr_test2")
00969                 chunk1 = myia.getchunk()
00970                 myia.done()
00971                 myia.open(imageList2[0])
00972                 chunk2 = myia.getchunk()
00973                 myia.done()
00974                 expected = chunk1 + chunk2
00975                 myia.open(outimage)
00976                 got = myia.getchunk()
00977                 myia.done()
00978                 self.assertTrue((got - expected < 0.000001 ).all())
00979 
00980         self.assertTrue(retValue['success'],retValue['error_msgs'])
00981     
00982     
00983     ####################################################################
00984     # Testing various the various polarization modes for data
00985     # correctness.
00986     #
00987     # The 3C129 test set has 4 polarizations and is great for
00988     # testing this one.
00989     #
00990     #
00991     # Returns a dictionary contain two keywords as follows:
00992     #        success:     set to True if all tests passed
00993     #        error_msgs:  detailed message(s) of any error(s) that occured.
00994     ####################################################################
00995     def test_pol(self):
00996         '''Immath pol: Testing various polarization modes for data correctness'''
00997         success = True
00998         errors = ''
00999     #    retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
01000         casalog.post( "Starting immath INPUT/OUTPUT tests.", 'NORMAL2' )
01001     
01002         # First make the I, Q, U, and V files.  This step may not be
01003         # needed if immath learns to do this for the user.
01004         immath( imageList2[3], expr='IM0', stokes='I', outfile='pol_test_I.im' )
01005         immath( imageList2[3], expr='IM0', stokes='Q', outfile='pol_test_Q.im' )
01006         immath( imageList2[3], expr='IM0', stokes='U', outfile='pol_test_U.im' )
01007         immath( imageList2[3], expr='IM0', stokes='V', outfile='pol_test_V.im' )
01008     
01009         imList = ['pol_test_Q.im', 'pol_test_U.im', 'pol_test_V.im']
01010         myia = iatool()
01011         # total polarization intensity
01012         outfile = 'pol_test1'
01013         self.assertTrue(immath( imagename=imList, outfile=outfile, mode='poli' ))
01014         myia.open(outfile)
01015         self.assertTrue(myia.coordsys().stokes()[0] == 'Ptotal')
01016         myia.done()
01017         
01018         # linear polarization intensity
01019         outfile = 'linear_pol_intensity_test'
01020         self.assertTrue(immath(imagename=imList[0:2], outfile=outfile, mode='poli' ))
01021         myia.open(outfile)
01022         self.assertTrue(myia.coordsys().stokes()[0] == 'Plinear')
01023         myia.done()
01024         
01025         imList = ['pol_test_Q.im', 'pol_test_U.im']
01026         self.assertTrue(immath( imagename=imList, outfile='pol_test2', mode='pola' ))
01027  
01028     # verification of fix to CAS-1678
01029     # https://bugs.aoc.nrao.edu/browse/CAS-1678
01030     def test_many_images(self):
01031         '''Immath: verification of fix to CAS-1678'''
01032         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
01033         casalog.post( "Starting immath many (>9) image test.", 'NORMAL2' )
01034     
01035         self.copy_img()
01036         imagename = [
01037             'immath0.im', 'immath1.im', 'immath2.im', 'immath3.im', 'immath4.im', 'immath5.im',
01038             'immath6.im', 'immath7.im', 'immath8.im', 'immath9.im','immath10.im'
01039         ]
01040         expr = 'IM0+IM1+IM2+IM3+IM4+IM5+IM6+IM7+IM8+IM9+IM10'
01041         myia = iatool()
01042         try:
01043             # full image test
01044             outfile = 'full_image_sum.im'
01045             if (immath(imagename=imagename, expr=expr, outfile=outfile)):
01046                 expected = numpy.ndarray([2,2])
01047                 expected.put(range(expected.size),66)
01048                 myia.open(outfile)
01049                 got = myia.getchunk()
01050                 myia.done()
01051                 if (not (got == expected).all()):
01052                     retValue['success'] = False
01053                     retValue['error_msgs'] += "\n Full image sum not correctly calculated"
01054             else:
01055                 retValue['success'] = False
01056                 retValue['error_msgs'] += "\nimmath returned False for full image sum"            
01057         except:
01058             retValue['success'] = False
01059             retValue['error_msgs'] += "\nFull image calculation threw an exception: " + str(sys.exc_info()[0])
01060     
01061         shutil.rmtree(outfile)        
01062         try:
01063             # subimage image test
01064             outfile = 'subimage_sum.im'
01065             if (immath(imagename=imagename, expr=expr, outfile=outfile, box='0,0,0,0')):
01066                 expected = numpy.ndarray([1,1])
01067                 expected.put(range(expected.size), 66)
01068                 myia.open(outfile)
01069                 got = myia.getchunk()
01070                 myia.done()
01071                 if (not (got == expected).all()):
01072                     retValue['success'] = False
01073                     retValue['error_msgs'] += "\n sub image sum not correctly calculated"
01074             else:
01075                 retValue['success'] = False
01076                 retValue['error_msgs'] += "\nimmath returned False for sub image sum: " + str(sys.exc_info()[0])
01077         except:
01078             retValue['success'] = False
01079             retValue['error_msgs'] += "\nSub image calculation threw an exception"
01080 
01081         self.rm_img()
01082         shutil.rmtree(outfile)
01083         self.assertTrue(retValue['success'],retValue['error_msgs'])
01084     
01085     
01086     # fixed setting trc brokenness with a kludge (as, given the state of the pre-existing code, was the best that could be done)
01087     def test_CAS_1910_fix(self):
01088         '''Immath: verification of fix to CAS-1910'''
01089         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
01090         try:
01091     
01092             if (
01093                 not immath(
01094                     imagename=cas1910_im, outfile='cas-1910_out.im',
01095                     mode='evalexpr', expr='IM0*1',
01096                     box='708,1158,1006,1456'
01097                 )
01098             ):
01099                 retValue['success'] = False
01100                 retValue['error_msgs'] += "\nimmath returned False for setting box correctly (CAS-1910)"
01101         except:
01102             retValue['success'] = False
01103             retValue['error_msgs'] += "\nimmath threw exception for setting box correctly (CAS-1910)"
01104 
01105         self.assertTrue(retValue['success'],retValue['error_msgs'])
01106     
01107     # cas-1452
01108     def test_one_function(self):
01109         '''Immath: verification of fix to CAS-1452'''
01110         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
01111         funcs = ['sin', 'SIN', 'Sin']
01112         imagename = cas1452_1_im
01113         ia.open(imagename)
01114         expected = numpy.sin(ia.getchunk())
01115         ia.close()
01116         #try:
01117         for f in funcs:
01118             try:
01119                 shutil.rmtree('cas-1452_out_' + f + '.im')
01120             except:
01121                 pass
01122             
01123             outfile = 'cas-1452_out_' + f + '.im'
01124             expr = f + "(\'" + imagename + "\')" 
01125             self.assertTrue(
01126                 immath(
01127                     imagename=imagename, outfile=outfile,
01128                     mode='evalexpr', expr=expr
01129                 )
01130             )
01131             ia.open(outfile)
01132             got = ia.getchunk()
01133             ia.close()
01134             maxdiff = numpy.abs(got - expected).max()
01135             self.assertTrue( maxdiff <= 1e-7)
01136             os.system('rm -rf ' + outfile)
01137     
01138         #except:
01139         #    retValue['success'] = False
01140         #    retValue['error_msgs'] += "\nimmath threw exception for " + f + " calculation"
01141         self.assertTrue(retValue['success'],retValue['error_msgs'])
01142     
01143     def test_CAS_1830_fix(self):
01144         '''Immath: verification of fix to CAS-1830'''
01145         test = "cas_1830_fix_test"
01146         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
01147         expected = [256, 256, 1, 1]
01148         i = 0
01149         for expr in ["IM0", "'" + cas1830_im + "'", '"' + cas1830_im + '"']:
01150             if (expr == "IM0"):
01151                 imagenames = [cas1830_im]
01152             else:
01153                 imagenames = [cas1830_im, ""]
01154             for imagename in imagenames:
01155                 outfile = 'cas1830_out+' + str(i)
01156                 if (imagename):
01157                     res = immath(imagename=imagename, expr=expr, chans='22', outfile=outfile)
01158                 else:
01159                     res = immath(expr=expr, chans='22', outfile=outfile)
01160                 self.assertTrue(res)
01161                 myia = iatool()
01162                 myia.open(outfile)
01163                 self.assertTrue((myia.shape() == expected).all())
01164                 myia.close()
01165                 i += 1
01166         self.assertTrue(retValue['success'],retValue['error_msgs'])
01167 
01168 
01169 class immath_test3(unittest.TestCase):
01170 
01171     def setUp(self):
01172             
01173         for img in imageList4:
01174             shutil.copytree(datapath + img, img)
01175     
01176     def tearDown(self):
01177         for img in imageList4:
01178             shutil.rmtree(img)     
01179         
01180         os.system('rm -rf pola*')
01181         os.system('rm -rf poli*')   
01182 
01183     def _comp(self, imagename, mode, outfile, expected, epsilon, polithresh=''):
01184         self.assertTrue(immath(imagename=imagename, outfile=outfile, mode=mode, polithresh=polithresh))
01185         self.assertTrue(os.path.exists(outfile))
01186         ia.open(outfile)
01187         got = ia.getchunk()
01188         ia.done()
01189         diff = expected - got
01190         if (epsilon == 0):
01191             #<debug>
01192             maxdiff = numpy.abs(numpy.max(got - expected))
01193             maxdiffrel = numpy.abs(numpy.max(diff/got))
01194             if (maxdiff > 0):
01195                 print "maxdiff " + str(maxdiff)
01196                 print "maxdiffrel " + str(maxdiffrel)
01197 
01198                 
01199             self.assertTrue((diff == 0).all())     
01200         else:
01201             self.assertTrue((numpy.abs(diff)/got < epsilon).all())        
01202 
01203     def test_CAS2120(self):
01204         '''immath: verification of old functionality and similar new functionality introduced by CAS-2120'''
01205 
01206         sysbits = struct.calcsize("P") * 8
01207         # epsilon necessary because of differences between 32 and 64 bit images
01208         epsilon = 3e-7
01209 
01210         # POLA
01211         mode = 'pola'
01212         myia = iatool()
01213         myia.open(POLA_im)
01214         expected = myia.getchunk()
01215         myia.done()
01216 
01217         # pola the old way
01218         self._comp([Q_im, U_im], mode, 'pola_1.im', expected, epsilon)  
01219 
01220         # test that order of Q, U doesn't matter
01221         self._comp([U_im, Q_im], mode, 'pola_2.im', expected, epsilon)  
01222         outfile = 'pola_2.im'
01223 
01224         # test making pola image from multi-stokes image
01225         self._comp(IQUV_im, mode, 'pola_3.im', expected, epsilon)  
01226 
01227         # test making pola image from multi-stokes image without V
01228         self._comp(IQU_im, mode, 'pola_4.im', expected, epsilon)  
01229 
01230         # test making pola image from multi-stokes image without I and V
01231         self._comp(QU_im, mode, 'pola_5.im', expected, epsilon)  
01232 
01233         # no Q, this should fail
01234         outfile = 'pola6.im'
01235         try:
01236             immath(imagename=UV_im, outfile=outfile, mode=mode)
01237             # should not get here
01238             self.assertTrue(false)
01239         except:
01240             self.assertFalse(os.path.exists(outfile))
01241 
01242         # no U, this should fail
01243         outfile = 'pola7.im'
01244         try:
01245             immath(imagename=Q_im, outfile=outfile, mode=mode)
01246             # should not get here
01247             self.assertTrue(false)
01248         except:
01249             self.assertFalse(os.path.exists(outfile))
01250 
01251         # no U, this should fail
01252         outfile = 'pola7.im'
01253         try:
01254             immath(imagename=[Q_im, V_im], outfile=outfile, mode=mode)
01255             # should not get here
01256             self.assertTrue(false)
01257         except:
01258             self.assertFalse(os.path.exists(outfile))
01259 
01260         # with a linear polarization threshold applied
01261         outfile = 'pola_8.im'
01262         self._comp(QU_im, mode, outfile, expected, epsilon, polithresh='30uJy/beam')
01263         mask_tbl = outfile + os.sep + 'mask0'
01264         self.assertTrue(os.path.exists(mask_tbl))
01265         
01266         mytb = tbtool()
01267         mytb.open(thresh_mask)
01268         col = 'PagedArray'
01269         maskexp = mytb.getcell(col, 0)
01270         mytb.done()
01271         mytb.open(mask_tbl)
01272         maskgot = mytb.getcell(col, 0)
01273         mytb.close()
01274 
01275         self.assertTrue((maskgot == maskexp).all())
01276 
01277         # POLI
01278         mode = 'poli'
01279         myia.open(POLL_im)
01280         poll = myia.getchunk()
01281         myia.done()
01282 
01283         myia.open(POLT_im)
01284         polt = myia.getchunk()
01285         myia.done()
01286 
01287         # linear polarization the old way
01288         self._comp([Q_im, U_im], mode, 'poli_1.im', poll, epsilon)  
01289 
01290         # Q, U order shouldn't matter
01291         self._comp([Q_im, U_im], mode, 'poli_2.im', poll, epsilon)  
01292 
01293         # new way, one multi-stokes image
01294         self._comp(IQU_im, mode, 'poli_3.im', poll, epsilon)  
01295 
01296         # new way, one multi-stokes image with only Q and U
01297         self._comp(QU_im, mode, 'poli_4.im', poll, epsilon)  
01298        
01299         # poli for IQUV image will produce a total, not linear, polarization image 
01300         self._comp([Q_im, U_im, V_im], mode, 'poli_5.im', polt, epsilon)  
01301         self._comp(IQUV_im, mode, 'poli_6.im', polt, epsilon)
01302 
01303         # fail, no U
01304         outfile = 'poli7.im'
01305         try:
01306             immath(imagename=[Q_im, V_im], outfile=outfile, mode=mode)
01307             # should not get here
01308             self.assertTrue(false)
01309         except:
01310             self.assertFalse(os.path.exists(outfile))
01311 
01312         # fail, no Q
01313         outfile = 'poli8.im'
01314         try:
01315             immath(imagename=UV_im, outfile=outfile, mode=mode)
01316             # should not get here
01317             self.assertTrue(false)
01318         except:
01319             self.assertFalse(os.path.exists(outfile))
01320 
01321     def test_CAS2943(self):
01322         """Test the stretch parameter"""
01323         myia = iatool()
01324         myia.fromshape("myim.im", [10, 20, 4, 40])
01325         myia.done()
01326         myia.fromshape("mask1.im", [10, 20, 4, 40])
01327         myia.done()
01328         myia.fromshape("mask2.im", [10, 20, 1, 1])
01329         myia.done()
01330         myia.fromshape("mask3.im", [10, 20, 4, 2])
01331         myia.done()
01332         outfile = "out1.im"
01333         immath(
01334             imagename="myim.im", outfile=outfile, mode="evalexpr",
01335             expr="1*IM0", mask="mask1.im > 5", stretch=False
01336         )
01337         myia.open(outfile)
01338         self.assertTrue((myia.shape() == [10, 20, 4, 40]).all())
01339         myia.done()
01340         outfile = "out2.im"
01341         self.assertFalse(
01342             immath(
01343                 imagename="myim.im", outfile=outfile, mode="evalexpr",
01344                 expr="1*IM0", mask="mask2.im > 5", stretch=False
01345             )
01346         )
01347         outfile = "out3.im"
01348         immath(
01349             imagename="myim.im", outfile=outfile, mode="evalexpr",
01350             expr="1*IM0", mask="mask2.im > 5", stretch=True
01351         )
01352         myia.open(outfile)
01353         self.assertTrue((myia.shape() == [10, 20, 4, 40]).all())
01354         myia.done()
01355         outfile = "out4.im"
01356         self.assertFalse(
01357             immath(
01358                 imagename="myim.im", outfile=outfile, mode="evalexpr",
01359                 expr="1*IM0", mask="mask3.im > 5", stretch=False
01360             )
01361         )
01362 
01363 def suite():
01364     return [immath_test1, immath_test2, immath_test3]
01365     
01366     
01367