casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
ngc2403_tutorial_regression.py
Go to the documentation of this file.
00001 ##########################################################################
00002 #                                                                        #
00003 # Use Case Script for reducing NGC 2403 HI line data                     #
00004 # This script reads four VLA archive files and stores them as a CASA     #
00005 # measurement set, and then processes it.                                #
00006 #                                                                        #
00007 # Original version GvM 2007-11-30        (Beta)                          #
00008 # Updated          GvM 2008-06-11        Beta Patch 2                    #
00009 # Modified/merge   STM 2008-07-25        Regressable version             #
00010 #                                                                        #
00011 # Based on 2008 Synthesis Imaging Summer School scripts                  #
00012 # NOTE: REGRESSION VERSION FOR CASA TESTING                              #
00013 #                                                                        #
00014 # Script Notes:                                                          #
00015 #    o WARNING: The MS generated by this script is 5.2GB (from the       #
00016 #      VLA export files that total 564MB).  This script can take         #
00017 #      40 minutes to run depending on your machine.                      #
00018 #                                                                        #
00019 #    o Uses the VLA export files AS649_1 to 4, which should be in the    #
00020 #      working directory that casapy was started in.  These VLA archive  #
00021 #      can be found in in the data repository at data/regression/ngc2403 #
00022 #                                                                        #
00023 #    o This script has some interactive commands, such as with           #
00024 #      the viewer.  If scriptmode=True, then this script                 #
00025 #      will stop and require a carriage-return to continue at these      #
00026 #      points.                                                           #
00027 #                                                                        #
00028 #    o Sometimes cut-and-paste of a series of lines from this script     #
00029 #      into the casapy terminal will get garbled (usually a single       #
00030 #      dropped character). In this case, try fewer lines, like groups    #
00031 #      of 4-6.                                                           #
00032 #                                                                        #
00033 #    o The results are written out as a dictionary in a pickle file      #
00034 #         out.ngc2403.tutorial.regression.<datestring>.pickle            #
00035 #      (not auto-deleted at start of script)                             #
00036 #                                                                        #
00037 #      This script keeps internal regression values, but you can provide #
00038 #      a file ngc2403_tutorial_regression.pickle from a previous run     #
00039 #                                                                        #
00040 #    o This script also generates a text file                            #
00041 #         out.ngc2403.tutorial.<datestring>.log                          #
00042 #      (not auto-deleted at start of script)                             #
00043 #                                                                        #
00044 ##########################################################################
00045 
00046 import time
00047 import os
00048 import pickle
00049 
00050 # 
00051 #=====================================================================
00052 #
00053 # This script has some interactive commands: scriptmode = True
00054 # if you are running it and want it to stop during interactive parts.
00055 
00056 scriptmode = False
00057 
00058 # Enable benchmarking?
00059 benchmarking = True
00060 
00061 #=====================================================================
00062 #
00063 # Set up some useful variables
00064 
00065 pathname=os.environ.get('CASAPATH').split()[0]
00066 
00067 prefix='n2403.tutorial'
00068 
00069 # Sets a shorthand for fixed input script/regression files
00070 scriptprefix='ngc2403_tutorial_regression'
00071 
00072 # These will be set later on, but set here also
00073 msfile = prefix + '.ms'
00074 splitfile = prefix + '.split.ms'
00075 outname = prefix + '.final.clean'
00076 momfile = outname + '.mom'
00077 
00078 #
00079 #=====================================================================
00080 # Clean up old versions of files to be created in this script
00081 
00082 os.system('rm -rf '+prefix+'.*')
00083 
00084 if benchmarking:
00085     startTime=time.time()
00086     startProc=time.clock()
00087 
00088 print 'Tutorial Regression Script for VLA NGC2403 HI data'
00089 print 'Will do: import, flagging, calibration, imaging'
00090 print ''
00091 #=====================================================================
00092 # Data Import
00093 #=====================================================================
00094 #
00095 # Import the data from VLA archive files to MS
00096 #
00097 print "--importvla--"
00098 print ""
00099 print " Use importvla to read 4 VLA archive files and write the data"
00100 print " into a Measurement Set (MS).  This will take a while ..."
00101 print ""
00102 
00103 # Set up the MS filename and save as new global variable
00104 msfile = prefix + '.ms'
00105 
00106 print " MS will be called "+msfile
00107 
00108 default('importvla')
00109 
00110 archivefiles=['AS649_1','AS649_2','AS649_3','AS649_4']
00111 vis = msfile
00112 importvla()
00113 
00114 if benchmarking:
00115     import2time=time.time()
00116 
00117 #=====================================================================
00118 # List a summary of the MS
00119 #=====================================================================
00120 #
00121 #
00122 print "--listobs--"
00123 print ""
00124 print " Use listobs to print verbose summary to logger"
00125 print " see the logger window for the listobs output"
00126 
00127 # Don't default this one and make use of the previous setting of
00128 # vis.  Remember, the variables are GLOBAL!
00129 
00130 # You may wish to see more detailed information, in this case
00131 # use the verbose = True option
00132 #
00133 verbose = True
00134 
00135 listobs()
00136 
00137 print ""
00138 print "The listobs output will be displayed in your logger window and in"
00139 print "the casapy.log file"
00140 
00141 if benchmarking:
00142     list2time=time.time()
00143 
00144 #=====================================================================
00145 # FLAGGING
00146 #=====================================================================
00147 #
00148 
00149     
00150 default('tflagdata')
00151 
00152 vis=msfile
00153 spw='0:5~112'
00154 correlation='RR'
00155 field='0'
00156 mode='manual'
00157 timerange='03:51:07~03:52:48'
00158 saveinputs('tflagdata',prefix+'.saved.tflagdata.n2403.rr.time0351')
00159 
00160 tflagdata()
00161 
00162 print ""
00163 print " now we clip RR above 0.4Jy"
00164 print ""
00165 
00166 mode='clip'
00167 timerange = ''
00168 correlation = 'RR'
00169 clipminmax = [-100, 0.4]
00170 saveinputs('tflagdata',prefix+'.saved.tflagdata.n2403.rr.clip')
00171 
00172 tflagdata()
00173 
00174 print ""
00175 print " now we clip LL above 1.0Jy"
00176 print ""
00177 
00178 timerange = ''
00179 correlation='LL'
00180 clipminmax = [-100, 1.0]
00181 saveinputs('tflagdata',prefix+'.saved.tflagdata.n2403.ll.clip')
00182 
00183 tflagdata()
00184 
00185 #=====================================================================
00186 # Save flagging done up to this point
00187 #=====================================================================
00188 #
00189 print ""
00190 print "--flagmanager--"
00191 print ""
00192 print " It is a good idea to save the flagging at certain times"
00193 print " First, list the flag versions using flagmanager"
00194 print ""
00195 
00196 # first we list the current flagging tables
00197 
00198 mode='list'
00199 
00200 flagmanager()
00201 
00202 print ""
00203 print " then, we save the flagging we just did"
00204 
00205 # then we save the flagging we just did
00206 
00207 mode='save'
00208 versionname='afterflagdata'
00209 comment='flags after running tflagdata'
00210 merge='replace'
00211 
00212 flagmanager()
00213 
00214 # and now we list one more time to show the changes made
00215 
00216 print ""
00217 print " then, list one more time to show the changes"
00218 
00219 
00220 mode='list'
00221 
00222 flagmanager()
00223 
00224 print " Done Flagging - proceed to Calibration"
00225 print ""
00226 
00227 if benchmarking:
00228     flag2time=time.time()
00229 
00230 #=====================================================================
00231 # CALIBRATION
00232 # Fill the model column for flux density calibrators
00233 #=====================================================================
00234 #
00235 print "--setjy--"
00236 print ""
00237 print " find the flux of the flux calibrators, and write it to the"
00238 print " column labeled MODEL_DATA"
00239 
00240 default('setjy')
00241 
00242 vis=msfile
00243 field='1,3,4'     # note: field 1 is the source NGC 2403, and field 2 is
00244                   # the phase calibrator 0841+708'
00245 spw='0:5~112'     # use spectral window 0 (which is the only one).  In that
00246                   # window, use channels 5 - 112 (ignoring edge channels)
00247 
00248 scalebychan=False
00249 
00250 standard='Perley-Taylor 99'  # enforce the older standard
00251 
00252 saveinputs('setjy',prefix+'.saved.setjy')
00253 
00254 setjy()
00255 
00256 if benchmarking:
00257     setjy2time=time.time()
00258 
00259 #=====================================================================
00260 # Determine antenna gains
00261 #=====================================================================
00262 #
00263 print "--gaincal--"
00264 print ""
00265 print " creates user defined table containing antenna gain solutions"
00266 print " once for each calibrator since uv ranges are different."
00267 print " Note: append is False first, then True"
00268 print ""
00269 
00270 default('gaincal')
00271 vis        = msfile
00272 caltable   = prefix + '.gcal'
00273 field      = '1'
00274 spw        = '0:5~112'
00275 selectdata = True
00276 uvrange    = '0~40klambda'
00277 solint     = 'inf'
00278 combine    = ''
00279 append     = False
00280 
00281 print " starting field 1"
00282 print ""
00283 
00284 saveinputs('gaincal',prefix+'.saved.gaincal.field1')
00285 
00286 gaincal()
00287 
00288 field='2'
00289 uvrange='0~20klambda'
00290 append=True
00291 
00292 print " starting field 2"
00293 print ""
00294 
00295 saveinputs('gaincal',prefix+'.saved.gaincal.field2')
00296 
00297 gaincal()
00298 
00299 field='3'
00300 uvrange='0~50klambda'
00301 
00302 print " starting field 3"
00303 print ""
00304 
00305 saveinputs('gaincal',prefix+'.saved.gaincal.field3')
00306 
00307 gaincal()
00308 
00309 field='4'
00310 uvrange=''
00311 
00312 print " starting field 4"
00313 print ""
00314 
00315 saveinputs('gaincal',prefix+'.saved.gaincal.field4')
00316 
00317 gaincal()
00318 
00319 if benchmarking:
00320     gaincal2time=time.time()
00321 
00322 #=====================================================================
00323 # Plot antenna gains
00324 #=====================================================================
00325 #
00326 print "--plotcal--"
00327 print ""
00328 print " first we plot the amplitude gains for antennas 9 - 12"
00329 
00330 default('plotcal')
00331 caltable= prefix + '.gcal'
00332 xaxis='time'
00333 yaxis='amp'
00334 field='2'
00335 antenna='9~12'
00336 
00337 print ""
00338 if scriptmode:
00339     showgui=T
00340     figfile=''
00341     saveinputs('plotcal',prefix+'.saved.plotcal.gaincal.ant9to12amp')
00342 
00343     plotcal()
00344 
00345     user_check=raw_input('Return to continue script\n')
00346 else:
00347     showgui=F
00348     figfile=prefix+'.plotcal.gaincal.amp.png'
00349     saveinputs('plotcal',prefix+'.saved.plotcal.gaincal.ant9to12amp')
00350 
00351     plotcal()
00352 
00353 
00354 print " then, we plot R and L just for antenna 9 in separate plots on"
00355 print " the same page.  Note use of the subplot parameter"
00356 
00357 yaxis='phase'
00358 antenna='9'
00359 poln='R'
00360 subplot=211
00361 saveinputs('plotcal',prefix+'.saved.plotcal.gaincal.ant9phase.panel1')
00362 
00363 if scriptmode:
00364     showgui=T
00365     plotcal()
00366 else:
00367     showgui=F
00368     figfile=''
00369     plotcal()
00370 
00371 poln='L'
00372 subplot=212
00373 
00374 print ""
00375 # Pause script if you are running in scriptmode
00376 if scriptmode:
00377     showgui=T
00378     figfile=''
00379     saveinputs('plotcal',prefix+'.saved.plotcal.gaincal.ant9phase.panel2')
00380 
00381     plotcal()
00382 
00383     print ""
00384     print " Next, we will determine the flux of 0841+708"
00385     user_check=raw_input('Return to continue script\n')
00386 else:
00387     showgui=F
00388     figfile=prefix+'.plotcal.gaincal.phase.png'
00389     saveinputs('plotcal',prefix+'.saved.plotcal.gaincal.ant9phase.panel2')
00390 
00391     plotcal()
00392 
00393 if benchmarking:
00394     plotgcal2time=time.time()
00395 
00396 #=====================================================================
00397 # Bootstrap flux of 0841+708
00398 #=====================================================================
00399 #
00400 print "--fluxscale--"
00401 print ""
00402 print " determines flux based on gains and flux calibrator fluxes"
00403 print " see Log window for flux value found"
00404 default('fluxscale')
00405 vis=msfile
00406 caltable= prefix + '.gcal'
00407 fluxtable=prefix + '.fcal'
00408 reference='1,3~4'
00409 transfer='2'
00410 
00411 saveinputs('fluxscale',prefix+'.saved.fluxscale')
00412 
00413 fluxscale()
00414 
00415 if benchmarking:
00416     fluxscale2time=time.time()
00417 
00418 #=====================================================================
00419 # Solves for bandpass, writes it to table
00420 #=====================================================================
00421 #
00422 print "--bandpass--"
00423 print ""
00424 print " determine bandpass"
00425 
00426 default('bandpass')
00427 
00428 vis      = msfile
00429 caltable = prefix + '.bcal'
00430 field    = '1,3~4'
00431 solint   = 'inf'
00432 combine  = ''
00433 solnorm  = True
00434 
00435 saveinputs('bandpass',prefix+'.saved.bandpass')
00436 
00437 bandpass()
00438 
00439 if benchmarking:
00440     bandpass2time=time.time()
00441 
00442 #=====================================================================
00443 # Plot bandpass
00444 #=====================================================================
00445 #
00446 print "--plotcal--"
00447 print ""
00448 print " First we plot solutions for antennas 9-12 for field 1 only"
00449 
00450 default('plotcal')
00451 
00452 vis=msfile
00453 caltable= prefix + '.bcal'
00454 xaxis               =     'chan'
00455 yaxis               =      'amp'
00456 field               =        '1'
00457 antenna             =     '9~12'
00458 plotrange           = [-1, -1, 0.9, 1.15]
00459 
00460 if scriptmode:
00461     showgui=T
00462     figfile=''
00463     saveinputs('plotcal',prefix+'.saved.plotcal.bandpass.field1.ant9to12amp')
00464 
00465     plotcal()
00466 
00467     print ""
00468     user_check=raw_input('Return to continue script\n')
00469 else:
00470     showgui=F
00471     figfile=prefix+'.plotcal.bandpass.field1.ant9to12amp.png'
00472     saveinputs('plotcal',prefix+'.saved.plotcal.bandpass.field1.ant9to12amp')
00473 
00474     plotcal()
00475 
00476 print ""
00477 
00478 antenna='25'
00479 
00480 if scriptmode:
00481     showgui=T
00482     field = '1,3~4'
00483     iteration='field'
00484     figfile=''
00485     saveinputs('plotcal',prefix+'.saved.plotcal.bandpass.fields.ant25amp')
00486 
00487     plotcal()
00488 
00489     print " we iterate over all three fields, just for antenna 25 using"
00490     print " the iteration parameter"
00491     print ""
00492 
00493     print " Make sure to click Next to go through the fields before hitting return"
00494     print ""
00495     print " note the galactic absorption in the first two fields"
00496     print " only field 4 (1331+305) is free of absorption"
00497     print " for now, we will use only bandpass solutions for field 4"
00498     print ""
00499     user_check=raw_input('Return when done to run applycal\n')
00500 
00501 else:
00502     showgui=F
00503     field = '1'
00504     iteration=''
00505     figfile=prefix+'.plotcal.bandpass.field1.ant25amp.png'
00506     saveinputs('plotcal',prefix+'.saved.plotcal.bandpass.field1.ant25amp')
00507 
00508     plotcal()
00509 
00510     field = '3'
00511     figfile=prefix+'.plotcal.bandpass.field3.ant25amp.png'
00512     saveinputs('plotcal',prefix+'.saved.plotcal.bandpass.field3.ant25amp')
00513 
00514     plotcal()
00515 
00516     field = '4'
00517     figfile=prefix+'.plotcal.bandpass.field4.ant25amp.png'
00518     saveinputs('plotcal',prefix+'.saved.plotcal.bandpass.field4.ant25amp')
00519 
00520     plotcal()
00521 
00522 if benchmarking:
00523     plotbcal2time=time.time()
00524 
00525 #=====================================================================
00526 #Apply calibration - results go to corrected_data column
00527 #=====================================================================
00528 print "--applycal--"
00529 print ""
00530 print " applies supplied calibration tables (gain and bandpass) and"
00531 print " writes corrected data to column labeled CORRECTED_DATA."
00532 print " This may take a while ..."
00533 
00534 default('applycal')
00535 
00536 vis=msfile
00537 spw='0:5~112'
00538 gaintable=[prefix+'.fcal',prefix+'.bcal']
00539 gainfield=['1', '4']
00540 
00541 saveinputs('applycal',prefix+'.saved.applycal')
00542 
00543 applycal()
00544 
00545 if benchmarking:
00546     correct2time=time.time()
00547 
00548 
00549 #=====================================================================
00550 # Flag data non-interactively
00551 #=====================================================================
00552 #
00553 print "--flagdata--"
00554 
00555 default('tflagdata')
00556 vis=msfile
00557 spw='0'
00558 mode='manual'
00559 
00560 print ""
00561 print " flag the narrow time range around 03:53 for RR"
00562 print ""
00563 
00564 # NOTE: this was flagged previously in RR if not in scriptmode, but do
00565 # it here again for consistency between modes
00566 #
00567 timerange='03:52:44~03:52:46'
00568 correlation='RR'
00569 
00570 saveinputs('tflagdata',prefix+'.saved.tflagdata.time0352')
00571 
00572 tflagdata()
00573 
00574 print ""
00575 print " flag antenna 0 for correlation LL over the whole time range"
00576 print ""
00577 
00578 antenna='0'
00579 timerange=''
00580 correlation='LL'
00581 
00582 saveinputs('tflagdata',prefix+'.saved.tflagdata.ant0.ll')
00583 
00584 tflagdata()
00585 
00586 if benchmarking:
00587     flagcorrect2time=time.time()
00588 
00589 #=====================================================================
00590 # Split
00591 #=====================================================================
00592 #
00593 # selects target source data (throws away all calibrator data).
00594 print ""
00595 print "--split--"
00596 print ""
00597 print " We are done with the calibrator data so we use split to select"
00598 print " source data only (field '0').  split will also move the"
00599 print " CORRECTED_DATA column to the DATA column."
00600 print ""
00601 
00602 default('split')
00603 
00604 splitfile = prefix + '.split.ms'
00605 
00606 vis       = msfile
00607 outputvis = splitfile
00608 field     = '0'
00609 
00610 saveinputs('split',prefix+'.saved.split')
00611 
00612 split()
00613 
00614 if benchmarking:
00615     split2time=time.time()
00616 
00617 #=====================================================================
00618 # Continuum subtraction
00619 #=====================================================================
00620 #
00621 # subtract continuum to form a line-only data set
00622 
00623 print "--uvcontsub--"
00624 print ""
00625 print " fit a continuum using line-free regions on both ends of the spectrum"
00626 print " and subtract this continuum.  Inspection of the earlier data cube"
00627 print " shows that a good choice for line-free channels at either end are"
00628 print " channels 21-30 and 92-111.  We use the parameter fitspw to specify"
00629 print " the range of channels to base the fit on"
00630 print ""
00631 print " Note that no output file is needed; the results are stored in the"
00632 print " 'corrected' data column"
00633 print ""
00634 print ""
00635 print " have patience - this will take a while ..."
00636 print ""
00637 
00638 default('uvcontsub')
00639 
00640 vis      = splitfile
00641 field    = '0'
00642 fitspw   = '0:21~30;92~111' 
00643 fitorder = 1
00644 
00645 saveinputs('uvcontsub',prefix+'.saved.uvcontsub')
00646 
00647 uvcontsub()
00648 
00649 if benchmarking:
00650     uvcontsub2time=time.time()
00651 
00652 uvcontsubfile = splitfile + '.contsub'
00653 
00654 #=====================================================================
00655 # IMAGING
00656 # make dirty image of channel 32
00657 #=====================================================================
00658 #
00659 print "--clean (dirty image)--"
00660 print ""
00661 print " for now, we will image just channels 32, which is line-free"
00662 print " and last are line-free but were not part of the line-free range in"
00663 print " uvcontsub and their rms noise is therefore indicative of the noise in"
00664 print " the channels with line emission.  The middle channel is an example of"
00665 print " a channel containing line emission without continuum"
00666 print ""
00667 print " Note by setting niter=0 we are just imaging; not cleaning"
00668 print ""
00669 
00670 default('clean')
00671 
00672 outdirty = prefix + '.dirty'
00673 
00674 vis       = uvcontsubfile
00675 imagename = outdirty
00676 field     = '0'
00677 spw       = '0'
00678 imagermode = ''
00679 mode      = 'channel'
00680 nchan     = 1
00681 start     = 32
00682 width     = 1
00683 niter     = 0
00684 imsize    = [512,512]
00685 cell      = ['4arcsec','4arcsec']
00686 weighting = 'briggs'
00687 robust    = 0.0
00688 
00689 clean()
00690 
00691 if benchmarking:
00692     dirty2time=time.time()
00693 
00694 #=====================================================================
00695 # view dirty image
00696 #=====================================================================
00697 #
00698 if scriptmode:
00699     print "--viewer (dirty image)--"
00700     print ""
00701     print " display dirty image of chan 32"
00702     print ""
00703     
00704     default('viewer')
00705 
00706     infile = outdirty+'.image'
00707 
00708     viewer()
00709 
00710     user_check=raw_input('when done viewing, Close and hit Return to continue\n')
00711 
00712     print ""
00713 
00714 #=====================================================================
00715 # Determine the rms in chan32
00716 #=====================================================================
00717 #
00718 # use the task imstat to do this
00719 print "--imstat (dirty image)--"
00720 print ""
00721 default('imstat')
00722 
00723 imagename = outdirty+'.image'
00724 box       = '0,0,511,511'
00725 chans     = '0'
00726 
00727 dirty_stat = imstat()
00728 rmsjy     = dirty_stat['sigma'][0]
00729 rmsmjy    = 1000 * rmsjy
00730 
00731 print " Dirty image chan32 rms = ", rmsmjy, "mJy"
00732 
00733 print ""
00734 
00735 if benchmarking:
00736     dirtystat2time=time.time()
00737 
00738 #=====================================================================
00739 # Now image and clean all channels
00740 #=====================================================================
00741 #
00742 
00743 print ""
00744 print "--clean--"
00745 print ""
00746 print " we will image all channels of interest, and are requesting"
00747 print " cleaning by setting niter to a large number and using a"
00748 print " threshold of 1.2mJy (2 x sigma of dirty image of ch32)"
00749 print ""
00750 
00751 default('clean')
00752 
00753 outname = prefix + '.final.clean'
00754 
00755 vis       = uvcontsubfile
00756 imagename = outname
00757 field     = '0'
00758 spw       = '0'
00759 imagermode = ''
00760 mode      = 'channel'
00761 nchan     = 64
00762 start     = 32
00763 width     = 1
00764 niter     = 100000
00765 threshold = 1.2
00766 psfmode   = 'clark'
00767 mask      = [0,0,511,511]
00768 imsize    = [512,512]
00769 cell      = ['4arcsec','4arcsec']
00770 weighting = 'briggs'
00771 robust    = 0.0
00772 
00773 saveinputs('clean',prefix+'.saved.clean')
00774 
00775 clean()
00776 
00777 if benchmarking:
00778     clean2time=time.time()
00779 
00780 print ""
00781 
00782 #=====================================================================
00783 # view result of clean
00784 #=====================================================================
00785 #
00786 # view all channels if you are running in scriptmode
00787 if scriptmode:
00788     print "--viewer (clean cube)--"
00789     print ""
00790     print " display continuum-free channels"
00791     print ""
00792     
00793     default('viewer')
00794 
00795     infile = outname+'.image'
00796 
00797     viewer()
00798 
00799     user_check=raw_input('when done viewing, Close and hit Return to continue\n')
00800 
00801     print ""
00802 
00803 #=====================================================================
00804 # display image header
00805 #=====================================================================
00806 #
00807 # 
00808 print "--imhead--"
00809 print ""
00810 print " We will need to specify a subset of this cube, so let's explore the"
00811 print " structure of the image cube first.  Use the task imhead for this"
00812 print ""
00813 
00814 default('imhead')
00815 
00816 imagename = outname+'.image'
00817 
00818 imhead()
00819 
00820 print ""
00821 print " Look in the log window for the output of imhead.  You will see that"
00822 print " the axis order is RA, Dec, Stokes, Frequency.  Keep this in mind"
00823 print " when specifying a subset of the image cube below"
00824 print ""
00825 
00826 #=====================================================================
00827 # Statistics on clean image cube and moments
00828 #=====================================================================
00829 #
00830 print '--imstat (clean cube)--'
00831 default('imstat')
00832 
00833 imagename = outname+'.image'
00834 
00835 # determine the stats in entire cube
00836 
00837 srcstat = imstat()
00838 
00839 print " Found image max = "+str(srcstat['max'][0])+" Jy"
00840 
00841 # determine the stats in a off-source box
00842 
00843 offbox = '10,384,195,505'
00844 box = offbox
00845 
00846 offstat = imstat()
00847 
00848 print " Found off-source image rms = "+str(offstat['sigma'][0])+" Jy"
00849 
00850 # determine the stats in line-free channels (here: 0-3)
00851 
00852 cenbox = '128,128,384,384'
00853 offlinechan = '0,1,2,3'
00854 
00855 box = cenbox
00856 chans = offlinechan
00857 
00858 offlinestat = imstat()
00859 
00860 print " Found off-line image rms = "+str(offlinestat['sigma'][0])+" Jy"
00861 offline_rms = offlinestat['sigma'][0]
00862 
00863 if benchmarking:
00864     stat2time=time.time()
00865 
00866 #=====================================================================
00867 # make a total HI map
00868 #=====================================================================
00869 #
00870 # use the task immoments to do this
00871 
00872 print ""
00873 print "--immoments--"
00874 print ""
00875 print " as the final step we determine the 0'th and first moment maps, aka"
00876 print " the total HI map and the velocity field.  For want of a better method"
00877 print " we exclude pixel values falling in the interval given by excludepix at"
00878 print "   cutoff = "+str(3*offline_rms)+" Jy"
00879 print " Note the use of the rms determined earlier in imstat"
00880 print ""
00881 
00882 default('immoments')
00883 
00884 momfile    = outname + '.mom'
00885 
00886 imagename  = outname + '.image'
00887 moments    = [0,1]
00888 chans     = '4~56'
00889 axis       = 'spec'
00890 excludepix = [-100, 3*offline_rms]
00891 outfile    = momfile
00892 
00893 saveinputs('immoments',prefix+'.saved.immoments')
00894 
00895 immoments()
00896 
00897 if benchmarking:
00898     moments2time=time.time()
00899 
00900 #=====================================================================
00901 # view result of immoments; first total HI, then velocity field
00902 #=====================================================================
00903 #
00904 # view if in scriptmode
00905 
00906 if scriptmode:
00907     print "--viewer--"
00908     print ""
00909 
00910     default('viewer')
00911 
00912     infile = outfile + '.integrated'
00913 
00914     viewer()
00915 
00916     print " display moment 0 of continuum-free channels"
00917     print ""
00918     user_check=raw_input('when done viewing, Close and hit Return to continue\n')
00919 
00920     infile = outfile + '.weighted_coord'
00921 
00922     viewer()
00923 
00924     print ""
00925     print " display moment 1 of continuum-free channels"
00926     print ""
00927     user_check=raw_input('when done viewing, Close and hit Return to continue\n')
00928 
00929     print ""
00930 
00931 
00932 #=====================================================================
00933 # Statistics on moment images
00934 #=====================================================================
00935 #
00936 print '--imstat (moment images)--'
00937 default('imstat')
00938 
00939 imagename = momfile+'.integrated'
00940 
00941 momzerostat=imstat()
00942 
00943 try:
00944     print " Found moment 0 max = "+str(momzerostat['max'][0])
00945     print " Found moment 0 rms = "+str(momzerostat['rms'][0])
00946 except:
00947     pass
00948 
00949 imagename = momfile+'.weighted_coord'
00950 
00951 momonestat=imstat()
00952 
00953 try:
00954     print " Found moment 1 median = "+str(momonestat['median'][0])
00955 except:
00956     pass
00957 
00958 if benchmarking:
00959     momstat2time=time.time()
00960 
00961 #=====================================================================
00962 # DONE
00963 #=====================================================================
00964 if benchmarking:
00965     endProc=time.clock()
00966     endTime=time.time()
00967 
00968 print ""
00969 print "Completed processing of NGC2403 data"
00970 print ""
00971 
00972 #
00973 ##########################################################################
00974 # Calculate regression values
00975 ##########################################################################
00976 print '--Calculate Regression Results--'
00977 print ''
00978 #
00979 # Save these stats
00980 #
00981 try:
00982     dirtyrms = dirty_stat['sigma'][0]
00983 except:
00984     dirtyrms = 0.0
00985 
00986 try:
00987     srcmax = srcstat['max'][0]
00988 except:
00989     srcmax = 0.0
00990 
00991 try:
00992     offrms = offstat['sigma'][0]
00993 except:
00994     offrms = 0.0
00995 
00996 try:
00997     offlinerms = offlinestat['sigma'][0]
00998 except:
00999     offlinerms = 0.0
01000     
01001 try:
01002     momzero_max = momzerostat['max'][0]
01003 except:
01004     momzero_max = 0.0
01005 
01006 try:
01007     momzero_rms = momzerostat['rms'][0]
01008 except:
01009     momzero_rms = 0.0
01010 
01011 try:
01012     momone_median = momonestat['median'][0]
01013 except:
01014     momone_median = 0.0
01015 
01016 #
01017 ##########################################################################
01018 # Canonical results to be used for regression
01019 
01020 canonical = {}
01021 canonical['exist'] = True
01022 
01023 canonical['date'] = '2009-12-07 (GAM)'
01024 canonical['version'] = 'CASA Version 3.0.0 Rev 9751'
01025 canonical['user'] = 'gmoellen'
01026 canonical['host'] = 'penns'
01027 canonical['cwd'] = '/home/penns/gmoellen/CASA/REG/N2403'
01028 print "Canonical regression from "+canonical['version']+" on "+canonical['date']
01029 
01030 canonical_results = {}
01031 canonical_results['dirty_image_rms'] = {}
01032 canonical_results['dirty_image_rms']['value'] = 0.000342
01033 
01034 canonical_results['clean_image_max'] = {}
01035 canonical_results['clean_image_max']['value'] = 0.0231359191239
01036 
01037 canonical_results['clean_image_offsrc_rms'] = {}
01038 canonical_results['clean_image_offsrc_rms']['value'] = 0.000533470036927
01039 
01040 canonical_results['clean_image_offline_rms'] = {}
01041 canonical_results['clean_image_offline_rms']['value'] = 0.000515150649237
01042 
01043 canonical_results['clean_momentzero_max'] = {}
01044 canonical_results['clean_momentzero_max']['value'] = 0.551860868931
01045 
01046 canonical_results['clean_momentzero_rms'] = {}
01047 canonical_results['clean_momentzero_rms']['value'] = 0.0878139138222
01048 
01049 # The following value is a velocity in BARY
01050 #  (in LSRK, the answer is ~132.47
01051 canonical_results['clean_momentone_median'] = {}
01052 canonical_results['clean_momentone_median']['value'] = 129.940628
01053 
01054 
01055 #
01056 ##########################################################################
01057 #
01058 # Try and load previous results from regression file
01059 #
01060 regression = {}
01061 regressfile = scriptprefix + '.pickle'
01062 prev_results = {}
01063 
01064 try:
01065     fr = open(regressfile,'r')
01066 except:
01067     print "No previous regression results file "+regressfile
01068 else:
01069     u = pickle.Unpickler(fr)
01070     regression = u.load()
01071     fr.close()
01072     print "Regression results filled from "+regressfile
01073     print "Regression from version "+regression['version']+" on "+regression['date']
01074     regression['exist'] = True
01075 
01076     prev_results = regression['results']
01077     
01078 #
01079 ##########################################################################
01080 #
01081 # Store results in dictionary
01082 #
01083 new_regression = {}
01084 
01085 # Some date and version info
01086 import datetime
01087 datestring=datetime.datetime.isoformat(datetime.datetime.today())
01088 
01089 myvers = casalog.version()
01090 myuser = os.getenv('USER')
01091 myhost = os.uname()[1]
01092 mycwd = os.getcwd()
01093 myos = os.uname()
01094 
01095 # Save info in regression dictionary
01096 new_regression['date'] = datestring
01097 new_regression['version'] = myvers
01098 new_regression['user'] = myuser
01099 new_regression['host'] = myhost
01100 new_regression['cwd'] = mycwd
01101 new_regression['os'] = myos
01102 
01103 new_regression['dataset'] = 'NGC2403 02-JAN-1999 VLA HI'
01104 
01105 # Dataset size info
01106 datasize_raw = 564.0 # MB
01107 datasize_ms = 5200.0 # MB
01108 new_regression['datasize'] = {}
01109 new_regression['datasize']['raw'] = datasize_raw
01110 new_regression['datasize']['ms'] = datasize_ms
01111 
01112 #
01113 ##########################################################################
01114 #
01115 # Timing
01116 #
01117 if benchmarking:
01118     # Save timing to regression dictionary
01119     new_regression['timing'] = {}
01120 
01121     total = {}
01122     total['wall'] = (endTime - startTime)
01123     total['cpu'] = (endProc - startProc)
01124     total['rate_raw'] = (datasize_raw/(endTime - startTime))
01125     total['rate_ms'] = (datasize_ms/(endTime - startTime))
01126 
01127     new_regression['timing']['total'] = total
01128 
01129     nstages = 19
01130     new_regression['timing']['nstages'] = nstages
01131 
01132     stages = {}
01133     stages[0] = ['import',(import2time-startTime)]
01134     stages[1] = ['listobs',(list2time-import2time)]
01135     stages[2] = ['tflagdata',(flag2time-list2time)]
01136     stages[3] = ['setjy',(setjy2time-flag2time)]
01137     stages[4] = ['gaincal',(gaincal2time-setjy2time)]
01138     stages[5] = ['plotgcal',(plotgcal2time-gaincal2time)]
01139     stages[6] = ['fluxscale',(fluxscale2time-plotgcal2time)]
01140     stages[7] = ['bandpass',(bandpass2time-fluxscale2time)]
01141     stages[8] = ['plotbcal',(plotbcal2time-bandpass2time)]
01142     stages[9] = ['applycal',(correct2time-plotbcal2time)]
01143     stages[10] = ['flagfinal',(flagcorrect2time-correct2time)]
01144     stages[11] = ['split',(split2time-flagcorrect2time)]
01145     stages[12] = ['uvcontsub',(uvcontsub2time-split2time)]
01146     stages[13] = ['clean(dirty)',(dirty2time-uvcontsub2time)]
01147     stages[14] = ['stat(dirty)',(dirtystat2time-dirty2time)]
01148     stages[15] = ['clean',(clean2time-dirtystat2time)]
01149     stages[16] = ['stat',(stat2time-clean2time)]
01150     stages[17] = ['moments',(moments2time-stat2time)]
01151     stages[18] = ['momstat',(momstat2time-moments2time)]
01152     
01153     new_regression['timing']['stages'] = stages
01154 
01155 #
01156 ##########################################################################
01157 # Fill results
01158 # Note that 'op' tells what to do for the diff :
01159 #    'divf' = abs( new - prev )/prev
01160 #    'diff' = new - prev
01161 
01162 results = {}
01163 
01164 op = 'divf'
01165 tol = 0.08
01166 results['dirty_image_rms'] = {}
01167 results['dirty_image_rms']['name'] = 'Dirty image rms'
01168 results['dirty_image_rms']['value'] = dirtyrms
01169 results['dirty_image_rms']['op'] = op
01170 results['dirty_image_rms']['tol'] = tol
01171 
01172 results['clean_image_max'] = {}
01173 results['clean_image_max']['name'] = 'Clean image max'
01174 results['clean_image_max']['value'] = srcmax
01175 results['clean_image_max']['op'] = op
01176 results['clean_image_max']['tol'] = tol
01177 
01178 results['clean_image_offsrc_rms'] = {}
01179 results['clean_image_offsrc_rms']['name'] = 'Clean image off-src rms'
01180 results['clean_image_offsrc_rms']['value'] = offrms
01181 results['clean_image_offsrc_rms']['op'] = op
01182 results['clean_image_offsrc_rms']['tol'] = tol
01183 
01184 results['clean_image_offline_rms'] = {}
01185 results['clean_image_offline_rms']['name'] = 'Clean image off-line rms'
01186 results['clean_image_offline_rms']['value'] = offlinerms
01187 results['clean_image_offline_rms']['op'] = op
01188 results['clean_image_offline_rms']['tol'] = tol
01189 
01190 results['clean_momentzero_max'] = {}
01191 results['clean_momentzero_max']['name'] = 'Moment 0 image max'
01192 results['clean_momentzero_max']['value'] = momzero_max
01193 results['clean_momentzero_max']['op'] = op
01194 results['clean_momentzero_max']['tol'] = tol
01195 
01196 results['clean_momentzero_rms'] = {}
01197 results['clean_momentzero_rms']['name'] = 'Moment 0 image rms'
01198 results['clean_momentzero_rms']['value'] = momzero_rms
01199 results['clean_momentzero_rms']['op'] = op
01200 results['clean_momentzero_rms']['tol'] = tol
01201 
01202 op = 'diff'
01203 tol = 0.1
01204 results['clean_momentone_median'] = {}
01205 results['clean_momentone_median']['name'] = 'Moment 1 image median'
01206 results['clean_momentone_median']['value'] = momone_median
01207 results['clean_momentone_median']['op'] = op
01208 results['clean_momentone_median']['tol'] = tol
01209 
01210 #
01211 ##########################################################################
01212 # Now go through and regress
01213 resultlist = ['dirty_image_rms','clean_image_max',
01214               'clean_image_offsrc_rms','clean_image_offline_rms',
01215               'clean_momentzero_max','clean_momentzero_rms','clean_momentone_median']
01216 
01217 for keys in resultlist:
01218     res = results[keys]
01219     if prev_results.has_key(keys):
01220         # This is a known regression
01221         prev = prev_results[keys]
01222         new_val = res['value']
01223         prev_val = prev['value']
01224         if res['op'] == 'divf':
01225             new_diff = (new_val - prev_val)/prev_val
01226         else:
01227             new_diff = new_val - prev_val
01228 
01229         if abs(new_diff)>res['tol']:
01230             new_status = 'Failed'
01231         else:
01232             new_status = 'Passed'
01233         
01234         results[keys]['prev'] = prev_val
01235         results[keys]['diff'] = new_diff
01236         results[keys]['status'] = new_status
01237         results[keys]['test'] = 'Last'
01238     elif canonical_results.has_key(keys):
01239         # Go back to canonical values
01240         prev = canonical_results[keys]
01241         new_val = res['value']
01242         prev_val = prev['value']
01243         if res['op'] == 'divf':
01244             new_diff = (new_val - prev_val)/prev_val
01245         else:
01246             new_diff = new_val - prev_val
01247 
01248         if abs(new_diff)>res['tol']:
01249             new_status = 'Failed'
01250         else:
01251             new_status = 'Passed'
01252         
01253         results[keys]['prev'] = prev_val
01254         results[keys]['diff'] = new_diff
01255         results[keys]['status'] = new_status
01256         results[keys]['test'] = 'Canon'
01257     else:
01258         # Unknown regression key
01259         results[keys]['prev'] = 0.0
01260         results[keys]['diff'] = 1.0
01261         results[keys]['status'] = 'Missed'
01262         results[keys]['test'] = 'none'
01263 
01264 # Done filling results
01265 new_regression['results'] = results
01266 
01267 #
01268 ##########################################################################
01269 #
01270 # Save regression results as dictionary using Pickle
01271 #
01272 pickfile = 'out.'+prefix + '.regression.'+datestring+'.pickle'
01273 f = open(pickfile,'w')
01274 p = pickle.Pickler(f)
01275 p.dump(new_regression)
01276 f.close()
01277 
01278 print ""
01279 print "Regression result dictionary saved in "+pickfile
01280 print ""
01281 print "Use Pickle to retrieve these"
01282 print ""
01283 
01284 # e.g.
01285 # f = open(pickfile)
01286 # u = pickle.Unpickler(f)
01287 # clnmodel = u.load()
01288 # polmodel = u.load()
01289 # f.close()
01290 
01291 #
01292 ##########################################################################
01293 #
01294 # Now print out results
01295 # The following writes a logfile for posterity
01296 #
01297 ##########################################################################
01298 #
01299 outfile='out.'+prefix+'.'+datestring+'.log'
01300 logfile=open(outfile,'w')
01301 
01302 # Print version info to outfile
01303 print >>logfile,'Regression = '+new_regression['dataset']
01304 print >>logfile,'Running '+myvers+' on host '+myhost
01305 print >>logfile,'at '+datestring
01306 print >>logfile,''
01307 
01308 # Print out comparison:
01309 print >>logfile,'---'
01310 print >>logfile,'Regression versus previous values:'
01311 print >>logfile,'---'
01312 
01313 res = {}
01314 resultlist = ['dirty_image_rms','clean_image_max',
01315               'clean_image_offsrc_rms','clean_image_offline_rms',
01316               'clean_momentzero_max','clean_momentzero_rms','clean_momentone_median']
01317 
01318 final_status = 'Passed'
01319 for keys in resultlist:
01320     res = results[keys]
01321     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'] )
01322     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'] )
01323     if res['status']=='Failed':
01324         final_status = 'Failed'
01325 
01326 if (final_status == 'Passed'):
01327     regstate=True
01328     print >>logfile,'---'
01329     print >>logfile,'Passed Regression test for NGC 2403'
01330     print >>logfile,'---'
01331     print ''
01332     print 'Regression PASSED'
01333     print ''
01334     print 'Passed Regression test for NGC 2403'
01335 else:
01336     regstate=False
01337     print >>logfile,'----FAILED Regression test for NGC 2403'
01338     print ''
01339     print 'Regression FAILED'
01340     print ''
01341     print '----FAILED Regression test for NGC 2403'
01342     
01343 #
01344 ##########################################################################
01345 # Print benchmarking etc.
01346 
01347 if benchmarking:
01348     print ''
01349     print 'Total wall clock time was: %10.3f ' % total['wall']
01350     print 'Total CPU        time was: %10.3f ' % total['cpu']
01351     print 'Raw processing rate MB/s was: %8.1f ' % total['rate_raw']
01352     print 'MS  processing rate MB/s was: %8.1f ' % total['rate_ms']
01353     print ''
01354     print '* Breakdown:                              *'
01355 
01356     print >>logfile,''
01357     print >>logfile,'********* Benchmarking *************************'
01358     print >>logfile,'*                                              *'
01359     print >>logfile,'Total wall clock time was: %10.3f ' % total['wall']
01360     print >>logfile,'Total CPU        time was: %10.3f ' % total['cpu']
01361     print >>logfile,'Raw processing rate MB/s was: %8.1f ' % total['rate_raw']
01362     print >>logfile,'MS  processing rate MB/s was: %8.1f ' % total['rate_ms']
01363     print >>logfile,'* Breakdown:                                   *'
01364 
01365     for i in range(nstages):
01366         print '* %16s * time was: %10.3f ' % tuple(stages[i])
01367         print >>logfile,'* %16s * time was: %10.3f ' % tuple(stages[i])
01368     
01369     print >>logfile,'************************************************'
01370     print >>logfile,'imager-b (2008-07-24) wall time was: 2740 seconds'
01371     print >>logfile,'imager-b (2008-07-24) CPU  time was: 1792 seconds'
01372 
01373 logfile.close()
01374 
01375 print "Done with NGC2403 Tutorial Regression"
01376 #
01377 ##########################################################################