casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
test_imhead.py
Go to the documentation of this file.
00001 ##########################################################################
00002 # imhead_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 imhead Task
00034 # </summary>
00035 #
00036 # <reviewed reviwer="" date="" tests="" demos="">
00037 # </reviewed
00038 #
00039 # <prerequisite>
00040 # <ul>
00041 #   <li> <linkto class="imhead.py:description">imhead</linkto> 
00042 # </ul>
00043 # </prerequisite>
00044 #
00045 # <etymology>
00046 # imhead_test stands for image header test
00047 # </etymology>
00048 #
00049 # <synopsis>
00050 # imhead_test.py is a Python script that tests the correctness
00051 # of the imhead task in CASA.  This is essentially a unit test
00052 # for the imhead task.
00053 #
00054 # However, it is also used as a regression test for the imhead task.
00055 #
00056 # </synopsis> 
00057 #
00058 # <example>
00059 # # This test was designed to run using the CASA unit test system.
00060 # # This example shows who to run it manually from within casapy.
00061 # runUnitTest.main(['test_imhead'])
00062 #
00063 # or outside casapy like this:
00064 # casapy -c runUnitTest.py test_imhead
00065 #
00066 # </example>
00067 #
00068 # <motivation>
00069 # To provide a test standard to the imhead task to try and ensure
00070 # coding changes do not break the 
00071 # </motivation>
00072 #
00073 # <todo>
00074 #  1. produce summary data
00075 #  2 make sure failure_msgs is used everywere, and display them#
00076 # </todo>
00077 #     
00078 #
00079 # SDJ Sep. 8, 2008 Created.
00080 # SDJ May 20, 2009 Updated to testing Framework
00081 
00082 
00083 ###########################################################################
00084 import numpy
00085 import os
00086 import shutil
00087 import casac
00088 from tasks import *
00089 from taskinit import *
00090 import commands
00091 import unittest
00092 
00093 ###########################################################################
00094 # NAME: mode_test
00095 #
00096 # SHORT DESCRIPTION: Make sure all of the modes are supported
00097 #                    and that a graceful exit occurs for an
00098 #                    invalid mode.
00099 #
00100 # DESCRIPTION: Call each of the modes to make sure they work.
00101 #              The VALID modes are: list, get, put, history, summary,
00102 #              fits, add, and del.
00103 # 
00104 #              The INVALID modes called are: '', 2.2, and bad
00105 #
00106 ############################################################################
00107 
00108 # Input file names
00109 input_file = 'ngc5921.clean.image'
00110 input_file_copy = 'ngc5921.clean.image.copy'
00111 
00112 class imhead_test(unittest.TestCase):
00113     
00114     def setUp(self):
00115         if(os.path.exists(input_file)):
00116             os.system('rm -rf ' +input_file)
00117 
00118         datapath=os.environ.get('CASAPATH').split()[0]+'/data/regression/ngc5921redux/reference/ngc5921_regression/'
00119         os.system('cp -r ' +datapath + input_file +' ' + input_file)
00120 
00121     def tearDown(self):
00122         os.system('rm -rf ' +input_file)
00123 
00124     def test_mode(self):
00125         '''Imhead: Test list,summary,history,get,put,del,add,empty,bad modes'''
00126         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }    
00127         casalog.post( "Staring imhead mode tests!", "NORMAL2" )
00128     
00129         
00130         ################################################################
00131         # List mode
00132         casalog.post( "Testing LIST mode", "NORMAL4" );
00133         results=None
00134         try:
00135             results = imhead( input_file, 'list' )
00136         except:
00137             retValue['success']=False
00138             retValue['error_msgs']=retValue['error_msgs']\
00139                      +"\nError: list mode test has failed on image "+input_file
00140     
00141         if ( results==None \
00142              or (isinstance(results,bool) and results==False )\
00143              or (isinstance(results,dict) and results=={} ) ):
00144             retValue['success']=False
00145             retValue['error_msgs']=retValue['error_msgs']\
00146                      +"\nError: list mode test has failed on image "+input_file\
00147                      +"\nThe results are: "+str(results)
00148     
00149         ################################################################
00150         # Summary mode
00151         casalog.post( "Testing SUMMARY mode", "NORMAL4" );
00152         results=None
00153         try:
00154             results = imhead( input_file, 'summary' )
00155         except:
00156             retValue['success']=False
00157             retValue['error_msgs']=retValue['error_msgs']\
00158                      +"\nError: summary mode test has failed on image "+input_file
00159     
00160         if ( results==None \
00161              or (isinstance(results,bool) and results==False )\
00162              or (isinstance(results,dict) and results=={} ) ):
00163             retValue['success']=False
00164             retValue['error_msgs']=retValue['error_msgs']\
00165                      +"\nError: summary mode test has failed on image "+input_file\
00166                      +"\nThe results are: "+str(results)
00167     
00168     
00169         ################################################################
00170         # History mode
00171         casalog.post( "Testing HISTORY mode", "NORMAL4" );
00172         results=None
00173         try:
00174             results = imhead( input_file, 'history' )
00175         except:
00176             retValue['success']=False
00177             retValue['error_msgs']=retValue['error_msgs']\
00178                      +"\nError: history mode test has failed on image "+input_file
00179     
00180         if ( results==None \
00181              or (isinstance(results,bool) and results==False )\
00182              or (isinstance(results,dict) and results=={} ) ):
00183             retValue['success']=False
00184             retValue['error_msgs']=retValue['error_msgs']\
00185                      +"\nError: history mode test has failed on image "+input_file\
00186                      +"\nThe results are: "+str(results)
00187     
00188         ################################################################
00189         # Fits mode
00190         #
00191         # Commented out since this isn't implemented yet!
00192         #casalog.post( "Testing FITS mode", "NORMAL4" );
00193         #results=None
00194         #try:
00195         #    results = imhead( input_file, 'fits' )
00196         #except:
00197         #    retValue['success']=False
00198         #    retValue['error_msgs']=retValue['error_msgs']\
00199         #             +"\nError: fits mode test has failed on image "+input_file
00200         #
00201         #if ( results==None \
00202         #     or (isinstance(results,bool) and results==False )\
00203         #     or (isinstance(results,dict) and results=={} ) ):
00204         #    retValue['success']=False
00205         #    retValue['error_msgs']=retValue['error_msgs']\
00206         #             +"\nError: fits mode test has failed on image "+input_file\
00207         #             +"\nThe results are: "+str(results)
00208         #    
00209     
00210     
00211         ################################################################
00212         # Get mode
00213         casalog.post( "Testing GET  mode", "NORMAL4" );
00214         results=None
00215         try:
00216             results = imhead( input_file, 'get', 'telescope' )
00217         except:
00218             retValue['success']=False
00219             retValue['error_msgs']=retValue['error_msgs']\
00220                      +"\nError: get mode test has failed on image "+input_file
00221     
00222         if ( results==None \
00223              or (isinstance(results,bool) and results==False )\
00224              or (isinstance(results,dict) and results=={} ) ):
00225             retValue['success']=False
00226             retValue['error_msgs']=retValue['error_msgs']\
00227                      +"\nError: get mode test has failed on image "+input_file\
00228                      +"\nThe results are: "+str(results)
00229     
00230     
00231         ################################################################
00232         # Put mode
00233         casalog.post( "Testing PUT mode", "NORMAL4" );
00234         results=None
00235         try:
00236             results = imhead( input_file, 'put', 'lastupdated', 'today' )
00237         except:
00238             retValue['success']=False
00239             retValue['error_msgs']=retValue['error_msgs']\
00240                      +"\nError: put mode test has failed on image "+input_file
00241     
00242         if ( results==None \
00243              or (isinstance(results,bool) and results==False )\
00244              or (isinstance(results,dict) and results=={} ) ):
00245             retValue['success']=False
00246             retValue['error_msgs']=retValue['error_msgs']\
00247                      +"\nError: put mode test has failed on image "+input_file\
00248                      +"\nThe results are: "+str(results)
00249     
00250         ################################################################
00251         # Del mode
00252         casalog.post( "Testing DEL mode", "NORMAL4" );
00253         results=None
00254         try:
00255             results = imhead( input_file, 'del', 'lastupdated')
00256         except:
00257             retValue['success']=False
00258             retValue['error_msgs']=retValue['error_msgs']\
00259                      +"\nError: del mode test has failed on image "+input_file
00260     
00261         if ( results==None \
00262              or (isinstance(results,bool) and results==False )\
00263              or (isinstance(results,dict) and results=={} ) ):
00264             retValue['success']=False
00265             retValue['error_msgs']=retValue['error_msgs']\
00266                      +"\nError: del mode test has failed on image "+input_file\
00267                      +"\nThe results are: "+str(results)    
00268     
00269     
00270         ################################################################
00271         # Add mode
00272         casalog.post( "Testing ADD mode", "NORMAL4" );
00273         results=None
00274         try:
00275             results = imhead( input_file, 'add', 'garbage', "added while testing imhead task.")
00276         except:
00277             retValue['success']=False
00278             retValue['error_msgs']=retValue['error_msgs']\
00279                      +"\nError: add mode test has failed on image "+input_file
00280     
00281         if ( results==None \
00282              or (isinstance(results,bool) and results==False )\
00283              or (isinstance(results,dict) and results=={} ) ):
00284             retValue['success']=False
00285             retValue['error_msgs']=retValue['error_msgs']\
00286                      +"\nError: add mode test has failed on image "+input_file\
00287                      +"\nThe results are: "+str(results)    
00288     
00289     
00290         ################################################################
00291         # Empty mode
00292         results=None
00293         try:
00294             results = imhead( input_file, '' )
00295         except:
00296             pass
00297         else:
00298             if ( results!=None \
00299                  and ( (isinstance(results,bool) and results==True )\
00300                  or (isinstance(results,dict) and results!={} ) ) ):
00301                 retValue['success']=False
00302                 retValue['error_msgs']=retValue['error_msgs']\
00303                          +"\nError: empty mode was not detected as invalid!"
00304     
00305     
00306         ################################################################
00307         # Empty mode
00308         results=None
00309         try:
00310             results = imhead( input_file, 2.2 )
00311         except:
00312             pass
00313         else:
00314             if ( results!=None \
00315                  and ( (isinstance(results,bool) and results==True )\
00316                  or (isinstance(results,dict) and results!={} ) ) ):
00317                 retValue['success']=False
00318                 retValue['error_msgs']=retValue['error_msgs']\
00319                          +"\nError: mode='2.2' was not detected as invalid!"
00320                 
00321     
00322         ################################################################
00323         # bad mode
00324         results=None
00325         try:
00326             results = imhead( input_file, 'bad' )
00327         except:
00328             pass
00329         else:
00330             if ( results!=None \
00331                  and ( (isinstance(results,bool) and results==True )\
00332                  or (isinstance(results,dict) and results!={} ) ) ):
00333                 retValue['success']=False
00334                 retValue['error_msgs']=retValue['error_msgs']\
00335                          +"\nError: 'bad' mode was not detected!"
00336     
00337         self.assertTrue(retValue['success'],retValue['error_msgs'])
00338         
00339     ###########################################################################
00340     # NAME: set_get_test
00341     #
00342     # SHORT DESCRIPTION: Set/get a variety of header items make sure each
00343     #                    of them work
00344     #
00345     # DESCRIPTION: Call each of the modes to make sure they work.
00346     #              The VALID hditems tested are: object, imtype, telescope,
00347     #                 observer, date-obs, equinox, rest frequency, projection,
00348     #                 beam major axis, beam minor axis, beam position angle,
00349     #                 beam unit, coord axis type. num pixels for coord axis,
00350     #                 coord axis reference value, coord axis delta,
00351     #                 coord axis units
00352     # 
00353     #              The INVALID hditems used are: '', and bad
00354     #
00355     ############################################################################
00356     def test_set_get(self):
00357         '''Imhead: test put/get modes'''
00358         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }    
00359         casalog.post( "Staring imhead get/put tests!", "NORMAL2" )
00360         
00361         # Test the set/get value routines.  All of them
00362     
00363         #######  OBJECT  #############
00364         val   = None
00365         newval= None
00366         try:
00367             val = imhead( input_file, 'get', 'object' )
00368             testval = 'theCoolObject'
00369             imhead( input_file, 'put', 'object', testval )
00370             newval = imhead( input_file, 'get', 'object' )
00371             got = imhead( input_file, 'get', 'object' )
00372             self.assertTrue(got['value'] == testval)
00373             if ( val != None ):
00374                 imhead( input_file, 'put', 'object', val['value'] )
00375         except:
00376             self.assertTrue(False)
00377         else:
00378             self.assertFalse( val!=None and val == newval )
00379     
00380         #######  IMTYPE  #############
00381         val   = None
00382         newval= None
00383         try:
00384             val=imhead( input_file, 'get', 'imtype' )
00385             imhead( input_file, 'put', 'imtype', '' )
00386             newval=imhead( input_file, 'get', 'imtype' )
00387             if ( val != None ):
00388                 imhead( input_file, 'put', 'imtype', val['value'] )
00389         except:
00390             self.assertTrue(False)
00391         else:        
00392             self.assertFalse( val!=None and val == newval )
00393     
00394         #######  TELESCOPE  #############
00395         val   = None
00396         newval= None
00397         try:
00398             val=imhead( input_file, 'get', 'telescope' )
00399             imhead( input_file, 'put', 'telescope', 'myTelescope' )
00400             newval=imhead( input_file, 'get', 'telescope' )
00401             if ( val != None ):        
00402                 imhead( input_file, 'put', 'telescope', val['value'] )
00403         except:
00404             self.assertTrue(False)
00405         else:
00406             self.assertFalse( val!=None and val == newval )
00407          
00408         #######  OBSERVER  #############
00409         val   = None
00410         newval= None
00411         try:
00412             val=imhead( input_file, 'get', 'observer' )
00413             imhead( input_file, 'put', 'observer', 'me' )
00414             newval=imhead( input_file, 'get', 'observer' )
00415             if ( val != None ):
00416                 imhead( input_file, 'put', 'observer', val['value'] )
00417         except:
00418             self.assertTrue(False)
00419         else:        
00420             self.assertFalse( val!=None and val == newval )
00421     
00422         #######  DATE-OBS  #############
00423         val   = None
00424         newval= None
00425         try:
00426             val=imhead( input_file, 'get', 'date-obs' )
00427             imhead( input_file, 'put', 'date-obs', '2007/06/20/00:00:00' )
00428             newval=imhead( input_file, 'get', 'date-obs' )
00429             if ( val != None ):
00430                 imhead( input_file, 'put', 'date-obs', str(val['value'])+str(val['unit']) )
00431         except:
00432             self.assertTrue(False)
00433         else:
00434             self.assertFalse( val!=None and val == newval )
00435               
00436         #######  EQUINOX  #############
00437         val   = None
00438         newval= None
00439         try:                    
00440             val=imhead( input_file, 'get', 'equinox' )
00441             imhead( input_file, 'put', 'equinox', 'B1950' )
00442             newval=imhead( input_file, 'get', 'equinox' )
00443             if ( val != None ):
00444                 imhead( input_file, 'put', 'equinox', val['value'] )
00445         except:
00446             self.assertTrue(False)
00447         else:
00448             self.assertFalse(val!=None and val == newval )
00449         #######  RESTFREQUENCY  #############
00450         val   = None
00451         newval= None
00452         try:                    
00453             val=imhead( input_file, 'get', 'restfreq' )
00454             print "*** val " + str(val)
00455             imhead( input_file, 'put', 'restfreq', '1.421GHz' )
00456             print "kk"
00457             imhead( input_file, 'put', 'restfreq', '15.272GHz, 1.67GHz' )
00458             print "yy"
00459             newval=imhead( input_file, 'get', 'restfreq' )
00460             print "newval " + str(newval)
00461             if ( val != None ):  
00462                 print "val2 " + str(val)      
00463                 #imhead( input_file, 'put', 'restfreq', str(val['value'])+str(val['unit']) )
00464                 imhead( input_file, 'put', 'restfreq', val['value'])
00465                 print "done"
00466         except Exception, instance:
00467             print str(instance)
00468             self.assertTrue(False)
00469         else:
00470             self.assertFalse( val!=None and val == newval )
00471                 
00472     
00473     
00474         #######  PROJECTION  #############
00475         val   = None
00476         newval= None
00477         try:                    
00478             val=imhead( input_file, 'get', 'projection' )
00479             imhead( input_file, 'put', 'projection', 'TAN' )
00480             newval=imhead( input_file, 'get', 'projection' )
00481             if ( val != None ):
00482                 imhead( input_file, 'put', 'projection', val['value'] )            
00483         except:
00484             self.assertTrue(False)
00485         else:
00486             self.assertFalse( val!=None and val == newval )
00487         #######  BEAM MAJOR  #############
00488         val   = None
00489         newval= None
00490         try:                    
00491             val=imhead( input_file, 'get', 'beammajor' )
00492             imhead( input_file, 'put', 'beammajor', '12arcsec')
00493             newval=imhead( input_file, 'get', 'beammajor' )
00494             if ( val != None ):        
00495                 imhead( input_file, 'put', 'beammajor', val )
00496         except:
00497             self.assertTrue(False)
00498         else:
00499             self.assertFalse( val!=None and val != newval )
00500          
00501         #######  BEAM  MINOR #############
00502         val   = None
00503         newval= None
00504         try:                    
00505             val=imhead( input_file, 'get', 'beamminor' )
00506             imhead( input_file, 'put', 'beamminor', '24arcsec' )
00507             newval=imhead( input_file, 'get', 'beamminor' )
00508             if ( val != None ):
00509                 imhead( input_file, 'put', 'beamminor', str(val['value'])+str(val['unit']) )
00510         except:
00511             retValue['success']=False
00512             retValue['error_msgs']=retValue['error_msgs']\
00513               +"\nError: set/get beam's minor axis failed in image "+input_file
00514         else:
00515             if ( val!=None and val == newval ) :
00516                 retValue['success']=False
00517                 retValue['error_msgs']=retValue['error_msgs']\
00518                         +"\nError Get/Set beam's minor axis Failed"\
00519                         +"\n       Original value: "+str(val)\
00520                         +"\n       Current value:  "+str(newval)\
00521                         +"\n       Expected value: '24arcsec'"
00522     
00523     
00524         #######  BEAM PA #############
00525         val   = None
00526         newval= None
00527         try:                    
00528             val=imhead( input_file, 'get', 'beampa' )
00529             imhead( input_file, 'put', 'beampa', '0.5deg' )
00530             newval=imhead( input_file, 'get', 'beampa' )
00531             if ( val != None ):        
00532                 imhead( input_file, 'put', 'beampa', str(val['value'])+str(val['unit']) )
00533         except:
00534             retValue['success']=False
00535             retValue['error_msgs']=retValue['error_msgs']\
00536               +"\nError: set/get beam's position angle failed in image "+input_file
00537         else:
00538             if ( val!=None and val == newval ) :
00539                 retValue['success']=False
00540                 retValue['error_msgs']=retValue['error_msgs']\
00541                         +"\nError Get/Set beam's position angle Failed"\
00542                         +"\n       Original value: "+str(val)\
00543                         +"\n       Current value:  "+str(newval)\
00544                         +"\n       Expected value: '0.5deg'"
00545     
00546            
00547         #######  BUNIT  #############
00548         val   = None
00549         newval= None
00550         try:                                
00551             val=imhead( input_file, 'get', 'bunit' )
00552             imhead( input_file, 'put', 'bunit', 'kJy/beam' )
00553             newval=imhead( input_file, 'get', 'bunit' )
00554             if ( val != None ):
00555                 imhead( input_file, 'put', 'bunit', str(val['value'])+str(val['unit']) )
00556         except:
00557             retValue['success']=False
00558             retValue['error_msgs']=retValue['error_msgs']\
00559               +"\nError: set/get beam's unit failed in image "+input_file
00560         else:
00561             if ( val!=None and val == newval ) :
00562                 retValue['success']=False
00563                 retValue['error_msgs']=retValue['error_msgs']\
00564                         +"\nError Get/Set beam's unit Failed"\
00565                         +"\n       Original value: "+str(val)\
00566                         +"\n       Current value:  "+str(newval)\
00567                         +"\n       Expected value: 'kJy/beam'"
00568     
00569     
00570         #######  CTYPE3  #############
00571         val   = None
00572         newval= None
00573         try:                                
00574             val=imhead( input_file, 'get', 'ctype3' )
00575             imhead( input_file, 'put', 'ctype3', 'Declination' )
00576             newval=imhead( input_file, 'get', 'ctype3' )
00577             if ( val != None ):
00578                 imhead( input_file, 'put', 'ctype3', val['value'] )
00579         except:
00580             retValue['success']=False
00581             retValue['error_msgs']=retValue['error_msgs']\
00582               +"\nError: set/get ctype3 failed in image "+input_file
00583         else:
00584             if ( val!=None and val == newval ) :
00585                 retValue['success']=False
00586                 retValue['error_msgs']=retValue['error_msgs']\
00587                         +"\nError Get/Set ctype3 unit Failed"\
00588                         +"\n       Original value: "+str(val)\
00589                         +"\n       Current value:  "+str(newval)\
00590                         +"\n       Expected value: 'Declination'"
00591         
00592     
00593         #######  CRPIX2  #############
00594         val   = None
00595         newval= None
00596         try:                                
00597             val=imhead( input_file, 'get', 'crpix2' )
00598             imhead( input_file, 'put', 'crpix2', '64.0' )
00599             newval=imhead( input_file, 'get', 'crpix2' )
00600             if ( val != None ):
00601                 imhead( input_file, 'put', 'crpix2', val['value'] )
00602         except:
00603             retValue['success']=False
00604             retValue['error_msgs']=retValue['error_msgs']\
00605               +"\nError: set/get beam's unit failed in image "+input_file
00606         else:
00607             if ( val!=None and val == newval ) :
00608                 retValue['success']=False
00609                 retValue['error_msgs']=retValue['error_msgs']\
00610                         +"\nError Get/Set beam's unit Failed"\
00611                         +"\n       Original value: "+str(val)\
00612                         +"\n       Current value:  "+str(newval)\
00613                         +"\n       Expected value: '64.0'"
00614     
00615     
00616         #######  CRVAL4  #############
00617         val   = None
00618         newval= None
00619         try:                                
00620             val=imhead( input_file, 'get', 'crval4' )
00621             imhead( input_file, 'put', 'crval4', '1.6' )
00622             newval=imhead( input_file, 'get', 'crval4' )
00623             if ( val != None ):
00624                 imhead( input_file, 'put', 'crval4', val['value'] )
00625         except:
00626             retValue['success']=False
00627             retValue['error_msgs']=retValue['error_msgs']\
00628               +"\nError: set/get crval4 failed in image "+input_file
00629         else:
00630             if ( val!=None and val == newval ) :
00631                 retValue['success']=False
00632                 retValue['error_msgs']=retValue['error_msgs']\
00633                         +"\nError Get/Set crval4 Failed"\
00634                         +"\n       Original value: "+str(val)\
00635                         +"\n       Current value:  "+str(newval)\
00636                         +"\n       Expected value: '1.6'"
00637     
00638     
00639         #######  CDELT4  #############
00640         val   = None
00641         newval= None
00642         try:                                
00643             val=imhead( input_file, 'get', 'cdelt4' )
00644             imhead( input_file, 'put', 'cdelt4', '2.5'  )
00645             newval=imhead( input_file, 'get', 'cdelt4' )
00646             if ( val != None ):
00647                 imhead( input_file, 'put', 'cdelt4', val['value'] )
00648         except:
00649             retValue['success']=False
00650             retValue['error_msgs']=retValue['error_msgs']\
00651               +"\nError: set/get cdelt4 failed in image "+input_file
00652         else:
00653             if ( val!=None and val == newval ) :
00654                 retValue['success']=False
00655                 retValue['error_msgs']=retValue['error_msgs']\
00656                         +"\nError Get/Set cdelt4 Failed"\
00657                         +"\n       Original value: "+str(val)\
00658                         +"\n       Current value:  "+str(newval)\
00659                         +"\n       Expected value: '2.5'"
00660     
00661     
00662     
00663         #######  CUNIT1  #############
00664         val   = None
00665         newval= None
00666         try:                                
00667             val=imhead( input_file, 'get', 'cunit1' )
00668             imhead( input_file, 'put', 'cunit1', 'deg' )
00669             newval=imhead( input_file, 'get', 'cunit1' )
00670             if ( val != None ):
00671                 imhead( input_file, 'put', 'cunit1', val['value'] )
00672         except:
00673             retValue['success']=False
00674             retValue['error_msgs']=retValue['error_msgs']\
00675               +"\nError: set/get cunit1 failed in image "+input_file
00676         else:
00677             if ( val!=None and val == newval ) :
00678                 retValue['success']=False
00679                 retValue['error_msgs']=retValue['error_msgs']\
00680                         +"\nError Get/Set cunit1 Failed"\
00681                         +"\n       Original value: "+str(val)\
00682                         +"\n       Current value:  "+str(newval)\
00683                         +"\n       Expected value: 'deg'"
00684     
00685     
00686         ################################################################
00687         # bad header time
00688         results=None
00689         try:
00690             results = imhead( input_file, 'get', 'bad' )
00691         except:
00692             pass
00693         else:
00694             if ( results!=None \
00695                  and ( (isinstance(results,bool) and results==True )\
00696                  or (isinstance(results,dict) and results!={} ) ) ):
00697                 retValue['success']=False
00698                 retValue['error_msgs']=retValue['error_msgs']\
00699                          +"\nError: 'bad' header item was not detected!"
00700     
00701         # This will get a default value of '', one could argue
00702         # that this maybe should not succeed, but this way is ok too.
00703         results=None
00704         try:
00705             results = imhead( input_file, 'put', 'bad' )
00706         except:
00707             retValue['success']=False
00708             retValue['error_msgs']=retValue['error_msgs']\
00709                  +"\nError: 'bad' header item was not placed in the header!"
00710     
00711         try:
00712             results = imhead( input_file, 'get', 'bad' )
00713         except:
00714             retValue['success']=False
00715             retValue['error_msgs']=retValue['error_msgs']\
00716                  +"\nError: 'bad' header item was not found after put."
00717             
00718     
00719     
00720     
00721         ################################################################
00722         # Empty header item
00723         results=None
00724         try:
00725             results = imhead( input_file, 'get', '' )
00726         except:
00727             pass
00728         else:
00729             if ( results!=None \
00730                  and ( (isinstance(results,bool) and results==True )\
00731                  or (isinstance(results,dict) and results!={} ) ) ):
00732                 retValue['success']=False
00733                 retValue['error_msgs']=retValue['error_msgs']\
00734                          +"\nError: Empty header item was not detected!"
00735     
00736         self.assertTrue(retValue['success'],retValue['error_msgs'])
00737     
00738     
00739     ###########################################################################
00740     # NAME: add_del_test
00741     #
00742     # SHORT DESCRIPTION: Set/get a variety of header items make sure each
00743     #                    of them work
00744     #
00745     # DESCRIPTION: Call each of the modes to make sure they work.
00746     #              The VALID hditems tested are: ???
00747     # 
00748     #              The INVALID hditems used are: TODO
00749     #
00750     ############################################################################
00751     def test_add_del(self):
00752         '''Imhead: test add/del modes'''
00753         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }    
00754         casalog.post( "Starting imhead add/del tests!", "NORMAL2" )
00755         
00756         #######  BEAM  #############
00757         val_maj = val_min = val_pa   = None
00758         newval= None
00759         try:                                
00760             val_maj=imhead( input_file, 'get', 'beammajor' )
00761             val_min=imhead( input_file, 'get', 'beamminor' )
00762             val_pa=imhead( input_file, 'get', 'beampa' )
00763             imhead( input_file, 'del', 'beammajor' )
00764     
00765             try:
00766                 newval=imhead( input_file, 'get', 'beammajor' )
00767             except:
00768                 pass
00769             if ( val_maj != None ):
00770                 imhead( input_file, 'add', 'beammajor', \
00771                         str(val_maj['value'])+str(val_maj['unit']) )
00772             if ( val_min != None ):            
00773                 imhead( input_file, 'add', 'beamminor', \
00774                         str(val_min['value'])+str(val_min['unit']) )
00775             if ( val_pa != None ):
00776                 imhead( input_file, 'add', 'beampa', \
00777                         str(val_pa['value'])+str(val_pa['unit']) )
00778         except:
00779             self.assertTrue(false)
00780         else:
00781             self.assertFalse(
00782                 isinstance(newval,str)
00783                 and newval.replace(' ','').find('NotKnown') > -1
00784             )
00785     
00786     
00787         #######  OBJECT  #############
00788         val = None
00789         newval= None
00790         try:                                    
00791             val=imhead( input_file, 'get', 'object' )
00792             imhead( input_file, 'del', 'object' )
00793             newval=imhead( input_file, 'get', 'object' )
00794             print "*** val " + str(val)
00795             print "*** new " + str(newval)
00796         except:
00797             self.assertTrue(False)
00798         else:
00799             self.assertTrue( val != newval )
00800     
00801         #######  IMTYPE  #############
00802         val = None
00803         newval= None
00804         try:                                    
00805             val=imhead( input_file, 'get', 'imtype' )
00806             imhead( input_file, 'del', 'imtype' )
00807             newval=imhead( input_file, 'get', 'imtype' )
00808     
00809             try:
00810                 newval=imhead( input_file, 'get', 'imtype' )
00811             except:
00812                 pass
00813             if ( val != None ):
00814                 imhead( input_file, 'add', 'imtype', val['value'] )
00815         except:
00816             self.assertTrue(False)
00817         else:
00818             self.assertTrue( val != newval )
00819     
00820         #######  USER DEFINED KEYWORD #############
00821         ###
00822         ### Add, get, put, and del a user defined
00823         ### keyword to the header.
00824         initVal="Testing the addition of user defined keyword"
00825         val=None
00826         try:
00827             imhead( input_file, 'add', 'test', initVal )
00828             val=imhead( input_file, 'get', 'test', val )
00829         except:
00830             self.assertTrue(False)
00831         else:
00832             self.assertTrue( initVal == val['value'] )
00833                 
00834         val2='Updated user keyword'
00835         newval=None
00836         try:    
00837             imhead( input_file, 'put', 'test', val2 )
00838             newval=imhead( input_file, 'get', 'test' )
00839         except:
00840             self.assertTrue(False)
00841         else:
00842             self.assertTrue( initVal == val['value'] )
00843     
00844         casalog.post( 'The next operation will cause an exception.', 'WARN' )
00845         results=None
00846         try:
00847             imhead( input_file, 'del', 'test')
00848         except:
00849             self.assertTrue(False)
00850         try:
00851             results=imhead( input_file, 'get', 'test' )
00852         except:
00853             pass
00854         else:
00855             self.assertFalse(
00856                 results!=None
00857                  and (
00858                     (isinstance(results,bool) and results==True )
00859                     or (isinstance(results,dict) and results!={} )
00860                 )
00861             )
00862         self.assertTrue(retValue['success'],retValue['error_msgs'])
00863     
00864     
00865     ###########################################################################
00866     # NAME: restored_test
00867     #
00868     # SHORT DESCRIPTION: Verify that the file has been resorted
00869     #                    of them work
00870     #
00871     # DESCRIPTION: Check to see if we have the original values again.  All
00872     #              of the tests should change the values back to what they
00873     #              were intially.
00874     #
00875     ############################################################################
00876     
00877     ##########  CHECK ORIG VALUES ############
00878     #
00879                 
00880     def test_values_restored(self):
00881         '''Imhead: test if original values are restored'''
00882         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }    
00883         casalog.post( "Starting imhead restored values test!", "NORMAL2" )
00884     
00885         if(os.path.exists(input_file_copy)):
00886             os.system('rm -rf ' +input_file_copy)
00887             
00888         shutil.copytree(input_file, input_file_copy)
00889         
00890         try:
00891             cur_hdr=imhead( input_file, 'list' )
00892             orig_hdr=imhead( input_file_copy, 'list' )
00893         except:
00894             retValue['success']=False
00895             retValue['error_msgs']=retValue['error_msgs']\
00896               +"\nError: Unable to get values from files: "\
00897               +"\n\t"+input_file\
00898               +", and\n\t"+input_file_copy
00899         else:
00900             for key in orig_hdr.keys() :
00901                 #print "CHECKING IF "+key+" has CHANGED VALUE."
00902                 #print "has key: ", cur_hdr.has_key(key)
00903                 #print "ORIG value: ", orig_hdr[key]
00904                 #print "CURRENT value: ", cur_hdr[key]
00905     
00906                 match = False
00907                 if ( cur_hdr.has_key(key) ):
00908                     if ( isinstance( orig_hdr[key], numpy.ndarray ) ):
00909                         if ( not isinstance( cur_hdr[key], numpy.ndarray ) ):
00910                             match = False
00911                         else:
00912                             results = orig_hdr[key] == orig_hdr[key]
00913                             if ( results.all() ):
00914                                 match = True
00915                     else:
00916                         if( isinstance( cur_hdr[key], float )\
00917                             and abs(cur_hdr[key]-orig_hdr[key]) < 0.00000001 ):
00918                             # Allow for rounding errors when changing values.
00919                             match = True
00920                         elif ( cur_hdr[key]==orig_hdr[key] ):
00921                             match = True
00922                         
00923     
00924                 if ( not match ):
00925                     retValue['success']=False
00926                     retValue['error_msgs']=retValue['error_msgs']\
00927                          +"\nError: "+str(key)+" has not been restored!"\
00928                          +"\n         Current value:   "+str(cur_hdr[key])\
00929                          +"\n         Expected value:  "+str(orig_hdr[key])
00930     
00931         ## LIST values again.  They should be the same as at the start of the test
00932         #imhead( input_file, 'list' )
00933         #print "\nCheck that the values listed are the same as at the"
00934         #print "beginning of the test"
00935         
00936         self.assertTrue(retValue['success'],retValue['error_msgs'])
00937 
00938     def test_types(self):
00939         '''Imhead: CAS-3285 Test types of keys'''
00940         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }    
00941         ima = input_file
00942         for i in range(4):
00943             cdelt = imhead(imagename=ima, mode='get', hdkey='cdelt'+str(i+1))
00944             if (type(cdelt['value']) == str):
00945                 retValue['success'] = False
00946                 retValue['error_msgs'] = retValue['error_msgs']\
00947                     +"Error: CDELT"+str(i+1)+" type should not be a string."
00948                     
00949                 self.assertTrue(retValue['success'], retValue['error_msgs']) 
00950     
00951 
00952     def test_units(self):
00953         '''Imhead: CAS-3285 Test if units are printed'''
00954         retValue = {'success': True, 'msgs': "", 'error_msgs': '' }    
00955         ima = input_file
00956         cdelt1 = imhead(imagename=ima, mode='get', hdkey='cdelt1')
00957         if (cdelt1['unit'] == ''):
00958             retValue['success'] = False
00959             retValue['error_msgs'] = retValue['error_msgs']\
00960                 +"Error: CDELT1"+" has no units."
00961             
00962         cdelt2 = imhead(imagename=ima, mode='get', hdkey='cdelt2')
00963         if (cdelt2['unit'] == ''):
00964             retValue['success'] = False
00965             retValue['error_msgs'] = retValue['error_msgs']\
00966                 +"Error: CDELT2"+" has no units."
00967                 
00968         cdelt4 = imhead(imagename=ima, mode='get', hdkey='cdelt4')
00969         if (cdelt4['unit'] == ''):
00970             retValue['success'] = False
00971             retValue['error_msgs'] = retValue['error_msgs']\
00972                 +"Error: CDELT4"+" has no units."
00973             
00974         self.assertTrue(retValue['success'], retValue['error_msgs'])
00975 
00976     def test_list(self):
00977         '''Imhead: CAS-3300 Test the printing of some keywords in list mode'''
00978         ima = input_file
00979         logfile = 'imhead.log'
00980         open(logfile,'w').close
00981         casalog.setlogfile(logfile)
00982         imhead(imagename=ima, mode='list')
00983         # restore logfile
00984         casalog.setlogfile('casapy.log')
00985         
00986         cmd = 'grep cdelt1 imhead.log'
00987         out = commands.getoutput(cmd)
00988         self.assertNotEqual(out,'','The keyword cdelt1 is not listed')
00989         cmd = 'grep crval1 imhead.log'
00990         out = commands.getoutput(cmd)
00991         self.assertNotEqual(out,'','The keyword crval1 is not listed')
00992         cmd = 'grep ctype1 imhead.log'
00993         out = commands.getoutput(cmd)
00994         self.assertNotEqual(out,'','The keyword ctype1 is not listed')
00995         cmd = 'grep cunit1 imhead.log'
00996         out = commands.getoutput(cmd)
00997         self.assertNotEqual(out,'','The keyword cunit1 is not listed')
00998         cmd = 'grep shape imhead.log'
00999         out = commands.getoutput(cmd)
01000         self.assertNotEqual(out,'','The keyword shape is not listed')
01001         
01002     def test_shape(self):
01003         '''Imhead: CAS-3301: Keyword shape should be included in the output'''
01004         shape = imhead(imagename=input_file,mode='get',hdkey='shape')
01005         self.assertTrue(shape,'Keyword shape is missing')
01006         self.assertTrue(shape['value'].all(), 'Not all values of shape exist.')
01007         self.assertEqual(shape['value'][0],256, 'Value of shape[0] should be 256 and it is %s instead.'
01008                          %shape['value'][0])
01009         
01010     def test_CAS4355(self):
01011         """ verify puthead can take sesigimal values where appropriate (CAS-4355)"""
01012         myia = iatool()
01013         image = "cas4355.im"
01014         myia.fromshape(image, [10,10])
01015         ra = "14:33:10.5"
01016         key = "crval1"
01017         imhead(imagename=image, mode="put", hdkey=key, hdvalue=ra)
01018         got = imhead(imagename=image, mode="get", hdkey=key)
01019         got = qa.canon(got)
01020         exp = qa.canon(qa.toangle(ra))
01021         self.assertTrue(qa.getunit(got) == qa.getunit(exp))
01022         self.assertTrue(abs(qa.getvalue(got)/qa.getvalue(exp) - 1) < 1e-8)
01023         
01024         dec = "-22.44.55.66"
01025         key = "crval2"
01026         imhead(imagename=image, mode="put", hdkey=key, hdvalue=dec)
01027         got = imhead(imagename=image, mode="get", hdkey=key)
01028         got = qa.canon(got)
01029         exp = qa.canon(qa.toangle(dec))
01030         self.assertTrue(qa.getunit(got) == qa.getunit(exp))
01031         self.assertTrue(abs(qa.getvalue(got)/qa.getvalue(exp) - 1) < 1e-8)
01032         
01033 def suite():
01034     return [imhead_test]    
01035