
##############################################################################
# Data reduction script for VY CMa Band 7 658-GHz 12-m data: Part 1: Calibration
# VYCMa_Band9_Calibration.py
# Tested using CASA Version 4.2.1  (r29048)
#
# Datasets used:
#
# NOTE - THIS DATASET DOES NOT HAVE ITS OWN BANDPASS CALIBRATOR AND SHOULD
# BE USED WITH CAUTION. IN THE PRESENT SCRIPT THE BANDPASS CALIBRATOR IS
# COPIED FROM THE NEXT DATASET (Xb3d). WHILE THIS PROVIDES A SATISFACTORY RESULT
# FOR THE BANDPASS AND AN IMPROVED SNR, SOME USERS MAY WANT TO OMIT THIS DATASET.
#
# uid___A002_X6d5bd2_X31 - observed Aug 18 2013 with 17 antennas
# Flux scale calibrator Pallas*
# Bandpass calibrator (copy from next dataset) 
# Phase reference source J0648-3044 
# Target Vy CMa
#
# uid___A002_X6d34fd_Xb3d - observed Aug 18 2013 with 18 antennas
# Flux scale calibrator J0522-364  
# Bandpass calibrator J0522-364
# Phase reference source J0648-3044 
# Target Vy CMa
#
# NOTE - THIS DATASET DOES NOT HAVE ITS OWN BANDPASS CALIBRATOR AND SHOULD
# BE USED WITH CAUTION. IN THE PRESENT SCRIPT THE BANDPASS CALIBRATOR IS
# COPIED FROM THE PREVIOUS DATASET (Xb3d). WHILE THIS PROVIDES A SATISFACTORY RESULT
# FOR THE BANDPASS AND AN IMPROVED SNR, SOME USERS MAY WANT TO OMIT THIS DATASET.
#
# uid___A002_X6d34fd_X102f - observed Aug 19 2013 with 20 antennas
# Flux scale calibrator  Pallas*
# Bandpass calibrator    (copy from previous dataset)
# Phase reference source J0648-3044
# Target                 Vy CMa
#
# Use the flux densities derived from Pallas for all data sets
#
##############################################################################
"""
See accompanying README file for details of the necessary input files
and comments on the data.

Prior to running this script you will need to obtain the Analysis Utilities package.
See http://casaguides.nrao.edu/index.php?title=Analysis_Utilities for details and 
for how to download Analysis Utilities.

"""

#----------------------------------------------------------------------------------
#----- Optional Steps -------------------------------------------------------------
#----------------------------------------------------------------------------------

#----- Set this option to true if you want to make diagnostic plots along the way.
#----- Note that this will slow down the reduction somewhat.
#----- Default is no plots (you can make them later anyway).
calplots=T

#----------------------------------------------------------------------------------
#----- Some setup steps -----------------------------------------------------------
#----------------------------------------------------------------------------------

version = casalog.version()
print "You are using " + version
if (version < '4.2.0'):
    print "\033[91m YOUR VERSION OF CASA IS TOO OLD FOR THIS GUIDE."
    print "\033[91m PLEASE UPDATE IT BEFORE PROCEEDING."
else:
    print "Your version of CASA is appropriate for this guide."

# Repeat imports if you exit and restart CASA if using copy and paste
#import re
#import os

thesteps=[]
step_title = {0: 'Import of the ASDMs, listing the data and plotting antenna table',
              1: 'Flag autocorrelations and pointing scans; back up flags',
              2: 'Generation and time averaging of the WVR cal table',
              3: 'Generation of the Tsys cal table',
              4: 'Generation of the antenna position cal table',
              5: 'Plot raw data',
              6: 'Application of the WVR, Tsys and antpos cal tables',
              7: 'Split out science SPWs and time average',
              8: 'Listobs, clear pointing table, and save original flags',
              9: 'Plot data with instrumental calibration',
              10: 'Initial flagging',
              11: 'Bandpass calibration',
              12: 'Putting a model for the flux calibrator',
              13: 'Calibrate the flux scale',
              14: 'Gain calibration',
              15: 'Application of the bandpass and gain cal tables',
              16: 'Plot calibrated phase ref data',
              17: 'Split out the science data'}

# The Python variable 'mysteps' will control which steps
# are executed when you start the script using
#   execfile('scriptForCalibration.py')
# e.g. setting
#   mysteps = [2,3,4]# before starting the script will make the script execute
# only steps 2, 3, and 4
# Setting mysteps = [] will make it execute all steps.

try:
  print 'List of steps to be executed ...', mysteps
  thesteps = mysteps
except:
  print 'global variable mysteps not set.'
if (thesteps==[]):
  thesteps = range(0,len(step_title))
  print 'Executing all steps: ', thesteps

######################################################

# If executing this script by copying and pasting, and you restart
# CASA, 
# Copy selection of channels for continuum calibration to avoid atmospheric lines
contchans='0:0~749;1240~1849;2440~3839'

