casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
test_sdplot.py
Go to the documentation of this file.
00001 import os
00002 import sys
00003 import shutil
00004 from __main__ import default
00005 from tasks import *
00006 from taskinit import *
00007 import unittest
00008 import time
00009 import filecmp
00010 from matplotlib import pylab as pl
00011 
00012 from sdplot import sdplot
00013 import asap as sd
00014 from asap.scantable import is_scantable
00015 
00016 class sdplot_unittest_base:
00017     """
00018     Base class for sdplot unit test
00019     """
00020     taskname = 'sdplot'
00021     # Data path of input/output
00022     datapath = os.environ.get('CASAPATH').split()[0] + \
00023                '/data/regression/unittest/' + taskname + '/'
00024     # directories to save figure
00025     prevdir = datapath+'prev_sdplot'
00026     currdir = os.path.abspath('curr_sdplot')
00027     # Minimum data size of figure allowed
00028     minsize = 20000
00029     # save figure for reference?
00030     saveref = True
00031     # GUI settings
00032     oldgui = sd.rcParams['plotter.gui']  # store previous GUI setting
00033     usegui = False   # need to set GUI status constant to compare
00034 
00035     # compare two figures
00036     def _checkOutFile( self, filename, compare=False ):
00037         self.assertTrue(os.path.exists(filename),"'%s' does not exists." % filename)
00038         self.assertTrue(os.path.isfile(filename),\
00039                         "Not a regular file. (A directory?): %s" % filename)
00040         self.assertTrue(os.path.getsize(filename) > self.minsize,\
00041                         "Data to small (less than %d KB): %s" % \
00042                         (int(self.minsize/1000), filename))
00043         prevfig = self.prevdir+'/'+filename
00044         currfig = self.currdir+'/'+filename
00045         if compare and os.path.exists(prevfig):
00046             # The unit test framework doesn't allow saving previous results
00047             # This test is not run.
00048             msg = "Compareing with previous plot:\n"
00049             msg += " (prev) %s\n (new) %s" % (prevfig,os.path.abspath(filename))
00050             casalog.post(msg,'INFO')
00051             self.assertTrue(filecmp.cmp(prevfig,os.path.abspath(filename),shallow=False))
00052         shutil.move(filename,currfig)
00053 
00054         # Save the figure for future comparison if possible.
00055         if os.path.exists(self.prevdir) and self.saveref:
00056             try:
00057                 casalog.post("copying %s to %s" % (currfig,prevfig),'INFO')
00058                 shutil.copyfile(currfig, prevfig)
00059             except IOError:
00060                 msg = "Unable to copy Figure '"+filename+"' to "+self.prevdir+".\n"
00061                 msg += "The figure remains in "+self.prevdir
00062                 casalog.post(msg,'WARN')
00063 
00064     # get plot information
00065     def _get_plot_info( self ):
00066         retdic = {}
00067         ax0 = sd.plotter._plotter.subplots[0]['axes']
00068         retdic['npanel'] = len(sd.plotter._plotter.subplots)
00069         retdic['nstack'] = len(sd.plotter._plotter.subplots[0]['lines'])
00070         retdic['rows'] = sd.plotter._rows
00071         retdic['cols'] = sd.plotter._cols
00072         retdic['xlabel'] = ax0.get_xlabel()
00073         retdic['xlim'] = ax0.get_xlim()
00074         retdic['ylabel'] = ax0.get_ylabel()
00075         retdic['ylim'] = ax0.get_ylim()
00076         retdic['title0'] = ax0.get_title()
00077         retdic['label0'] = ax0.get_lines()[0].get_label()
00078         return retdic
00079 
00080     def _mergeDict( self, base, add ):
00081         self.assertTrue(isinstance(base,dict) and \
00082                         isinstance(add, dict),\
00083                         "Need to specify two dictionaries to merge")
00084         retdic = base.copy()
00085         for key, val in add.iteritems():
00086             retdic[key] = val
00087         return retdic
00088         
00089 
00090     # compare two dictionaries
00091     def _compareDictVal( self, testdict, refdict, reltol=1.0e-5, complist=None ):
00092         self.assertTrue(isinstance(testdict,dict) and \
00093                         isinstance(refdict, dict),\
00094                         "Need to specify two dictionaries to compare")
00095         if complist:
00096             keylist = complist
00097         else:
00098             keylist = refdict.keys()
00099         
00100         for key in keylist:
00101             self.assertTrue(testdict.has_key(key),\
00102                             msg="%s is not defined in the current results."\
00103                             % key)
00104             self.assertTrue(refdict.has_key(key),\
00105                             msg="%s is not defined in the reference data."\
00106                             % key)
00107             testval = self._to_list(testdict[key])
00108             refval = self._to_list(refdict[key])
00109             self.assertTrue(len(testval)==len(refval),"Number of elemnets differs.")
00110             for i in range(len(testval)):
00111                 if isinstance(refval[i],str):
00112                     self.assertTrue(testval[i]==refval[i],\
00113                                     msg="%s[%d] differs: %s (expected: %s) " % \
00114                                     (key, i, str(testval[i]), str(refval[i])))
00115                 else:
00116                     self.assertTrue(self._isInAllowedRange(testval[i],refval[i],reltol),\
00117                                     msg="%s[%d] differs: %s (expected: %s) " % \
00118                                     (key, i, str(testval[i]), str(refval[i])))
00119             del testval, refval
00120             
00121     def _isInAllowedRange( self, testval, refval, reltol=1.0e-5 ):
00122         """
00123         Check if a test value is within permissive relative difference from refval.
00124         Returns a boolean.
00125         testval & refval : two numerical values to compare
00126         reltol           : allowed relative difference to consider the two
00127                            values to be equal. (default 0.01)
00128         """
00129         denom = refval
00130         if refval == 0:
00131             if testval == 0:
00132                 return True
00133             else:
00134                 denom = testval
00135         rdiff = (testval-refval)/denom
00136         del denom,testval,refval
00137         return (abs(rdiff) <= reltol)
00138 
00139     def _to_list( self, input ):
00140         """
00141         Convert input to a list
00142         If input is None, this method simply returns None.
00143         """
00144         import numpy
00145         listtypes = (list, tuple, numpy.ndarray)
00146         if input == None:
00147             return None
00148         elif type(input) in listtypes:
00149             return list(input)
00150         else:
00151             return [input]
00152     
00153 #####
00154 # Tests on bad parameters and exceptions
00155 #####
00156 class sdplot_errorTest( sdplot_unittest_base, unittest.TestCase ):
00157     """
00158     Test bad input parameters and exceptions
00159     
00160     The list of tests:
00161       test_default    --- default parameters (raises an error)
00162 
00163     Note: input data is generated from a single dish regression data,
00164     'OrionS_rawACSmod', as follows:
00165       default(sdcal)
00166       sdcal(infile='OrionS_rawACSmod',scanlist=[20,21,22,23],
00167                 calmode='ps',tau=0.09,outfile=self.infile)
00168     """
00169     # Input and output names
00170     infile = 'OrionS_rawACSmod_cal2123.asap'
00171     outfile = sdplot_unittest_base.taskname + '_testErr.png'
00172     badid = 99
00173     badstr = "bad"
00174 
00175     def setUp( self ):
00176         # switch on/off GUI
00177         sd.rcParams['plotter.gui'] = self.usegui
00178         sd.plotter.__init__()
00179         # Fresh copy of input data
00180         if os.path.exists(self.infile):
00181             shutil.rmtree(self.infile)
00182         shutil.copytree(self.datapath+self.infile, self.infile)
00183         default(sdplot)
00184 
00185     def tearDown( self ):
00186         if (os.path.exists(self.infile)):
00187             shutil.rmtree(self.infile)
00188         # restore GUI setting
00189         sd.rcParams['plotter.gui'] = self.oldgui
00190         sd.plotter.__init__()
00191 
00192     # Actual tests
00193     def test_default( self ):
00194         """test_default: Default parameters (should Fail)"""
00195         result = sdplot()
00196         self.assertFalse(result)
00197 
00198     def test_overwrite( self ):
00199         """test_overwrite: Specify existing output file name with overwrite=False (task script raises Exception)"""
00200         res1 = sdplot(infile=self.infile,outfile=self.outfile)
00201         self.assertEqual(res1,None)
00202         try:
00203             res2 = sdplot(infile=self.infile,
00204                           outfile=self.outfile,overwrite=False)
00205             self.assertTrue(False,
00206                             msg='The task must throw exception')
00207         except Exception, err:
00208             pos=str(err).find("Output file '%s' exist." % self.outfile)
00209             self.assertNotEqual(pos,-1,
00210                                 msg='Unexpected exception was thrown: %s'%(str(err)))
00211     def test_badSelection( self ):
00212         """test_badSelection: Invalid data selection (no data selected) """
00213         # the AipsError raised in cpp is caught and rethrown in
00214         # the middle of task script
00215         iflist = [self.badid]
00216         try:
00217             result = sdplot(infile=self.infile,iflist=iflist)
00218             self.assertTrue(False,
00219                             msg='The task must throw exception')
00220         except Exception, err:
00221             pos=str(err).find("Selection contains no data. Not applying it.")
00222             self.assertNotEqual(pos,-1,
00223                                 msg='Unexpected exception was thrown: %s'%(str(err)))
00224 
00225     def test_noTweight( self ):
00226         """test_noTweight: Time averaging without tweight"""
00227         # this error is handled in task interface in sdplot
00228         result = sdplot(infile=self.infile,timeaverage=True,tweight='')
00229         self.assertFalse(result)
00230 
00231     def test_noPweight( self ):
00232         """test_noPweight: Polarization averaging without pweight"""
00233         # this error is handled in task interface in sdplot
00234         result = sdplot(infile=self.infile,polaverage=True,pweight='')
00235         self.assertFalse(result)
00236 
00237     def test_badLincat( self ):
00238         """test_badLinecat: Invalid line catalog (cpp throws AipsError)"""
00239         # The aips error thrown in cpp is caught and rethrown at the end
00240         # of task script
00241         type = "spectra"
00242         linecat = self.badstr
00243         try:
00244             result = sdplot(infile=self.infile,plottype=type,linecat=linecat)
00245             self.assertTrue(False,
00246                             msg='The task must throw exception')
00247         except Exception, err:
00248             pos=str(err).find("No match.")
00249             self.assertNotEqual(pos,-1,
00250                                 msg='Unexpected exception was thrown: %s'%(str(err)))
00251 
00252     def test_badStack( self ):
00253         """test_badStack: Invalid stack mode (python tool raises TypeError)"""
00254         type = "spectra"
00255         stack = " "
00256         try:
00257             result = sdplot(infile=self.infile,plottype=type,stack=stack)
00258             self.assertTrue(False,
00259                             msg='The task must throw exception')
00260         except Exception, err:
00261             pos=str(err).find("Invalid mode")
00262             self.assertNotEqual(pos,-1,
00263                                 msg='Unexpected exception was thrown: %s'%(str(err)))
00264 
00265 
00266 #####
00267 # Tests on basic task parameters
00268 #####
00269 class sdplot_basicTest( sdplot_unittest_base, unittest.TestCase ):
00270     """
00271     Test plot parameters only. Least data filterings and no averaging.
00272     
00273     The list of tests:
00274       testplot01-03 --- possible plot types
00275       testplot04-07 --- possible axes (spectral plotting)
00276       testplot08-12 --- panelling and stacking (spectral plotting)
00277       testplot13-15 --- plot range control (spectral plotting)
00278       testplot16-19 --- plot style control (spectral plotting)
00279       testplot20-21 --- header control (spectral plotting)
00280       testplot22-23,28 --- plot layout control (spectral plotting)
00281       testplot24-25 --- row panelling or stacking (spectral plotting)
00282       testplot26-27 --- flag application
00283       testplot29-30 --- restfreq
00284 
00285     Note: input data is generated from a single dish regression data,
00286     'OrionS_rawACSmod', as follows:
00287       default(sdcal)
00288       sdcal(infile='OrionS_rawACSmod',scanlist=[20,21,22,23],
00289                 calmode='ps',tau=0.09,outfile=self.infile)
00290     """
00291     # Input and output names
00292     infile = 'OrionS_rawACSmod_cal2123.asap'
00293     figroot = sdplot_unittest_base.taskname + '_test'
00294     figsuff = '.png'
00295     fig=None
00296     baseinfo = {'npanel': 2, 'nstack': 2,
00297                'xlabel': 'Channel',
00298                'ylabel': 'Brightness Temperature (K)'}
00299 
00300     def setUp( self ):
00301         # switch on/off GUI
00302         sd.rcParams['plotter.gui'] = self.usegui
00303         sd.plotter.__init__()
00304         # Fresh copy of input data
00305         if os.path.exists(self.infile):
00306             shutil.rmtree(self.infile)
00307         shutil.copytree(self.datapath+self.infile, self.infile)
00308         # Generate directory to save figures
00309         if not os.path.exists(self.currdir):
00310             os.makedirs(self.currdir)
00311         # Create a directory to store the figures for future comparison
00312         if (not os.path.exists(self.prevdir)) and self.saveref:
00313             try: os.makedirs(self.prevdir)
00314             except OSError:
00315                 msg = "Unable to create directory, "+self.prevdir+".\n"
00316                 msg += "Plot figures will remain in "+self.currdir
00317                 casalog.post(msg,'WARN')
00318         
00319         default(sdplot)
00320 
00321     def tearDown( self ):
00322         if (os.path.exists(self.infile)):
00323             shutil.rmtree(self.infile)
00324         # restore GUI setting
00325         sd.rcParams['plotter.gui'] = self.oldgui
00326         sd.plotter.__init__()
00327 
00328     # Actual tests
00329     def testplot01( self ):
00330         """Test 1: test plot type --- az/el"""
00331         tid = "01"
00332         infile = self.infile
00333         outfile = self.figroot+tid+self.figsuff
00334         plottype = 'azel'
00335         header = False
00336         result = sdplot(infile=self.infile,plottype=plottype,header=header,
00337                         outfile=outfile)
00338         # Tests
00339         self.assertEqual(result,None)
00340         self.assertEqual(len(pl.gcf().axes),2)
00341         self.assertEqual(len(pl.gca().get_lines()),1)
00342         self.assertEqual(pl.gca().get_xlabel(),'Time (UT [hour])')
00343         self.assertEqual(pl.gca().get_ylabel(),'Az [deg.]')
00344         self._checkOutFile(outfile)
00345 
00346     def testplot02( self ):
00347         """Test 2: test plot type --- pointing"""
00348         tid = "02"
00349         infile = self.infile
00350         outfile = self.figroot+tid+self.figsuff
00351         plottype = 'pointing'
00352         header = False
00353         result = sdplot(infile=self.infile,plottype=plottype,header=header,
00354                         outfile=outfile)
00355         # Tests
00356         self.assertEqual(result,None)
00357         self.assertEqual(len(pl.gcf().axes),1)
00358         self.assertEqual(len(pl.gca().get_lines()),1)
00359         self.assertEqual(pl.gca().get_xlabel(),'RA [deg.]')
00360         self.assertEqual(pl.gca().get_ylabel(),'Declination [deg.]')
00361         self._checkOutFile(outfile)
00362 
00363     def testplot03( self ):
00364         """
00365         Test 3: test plot type --- total power (row # vs total power)
00366         """
00367         tid = "03"
00368         infile = self.infile
00369         outfile = self.figroot+tid+self.figsuff
00370         plottype = 'totalpower'
00371         header = False
00372         result = sdplot(infile=infile,plottype=plottype,header=header,
00373                         outfile=outfile)
00374         locinfo = {'npanel': 1, 'nstack': 1,
00375                    'xlabel': 'row number',
00376                    'ylabel': 'Brightness Temperature (K)'}
00377         # Tests
00378         self.assertEqual(result,None)
00379         currinfo = self._get_plot_info()
00380         self._compareDictVal(currinfo, locinfo)
00381         self._checkOutFile(outfile)
00382 
00383     def testplot04( self ):
00384         """
00385         Test 4: test possible axes for spectral plotting --- specunit='channel'
00386         """
00387         tid = "04"
00388         infile = self.infile
00389         outfile = self.figroot+tid+self.figsuff
00390         specunit = 'channel'
00391         fluxunit = 'K'
00392         stack = 'p'
00393         panel = 'i'
00394         iflist = [0,2]
00395         header = False
00396         result = sdplot(infile=infile,specunit=specunit,fluxunit=fluxunit,
00397                         stack=stack,panel=panel,iflist=iflist,
00398                         header=header,outfile=outfile)
00399         # Tests
00400         self.assertEqual(result,None)
00401         currinfo = self._get_plot_info()
00402         self._compareDictVal(currinfo, self.baseinfo)
00403         self._checkOutFile(outfile)
00404 
00405     def testplot05( self ):
00406         """
00407         Test 5: test possible axes for spectral plotting --- specunit='GHz'
00408         """
00409         tid = "05"
00410         infile = self.infile
00411         outfile = self.figroot+tid+self.figsuff
00412         specunit = 'GHz'
00413         fluxunit = 'K'
00414         stack = 'p'
00415         panel = 'i'
00416         iflist = [0,2]
00417         header = False
00418         result = sdplot(infile=infile,specunit=specunit,fluxunit=fluxunit,
00419                         stack=stack,panel=panel,iflist=iflist,
00420                         header=header,outfile=outfile)
00421         locinfo = {'xlabel': 'LSRK Frequency (%s)' % specunit}
00422         refinfo = self._mergeDict(self.baseinfo,locinfo)
00423         # Tests
00424         self.assertEqual(result,None)
00425         currinfo = self._get_plot_info()
00426         self._compareDictVal(currinfo, refinfo)
00427         self._checkOutFile(outfile)
00428 
00429     def testplot06( self ):
00430         """
00431         Test 6: test possible axes for spectral plotting --- specunit='km/s'
00432         """
00433         tid = "06"
00434         infile = self.infile
00435         outfile = self.figroot+tid+self.figsuff
00436         specunit = 'km/s'
00437         fluxunit = 'K'
00438         stack = 'p'
00439         panel = 'i'
00440         iflist = [0,2]
00441         header = False
00442         result = sdplot(infile=infile,specunit=specunit,fluxunit=fluxunit,
00443                         stack=stack,panel=panel,iflist=iflist,
00444                         header=header,outfile=outfile)
00445         locinfo = {'xlabel': 'LSRK RADIO velocity (%s)' % (specunit)}
00446         refinfo = self._mergeDict(self.baseinfo,locinfo)
00447         # Tests
00448         self.assertEqual(result,None)
00449         currinfo = self._get_plot_info()
00450         self._compareDictVal(currinfo, refinfo)
00451         self._checkOutFile(outfile)
00452 
00453     def testplot07( self ):
00454         """
00455         Test 7: test possible axes for spectral plotting --- fluxunit='Jy'
00456         """
00457         tid = "07"
00458         outfile = self.figroot+tid+self.figsuff
00459         infile = self.infile
00460         specunit = 'channel'
00461         fluxunit = 'Jy'
00462         stack = 'p'
00463         panel = 'i'
00464         iflist = [0,2]
00465         header = False
00466         result = sdplot(infile=infile,specunit=specunit,fluxunit=fluxunit,
00467                         stack=stack,panel=panel,iflist=iflist,
00468                         header=header,outfile=outfile)
00469         locinfo = {'ylabel': 'Flux density (Jy)'}
00470         refinfo = self._mergeDict(self.baseinfo,locinfo)
00471         # Tests
00472         self.assertEqual(result,None)
00473         currinfo = self._get_plot_info()
00474         self._compareDictVal(currinfo, refinfo)
00475         self._checkOutFile(outfile)
00476 
00477     def testplot08( self ):
00478         """
00479         Test 8: test panelling and stacking (spectral plotting) --- panel='pol', stack='scan' (2px2s)
00480         """
00481         tid = "08"
00482         outfile = self.figroot+tid+self.figsuff
00483         infile = self.infile
00484         panel = 'pol'
00485         stack = 'scan'
00486         header = False
00487         result = sdplot(infile=infile,stack=stack,panel=panel,
00488                         header=header,outfile=outfile)
00489         locinfo = {'title0': 'XX', 'label0': 'Scan 21 (OrionS)'}
00490         refinfo = self._mergeDict(self.baseinfo,locinfo)
00491         # Tests
00492         self.assertEqual(result,None)
00493         currinfo = self._get_plot_info()
00494         self._compareDictVal(currinfo, refinfo)
00495         self._checkOutFile(outfile)
00496 
00497     def testplot09( self ):
00498         """
00499         Test 9: test panelling and stacking (spectral plotting) --- panel='scan', stack='if' (2px4s)
00500         """
00501         tid = "09"
00502         outfile = self.figroot+tid+self.figsuff
00503         infile = self.infile
00504         panel = 'scan'
00505         stack = 'if'
00506         header = False
00507         result = sdplot(infile=infile,stack=stack,panel=panel,
00508                         header=header,outfile=outfile)
00509         locinfo = {'nstack': 4,
00510                    'title0': 'Scan 21 (OrionS)', 'label0': 'IF0'}
00511         refinfo = self._mergeDict(self.baseinfo,locinfo)
00512         # Tests
00513         self.assertEqual(result,None)
00514         currinfo = self._get_plot_info()
00515         self._compareDictVal(currinfo, refinfo)
00516         self._checkOutFile(outfile)
00517 
00518     def testplot10( self ):
00519         """
00520         Test 10: test panelling and stacking (spectral plotting) --- panel='if', stack='time' (4px8s)
00521         """
00522         tid = "10"
00523         outfile = self.figroot+tid+self.figsuff
00524         infile = self.infile
00525         panel = 'if'
00526         stack = 'time'
00527         header = False
00528         result = sdplot(infile=infile,stack=stack,panel=panel,
00529                         header=header,outfile=outfile)
00530         locinfo = {'npanel': 4, 'nstack': 8,
00531                    'title0': 'IF0', 'label0': '2006/01/19/01:48:38'}
00532         refinfo = self._mergeDict(self.baseinfo,locinfo)
00533         # Tests
00534         self.assertEqual(result,None)
00535         currinfo = self._get_plot_info()
00536         self._compareDictVal(currinfo, refinfo)
00537         self._checkOutFile(outfile)
00538 
00539     def testplot11( self ):
00540         """
00541         Test 11: test panelling and stacking (spectral plotting) --- panel='time', stack='beam' (8px1s)
00542         """
00543         tid = "11"
00544         outfile = self.figroot+tid+self.figsuff
00545         infile = self.infile
00546         panel = 'time'
00547         stack = 'beam'
00548         header = False
00549         result = sdplot(infile=infile,stack=stack,panel=panel,
00550                         header=header,outfile=outfile)
00551         locinfo = {'npanel': 8,'nstack': 1,
00552                    'title0': '2006/01/19/01:48:38','label0': 'Beam 0'}
00553         refinfo = self._mergeDict(self.baseinfo,locinfo)
00554         # Tests
00555         self.assertEqual(result,None)
00556         currinfo = self._get_plot_info()
00557         self._compareDictVal(currinfo, refinfo)
00558         self._checkOutFile(outfile)
00559 
00560     def testplot12( self ):
00561         """
00562         Test 12: test panelling and stacking (spectral plotting) --- panel='beam', stack='pol' (1px2s)
00563         """
00564         tid = "12"
00565         outfile = self.figroot+tid+self.figsuff
00566         infile = self.infile
00567         panel = 'beam'
00568         stack = 'pol'
00569         header = False
00570         result = sdplot(infile=infile,stack=stack,panel=panel,
00571                         header=header,outfile=outfile)
00572         locinfo = {'npanel': 1,'nstack': 2,
00573                    'title0': 'Beam 0', 'label0': 'XX'}
00574         refinfo = self._mergeDict(self.baseinfo,locinfo)
00575         # Tests
00576         self.assertEqual(result,None)
00577         currinfo = self._get_plot_info()
00578         self._compareDictVal(currinfo, refinfo)
00579         self._checkOutFile(outfile)
00580 
00581     def testplot13( self ):
00582         """
00583         Test 13: test plot range control for spectral plotting --- abscissa
00584         """
00585         tid = "13"
00586         outfile = self.figroot+tid+self.figsuff
00587         infile = self.infile
00588         iflist = [0]
00589         sprange = [3500,5000]
00590         header = False
00591         result = sdplot(infile=infile,iflist=iflist,sprange=sprange,
00592                         header=header,outfile=outfile)
00593         locinfo = {'npanel': 1,'nstack': 2,
00594                    'title0': 'IF0', 'label0': 'XX',
00595                    'xlim': sprange}
00596         refinfo = self._mergeDict(self.baseinfo,locinfo)
00597         # Tests
00598         self.assertEqual(result,None)
00599         currinfo = self._get_plot_info()
00600         self._compareDictVal(currinfo, refinfo)
00601         self._checkOutFile(outfile)
00602 
00603     def testplot14( self ):
00604         """
00605         Test 14: test plot range control for spectral plotting --- ordinate
00606         """
00607         tid = "14"
00608         outfile = self.figroot+tid+self.figsuff
00609         infile = self.infile
00610         iflist = [0]
00611         flrange = [0.,6.]
00612         header = False
00613         result = sdplot(infile=infile,iflist=iflist,flrange=flrange,
00614                         header=header,outfile=outfile)
00615         locinfo = {'npanel': 1, 'ylim': flrange}
00616         refinfo = self._mergeDict(self.baseinfo,locinfo)
00617         # Tests
00618         self.assertEqual(result,None)
00619         currinfo = self._get_plot_info()
00620         self._compareDictVal(currinfo, refinfo)
00621         self._checkOutFile(outfile)
00622 
00623     def testplot15( self ):
00624         """
00625         Test 15: test plot range control for spectral plotting --- both
00626         """
00627         tid = "15"
00628         outfile = self.figroot+tid+self.figsuff
00629         infile = self.infile
00630         iflist = [0]
00631         sprange = [3500,5000]
00632         flrange = [0.,6.]
00633         header = False
00634         result = sdplot(infile=infile,iflist=iflist,sprange=sprange,
00635                         header=header,flrange=flrange,outfile=outfile)
00636         locinfo = {'npanel': 1, 'xlim': sprange, 'ylim': flrange}
00637         refinfo = self._mergeDict(self.baseinfo,locinfo)
00638         # Tests
00639         self.assertEqual(result,None)
00640         currinfo = self._get_plot_info()
00641         self._compareDictVal(currinfo, refinfo)
00642         self._checkOutFile(outfile)
00643 
00644     def testplot16( self ):
00645         """
00646         Test 16: plot style control (spectral plotting) --- histogram
00647         """
00648         tid = "16"
00649         outfile = self.figroot+tid+self.figsuff
00650         infile = self.infile
00651         iflist = [0]
00652         sprange = [3900,4300]
00653         histogram = True
00654         header = False
00655         result = sdplot(infile=infile,iflist=iflist,sprange=sprange,
00656                         header=header,histogram=histogram,outfile=outfile)
00657         locinfo = {'npanel': 1, 'xlim': sprange}
00658         refinfo = self._mergeDict(self.baseinfo,locinfo)
00659         # Tests
00660         self.assertEqual(result,None)
00661         currinfo = self._get_plot_info()
00662         self._compareDictVal(currinfo, refinfo)
00663         self._checkOutFile(outfile)
00664 
00665     def testplot17( self ):
00666         """
00667         Test 17: plot style control (spectral plotting) --- colormap
00668         """
00669         tid = "17"
00670         outfile = self.figroot+tid+self.figsuff
00671         infile = self.infile
00672         iflist = [0]
00673         sprange = [3900,4300]
00674         colormap = "pink orange"
00675         header = False
00676         result = sdplot(infile=infile,iflist=iflist,sprange=sprange,
00677                         header=header,colormap=colormap,outfile=outfile)
00678         locinfo = {'npanel': 1, 'xlim': sprange}
00679         refinfo = self._mergeDict(self.baseinfo,locinfo)
00680         # Tests
00681         self.assertEqual(result,None)
00682         currinfo = self._get_plot_info()
00683         self._compareDictVal(currinfo, refinfo)
00684         self._checkOutFile(outfile)
00685 
00686     def testplot18( self ):
00687         """
00688         Test 18: plot style control (spectral plotting) --- linewidth
00689         """
00690         tid = "18"
00691         outfile = self.figroot+tid+self.figsuff
00692         infile = self.infile
00693         iflist = [0]
00694         sprange = [3900,4300]
00695         linewidth = 3
00696         header = False
00697         result = sdplot(infile=infile,iflist=iflist,sprange=sprange,
00698                         header=header,linewidth=linewidth,outfile=outfile)
00699         locinfo = {'npanel': 1, 'xlim': sprange}
00700         refinfo = self._mergeDict(self.baseinfo,locinfo)
00701         # Tests
00702         self.assertEqual(result,None)
00703         currinfo = self._get_plot_info()
00704         self._compareDictVal(currinfo, refinfo)
00705         self._checkOutFile(outfile)
00706 
00707     def testplot19( self ):
00708         """
00709         Test 19: plot style control (spectral plotting) --- linestyle
00710         """
00711         tid = "19"
00712         outfile = self.figroot+tid+self.figsuff
00713         infile = self.infile
00714         iflist = [0]
00715         sprange = [3900,4300]
00716         linewidth = 2
00717         linestyles = "dotted dashdot"
00718         header = False
00719         result = sdplot(infile=infile,iflist=iflist,sprange=sprange,
00720                         linewidth=linewidth,linestyles=linestyles,
00721                         header=header,outfile=outfile)
00722         locinfo = {'npanel': 1, 'xlim': sprange}
00723         refinfo = self._mergeDict(self.baseinfo,locinfo)
00724         # Tests
00725         self.assertEqual(result,None)
00726         currinfo = self._get_plot_info()
00727         self._compareDictVal(currinfo, refinfo)
00728         self._checkOutFile(outfile)
00729 
00730     def testplot20( self ):
00731         """
00732         Test 20: header control (spectral plotting) --- larger fontsize
00733         """
00734         tid = "20"
00735         outfile = self.figroot+tid+self.figsuff
00736         infile = self.infile
00737         iflist = [0,2]
00738         headsize = 11
00739         result = sdplot(infile=infile,iflist=iflist,headsize=headsize,
00740                         outfile=outfile)
00741         # Tests
00742         self.assertEqual(result,None)
00743         currinfo = self._get_plot_info()
00744         self._compareDictVal(currinfo, self.baseinfo)
00745         self._checkOutFile(outfile, compare=False)
00746 
00747     def testplot21( self ):
00748         """
00749         Test 21: header control (spectral plotting) --- header on
00750         """
00751         tid = "21"
00752         outfile = self.figroot+tid+self.figsuff
00753         infile = self.infile
00754         iflist = [0,2]
00755         result = sdplot(infile=infile,iflist=iflist,
00756                         outfile=outfile)
00757         # Tests
00758         self.assertEqual(result,None)
00759         currinfo = self._get_plot_info()
00760         self._compareDictVal(currinfo, self.baseinfo)
00761         self._checkOutFile(outfile, compare=False)
00762 
00763     def testplot22( self ):
00764         """
00765         Test 22: plot layout control (spectral plotting) --- panel margin
00766         """
00767         tid = "22"
00768         outfile = self.figroot+tid+self.figsuff
00769         infile = self.infile
00770         iflist = [0,2]
00771         plotstyle = True
00772         margin = [0.15,0.3,0.85,0.7,0.25,0.25]
00773         header = False
00774         result = sdplot(infile=infile,iflist=iflist,plotstyle=plotstyle,
00775                         margin=margin,header=header,outfile=outfile)
00776         # Tests
00777         self.assertEqual(result,None)
00778         currinfo = self._get_plot_info()
00779         self._compareDictVal(currinfo, self.baseinfo)
00780         self._checkOutFile(outfile)
00781 
00782     def testplot23( self ):
00783         """
00784         Test 23: plot layout control (spectral plotting) --- legend location (left bottom)
00785         """
00786         tid = "23"
00787         outfile = self.figroot+tid+self.figsuff
00788         infile = self.infile
00789         iflist = [0,2]
00790         plotstyle = True
00791         legendloc = 3
00792         header = False
00793         result = sdplot(infile=infile,iflist=iflist,plotstyle=plotstyle,
00794                         legendloc=legendloc,header=header,outfile=outfile)
00795         # Tests
00796         self.assertEqual(result,None)
00797         currinfo = self._get_plot_info()
00798         self._compareDictVal(currinfo, self.baseinfo)
00799         self._checkOutFile(outfile)
00800 
00801     def testplot24( self ):
00802         """
00803         Test 24: test panelling and stacking (spectral plotting) --- panel='row' (16px1s)
00804         """
00805         tid = "24"
00806         outfile = self.figroot+tid+self.figsuff
00807         infile = self.infile
00808         panel = 'row'
00809         header = False
00810         result = sdplot(infile=infile,panel=panel,
00811                         header=header,outfile=outfile)
00812         locinfo = {'npanel': 16, 'nstack': 1,
00813                    'title0': 'row 0', 'label0': 'XX'}
00814         refinfo = self._mergeDict(self.baseinfo,locinfo)
00815         # Tests
00816         self.assertEqual(result,None)
00817         currinfo = self._get_plot_info()
00818         self._compareDictVal(currinfo, refinfo)
00819         self._checkOutFile(outfile)
00820 
00821     def testplot25( self ):
00822         """
00823         Test 25: test panelling and stacking (spectral plotting) --- panel='scan', stack='row' (1px16s)
00824         """
00825         tid = "25"
00826         outfile = self.figroot+tid+self.figsuff
00827         infile = self.infile
00828         stack = 'row'
00829         header = False
00830         result = sdplot(infile=infile,stack=stack,
00831                         header=header,outfile=outfile)
00832         locinfo = {'npanel': 1, 'nstack': 16,
00833                    'title0': '', 'label0': 'row 0'}
00834         refinfo = self._mergeDict(self.baseinfo,locinfo)
00835         # Tests
00836         self.assertEqual(result,None)
00837         currinfo = self._get_plot_info()
00838         self._compareDictVal(currinfo, refinfo)
00839         self._checkOutFile(outfile)
00840 
00841     def testplot26( self ):
00842         """
00843         Test 26: test handling of FLAGROW
00844         """
00845         from asap import scantable
00846         tid = "26"
00847         outfile = self.figroot+tid+self.figsuff
00848         ### flag rows=[0,3,6,9,12,15]
00849         infile = "orion_flagrow.asap"
00850         scan = scantable(filename=self.infile,average=False)
00851         scan.flag_row(rows=[0,3,6,9,12,15])
00852         scan.save(name=infile,format='ASAP')
00853         #
00854         panel = 'row'
00855         stack = 'scan'
00856         header = False
00857         result = sdplot(infile=infile,panel=panel,stack=stack,
00858                         header=header,outfile=outfile)
00859         self.assertEqual(result,None)
00860         self._checkOutFile(outfile)
00861 
00862     def testplot27( self ):
00863         """
00864         Test 27: test handling of FLAGTRA
00865         """
00866         from asap import scantable
00867         tid = "27"
00868         outfile = self.figroot+tid+self.figsuff
00869         ### flag channels [7168,8191]
00870         infile = "orion_flagchan7168to8191.asap"
00871         scan = scantable(filename=self.infile,average=False)
00872         scan.set_unit('channel')
00873         msk = scan.create_mask([7168,8191])
00874         scan.flag(mask=msk)
00875         scan.save(name=infile,format='ASAP')
00876         #
00877         panel = 'row'
00878         header = False
00879         result = sdplot(infile=infile,panel=panel,
00880                         header=header,outfile=outfile)
00881         self.assertEqual(result,None)
00882         self._checkOutFile(outfile)
00883 
00884     def testplot28( self ):
00885         """
00886         Test 28: plot layout control (spectral plotting) --- panel layout
00887         """
00888         tid = "28"
00889         outfile = self.figroot+tid+self.figsuff
00890         infile = self.infile
00891         iflist = [0,2]
00892         panel = 'r'
00893         plotstyle = True
00894         subplot = 24
00895         header = False
00896         result = sdplot(infile=infile,iflist=iflist,plotstyle=plotstyle,
00897                         subplot=subplot,header=header,outfile=outfile)
00898         locinfo = {'rows': 2, 'cols': 4}
00899         refinfo = self._mergeDict(self.baseinfo,locinfo)
00900         # Tests
00901         self.assertEqual(result,None)
00902         currinfo = self._get_plot_info()
00903         self._compareDictVal(currinfo, refinfo)
00904         self._checkOutFile(outfile)
00905 
00906     def testplot29( self ):
00907         """
00908         Test 29: plot with user defined restfreq (a list of num and qauntity)
00909         """
00910         tid = "29"
00911         outfile = self.figroot+tid+self.figsuff
00912         infile = self.infile
00913         iflist = [1,2]
00914         specunit = 'km/s'
00915         restfreq = ['45.3GHz', 44.075e9]
00916         panel = 'i'
00917         header = False
00918         result = sdplot(infile=infile,iflist=iflist,panel = panel,
00919                         specunit=specunit,restfreq=restfreq,
00920                         header=header,outfile=outfile)
00921         locinfo = {'xlim': (-170.62517234590837, 160.27007370505743),
00922                    'xlabel': 'LSRK RADIO velocity (km/s)',
00923                    'title0': 'IF1', 'label0': 'XX'}
00924         refinfo = self._mergeDict(self.baseinfo,locinfo)
00925         # Tests
00926         self.assertEqual(result,None)
00927         currinfo = self._get_plot_info()
00928         self._compareDictVal(currinfo, refinfo)
00929         self._checkOutFile(outfile)
00930 
00931     def testplot30( self ):
00932         """
00933         Test 30: plot with user defined restfreq (a list of dict)
00934         """
00935         tid = "30"
00936         outfile = self.figroot+tid+self.figsuff
00937         infile = self.infile
00938         iflist = [2]
00939         specunit = 'km/s'
00940         restfreq = [{'name': 'ch3oh', 'value': 44.075e9}]
00941         panel = 'i'
00942         header = False
00943         result = sdplot(infile=infile,iflist=iflist,panel = panel,
00944                         specunit=specunit,restfreq=restfreq,
00945                         header=header,outfile=outfile)
00946         locinfo = {'npanel': 1, 'xlabel': 'LSRK RADIO velocity (km/s)',
00947                    'xlim': (-169.54464299991017, 170.54735123960856),
00948                    'title0': 'IF2'}
00949         refinfo = self._mergeDict(self.baseinfo,locinfo)
00950         # Tests
00951         self.assertEqual(result,None)
00952         currinfo = self._get_plot_info()
00953         self._compareDictVal(currinfo, refinfo)
00954         self._checkOutFile(outfile)
00955 
00956 
00957 #####
00958 # Tests on scantable storage and insitu
00959 #####
00960 class sdplot_storageTest( sdplot_unittest_base, unittest.TestCase ):
00961     """
00962     Unit tests of task sdplot. Test scantable sotrage and insitu
00963     parameters
00964     
00965     The list of tests:
00966     testMT  --- storage = 'memory', insitu = True
00967     testMF  --- storage = 'memory', insitu = False
00968     testDT  --- storage = 'disk', insitu = True
00969     testDF  --- storage = 'disk', insitu = False
00970 
00971     Note: input data is generated from a single dish regression data,
00972     'OrionS_rawACSmod', as follows:
00973       default(sdcal)
00974       sdcal(infile='OrionS_rawACSmod',scanlist=[20,21,22,23],
00975                 calmode='ps',tau=0.09,outfile=self.infile)
00976     """
00977     # Input and output names
00978     infile = 'OrionS_rawACSmod_cal2123.asap'
00979     figroot = sdplot_unittest_base.taskname + '_store'
00980     figsuff = '.png'
00981     fig=None
00982 
00983     out_uc = {'spunit': 'km/s', 'flunit': 'Jy',\
00984               'frame': 'LSRD', 'doppler': 'OPTICAL'}
00985     refaxlabel = {'x': ("%s %s velocity (%s)" % \
00986                         (out_uc['frame'],out_uc['doppler'],out_uc['spunit'])),
00987                   'y': "Flux density (%s)" % out_uc['flunit']}
00988 
00989     # common parameter values
00990     fluxunit = out_uc['flunit']
00991     specunit = out_uc['spunit']
00992     frame = out_uc['frame']
00993     doppler = out_uc['doppler']
00994     stack = 'p'
00995     panel = 'i'
00996     iflist = [0,2]
00997     header = False
00998 
00999     def setUp( self ):
01000         # switch on/off GUI
01001         sd.rcParams['plotter.gui'] = self.usegui
01002         sd.plotter.__init__()
01003         # Fresh copy of input data
01004         if os.path.exists(self.infile):
01005             shutil.rmtree(self.infile)
01006         shutil.copytree(self.datapath+self.infile, self.infile)
01007         # Generate directory to save figures
01008         if not os.path.exists(self.currdir):
01009             os.makedirs(self.currdir)
01010         # Create a directory to store the figures for future comparison
01011         if (not os.path.exists(self.prevdir)) and self.saveref:
01012             try: os.makedirs(self.prevdir)
01013             except OSError:
01014                 msg = "Unable to create directory, "+self.prevdir+".\n"
01015                 msg += "Plot figures will remain in "+self.currdir
01016                 casalog.post(msg,'WARN')
01017         
01018         default(sdplot)
01019 
01020     def tearDown( self ):
01021         if (os.path.exists(self.infile)):
01022             shutil.rmtree(self.infile)
01023         # restore GUI setting
01024         sd.rcParams['plotter.gui'] = self.oldgui
01025         sd.plotter.__init__()
01026 
01027     # helper functions of tests
01028     def _get_unit_coord( self, scanname ):
01029         # Returns a dictionary which stores units and coordinates of a
01030         # scantable, scanname. Returned dictionary stores spectral
01031         # unit, flux unit, frequency frame, and doppler of scanname.
01032         self.assertTrue(os.path.exists(scanname),\
01033                         "'%s' does not exists." % scanname)
01034         self.assertTrue(is_scantable(scanname),\
01035                         "Input table is not a scantable: %s" % scanname)
01036         scan = sd.scantable(scanname, average=False,parallactify=False)
01037         retdict = {}
01038         retdict['spunit'] = scan.get_unit()
01039         retdict['flunit'] = scan.get_fluxunit()
01040         coord = scan._getcoordinfo()
01041         retdict['frame'] = coord[1]
01042         retdict['doppler'] = coord[2]
01043         return retdict
01044 
01045     def _get_uclist( self, stlist ):
01046         # Returns a list of dictionaries of units and coordinates of
01047         # a list of scantables in stlist. This method internally calls
01048         # _get_unit_coord(scanname).
01049         retlist = []
01050         for scanname in stlist:
01051             retlist.append(self._get_unit_coord(scanname))
01052         #print retlist
01053         return retlist
01054 
01055     def _comp_unit_coord( self, stlist, before):
01056         ### stlist: a list of scantable names
01057         if isinstance(stlist,str):
01058             stlist = [ stlist ]
01059         ### before: a return value of _get_uclist() before run
01060         if isinstance(before, dict):
01061             before = [ before ]
01062         if len(stlist) != len(before):
01063             raise Exception("Number of scantables in list is different from reference data.")
01064         self.assertTrue(isinstance(before[0],dict),\
01065                         "Reference data should be (a list of) dictionary")
01066 
01067         after = self._get_uclist(stlist)
01068         for i in range(len(stlist)):
01069             print "Testing units and coordinates of '%s'" %\
01070                   stlist[i]
01071             self._compareDictVal(after[i],before[i])
01072 
01073     def _check_axlabel( self, axlist, refval ):
01074         ip = 0
01075         print "Testing axes labels [expected: x = %s, y = %s]" % (refval['x'],refval['y'])
01076         for ax in axlist:
01077             xlab = ax.get_xlabel()
01078             ylab = ax.get_ylabel()
01079             self.assertTrue(xlab==refval['x'],\
01080                             "X-label differs (panel%d): %s (expected: %s)" %\
01081                             (ip,xlab,refval['x']))
01082             self.assertTrue(ylab==refval['y'],\
01083                             "Y-label differs (panel%d): %s (expected: %s)" %\
01084                             (ip,ylab,refval['y']))
01085             ip += 1
01086 
01087     def _get_axlist( self ):
01088         axlist = []
01089         for subp in sd.plotter._plotter.subplots:
01090             axlist.append(subp['axes'])
01091         return axlist
01092 
01093     # Actual tests
01094     def testMT( self ):
01095         """Storage Test MT: storage='memory' and insitu=T"""
01096         tid="MT"
01097         outfile = self.figroot+tid+self.figsuff
01098         
01099         # Backup units and coords of input scantable before run.
01100         initval = self._get_unit_coord(self.infile)
01101 
01102         sd.rcParams['scantable.storage'] = 'memory'
01103         sd.rcParams['insitu'] = True
01104         print "Running test with storage='%s' and insitu=%s" % \
01105               (sd.rcParams['scantable.storage'], str(sd.rcParams['insitu']))
01106         result = sdplot(infile=self.infile,specunit=self.specunit,\
01107                         fluxunit=self.fluxunit,frame=self.frame,\
01108                         doppler=self.doppler,stack=self.stack,panel=self.panel,\
01109                         iflist=self.iflist,header=self.header,outfile=outfile)
01110         # Test plot
01111         self.assertEqual(result,None)
01112         self._checkOutFile(outfile)
01113         axlist = self._get_axlist()
01114         self._check_axlabel(axlist,self.refaxlabel)
01115         # Compare units and coords of input scantable before/after run
01116         self._comp_unit_coord(self.infile,initval)
01117 
01118     def testMF( self ):
01119         """Storage Test MF: storage='memory' and insitu=F"""
01120         tid="MF"
01121         outfile = self.figroot+tid+self.figsuff
01122         
01123         # Backup units and coords of input scantable before run.
01124         initval = self._get_unit_coord(self.infile)
01125 
01126         sd.rcParams['scantable.storage'] = 'memory'
01127         sd.rcParams['insitu'] = False
01128         print "Running test with storage='%s' and insitu=%s" % \
01129               (sd.rcParams['scantable.storage'], str(sd.rcParams['insitu']))
01130         result = sdplot(infile=self.infile,specunit=self.specunit,\
01131                         fluxunit=self.fluxunit,frame=self.frame,\
01132                         doppler=self.doppler,stack=self.stack,panel=self.panel,\
01133                         iflist=self.iflist,header=self.header,outfile=outfile)
01134         # Test plot
01135         self.assertEqual(result,None)
01136         self._checkOutFile(outfile)
01137         axlist = self._get_axlist()
01138         self._check_axlabel(axlist,self.refaxlabel)
01139         # Compare units and coords of input scantable before/after run
01140         self._comp_unit_coord(self.infile,initval)
01141 
01142     def testDT( self ):
01143         """Storage Test DT: storage='disk' and insitu=T"""
01144         tid="DT"
01145         outfile = self.figroot+tid+self.figsuff
01146         
01147         # Backup units and coords of input scantable before run.
01148         initval = self._get_unit_coord(self.infile)
01149 
01150         sd.rcParams['scantable.storage'] = 'disk'
01151         sd.rcParams['insitu'] = True
01152         print "Running test with storage='%s' and insitu=%s" % \
01153               (sd.rcParams['scantable.storage'], str(sd.rcParams['insitu']))
01154         result = sdplot(infile=self.infile,specunit=self.specunit,\
01155                         fluxunit=self.fluxunit,frame=self.frame,\
01156                         doppler=self.doppler,stack=self.stack,panel=self.panel,\
01157                         iflist=self.iflist,header=self.header,outfile=outfile)
01158         # Test plot
01159         self.assertEqual(result,None)
01160         self._checkOutFile(outfile)
01161         axlist = self._get_axlist()
01162         self._check_axlabel(axlist,self.refaxlabel)
01163         # Compare units and coords of input scantable before/after run
01164         self._comp_unit_coord(self.infile,initval)
01165 
01166     def testDF( self ):
01167         """Storage Test DF: storage='disk' and insitu=F"""
01168         tid="DF"
01169         outfile = self.figroot+tid+self.figsuff
01170         
01171         # Backup units and coords of input scantable before run.
01172         initval = self._get_unit_coord(self.infile)
01173 
01174         sd.rcParams['scantable.storage'] = 'disk'
01175         sd.rcParams['insitu'] = False
01176         print "Running test with storage='%s' and insitu=%s" % \
01177               (sd.rcParams['scantable.storage'], str(sd.rcParams['insitu']))
01178         result = sdplot(infile=self.infile,specunit=self.specunit,\
01179                         fluxunit=self.fluxunit,frame=self.frame,\
01180                         doppler=self.doppler,stack=self.stack,panel=self.panel,\
01181                         iflist=self.iflist,header=self.header,outfile=outfile)
01182         # Test plot
01183         self.assertEqual(result,None)
01184         self._checkOutFile(outfile)
01185         axlist = self._get_axlist()
01186         self._check_axlabel(axlist,self.refaxlabel)
01187         # Compare units and coords of input scantable before/after run
01188         self._comp_unit_coord(self.infile,initval)
01189 
01190 #####
01191 # Tests on plottype='grid'
01192 #####
01193 class sdplot_gridTest( sdplot_unittest_base, unittest.TestCase ):
01194     """
01195     Unit tests of task sdplot. Test plottype='grid'
01196     
01197     The list of tests:
01198     testgrid01 - 08 --- test gridding
01199     testgrid09 - 11 --- test plot range
01200     testgrid12 - 14 --- test color and line
01201 
01202     Note: input data is generated from a intermediate data of
01203     single dish regression data,
01204     'FLS3a_calfs', as follows:
01205     sdsave(infile='FLS3a_calfs',outfile='FLS3a_calfs.asap')
01206     sdgrid(infiled=['FLS3a_calfs.asap'], ifno=0, npix=[6,6],
01207            outfile='FLS3a_calfs.6x6.asap')
01208     """
01209     # Input and output names
01210     infile = 'FLS3a_calfs.6x6.asap'
01211     #infile = 'FLS3a_calfs.asap'
01212     figroot = sdplot_unittest_base.taskname + '_grid'
01213     figsuff = '.png'
01214     fig=None
01215 
01216     # common parameter values
01217     type = 'grid'
01218     header = False
01219     pollist = [0]
01220     subplot = 66
01221     cell = ["0.033934774957430407rad","0.0080917391193671574rad"]
01222     center="J2000 17:17:58.94 +59.30.01.962"
01223 
01224     baseinfo = {'npanel': 36, 'nstack': 1,
01225                 'rows': 6, 'cols': 6,
01226                'xlabel': 'Channel',
01227                'ylabel': 'Brightness Temperature (K)'}
01228 
01229     # Test settings
01230     saveref = False
01231     usegui = False
01232     compare = False #(not usegui)
01233     
01234     def setUp( self ):
01235         # switch on/off GUI
01236         sd.rcParams['plotter.gui'] = self.usegui
01237         sd.plotter.__init__()
01238         # Fresh copy of input data
01239         if os.path.exists(self.infile):
01240             shutil.rmtree(self.infile)
01241         shutil.copytree(self.datapath+self.infile, self.infile)
01242         # Generate directory to save figures
01243         if not os.path.exists(self.currdir):
01244             os.makedirs(self.currdir)
01245         # Create a directory to store the figures for future comparison
01246         if (not os.path.exists(self.prevdir)) and self.saveref:
01247             try: os.makedirs(self.prevdir)
01248             except OSError:
01249                 msg = "Unable to create directory, "+self.prevdir+".\n"
01250                 msg += "Plot figures will remain in "+self.currdir
01251                 casalog.post(msg,'WARN')
01252         
01253         default(sdplot)
01254 
01255     def tearDown( self ):
01256         if (os.path.exists(self.infile)):
01257             shutil.rmtree(self.infile)
01258         # restore GUI setting
01259         sd.rcParams['plotter.gui'] = self.oldgui
01260         sd.plotter.__init__()
01261 
01262     # helper functions of tests
01263 
01264     # Actual tests
01265     def testgrid01( self ):
01266         """testgrid01: default gridding (1x1)"""
01267         tid="01"
01268         outfile = self.figroot+tid+self.figsuff
01269         result = sdplot(infile=self.infile, pollist=self.pollist,
01270                         plottype=self.type, header=self.header,
01271                         outfile=outfile)
01272         locinfo = {'npanel': 1, 'rows': 1, 'cols': 1,
01273                    'title0': 'J2000 17:17:58.9 +59.30.02.0'}
01274         refinfo = self._mergeDict(self.baseinfo,locinfo)
01275         # Tests
01276         self.assertEqual(result,None)
01277         currinfo = self._get_plot_info()
01278         self._compareDictVal(currinfo, refinfo)
01279         self._checkOutFile(outfile,self.compare)
01280 
01281     def testgrid02( self ):
01282         """testgrid02: default center"""
01283         tid="02"
01284         outfile = self.figroot+tid+self.figsuff
01285         cell = self.cell
01286         subplot = self.subplot
01287         result = sdplot(infile=self.infile, pollist=self.pollist,
01288                         plottype=self.type,
01289                         cell=cell, subplot=subplot,
01290                         header=self.header, outfile=outfile)
01291         locinfo = {}#'title0': 'J2000 17:17:58 +59.30.02.0'}
01292         refinfo = self._mergeDict(self.baseinfo,locinfo)
01293         # Tests
01294         self.assertEqual(result,None)
01295         currinfo = self._get_plot_info()
01296         self._compareDictVal(currinfo, refinfo)
01297         self._checkOutFile(outfile,self.compare)
01298 
01299     def testgrid03( self ):
01300         """testgrid03: default cell"""
01301         tid="03"
01302         outfile = self.figroot+tid+self.figsuff
01303         center = self.center
01304         subplot = self.subplot
01305         result = sdplot(infile=self.infile, pollist=self.pollist,
01306                         plottype=self.type, center=center,
01307                         subplot=subplot,
01308                         header=self.header, outfile=outfile)
01309         locinfo = {}#'title0': 'J2000 17:17:58 +59.30.02.0'}
01310         refinfo = self._mergeDict(self.baseinfo,locinfo)
01311         # Tests
01312         self.assertEqual(result,None)
01313         currinfo = self._get_plot_info()
01314         self._compareDictVal(currinfo, refinfo)
01315         self._checkOutFile(outfile,self.compare)
01316 
01317     def testgrid04( self ):
01318         """testgrid04: default subplot  (1x1)"""
01319         tid="04"
01320         outfile = self.figroot+tid+self.figsuff
01321         center = self.center
01322         cell = self.cell
01323         result = sdplot(infile=self.infile, pollist=self.pollist,
01324                         plottype=self.type, center=center,
01325                         cell=cell,
01326                         header=self.header, outfile=outfile)
01327         locinfo = {'npanel': 1, 'rows': 1, 'cols': 1,
01328                    'title0': 'J2000 17:17:58.9 +59.30.02.0'}
01329         refinfo = self._mergeDict(self.baseinfo,locinfo)
01330         # Tests
01331         self.assertEqual(result,None)
01332         currinfo = self._get_plot_info()
01333         self._compareDictVal(currinfo, refinfo)
01334         self._checkOutFile(outfile,self.compare)
01335 
01336     def testgrid05( self ):
01337         """testgrid05: test center (1x1)"""
01338         tid="05"
01339         outfile = self.figroot+tid+self.figsuff
01340         center = self.center
01341         result = sdplot(infile=self.infile, pollist=self.pollist,
01342                         plottype=self.type, center=center,
01343                         header=self.header, outfile=outfile)
01344         locinfo = {'npanel': 1, 'rows': 1, 'cols': 1,
01345                    'title0': 'J2000 17:17:58.9 +59.30.02.0'}
01346         refinfo = self._mergeDict(self.baseinfo,locinfo)
01347         # Tests
01348         self.assertEqual(result,None)
01349         currinfo = self._get_plot_info()
01350         self._compareDictVal(currinfo, refinfo)
01351         self._checkOutFile(outfile,self.compare)
01352 
01353     def testgrid06( self ):
01354         """testgrid06: test cell  (1x1)"""
01355         tid="06"
01356         outfile = self.figroot+tid+self.figsuff
01357         cell = self.cell
01358         result = sdplot(infile=self.infile, pollist=self.pollist,
01359                         plottype=self.type, cell=cell,
01360                         header=self.header, outfile=outfile)
01361         locinfo = {'npanel': 1, 'rows': 1, 'cols': 1,
01362                    'title0': 'J2000 17:17:58.9 +59.30.02.0'}
01363         refinfo = self._mergeDict(self.baseinfo,locinfo)
01364         # Tests
01365         self.assertEqual(result,None)
01366         currinfo = self._get_plot_info()
01367         self._compareDictVal(currinfo, refinfo)
01368         self._checkOutFile(outfile,self.compare)
01369 
01370     def testgrid07( self ):
01371         """testgrid07: test subplot"""
01372         tid="07"
01373         outfile = self.figroot+tid+self.figsuff
01374         subplot = self.subplot
01375         result = sdplot(infile=self.infile, pollist=self.pollist,
01376                         plottype=self.type, subplot=subplot,
01377                         header=self.header, outfile=outfile)
01378         locinfo = {}#'title0': 'J2000 17:17:58 +59.30.02.0'}
01379         refinfo = self._mergeDict(self.baseinfo,locinfo)
01380         # Tests
01381         self.assertEqual(result,None)
01382         currinfo = self._get_plot_info()
01383         self._compareDictVal(currinfo, refinfo)
01384         self._checkOutFile(outfile,self.compare)
01385 
01386     def testgrid08( self ):
01387         """testgrid08: test grid"""
01388         tid="08"
01389         outfile = self.figroot+tid+self.figsuff
01390         center = self.center
01391         cell = self.cell
01392         subplot = self.subplot
01393 
01394         result = sdplot(infile=self.infile, pollist=self.pollist,
01395                         plottype=self.type, center=center,
01396                         cell=cell, subplot=subplot,
01397                         header=self.header, outfile=outfile)
01398         locinfo = {}#'title0': 'J2000 17:17:58 +59.30.02.0'}
01399         refinfo = self._mergeDict(self.baseinfo,locinfo)
01400         # Tests
01401         self.assertEqual(result,None)
01402         currinfo = self._get_plot_info()
01403         self._compareDictVal(currinfo, refinfo)
01404         self._checkOutFile(outfile,self.compare)
01405 
01406     def testgrid09( self ):
01407         """testgrid09: test sprange"""
01408         tid="09"
01409         outfile = self.figroot+tid+self.figsuff
01410         subplot = self.subplot
01411         sprange = [200,800]
01412 
01413         result = sdplot(infile=self.infile, pollist=self.pollist,
01414                         plottype=self.type, subplot=subplot,
01415                         sprange=sprange,
01416                         header=self.header, outfile=outfile)
01417         locinfo = {#'npanel': 1, 'rows': 1, 'cols': 1,
01418                    'xlim': sprange}
01419         refinfo = self._mergeDict(self.baseinfo,locinfo)
01420         # Tests
01421         self.assertEqual(result,None)
01422         currinfo = self._get_plot_info()
01423         self._compareDictVal(currinfo, refinfo)
01424         self._checkOutFile(outfile,self.compare)
01425 
01426     def testgrid10( self ):
01427         """testgrid10: test flrange"""
01428         tid="10"
01429         outfile = self.figroot+tid+self.figsuff
01430         subplot = self.subplot
01431         flrange = [-2.,10.]
01432 
01433         result = sdplot(infile=self.infile, pollist=self.pollist,
01434                         plottype=self.type, subplot=subplot,
01435                         flrange=flrange,
01436                         header=self.header, outfile=outfile)
01437         locinfo = {#'npanel': 1, 'rows': 1, 'cols': 1,
01438                    'ylim': flrange}
01439         refinfo = self._mergeDict(self.baseinfo,locinfo)
01440         # Tests
01441         self.assertEqual(result,None)
01442         currinfo = self._get_plot_info()
01443         self._compareDictVal(currinfo, refinfo)
01444         self._checkOutFile(outfile,self.compare)
01445 
01446     def testgrid11( self ):
01447         """testgrid11: test sprange and flrange"""
01448         tid="11"
01449         outfile = self.figroot+tid+self.figsuff
01450         subplot = self.subplot
01451         sprange = [200,800]
01452         flrange = [-2.,10.]
01453 
01454         result = sdplot(infile=self.infile, pollist=self.pollist,
01455                         plottype=self.type, subplot=subplot,
01456                         sprange=sprange, flrange=flrange,
01457                         header=self.header, outfile=outfile)
01458         locinfo = {#'npanel': 1, 'rows': 1, 'cols': 1,
01459                    'xlim': sprange, 'ylim': flrange}
01460         refinfo = self._mergeDict(self.baseinfo,locinfo)
01461         # Tests
01462         self.assertEqual(result,None)
01463         currinfo = self._get_plot_info()
01464         self._compareDictVal(currinfo, refinfo)
01465         self._checkOutFile(outfile,self.compare)
01466 
01467     def testgrid12( self ):
01468         """testgrid12: test colormap"""
01469         tid="12"
01470         outfile = self.figroot+tid+self.figsuff
01471         subplot = self.subplot
01472         colormap = "orange pink"
01473         
01474         result = sdplot(infile=self.infile, pollist=self.pollist,
01475                         plottype=self.type, subplot=subplot,
01476                         colormap=colormap,
01477                         header=self.header, outfile=outfile)
01478         locinfo = {}
01479         refinfo = self._mergeDict(self.baseinfo,locinfo)
01480         # Tests
01481         self.assertEqual(result,None)
01482         currinfo = self._get_plot_info()
01483         self._compareDictVal(currinfo, refinfo)
01484         self._checkOutFile(outfile,self.compare)
01485 
01486     def testgrid13( self ):
01487         """testgrid13: test linestyles"""
01488         tid="13"
01489         outfile = self.figroot+tid+self.figsuff
01490         subplot = self.subplot
01491         linestyles = "dashdot"
01492         
01493         result = sdplot(infile=self.infile, pollist=self.pollist,
01494                         plottype=self.type, subplot=subplot,
01495                         linestyles=linestyles,
01496                         header=self.header, outfile=outfile)
01497         locinfo = {}
01498         refinfo = self._mergeDict(self.baseinfo,locinfo)
01499         # Tests
01500         self.assertEqual(result,None)
01501         currinfo = self._get_plot_info()
01502         self._compareDictVal(currinfo, refinfo)
01503         self._checkOutFile(outfile,self.compare)
01504 
01505     def testgrid14( self ):
01506         """testgrid14: test linewidth"""
01507         tid="14"
01508         outfile = self.figroot+tid+self.figsuff
01509         subplot = self.subplot
01510         linewidth=3
01511         
01512         result = sdplot(infile=self.infile, pollist=self.pollist,
01513                         plottype=self.type, subplot=subplot,
01514                         linewidth=linewidth,
01515                         header=self.header, outfile=outfile)
01516         locinfo = {}
01517         refinfo = self._mergeDict(self.baseinfo,locinfo)
01518         # Tests
01519         self.assertEqual(result,None)
01520         currinfo = self._get_plot_info()
01521         self._compareDictVal(currinfo, refinfo)
01522         self._checkOutFile(outfile,self.compare)
01523 
01524 #####
01525 # Tests on string data selection
01526 #####
01527 class sdplot_selectTest( sdplot_unittest_base, unittest.TestCase ):
01528     """
01529     Test CASA type data selection in string.
01530     
01531     The list of tests:
01532       testsel01 --- scanlist
01533       testsel01 --- iflist
01534       testsel01 --- pollist
01535       testsel01 --- beamlist
01536 
01537     Note: input data is generated from a single dish regression data,
01538     'OrionS_rawACSmod', as follows:
01539       default(sdcal)
01540       sdcal(infile='OrionS_rawACSmod',scanlist=[20,21,22,23],
01541             calmode='ps',tau=0.09,outfile='tmp.asap')
01542       sdcal(infile='tmp.asap',scanaverage=True,outfile=self.infile)
01543     """
01544     # Input and output names
01545     infile = 'OrionS_rawACSmod_calSave.asap'
01546     figroot = sdplot_unittest_base.taskname + '_sel'
01547     figsuff = '.png'
01548     fig=None
01549     baseinfo = {'npanel': 2, 'nstack': 2,
01550                'xlabel': 'Channel',
01551                'ylabel': 'Brightness Temperature (K)'}
01552 
01553     # common parameter values
01554     header = False
01555 
01556     # Test settings
01557     saveref = True
01558     usegui = False
01559     compare = (not usegui)
01560     
01561     def setUp( self ):
01562         # switch on/off GUI
01563         sd.rcParams['plotter.gui'] = self.usegui
01564         sd.plotter.__init__()
01565         # Fresh copy of input data
01566         if os.path.exists(self.infile):
01567             shutil.rmtree(self.infile)
01568         shutil.copytree(self.datapath+self.infile, self.infile)
01569         # Generate directory to save figures
01570         if not os.path.exists(self.currdir):
01571             os.makedirs(self.currdir)
01572         # Create a directory to store the figures for future comparison
01573         if (not os.path.exists(self.prevdir)) and self.saveref:
01574             try: os.makedirs(self.prevdir)
01575             except OSError:
01576                 msg = "Unable to create directory, "+self.prevdir+".\n"
01577                 msg += "Plot figures will remain in "+self.currdir
01578                 casalog.post(msg,'WARN')
01579         
01580         default(sdplot)
01581 
01582     def tearDown( self ):
01583         if (os.path.exists(self.infile)):
01584             shutil.rmtree(self.infile)
01585         # restore GUI setting
01586         sd.rcParams['plotter.gui'] = self.oldgui
01587         sd.plotter.__init__()
01588 
01589     # helper functions of tests
01590 
01591     # Actual tests
01592     def testsel01( self ):
01593         """testsel01: scanlist='23~25'"""
01594         tid="01"
01595         outfile = self.figroot+tid+self.figsuff
01596         scanlist="23~25"
01597         panel = 's'
01598         result = sdplot(infile=self.infile, scanlist=scanlist,
01599                         panel=panel, header=self.header,
01600                         outfile=outfile)
01601         locinfo = {'npanel': 2, 'title0': 'Scan 23 (OrionS)'}
01602         refinfo = self._mergeDict(self.baseinfo,locinfo)
01603         # Tests
01604         self.assertEqual(result,None)
01605         currinfo = self._get_plot_info()
01606         self._compareDictVal(currinfo, refinfo)
01607         self._checkOutFile(outfile,self.compare)
01608 
01609     def testsel02( self ):
01610         """testsel02: iflist='1, 3~12,>= 14'"""
01611         tid="02"
01612         outfile = self.figroot+tid+self.figsuff
01613         iflist='1, 3~12,>= 14'
01614         panel = 'i'
01615         result = sdplot(infile=self.infile, iflist=iflist,
01616                         panel=panel, header=self.header,
01617                         outfile=outfile)
01618         locinfo = {'npanel': 5, 'title0': 'IF1'}
01619         refinfo = self._mergeDict(self.baseinfo,locinfo)
01620         # Tests
01621         self.assertEqual(result,None)
01622         currinfo = self._get_plot_info()
01623         self._compareDictVal(currinfo, refinfo)
01624         self._checkOutFile(outfile,self.compare)
01625 
01626     def testsel03( self ):
01627         """testsel03: pollist='>0'"""
01628         tid="03"
01629         outfile = self.figroot+tid+self.figsuff
01630         pollist='>0'
01631         panel = 'p'
01632         result = sdplot(infile=self.infile, pollist=pollist,
01633                         panel=panel, header=self.header,
01634                         outfile=outfile)
01635         locinfo = {'npanel': 1, 'nstack': 1, 'title0': 'LL'}
01636         refinfo = self._mergeDict(self.baseinfo,locinfo)
01637         # Tests
01638         self.assertEqual(result,None)
01639         currinfo = self._get_plot_info()
01640         self._compareDictVal(currinfo, refinfo)
01641         self._checkOutFile(outfile,self.compare)
01642 
01643     def testsel04( self ):
01644         """testsel04: beamlist='<1'"""
01645         tid="04"
01646         outfile = self.figroot+tid+self.figsuff
01647         beamlist='<1'
01648         panel = 'b'
01649         result = sdplot(infile=self.infile, beamlist=beamlist,
01650                         panel=panel, header=self.header,
01651                         outfile=outfile)
01652         locinfo = {'npanel': 1, 'title0': 'Beam 0'}
01653         refinfo = self._mergeDict(self.baseinfo,locinfo)
01654         # Tests
01655         self.assertEqual(result,None)
01656         currinfo = self._get_plot_info()
01657         self._compareDictVal(currinfo, refinfo)
01658         self._checkOutFile(outfile,self.compare)
01659 
01660 
01661 
01662 def suite():
01663     return [sdplot_basicTest, sdplot_storageTest,sdplot_gridTest,
01664             sdplot_selectTest, sdplot_errorTest]