casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
ngc4826_tutorial_regression.py
Go to the documentation of this file.
00001 ##########################################################################
00002 #                                                                        #
00003 # Demo Script for NGC 4826 (BIMA line data)                              #
00004 #                                                                        #
00005 # Converted by  STM 2008-05-27 (Beta Patch 2.0) new tasking/clean/cal    #
00006 # Updated by     CB 2008-05-30                  start from raw data      #
00007 # Updated by    STM 2008-06-01                  scriptmode, plotting     #
00008 # Updated by CB,STM 2008-06-02                  improvements             #
00009 # Updated by CB,STM 2008-06-03                  bigger cube, pbcor       #
00010 # Updated by CB,STM 2008-06-04                  pbcor stuff              #
00011 # Updated by CB,STM 2008-06-04                  tutorial script          #
00012 # Updated by CB     2008-06-05                  small tweaks             #
00013 # Updated by CB,STM 2008-06-12                  final revisions (DS)     #
00014 # Updated by STM    2008-06-14                  post-school fix          #
00015 # Updated by STM    2008-06-17                  scriptmode for regress   #
00016 # Updated by STM    2008-06-19                  regression dictionaries  #
00017 # Updated by STM    2008-06-30                  add channel check        #
00018 # Updated by STM    2008-07-08                  bug fixes                #
00019 # Updated by STM    2008-10-06                  Patch 3 regression       #
00020 # Updated by STM    2008-10-16                  Patch 3 immoments        #
00021 # Updated by STM    2008-10-22                  testing version          #
00022 # Updated by STM    2008-11-03                  minor updates            #
00023 # Updated by STM    2008-11-19                  Patch 3 400x400 image    #
00024 # Updated by STM    2008-12-01                  Patch 3 release          #
00025 # Updated by STM    2008-06-03                  Patch 4 vals, fix error  #
00026 # Updated by STM    2009-06-19                  Patch 4 release          #
00027 # Updated by STM    2009-12-07                  Release 3.0 final        #
00028 #                                                                        #
00029 # N4826 - BIMA SONG Data                                                 #
00030 #                                                                        #
00031 # This data is from the BIMA Survey of Nearby Galaxies (BIMA SONG)       #
00032 # Helfer, Thornley, Regan, et al., 2003, ApJS, 145, 259                  #
00033 # Many thanks to Michele Thornley for providing the data and description #
00034 #                                                                        #
00035 # First day of observations only                                         #
00036 # Trial for summer school                                                #
00037 # NOTE: REGRESSION VERSION FOR CASA TESTING                              #
00038 #                                                                        #
00039 # Script Notes:                                                          #
00040 #    o This script has some interactive commands, such as with plotxy    #
00041 #      and the viewer.  If scriptmode=True, then this script will stop   #
00042 #      and require a carriage-return to continue at these points.        #
00043 #    o Sometimes cut-and-paste of a series of lines from this script     #
00044 #      into the casapy terminal will get garbled (usually a single       #
00045 #      dropped character). In this case, try fewer lines, like groups    #
00046 #      of 4-6.                                                           #
00047 #    o The results are written out as a dictionary in a pickle file      #
00048 #         out.ngc4826.tutorial.regression.<datestring>.pickle            #
00049 #      as well as in a text file                                         #
00050 #         out.ngc4826.tutorial.<datestring>.log                          #
00051 #      (these are not auto-deleted at start of script)                   #
00052 #    o This script keeps internal regression values, but you can provide #
00053 #      a file ngc4826_tutorial_regression.pickle from a previous run     #
00054 #                                                                        #
00055 ##########################################################################
00056 import time
00057 import os
00058 import pickle
00059 
00060 #scriptmode = True
00061 
00062 # If you want to run like a regression, including making PNG for plots,
00063 # then set to False
00064 scriptmode = False
00065 
00066 # Enable benchmarking?
00067 benchmarking = True
00068 
00069 # Sets a shorthand for fixed input script/regression files
00070 scriptprefix='ngc4826_tutorial_regression'
00071 
00072 #
00073 ##########################################################################
00074 #                                                                        
00075 # Clear out previous run results
00076 os.system('rm -rf ngc4826.tutorial.*')
00077 
00078 # Sets a shorthand for the ms, not necessary
00079 prefix='ngc4826.tutorial'
00080 msfile = prefix + '.16apr98.ms'
00081 
00082 print 'Tutorial Regression Script for BIMASONG NGC4826 Mosaic'
00083 print 'Version for Release 0 (3.0.0) 7-Dec-2009'
00084 print 'Will do: import, flagging, calibration, imaging'
00085 print ''
00086 #
00087 ##########################################################################
00088 #
00089 # 
00090 ##########################################################################
00091 #
00092 # N4826 - BIMA SONG Data
00093 # 16apr98
00094 #       source=ngc4826
00095 #       phasecal=1310+323
00096 #       fluxcal=3c273, Flux = 23 Jy on 16apr98
00097 #       passcal= none - data were observed with online bandpass correction.
00098 #
00099 # NOTE: This data has been filled into MIRIAD, line-length correction 
00100 #       done, and then exported as separate files for each source.
00101 #       3c273 was not line length corrected since it was observed
00102 #       for such a short amount of time that it did not need it.  
00103 #
00104 # From miriad: source Vlsr = 408; delta V is 20 km/s 
00105 #
00106 #
00107 ##########################################################################
00108 #
00109 if benchmarking:
00110     startTime=time.time()
00111     startProc=time.clock()
00112 
00113 _mydatapath = os.environ.get('CASAPATH').split()[0]+'/data/regression/ngc4826/'
00114 
00115 ##########################################################################
00116 # Import and concatenate sources
00117 ##########################################################################
00118 #
00119 # USB spectral windows written separately by miriad for 16apr98
00120 # Assumes these are in sub-directory called "fitsfiles" of working directory
00121 print '--Importuvfits (16apr98)--'
00122 default('importuvfits')
00123 
00124 print "Starting from the uvfits files exported by miriad"
00125 print "The USB spectral windows were written separately by miriad for 16apr98"
00126 
00127 importuvfits(fitsfile=_mydatapath+'fitsfiles/3c273.fits5', vis='ngc4826.tutorial.3c273.5.ms')
00128 
00129 importuvfits(fitsfile=_mydatapath+'fitsfiles/3c273.fits6', vis='ngc4826.tutorial.3c273.6.ms')
00130 
00131 importuvfits(fitsfile=_mydatapath+'fitsfiles/3c273.fits7', vis='ngc4826.tutorial.3c273.7.ms')
00132 
00133 importuvfits(fitsfile=_mydatapath+'fitsfiles/3c273.fits8', vis='ngc4826.tutorial.3c273.8.ms')
00134 
00135 importuvfits(fitsfile=_mydatapath+'fitsfiles/1310+323.ll.fits9', vis='ngc4826.tutorial.1310+323.ll.9.ms')
00136 
00137 importuvfits(fitsfile=_mydatapath+'fitsfiles/1310+323.ll.fits10', vis='ngc4826.tutorial.1310+323.ll.10.ms')
00138 
00139 importuvfits(fitsfile=_mydatapath+'fitsfiles/1310+323.ll.fits11', vis='ngc4826.tutorial.1310+323.ll.11.ms')
00140 
00141 importuvfits(fitsfile=_mydatapath+'fitsfiles/1310+323.ll.fits12', vis='ngc4826.tutorial.1310+323.ll.12.ms')
00142 
00143 importuvfits(fitsfile=_mydatapath+'fitsfiles/1310+323.ll.fits13', vis='ngc4826.tutorial.1310+323.ll.13.ms')
00144 
00145 importuvfits(fitsfile=_mydatapath+'fitsfiles/1310+323.ll.fits14', vis='ngc4826.tutorial.1310+323.ll.14.ms')
00146 
00147 importuvfits(fitsfile=_mydatapath+'fitsfiles/1310+323.ll.fits15', vis='ngc4826.tutorial.1310+323.ll.15.ms')
00148 
00149 importuvfits(fitsfile=_mydatapath+'fitsfiles/1310+323.ll.fits16', vis='ngc4826.tutorial.1310+323.ll.16.ms')
00150 
00151 importuvfits(fitsfile=_mydatapath+'fitsfiles/ngc4826.ll.fits5', vis='ngc4826.tutorial.ngc4826.ll.5.ms')
00152 
00153 importuvfits(fitsfile=_mydatapath+'fitsfiles/ngc4826.ll.fits6', vis='ngc4826.tutorial.ngc4826.ll.6.ms')
00154 
00155 importuvfits(fitsfile=_mydatapath+'fitsfiles/ngc4826.ll.fits7', vis='ngc4826.tutorial.ngc4826.ll.7.ms')
00156 
00157 importuvfits(fitsfile=_mydatapath+'fitsfiles/ngc4826.ll.fits8', vis='ngc4826.tutorial.ngc4826.ll.8.ms')
00158 
00159 if benchmarking:
00160     import2time=time.time()
00161 
00162 #
00163 ##########################################################################
00164 #
00165 print '--Concat--'
00166 default('concat')
00167 
00168 concat(vis=['ngc4826.tutorial.3c273.5.ms',
00169             'ngc4826.tutorial.3c273.6.ms',
00170             'ngc4826.tutorial.3c273.7.ms',
00171             'ngc4826.tutorial.3c273.8.ms',
00172             'ngc4826.tutorial.1310+323.ll.9.ms',
00173             'ngc4826.tutorial.1310+323.ll.10.ms',
00174             'ngc4826.tutorial.1310+323.ll.11.ms',
00175             'ngc4826.tutorial.1310+323.ll.12.ms',
00176             'ngc4826.tutorial.1310+323.ll.13.ms',
00177             'ngc4826.tutorial.1310+323.ll.14.ms',
00178             'ngc4826.tutorial.1310+323.ll.15.ms',
00179             'ngc4826.tutorial.1310+323.ll.16.ms',
00180             'ngc4826.tutorial.ngc4826.ll.5.ms',
00181             'ngc4826.tutorial.ngc4826.ll.6.ms',
00182             'ngc4826.tutorial.ngc4826.ll.7.ms',
00183             'ngc4826.tutorial.ngc4826.ll.8.ms'],
00184        concatvis='ngc4826.tutorial.ms',
00185        freqtol="",dirtol="1arcsec",async=False)
00186 
00187 if benchmarking:
00188     concat2time=time.time()
00189 
00190 #
00191 ##########################################################################
00192 #
00193 # TUTORIAL NOTES:
00194 #
00195 # You can invoke tasks in two ways:
00196 #
00197 # (1) As function calls with arguments as shown above for concat and used
00198 #     extensively in this script, e.g.
00199 #
00200 #        task( par1=val1, par2=val2, ... )
00201 #
00202 #     with parameters set as arguments in the call.  Note that in this
00203 #     case, the global parameter values are NOT used or changed, and any
00204 #     task parameters that are not specified as arguments to the call
00205 #     will be defaulted to the task-specific default values (see the
00206 #     "help task" description).
00207 #
00208 # (2) By setting the values of the global parameters and then using the
00209 #     "go" command (if taskname is set) or calling the task with no
00210 #     arguments.  For example:
00211 #
00212 #        default task
00213 #        par1 = val1
00214 #        par2 = val2
00215 #        ...
00216 #        inp
00217 #        task()
00218 #
00219 #     In this case, the "default" command sets the parmeters to their
00220 #     task defaults, and sets the "taskname" paramter to the task to be
00221 #     run.  The "inp" command displays the current values for the task
00222 #     parameters.  Then the call with no arguments runs with the globals.
00223 #
00224 #     Warning: "go" does not work inside scripts. See Cookbook.
00225 #
00226 # Using the concat call above as an example, we would do:
00227 #
00228 #default('concat')
00229 #
00230 #vis = ['ngc4826.tutorial.3c273.5.ms',
00231 #       'ngc4826.tutorial.3c273.6.ms',
00232 #       'ngc4826.tutorial.3c273.7.ms',
00233 #       'ngc4826.tutorial.3c273.8.ms',
00234 #       'ngc4826.tutorial.1310+323.ll.9.ms',
00235 #       'ngc4826.tutorial.1310+323.ll.10.ms',
00236 #       'ngc4826.tutorial.1310+323.ll.11.ms',
00237 #       'ngc4826.tutorial.1310+323.ll.12.ms',
00238 #       'ngc4826.tutorial.1310+323.ll.13.ms',
00239 #       'ngc4826.tutorial.1310+323.ll.14.ms',
00240 #       'ngc4826.tutorial.1310+323.ll.15.ms',
00241 #       'ngc4826.tutorial.1310+323.ll.16.ms',       
00242 #       'ngc4826.tutorial.ngc4826.ll.5.ms',
00243 #       'ngc4826.tutorial.ngc4826.ll.6.ms',
00244 #       'ngc4826.tutorial.ngc4826.ll.7.ms',
00245 #       'ngc4826.tutorial.ngc4826.ll.8.ms']
00246 #
00247 #concatvis='ngc4826.tutorial.ms'
00248 #freqtol = ""
00249 #dirtol = "1arcsec"
00250 #async=False
00251 #
00252 #concat()
00253 
00254 #
00255 ##########################################################################
00256 #
00257 # Fix up the MS (temporary, changes to importfits underway)
00258 #
00259 print '--Fixing up spw rest frequencies in MS--'
00260 vis='ngc4826.tutorial.ms'
00261 tb.open(vis+'/SOURCE',nomodify=false)
00262 spwid=tb.getcol('SPECTRAL_WINDOW_ID')
00263 #spwid.setfield(-1,int)
00264 # Had to do this for 64bit systems 08-Jul-2008
00265 spwid.setfield(-1,'int32')
00266 tb.putcol('SPECTRAL_WINDOW_ID',spwid)
00267 tb.close()
00268 
00269 # This ensures that the rest freq will be found for all spws. 
00270 
00271 #
00272 ##########################################################################
00273 # 16 APR Calibration
00274 ##########################################################################
00275 print '--Clearcal--'
00276 print 'Create scratch columns and initialize in '+'ngc4826.tutorial.ms'
00277 
00278 # Force create/initialize of scratch columns
00279 # NOTE: plotxy will not run properly without this step.
00280 #
00281 clearcal(vis='ngc4826.tutorial.ms', addmodel=False)
00282 
00283 if benchmarking:
00284     clearcal2time=time.time()
00285 
00286 #
00287 ##########################################################################
00288 #
00289 # List contents of MS
00290 #
00291 print '--Listobs--'
00292 listobs(vis='ngc4826.tutorial.ms')
00293 
00294 # Should see the listing in logger
00295 # Some parts shown below
00296 #
00297 
00298 print "There are 3 fields observed in a total of 16 spectral windows"
00299 print "   field=0    3c273    spwids 0,1,2,3               64 chans "
00300 print "   field=1    1310+323 spwids 4,5,6,7,8,9,10,11     32 chans "
00301 print "   field=2~8  NGC4826  spwids 12,13,14,15           64 chans "
00302 print ""
00303 print "See listobs summary in logger"
00304 
00305 if benchmarking:
00306     list2time=time.time()
00307 
00308 # Fields: 9
00309 # ID   Code Name          Right Ascension  Declination   Epoch   
00310 # 0         3C273         12:29:06.70      +02.03.08.60  J2000   
00311 # 1         1310+323      13:10:28.66      +32.20.43.78  J2000   
00312 # 2         NGC4826       12:56:44.24      +21.41.05.10  J2000   
00313 # 3         NGC4826       12:56:41.08      +21.41.05.10  J2000   
00314 # 4         NGC4826       12:56:42.66      +21.41.43.20  J2000   
00315 # 5         NGC4826       12:56:45.82      +21.41.43.20  J2000   
00316 # 6         NGC4826       12:56:47.39      +21.41.05.10  J2000   
00317 # 7         NGC4826       12:56:45.82      +21.40.27.00  J2000   
00318 # 8         NGC4826       12:56:42.66      +21.40.27.00  J2000   
00319 # Spectral Windows:
00320 # SpwID  #Chans Frame Ch1(MHz)    ChanWid(kHz)TotBW(kHz)  Ref(MHz)    Corrs
00321 # 0          64 LSRK  115108.478  1562.5      100000      115108.478  YY  
00322 # 1          64 LSRK  115198.615  1562.5      100000      115198.615  YY  
00323 # 2          64 LSRK  115288.478  1562.5      100000      115288.478  YY  
00324 # 3          64 LSRK  115378.615  1562.5      100000      115378.615  YY  
00325 # 4          32 LSRK  114974.256  3125        100000      114974.256  YY  
00326 # 5          32 LSRK  115074.393  3125        100000      115074.393  YY  
00327 # 6          32 LSRK  115174.256  3125        100000      115174.256  YY  
00328 # 7          32 LSRK  115274.393  3125        100000      115274.393  YY  
00329 # 8          32 LSRK  115374.256  3125        100000      115374.256  YY  
00330 # 9          32 LSRK  115474.392  3125        100000      115474.392  YY  
00331 # 10         32 LSRK  115574.255  3125        100000      115574.255  YY  
00332 # 11         32 LSRK  115674.392  3125        100000      115674.392  YY  
00333 # 12         64 LSRK  114950.191  1562.5      100000      114950.191  YY  
00334 # 13         64 LSRK  115040.205  1562.5      100000      115040.205  YY  
00335 # 14         64 LSRK  115129.946  1562.5      100000      115129.946  YY  
00336 # 15         64 LSRK  115219.96   1562.5      100000      115219.96   YY  
00337 
00338 #
00339 ##########################################################################
00340 # Plotting and Flagging
00341 ##########################################################################
00342 #
00343 # The plotxy task is the interactive x-y display and flagging GUI
00344 #
00345 #print '--Plotxy--'
00346 #default(plotxy)
00347 
00348 # First look at amplitude as a funciton of uv-distance using an
00349 # average over all times and channels for each source.
00350 #if scriptmode:
00351 #    plotxy(vis='ngc4826.tutorial.ms',xaxis='uvdist',yaxis='amp',
00352 #           field='0',spw='0~3',
00353 #           averagemode='vector',timebin='1e7',width='1000',crossscans=True,
00354 #           selectplot=True,title='Field 0 SPW 0~3')
00355 
00356 #    print "Looking at 3C273 versus uvdist with time and chan average"
00357     # Pause script if you are running in scriptmode
00358 #    user_check=raw_input('Return to continue script\n')
00359 #else:
00360 #    plotxy(vis='ngc4826.tutorial.ms',xaxis='uvdist',yaxis='amp',
00361 #           field='0',spw='0~3',
00362 #           averagemode='vector',timebin='1e7',width='1000',crossscans=True,
00363 #           selectplot=True,title='Field 0 SPW 0~3',
00364 #           interactive=False,
00365 #           figfile='ngc4826.tutorial.ms.plotxy.field0.ampuv.allavg.png')
00366 
00367 # NOTE: width here needs to be larger than combination of all channels
00368 # selected with spw and/or field. Since field and spw are unique in this
00369 # case, both don't need to be specified, however plotting is much faster
00370 # if you "help it" by selecting both.
00371 
00372 # Now lets look at the target source, the first of the NGC4826 mosaic fields
00373 # which are 2~8 in this MS.
00374 #
00375 # Since we are plotting versus velocity we can clearly see the bad edge
00376 # channels and the overlap between spw
00377 #
00378 # There is nothing terribly wrong with this data and again we will flag the
00379 # edge channels non-interactively later for consistency.
00380 #
00381 # Normally, if there were obviously bad data, you would flag it here
00382 # before calibration.  To do this, hit the Mark Region button, then draw a box around
00383 # some of the moderately high outliers, and then Flag.
00384 #
00385 # But this data is relatively clean, and flagging will not improve results.
00386 #
00387 # Interactive plotxy
00388 #if scriptmode:
00389 #    plotxy(vis='ngc4826.tutorial.ms',xaxis='velocity',yaxis='amp',
00390 #           field='2',spw='12~15',
00391 #           averagemode='vector',timebin='1e7',crossscans=True,
00392 #           selectplot=True,newplot=False,title='Field 2 SPW 12~15')
00393 
00394 #    print "You could Mark Region around outliers and Flag"
00395     # Pause script if you are running in scriptmode
00396 #    user_check=raw_input('Return to continue script\n')
00397 #else:
00398     # Output to file
00399     # Set up a Python loop to do all the N4826 fields:
00400 #    for fld in range(2,9):
00401 #        field = str(fld)
00402 #        plotxy(vis='ngc4826.tutorial.ms',xaxis='velocity',yaxis='amp',
00403 #               field=field,spw='12~15',
00404 #               averagemode='vector',timebin='1e7',crossscans=True,
00405 #               selectplot=True,newplot=False,title='Field 2 SPW 12~15',
00406 #               interactive=False,
00407 #               figfile='ngc4826.tutorial.ms.plotxy.field2.ampvel.tavg.png')
00408 
00409     # Now the 1310+323 field
00410 #    plotxy(vis='ngc4826.tutorial.ms',xaxis='velocity',yaxis='amp',
00411 #           field='1',spw='4~11',
00412 #           averagemode='vector',timebin='1e7',crossscans=True,
00413 #           selectplot=True,newplot=False,title='Field 1 SPW 4~11',
00414 #           interactive=False,
00415 #           figfile='ngc4826.tutorial.ms.plotxy.field1.ampvel.tavg.png')
00416 
00417     # Now the 3C273 field
00418     # This one should be time and channel averaged to test this
00419 #   plotxy(vis='ngc4826.tutorial.ms',xaxis='velocity',yaxis='amp',
00420 #         field='0',spw='0~3',
00421 #         averagemode='vector',timebin='1e7',crossscans=True,
00422 #           selectplot=True,newplot=False,title='Field 0 SPW 0~3',
00423 #           interactive=False,
00424 #           figfile='ngc4826.tutorial.ms.plotxy.field0.ampvel.tavg.png')
00425 
00426 # You can also have it iterate over baselines, using Next to advance
00427 # Set to NOT plot autocorrelations
00428 # Example using 3C273: (interactive only)
00429 #if scriptmode:
00430 #    plotxy(vis='ngc4826.tutorial.ms',xaxis='channel',yaxis='amp',
00431 #           field='0',spw='0~3',
00432 #           selectdata=True,antenna='*&*',
00433 #           averagemode='vector',timebin='1e7',crossscans=True,
00434 #           iteration='baseline',
00435 #           selectplot=True,newplot=False,title='Field 0 SPW 0~3')
00436         
00437     # Pause script if you are running in scriptmode
00438 #    user_check=raw_input('Return to continue script\n')
00439 
00440 #
00441 # Finally, look for bad data. Here we look at field 8 w/o averaging
00442 #if scriptmode:
00443 #    plotxy(vis='ngc4826.tutorial.ms',xaxis='time',yaxis='amp',field='8',spw='12~15',
00444 #           selectplot=True,newplot=False,title='Field 8 SPW 12~15')
00445 
00446 #    print "You can see some bad data here"
00447 #    print "Mark Region and Locate, look in logger"
00448 #    print "This is a correlator glitch in baseline 3-9 at 06:19:30"
00449 #    print "PLEASE DON\'T FLAG ANYTHING HERE. THE SCRIPT WILL DO IT!"
00450 #    print "In a normal session you could Mark Region and Flag."
00451 #    print "Here we will use flagdata instead."
00452     # Pause script if you are running in scriptmode
00453 #    user_check=raw_input('Return to continue script\n')
00454 
00455     # If you change xaxis='channel' you see its all channels
00456 #else:
00457     # Plot to file
00458 #    plotxy(vis='ngc4826.tutorial.ms',xaxis='time',yaxis='amp',
00459 #           field='8',spw='12~15',
00460 #           selectplot=True,newplot=False,title='Field 8 SPW 12~15',
00461 #           interactive=False,
00462 #           figfile='ngc4826.tutorial.ms.plotxy.field2.amptime.noavg.png')
00463     
00464 if benchmarking:
00465     plotxy2time=time.time()
00466 
00467 #
00468 ##########################################################################
00469 #
00470 # Flag end channels
00471 #
00472 print '--Flagdata--'
00473 default('tflagdata')
00474 
00475 print ""
00476 print "Flagging edge channels in all spw"
00477 print "  0~3:0~1;62~63 , 4~11:0~1;30~31, 12~15:0~1;62~63 "
00478 print ""
00479 
00480 tflagdata(vis='ngc4826.tutorial.ms', mode='manual',
00481          spw='0~3:0;1;62;63,4~11:0;1;30;31,12~15:0;1;62;63')
00482 
00483 #
00484 # Flag correlator glitch
00485 #
00486 print ""
00487 print "Flagging bad correlator field 8 antenna 3&9 spw 15 all channels"
00488 print "  timerange 1998/04/16/06:19:00.0~1998/04/16/06:20:00.0"
00489 print ""
00490 
00491 tflagdata(vis='ngc4826.tutorial.ms', mode='manual', field='8', spw='15', antenna='3&9', 
00492          timerange='1998/04/16/06:19:00.0~1998/04/16/06:20:00.0')
00493 
00494 #
00495 # Flag non-fringing antenna 6
00496 #
00497 # NOTE: this is already flagged in the data so do nothing more here
00498 #flagdata(vis='ngc4826.tutorial.ms', mode='manualflag', antenna='6',
00499 #        timerange='1998/04/16/09:42:39.0~1998/04/16/10:24:46.0')
00500 
00501 #
00502 #
00503 ##########################################################################
00504 #
00505 # Some example clean-up editing
00506 # Slightly high almost-edge channel in field='1', spw='4' (channel 2)
00507 # can be flagged interactively with plotxy.
00508 #
00509 #plotxy(vis='ngc4826.tutorial.ms',
00510 #       xaxis='channel',yaxis='amp',field='1',spw='4',
00511 #       averagemode='vector',timebin='1e7',crossscans=True,
00512 #       selectplot=True,newplot=False,title='Field 1 SPW 4')
00513 
00514 #
00515 ##########################################################################
00516 #
00517 # Use Flagmanager to save a copy of the flags so far
00518 #
00519 print '--Flagmanager--'
00520 default('flagmanager')
00521 
00522 print "Now will use flagmanager to save a copy of the flags we just made"
00523 print "These are named myflags"
00524 
00525 flagmanager(vis='ngc4826.tutorial.ms',mode='save',versionname='myflags',
00526             comment='My flags',merge='replace')
00527 
00528 # Can also use Flagmanager to list all saved versions
00529 #
00530 flagmanager(vis='ngc4826.tutorial.ms',mode='list')
00531 
00532 if benchmarking:
00533     flag2time=time.time()
00534 
00535 print "Completed pre-calibration flagging"
00536 
00537 #
00538 ##########################################################################
00539 #
00540 # CALIBRATION
00541 #
00542 ##########################################################################
00543 #
00544 # Bandpasses are very flat because of observing mode used (online bandpass
00545 # correction) so bandpass calibration is unnecessary for these data.
00546 #
00547 ##########################################################################
00548 #
00549 # Derive gain calibration solutions.
00550 # We will use VLA-like G (per-scan) calibration:
00551 #
00552 ##########################################################################
00553 #
00554 # Set the flux density of 3C273 to 23 Jy
00555 #
00556 print '--Setjy (3C273)--'
00557 default('setjy')
00558 
00559 setjy(vis='ngc4826.tutorial.ms',field='0',fluxdensity=[23.0,0.,0.,0.],spw='0~3', scalebychan=False, usescratch=False)
00560 #
00561 # Not really necessary to set spw but you get lots of warning messages if
00562 # you don't
00563 
00564 if benchmarking:
00565     setjy2time=time.time()
00566 
00567 #
00568 ##########################################################################
00569 #
00570 # Gain calibration
00571 #
00572 print '--Gaincal--'
00573 default('gaincal')
00574 
00575 # This should be combining all spw for the two calibrators for single
00576 # scan-based solutions
00577 
00578 print 'Gain calibration for fields 0,1 and spw 0~11'
00579 print 'Using solint=inf combining over spw'
00580 print 'Output table ngc4826.tutorial.16apr98.gcal'
00581 
00582 gaincal(vis='ngc4826.tutorial.ms', caltable='ngc4826.tutorial.16apr98.gcal',
00583         field='0,1', spw='0~11', gaintype='G', minsnr=2.0,
00584         refant='ANT5', gaincurve=False, opacity=0.0,
00585         solint='inf', combine='spw')
00586 
00587 if benchmarking:
00588     gaincal2time=time.time()
00589 
00590 #
00591 ##########################################################################
00592 #
00593 # Transfer the flux density scale:
00594 #
00595 print '--Fluxscale--'
00596 default('fluxscale')
00597 
00598 print ''
00599 print 'Transferring flux of 3C273 to sources: 1310+323'
00600 print 'Output table ngc4826.tutorial.16apr98.fcal'
00601 
00602 fluxscale(vis='ngc4826.tutorial.ms', caltable='ngc4826.tutorial.16apr98.gcal',
00603           fluxtable='ngc4826.tutorial.16apr98.fcal',
00604           reference='3C273', transfer=['1310+323'])
00605 
00606 # Flux density for 1310+323 is: 1.48 +/- 0.016 (SNR = 90.6, nAnt= 8)
00607 
00608 if benchmarking:
00609     fluxscale2time=time.time()
00610 
00611 #
00612 ##########################################################################
00613 #
00614 # Plot calibration
00615 print '--Plotcal (fluxscale)--'
00616 default(plotcal)
00617 
00618 if scriptmode:
00619     # Interactive plotcal
00620     plotcal(caltable='ngc4826.tutorial.16apr98.fcal', yaxis='amp', field='')
00621     print ''
00622     print 'Plotting final scaled gain calibration table'
00623     print 'First amp vs. time for all fields '
00624         
00625     # Pause script if you are running in scriptmode
00626     user_check=raw_input('Return to continue script\n')
00627 
00628     plotcal(caltable='ngc4826.tutorial.16apr98.fcal', yaxis='phase', field='')
00629     print ''
00630     print 'and phase vs. time '
00631 
00632     # Pause script if you are running in scriptmode
00633     user_check=raw_input('Return to continue script\n')
00634 
00635     # And you can plot the SNR of the solution
00636     plotcal(caltable='ngc4826.tutorial.16apr98.fcal', yaxis='snr', field='')
00637 else:
00638     # You can also plotcal to file
00639     plotcal(caltable='ngc4826.tutorial.16apr98.fcal',yaxis='amp',field='',
00640             showgui=False,figfile='ngc4826.tutorial.16apr98.fcal.plotcal.amp.png')
00641     plotcal(caltable='ngc4826.tutorial.16apr98.fcal',yaxis='phase',field='',
00642             showgui=False,figfile='ngc4826.tutorial.16apr98.fcal.plotcal.phase.png')
00643     plotcal(caltable='ngc4826.tutorial.16apr98.fcal',yaxis='snr',field='',
00644             showgui=False,figfile='ngc4826.tutorial.16apr98.fcal.plotcal.snr.png')
00645 
00646 if benchmarking:
00647     plotcal2time=time.time()
00648 
00649 #
00650 ##########################################################################
00651 #
00652 # Correct the calibrater/target source data:
00653 # Use new parm spwmap to apply gain solutions derived from spwid1
00654 # to all other spwids... 
00655 print '--Applycal--'
00656 default('applycal')
00657 
00658 print 'Applying calibration table ngc4826.tutorial.16apr98.fcal to data'
00659 
00660 applycal(vis='ngc4826.tutorial.ms',
00661          field='', spw='',
00662          gaincurve=False, opacity=0.0, 
00663          gaintable='ngc4826.tutorial.16apr98.fcal',
00664          spwmap=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
00665 
00666 if benchmarking:
00667     correct2time=time.time()
00668 
00669 #
00670 ##########################################################################
00671 #
00672 # Check calibrated data
00673 #print '--Plotxy--'
00674 #default(plotxy)
00675 
00676 #
00677 # Here we plot the first of the NGC4826 fields unaveraged versus velocity
00678 # Notice how the spw fit together
00679 
00680 # Interactive plotxy
00681 #print "Will plot all the NGC4826 calibrated data unaveraged - this will take a while"
00682 #plotxy(vis='ngc4826.tutorial.ms',xaxis='velocity',yaxis='amp',field='2~8',spw='12~15',
00683 #       averagemode='vector',datacolumn='corrected',
00684 #       selectplot=True,newplot=False,title='Field 2~8 SPW 12~15')
00685 
00686 #print ""
00687 #print "Look for outliers, flag them if there are any bad ones"
00688 #print ""
00689         
00690 # Pause script if you are running in scriptmode
00691 #user_check=raw_input('Return to continue script\n')
00692 
00693 # You can also plot all the N4826 fields 2 through 8, for example using a loop:
00694 
00695 #for fld in range(2,9):
00696 #       field = str(fld)
00697 #       plotxy(vis='ngc4826.tutorial.ms',xaxis='velocity',yaxis='amp',
00698 #              field=field,spw='11~15',
00699 #              averagemode='vector',datacolumn='corrected',
00700 #              selectplot=True,newplot=False,title='Field '+field+' SPW 11~15')
00701 #       
00702 #       user_check=raw_input('Return to continue script\n')
00703 
00704 # Now here we time-average the data, plotting versus velocity
00705 
00706 #plotxy(vis='ngc4826.tutorial.ms',xaxis='velocity',yaxis='amp',field=field,spw=spw,
00707 #       averagemode='vector',datacolumn='corrected',
00708 #       timebin='1e7',crossscans=True,plotcolor='blue',
00709 #       selectplot=True,newplot=False,title='Field '+field+' SPW '+spw)
00710 #print ""
00711 #print 'Final Spectrum field '+field+' spw '+spw+' TimeAverage Corrected Data'
00712         
00713 # Pause script if you are running in scriptmode
00714 #user_check=raw_input('Return to continue script\n')
00715 
00716 # Here we overplot 3C273 the Time+Chan averaged calibrated and uncalibrated data
00717 
00718 #
00719 # First the corrected column in blue
00720 #field = '0'
00721 #spw = '0~3'
00722 #plotxy(vis='ngc4826.tutorial.ms',xaxis='uvdist',yaxis='amp',field=field,spw=spw,
00723 #       averagemode='vector',width='1000',datacolumn='corrected',
00724 #       timebin='1e7',crossscans=True,plotcolor='blue',
00725 #       selectplot=True,newplot=False,title='Field '+field+' SPW '+spw)
00726 #print ""
00727 #print 'Plotting field '+field+' spw '+spw+' TimeChanAverage Corrected Data in blue'
00728 #
00729 # Now the original data column in red
00730 #plotxy(vis='ngc4826.tutorial.ms',xaxis='uvdist',yaxis='amp',field=field,spw=spw,
00731 #       averagemode='vector',width='1000',datacolumn='data',
00732 #       timebin='1e7',crossscans=True,plotcolor='red',overplot=True,
00733 #       selectplot=True,newplot=False,title='Field '+field+' SPW '+spw)
00734 #
00735 #print 'OverPlotting field '+field+' spw '+spw+' TimeChanAverage Original Data in red'
00736         
00737 ## Pause script if you are running in scriptmode
00738 #user_check=raw_input('Return to continue script\n')
00739 
00740 #if benchmarking:
00741 #    plotfinal2time=time.time()
00742 
00743 print "Done calibration and plotting"
00744 #
00745 ##########################################################################
00746 #
00747 # SPLIT THE DATA INTO SINGLE-SOURCE MS
00748 # AND THEN IMAGE THE CALIBRATOR
00749 #
00750 ##########################################################################
00751 #
00752 #
00753 # Split out calibrated target source and calibrater data:
00754 #
00755 print '--Split--'
00756 default('split')
00757 
00758 print 'Splitting 3C273 data to ngc4826.tutorial.16apr98.3C273.split.ms'
00759 
00760 split(vis='ngc4826.tutorial.ms',
00761       outputvis='ngc4826.tutorial.16apr98.3C273.split.ms',
00762       field='0',spw='0~3:0~63', datacolumn='corrected')
00763 
00764 print 'Splitting 1310+323 data to ngc4826.tutorial.16apr98.1310+323.split.ms'
00765 
00766 split(vis='ngc4826.tutorial.ms',
00767       outputvis='ngc4826.tutorial.16apr98.1310+323.split.ms',
00768       field='1', spw='4~11:0~31', datacolumn='corrected')
00769 
00770 print 'Splitting NGC4826 data to ngc4826.tutorial.16apr98.src.split.ms'
00771 
00772 split(vis='ngc4826.tutorial.ms',
00773       outputvis='ngc4826.tutorial.16apr98.src.split.ms',
00774       field='2~8', spw='12~15:0~63',
00775       datacolumn='corrected')
00776 
00777 if benchmarking:
00778     split2time=time.time()
00779 
00780 #
00781 ##########################################################################
00782 #
00783 #print '--Clearcal (split data)--'
00784 
00785 # If you want to use plotxy before cleaning to look at the split ms
00786 # then you will need to force the creation of the scratch columns
00787 # (clean will also do this)
00788 #clearcal('ngc4826.tutorial.16apr98.1310+323.split.ms')
00789 
00790 #clearcal('ngc4826.tutorial.16apr98.src.split.ms')
00791 
00792 #Then you might look at the data
00793 #clearplot()
00794 #plotxy(vis='ngc4826.tutorial.16apr98.src.split.ms',xaxis='time',yaxis='amp')
00795 
00796 #if benchmarking:
00797 #    clearfinal2time=time.time()
00798 
00799 #
00800 ##########################################################################
00801 #
00802 # You might image the calibrater data:
00803 #
00804 #print '--Clean (1310+323)--'
00805 #default('clean')
00806 #
00807 #
00808 #clean(vis='ngc4826.tutorial.16apr98.1310+323.split.ms', 
00809 #      imagename='ngc4826.tutorial.16apr98.cal.clean',
00810 #      cell=[1.,1.],imsize=[256,256],
00811 #      field='0',spw='0~7',threshold=10.,
00812 #      mode='mfs',psfmode='clark',niter=100,stokes='I')
00813 
00814 # You can look at this in the viewer
00815 #viewer('ngc4826.tutorial.16apr98.cal.clean.image')
00816 
00817 #if benchmarking:
00818 #    cleancal2time=time.time()
00819 
00820 #
00821 #
00822 ##########################################################################
00823 #
00824 # IMAGING OF NGC4826 MOSAIC
00825 #
00826 ##########################################################################
00827 #
00828 #          Mosaic field spacing looks like:
00829 #
00830 #          F3 (field 3)         F2 (field 2)
00831 #
00832 #   F4 (field 4)      F0 (field 0)        F1 (field 1)
00833 #
00834 #          F5 (field 5)         F6 (field 6)
00835 #
00836 # 4x64 channels = 256 channels 
00837 #
00838 # Primary Beam should be about 1.6' FWHM (7m dishes, 2.7mm wavelength)
00839 # Resolution should be about 5-8"
00840 ##########################################################################
00841 #
00842 # Image the target source mosaic:
00843 #
00844 print '--Clean (NGC4826)--'
00845 default('clean')
00846 
00847 # Make image big enough so mosaic is in inner quarter (400x400)
00848 clnsize = 400
00849 print " Creating CLEAN image of size "+str(clnsize)
00850 
00851 clean(vis='ngc4826.tutorial.16apr98.src.split.ms',
00852       imagename='ngc4826.tutorial.16apr98.src.clean',
00853       field='0~6',spw='0~3',
00854       cell=[1.,1.],imsize=[clnsize,clnsize],
00855       stokes='I',
00856       mode='channel',nchan=36,start=34,width=4,
00857       interpolation='nearest',
00858       psfmode='clark',imagermode='mosaic',ftmachine='mosaic',
00859       scaletype='SAULT',
00860 ### As we moved to clean by default in flat sigma rather than
00861 ### flat snr it converges less well
00862  ###     cyclefactor=1.5,niter=10000,threshold='45mJy',
00863       cyclefactor=4,niter=10000,threshold='45mJy',
00864       minpb=0.3,pbcor=False, usescratch=False)
00865 
00866 ### NOTE: mosaic data ...Sault weighting implies a noise unform image
00867 
00868 ### Using ftmachine='mosaic', can also use ftmachine='ft' for more
00869 ### traditional image plane mosaicing
00870 
00871 ### NOTE: that niter is set to large number so that stopping point is
00872 ### controlled by threshold.
00873 
00874 ### NOTE: with pbcor=False, the final image is not "flux correct",
00875 ### instead the image has constant noise despite roll off in power as
00876 ### you move out from the phase center(s). Though this format makes it
00877 ### "look nicest", for all flux density measurements, and to get an
00878 ### accurate integrated intensity image, one needs to divide the
00879 ### srcimage.image/srcimage.flux in order to correct for the mosaic
00880 ### response pattern. One could also achieve this by setting pbcor=True
00881 ### in clean.
00882 
00883 # Try running clean adding the parameter interactive=True.
00884 # This parameter will periodically bring up the viewer to allow
00885 # interactive clean boxing. For poor uv-coverage, deep negative bowls
00886 # from missing short spacings, this can be very important to get correct
00887 # integrated flux densities.
00888 
00889 if benchmarking:
00890     clean2time=time.time()
00891 
00892 #
00893 ##########################################################################
00894 #
00895 # Do interactive viewing of clean image
00896 print '--Viewer--'
00897 if scriptmode:
00898     viewer('ngc4826.tutorial.16apr98.src.clean.image')
00899 
00900     print ""
00901     print "This is the non-pbcorrected cube of NGC4826"
00902     print "Use tape deck to move through channels"
00903     print "Close the viewer when done"
00904     print ""
00905 
00906     # Pause script if you are running in scriptmode
00907     user_check=raw_input('Return to continue script\n')
00908 
00909 #
00910 ##########################################################################
00911 #
00912 # Statistics on clean image cube
00913 #
00914 print '--ImStat (Clean cube)--'
00915 
00916 srcstat = imstat('ngc4826.tutorial.16apr98.src.clean.image')
00917 
00918 print "Found image max = "+str(srcstat['max'][0])
00919 
00920 # 256x256: refpix = '128,128,128,128'
00921 # 400x400: refpix = '200,200,200,200'
00922 # 512x512: refpix = '256,256,256,256'
00923 # 800x800: refpix = '400,400,400,400'
00924 refpix = int(clnsize/2)
00925 refbox = str(refpix)+','+str(refpix)+','+str(refpix)+','+str(refpix)
00926 print "  Using Reference Pixel "+refbox
00927 
00928 # 256x256: offbox = '106,161,153,200'
00929 # 400x400: offbox = '178,233,225,272'
00930 # 512x512: offbox = '234,289,281,328'
00931 # 800x800: offbox = '378,433,425,472'
00932 blcx = refpix - 22
00933 blcy = refpix + 33
00934 trcx = refpix + 25
00935 trcy = refpix + 72
00936 offbox = str(blcx)+','+str(blcy)+','+str(trcx)+','+str(trcy)
00937 print "  Using Off-Source Box "+offbox
00938 
00939 offstat = imstat('ngc4826.tutorial.16apr98.src.clean.image',
00940                  box=offbox)
00941 
00942 print "Found off-source image rms = "+str(offstat['sigma'][0])
00943 
00944 # 256x256: cenbox = '108,108,148,148'
00945 # 400x400: cenbox = '180,180,320,320'
00946 # 512x512: cenbox = '236,236,276,276'
00947 # 800x800: cenbox = '380,380,420,420'
00948 blcx = refpix - 20
00949 blcy = refpix - 20
00950 trcx = refpix + 20
00951 trcy = refpix + 20
00952 cenbox = str(blcx)+','+str(blcy)+','+str(trcx)+','+str(trcy)
00953 print "  Using On-Source Box "+cenbox
00954 
00955 # offlinechan = '0,1,2,3,4,5,30,31,32,33,34,35'
00956 
00957 offlinestat = imstat('ngc4826.tutorial.16apr98.src.clean.image',
00958                      box=cenbox,
00959                      chans='0,1,2,3,4,5,30,31,32,33,34,35')
00960 
00961 print "Found off-line image rms = "+str(offlinestat['sigma'][0])
00962 
00963 #
00964 ##########################################################################
00965 #
00966 # Statistics on clean model
00967 #
00968 print '--ImStat (Clean model)--'
00969 
00970 modstat = imstat('ngc4826.tutorial.16apr98.src.clean.model')
00971 
00972 print "Found total model flux = "+str(modstat['sum'][0])
00973 
00974 #
00975 ##########################################################################
00976 #
00977 # Manually correct for mosaic response pattern using .image/.flux images
00978 #
00979 print '--ImMath (PBcor)--'
00980 
00981 immath(outfile='ngc4826.tutorial.16apr98.src.clean.pbcor',
00982        mode='evalexpr',
00983        expr="'ngc4826.tutorial.16apr98.src.clean.image'/'ngc4826.tutorial.16apr98.src.clean.flux'")
00984 
00985 # now pbcor the model, be careful to mask zeros
00986 
00987 immath(outfile='ngc4826.tutorial.16apr98.src.clean.pbcormod',
00988        mode='evalexpr',
00989        expr="'ngc4826.tutorial.16apr98.src.clean.model'['ngc4826.tutorial.16apr98.src.clean.model'!=0.0]/'ngc4826.tutorial.16apr98.src.clean.flux'")
00990 
00991 
00992 #
00993 ##########################################################################
00994 #
00995 # Statistics on PBcor image cube
00996 #
00997 print '--ImStat (PBcor cube)--'
00998 
00999 pbcorstat = imstat('ngc4826.tutorial.16apr98.src.clean.pbcor')
01000 
01001 print "Found image max = "+str(pbcorstat['max'][0])
01002 
01003 pbcoroffstat = imstat('ngc4826.tutorial.16apr98.src.clean.pbcor',
01004                       box=offbox)
01005 
01006 print "Found off-source image rms = "+str(pbcoroffstat['sigma'][0])
01007 
01008 pbcorofflinestat = imstat('ngc4826.tutorial.16apr98.src.clean.pbcor',
01009                           box=cenbox,
01010                           chans='0,1,2,3,4,5,30,31,32,33,34,35')
01011 
01012 print "Found off-line image rms = "+str(pbcorofflinestat['sigma'][0])
01013 
01014 #
01015 # Statistics on PBcor image cube
01016 #
01017 print '--ImStat (PSF)--'
01018 
01019 psfstat = imstat('ngc4826.tutorial.16apr98.src.clean.psf',
01020                  box=refbox,chans='27')
01021 
01022 print "Found PSF value at refpix = "+str(psfstat['mean'][0])+" (should be 1.0)"
01023 
01024 if benchmarking:
01025     math2time=time.time()
01026 
01027 #
01028 # Statistics on PBcor model cube
01029 #
01030 print '--ImStat (PBcor model)--'
01031 
01032 pbcormodstat = imstat('ngc4826.tutorial.16apr98.src.clean.pbcormod')
01033 
01034 print "Found total model flux = "+str(pbcormodstat['sum'][0])
01035 
01036 #
01037 ##########################################################################
01038 #
01039 # Do zeroth and first moments
01040 #
01041 # NGC4826 LSR velocity is 408 km/s; delta is 20 km/s
01042 
01043 # NOTE: before 02-Jul-2008 (5631) the planes were 1-based, are now 0-based
01044 # was planes 7~28, now 6~27
01045 
01046 print '--ImMoments--'
01047 default('immoments')
01048 
01049 momfile = 'ngc4826.tutorial.16apr98.moments'
01050 momzeroimage = 'ngc4826.tutorial.16apr98.moments.integrated'
01051 momoneimage = 'ngc4826.tutorial.16apr98.moments.mom1'
01052 
01053 print "Calculating Moments 0,1 for PBcor image"
01054 
01055 # In the following we will let immoments figure out which axis
01056 # to collapse along, the spectral axis=3
01057 
01058 immoments(imagename='ngc4826.tutorial.16apr98.src.clean.pbcor',
01059           moments=[0],
01060           chans='6~27',
01061           outfile='ngc4826.tutorial.16apr98.moments.integrated') 
01062 
01063 # TUTORIAL NOTES: For moment 0 we use the image corrected for the
01064 # mosaic response to get correct integrated flux densities. However,
01065 # in *real signal* regions, the value of moment 1 is not dependent on
01066 # the flux being correct so the non-pb corrected SAULT image can be
01067 # used, this avoids having lots of junk show up at the edges of your
01068 # moment 1 image due to the primary beam correction. Try it both ways
01069 # and see for yourself.
01070 
01071 # TUTORIAL NOTES:
01072 #
01073 # Moments greater than zero need to have a conservative lower
01074 # flux cutoff to produce sensible results.
01075 
01076 immoments(imagename='ngc4826.tutorial.16apr98.src.clean.image',
01077           moments=[1],includepix=[0.2,1000.0],
01078           chans='6~27',
01079           outfile='ngc4826.tutorial.16apr98.moments.mom1') 
01080 
01081 # Now view the resulting images
01082 if scriptmode:
01083     viewer('ngc4826.tutorial.16apr98.moments.integrated')
01084     #
01085     print "Now viewing Moment-0 ngc4826.tutorial.16apr98.moments.integrated"
01086     print "Note PBCOR effects at field edge"
01087     print "Change the colorscale to get better image"
01088     print "You can also Open and overlay Contours of Moment-1 ngc4826.tutorial.16apr98.moments.mom1"
01089     print "Close the viewer when done"
01090     
01091     # Pause script if you are running in scriptmode
01092     user_check=raw_input('Return to continue script\n')
01093 
01094 # Do a moment one on channel 0 to check that the indexing is right
01095 # NOTE: THIS STILL CRASHES
01096 try:
01097     immoments(imagename='ngc4826.tutorial.16apr98.src.clean.image',
01098               moments=[1],includepix=[],
01099               chans='0',
01100               outfile='ngc4826.tutorial.16apr98.moments.plane0.mom1') 
01101 except:
01102     pass
01103 
01104 # Do a moment one on channel 35 to check that the indexing is right
01105 try:
01106     immoments(imagename='ngc4826.tutorial.16apr98.src.clean.image',
01107           moments=[1],includepix=[],
01108           chans='35',
01109           outfile='ngc4826.tutorial.16apr98.moments.plane35.mom1')
01110 except:
01111     pass
01112 
01113 if benchmarking:
01114     moments2time=time.time()
01115 
01116 #
01117 ##########################################################################
01118 #
01119 # Statistics on moment images
01120 #
01121 print '--ImStat (Moment images)--'
01122 
01123 momzerostat=imstat('ngc4826.tutorial.16apr98.moments.integrated')
01124 
01125 try:
01126     print "Found moment 0 max = "+str(momzerostat['max'][0])
01127     print "Found moment 0 rms = "+str(momzerostat['rms'][0])
01128 except:
01129     pass
01130 
01131 momonestat = imstat('ngc4826.tutorial.16apr98.moments.mom1')
01132 
01133 try:
01134     print "Found moment 1 median = "+str(momonestat['median'][0])
01135 except:
01136     pass
01137 
01138 
01139 
01140 ia.open('ngc4826.tutorial.16apr98.src.clean.image')
01141 csys=ia.coordsys()
01142 vel0=0.0
01143 vel35=0.0
01144 
01145 try:
01146     momoneplane0=imstat('ngc4826.tutorial.16apr98.moments.plane0.mom1')
01147     print "Found plane 0 moment 1 value = "+str(momoneplane0['median'][0])
01148 except:
01149     pass
01150 
01151 
01152 try:
01153     momoneplane35=imstat('ngc4826.tutorial.16apr98.moments.plane35.mom1')
01154     print "Found plane 35 moment 1 value = "+str(momoneplane35['median'][0])
01155 except:
01156     pass
01157 
01158 if(type(momoneplane0)==bool):
01159     vel0=csys.frequencytovelocity(ia.toworld([0,0,0,0])['numeric'][3])
01160 if(type(momoneplane35)==bool):
01161     vel35=csys.frequencytovelocity(ia.toworld([0,0,0,35])['numeric'][3])
01162 
01163 
01164 #
01165 ##########################################################################
01166 #
01167 # Get MS stats
01168 #
01169 ms.open('ngc4826.tutorial.16apr98.1310+323.split.ms')
01170 vismean_cal=pl.mean(ms.range(["amplitude"]).get("amplitude"))
01171 ms.close()
01172 ms.open('ngc4826.tutorial.16apr98.src.split.ms')
01173 vismean_src=pl.mean(ms.range(["amplitude"]).get("amplitude"))
01174 ms.close()
01175 
01176 #
01177 ##########################################################################
01178 #
01179 # An alternative is to mask the pbcor image before calculating
01180 # moments.  The following block shows how to do this.
01181 
01182 # To do this, open the clean pbcor file in the viewer and use the
01183 # Region Manager to create a region file
01184 
01185 #print '--Viewer--'
01186 #viewer(ngc4826.tutorial.16apr98.src.clean.pbcor)
01187 
01188 # TUTORIAL NOTES: After loading ngc4826.tutorial.16apr98.src.clean.pbcor
01189 # in the viewer as a raster, click on the file icon in top left
01190 # corner, and select the momzero image but open as a Contour map
01191 # instead of Raster. Then decrease "contour scale factor" in "Data
01192 # Display Options" gui to something like 10. select "region manager
01193 # tool" from "tool" drop down menu In region manager tool select "all
01194 # axes". Then assign the sqiggly Polygon button to a mouse button by
01195 # clicking on it with a mouse button. Then draw a polygon region
01196 # around galaxy emission, avoiding edge regions. Then in "region
01197 # manager tool" select "save last region".
01198 
01199 # Pause script if you are running in scriptmode
01200 #user_check=raw_input('Return to continue script\n')
01201 
01202 # You should have created region file ngc4826.tutorial.16apr98.src.clean.pbcor.rgn
01203 
01204 # Now use immath to use the region file to mask the cube
01205 #
01206 #print '--ImMath (masking)--'
01207 #immath(outfile='ngc4826.tutorial.16apr98.src.clean.pbcor.masked',
01208 #       mode='evalexpr',
01209 #       expr="'ngc4826.tutorial.16apr98.src.clean.pbcor'",
01210 #       region='ngc4826.tutorial.16apr98.src.clean.pbcor.rgn')
01211 
01212 #
01213 # And then make masked moment images
01214 
01215 #print '--ImMoments (masked)--'
01216 #print 'Creating masked moment 0 image ngc4826.tutorial.16apr98.moments.integratedmasked'
01217 #       
01218 #immoments(imagename='ngc4826.tutorial.16apr98.src.clean.pbcor.masked',
01219 #          moments=0,axis=3,
01220 #          planes='6~27',
01221 #          outfile='ngc4826.tutorial.16apr98.moments.integratedmasked') 
01222 #
01223 #print 'Creating masked moment 1 image ngc4826.tutorial.16apr98.moments.mom1masked'
01224 #
01225 #immoments(imagename='ngc4826.tutorial.16apr98.src.clean.pbcor.masked',
01226 #          moments=1,axis=3,
01227 #          includepix=[0.2,1000.0],
01228 #          planes='6~27',
01229 #          outfile='ngc4826.tutorial.16apr98.moments.mom1masked') 
01230 
01231 # Now view the resulting images
01232 #viewer('ngc4826.tutorial.16apr98.moments.integratedmasked')
01233 #
01234 #print "Now viewing masked Moment-0 ngc4826.tutorial.16apr98.moments.integratedmasked"
01235 #print "You can Open and overlay Contours of Moment-1 ngc4826.tutorial.16apr98.moments.mom1masked"
01236 #
01237 # Pause script if you are running in scriptmode
01238 #user_check=raw_input('Return to continue script\n')
01239 
01240 # Finally, can compute and print statistics
01241 #print '--ImStat (masked moments)--'
01242 #
01243 #maskedmomzerostat = imstat('ngc4826.tutorial.16apr98.moments.integratedmasked')
01244 #print "Found masked moment 0 max = "+str(maskedmomzerostat['max'][0])
01245 #print "Found masked moment 0 rms = "+str(maskedmomzerostat['rms'][0])
01246 #
01247 #maskedmomonestat=imstat('ngc4826.tutorial.16apr98.moments.mom1masked')
01248 #print "Found masked moment 1 median = "+str(maskedmomonestat['median'][0])
01249 
01250 if benchmarking:
01251     endProc=time.clock()
01252     endTime=time.time()
01253 
01254 #
01255 ##########################################################################
01256 # Previous results to be used for regression
01257 
01258 # Canonical regression values (using this script STM 2008-06-04) were:
01259 #vis_mean_cal=4.3269
01260 #vis_mean_src=156.992
01261 #clean_image_max=1.45868253708
01262 #clean_offsrc_rms=0.0438643493782
01263 #clean_offline_rms=0.0544108718199
01264 #clean_momentzero_max=169.420959473
01265 #clean_momentzero_rms=14.3375244141
01266 # And from STM 2008-06-18
01267 #clean_momentone_median=428.43
01268 # And from STM 2008-06-30
01269 #clean_momentone_planezero = 688.575012
01270 #clean_momentone_planelast = 119.659264
01271 # MS mean STM 2008-07-02
01272 #vis_mean_cal = 194.613642
01273 #vis_mean_src = 54.583024
01274 
01275 #New values STM 2008-10-06 Patch3 (gaincal fix)
01276 #clean_image_max = 1.466937
01277 #clean_offsrc_rms = 0.043549
01278 #clean_offline_rms = 0.054727
01279 #clean_momentzero_max = 174.315887
01280 #clean_momentzero_rms = 14.601299
01281 #clean_momentone_median = 427.726257
01282 #clean_momentone_planezero = 688.575012
01283 #clean_momentone_planelast = 119.659264
01284 #vis_mean_cal = 194.914215
01285 #vis_mean_src = 54.626986
01286 
01287 #New model fluxes STM 2008-10-23 Patch3
01288 #  from run w/o clean mosaic pb change using 256x256 image
01289 #model_sum = 73.183142
01290 #model_pbcor_sum = 76.960971
01291 
01292 #New values STM 2008-12-01 Patch3.0 (released version)
01293 #for 400x400 clean 
01294 #testdate = '2008-12-01 (STM)'
01295 #testvers = 'CASA Version 2.3.0 Rev 6654'
01296 #clean_image_max = 1.481322
01297 #clean_offsrc_rms = 0.043665
01298 #clean_offline_rms = 0.055379
01299 #clean_momentzero_max = 174.731827
01300 #clean_momentzero_rms = 14.858011
01301 #clean_momentone_median = 428.499237
01302 #clean_momentone_planezero = 688.575012
01303 #clean_momentone_planelast = 119.659264
01304 #vis_mean_cal = 194.915497
01305 #vis_mean_src = 54.627127
01306 #model_sum = 72.437971
01307 #model_pbcor_sum = 70.417830
01308 
01309 #New values STM 2009-02-25 Patch3.1
01310 #for 400x400 clean 
01311 #testdate = '2009-02-25 (STM)'
01312 #testvers = 'CASA Version 2.3.1 Rev 6826'
01313 #clean_image_max = 1.481322
01314 #clean_offsrc_rms = 0.043665
01315 #clean_offline_rms = 0.055379
01316 #clean_momentzero_max = 174.731842
01317 #clean_momentzero_rms = 14.858011
01318 #clean_momentone_median = 428.499237
01319 #clean_momentone_planezero = 688.575012
01320 #clean_momentone_planelast = 119.659264
01321 #vis_mean_cal = 194.915497
01322 #vis_mean_src = 54.627127
01323 #model_sum = 72.437973
01324 #model_pbcor_sum = 70.417831
01325 
01326 #New values STM 2009-06-19 Patch4 (released version)
01327 #for 400x400 clean
01328 #testdate = '2009-06-19 (STM)'
01329 #testvers = 'CASA Version 2.4.0 Rev 8115'
01330 #clean_image_max = 1.418478
01331 #clean_offsrc_rms = 0.043584
01332 #clean_offline_rms = 0.056824
01333 #clean_momentzero_max = 171.601685
01334 #clean_momentzero_rms = 15.532441
01335 #clean_momentone_median = 428.499237
01336 #clean_momentone_planezero = 688.575012
01337 #clean_momentone_planelast = 119.659264
01338 #vis_mean_cal = 194.915497
01339 #vis_mean_src = 54.627127
01340 #model_sum = 70.707405
01341 #model_pbcor_sum = 63.006854
01342 
01343 #New values KG 2009-11-01 Release 0 (prerelease version)
01344 #for 400x400 clean
01345 #new values for flat noise clean
01346 #testdate = '2009-12-02 (KG)'
01347 #testvers = 'CASA Version 3.0.0 Rev 9692'
01348 #clean_image_max = 1.46
01349 #clean_offsrc_rms = 0.0573
01350 #clean_offline_rms = 0.05429
01351 #clean_momentzero_max = 165.7
01352 #clean_momentzero_rms = 15.1
01353 #clean_momentone_median = 422.84
01354 #clean_momentone_planezero = 688.575012
01355 #clean_momentone_planelast = 119.659264
01356 #vis_mean_cal = 194.915497
01357 #vis_mean_src = 54.627127
01358 #model_sum = 74.374
01359 #model_pbcor_sum = 65.319
01360 
01361 ## #New values STM 2009-12-02 Release 0 (prerelease version)
01362 ## #for 400x400 clean
01363 ## #new values for flat noise clean
01364 ## testdate = '2009-12-02 (STM)'
01365 ## testvers = 'CASA Version 3.0.1 Rev 10130'
01366 ## clean_image_max = 1.465047 
01367 ## clean_offsrc_rms = 0.058497
01368 ## clean_offline_rms = 0.055416
01369 ## clean_momentzero_max = 163.726852
01370 ## clean_momentzero_rms = 15.206372
01371 ## clean_momentone_median = 428.326385
01372 ## clean_momentone_planezero = 696.702393
01373 ## clean_momentone_planelast = 127.786629
01374 ## vis_mean_cal = 194.915085
01375 ## vis_mean_src = 54.627020
01376 ## model_sum = 71.171693
01377 ## model_pbcor_sum = 61.853749
01378 
01379 ## #New values RR 2010-03-30 3.0.1 prerelease
01380 ## #for 400x400 clean
01381 ## #new values after start channel change.  I did not update passing values.
01382 ## testdate = '2010-03-30 (RR)'
01383 ## testvers = 'CASA Version 3.0.1 (build #10841)'
01384 ## clean_image_max = 1.615747 # was 1.465047 Peak hits a channel better?
01385 ## clean_offsrc_rms = 0.058497
01386 ## clean_offline_rms = 0.055416
01387 ## clean_momentzero_max = 163.726852
01388 ## clean_momentzero_rms = 15.206372
01389 ## clean_momentone_median = 429.658844 # was 428.326385; change << 1 chanwidth.
01390 ## clean_momentone_planezero = 696.702393
01391 ## clean_momentone_planelast = 127.786629
01392 ## vis_mean_cal = 194.915085
01393 ## vis_mean_src = 54.627020
01394 ## model_sum = 71.171693
01395 ## model_pbcor_sum = 66.882499 # was 61.853749 Peak hits a channel better?
01396 
01397 ## # slight change in regression values - reason not known yet.
01398 ## # Remy's changes to cleanhelper, or something from Sanjay or Kumar?
01399 ## testdate = '2010-04-24 (RR)'
01400 ## testvers = 'CASA Version 3.0.2 (build #11181)'
01401 ## clean_image_max = 1.615747
01402 ## clean_offsrc_rms = 0.058497
01403 ## clean_offline_rms = 0.055416
01404 ## clean_momentzero_max = 163.726852
01405 ## clean_momentzero_rms = 15.206372
01406 ## clean_momentone_median = 423.6954 # was 429.6588; change << 1 chanwidth.
01407 ## clean_momentone_planezero = 696.702393
01408 ## clean_momentone_planelast = 127.786629
01409 ## vis_mean_cal = 194.915085
01410 ## vis_mean_src = 54.627020
01411 ## model_sum = 71.171693
01412 ## model_pbcor_sum = 75.92 # was 66.88 Peak hits a channel better?
01413 
01414 # slight change in 1 regression value - Kumar fixed a bug in setjy with
01415 # multiple spws, which could affect this script.
01416 testdate = '2010-04-29 (RR)'
01417 testvers = 'CASA Version 3.0.2 (build #11306)'
01418 clean_image_max = 1.615747
01419 clean_offsrc_rms = 0.058497
01420 clean_offline_rms = 0.055416
01421 clean_momentzero_max = 165.74
01422 clean_momentzero_rms = 14.234
01423 #
01424 #  32 bits gets 423.6954 and 64 bits gets 422.142792
01425 #  diff << 1 chanwidth.
01426 clean_momentone_median = 422.92
01427 clean_momentone_planezero = 696.702393
01428 clean_momentone_planelast = 127.786629
01429 vis_mean_cal = 195.0509
01430 vis_mean_src = 54.665
01431 model_sum = 71.349
01432 model_pbcor_sum = 75.92 # was 66.88 Peak hits a channel better?
01433 
01434 # RR, 1/19/2011 - The rmses went down, just like in orionmos4sim.  This is
01435 # good, so I won't complain too loudly.  The moment 1 median and pbcor_sum have
01436 # jiggled around a fair bit.  The median is _not_ affected by the two spurious
01437 # blobs at 501.64 km/s, though.  (Verified by doing imstat with a tight polygon
01438 # region.)
01439 clean_offsrc_rms = 0.0604
01440 clean_offline_rms = 0.0625
01441 clean_momentzero_rms = 14.05
01442 # The chanwidth is ~16 km/s.
01443 clean_momentone_median = 435.368103
01444 
01445 model_pbcor_sum = 72.72
01446 
01447 ## # RR, 3/11/2011 - The rmses went up, but not to their historical maxima.  The
01448 ## # model_pbcor_sum went down, but not to its historical minimum.  Nobody seems
01449 ## # to know why.
01450 ## clean_offsrc_rms = 0.0535
01451 ## clean_offline_rms = 0.0563
01452 ## model_pbcor_sum = 62.5022
01453 ## # RR, 3/12/2011 - And now, mysteriously, they're back to their 1/19/2011 values.
01454 
01455 ## RR, 3/25 - 4/3/2011, after clean was changed to used the center of output
01456 ## channel frequencies, instead of center of the first input channel in each
01457 ## output channel.
01458 clean_image_max = 1.4647
01459 clean_momentone_median = 424.40
01460 clean_momentone_planezero = 690.6068
01461 clean_momentone_planelast = 121.6911
01462 
01463 canonical = {}
01464 canonical['exist'] = True
01465 
01466 canonical['date'] = testdate
01467 canonical['version'] = testvers
01468 canonical['user'] = 'smyers'
01469 canonical['host'] = 'sandrock'
01470 canonical['cwd'] = '/home/sandrock/smyers/Testing/Patch4/N4826'
01471 print "Using internal regression from "+canonical['version']+" on "+canonical['date']
01472 
01473 canonical_results = {}
01474 canonical_results['clean_image_max'] = {}
01475 canonical_results['clean_image_max']['value'] = clean_image_max
01476 canonical_results['clean_image_offsrc_max'] = {}
01477 canonical_results['clean_image_offsrc_max']['value'] = clean_offsrc_rms
01478 canonical_results['clean_image_offline_max'] = {}
01479 canonical_results['clean_image_offline_max']['value'] = clean_offline_rms
01480 canonical_results['clean_momentzero_max'] = {}
01481 canonical_results['clean_momentzero_max']['value'] = clean_momentzero_max
01482 canonical_results['clean_momentzero_rms'] = {}
01483 canonical_results['clean_momentzero_rms']['value'] = clean_momentzero_rms
01484 # And from STM 2008-06-18
01485 canonical_results['clean_momentone_median'] = {}
01486 canonical_results['clean_momentone_median']['value'] = clean_momentone_median
01487 # And from STM 2008-06-30
01488 canonical_results['clean_momentone_planezero'] = {}
01489 canonical_results['clean_momentone_planezero']['value'] = clean_momentone_planezero
01490 canonical_results['clean_momentone_planelast'] = {}
01491 canonical_results['clean_momentone_planelast']['value'] = clean_momentone_planelast
01492 canonical_results['clean_psfcenter'] = {}
01493 canonical_results['clean_psfcenter']['value'] = 1.0
01494 
01495 # MS mean STM 2008-07-02
01496 canonical_results['vis_mean_cal'] = {}
01497 canonical_results['vis_mean_cal']['value'] = vis_mean_cal
01498 canonical_results['vis_mean_src'] = {}
01499 canonical_results['vis_mean_src']['value'] = vis_mean_src
01500 
01501 # Model fluxes STM 2008-10-22
01502 canonical_results['model_sum'] = {}
01503 canonical_results['model_sum']['value'] = model_sum
01504 canonical_results['model_pbcor_sum'] = {}
01505 canonical_results['model_pbcor_sum']['value'] = model_pbcor_sum
01506 
01507 canonical['results'] = canonical_results
01508 
01509 print "Canonical Regression (default) from "+canonical['date']
01510 
01511 #
01512 # Try and load previous results from regression file
01513 #
01514 regression = {}
01515 regressfile = scriptprefix + '.pickle'
01516 prev_results = {}
01517 
01518 try:
01519     fr = open(regressfile,'r')
01520 except:
01521     print "No previous regression results file "+regressfile
01522     regression['exist'] = False
01523 else:
01524     u = pickle.Unpickler(fr)
01525     regression = u.load()
01526     fr.close()
01527     print "Regression results filled from "+regressfile
01528     print "Regression from version "+regression['version']+" on "+regression['date']
01529     regression['exist'] = True
01530 
01531     prev_results = regression['results']
01532     
01533 #
01534 ##########################################################################
01535 # Calculate regression values
01536 ##########################################################################
01537 #
01538 print '--Calculate Results--'
01539 print ''
01540 #
01541 # Currently using non-PBcor values
01542 #
01543 try:
01544     srcmax = srcstat['max'][0]
01545 except:
01546     srcmax = 0.0
01547 
01548 try:
01549     offrms = offstat['sigma'][0]
01550 except:
01551     offrms = 0.0
01552 
01553 try:
01554     offlinerms = offlinestat['sigma'][0]
01555 except:
01556     offlinerms = 0.0
01557     
01558 try:
01559     momzero_max = momzerostat['max'][0]
01560 except:
01561     momzero_max = 0.0
01562 
01563 try:
01564     momzero_rms = momzerostat['rms'][0]
01565 except:
01566     momzero_rms = 0.0
01567 
01568 try:
01569     momone_median = momonestat['median'][0]
01570 except:
01571     momone_median = 0.0
01572 
01573 #
01574 # Added these sanity checks STM 2008-06-30
01575 #
01576 try:
01577     momone_plane0 = momoneplane0['median'][0]
01578 except:
01579     momone_plane0 = vel0
01580 
01581 try:
01582     momone_plane35 = momoneplane35['median'][0]
01583 except:
01584     momone_plane35 = vel35
01585 
01586 try:
01587     psfcenter = psfstat['mean'][0]
01588 except:
01589     psfcenter = 0.0
01590 
01591 #
01592 # Added model image fluxes STM 2008-10-22
01593 #
01594 try:
01595     modflux = modstat['sum'][0]
01596 except:
01597     modflux = 0.0
01598 
01599 try:
01600     pbcormodflux = pbcormodstat['sum'][0]
01601 except:
01602     pbcormodflux = 0.0
01603 
01604 #
01605 # Store results in dictionary
01606 #
01607 new_regression = {}
01608 
01609 # Some date and version info
01610 import datetime
01611 datestring=datetime.datetime.isoformat(datetime.datetime.today())
01612 
01613 # System info
01614 myvers = casalog.version()
01615 try:
01616     myuser = os.getlogin()
01617 except:
01618     myuser = os.getenv('USER')
01619 #myhost = str( os.getenv('HOST') )
01620 myuname = os.uname()
01621 myhost = myuname[1]
01622 myos = myuname[0]+' '+myuname[2]+' '+myuname[4]
01623 mycwd = os.getcwd()
01624 mypath = os.environ.get('CASAPATH')
01625 
01626 mydataset = 'NGC4826 16apr98 BIMA'
01627 
01628 # Save info in regression dictionary
01629 new_regression['date'] = datestring
01630 new_regression['version'] = myvers
01631 new_regression['user'] = myuser
01632 new_regression['host'] = myhost
01633 new_regression['cwd'] = mycwd
01634 new_regression['os'] = myos
01635 new_regression['uname'] = myuname
01636 new_regression['aipspath'] = mypath
01637 
01638 new_regression['dataset'] = mydataset
01639 
01640 # Fill results
01641 # Note that 'op' tells what to do for the diff :
01642 #    'divf' = abs( new - prev )/prev
01643 #    'diff' = new - prev
01644 
01645 results = {}
01646 
01647 op = 'divf'
01648 tol = 0.08
01649 results['clean_image_max'] = {}
01650 results['clean_image_max']['name'] = 'Clean image max'
01651 results['clean_image_max']['value'] = srcmax
01652 results['clean_image_max']['op'] = op
01653 results['clean_image_max']['tol'] = tol
01654 
01655 results['clean_image_offsrc_max'] = {}
01656 results['clean_image_offsrc_max']['name'] = 'Clean image off-src rms'
01657 results['clean_image_offsrc_max']['value'] = offrms
01658 results['clean_image_offsrc_max']['op'] = op
01659 results['clean_image_offsrc_max']['tol'] = tol
01660 
01661 results['clean_image_offline_max'] = {}
01662 results['clean_image_offline_max']['name'] = 'Clean image off-line rms'
01663 results['clean_image_offline_max']['value'] = offlinerms
01664 results['clean_image_offline_max']['op'] = op
01665 results['clean_image_offline_max']['tol'] = tol
01666 
01667 results['clean_momentzero_max'] = {}
01668 results['clean_momentzero_max']['name'] = 'Moment 0 image max'
01669 results['clean_momentzero_max']['value'] = momzero_max
01670 results['clean_momentzero_max']['op'] = op
01671 results['clean_momentzero_max']['tol'] = tol
01672 
01673 results['clean_momentzero_rms'] = {}
01674 results['clean_momentzero_rms']['name'] = 'Moment 0 image rms'
01675 results['clean_momentzero_rms']['value'] = momzero_rms
01676 results['clean_momentzero_rms']['op'] = op
01677 results['clean_momentzero_rms']['tol'] = tol
01678 
01679 op = 'diff'
01680 tol = 0.1
01681 results['clean_momentone_median'] = {}
01682 results['clean_momentone_median']['name'] = 'Moment 1 image median'
01683 results['clean_momentone_median']['value'] = momone_median
01684 results['clean_momentone_median']['op'] = op
01685 results['clean_momentone_median']['tol'] = 3.0 # km/s.  Was 0.1 before CAS-2163.
01686 
01687 #
01688 # Added these sanity checks STM 2008-06-30
01689 #
01690 results['clean_momentone_planezero'] = {}
01691 results['clean_momentone_planezero']['name'] = 'Moment 1 plane 0'
01692 results['clean_momentone_planezero']['value'] = momone_plane0
01693 results['clean_momentone_planezero']['op'] = op
01694 results['clean_momentone_planezero']['tol'] = tol
01695 
01696 results['clean_momentone_planelast'] = {}
01697 results['clean_momentone_planelast']['name'] = 'Moment 1 plane 35'
01698 results['clean_momentone_planelast']['value'] = momone_plane35
01699 results['clean_momentone_planelast']['op'] = op
01700 results['clean_momentone_planelast']['tol'] = tol
01701 
01702 tol = 0.01
01703 results['clean_psfcenter'] = {}
01704 results['clean_psfcenter']['name'] = 'PSF CH27 at RefPix'
01705 results['clean_psfcenter']['value'] = psfcenter
01706 results['clean_psfcenter']['op'] = op
01707 results['clean_psfcenter']['tol'] = tol
01708 
01709 # And return the ms mean 2008-07-02 STM
01710 op = 'divf'
01711 tol = 0.08
01712 results['vis_mean_cal'] = {}
01713 results['vis_mean_cal']['name'] = 'Vis mean of cal'
01714 results['vis_mean_cal']['value'] = vismean_cal
01715 results['vis_mean_cal']['op'] = op
01716 results['vis_mean_cal']['tol'] = tol
01717 
01718 results['vis_mean_src'] = {}
01719 results['vis_mean_src']['name'] = 'Vis mean of src'
01720 results['vis_mean_src']['value'] = vismean_src
01721 results['vis_mean_src']['op'] = op
01722 results['vis_mean_src']['tol'] = tol
01723 
01724 # model total fluxes 2008-10-22 STM
01725 
01726 results['model_sum'] = {}
01727 results['model_sum']['name'] = 'Model image sum'
01728 results['model_sum']['value'] = modflux
01729 results['model_sum']['op'] = op
01730 results['model_sum']['tol'] = tol
01731 
01732 results['model_pbcor_sum'] = {}
01733 results['model_pbcor_sum']['name'] = 'PBcor Model image sum'
01734 results['model_pbcor_sum']['value'] = pbcormodflux
01735 results['model_pbcor_sum']['op'] = op
01736 results['model_pbcor_sum']['tol'] = tol
01737 
01738 # Now go through and regress
01739 resultlist = ['clean_image_max','clean_image_offsrc_max','clean_image_offline_max',
01740               'clean_momentzero_max','clean_momentzero_rms','clean_momentone_median',
01741               'clean_momentone_planezero','clean_momentone_planelast','clean_psfcenter',
01742               'vis_mean_cal','vis_mean_src','model_sum','model_pbcor_sum']
01743 
01744 for keys in resultlist:
01745     res = results[keys]
01746     prev = None
01747     if prev_results.has_key(keys):
01748         # This is a known regression
01749         prev = prev_results[keys]
01750         results[keys]['test'] = 'Last'
01751     elif canonical_results.has_key(keys):
01752         # Go back to canonical values
01753         prev = canonical_results[keys]
01754         results[keys]['test'] = 'Canon'
01755     if prev:
01756         new_val = res['value']
01757         prev_val = prev['value']
01758         new_diff = new_val - prev_val
01759         if res['op'] == 'divf':
01760             new_diff /= prev_val
01761 
01762         if abs(new_diff) > res['tol']:
01763             new_status = 'Failed'
01764         else:
01765             new_status = 'Passed'
01766         
01767         results[keys]['prev'] = prev_val
01768         results[keys]['diff'] = new_diff
01769         results[keys]['status'] = new_status
01770     else:
01771         # Unknown regression key
01772         results[keys]['prev'] = 0.0
01773         results[keys]['diff'] = 1.0
01774         results[keys]['status'] = 'Missed'
01775         results[keys]['test'] = 'none'
01776 
01777 # Done filling results
01778 new_regression['results'] = results
01779 
01780 # Dataset size info
01781 datasize_raw = 96.0 # MB
01782 datasize_ms = 279.0 # MB
01783 new_regression['datasize'] = {}
01784 new_regression['datasize']['raw'] = datasize_raw
01785 new_regression['datasize']['ms'] = datasize_ms
01786 
01787 #
01788 # Timing
01789 #
01790 if benchmarking:
01791     # Save timing to regression dictionary
01792     new_regression['timing'] = {}
01793 
01794     total = {}
01795     total['wall'] = (endTime - startTime)
01796     total['cpu'] = (endProc - startProc)
01797     total['rate_raw'] = (datasize_raw/(endTime - startTime))
01798     total['rate_ms'] = (datasize_ms/(endTime - startTime))
01799 
01800     new_regression['timing']['total'] = total
01801 
01802     nstages = 15
01803     new_regression['timing']['nstages'] = nstages
01804 
01805     stages = {}
01806     stages[0] = ['import',(import2time-startTime)]
01807     stages[1] = ['concat',(concat2time-import2time)]
01808     stages[2] = ['clearcal',(clearcal2time-concat2time)]
01809     stages[3] = ['listobs',(list2time-clearcal2time)]
01810     stages[4] = ['plotxy',(plotxy2time-list2time)]
01811     stages[5] = ['tflagdata',(flag2time-plotxy2time)]
01812     stages[6] = ['setjy',(setjy2time-flag2time)]
01813     stages[7] = ['gaincal',(gaincal2time-setjy2time)]
01814     stages[8] = ['fluxscale',(fluxscale2time-gaincal2time)]
01815     stages[9] = ['plotcal',(plotcal2time-fluxscale2time)]
01816     stages[10] = ['applycal',(correct2time-plotcal2time)]
01817     stages[11] = ['split',(split2time-correct2time)]
01818     stages[12] = ['clean',(clean2time-split2time)]
01819     stages[13] = ['math/stat',(math2time-clean2time)]
01820     stages[14] = ['moments',(moments2time-math2time)]
01821     
01822     new_regression['timing']['stages'] = stages
01823 
01824 #
01825 ##########################################################################
01826 #
01827 # Save regression results as dictionary using Pickle
01828 #
01829 pickfile = 'out.'+prefix + '.regression.'+datestring+'.pickle'
01830 f = open(pickfile,'w')
01831 p = pickle.Pickler(f)
01832 p.dump(new_regression)
01833 f.close()
01834 
01835 print ""
01836 print "Regression result dictionary saved in "+pickfile
01837 print ""
01838 print "Use Pickle to retrieve these"
01839 print ""
01840 
01841 # e.g.
01842 # f = open(pickfile)
01843 # u = pickle.Unpickler(f)
01844 # clnmodel = u.load()
01845 # polmodel = u.load()
01846 # f.close()
01847 
01848 #
01849 ##########################################################################
01850 #
01851 # Now print out results
01852 # The following writes a logfile for posterity
01853 #
01854 ##########################################################################
01855 #
01856 #outfile='n4826.'+datestring+'.log'
01857 outfile='out.'+prefix+'.'+datestring+'.log'
01858 logfile=open(outfile,'w')
01859 
01860 # Print version info to outfile
01861 print >>logfile,'Running '+myvers+' on host '+myhost
01862 print >>logfile,'at '+datestring
01863 print >>logfile,''
01864 
01865 #
01866 # Report a few key stats
01867 #
01868 print '  NGC4826 Image Cube Max = '+str(srcstat['max'][0])
01869 print "          At ("+str(srcstat['maxpos'][0])+","+str(srcstat['maxpos'][1])+") Channel "+str(srcstat['maxpos'][3])
01870 print '          '+srcstat['maxposf']
01871 print ''
01872 print '          Off-Source Rms = '+str(offstat['sigma'][0])
01873 print '          Signal-to-Noise ratio = '+str(srcstat['max'][0]/offstat['sigma'][0])
01874 print ''
01875 print '          Off-Line   Rms = '+str(offlinestat['sigma'][0])
01876 print '          Signal-to-Noise ratio = '+str(srcstat['max'][0]/offlinestat['sigma'][0])
01877 print ''
01878 
01879 print >>logfile,'  NGC4826 Image Cube Max = '+str(srcstat['max'][0])
01880 print >>logfile,"          At ("+str(srcstat['maxpos'][0])+","+str(srcstat['maxpos'][1])+") Channel "+str(srcstat['maxpos'][3])
01881 print >>logfile,'          '+srcstat['maxposf']
01882 print >>logfile,''
01883 print >>logfile,'          Off-Source Rms = '+str(offstat['sigma'][0])
01884 print >>logfile,'          Signal-to-Noise ratio = '+str(srcstat['max'][0]/offstat['sigma'][0])
01885 print >>logfile,''
01886 print >>logfile,'          Off-Line   Rms = '+str(offlinestat['sigma'][0])
01887 print >>logfile,'          Signal-to-Noise ratio = '+str(srcstat['max'][0]/offlinestat['sigma'][0])
01888 print >>logfile,''
01889 
01890 # Print out comparison:
01891 res = {}
01892 resultlist = ['clean_image_max','clean_image_offsrc_max','clean_image_offline_max',
01893                'clean_momentzero_max','clean_momentzero_rms','clean_momentone_median',
01894               'clean_momentone_planezero','clean_momentone_planelast','clean_psfcenter',
01895               'vis_mean_cal','vis_mean_src','model_sum','model_pbcor_sum']
01896 
01897 # First versus canonical values
01898 print >>logfile,'---'
01899 print >>logfile,'Regression versus previous values:'
01900 print >>logfile,'---'
01901 print '---'
01902 print 'Regression versus previous values:'
01903 print '---'
01904 
01905 if regression['exist']:
01906     print >>logfile,"  Regression results filled from "+regressfile
01907     print >>logfile,"  Regression from version "+regression['version']+" on "+regression['date']
01908     print >>logfile,"  Regression platform "+regression['host']
01909     
01910     print "  Regression results filled from "+regressfile
01911     print "  Regression from version "+regression['version']+" on "+regression['date']
01912     print "  Regression platform "+regression['host']
01913     if regression.has_key('aipspath'):
01914         print >>logfile,"  Regression casapath "+regression['aipspath']
01915         print "  Regression casapath "+regression['aipspath']
01916     
01917 else:
01918     print >>logfile,"  No previous regression file"
01919 
01920 print ""
01921 print >>logfile,""
01922 
01923 final_status = 'Passed'
01924 for keys in resultlist:
01925     res = results[keys]
01926     print '--%30s : %12.6f was %12.6f %4s %12.6f (%6s) %s ' % ( res['name'], res['value'], res['prev'], res['op'], res['diff'], res['status'], res['test'] )
01927     print >>logfile,'--%30s : %12.6f was %12.6f %4s %12.6f (%6s) %s ' % ( res['name'], res['value'], res['prev'], res['op'], res['diff'], res['status'], res['test'] )
01928     if res['status']=='Failed':
01929         final_status = 'Failed'
01930 
01931 if (final_status == 'Passed'):
01932     regstate=True
01933     print >>logfile,'---'
01934     print >>logfile,'Passed Regression test for NGC 4826 Mosaic'
01935     print >>logfile,'---'
01936     print 'Passed Regression test for NGC 4826 Mosaic'
01937     print ''
01938     print 'Regression PASSED'
01939     print ''
01940 else:
01941     regstate=False
01942     print >>logfile,'----FAILED Regression test for NGC 4826 Mosaic'
01943     print '----FAILED Regression test for NGC 4826 Mosaic'
01944     print ''
01945     print 'Regression FAILED'
01946     print ''
01947     
01948 #
01949 ##########################################################################
01950 # Print benchmarking etc.
01951 
01952 if benchmarking:
01953     print ''
01954     print 'Total wall clock time was: %10.3f ' % total['wall']
01955     print 'Total CPU        time was: %10.3f ' % total['cpu']
01956     print 'Raw processing rate MB/s was: %8.1f ' % total['rate_raw']
01957     print 'MS  processing rate MB/s was: %8.1f ' % total['rate_ms']
01958     print ''
01959     print '* Breakdown:                              *'
01960 
01961     print >>logfile,''
01962     print >>logfile,'********* Benchmarking *************************'
01963     print >>logfile,'*                                              *'
01964     print >>logfile,'Total wall clock time was: %10.3f ' % total['wall']
01965     print >>logfile,'Total CPU        time was: %10.3f ' % total['cpu']
01966     print >>logfile,'Raw processing rate MB/s was: %8.1f ' % total['rate_raw']
01967     print >>logfile,'MS  processing rate MB/s was: %8.1f ' % total['rate_ms']
01968     print >>logfile,'* Breakdown:                                   *'
01969 
01970     for i in range(nstages):
01971         print '* %16s * time was: %10.3f ' % tuple(stages[i])
01972         print >>logfile,'* %16s * time was: %10.3f ' % tuple(stages[i])
01973     
01974     print >>logfile,'************************************************'
01975     print >>logfile,'sandrock (2008-06-17) wall time was: 377 seconds'
01976     print >>logfile,'sandrock (2008-06-17) CPU  time was: 312 seconds'
01977 
01978 logfile.close()
01979 
01980 print "Done with NGC4826 Tutorial Regression"
01981 #
01982 ##########################################################################