# Copy the definition of basename before executing steps 0-7
basename=['uid___A002_X6d5bd2_X31','uid___A002_X6d34fd_Xb3d','uid___A002_X6d34fd_X102f']
# Copy the definition of refant for steps 5-15
refantenna='DV05'

# Import of the ASDMs, listing the data and plotting antenna table
mystep = 0
if(mystep in thesteps):
  casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
  print 'Step ', mystep, step_title[mystep]

  for name in basename:
      os.system('rm -rf '+name+'.ms')
      importasdm(asdm=name, vis=name+'.ms', process_flags=F, 
                 asis='Antenna Station CalWVR Receiver Source')

# Do listobs and write info for each dataset to a text file
  for name in basename:
      os.system('rm '+name+'_listobs.txt')
      listobs(vis=name+'.ms', listfile=name+'_listobs.txt', verbose=True)
      print "<< Printed listobs output to "+name+'.listobs.txt'

# Plot antenna configuration to a file
  for name in basename:
      os.system('rm -rf plotants_'+name+'.png')
      plotants(name+'.ms', figfile='plotants_'+name+'.png')

  print 'Choose refant - with lots of short baselines but not so close other antennas to\nthat it will be shadowed. Definition is at top of script, change if desired.'

#################################
# Flag autocorrelations and pointing scans; back up flags
mystep = 1 
if(mystep in thesteps):
  casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
  print 'Step ', mystep, step_title[mystep]

# Remove all previous flags
  for name in basename:
      flagdata(vis=name+'.ms',mode='unflag', flagbackup=F)

  for name in basename:
      flagdata(vis = name+'.ms',
               mode = 'manual',
               spw = '1~12',
               autocorr = T,
               flagbackup = F)
  
  for name in basename:
      flagdata(vis = name+'.ms',
               mode = 'manual',
               intent = '*POINTING*,*SIDEBAND_RATIO*,*ATMOSPHERE*',
               flagbackup = F)

# Store current flagging state
  for name in basename:
      flagmanager(vis = name+'.ms', mode = 'save',
                  versionname = 'Apriori')

# To restore a priori flags:
#for name in basename:
#	flagmanager(vis = name+'.ms', mode = 'restore', versionname = 'Apriori')	

###############
# Generation and time averaging of the WVR cal table
mystep = 2
if(mystep in thesteps):
  casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
  print 'Step ', mystep, step_title[mystep]
  
  for name in basename:
      os.system('rm -rf ' +name+'.ms.wvr') 
      mylogfile = casalog.logfile()
      casalog.setlogfile(name+'.ms.wvrgcal')
      wvrgcal(vis = name+'.ms',
              caltable = name+'.ms.wvr',
              toffset = 0,
              tie = ['Vy CMa,J0648-3044'],
              statsource = 'Vy CMa')
      casalog.setlogfile(mylogfile)
  
  for name in basename:
      os.system('rm -rf ' +name+'.ms.wvr.smooth') 
      smoothcal(vis = name+'.ms',
                tablein = name+'.ms.wvr',
                caltable = name+'.ms.wvr.smooth',
                smoothtype = 'mean',
                smoothtime = 6.048)
  
  if(calplots):
      print 'Please ignor any messages arising from data sets with <17 antennas'
      for name in basename:
          os.system('rm -rf '+name+'.ms.wvr.smooth*.png')
          for ant in range(3):
              plotcal(caltable = name+'.ms.wvr.smooth',
                      xaxis = 'time', yaxis = 'phase',
                      plotrange = [0,0,-180,180],
                      antenna=str(ant*8)+'~'+str(ant*8+7),
                      iteration = 'antenna',
                      markersize=3.0,
                      figfile=name+'.ms.wvr.smooth_ant'+str(ant*8)+'-'+str(ant*8+7)+'.png',
                      subplot = 421)

# Flag WVR autocorrelations
  for name in basename:
      flagdata(vis = name+'.ms',
               mode = 'manual',
               spw = '0',
               autocorr = T,
               flagbackup = F)
  
#####################################	
# Generation of the Tsys cal table
mystep = 3
if(mystep in thesteps):
  casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
  print 'Step ', mystep, step_title[mystep]
 
  for name in basename:
      os.system('rm -rf '+name+'.ms.tsys') 
      gencal(vis = name+'.ms',
             caltable = name+'.ms.tsys',
             caltype = 'tsys')  

  if(calplots):
      for name in basename:
          os.system('rm -rf '+name+'.ms.tsys*.png')
          for ant in range(3):
             plotcal(caltable = name+'.ms.tsys',
                xaxis = 'freq', yaxis = 'tsys',
               spw='9:8~120',
               markersize=3.0,
               antenna=str(ant*8)+'~'+str(ant*8+7),
               iteration = 'antenna',
               figfile=name+'.ms.tsys_ant'+str(ant*8)+'-'+str(ant*8+7)+'.png',
               subplot = 421)

