casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
test_imval.py
Go to the documentation of this file.
00001 ###########################################################################
00002 # imval_test.py
00003 #
00004 # Copyright (C) 2008, 2009
00005 # Associated Universities, Inc. Washington DC, USA.
00006 #
00007 # This scripts free software; you can redistribute it and/or modify it
00008 # under the terms of the GNU Library General Public License as published by
00009 # the Free Software Foundation; either version 2 of the License, or (at your
00010 # option) any later version.
00011 #
00012 # This library is distributed in the hope that it will be useful, but WITHOUT
00013 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
00014 # FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
00015 # License for more details.
00016 #
00017 # You should have received a copy of the GNU Library General Public License
00018 # along with this library; if not, write to the Free Software Foundation,
00019 # Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
00020 #
00021 # Correspondence concerning AIPS++ should be adressed as follows:
00022 #        Internet email: aips2-request@nrao.edu.
00023 #        Postal address: AIPS++ Project Office
00024 #                        National Radio Astronomy Observatory
00025 #                        520 Edgemont Road
00026 #                        Charlottesville, VA 22903-2475 USA
00027 #
00028 # <author>
00029 # Shannon Jaeger (University of Calgary)
00030 # </author>
00031 #
00032 # <summary>
00033 # Test suite for the CASA imval Task
00034 # </summary>
00035 #
00036 # <reviewed reviwer="" date="" tests="" demos="">
00037 # </reviewed
00038 #
00039 # <prerequisite>
00040 # <ul>
00041 #   <li> <linkto class="imval.py:description">imval</linkto> 
00042 # </ul>
00043 # </prerequisite>
00044 #
00045 # <etymology>
00046 # imval_test stands for image value test
00047 # </etymology>
00048 #
00049 # <synopsis>
00050 # imval_test.py is a Python script that tests the correctness
00051 # of the imval task in CASA.
00052 #
00053 # Regression Test for the imval task.
00054 #
00055 # input/output tests.  Valid and invalid inputs are given
00056 #         for the following paramaters:
00057 #           a) No imagename 
00058 #           b) Bad imagename given
00059 #           c) Incorrect data type, not a string, to imagename parameter
00060 #           d) Out of range errors for, box, chans, & stokes parameters
00061 #           e) incorrect data type to box, chans, & stokes parameters
00062 #           f) Bad file name to region parameter
00063 #           g) Incorrect data type, not a string, to region parameter
00064 #           h) File name that does not contain a region to the region param.
00065 # Value at a single point tests.
00066 #           a) Value at bottom-left corner
00067 #           b) Value at bottom-right corner
00068 #           c) Value at top-left corner
00069 #           d) Value at top-right corner
00070 #           e) Value at 3 points within the image.
00071 # An array of values
00072 #           a) A slice of the directional plane
00073 #           b) Two slices of the directional plane
00074 #           c) A cube RA,Dec,and Spectral axes
00075 #           d) Two cubes RA,Dec,and Spectral axes
00076 #           e) A 4D blob: RA,Dec, Spetral, & Stokes.
00077 # </synopsis> 
00078 #
00079 # <example>
00080 # # This test was designed to run in the automated CASA test system.
00081 # # This example shows who to run it manually from within casapy.
00082 # casapy -c runUnitTest test_imcontsub
00083 #
00084 # or
00085 #
00086 # # This example shows who to run it manually from with casapy.
00087 # runUnitTest.main(['imcontsub_test'])
00088 #
00089 # </example>
00090 #
00091 # <motivation>
00092 # To provide a test standard to the imval task to try and ensure
00093 # coding changes do not break the task.
00094 # </motivation>
00095 #
00096 # <todo>
00097 #  1. produce summary data
00098 #  2 make sure failure_msgs is used everywere, and display them#
00099 # </todo>
00100 #     
00101 #
00102 # SDJ Sep. 8, 2008 Created.
00103 # SDJ May 20, 2009 Updated to testing Framework
00104 #----------------------------
00105 
00106 ###########################################################################
00107 import time
00108 import os
00109 import shutil
00110 import glob
00111 import numpy
00112 import casac
00113 from tasks import *
00114 from taskinit import *
00115 import unittest
00116 
00117 
00118 # Input files
00119 image_file = 'n4826_bima.im'
00120 good_rgn_file   =  'n4826_bima_test.rgn'
00121 
00122 
00123 ###########################################################################
00124 # NAME: info
00125 #
00126 # SHORT DESCRIPTION: Display information.
00127 #
00128 # DESCRIPTION: Write information to the local logger.
00129 #
00130 ############################################################################
00131 
00132 def info(message):
00133     #note(message,origin='regionmgrtest')
00134     print message
00135     casalog.postLocally(message, priority="NORMAL", origin='regionmgrtest')
00136 
00137 
00138 ###########################################################################
00139 # NAME: note
00140 #
00141 # SHORT DESCRIPTION: Display information.
00142 #
00143 # DESCRIPTION: Write information to the local logger with the given priority
00144 #
00145 ############################################################################
00146 
00147 def note(message, priority="NORMAL", origin="imval_test"):
00148     print message
00149     casalog.postLocally(message, priority, origin)
00150 
00151 
00152 ###########################################################################
00153 # NAME: input_test
00154 #
00155 # SHORT DESCRIPTION: Make sure invalid input is detected.
00156 #
00157 # DESCRIPTION: Test input that is the wrong type, to no values given.
00158 #              We expect lots of exceptions for this test!
00159 #              More precisely
00160 #           a) No imagename given
00161 #           b) Bad imagename given
00162 #           c) Incorrect data type, not a string, to imagename parameter
00163 #           d) Out of range errors for, box, chans, & stokes parameters
00164 #           e) incorrect data type to box, chans, & stokes parameters
00165 #           f) Bad file name to region parameter
00166 #           g) Incorrect data type, not a string, to region parameter
00167 #           h) File name that does not contain a region to the region param.
00168 #
00169 ############################################################################
00170 
00171 class imval_test(unittest.TestCase):
00172     
00173     def setUp(self):
00174         if (os.path.exists(image_file)):
00175             os.system('rm -rf ' +image_file+ ' ' +good_rgn_file)
00176             
00177         datapath = os.environ.get('CASAPATH').split()[0]+'/data/regression/ATST3/NGC4826/'
00178         os.system('cp -r ' +datapath + image_file +' ' + image_file)
00179         os.system('cp -r ' +datapath + good_rgn_file +' ' + good_rgn_file)
00180 
00181     def tearDown(self):
00182             os.system('rm -rf ' +image_file+ ' ' +good_rgn_file)
00183         
00184     def test_input(self):
00185         '''Imval: Input/output tests'''
00186         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00187         note( "Starting imval INPUT/OUTPUT tests.", 'NORMAL2' )
00188     
00189         ###########################################################
00190         # Image name tests
00191         info( 'Performing input/output tests on imagename, errors WILL occur.' )
00192         results=None
00193         try:
00194             results = imval( imagename='' )
00195         except:
00196             pass
00197         else:
00198             if ( results!=None \
00199                  and ( (isinstance(results,bool) and results==True )\
00200                  or (isinstance(results,dict) and results!={} ) ) ):
00201                 retValue['success']=False
00202                 retValue['error_msgs']=retValue['error_msgs']\
00203                      +"\nError: Empty imagename parameter not detected."
00204     
00205         results = None
00206         try:
00207             results = imval( imagename=good_rgn_file )
00208         except:
00209             pass
00210         else:
00211             if ( results!=None \
00212                  and ( (isinstance(results,bool) and results==True )\
00213                  or (isinstance(results,dict) and results!={} ) ) ):
00214                 retValue['success']=False
00215                 retValue['error_msgs']=retValue['error_msgs']\
00216                               +"\nError: Invalid image file name not detected."
00217     
00218         results=None
00219         try:
00220             results = imval( imagename=2.3 )
00221         except:
00222             pass
00223         else:
00224             if ( results!=None \
00225                  and ( (isinstance(results,bool) and results==True )\
00226                  or (isinstance(results,dict) and results!={} ) ) ):
00227                 retValue['success']=False
00228                 retValue['error_msgs']=retValue['error_msgs']\
00229                          +"\nError: Invalid image file name, 2.3,  not detected."
00230     
00231         results=None
00232         try:
00233             results = imval( imagename='n4826_bima.im' )
00234         except:
00235             retValue['success']=False
00236             retValue['error_msgs']=retValue['error_msgs']\
00237                          +"\nError: imval failed with valid file name, n4826_bima.im."
00238         if ( results == None ):
00239             retValue['success']=False
00240             retValue['error_msgs']=retValue['error_msgs']\
00241                      +"\nError: Valid imagename, n4826_bima.im, test failed."
00242         del results        
00243             
00244         ###################################################################
00245         # Testing out of range errors.
00246         # BLC=0,0,0,0  and TRC= 255,255,0,29   for n4826_bima.im
00247         info( 'Performing input/output tests on "box", errors WILL occur.' )
00248         results=None
00249         try:
00250             results = imval( imagename=image_file, box='-3,0,-3,3' )
00251         except:
00252             pass
00253         else:
00254             if ( results!=None \
00255                  and ( (isinstance(results,bool) and results==True )\
00256                  or (isinstance(results,dict) and results!={} ) ) ):
00257                 retValue['success']=False
00258                 retValue['error_msgs']=retValue['error_msgs']\
00259                              +'\nInvalid box parameter, x=-3, values not detected.'
00260             
00261         results=None
00262         try:
00263             results = imval( imagename=image_file, box='200,0,262,3' )
00264         except:
00265             pass
00266         else:
00267             if ( results!=None \
00268                  and ( (isinstance(results,bool) and results==True )\
00269                  or (isinstance(results,dict) and results!={} ) ) ):
00270                 retValue['success']=False
00271                 retValue['error_msgs']=retValue['error_msgs']\
00272                      +'Invalid box parameter values,262, not detected.'
00273     
00274         results=None
00275         try:
00276             results = imval( imagename=image_file, box='0,-3,0,3' )
00277         except:
00278             pass
00279         else:
00280             if ( results!=None \
00281                  and ( (isinstance(results,bool) and results==True )\
00282                  or (isinstance(results,dict) and results!={} ) ) ):
00283                 retValue['success']=False
00284                 retValue['error_msgs']=retValue['error_msgs']\
00285                        + 'Invalid box parameter value, y=-3, not detected.'
00286     
00287         results=None
00288         try:
00289             results = imval( imagename=image_file, box='0,270,0,3' )
00290         except:
00291             pass
00292         else:
00293             if ( results!=None \
00294                  and ( (isinstance(results,bool) and results==True )\
00295                  or (isinstance(results,dict) and results!={} ) ) ):
00296                 retValue['success']=False
00297                 retValue['error_msgs']=retValue['error_msgs']\
00298                           + 'Invalid box parameter value, y=270, not detected.'
00299     
00300         results=None
00301         try:
00302             results = imval( imagename=image_file, box='0,110,0,10' )
00303         except:
00304             pass
00305         else:
00306             if ( results!=None \
00307                  and ( (isinstance(results,bool) and results==True )\
00308                  or (isinstance(results,dict) and results!={} ) ) ):
00309                 retValue['success']=False
00310                 retValue['error_msgs']=retValue['error_msgs']\
00311                           + 'Invalid box parameter value, y[1]>y[0], not detected.'
00312     
00313         results=None
00314         try:
00315             results = imval( imagename=image_file, box="1,2,3,4" )
00316         except:
00317             retValue['success']=False
00318             retValue['error_msgs']=retValue['error_msgs'] \
00319                        +'Valid box parameter values caused an error.'
00320     
00321         if ( results == None ):
00322             retValue['success']=False
00323             retValue['error_msgs']=retValue['error_msgs']\
00324                      +"\nError: Valid box test, box=[1,2,3,4], failed."
00325         del results        
00326     
00327         ##############################################################
00328         # CHANS parameter testing
00329         info( 'Performing input/output tests on "chans", errors WILL occur.' )
00330         result=None
00331         try:
00332             results = imval( imagename=image_file, chans='-3' )
00333         except:
00334             pass
00335         else:
00336             if ( results!=None \
00337                  and ( (isinstance(results,bool) and results==True )\
00338                  or (isinstance(results,dict) and results!={} ) ) ):
00339                         retValue['success']=False
00340                         retValue['error_msgs']=retValue['error_msgs'] \
00341                                +'Invalid chans parameter value,-3, not detected.'
00342     
00343         resutls=None
00344         try:
00345             results = imval( imagename=image_file, chans='50' )
00346         except:
00347             pass
00348         else:
00349             if ( results!=None \
00350                  and ( (isinstance(results,bool) and results==True )\
00351                  or (isinstance(results,dict) and results!={} ) ) ):
00352                         retValue['success']=False
00353                         retValue['error_msgs']=retValue['error_msgs'] \
00354                             +'Invalid chans parameter value,50, not detected.'
00355     
00356         results=None
00357         try:
00358             results = imval( imagename=image_file, chans="10" )
00359         except:
00360             retValue['success']=False
00361             retValue['error_msgs']=retValue['error_msgs'] \
00362                   +'Valid chans parameter value caused an error.'
00363     
00364         if ( results == None ):
00365             retValue['success']=False
00366             retValue['error_msgs']=retValue['error_msgs']\
00367                      +"\nError: Valid channel test, chans='10', failed."
00368         del results
00369     
00370     
00371         ###############################################################
00372         # STOKES parameter testing
00373         info( 'Performing input/output tests on "stokes", errors WILL occur.' )
00374         results=None
00375         try:
00376             results = imval( imagename=image_file, stokes='Q' )        
00377         except:
00378             pass
00379         else:
00380             if ( results!=None \
00381                  and ( (isinstance(results,bool) and results==True )\
00382                  or (isinstance(results,dict) and results!={} ) ) ):
00383                 retValue['success']=False
00384                 retValue['error_msgs']=retValue['error_msgs'] \
00385                            +'Invalid stokes value, Q,  not detected.'
00386     
00387         results=None
00388         try:
00389             results = imval( imagename=image_file, stokes=0 )
00390         except:
00391             pass
00392         else:
00393             if ( results!=None \
00394                  and ( (isinstance(results,bool) and results==True )\
00395                  or (isinstance(results,dict) and results!={} ) ) ):
00396                 retValue['success']=False
00397                 retValue['error_msgs']=retValue['error_msgs'] \
00398                            +'Invalid stokes value, 0,  not detected.'
00399         results=None
00400         try:
00401             results = imval( imagename=image_file, stokes='I' )
00402         except:
00403             retValue['success']=False
00404             retValue['error_msgs']=retValue['error_msgs'] \
00405                            +'Valid stokes value, I, caused errors.'
00406     
00407         if ( results == None ):
00408             retValue['success']=False
00409             retValue['error_msgs']=retValue['error_msgs']\
00410                      +"\nError: Valid stokes, 'I', test failed on file ."\
00411                      +image_file+"\nRESULTS: "+str(results)
00412         del results
00413             
00414         ########################################
00415         # REGION parameter tests
00416         info( 'Performing input/output tests on "region", errors WILL occur.' )
00417         results=None
00418         try:
00419             results = imval( imagename=image_file, region=[1,3] )
00420         except:
00421             pass
00422         else:
00423             if ( results!=None \
00424                  and ( (isinstance(results,bool) and results==True )\
00425                  or (isinstance(results,dict) and results!={} ) ) ):
00426                 retValue['success']=False
00427                 retValue['error_msgs']=retValue['error_msgs']\
00428                    +"\nError: Bad region, '[1, 3]', was not reported."
00429                 
00430                    
00431         # First make sure the region file does not exist.
00432         garbage_rgn_file = os.getcwd()+'/garbage.rgn'
00433         if ( os.path.exists( garbage_rgn_file )):
00434             os.remove( garbage_rgn_file )
00435         
00436         try:
00437             results = imval( imagename=image_file, \
00438                              region=garbage_rgn_file )
00439         except:
00440             #We want this to fail
00441             no_op = 'noop'
00442         else:
00443             if ( results!=None \
00444                  and ( (isinstance(results,bool) and results==True )\
00445                  or (isinstance(results,dict) and results!={} ) ) ):
00446                 retValue['success']=False
00447                 retValue['error_msgs']=retValue['error_msgs']\
00448                        + "\nError: Bad region file, 'garbage.rgn', was NOT "\
00449                        + "reported as missing."
00450                        
00451         try:
00452             rgn_file = os.getcwd()+'garbage.rgn'
00453             fp=open( rgn_file, 'w' )
00454             fp.writelines('This file does NOT contain a valid CASA region specification\n')
00455             fp.close()
00456         except Exception, err:
00457             retValue['success']=False
00458             retValue['error_msgs']=retValue['error_msgs']\
00459                      +"\nError: Unable to create bad region file.\n\t"
00460             raise Exception, err
00461     
00462             
00463     
00464         try:
00465             results = imval( imagename=image_file, region=rgn_file )
00466         except:
00467             no_op='noop'
00468         else:
00469             if ( results!=None \
00470                  and ( (isinstance(results,bool) and results==True )\
00471                  or (isinstance(results,dict) and results!={} ) ) ):
00472                 retValue['success']=False
00473                 retValue['error_msgs']=retValue['error_msgs']\
00474                               + "\nError: Bad region file, 'garbage.rgn',"\
00475                               + " was not reported as bad."
00476     
00477         
00478         results=None
00479         try:
00480             results=imval( imagename=image_file, region=good_rgn_file )
00481         except:
00482             retValue['success']=False
00483             retValue['error_msgs']=retValue['error_msgs']\
00484                        +"\nError: Unable to get image values in region "\
00485                        +" specified by file, "+good_rgn_file
00486         if ( results == None or results==False ):
00487             retValue['success']=False
00488             retValue['error_msgs']=retValue['error_msgs']\
00489                      +"\nError: Valid region file, "+good_rgn_file\
00490                      +" tset has failed."\
00491                      +"\nRESULTS: "+str(results)
00492         del results
00493                 
00494         self.assertTrue(retValue['success'],retValue['error_msgs'])
00495     
00496     ###########################################################################
00497     # NAME: single_point
00498     #
00499     # SHORT DESCRIPTION: Do tests to find the value at a single point
00500     #
00501     # DESCRIPTION:
00502     #           a) Value at bottom-left corner
00503     #           b) Value at bottom-right corner
00504     #           c) Value at top-left corner
00505     #           d) Value at top-right corner
00506     #           e) Value at 3 points within the image.
00507     #
00508     ############################################################################
00509     
00510     def test_single_point(self):
00511         '''Imval: Single point tests'''
00512         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00513         note( "Starting SINGLE POINT tests.", 'NORMAL2' )
00514     
00515         # Find the min/max points of the image.
00516         bbox={}
00517         try: 
00518             ia.open( image_file )
00519             bbox=ia.boundingbox()
00520             ia.done()
00521         except:
00522             retValue['success']=False
00523             retValue['error_msgs']=retValue['error_msgs']\
00524                      +"\nError: Unable to find size of image "+image_name
00525     
00526         dir_blc=[]
00527         dir_trc=[]
00528         min_chan=max_chan=-1
00529         min_stokes=max_stokes=-1    
00530         if ( len(bbox) > 0 and bbox.has_key('blc') and bbox.has_key('trc') ):
00531             blc=bbox['blc']
00532             trc=bbox['trc']
00533     
00534             dir_blc=[blc[0], blc[1]]
00535             dir_trc=[trc[0], trc[1]]
00536             min_chan=blc[3]
00537             max_chan=trc[3]
00538             min_Stokes=blc[2]
00539             max_stokes=trc[2]
00540     
00541         error_margin=0.00001
00542     
00543         
00544         #############################################################
00545         # Bottom-left
00546         tbox=str(dir_blc[0])+','+str(dir_blc[1])+','+str(dir_blc[0])+','\
00547               +str(dir_blc[1])
00548         msg="Bottom left corner value was Not Found"
00549         results=None
00550         try:
00551             results=imval( imagename=image_file, box=tbox, chans=str(min_chan), \
00552                            stokes=str(min_stokes) )
00553         except Exception:
00554             retValue['success']=False
00555             retValue['error_msgs']=retValue['error_msgs']\
00556                      +"\nError: Failed to get the value in the bottom left"\
00557                      +" corner, "+tbox+"."
00558         else:
00559             if ( results!=None and results.has_key( 'blc') \
00560                  and results.has_key('data') and results.has_key('unit')\
00561                  and results.has_key('mask') ):
00562                 msg='Bottom left corner valus is, '+str(results['blc'])\
00563                      +', value is: '+str(results['data'])+str(results['unit'])\
00564                      +' with mask '+str(results['mask'])
00565             if ( results==None or not results.has_key('data') \
00566                  or not results.has_key('data') or \
00567                ( results['data']+1.035184e-09>error_margin or not results['mask']) ):
00568                 retValue['success']=False
00569                 retValue['error_msgs']=retValue['error_msgs']\
00570                      +"\nError: Expected 1.035184e-09Jy/Beam with mask=True."\
00571                      +"\n\t"+msg
00572     
00573         #############################################################
00574         # Bottom-right
00575         tbox=str(dir_trc[0])+','+str(dir_blc[1])+','+str(dir_trc[0])+','\
00576               +str(dir_blc[1])
00577         msg="Bottom right corner value was Not Found"
00578         results=None
00579         try:
00580             results=imval( imagename=image_file, box=tbox, chans=str(min_chan),\
00581                            stokes=str(min_stokes) )
00582         except Exception:
00583             retValue['success']=False
00584             retValue['error_msgs']=retValue['error_msgs']\
00585                      +"\nError: Failed to get the value in the bottom right"\
00586                      +" corner. "+tbox+"."                
00587         else:
00588             if ( results!=None and results.has_key( 'blc') \
00589                  and results.has_key('data') and results.has_key('unit')\
00590                  and results.has_key('mask') ):
00591                 msg='Bottom right corner, '+str(results['blc'])+', value is: '\
00592                      +str(results['data'])+str(results['unit'])\
00593                      +' with mask '+str(results['mask'])
00594             if ( results==None or not results.has_key('data') \
00595                  or not results.has_key('data') or \
00596                 ( results['data']+1.172165e-09 > 0.00001 or not results['mask'])):
00597                 retValue['success']=False
00598                 retValue['error_msgs']=retValue['error_msgs']\
00599                          +'\nError: Expected value of -1.172165e-09 and mask=True'\
00600                          +'\n\t'+msg
00601     
00602         ######################################################3
00603         # Top-left
00604         tbox=str(dir_blc[0])+','+str(dir_trc[1])+','+str(dir_blc[0])+','\
00605               +str(dir_trc[1])
00606         msg="Top left corner value was Not Found"
00607         results=None
00608     
00609         try:
00610             results=imval( imagename=image_file, box=tbox, chans=str(min_chan),
00611                            stokes=str(min_stokes) )
00612         except Exception:
00613             retValue['success']=False
00614             retValue['error_msgs']=retValue['error_msgs']\
00615                      +"\nError: Failed to get the value in the top left"\
00616                      +" corner, "+tbox+"."
00617         else:
00618             if ( results!=None and results.has_key( 'blc') \
00619                  and results.has_key('data') and results.has_key('unit')\
00620                  and results.has_key('mask') ):
00621                 msg='Top left corner, '+str(results['blc'])+', value is: '\
00622                      +str(results['data'])+str(results['unit'])\
00623                      +' with mask '+str(results['mask'])
00624             if ( results==None or not results.has_key('data') \
00625                  or not results.has_key('data') or \
00626                  ( results['data']+4.2731923e-09>error_margin or not results['mask'])):
00627                 retValue['success']=False
00628                 retValue['error_msgs'] = retValue['error_msgs'] + "\nError: Expected value of -4.273192e-09, and mask=True"  + "\n\t" + msg
00629                 
00630         #############################################################
00631         # Top-right
00632         tbox=str(dir_trc[0])+','+str(dir_trc[1])+','+str(dir_trc[0])+','\
00633               +str(dir_trc[1])
00634         msg="Top right corner value was Not Found"
00635         results=None
00636         try:
00637             results=imval( imagename=image_file, box=tbox, chans=str(min_chan),\
00638                            stokes=str(min_stokes) )
00639         except Exception:
00640             retValue['success']=False
00641             retValue['error_msgs']=retValue['error_msgs']\
00642                      +"\nError: Failed to get the value in the top right"\
00643                      +" corner. "+tbox+"."
00644         else:
00645             if ( results!=None and results.has_key( 'blc') \
00646                  and results.has_key('data') and results.has_key('unit')\
00647                  and results.has_key('mask') ):
00648                 msg='Top right corner, '+str(results['blc'])+', value is: '\
00649                      +str(results['data'])+str(results['unit'])\
00650                      +' with mask '+str(results['mask'])
00651             if ( results==None or not results.has_key('data') \
00652                  or not results.has_key('data') or \
00653                  (results['data']+3.647830e-09>error_margin or not results['mask'])):
00654                 retValue['success']=False
00655                 retValue['error_msgs']=retValue['error_msgs']\
00656                     +'\nError: Expected value -3.647830e-09Jy/Beam and mask=True'\
00657                     +'\n\t'+msg
00658     
00659         #########################################################3
00660         # Last channel and stokes
00661         tbox=str(dir_trc[0])+','+str(dir_trc[1])+','+str(dir_trc[0])+','+\
00662               str(dir_trc[1])
00663         msg="Value NOT found when looking at last chanel and last stokes"
00664         results=None
00665     
00666         try:
00667             results=imval( imagename=image_file, box=tbox, chans=str(max_chan), \
00668                            stokes=str(max_stokes) )
00669         except Exception:
00670             retValue['success']=False
00671             retValue['error_msgs']=retValue['error_msgs']\
00672                      +"\nError: Failed to get the value at the last channel "\
00673                      +" and last stokes, "+tbox+"."
00674         else:
00675             if ( results!=None and results.has_key( 'blc') \
00676                  and results.has_key('data') and results.has_key('unit')\
00677                  and results.has_key('mask') ):
00678                 msg='Value found at'+str(results['blc'])+' is: '\
00679                      +str(results['data'])+str(results['unit'])\
00680                      +'. with mask '+str(results['mask'])
00681                 if ( results==None or not results.has_key('data') or \
00682                      ( results['data']-3.55266e-10 > error_margin ) ):
00683                     retValue['success']=False
00684                     retValue['error_msgs']=retValue['error_msgs']\
00685                             +'\nError: Expected value -3.647830e-09Jy/Beam and'\
00686                             +' mask=True \n\t'+msg
00687     
00688             #######################################################
00689             # A couple of not so random points
00690             tbox=str(int(dir_trc[0]*2/3))+','+str(int(dir_trc[1]*2/3))+','\
00691                   +str(int(dir_trc[0]*2/3))+','+str(int(dir_trc[1]*2/3))
00692             msg="Value NOT found when looking at first random point,"+tbox+"."
00693             results=None
00694     
00695             try:
00696                 results=imval( imagename=image_file, box=tbox, \
00697                 chans=str(int(max_chan*2/3)), stokes=str(max_stokes) )
00698             except Exception:
00699                 retValue['success']=False
00700                 retValue['error_msgs']=retValue['error_msgs']\
00701                      +"\nError: "+msg
00702             else:
00703                 if ( results!=None and results.has_key( 'blc') \
00704                      and results.has_key('data') and results.has_key('unit')\
00705                      and results.has_key('mask') ):
00706                     msg='Value found at'+str(results['blc'])+' is: '\
00707                          +str(results['data'])+str(results['unit'])\
00708                          +'. with mask '+str(results['mask'])
00709                 if ( results==None or not results.has_key('data') or \
00710                      ( results['data']-0.062294 > error_margin ) ):
00711                     retValue['success']=False
00712                     retValue['error_msgs']=retValue['error_msgs']\
00713                     +'\nError: Expected value of 0.062294Jy/Beam and mask=True'\
00714                        +'\n\t'+msg
00715     
00716             # Second random point
00717             tbox=str(int(dir_trc[0]*1/6))+','+str(int(dir_trc[1]*2/6))+','\
00718                   +str(int(dir_trc[0]*1/6))+','+str(int(dir_trc[1]*2/6))
00719             msg="Value NOT found when looking at second random point,"+tbox+"."
00720             results=None
00721     
00722             try:
00723                 results=imval( imagename=image_file, box=tbox, \
00724                             chans=str(int(max_chan*5/6)), stokes=str(max_stokes) )
00725             except Exception:
00726                 retValue['success']=False
00727                 retValue['error_msgs']=retValue['error_msgs']\
00728                      +"\nError: "+msg
00729             else:
00730                 if ( results!=None and results.has_key( 'blc') \
00731                      and results.has_key('data') and results.has_key('unit')\
00732                      and results.has_key('mask') ):
00733                      msg='Value found at'+str(results['blc'])+' is: '\
00734                      +str(results['data'])+str(results['unit'])\
00735                      +'. with mask '+str(results['mask'])
00736     
00737                 if ( results==None or not results.has_key('data') or \
00738                      ( results['data']+0.070744 > error_margin ) ):
00739                     retValue['success']=False
00740                     retValue['error_msgs']=retValue['error_msgs']\
00741                           +'Error: Expected value of -0.070744Jy/Beam and '\
00742                           +'mask=True'+'\n\t'+msg
00743     
00744         self.assertTrue(retValue['success'],retValue['error_msgs'])
00745     
00746     ###########################################################################
00747     # NAME: arrays 
00748     #
00749     # SHORT DESCRIPTION: Do tests to find the value at a single point
00750     #
00751     # DESCRIPTION:
00752     #           a) A slice of the directional plane
00753     #           b) Two slices of the directional plane
00754     #           c) A cube RA,Dec,and Spectral axes
00755     #           d) Two cubes RA,Dec,and Spectral axes
00756     #           e) A 4D blob: RA,Dec, Spetral, & Stokes.
00757     #
00758     # Note for the image we are using the axes are: RA, Dec, Stokes, Spectral
00759     #
00760     # TODO - check shape value on spectral value
00761     #        tests d and e.
00762     #      - This could be done in a loop, or some of it pulled out to
00763     #        a separate method instead of repeating code!
00764     ############################################################################
00765     
00766     def test_array(self):
00767         '''Imval: array values'''
00768         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }
00769         note( "Starting ARRAY RESULTS tests.", 'NORMAL2' )
00770         error_margin = 0.00001
00771     
00772         # Find the min/max points of the image.
00773         bbox={}
00774         try: 
00775             ia.open( image_file )
00776             bbox=ia.boundingbox()
00777             ia.done()
00778         except:
00779             retValue['success']=False
00780             retValue['error_msgs']=retValue['error_msgs']\
00781                      +"\nError: Unable to find size of input image "+image_name
00782         
00783         dir_blc=dir_trc=[]
00784         min_chan=max_chan=min_stokes=max_stokes=-2
00785         if ( len(bbox) > 0 and bbox.has_key('blc') and bbox.has_key('trc') ):
00786             blc=bbox['blc']
00787             trc=bbox['trc']
00788             
00789             dir_blc=[blc[0], blc[1]]
00790             dir_trc=[trc[0], trc[1]]
00791             min_chan=blc[3]
00792             max_chan=trc[3]
00793             min_stokes=blc[2]
00794             max_stokes=trc[2]
00795         else:
00796             retValue['success']=False
00797             retValue['error_msgs']=retValue['error_msgs']\
00798                      +"\nError: Unable to find corners of input image "+image_name
00799             return retValue
00800     
00801         #
00802         # We want to find an array of values for the following areas:
00803         #    1. inner quarter, for channel 5
00804         #    2. inner quarter, for channesl 5 and 10
00805         #    3. inner third, for channels 15to17
00806         #
00807         # Setup a few arrays with the input values so that we can do
00808         # these tests in a beautiful loop.
00809     
00810         # Input values
00811         testnames= [ 'inner 1/2 with 1 channel', 'inner 1/2 multi-channel',\
00812                      'inner 1/3rd multi-channel' ]
00813         boxes=[]
00814         boxes.append( str(int(dir_trc[0]*1/4))+','+str(int(dir_trc[1]*1/4))+\
00815                       ','+str(int(dir_trc[0]*3/4))+','+str(int(dir_trc[1]*3/4)))
00816         boxes.append( str(int(dir_trc[0]*1/4))+','+str(int(dir_trc[1]*1/4))+\
00817                       ','+str(int(dir_trc[0]*3/4))+','+str(int(dir_trc[1]*3/4)))
00818                       
00819         boxes.append(str(int(dir_trc[0]*1/3))+','+str(int(dir_trc[1]*1/3))+\
00820                      ','+str(int(dir_trc[0]*5/6))+','+str(int(dir_trc[1]*5/6)))
00821                     
00822         chans  = [ '5', '5,10', '15~17']
00823         stokes = [ '0', '0', '0'  ]
00824     
00825         # Expected results.
00826         shapes = [ [129,129,1,1], [129,129,2,1], [128,128,3,1] ]
00827         mins   = [ 0.417753, -0.417753, 0.4758411 ]
00828         maxs   = [ 1.69093, 1.537767, 0.999663 ]
00829         means  = [ 0.003042, 1000.0, 10000.0 ]
00830         
00831         for index in range(0,len(boxes)):
00832             results=None
00833             tbox=boxes[index]
00834     
00835             try:
00836                 results=imval( imagename=image_file, box=tbox, \
00837                                chans=chans[index], stokes=stokes[index] )
00838             except Exception, e:
00839                 retValue['success']=False
00840                 retValue['error_msgs']=retValue['error_msgs']\
00841                                         +"\nError: Failed " + testnames[index]\
00842                                         + " test, region is: "\
00843                                         + tbox+".\n\t"+str(e)
00844                 return retValue
00845                                         
00846             msg=''
00847             if ( results!=None and results.has_key( 'blc') \
00848                  and results.has_key( 'trc') ):
00849                 msg='Data array bounded by: , '+str(results['blc'])\
00850                      +' and '+str(results['trc'])
00851                 
00852             data_array=[]
00853             if ( results!=None and results.has_key( 'data') ):
00854                 data_array=results['data']
00855     
00856             mask_array=[]
00857             if ( results!=None and results.has_key( 'mask') ):
00858                 mask_array=results['mask']
00859     
00860             if ( len( mask_array ) < 1 or \
00861                  ( mask_array.min()!=True and mask_array.max() != True ) ):
00862                 retValue['success']=False
00863                 retValue['error_msgs']=retValue['error_msgs']\
00864                      +"\nError: Either no mask found, or False values were"\
00865                      +' found in the mask, expected all True values.'
00866     
00867             # Expect shape of 
00868             if ( len( data_array ) < 0 ):
00869                 retValue['success']=False
00870                 retValue['error_msgs']=retValue['error_msgs']\
00871                                         +"\nError: Empty data array found. "+msg
00872             else:
00873                 msg=msg+'\nwith shape of '+ str(numpy.shape(data_array))
00874                 # Note that the data and mask arrays are 2-D only, the
00875                 # degenerative axes are dropped.  However, our expected
00876                 # shape information contains 4 axes, so we can't do a
00877                 # direct comparison.
00878                 #print "DATA SHAPE: ", numpy.shape(data_array)
00879                 #print "MASK SHAPE: ", numpy.shape(mask_array)
00880                 #print "EXPECTED SHAPES: ", shapes[index]
00881                 if ( numpy.shape(data_array)[0] != shapes[index][0] \
00882                      or numpy.shape(data_array)[1] != shapes[index][1] \
00883                      or numpy.shape(data_array) != numpy.shape(mask_array) ):
00884                     retValue['success']=False
00885                     retValue['error_msgs']=retValue['error_msgs']\
00886                             +"\nError: Incorrect data or mask array size for "\
00887                             +"\n"+msg+"\nexpected shape to be "\
00888                             +str(shapes[index][0])\
00889                             +"X"+str(shapes[index][1])
00890                     
00891                 dmin=data_array.min()
00892                 dmax=data_array.max()
00893                 dmean=data_array.mean()
00894                 # CHECK THAT THESE ARE CORRECT
00895                 # What if the min is < 0?
00896                 if ( dmin+mins[index] > error_margin ):
00897                     retValue['success']=False
00898                     retValue['error_msgs']=retValue['error_msgs']\
00899                            +"\nError: Expected minimum value of, "\
00900                            + str(mins[index])\
00901                            +" but found minimum of "+str(dmin)+"."
00902                 if ( dmax-maxs[index] > error_margin ):
00903                     retValue['success']=False
00904                     retValue['error2_msgs']=retValue['error_msgs']\
00905                            +"\nError: Expected maximum value of, "\
00906                            + str(maxes[index])\
00907                            +" but found maximum of "+str(dmax)+"."
00908                 if ( dmean-means[index] > error_margin ):
00909                     retValue['success']=False
00910                     retValue['error_msgs']=retValue['error_msgs']\
00911                       +"\nError: Expected mean of, "\
00912                       + str(means[index])\
00913                       +" but found mean of "+str(dmax)+"."
00914     
00915         self.assertTrue(retValue['success'],retValue['error_msgs'])     
00916         
00917     def test_coord_return(self):
00918         """Test returned coordinates CAS-2651"""
00919         myimval = imval(imagename=image_file, box="40,40,50,50", chans="5")
00920         myia = iatool()
00921         myia.open(image_file)
00922         mycsys = myia.coordsys()
00923         expected = mycsys.toworld([45,45,0,5])['numeric']
00924         got = myimval["coords"][5,5]
00925         diff = got - expected
00926         # not 0 because of 32 bit precision issues
00927         self.assertTrue(max(abs(diff)) < 1e-16)
00928         
00929     
00930 def suite():
00931     return [imval_test]
00932 
00933