######################################
# Generation of the antenna position cal table
mystep = 4
if(mystep in thesteps):
  casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
  print 'Step ', mystep, step_title[mystep]

  for name in basename:    
      os.system('rm -rf '+ name+'.ms.antpos') 
    
  os.system('rm -rf uid___A002_X6d5bd2_X31.ms.antpos') 
  gencal(vis = 'uid___A002_X6d5bd2_X31.ms',
    caltable = 'uid___A002_X6d5bd2_X31.ms.antpos',
    caltype = 'antpos',
    antenna = 'DA41,DA46,DA56,DV03,DV04,DV05,DV07,DV11,DV13,DV14,DV15,DV17,DV18,DV19,DV22,DV24,DV25',
    parameter = [-0.018216, 0.067084, 0.060448, 0.000006, 0.000228, -0.000297,0.000065, 0.000035, 0.000115, -0.000196, -0.000061, 0.000178, -0.000132, 0.000341, -0.000190, 0.000068, 0.000267, -0.000494, -0.000524, 0.000838, 0.000626, 0.000112, -0.000116, 0.000112, -0.000032, 0.000188, -0.000261, 0.000043, -0.000173, 0.000008, 0.000037, 0.000468, -0.000484, 0.000167, -0.000474, 0.000167, -0.000047, 0.000177, -0.000151, -0.000282, -0.000304, -0.000094, 0.000009, 0.000227, -0.000283, -0.000404, 0.003222, 0.001466, -0.000296, 0.000305, 0.000940] )

  os.system('rm -rf uid___A002_X6d34fd_Xb3d.ms.antpos') 
  gencal(vis = 'uid___A002_X6d34fd_Xb3d.ms',
    caltable = 'uid___A002_X6d34fd_Xb3d.ms.antpos',
    caltype = 'antpos',
    antenna = 'DA41,DA46,DA52,DA56,DV03,DV04,DV05,DV07,DV11,DV13,DV14,DV15,DV17,DV18,DV19,DV22,DV24,DV25',
    parameter = [-0.018216, 0.067084, 0.060448, 0.000006, 0.000228, -0.000297,0.000046, 0.000004, 0.000165,0.000065, 0.000035, 0.000115, -0.000196, -0.000061, 0.000178, -0.000132, 0.000341, -0.000190, 0.000068, 0.000267, -0.000494, -0.000524, 0.000838, 0.000626, 0.000112, -0.000116, 0.000112, -0.000032, 0.000188, -0.000261, 0.000043, -0.000173, 0.000008, 0.000037, 0.000468, -0.000484, 0.000167, -0.000474, 0.000167, -0.000047, 0.000177, -0.000151, -0.000282, -0.000304, -0.000094, 0.000009, 0.000227, -0.000283, -0.000404, 0.003222, 0.001466, -0.000296, 0.000305, 0.000940] )

  os.system('rm -rf uid___A002_X6d34fd_X102f.ms.antpos') 
  gencal(vis = 'uid___A002_X6d34fd_X102f.ms',
    caltable = 'uid___A002_X6d34fd_X102f.ms.antpos',
    caltype = 'antpos',
    antenna = 'DA41,DA46,DA52,DA56,DV03,DV04,DV05,DV07,DV11,DV13,DV14,DV15,DV17,DV18,DV19,DV22,DV24,DV25',
    parameter = [-0.018216, 0.067084, 0.060448, 0.000006, 0.000228, -0.000297, 0.000046, 0.000004, 0.000165,0.000065, 0.000035, 0.000115, -0.000196, -0.000061, 0.000178, -0.000132, 0.000341, -0.000190, 0.000068, 0.000267, -0.000494, -0.000524, 0.000838, 0.000626, 0.000112, -0.000116, 0.000112, -0.000032, 0.000188, -0.000261, 0.000043, -0.000173, 0.000008, 0.000037, 0.000468, -0.000484, 0.000167, -0.000474, 0.000167, -0.000047, 0.000177, -0.000151, -0.000282, -0.000304, -0.000094, 0.000009, 0.000227, -0.000283, -0.000404, 0.003222, 0.001466, -0.000296, 0.000305, 0.000940] )


#######
# Plot visibilities of bandpass calibrator before applying instrumental calibration
mystep = 5
if(mystep in thesteps):
    casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
    print 'Step ', mystep, step_title[mystep]

    os.system('rm -rf uid___A002_X6d34fd_Xb3d.ms.rawBPsource_*.png')
    plotms(vis='uid___A002_X6d34fd_Xb3d.ms', 
           field='J0522-364',
           xaxis='frequency', yaxis='amp',
           selectdata=T, spw='11', 
           avgchannel='20',
           avgtime='1e8',avgscan=T,
           coloraxis='baseline',
           antenna=refantenna+'&*',
           ydatacolumn='data',
           showgui=F,
           plotfile='uid___A002_X6d34fd_Xb3d.ms.rawBPsource_amp.png')

    plotms(vis='uid___A002_X6d34fd_Xb3d.ms', 
           field='J0522-364',
           xaxis='frequency', yaxis='phase',
           selectdata=T, spw='11',
           avgchannel='20',
           avgtime='1e8',avgscan=T,
           coloraxis='baseline',
           antenna=refantenna+'&*',
           ydatacolumn='data',
           showgui=F,
           plotfile='uid___A002_X6d34fd_Xb3d.ms.rawBPsource_phase.png')

####################################
# Apply WVR, Tsys and antenna position corrections 
mystep = 6
if(mystep in thesteps):
    casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
    print 'Step ', mystep, step_title[mystep]

    from recipes.almahelpers import tsysspwmap
    tsysmap = tsysspwmap(vis = basename[0]+'.ms', tsystable = basename[0]+'.ms.tsys')
    
    for field in ['Pallas','J0648-3044','Vy CMa']:
        name='uid___A002_X6d5bd2_X31'
        applycal(vis='uid___A002_X6d5bd2_X31.ms',
                 spw='11',
                 field=field,
                 gainfield=[field,'',''],
                 interp=['linear,linear'],
                 gaintable=[name+'.ms.tsys',name+'.ms.wvr.smooth',name+'.ms.antpos'],
                 flagbackup=F, calwt=T, 
                 spwmap = [tsysmap,[],[]])

    for field in ['J0522-364','J0648-3044','Vy CMa']:
        name='uid___A002_X6d34fd_Xb3d'
        applycal(vis = 'uid___A002_X6d34fd_Xb3d.ms',
                 spw='11',
                 field=field,
                 gainfield=[field,'',''],
                 interp=['linear,linear'],
                 gaintable=[name+'.ms.tsys',name+'.ms.wvr.smooth',name+'.ms.antpos'],
                 flagbackup=F, calwt=T, 
                 spwmap = [tsysmap,[],[]])

    for field in ['Pallas','J0648-3044','Vy CMa']:
        name='uid___A002_X6d34fd_X102f'
        applycal(vis = 'uid___A002_X6d34fd_X102f.ms',
                 spw='11',
                 field=field,
                 gainfield=[field,'',''],
                 interp=['linear,linear'],
                 gaintable=[name+'.ms.tsys',name+'.ms.wvr.smooth',name+'.ms.antpos'],
                 flagbackup=F, calwt=T, 
                 spwmap = [tsysmap,[],[]])

###############################################
# Split out science spw with time averaging
mystep = 7
if(mystep in thesteps):
    casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
    print 'Step ', mystep, step_title[mystep]

    for name in basename:
        os.system('rm -rf '+ name+'.ms.split') 
        split(vis = name+'.ms',
              outputvis = name+'.ms.split',
              datacolumn = 'corrected',
              spw = '11',
              timebin = '6.048s',
              keepflags = T)
  
#########################################
# Listobs, clear pointing table, and save original flags
mystep=8
if(mystep in thesteps):
  casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
  print 'Step ', mystep, step_title[mystep]

  for name in basename:
      os.system('rm -rf '+name+'.ms.split.listobs.txt')
      listobs(vis = name+'.ms.split',
              listfile = name+'.ms.split.listobs.txt')

# Remove POINTING tables
  for name in basename:
      tb.open(name+'.ms.split/POINTING', nomodify = False)
      a = tb.rownumbers()
      tb.removerows(a)
      tb.close()

# Store pre-flagging state
  for name in basename:
      flagmanager(vis = name+'.ms.split',
                  mode = 'save',
                  versionname = 'Pre-flagging')

#######
# Plot visibilities of bandpass calibration source after applying instrumental calibration
mystep = 9
if(mystep in thesteps):
    casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
    print 'Step ', mystep, step_title[mystep]

    os.system('rm -rf uid___A002_X6d34fd_Xb3d.ms.split.corrBPsource_*.png')
    plotms(vis='uid___A002_X6d34fd_Xb3d.ms.split', 
           field='J0522-364',
           xaxis='frequency', yaxis='amp',
           selectdata=T, spw='0', 
           avgchannel='20',
           avgtime='1e8',avgscan=T,
           coloraxis='baseline',
           antenna=refantenna+'&*',
           showgui=F,
           plotfile='uid___A002_X6d34fd_Xb3d.ms.split.corrBPsource_amp.png')
    plotms(vis='uid___A002_X6d34fd_Xb3d.ms.split', 
           field='J0522-364',
           xaxis='frequency', yaxis='phase',
           selectdata=T, spw='0',
           avgchannel='20',
           avgtime='1e8',avgscan=T,
           coloraxis='baseline',
           antenna=refantenna+'&*',
           showgui=F,
           plotfile='uid___A002_X6d34fd_Xb3d.ms.split.corrBPsource_phase.png')

    print 'You should see that the scatter in the data is slightly less.'

#################
# Flagging shadowed data and any other bad data and back up flags
mystep = 10
if(mystep in thesteps):
  casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
  print 'Step ', mystep, step_title[mystep]

  for name in basename:
      flagdata(vis = name+'.ms.split',
               mode = 'shadow',
               flagbackup = F)

# DA41 is bad in the first data set
  flagdata(vis = 'uid___A002_X6d5bd2_X31.ms.split',antenna='DA41', 
           mode = 'manual', scan='0~24')

  for name in basename:
      flagmanager(vis = name+'.ms.split',
                  mode = 'save',
                  versionname = 'BeforeBandpassCalibration')

 
#################################
# Bandpass calibration
# Only one uid has the required source
# First perform time-dependent calibration, averaging the central channels
mystep = 11
if(mystep in thesteps):
  casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
  print 'Step ', mystep, step_title[mystep]

  os.system('rm -rf cal-uid___A002_X6d34fd_Xb3d-BPint.Gap')
  gaincal(vis='uid___A002_X6d34fd_Xb3d.ms.split',
          caltable='cal-'+'uid___A002_X6d34fd_Xb3d-BPint.Gap',
          spw=contchans,
          field='J0522-364',
          selectdata=F, solint='int',
          refant=refantenna, calmode='ap')

  if(calplots): # make some plots if calplots=True     
      os.system('rm -rf cal-uid___A002_X6d34fd_Xb3d-time-BPint-Gap.png')
      plotcal(caltable='cal-uid___A002_X6d34fd_Xb3d-BPint.Gap',
              xaxis = 'time', yaxis = 'phase',
              plotsymbol='o', plotrange = [0,0,-180,180],
              figfile='cal-uid___A002_X6d34fd_Xb3d-time-BPint-Gap.png',
              subplot = 211)
      plotcal(caltable='cal-'+'uid___A002_X6d34fd_Xb3d-BPint.Gap',
              xaxis = 'time', yaxis = 'amp',
              plotsymbol='o',
              figfile='cal-uid___A002_X6d34fd_Xb3d-time-BPint-Gap.png',
              subplot = 212)


      os.system('rm -rf cal-uid___A002_X6d34fd_Xb3d.B1')
      bandpass(vis='uid___A002_X6d34fd_Xb3d.ms.split',
               caltable='cal-uid___A002_X6d34fd_Xb3d.B1',
               field='J0522-364', 
               bandtype='B', 
               fillgaps=10, solnorm = T, 
               solint='inf,20ch', 
               refant=refantenna,
               gaintable='cal-uid___A002_X6d34fd_Xb3d-BPint.Gap')


  if(calplots): # make some plots if calplots=True
      os.system('rm -rf cal-uid___A002_X6d34fd_Xb3d-phase*-B1.png')
      os.system('rm -rf cal-uid___A002_X6d34fd_Xb3d-amp*-B1.png')
      for ant in range(3):
          plotcal(caltable = 'cal-uid___A002_X6d34fd_Xb3d.B1',
              xaxis='freq', yaxis='phase',
              antenna=str(ant*8)+'~'+str(ant*8+7),
              iteration='antenna',subplot=421, 
              plotrange = [0,0,-180,180],
              figfile='cal-uid___A002_X6d34fd_Xb3d-phase_ant'+str(ant*8)+'-'+str(ant*8+7)+'-B1.png')
          plotcal(caltable = 'cal-uid___A002_X6d34fd_Xb3d.B1',
              xaxis='freq', yaxis='amp',
              antenna=str(ant*8)+'~'+str(ant*8+7),
              iteration='antenna',subplot=421, 
              plotrange = [0,0,-180,180],
              figfile='cal-uid___A002_X6d34fd_Xb3d-amp_ant'+str(ant*8)+'-'+str(ant*8+7)+'-B1.png')
#################
# Putting in model for flux calibrator Pallas 
# This is only present in two of the data sets, so we use it to derive the flux density
# of the bandpass calibrator and use this to set the scale for the other data set
# Use the plots to decide the uvrange to use in calibration of Pallas
 
mystep = 12
if(mystep in thesteps):
  casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
  print 'Step ', mystep, step_title[mystep]

  setjy(vis = 'uid___A002_X6d5bd2_X31.ms.split',
    field = 'Pallas', 
    spw = '0',
    standard = 'Butler-JPL-Horizons 2012')
  os.system('rm -rf uid___A002_X6d5bd2_X31.ms.split.setjy.Pallas.png') 
  plotms(vis = 'uid___A002_X6d5bd2_X31.ms.split',
         xaxis = 'uvdist',
         yaxis = 'amp',
         ydatacolumn = 'model',
         field = 'Pallas',
         spw = '0',
         avgchannel = '9999',
         plotfile = 'uid___A002_X6d5bd2_X31.ms.split.setjy.Pallas.png')
 
  setjy(vis = 'uid___A002_X6d34fd_X102f.ms.split',
    field = 'Pallas', 
    spw = '0',
    standard = 'Butler-JPL-Horizons 2012')
  os.system('rm -rf uid___A002_X6d34fd_X102f.ms.split.setjy.Pallas.png') 
  plotms(vis = 'uid___A002_X6d34fd_X102f.ms.split',
         xaxis = 'uvdist',
         yaxis = 'amp',
         ydatacolumn = 'model',
         field = 'Pallas',
         spw = '0',
         avgchannel = '9999',
         plotfile = 'uid___A002_X6d34fd_X102f.ms.split.setjy.Pallas.png')

#################################
# Setting the flux scale
# We use the flux scale derived at 321 GHz for J0522-364 and J0648-3044
 
mystep = 13
if(mystep in thesteps):
  casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
  print 'Step ', mystep, step_title[mystep]

# Remove any previous models for QSOs
  for name in basename:
      delmod(vis=name+'.ms.split', field='J*')

# Use Pallas where present
  os.system('rm -rf cal-uid___A002_X6d5bd2_X31.Gp_short') 
  gaincal(vis = 'uid___A002_X6d5bd2_X31.ms.split',
    caltable = 'cal-uid___A002_X6d5bd2_X31.Gp_short',
    field = 'Pallas',
    spw=contchans,
    minblperant=2,
    minsnr = 2,
    selectdata = T,
    uvrange = '0~380',
    solint = 'inf',
    refant = refantenna,
    gaintype = 'G',
    calmode = 'p',
    gaintable = 'cal-uid___A002_X6d34fd_Xb3d.B1')
  
  gaincal(vis = 'uid___A002_X6d5bd2_X31.ms.split',
    caltable = 'cal-uid___A002_X6d5bd2_X31.Gp_short',
    field = 'J*',
    spw=contchans,
    minblperant=2,
    minsnr = 2,
    selectdata = T,
    solint = 'inf',
    refant = refantenna,
    gaintype = 'G',
    calmode = 'p',
    append = T,
    gaintable = 'cal-uid___A002_X6d34fd_Xb3d.B1')

  os.system('rm -rf cal-uid___A002_X6d5bd2_X31.Gap_short') 
  gaincal(vis = 'uid___A002_X6d5bd2_X31.ms.split',
    caltable = 'cal-uid___A002_X6d5bd2_X31.Gap_short',
    field = 'Pallas,J*',
    spw=contchans,
    minblperant=2,
    minsnr = 2,
    selectdata = T,
    solint = 'inf',
    refant = refantenna,
    uvrange = '0~380',
    gaintype = 'T',
    calmode = 'ap',
    gaintable = ['cal-uid___A002_X6d34fd_Xb3d.B1', 'cal-uid___A002_X6d5bd2_X31.Gp_short'])

  os.system('rm -rf cal-uid___A002_X6d5bd2_X31.Gap_short_flux') 
  F1=fluxscale(vis = 'uid___A002_X6d5bd2_X31.ms.split',
    caltable = 'cal-uid___A002_X6d5bd2_X31.Gap_short',
    fluxtable = 'cal-uid___A002_X6d5bd2_X31.Gap_short_flux',
    reference = 'Pallas') 

#
  os.system('rm -rf cal-uid___A002_X6d34fd_X102f.Gp_short') 
  gaincal(vis = 'uid___A002_X6d34fd_X102f.ms.split',
    caltable = 'cal-uid___A002_X6d34fd_X102f.Gp_short',
    field = 'Pallas',
    spw=contchans,
    minblperant=2,
    minsnr = 2, 
    selectdata = T,
    uvrange = '0~380',
    solint = 'inf',
    refant = refantenna,
    gaintype = 'G',
    calmode = 'p',
    gaintable = 'cal-uid___A002_X6d34fd_Xb3d.B1')
  
  gaincal(vis = 'uid___A002_X6d34fd_X102f.ms.split',
    caltable = 'cal-uid___A002_X6d34fd_X102f.Gp_short',
    field = 'J*', 
    spw=contchans,
    minblperant=2,
    minsnr = 2,
    selectdata = T,
    solint = 'inf',
    refant = refantenna,
    gaintype = 'G',
    calmode = 'p',
    append = T,
    gaintable = 'cal-uid___A002_X6d34fd_Xb3d.B1')

  os.system('rm -rf cal-uid___A002_X6d34fd_X102f.Gap_short') 
  gaincal(vis = 'uid___A002_X6d34fd_X102f.ms.split',
    caltable = 'cal-uid___A002_X6d34fd_X102f.Gap_short',
    field = 'Pallas,J*',
    spw=contchans,
    minblperant=2,
    minsnr = 2, 
    selectdata = T,
    solint = 'inf',
    refant = refantenna,
    uvrange = '0~380',
    gaintype = 'T',
    calmode = 'ap',
    gaintable = ['cal-uid___A002_X6d34fd_Xb3d.B1', 'cal-uid___A002_X6d34fd_X102f.Gp_short'])

  os.system('rm -rf cal-uid___A002_X6d34fd_X102f.Gap_short_flux') 
  F2=fluxscale(vis = 'uid___A002_X6d34fd_X102f.ms.split',
    caltable = 'cal-uid___A002_X6d34fd_X102f.Gap_short',
    fluxtable = 'cal-uid___A002_X6d34fd_X102f.Gap_short_flux',
    reference = 'Pallas')

# J0522 flux density extrapolated from 321 GHz
# These are the values I got at 321 GHz
# Fitted spectrum for J0522-364 with fitorder=1: 
# Flux density = 4.77004 +/- 0.00314719 (freq=316.093 GHz) 
# spidx=-0.53027 +/- 0.0397935
# Fitted spectrum for J0648-3044 with fitorder=1: 
# Flux density = 0.440988 +/- 0.000683724 (freq=316.093 GHz) 
# spidx=-0.776429 +/- 0.0934349

  J0522_flux= 4.77004
  J0522_rfreq=316.093
  J0522_spidx=-0.53027
# Also use the spec index since there is only one spw here
  J0648_spidx=-0.776429

  J0648_flux=(F1['2']['0']['fluxd'][0]/(F1['2']['0']['fluxdErr'][0])**2 + F2['2']['0']['fluxd'][0]/(F2['2']['0']['fluxdErr'][0])**2)/((F1['2']['0']['fluxdErr'][0])**-2 + (F2['2']['0']['fluxdErr'][0])**-2)
  J0648_rfreq=1e-9*(F1['freq'][0]+F2['freq'][0])/2.

  print 'Flux density of J0648-3044 is %5.3f at %7.3f GHz' % (J0648_flux, 1.e-9*J0648_rfreq)
  print 'See logger for individual results and uncertainties.'

# These are the values I got at 658 GHz
#  J0648_flux= 0.28 Jy
#  J0648_rfreq= 656.981 GHz

  setjy(vis='uid___A002_X6d34fd_Xb3d.ms.split',
        field='J0522-364',
        standard='manual',
        fluxdensity=[J0522_flux,0,0,0],
        spix=J0522_spidx,
        reffreq=str(J0522_rfreq)+'GHz')      

  for name in basename:
      setjy(vis=name+'.ms.split',
            field='J0648-3044',
            standard='manual',
            fluxdensity=[J0648_flux,0,0,0],
            spix=J0648_spidx,
            reffreq=str(J0648_rfreq)+'GHz')

#################
# Time-dependent calibration 
mystep = 14
if(mystep in thesteps):
  casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
  print 'Step ', mystep, step_title[mystep]

# phase calibration per integration
  for name in basename:
      os.system('rm -rf cal-'+name+'.Gp_int')
      gaincal(vis=name+'.ms.split',
              caltable = 'cal-'+name+'.Gp_int',
              field='J*',
              minsnr=2,
              spw=contchans,
              solint='int',
              refant=refantenna,
              calmode='p',
              gaintable = 'cal-uid___A002_X6d34fd_Xb3d.B1')

  if(calplots): # make some plots if calplots=True
      for name in basename:
          os.system('rm -rf cal-'+name+'-phase-time-Gp_int.png')
          plotcal(caltable='cal-'+name+'.Gp_int',
                  xaxis = 'time', yaxis = 'phase',poln='X',
                  plotsymbol='o',
                  figfile='cal-'+name+'-phase-time-Gp_int.png',
                  subplot = 211)
          plotcal(caltable='cal-'+name+'.Gp_int',
                  xaxis = 'time', yaxis = 'phase',poln='Y',
                  plotsymbol='o',
                  figfile='cal-'+name+'-phase-time-Gp_int.png',
                  subplot = 212)

# phase calibration per scan to apply to target
  for name in basename:
      os.system('rm -rf cal-'+name+'.Gp_inf')
      gaincal(vis=name+'.ms.split',
              caltable = 'cal-'+name+'.Gp_inf',
              field='J*',
              minsnr=2,
              spw=contchans,
              solint='inf',
              refant=refantenna,
              calmode='p',
              gaintable = 'cal-uid___A002_X6d34fd_Xb3d.B1')

  if(calplots): # make some plots if calplots=True
      for name in basename:
          os.system('rm -rf cal-'+name+'-phase-time-Gp_inf.png')
          plotcal(caltable='cal-'+name+'.Gp_inf',
                  xaxis = 'time', yaxis = 'phase',poln='X',
                  plotsymbol='o',
                  figfile='cal-'+name+'-phase-time-Gp_inf.png',
                  subplot = 211)
          plotcal(caltable='cal-'+name+'.Gp_inf',
                  xaxis = 'time', yaxis = 'phase',poln='Y',
                  plotsymbol='o',
                  figfile='cal-'+name+'-phase-time-Gp_inf.png',
                  subplot = 212)
# amp cal per scan
  for name in basename:
      os.system('rm -rf cal-'+name+'.Gap_inf')
      gaincal(vis=name+'.ms.split',
              caltable = 'cal-'+name+'.Gap_inf',
              field='J*',
              minsnr=2,
              spw=contchans,
              solint='inf',
              refant=refantenna,
              gaintype='T',
              calmode='ap',
              gaintable = ['cal-uid___A002_X6d34fd_Xb3d.B1','cal-'+name+'.Gp_int'])

  if(calplots): # make some plots if calplots=True
      for name in basename:
          os.system('rm -rf cal-'+name+'-time-Gap_inf.png')
          plotcal(caltable='cal-'+name+'.Gap_inf',
                  xaxis = 'time', yaxis = 'phase',
                  plotsymbol='o',
                  figfile='cal-'+name+'-time-Gap_inf.png',
                  subplot = 211)
          plotcal(caltable='cal-'+name+'.Gap_inf',
                  xaxis = 'time', yaxis = 'amp',
                  plotsymbol='o',
                  figfile='cal-'+name+'-time-Gap_inf.png',
                  subplot = 212)

#################
# Apply calibration
mystep = 15
if(mystep in thesteps):
  casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
  print 'Step ', mystep, step_title[mystep]

  applycal(vis='uid___A002_X6d34fd_Xb3d.ms.split',
           field='J0522-364',
           gaintable=['cal-uid___A002_X6d34fd_Xb3d.B1','cal-uid___A002_X6d34fd_Xb3d.Gp_inf','cal-uid___A002_X6d34fd_Xb3d.Gap_inf'],
           gainfield=['','J0522-364','J0522-364'],
           interp='linear,linear',
           calwt=F,flagbackup=F)

  for name in basename:
      applycal(vis=name+'.ms.split',
               field='J0648-3044',
               gaintable=['cal-uid___A002_X6d34fd_Xb3d.B1','cal-'+name+'.Gp_inf','cal-'+name+'.Gap_inf'],
               gainfield=['','J0648-3044','J0648-3044'],
               interp='linear,linear',
               calwt=F,flagbackup=F)

# Pass target data with failed phase-ref solutions as target is bright enough to self-cal
  for name in basename:
      applycal(vis=name+'.ms.split',
               field='V*',
               gaintable=['cal-uid___A002_X6d34fd_Xb3d.B1','cal-'+name+'.Gp_inf','cal-'+name+'.Gap_inf'],
               gainfield=['','J0648-3044','J0648-3044'],
               interp='linear,linear',
               applymode='calonly',
               calwt=F,flagbackup=F)

#######
# Plot phase-ref visibilities after applying instrumental calibration
mystep = 16
if(mystep in thesteps):
    casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
    print 'Step ', mystep, step_title[mystep]

    for name in basename:
        os.system('rm -rf '+name+'.ms.split.J0648-3044_*.png')
	plotms(vis=name+'.ms.split', 
	       field='J0648-3044',
	       xaxis='time', yaxis='amp',
	       selectdata=T, spw='0', 
	       avgtime='120s',avgchannel='3840',
               ydatacolumn='corrected',
               antenna=refantenna+'&*',
               showgui=F,
               plotfile=name+'.ms.split.J0648-3044_amp.png')
	plotms(vis=name+'.ms.split', 
	       field='J0648-3044',
	       xaxis='time', yaxis='phase',
	       selectdata=T, spw='0',
	       avgtime='120s',avgchannel='3840',
               ydatacolumn='corrected',
               antenna=refantenna+'&*',
               showgui=F,
               plotfile=name+'.ms.split.J0648-3044_phase.png')


###########################
# Split out the science data, concatenate and transform to lsrk to allow self-calibration
mystep = 17
if(mystep in thesteps):
    casalog.post('Step '+str(mystep)+' '+step_title[mystep],'INFO')
    print 'Step ', mystep, step_title[mystep]

    vislist=[]
    for name in basename:
            os.system('rm -rf '+name+'_VYCMa_658.ms')
            mstransform(vis=name+'.ms.split',
            outputvis=name+'_VYCMa_658.ms',datacolumn='corrected',
            field='V*') 
            vislist.append(name+'_VYCMa_658.ms')

    os.system('rm -rf VYCMa_658_origspw.ms')
    concat(vis=vislist,
           concatvis='VYCMa_658_origspw.ms')
       
# Regrid to LSRK
    os.system('rm -rf VYCMa_658.ms')
    mstransform(vis='VYCMa_658_origspw.ms',
                outputvis='VYCMa_658.ms',datacolumn='data',
                spw='0~2',
                field='V*',combinespws=T,regridms=T,
                mode='frequency',
                outframe='lsrk')
    
# Do listobs and write info to a text file
    os.system('rm VYCMa_658_listobs.txt')
    listobs(vis='VYCMa_658.ms', listfile='VYCMa_658_listobs.txt', verbose=True)
    print '<< Printed listobs output to VYCMa_658_listobs.txt'

#----------------------------------------------------------------------------------
#----- End of calibration script.
#----- To continue, see imaging script "VYCMa_Band9_Imaging.py"
#----------------------------------------------------------------------------------
