AntennaeBand7 North Calibration 3.4: Difference between revisions

From CASA Guides
Jump to navigationJump to search
 
(63 intermediate revisions by 3 users not shown)
Line 1: Line 1:
[[Category:ALMA]][[Category:Calibration]][[Category:Spectral Line]]
[[Category:ALMA]][[Category:Calibration]][[Category:Spectral Line]]


*'''This script assumes that you have downloaded Antennae_Band7_UnCalibratedMSAndTablesForReduction.tgz from [[AntennaeBand7#Obtaining_the_Data]]'''.
*'''Details of the ALMA observations are provided at [[AntennaeBand7_North_SS12]]'''.


*'''Details of the ALMA observations are provided at [[AntennaeBand7_3.4]]'''.
*'''This casaguide covers the processing of a subset of the full Science Verification data; we consider only the the mosaic of the northern galaxy.'''
 
*'''This casaguide covers the processing of a subset of the data for the Northern mosaic'''.


*'''This portion of the guide covers calibration of the raw visibility data. To skip to the imaging portion of the guide, see: [[AntennaeBand7 North Imaging 3.4]]'''.
*'''This portion of the guide covers calibration of the raw visibility data. To skip to the imaging portion of the guide, see: [[AntennaeBand7 North Imaging 3.4]]'''.
Line 17: Line 15:
The general procedure in this guide follows the other ALMA CASA guides: [[NGC3256Band3]] and [[TWHydraBand7_3.4]].
The general procedure in this guide follows the other ALMA CASA guides: [[NGC3256Band3]] and [[TWHydraBand7_3.4]].


==Unpack the Data==
==Getting Started==
 
Once you have downloaded the Antennae_Band7_UnCalibratedMSandTablesForReduction.tgz, unpack the file in a terminal outside CASA using
 
<source lang="bash">


tar -xvzf Antennae_Band7_UnCalibratedMSandTablesForReduction.tgz
For the Synthesis Imaging school tutorial, we have provided you with the data you will need for this tutorial. For the Tuesday tutorials in the Speare building, the data live in "/var/nrao/ss_ant/calibration/"


</source>
For this portion of the guide change to the directory "ss_ant/calibration" and begin work from there. You will find a README file explaining the contents of the directory. These include the data, several calibration tables, and a directory of useful scripts ("analysis_scripts/"). Work on this portion of the guide from inside this directory.


then change directory to the new directory (created by the unpacking)
From the "calibration/" directory, begin by starting CASA.


<source lang="bash">
<source lang="bash">
 
casapy
cd Antennae_Band7_UnCalibratedMSandTablesForReduction
 
</source>
</source>


You may wish to type
Note that this guide requires Python module [[analysis_Utilities|analysisUtils]]. Test whether these are available inside of CASA (see below) by trying the following:
 
<source lang="bash">
 
ls


<source lang="python">
# In CASA
sys.path.append("analysis_scripts/")
import analysisUtils as au
</source>
</source>


to look at the files present. You should see a set of files with extension ".ms". These are CASA measurement set (MS) files. The data have already been converted to MS format from the native ALMA format using the CASA task {{importasdm}}. In addition to the data, we provide you with calibration tables containing system temperature (Tsys), water vapor radiometer (WVR), and antenna position information. For Early Science, these tables will either be pre-applied or supplied with the data.
if it works, you have the analysis_Utilities in the path and may proceed with the guide. The "sys.path.append" call adds the subdirectory "analysis_scripts/" to your path (so that python searches this directory when trying to import a module). If this does not work as for help or refer here: [[analysis_Utilities|analysisUtils]] to learn how to retrieve these scripts on your own.
 
This guide requires Python module [[analysis_Utilities|analysisUtils]]. If you have not already installed [[analysis_Utilities|analysisUtils]] please follow the link to do so.
 
To begin, start CASA by typing


<source lang="bash">
This guide has been written for CASA release 3.4.0.  Please confirm your version before proceeding by pasting the following lines of code into your shell:


casapy
</source>
Be sure that you are using the version indicated at the top of this page.
==Confirm your version of CASA==
This guide has been written for CASA release 3.4.0.  Please confirm your version before proceeding.
<source lang="python">
<source lang="python">
# In CASA
# In CASA
Line 71: Line 50:
</source>
</source>


==Install Analysis Utilities==
Once you have verified that you have the right version of CASA and have access to the analysis utilities module, you can are ready to begin.


Analysis Utilities (or analysisUtils for short) is a small set of Python scripts that provide a number of analysis and plotting utilities for ALMA data reduction. This guide uses a few of these utilities. They are very easy to install (just download and untar). See
==Initial Inspection and A Priori Flagging==


http://casaguides.nrao.edu/index.php?title=Analysis_Utilities
Start here if you wish to step through the full guide (which we recommend). If you are pressed for time or want to move directly to imaging you may chose to start with the final flagging instead.


for a full description and download instructions. If you do not wish to do this, see the CASA 3.3 version of the guide linked at the top of this page for alternative (but slow) plotting options. Analysis Utilities are updated frequently so if its been a while since you installed it, its probably worth doing it again. If you are at an ALMA site or ARC, the analysis utilities are probably already installed and up to date.
===Initial Inspection===
 
==Initial Inspection==


First we will take stock of what we have. If you have not already done so, begin by reviewing the description of the observations here: [[AntennaeBand7_3.4]]. In this tutorial we only deal with the 4 data sets for the Northern mosaic:
First we will take stock of what we have. If you have not already done so, begin by reviewing the description of the observations here: [[AntennaeBand7_3.4]]. In this tutorial we only deal with the 4 data sets for the Northern mosaic:
Line 90: Line 67:


Detailed instructions and a walkthrough will be given only for the first of these <tt>uid___A002_X1ff7b0_Xb.ms</tt>.
Detailed instructions and a walkthrough will be given only for the first of these <tt>uid___A002_X1ff7b0_Xb.ms</tt>.
<pre style="background-color: #ffa07a;">
We provide you with the "raw" data for only uid___A002_X1ff7b0_Xb.ms. For
the other three data sets we provide the data with the WVR and Tsys calibrations
already applied (but not other calibration). We recommend that you step through
the application of the WVR and Tsys calibration for this first data set, so that
you understand how it is done. The guide will then take you through the full
calibration of that first data set. At the end, you can find suggestions on how
to calibrate the other three. You may do so, or you may proceed to image
the provided calibrated data.".
</pre>


The first step is to get basic information about the data: targets observed, time range, spectral setup, and so on. We do this using the task {{listobs}}, which will output a detailed summary of a dataset. Enter the following commands into CASA:
The first step is to get basic information about the data: targets observed, time range, spectral setup, and so on. We do this using the task {{listobs}}, which will output a detailed summary of a dataset. Enter the following commands into CASA:
Line 224: Line 212:
This will show you the antenna positions for the given dataset, and save that as a file named "uid___A002_X1ff7b0_Xb.plotants.png". The <tt>clearstat</tt> command will clear any lingering table locks from the plotting.
This will show you the antenna positions for the given dataset, and save that as a file named "uid___A002_X1ff7b0_Xb.plotants.png". The <tt>clearstat</tt> command will clear any lingering table locks from the plotting.


==How to Deal With Multiple Measurement Sets==
===Aside: How to Deal With Multiple Measurement Sets===


It should already be clear from the initial inspection that dealing with 4 (or more) data sets at the same time can be a bit problematic. The source name changes between these two scripts and there are different numbers of fields in the mosaic.  We get around much of this issue by dealing with only the 4 Northern Mosaic datasets and ignoring the 6 Southern ones, as well as focusing on a single MS in the walthrough portion of this guide.
It should already be clear from the initial inspection that dealing with 4 (or more) data sets at the same time can be a bit problematic. The source name changes between these two scripts and there are different numbers of fields in the mosaic.  We get around much of this issue by dealing with only the 4 Northern Mosaic datasets and ignoring the 6 Southern ones, as well as focusing on a single MS in the walthrough portion of this guide.
Line 232: Line 220:
Near the end of the tutorial we will direct you to process the remainder of the Northern Mosaic fields using  'for' loops. We will not be able to show every diagnostic plot but we give an example of each and the syntax to generate the rest. Also please be aware that even on a very fast machine this whole process can take a while, we are simply dealing with a lot of data.
Near the end of the tutorial we will direct you to process the remainder of the Northern Mosaic fields using  'for' loops. We will not be able to show every diagnostic plot but we give an example of each and the syntax to generate the rest. Also please be aware that even on a very fast machine this whole process can take a while, we are simply dealing with a lot of data.


==''A Priori'' Flagging==
===''A Priori'' Flagging===


Even before we look in detail, we know that there are some data that we wish to exclude. We will start by flagging "shadowed" data where one antenna blocks the line of sight of another. We will also flag scans that were used to carry out pointing and atmospheric calibration, identified by their scan intent. Finally, we will flag the autocorrelation data (the correlation of the signal from an antenna with itself) as we are only interested in cross-correlation data  to make an interferometric image.
Even before we look in detail, we know that there are some data that we wish to exclude. We will start by flagging "shadowed" data where one antenna blocks the line of sight of another. We will also flag scans that were used to carry out pointing and atmospheric calibration, identified by their scan intent. Finally, we will flag the autocorrelation data (the correlation of the signal from an antenna with itself) as we are only interested in cross-correlation data  to make an interferometric image.


You may want to reset the flagging if you have tried this step before and are starting over though this is not necessary on your first time through. Do so using {{flagdata}}:
You may want to reset the flagging if you have tried this step before and are starting over though this is not necessary on your first time through. Do so using {{tflagdata}}:
<source lang="python">
<source lang="python">
# In CASA
# In CASA
flagdata(vis='uid___A002_X1ff7b0_Xb.ms',mode='manualflag', unflag=T, flagbackup=F)
tflagdata(vis='uid___A002_X1ff7b0_Xb.ms',mode='unflag',action='apply',flagbackup=F)
</source>
</source>
<b>CASA 3.4 Note:</b> here we use the new <tt>tflagdata</tt> which, although still experimental, is faster than <tt>flagdata</tt> for most operations.


To carry out the flagging, we will assemble a set of flagging commands and then use the <tt>flagcmd</tt> task to execute them.  These commands will be stored in a Python list of strings called <tt>myflags</tt>, each of which will be a specific flagging command.  The operation of {{flagcmd}} is decribed by <tt>help flagcmd</tt> (with examples), and the syntax for the flagging command modes is given in <tt>help tflagdata</tt>.
To carry out the flagging, we will assemble a set of flagging commands and then use the <tt>flagcmd</tt> task to execute them.  These commands will be stored in a Python list of strings called <tt>myflags</tt>, each of which will be a specific flagging command.  The operation of {{flagcmd}} is decribed by <tt>help flagcmd</tt> (with examples), and the syntax for the flagging command modes is given in <tt>help tflagdata</tt>.
Line 304: Line 293:
flag version tables.
flag version tables.


==Create and Apply Tsys, WVR, and Antenna Position Calibration Tables==
===Create and Apply Tsys, WVR, and Antenna Position Calibration Tables===


We now carry out "a priori" calibration steps that need to occur before getting to data-derived calibrations.
We now carry out "a priori" calibration steps that need to occur before getting to data-derived calibrations.
Line 328: Line 317:
</figure>
</figure>


===Tsys===
====Tsys====


The Tsys calibration gives a first-order correction for the atmospheric opacity as a function of time and frequency and associates weights with each visibility that persists through imaging.
The Tsys calibration gives a first-order correction for the atmospheric opacity as a function of time and frequency and associates weights with each visibility that persists through imaging.
Line 376: Line 365:
#In CASA
#In CASA
os.system('rm -rf cal_plots/Tsys_plots/uid___A002_X1ff7b0_Xb.tdm.tsys*')
os.system('rm -rf cal_plots/Tsys_plots/uid___A002_X1ff7b0_Xb.tdm.tsys*')
tsysfields=['3c279','Titan','Antennae']
tsysfields=['3c279','Titan','NGC4038*']
caltable=asdm+'.tdm.tsys'
outfname={'3c279':'3c279','Titan':'Titan','NGC4038*':'NGC4038'}
for field in tsysfields:
for field in tsysfields:
     au.plotbandpass2(caltable='uid___A002_X1ff7b0_Xb.tdm.tsys',
     au.plotbandpass2(caltable='uid___A002_X1ff7b0_Xb.tdm.tsys',
                     field=field,yaxis='amp',xaxis='freq',
                     field=field,yaxis='amp',xaxis='freq',
                     showatm=True,overlay='time',
                     showatm=True,overlay='time',
                     figfile='cal_plots/Tsys_plots/uid___A002_X1ff7b0_Xb.tdm.tsys.'+field,
                     figfile='cal_plots/Tsys_plots/uid___A002_X1ff7b0_Xb.tdm.tsys.'+outfname[field],
                     buildpdf=False,
                     buildpdf=False,
                     interactive=False,chanrange='8~120',subplot=42)
                     interactive=False,chanrange='8~120',subplot=42)
Line 389: Line 378:
Now have a look at the Tsys vs. frequency plots or see <xr id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.DV02.spw5.CASA3_4.png"/>, <xr id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.DV08.spw5.CASA3_4.png"/>, and <xr id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.PM01.spw5.CASA3_4.png"/> for examples on our first data set. You can see the effect of a close pair of atmospheric ozone absorption lines at about 343.2 GHz that makes Tsys larger near that frequency in all antennas. Applying the Tsys calibration tables will minimize the contribution of these atmospheric lines. Again DV04 stands out with its very high Tsys.  Although not present in the first data sets, Antenna DV12 exhibits periodic spikes in Tsys vs. frequency for one polarization (see <xr id="Uid___A002_X215db8_X392.tdm.tsys.3c279.DV11.spw5.CASA3_4.png"/> for an example from a data set in Southern Mosaic).  It may or may not be possible to calibrate that behavior out.  We will make a note to look carefully at DV12 further on in the calibration process.
Now have a look at the Tsys vs. frequency plots or see <xr id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.DV02.spw5.CASA3_4.png"/>, <xr id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.DV08.spw5.CASA3_4.png"/>, and <xr id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.PM01.spw5.CASA3_4.png"/> for examples on our first data set. You can see the effect of a close pair of atmospheric ozone absorption lines at about 343.2 GHz that makes Tsys larger near that frequency in all antennas. Applying the Tsys calibration tables will minimize the contribution of these atmospheric lines. Again DV04 stands out with its very high Tsys.  Although not present in the first data sets, Antenna DV12 exhibits periodic spikes in Tsys vs. frequency for one polarization (see <xr id="Uid___A002_X215db8_X392.tdm.tsys.3c279.DV11.spw5.CASA3_4.png"/> for an example from a data set in Southern Mosaic).  It may or may not be possible to calibrate that behavior out.  We will make a note to look carefully at DV12 further on in the calibration process.


===WVR===
====WVR====


The WVR calibration uses observations of the wings of the 183 GHz atmospheric water line to correct for phase variations as a function of time. As noted in the tsys section, this run of gencal will append to existing WVR produced tables. To avoid this, preexisting wvrgcal data is removed.  
The WVR calibration uses observations of the wings of the 183 GHz atmospheric water line to correct for phase variations as a function of time. As noted in the tsys section, this run of gencal will append to existing WVR produced tables. To avoid this, preexisting wvrgcal data is removed.  
Line 398: Line 387:
</source>
</source>


===Antenna Positions===
====Antenna Positions====
The antenna position table reflects refinements in the measured positions of the antennas from those stored in the data. gencal will now be used put antenna position data into each observation. Again, gencal will merely append to existing antenna position data, ruining any subsequent results. We start by removing any existing antenna position refinements, followed by defining the antenna names, then their refinements (both as arrays), finally running gencal to create the information CASA can refer to for antenna positions.
The antenna position table reflects refinements in the measured positions of the antennas from those stored in the data. gencal will now be used put antenna position data into each observation. Again, gencal will merely append to existing antenna position data, ruining any subsequent results. We start by removing any existing antenna position refinements, followed by defining the antenna names, then their refinements (both as arrays), finally running gencal to create the information CASA can refer to for antenna positions.
<source lang="python">
<source lang="python">
Line 422: Line 411:
</source>
</source>


===Applycal===
====Applycal====


We are now ready to apply the Tsys and the WVR calibration tables to the data with {{applycal}}, which reads the specified gain calibration tables, applies them to the (raw) data column, and writes the calibrated results into the corrected column. It is important to only apply Tsys and WVR corrections obtained close in time to the data being corrected, so in addition to looping over data sets we define the list of unique source names and loop over these. Then by setting '''gainfield''' and '''field''' to the same value we ensure that Tsys and WVR calibrations are only applied to the source for which they are measured. We will only correct '''spw''' 1 and 3, our science windows, because we will drop the other data in a moment.
We are now ready to apply the Tsys and the WVR calibration tables to the data with {{applycal}}, which reads the specified gain calibration tables, applies them to the (raw) data column, and writes the calibrated results into the corrected column. It is important to only apply Tsys and WVR corrections obtained close in time to the data being corrected, so in addition to looping over data sets we define the list of unique source names and loop over these. Then by setting '''gainfield''' and '''field''' to the same value we ensure that Tsys and WVR calibrations are only applied to the source for which they are measured. We will only correct '''spw''' 1 and 3, our science windows, because we will drop the other data in a moment.
Line 442: Line 431:
you would use <tt>spwmap=[[],[0,5,5,7,5,5,5,7],[]]</tt>.
you would use <tt>spwmap=[[],[0,5,5,7,5,5,5,7],[]]</tt>.


Now run the applycal commands.
Now run the applycal commands (this may take up to 10 minutes, maybe more depending on your workstation):
<source lang="python">
<source lang="python">
# In CASA
# In CASA
Line 465: Line 454:
If you were to you browse through the whole data set, you will probably note some problems along the same lines as the DV04 issue we saw above. We'll apply these as additional data flagging in just a moment.
If you were to you browse through the whole data set, you will probably note some problems along the same lines as the DV04 issue we saw above. We'll apply these as additional data flagging in just a moment.


==Inspect Data==
===Inspect Data===


<figure id="plotms_amp_vs_freq_example-data.png">
<figure id="plotms_amp_vs_freq_example-data.png">
Line 519: Line 508:


</pre>
</pre>
<b>Note: Not all the plots described below are shown to the right.  Feel free to experiment also.</b>


First, we plot amplitude as a function of frequency for 3c279. We start by plotting the DATA column, set color to indicate the two correlations (i.e., the XX and YY polarizations), and ask plotms to iterate over baseline. By setting '''antenna''' to 'DV11&*' we select only baselines that include DV11. We ask plotms to average all data over a very long timescale, '''avgtime''' = 1e8 seconds ~ 3 years or much longer than the time spanned by the whole data set. By setting '''avgscan''' = True we allow {{plotms}} to average across scan boundaries. The result is a plot of average amplitude per channel vs. frequency.
First, we plot amplitude as a function of frequency for 3c279. We start by plotting the DATA column, set color to indicate the two correlations (i.e., the XX and YY polarizations), and ask plotms to iterate over baseline. By setting '''antenna''' to 'DV11&*' we select only baselines that include DV11. We ask plotms to average all data over a very long timescale, '''avgtime''' = 1e8 seconds ~ 3 years or much longer than the time spanned by the whole data set. By setting '''avgscan''' = True we allow {{plotms}} to average across scan boundaries. The result is a plot of average amplitude per channel vs. frequency.
Line 704: Line 695:
The suite of plots we generated above (along with the earlier inspection of the Tsys tables) gives us the tools we need to identify problematic data through the data sets. We use this to generate a set of inspection-driven {{flagdata}} commands for each data set. We apply these before the bandpass and gain calibration.
The suite of plots we generated above (along with the earlier inspection of the Tsys tables) gives us the tools we need to identify problematic data through the data sets. We use this to generate a set of inspection-driven {{flagdata}} commands for each data set. We apply these before the bandpass and gain calibration.


==Apply Flagging==
==Final Flagging and Calibration==
Based on this inspection and the other plots we have made, we now flag problematic portions of the data. We break up the flags by reason for flagging in order to illustrate the process. As you reduce your own data it may be more efficient to group flags by data set and make use of the flagcmd command. Except for the "post-calibration" flagging, the inspection plots that we just looked through have already revealed all of the problems that we flag. We structure the guide so that the flagging is grouped in one place.
 
Starting from the <tt>.wvrtsys.ms</tt> data we just flagged, pre-calibrated, and split, we continue on with extra flagging and the main calibration.
 
===Starting Point===
 
If you went through the process of pre-calibration from the previous section, then you should have a <tt>.wvrtsys.ms</tt> dataset ready to go.


As before, we may wish to reset our flags before beginning (particularly if one iterates this process) via:
If you are starting the tutorial at this point, then you should download or copy (from a designated location) the tar-ball <tt>Antennae_Band7_North_PreCalibratedMS.tgz</tt>.  When you unpack this
<source lang="bash">


<source lang="python">
tar -xvzf Antennae_Band7_North_PreCalibratedMS.tgz
# In CASA


basename_all=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9",
    "uid___A002_X2181fb_X49","uid___A002_X1ff7b0_X1c8","uid___A002_X207fe4_X1f7",
    "uid___A002_X207fe4_X4d7","uid___A002_X215db8_X18","uid___A002_X215db8_X1d5",
    "uid___A002_X215db8_X392"]
for asdm in basename_all:
    flagdata(vis = asdm+'.wvrtsys.ms',mode='manualflag', unflag= T, flagbackup = F)
</source>
</source>
you will find the <tt>.wvrtsys.ms</tt> files in a sub-directory named <tt>Antennae_Band7_North_PreCalibratedMS</tt>.  You will <tt>cd</tt> into this directory to run CASA, or move the files into your working directory.


Remember that we dropped the flagged data when splitting out after the WVR and Tsys calibration, so this should not undo your "A Priori" flagging of shadowed data, autocorrelations, etc.. In any case this unflagging step is not necessary during the first iteration.
===Apply More Flagging: Search and Destroy===


* '''Edge Channels'''
<figure id="plotms.uid___A002_X1ff7b0_Xb.3C279.ampvschan.png">
[[File:plotms.uid___A002_X1ff7b0_Xb.3C279.ampvschan.png|200px|thumb|right|<caption> Amplitude vs. channel for baselines to DV11. This kind of plot can be inspected to get an idea of the presence or magnitude of any roll-off in sensitivity near the edges of the spectral window.</caption>]]
</figure>
<figure id="amp_vs_uv_titan_obs.png">
[[File:amp_vs_uv_titan_obs.png|200px|thumb|right|<caption> Observed amplitude vs. uv-distance for observations of Titan in the first data set. Note the scatter for low projected antenna separations. We will flag these short-spacing data, which may reflect contamination by Saturn, and use only the more extended baselines for flux calibration.</caption>]]
</figure>
<figure id="phase_vs_freq_DV13.png">
[[File:phase_vs_freq_DV13.png|200px|thumb|right|<caption> Phase vs. frequency for DV13 in a data set where this antenna shows evidence of imperfect delay calibration.</caption>]]
</figure>
<figure id="amp_vs_time_missing_scans.png">
[[File:amp_vs_time_missing_scans.png|200px|thumb|right|<caption> Amplitude vs. time colored by field for a data set where the final visit to the phase calibrator is missing. We will flag the last set of source data to ensure that each visit to the source is flanked in time by visits to the phase calibrator.</caption>]]
</figure>
<figure id="phase_vs_time_DV09.png">
[[File:phase_vs_time_DV09.png|200px|thumb|right|<caption> Phase vs. time for DV09 on a problematic day. It may prove problematic to calibrate the data near this discontinuity so we flag data near this time.</caption>]]
</figure>
<figure id="amp_vs_uvdist_outliers.png">
[[File:amp_vs_uvdist_outliers.png|200px|thumb|right|<caption> Amplitude vs. u-v distance ''after'' calibration. Note the outlying data. We track these down using the select (box with green "+") and locate (magnifying glass) features inside plotms and identify several problematic baselines across our data. ''Note that you cannot make this plot at this point in the guide, these pathologies become evident after calibration, requiring an iterative approach to reduction.''</caption>]]
</figure>


ALMA's sensitivity decreases near the edge of the baseband and it is often useful to check for a 'roll-off' in sensitivity near the edge of the band. This will appear as a downturn in amplitude as a function of channel near the edge of the window in the uncalibrated data, as a flaring due to increased noise at the spw edges in the calibrated data. It will also be visible in the amplitude part of the bandpass calibration table. Because our FDM spw does not cover the full baseband, we do not see a strong roll off in our data (see <xr id="amp_vs_channel_example.png"/>), where there is only a mild hint of a roll-off at the high end) but we do flag a (very) few channels at the high and low-frequency edge of the data set to be safe.


<figure id="amp_vs_channel_example.png">
Based on this inspection and the other plots we have made, we now flag problematic portions of the data. We break up the flags by reason for flagging in order to illustrate the process. As you reduce your own data it may be more efficient to group flags by data set and make use of the flagcmd command. Except for the "post-calibration" flagging, the inspection plots that we just looked through have already revealed all of the problems that we flag. We structure the guide so that the flagging is grouped in one place.
[[File:amp_vs_channel_example.png|200px|thumb|right|<caption> Amplitude vs. channel for one uncalibrated antenna pair. This kind of plot can be inspected to get an idea of the presence or magnitude of any roll-off in sensitivity near the edges of the spectral window.</caption>]]
</figure>


As before, we may wish to reset our flags before beginning (particularly if one iterates this process) using {{tflagdata}}:
<source lang="python">
<source lang="python">
# In CASA
# In CASA
tflagdata(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms', mode='unflag', action='apply', flagbackup=F)
</source>
Remember that we dropped the flagged data when splitting out after the WVR and Tsys calibration, so this should not undo your "A Priori" flagging of shadowed data, autocorrelations, etc.. In any case this unflagging step is not necessary during the first iteration.


for asdm in basename_all:
As before, we will accumulate our flagging commands in Python string list variables. However, because the flagging commands will in general depend upon the dataset, we will construct a dictionary indexed by asdm name prefix:
    flagdata(vis = asdm+'.wvrtsys.ms',spw = '0:0~7,0:3831~3839', flagbackup = F)
<source lang="python">
 
# In CASA
for asdm in basename_all:
myflagdict = {'uid___A002_X1ff7b0_Xb':[],
    flagdata(vis = asdm+'.wvrtsys.ms',spw = '0:3260~3320', flagbackup = F)
              'uid___A002_X207fe4_X3a':[],
              'uid___A002_X207fe4_X3b9':[],
              'uid___A002_X2181fb_X49':[]}
</source>
</source>
Although we are walking you through only the first dataset, we will accumulate flags for all the datasets.


* '''Problematic Tsys measurements'''
* '''Edge Channels'''


Above we noted issues with the Tsys measurements for both DV04 and DV12. We flag the affected data. Each of these issues should be visible in the Tsys plots you made above (e.g., see <xr id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.DV02.spw5.CASA3_4.png"/> and <xr id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.PM01.spw5.CASA3_4.png"/>).
ALMA's sensitivity decreases near the edge of the baseband and it is often useful to check for a 'roll-off' in sensitivity near the edge of the band. This will appear as a downturn in amplitude as a function of channel near the edge of the window in the uncalibrated data, as a flaring due to increased noise at the spw edges in the calibrated data. It will also be visible in the amplitude part of the bandpass calibration table. Because our FDM spw does not cover the full baseband, we do not see a strong roll off in our data (see <xr id="plotms.uid___A002_X1ff7b0_Xb.3C279.ampvschan.png"/>), where there is only a mild hint of a roll-off at the high end) but we do flag a (very) few channels at the high and low-frequency edge of the data set to be safe.


<source lang="python">
<source lang="python">
# In CASA
# In CASA
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
      field='3c279',
      xaxis='channel', yaxis='amp',
      selectdata=T, spw='',
      avgtime='1e8',avgscan=T,
      coloraxis='baseline',
      antenna='DV11&*',
      ydatacolumn='corrected',
      plotfile='plotms.uid___A002_X1ff7b0_Xb.3C279.ampvschan.png')
</source>


asdm="uid___A002_X1ff7b0_Xb"
We construct the flag commands (same for all datasets:
flagdata(vis=asdm+'.wvrtsys.ms', antenna='DV04', flagbackup=F)
<source lang="python">
# In CASA
myflagdict['uid___A002_X1ff7b0_Xb'].append("mode='manual' spw='0:0~7,0:3831~3839'")
myflagdict['uid___A002_X207fe4_X3a'].append("mode='manual' spw='0:0~7,0:3831~3839'")
myflagdict['uid___A002_X207fe4_X3b9'].append("mode='manual' spw='0:0~7,0:3831~3839'")
myflagdict['uid___A002_X2181fb_X49'].append("mode='manual' spw='0:0~7,0:3831~3839'")
</source>


asdm="uid___A002_X207fe4_X3a"
* '''Problematic Tsys measurements'''
flagdata(vis=asdm+'.wvrtsys.ms',antenna='DV12',correlation='YY', flagbackup=F)


asdm="uid___A002_X207fe4_X3b9"
Above we noted issues with the Tsys measurements for both DV04 and DV12. We flag the affected data. Each of these issues should be visible in the Tsys plots you made above (e.g., see <xr id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.DV02.spw5.CASA3_4.png"/> and <xr id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.PM01.spw5.CASA3_4.png"/>).
flagdata(vis=asdm+'.wvrtsys.ms',antenna='DV12',correlation='YY', flagbackup=F)


asdm="uid___A002_X2181fb_X49"
We add the flag:
flagdata(vis=asdm+'.wvrtsys.ms',antenna='DV12',correlation='YY', flagbackup=F)
<source lang="python">
# In CASA
myflagdict['uid___A002_X1ff7b0_Xb'].append("mode='manual' antenna='DV04'")
</source>


asdm="uid___A002_X1ff7b0_X1c8"
<b>Note:</b> As noted above DV12 has dodgy Tsys in YY, but is not present in the first SB. Thus, we will add the flags
flagdata(vis=asdm+'.wvrtsys.ms',antenna='DV04',flagbackup=F)
<source lang="python">
 
# In CASA
asdm="uid___A002_X207fe4_X1f7"  
myflagdict['uid___A002_X207fe4_X3a'].append("mode='manual' antenna='DV12' correlation='YY'")
flagdata(vis=asdm+'.wvrtsys.ms',antenna='DV12',correlation='YY', flagbackup=F)
myflagdict['uid___A002_X207fe4_X3b9'].append("mode='manual' antenna='DV12' correlation='YY'")
 
myflagdict['uid___A002_X2181fb_X49'].append("mode='manual' antenna='DV12' correlation='YY'")
asdm="uid___A002_X207fe4_X4d7"
flagdata(vis=asdm+'.wvrtsys.ms',antenna='DV12',correlation='YY', flagbackup=F)
 
asdm="uid___A002_X215db8_X18"
flagdata(vis=asdm+'.wvrtsys.ms',antenna='DV12',correlation='YY', flagbackup=F)
 
asdm="uid___A002_X215db8_X1d5"
flagdata(vis=asdm+'.wvrtsys.ms',antenna='DV12',correlation='YY', flagbackup=F)
 
asdm="uid___A002_X215db8_X392"
flagdata(vis=asdm+'.wvrtsys.ms',antenna='DV12',correlation='YY', flagbackup=F)
</source>
</source>


* '''Unreliable Short-Spacing Measurements on Titan'''
* '''Unreliable Short-Spacing Measurements on Titan'''
<figure id="amp_vs_uv_titan_obs.png">
[[File:amp_vs_uv_titan_obs.png|200px|thumb|right|<caption> Observed amplitude vs. uv-distance for observations of Titan in the first data set. Note the scatter for low projected antenna separations. We will flag these short-spacing data, which may reflect contamination by Saturn, and use only the more extended baselines for flux calibration.</caption>]]
</figure>


Saturn may contaminate the short u-v spacings from Titan. In any case these often show significant scatter (<xr id="amp_vs_uv_titan_obs.png"/>), so we flag them. There are still enough baselines to determine a good amplitude calibration for each antenna.
Saturn may contaminate the short u-v spacings from Titan. In any case these often show significant scatter (<xr id="amp_vs_uv_titan_obs.png"/>), so we flag them. There are still enough baselines to determine a good amplitude calibration for each antenna.
Line 788: Line 802:
<source lang="python">
<source lang="python">
# In CASA
# In CASA
myflagdict['uid___A002_X1ff7b0_Xb'].append("mode='manual' field='Titan' uvrange='0~50'")
</source>


asdm="uid___A002_X1ff7b0_Xb"
<b>Note:</b> For different scheduling blocks, this may show up at different uv-distances. We set these individually (you can make the plots if you want to see where we get the values):
flagdata(vis=asdm+'.wvrtsys.ms', field='Titan', uvrange='0~50', flagbackup = F)
<source lang="python">
 
# In CASA
asdm="uid___A002_X207fe4_X3a"
myflagdict['uid___A002_X207fe4_X3a'].append("mode='manual' field='Titan' uvrange='0~40'")
flagdata(vis=asdm+'.wvrtsys.ms', field='Titan', uvrange='0~40', flagbackup = F)
myflagdict['uid___A002_X207fe4_X3b9'].append("mode='manual' field='Titan' uvrange='0~50'")
 
myflagdict['uid___A002_X2181fb_X49'].append("mode='manual' field='Titan' uvrange='0~30'")
asdm="uid___A002_X207fe4_X3b9"
flagdata(vis=asdm+'.wvrtsys.ms', field='Titan', uvrange='0~50', flagbackup = F)
 
asdm="uid___A002_X2181fb_X49"
flagdata(vis=asdm+'.wvrtsys.ms', field='Titan', uvrange='0~30', flagbackup = F)
 
asdm="uid___A002_X1ff7b0_X1c8"
flagdata(vis=asdm+'.wvrtsys.ms', field='Titan', uvrange='0~50', flagbackup = F)
 
asdm="uid___A002_X207fe4_X1f7"
flagdata(vis=asdm+'.wvrtsys.ms', field='Titan', uvrange='0~30', flagbackup = F)
 
asdm="uid___A002_X207fe4_X4d7"
flagdata(vis=asdm+'.wvrtsys.ms', field='Titan', uvrange='0~30', flagbackup = F)
</source>
</source>


* '''Delay Issues'''  
* '''Delay Issues'''  
<figure id="phase_vs_freq_DV13.png">
[[File:phase_vs_freq_DV13.png|200px|thumb|right|<caption> Phase vs. frequency for DV13 in a data set where this antenna shows evidence of imperfect delay calibration.</caption>]]
</figure>


DV13 and a few other antennas show signatures of an imperfect delay calibration. This is most easily identified via strong "wrapping" of phase as a function of frequency (see <xr id="phase_vs_freq_DV13.png"/>). Such effects can be calibrated out with mild delay issues largely accounted for by the bandpass solution. The phase wrapping in DV13 seems weak enough that we will trust the calibrations to remove it. For a more extreme example see the CASA guide describing the calibration of [[NGC3256Band3]].
DV13 and a few other antennas show signatures of an imperfect delay calibration. This is most easily identified via strong "wrapping" of phase as a function of frequency (see <xr id="phase_vs_freq_DV13.png"/>). Such effects can be calibrated out with mild delay issues largely accounted for by the bandpass solution. The phase wrapping in DV13 seems weak enough that we will trust the calibrations to remove it. For a more extreme example see the CASA guide describing the calibration of [[NGC3256Band3]].


* '''Missing Phase Calibrator Observations'''
* '''Missing Phase Calibrator Observations'''
<figure id="amp_vs_time_missing_scans.png">
[[File:amp_vs_time_missing_scans.png|200px|thumb|right|<caption> Amplitude vs. time colored by field for a data set where the final visit to the phase calibrator is missing. We will flag the last set of source data to ensure that each visit to the source is flanked in time by visits to the phase calibrator.</caption>]]
</figure>


As a general rule, we want to be sure that observations of the phase calibrator (3c279) bracket each source observation. Two of the data sets do not include a final phase calibrator observation (see <xr id="amp_vs_time_missing_scans.png"/>) and for those two cases we flag the affected source observations.
As a general rule, we want to be sure that observations of the phase calibrator (3c279) bracket each source observation. Two of the data sets do not include a final phase calibrator observation (see <xr id="amp_vs_time_missing_scans.png"/>) and for those two cases we flag the affected source observations.
Line 829: Line 823:
<source lang="python">
<source lang="python">
# In CASA
# In CASA
 
myflagdict['uid___A002_X207fe4_X3b9'].append("mode='manual' timerange='00:53:47~01:08:00'")
asdm="uid___A002_X207fe4_X3b9"
flagdata(vis=asdm+'.wvrtsys.ms',timerange='00:53:47~01:08:00',flagbackup = F)
 
asdm="uid___A002_X215db8_X18"
flagdata(vis=asdm+'.wvrtsys.ms',antenna='DV10',timerange='19:46:20~20:34:40',flagbackup=F)
</source>
</source>


Line 840: Line 829:


For several antennas we find sudden jumps in the phase of the phase calibrator as a function of time. These are visible in the plots of uncalibrated phase vs. time for single baselines above, and we show an example in <xr id="phase_vs_time_DV09.png"/>. It will not be possible to effectively interpolate the phase between measurements when we see these discontinuities. The safest approach is to flag the source data across these jumps. We do so here (though note that the last two flaggings are borderline cases).
For several antennas we find sudden jumps in the phase of the phase calibrator as a function of time. These are visible in the plots of uncalibrated phase vs. time for single baselines above, and we show an example in <xr id="phase_vs_time_DV09.png"/>. It will not be possible to effectively interpolate the phase between measurements when we see these discontinuities. The safest approach is to flag the source data across these jumps. We do so here (though note that the last two flaggings are borderline cases).
<figure id="phase_vs_time_DV09.png">
[[File:phase_vs_time_DV09.png|200px|thumb|right|<caption> Phase vs. time for DV09 on a problematic day. It may prove problematic to calibrate the data near this discontinuity so we flag data near this time.</caption>]]
</figure>


<source lang="python">
<source lang="python">
# In CASA
# In CASA
 
myflagdict['uid___A002_X207fe4_X3a'].append("mode='manual' antenna='DV09' timerange='21:24:09~21:35:35'")
asdm="uid___A002_X207fe4_X3a"
flagdata(vis=asdm+'.wvrtsys.ms',antenna='DV09', timerange='21:24:09~21:35:35', flagbackup = F)
 
asdm="uid___A002_X207fe4_X1f7"
flagdata(vis=asdm+'.wvrtsys.ms',antenna='DV09',timerange='23:30:52~24:10:00',flagbackup=F)
flagdata(vis=asdm+'.wvrtsys.ms',antenna='PM01',timerange='23:16:50~24:10:00',flagbackup=F)
flagdata(vis=asdm+'.wvrtsys.ms',antenna='PM03',timerange='23:16:50~24:10:00',flagbackup=F)
</source>
</source>


* '''Outliers Visible After Calibration'''
* '''Outliers Visible After Calibration'''


<figure id="amp_vs_uvdist_outliers.png">
Often issues with the data may become evident after calibration (i.e., after the next few steps that we apply). These data can appear as outliers in diagnostic plots for the calibrated data or even show up in the imaging stages. Once these are identified, best practice is to apply this new flagging then redo the calibration (if the issue is very minor, then re-calibrating may not be necessary).
[[File:amp_vs_uvdist_outliers.png|200px|thumb|right|<caption> Amplitude vs. u-v distance ''after'' calibration. Note the outlying data. We track these down using the select (box with green "+") and locate (magnifying glass) features inside plotms and identify several problematic baselines across our data. ''Note that you cannot make this plot at this point in the guide, these pathologies become evident after calibration, requiring an iterative approach to reduction.''</caption>]]
</figure>


Often issues with the data may become evident after calibration (i.e., after the next few steps that we apply). These data can appear as outliers in diagnostic plots for the calibrated data or even show up in the imaging stages. Once these are identified, best practice is to apply this new flagging then redo the calibration (if the issue is very minor, then re-calibrating may not be necessary).
<source lang="python">
# In CASA
myflagdict['uid___A002_X207fe4_X3a'].append("mode='manual' timerange='21:18:00~21:22:15'")
myflagdict['uid___A002_X2181fb_X49'].append("mode='manual' antenna='DV01&DV04'")
</source>


As before, we use {{flagcmd}} to apply our flags. Here we just apply to the first dataset. Our flags are:
<source lang="python">
<source lang="python">
# In CASA
# In CASA
asdm="uid___A002_X207fe4_X3a"
myextraflags = myflagdict['uid___A002_X1ff7b0_Xb']
flagdata(vis=asdm+'.wvrtsys.ms',timerange='21:18:00~21:22:15', flagbackup=F)
</source>
e.g.
<pre style="background-color: #fffacd;">
CASA <116>: myextraflags
  Out[116]:
["mode='manual' spw='0:0~7,0:3831~3839'",
"mode='manual' antenna='DV04'",
"mode='manual' field='Titan' uvrange='0~50'"]
</pre>


asdm="uid___A002_X2181fb_X49"
Go ahead now:
flagdata(vis=asdm+'.wvrtsys.ms',antenna='DV01&DV04', flagbackup=F)
<source lang="python">
# In CASA
flagcmd(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
        inpmode='cmd', command=myextraflags,
        action='apply', flagbackup=True)
</source>
</source>


Line 878: Line 871:
<source lang="python">
<source lang="python">
# In CASA
# In CASA
basename_all=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9",
flagmanager(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',mode='save',versionname ='User')
    "uid___A002_X2181fb_X49","uid___A002_X1ff7b0_X1c8","uid___A002_X207fe4_X1f7",
    "uid___A002_X207fe4_X4d7","uid___A002_X215db8_X18","uid___A002_X215db8_X1d5",
    "uid___A002_X215db8_X392"]
 
for asdm in basename_all:
    flagmanager(vis=asdm+'.wvrtsys.ms',mode='save',versionname ='User')
</source>
</source>


Applying this flagging will remove the most egregious pathologies from the data. We are now ready to calibrate the data.
Applying this flagging will remove the most egregious pathologies from the data. We are now ready to calibrate the data.


==Bandpass Calibration==
===Bandpass Calibration===
 
We begin by calibrating the phase and amplitude response of each antenna as a function of frequency, called "bandpass calibration." We have already seen that the data contain smooth but systematic variations in both phase and amplitude as a function of frequency. We can see this again in a more compact form by plotting phase as a function of frequency for all baselines associated with each antenna (<xr id="plotms_phase_vs_freq_example.png"/>).


<figure id="plotms_phase_vs_freq_example.png">
<figure id="plotms_phase_vs_freq_example.png">
[[File:plotms_phase_vs_freq_example.png|200px|thumb|right|<caption> Phase vs. frequency for the bandpass calibrator, 3c279 in the first data set. We plot all baselines with DV02, averaged over time, and show only the 'XX' correlation.</caption>]]
[[File:plotms_phase_vs_freq_example.png|200px|thumb|right|<caption> Phase vs. frequency for the bandpass calibrator, 3c279 in the first data set. We plot all baselines with DV02, averaged over time, and show only the 'XX' correlation.</caption>]]
</figure>
<figure id="Uid_A002_X1ff7b0_Xb-phasecont.png">
[[File:Uid_A002_X1ff7b0_Xb-phasecont.png|200px|thumb|right|<caption> Phase vs. time for the bandpass calibrator, 3c279. Averaged over channel. Only baselines with antenna DV02, and corr='XX'</caption>]]
</figure>
</figure>
<figure id="plotcal.uid___A002_X1ff7b0_Xb.bpphase.gcal.png">
[[File:plotcal.uid___A002_X1ff7b0_Xb.bpphase.gcal.png|200px|thumb|right|<caption> Short interval phase vs. time solution carried out and applied during bandpass calibration, here for the first data set. This solution removes any systematic variations in phase vs. time.</caption>]]
</figure>
<figure id="plotbandpass.uid___A002_X1ff7b0_Xb.bandpass.DV02.spw0.t1.png">
[[File:plotbandpass.uid___A002_X1ff7b0_Xb.bandpass.DV02.spw0.t1.png|200px|thumb|right|<caption> Bandpass solutions for the first set of antennas and the first data set.</caption>]]
</figure>
<figure id="plotbandpass.uid___A002_X1ff7b0_Xb.bandpass.DV09.spw0.t1.png">
[[File:plotbandpass.uid___A002_X1ff7b0_Xb.bandpass.DV09.spw0.t1.png|200px|thumb|right|<caption> Bandpass solutions for the second set of antennas and the first data set.</caption>]]
</figure>
<figure id="plotbandpass.uid___A002_X1ff7b0_Xb.bandpass.PM02.spw0.t1.png">
[[File:plotbandpass.uid___A002_X1ff7b0_Xb.bandpass.PM02.spw0.t1.png|200px|thumb|right|<caption> Bandpass solutions for the final set of antennas and the first data set.</caption>]]
</figure>
We begin by calibrating the phase and amplitude response of each antenna as a function of frequency, called "bandpass calibration." We have already seen that the data contain smooth but systematic variations in both phase and amplitude as a function of frequency. We can see this again in a more compact form by plotting phase as a function of frequency for all baselines associated with each antenna (<xr id="plotms_phase_vs_freq_example.png"/>).


<source lang="python">
<source lang="python">
# In CASA
# In CASA
basename_all=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9",
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',  
    "uid___A002_X2181fb_X49","uid___A002_X1ff7b0_X1c8","uid___A002_X207fe4_X1f7",
      xaxis='freq', yaxis='phase',  
    "uid___A002_X207fe4_X4d7","uid___A002_X215db8_X18","uid___A002_X215db8_X1d5",
      selectdata=True, field='3c279', correlation='XX',
    "uid___A002_X215db8_X392"]
      avgtime='1e8', avgscan=T, antenna='*&*',
 
      coloraxis='baseline', iteraxis='antenna')
for asdm in basename_all:
    plotms(vis= asdm+'.wvrtsys.ms',  
            xaxis='freq', yaxis='phase',  
            selectdata=True, field='3c279', correlation='XX',
            avgtime='1e8', avgscan=T, antenna='*&*',
            coloraxis='baseline', iteraxis='antenna')
    dummy_string = raw_input("Plotting phase vs. frequency for "+asdm+". Hit <Enter> for next data set or cycle through antennas [type 'stop'+<Enter> to break out].")
    # check if a stop has been requested
    if dummy_string == "stop":
        break
</source>
</source>


Line 919: Line 912:


The phase (and amplitude) also varies as a function of time, as we saw before. Here are the similar plots for phase vs. time (see <xr id="Uid_A002_X1ff7b0_Xb-phasecont.png"/>).
The phase (and amplitude) also varies as a function of time, as we saw before. Here are the similar plots for phase vs. time (see <xr id="Uid_A002_X1ff7b0_Xb-phasecont.png"/>).
<figure id="Uid_A002_X1ff7b0_Xb-phasecont.png">
[[File:Uid_A002_X1ff7b0_Xb-phasecont.png|200px|thumb|right|<caption> Phase vs. time for the bandpass calibrator, 3c279. Averaged over channel. Only baselines with antenna DV02, and corr='XX'</caption>]]
</figure>


<source lang="python">
<source lang="python">
# In CASA
# In CASA
for asdm in basename_all:
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',  
    plotms(vis= asdm+'.wvrtsys.ms',  
      xaxis='time', yaxis='phase',  
          xaxis='time', yaxis='phase',  
      selectdata=True, field='3c279',  
          selectdata=True, field='3c279',  
      spw='0:1200~1300', antenna='*&*',correlation='XX',
          spw='0:1200~1300', antenna='*&*',correlation='XX',
      avgchannel='1000',  avgscan=T,  
          avgchannel='1000',  avgscan=T,  
      coloraxis='baseline', iteraxis='antenna')
          coloraxis='baseline', iteraxis='antenna')
    dummy_string = raw_input("Plotting phase vs. time for "+asdm+". Hit <Enter> for next data set or cycle through antennas [type 'stop'+<Enter> to break out].")
    # check if a stop has been requested
    if dummy_string == "stop":
        break
</source>
</source>


Line 948: Line 932:
<source lang="python">
<source lang="python">
#In CASA
#In CASA
gaincal(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
        selectdata=T,field='3c279',spw='0:1100~1300',
        caltable='uid___A002_X1ff7b0_Xb.bpphase.gcal',
        solint='int',refant='DV11',calmode='p')
</source>


for asdm in basename_all:
We can plot these using {{plotcal}} (since DV04 is flagged we can leave it out of the plot):
    print "Running a short solution interval phase calibration for "+asdm
<source lang="python">
    os.system('rm -rf '+asdm+'.bpphase.gcal')
#In CASA
    gaincal(vis = asdm+'.wvrtsys.ms',
plotcal(caltable='uid___A002_X1ff7b0_Xb.bpphase.gcal',
              selectdata=T,field = '3c279',spw = '0:1100~1300',
        yaxis='phase',plotrange=[-1,-1,-180,180],
              caltable = asdm+'.bpphase.gcal',
        iteration='antenna',subplot=521,
              solint = 'int',refant = 'DV11',calmode='p')
        antenna='DV02,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03',
        figfile='plotcal.uid___A002_X1ff7b0_Xb.bpphase.gcal.png')
</source>
</source>
See <xr id="plotcal.uid___A002_X1ff7b0_Xb.bpphase.gcal.png"/> to the right. Phase coherence looks good!


Now we use {{bandpass}} to solve for the frequency response of each antenna. To do this, we average all data in time by setting '''solint''' to 'inf' (that is, 'infinite'). We allow combination across scans and the different field IDs found for 3c279 by setting '''combine''' to "scan,field". We apply the phase vs. time calibration that we just derived on-the-fly using the parameter "gaintable".
Now we use {{bandpass}} to solve for the frequency response of each antenna. To do this, we average all data in time by setting '''solint''' to 'inf' (that is, 'infinite'). We allow combination across scans and the different field IDs found for 3c279 by setting '''combine''' to "scan,field". We apply the phase vs. time calibration that we just derived on-the-fly using the parameter "gaintable".


<source lang="python">
<source lang="python">
for asdm in basename_all:
bandpass(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
    print "Running a bandpass calibration for "+asdm
        field='3c279',
    os.system('rm -rf '+asdm+'.bandpass.bcal')
        gaintable='uid___A002_X1ff7b0_Xb.bpphase.gcal',
    bandpass(vis = asdm+'.wvrtsys.ms',
        caltable='uid___A002_X1ff7b0_Xb.bandpass.bcal',
              field = '3c279',
        bandtype='B',
              gaintable = asdm+'.bpphase.gcal',
        solint='inf',combine='scan,field',solnorm=T,refant='DV11',
              caltable = asdm+'.bandpass.bcal',
        minblperant=3,minsnr=2,fillgaps=62)
              bandtype='B',
              solint = 'inf',combine = 'scan,field', solnorm=T,refant = 'DV11',
              minblperant=3,minsnr=2,fillgaps=62)
</source>
</source>


Line 997: Line 985:
We loop through and using analysis utils, again generating .png files of each calibration. As the bandpass plots take a while you may want to go have a cup of coffee and inspect them using your favorite image viewer. Otherwise, switch the '''interactive''' parameter to True to see them in real time instead.
We loop through and using analysis utils, again generating .png files of each calibration. As the bandpass plots take a while you may want to go have a cup of coffee and inspect them using your favorite image viewer. Otherwise, switch the '''interactive''' parameter to True to see them in real time instead.


<figure id="uid___A002_X1ff7b0_X1c8.bpphase.page1.png">
[[File:uid___A002_X1ff7b0_X1c8.bpphase.page1.png|200px|thumb|right|<caption> Short interval phase vs. time solution carried out and applied during bandpass calibration, here for the first set of antennas for the first data set. This solution removes any systematic variations in phase vs. time.</caption>]]
</figure>
<figure id="Uid___A002_X1ff7b0_X1c8.bandpass.DV02.spw0.t1.CASA3.4.png">
[[File:Uid___A002_X1ff7b0_X1c8.bandpass.DV02.spw0.t1.CASA3.4.png|200px|thumb|right|<caption> Bandpass amplitude solution for the first set of antennas and the first data set.</caption>]]
</figure>
<figure id="uid___A002_X1ff7b0_Xb.bcal_phase.page1.png">
[[File:uid___A002_X1ff7b0_Xb.bcal_phase.page1.png|200px|thumb|right|<caption> Phase vs. frequency calibration from the bandpass calibration for the first set of antennas and the first data set.</caption>]]
</figure>
<source lang="python">
<source lang="python">
#In CASA
#In CASA
basename_all=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9",
os.system('rm -rf cal_plots/uid___A002_X1ff7b0_Xb.bandpass.png')
    "uid___A002_X2181fb_X49","uid___A002_X1ff7b0_X1c8","uid___A002_X207fe4_X1f7",
au.plotbandpass2(caltable='uid___A002_X1ff7b0_Xb.bandpass.bcal',
    "uid___A002_X207fe4_X4d7","uid___A002_X215db8_X18","uid___A002_X215db8_X1d5",
                field='',xaxis='freq',yaxis='both',
    "uid___A002_X215db8_X392"]
                figfile='cal_plots/uid___A002_X1ff7b0_Xb.bandpass.png',
 
                showatm=True,interactive=False,subplot=42)
os.system('rm -rf cal_plots/*bandpass*.png')
for asdm in basename_all:
  au.plotbandpass2(caltable=asdm+'.bandpass.bcal',
                field='',xaxis='freq',yaxis='both',
                figfile='cal_plots/'+asdm+'.bandpass.png',
                showatm=True,interactive=False,subplot=42)
</source>
</source>


==Gain (Phase and Amplitude) Calibration==
You can see the plots produced by this in <xr id="plotbandpass.uid___A002_X1ff7b0_Xb.bandpass.DV02.spw0.t1.png"/>,
The bandpass calibration will account for the phase and amplitude response of our antennas as a function of frequency. We now solve for the absolute flux scale of the data by referencing to Titan and then calibrate the phase and amplitude behavior of the antennas as a function of time.
<xr id="plotbandpass.uid___A002_X1ff7b0_Xb.bandpass.DV09.spw0.t1.png"/> and  
<xr id="plotbandpass.uid___A002_X1ff7b0_Xb.bandpass.PM02.spw0.t1.png"/>.


Before using Titan to set the flux, there is an important systematic to account for. When we looked at the integrated spectra of our targets above, remember that Titan showed a whopping spectral line, in fact the same CO(3-2) line that we wish to observe in the Antennae. We will set the flux of Titan (and thus all of our data) by referencing to a model in casa that does not account for this line. Therefore we need to flag the part of the Titan observations contaminated by the line before we calibrate (you can see the affected channel range in <xr id="Antennae-TitanLine.png"/>). We run the following additional flagging step:
===Gain (Phase and Amplitude) Calibration===


<figure id="Antennae-TitanLine.png">
<figure id="Antennae-TitanLine.png">
[[File:Antennae-TitanLine.png|200px|thumb|right|<caption> Uncalibrated amplitude vs. channel plot for the flux calibrator, Titan (uid___A002_X1ff7b0_Xb dataset). Averaged over time, corr='XX', and colorized by baseline.</caption>]]
[[File:Antennae-TitanLine.png|200px|thumb|right|<caption> Uncalibrated amplitude vs. channel plot for the flux calibrator, Titan (uid___A002_X1ff7b0_Xb dataset). Averaged over time, corr='XX', and colorized by baseline.</caption>]]
</figure>
</figure>
<figure id="uid___A002_X1ff7b0_Xb.intphase.png">
[[File:uid___A002_X1ff7b0_Xb.intphase.png|200px|thumb|right|<caption>Plotcal for <tt>.intphase</tt> solutions. Note only minor sub-scan phase variations are present.</caption>]]
</figure>
<figure id="uid___A002_X1ff7b0_Xb.scanphase.png">
[[File:uid___A002_X1ff7b0_Xb.scanphase.png|200px|thumb|right|<caption>Plotcal for <tt>.scanphase</tt> solutions. This is what we will apply to our data.</caption>]]
</figure>
<figure id="uid___A002_X1ff7b0_Xb.fluxcal.amp.png">
[[File:uid___A002_X1ff7b0_Xb.fluxcal.amp.png|200px|thumb|right|<caption>Plotcal for <tt>.flux.cal/tt> solutions. These gain amplitudes have been adjusted by <tt>fluxscale</tt> to give the correct flux densities for the secondary calibrator 3C279.</caption>]]
</figure>
The bandpass calibration will account for the phase and amplitude response of our antennas as a function of frequency. We now solve for the absolute flux scale of the data by referencing to Titan and then calibrate the phase and amplitude behavior of the antennas as a function of time.
Before using Titan to set the flux, there is an important systematic to account for. When we looked at the integrated spectra of our targets above, remember that Titan showed a whopping spectral line, in fact the same CO(3-2) line that we wish to observe in the Antennae. We will set the flux of Titan (and thus all of our data) by referencing to a model in casa that does not account for this line. Therefore we need to flag the part of the Titan observations contaminated by the line before we calibrate (you can see the affected channel range in <xr id="Antennae-TitanLine.png"/>). We run the following additional flagging step (again using the new {{tflagdata}} task, which is faster than <tt>flagdata</tt> and undergoing testing this cycle):
<source lang="python">
<source lang="python">
# in CASA
# in CASA
basename_all=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9",
tflagdata(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',flagbackup=F,  
    "uid___A002_X2181fb_X49","uid___A002_X1ff7b0_X1c8","uid___A002_X207fe4_X1f7",
          field='Titan',spw='0:1100~1700',
    "uid___A002_X207fe4_X4d7","uid___A002_X215db8_X18","uid___A002_X215db8_X1d5",
          mode='manual',action='apply',savepars=True)
    "uid___A002_X215db8_X392"]


for asdm in basename_all:
flagmanager(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',mode='save',versionname='Calibration')
    print "Flagging CO(3-2) in Titan for "+asdm
    flagdata(vis=asdm+'.wvrtsys.ms',flagbackup=F,
        field=['Titan'],
        spw=['0:1100~1700'])
 
for asdm in basename_all:
  flagmanager(vis =asdm+'.wvrtsys.ms',mode = 'save',versionname = 'Calibration')
</source>
</source>


Next, we will use the {{setjy}} task to read the predicted complex visibilities for Titan into the MODEL column of each data set.
Next, we will use the {{setjy}} task to read the predicted complex visibilities for Titan into the MODEL column of each data set.
<source lang="python">
<source lang="python">
# in CASA
# in CASA
for asdm in basename_all:
setjy(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',field='Titan',
    print "Reading model for Titan into "+asdm
      usescratch=False,scalebychan=True,
    setjy(vis = asdm+'.wvrtsys.ms',field = 'Titan',
      standard='Butler-JPL-Horizons 2010')
          usescratch=False,scalebychan=True,
          standard = 'Butler-JPL-Horizons 2010')
</source>
</source>
By setting <tt>usescratch=False</tt> we are making use of the new <i>scratchless</i> mode of calibration (this mode is new, and can have problems with complicated models or MS structure, but we have only one spectral window and are not using a complicated model).


{{setjy}} will output the flux of Titan to the CASA logger and it is worth recording this information. The flux of Titan at these frequencies is about 2.9 Jy. For example, for dataset uid___A002_X1ff7b0_Xb.wvrtsys.ms:
{{setjy}} will output the flux of Titan to the CASA logger and it is worth recording this information. The flux of Titan at these frequencies is about 2.9 Jy. For example, for dataset uid___A002_X1ff7b0_Xb.wvrtsys.ms:
<pre style="background-color: #fffacd;">
<pre style="background-color: #fffacd;">
   2012-05-10 15:46:24 INFO setjy       Titan (fld ind 1) spw 0  [I=2.8614, Q=0, U=0, V=0] Jy, (JPL-Butler Solar System Object)
   INFO setjy       Titan (fld ind 1) spw 0  [I=2.8614, Q=0, U=0, V=0] Jy, (JPL-Butler Solar System Object)
</pre>
</pre>


Now we are going to take a look at the titan model for one dataset
We can use {{plotms}} to take a look at the Titan model
 
<source lang="python">
<source lang="python">
# in CASA
# in CASA
plotms(vis ='uid___A002_X1ff7b0_X1c8.wvrtsys.ms', xaxis='uvdist', yaxis='amp',
plotms(vis ='uid___A002_X1ff7b0_Xb.wvrtsys.ms', xaxis='uvdist', yaxis='amp',
ydatacolumn='model', field='Titan',avgtime='1e8',
      ydatacolumn='model', field='Titan',avgtime='1e8',
avgchannel='', avgscan=F, avgbaseline=F, coloraxis='corr')
      plotfile='plotms.uid___A002_X1ff7b0_Xb.Titan.modelamp.png')
 
#
plotms(vis ='uid___A002_X1ff7b0_X1c8.wvrtsys.ms', xaxis='uvdist', yaxis='phase',
plotms(vis ='uid___A002_X1ff7b0_Xb.wvrtsys.ms', xaxis='uvdist', yaxis='phase',
ydatacolumn='model', field='Titan',avgtime='1e8',
      ydatacolumn='model', field='Titan',avgtime='1e8')
avgchannel='', avgscan=F, avgbaseline=F, coloraxis='corr')
</source>
</source>
You can see the fall-off of the model visibilities with uv-distance (it is resolved), but the phases are zero (it is symmetric).


Next we'll run a short-solution interval {{gaincal}} to solve for phase variation on short timescales during observations of our two calibrators, with '''solint''' set to "int". By applying this on-the-fly, we can remove any decorrelation in the data due to phase scatter when we solve for the amplitude calibration. However, there is no benefit to using this short-timescale solution to calibrate the source because we only have information on the gain during calibrator visits (though see the Imaging portion of this guide). Instead we will solve for the gains to apply to the source using a longer '''solint''' in just a moment.
Next we will run a short-solution interval {{gaincal}} to solve for phase variation on short timescales during observations of our two calibrators, with '''solint''' set to "int". By applying this on-the-fly, we can remove any decorrelation in the data due to phase scatter when we solve for the amplitude calibration. However, there is no benefit to using this short-timescale solution to calibrate the source because we only have information on the gain during calibrator visits (though see the Imaging portion of this guide). Instead we will solve for the gains to apply to the source using a second run of {{gaincal}} longer '''solint'''.


First, for the calibrators using <tt>solint='int'</tt>:
<source lang="python">
<source lang="python">
# in CASA
# in CASA
basename_all=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9",
os.system('rm -rf uid___A002_X1ff7b0_Xb.intphase.gcal')
    "uid___A002_X2181fb_X49","uid___A002_X1ff7b0_X1c8","uid___A002_X207fe4_X1f7",
gaincal(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
    "uid___A002_X207fe4_X4d7","uid___A002_X215db8_X18","uid___A002_X215db8_X1d5",
        caltable='uid___A002_X1ff7b0_Xb.intphase.gcal',
    "uid___A002_X215db8_X392"]
        gaintable='uid___A002_X1ff7b0_Xb.bandpass.bcal',  
 
        calmode='p',solint='int',minsnr=2.0,minblperant=4,
for asdm in basename_all:
        field='Titan,3c279',spw='0:40~3800',refant='DV11')
    print "Carrying out short timescale phase solution for "+asdm
    os.system('rm -rf '+asdm+'.intphase.gcal')
    gaincal(vis=asdm+'.wvrtsys.ms',
                gaintable=asdm+'.bandpass.bcal',  
                caltable=asdm+'.intphase.gcal',
                calmode='p',
                field='Titan,3c279',
                spw='0:40~3800',
                refant='DV11', solint='int',minsnr=2.0, minblperant=4)
</source>
</source>
Note that we pre-apply only the bandpass solution and not the throw-away initial phase-cal.


Now we derive the longer timescale phase calibration table using '''solint''' set to "inf", but not allowing scan combination. This calibration has higher signal to noise due to combining more data, and for the purposes of correcting the source, it is just as precise as the short timescale solution.
Now we derive the longer timescale phase calibration table using <tt>solint='inf'</tt>, but not allowing scan combination (so we get a single solution per scan). This calibration has higher signal to noise due to combining more data, and for the purposes of correcting the source, it is just as precise as the short timescale solution.
 
<source lang="python">
<source lang="python">
# in CASA
# in CASA
basename_all=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9",
os.system('rm -rf uid___A002_X1ff7b0_Xb.scanphase.gcal')
    "uid___A002_X2181fb_X49","uid___A002_X1ff7b0_X1c8","uid___A002_X207fe4_X1f7",
gaincal(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
    "uid___A002_X207fe4_X4d7","uid___A002_X215db8_X18","uid___A002_X215db8_X1d5",
        caltable='uid___A002_X1ff7b0_Xb.scanphase.gcal',
    "uid___A002_X215db8_X392"]
        gaintable='uid___A002_X1ff7b0_Xb.bandpass.bcal',  
 
        calmode='p',solint='inf',minsnr=2.0,minblperant=4,
for asdm in basename_all:
        field='Titan,3c279',spw='0:40~3800',refant='DV11')
    print "Carrying out longer timescale phase solution for "+asdm
    os.system('rm -rf '+asdm+'.scanphase.gcal')
    gaincal(vis=asdm+'.wvrtsys.ms',
                gaintable=asdm+'.bandpass.bcal',  
                caltable=asdm+'.scanphase.gcal',
                calmode='p',
                field='Titan,3c279',
                spw='0:40~3800',
                refant='DV11', solint='inf',minsnr=2.0,minblperant=4)
</source>
</source>


Now we apply the short-timescale phase solution and carry out a scan length ('''solint''' set to "inf") calibration of the data using '''calmode''' of 'ap'.
Now we apply the short-timescale phase solution and carry out a scan length (<tt>solint='inf',combine=''</tt>) calibration of the data for amplitude and phase (<tt>calmode='ap'</tt>):
 
<source lang="python">
<source lang="python">
# in CASA
# in CASA
basename_all=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9",
os.system('rm -rf uid___A002_X1ff7b0_Xb.amp.cal')
    "uid___A002_X2181fb_X49","uid___A002_X1ff7b0_X1c8","uid___A002_X207fe4_X1f7",
gaincal(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
    "uid___A002_X207fe4_X4d7","uid___A002_X215db8_X18","uid___A002_X215db8_X1d5",
        caltable='uid___A002_X1ff7b0_Xb.amp.cal',
    "uid___A002_X215db8_X392"]
        gaintable=['uid___A002_X1ff7b0_Xb.bandpass.bcal',
 
                  'uid___A002_X1ff7b0_Xb.intphase.gcal'],
for asdm in basename_all:
        calmode='ap',solint='inf',minblperant=4,
    print "Solving for longer (scan) interval amplitude solution for "+asdm
        field='Titan,3c279',spw='0:40~3800',refant='DV11')
    os.system('rm -rf '+asdm+'.amp.cal')
    gaincal(vis = asdm+'.wvrtsys.ms',
              gaintable =[asdm+'.bandpass.bcal',asdm+'.intphase.gcal'],
              caltable = asdm+'.amp.cal',
              calmode='ap',
              field = 'Titan,3c279',
              spw='0:40~3800',
              refant = 'DV11',solint = 'inf', minblperant=4)
</source>
</source>
 
This "amp.cal" solution gives us the amplitude variations as a function of time, but they are not yet pinned to a realistic scale except in the case of Titan, where we have solved using the model input by {{setjy}}. We will set the flux of our secondary calibrator 3c279 with reference to Titan using {{fluxscale}}:
This "amp.cal" solution gives us the amplitude variations as a function of time, but they are not yet pinned to a realistic scale except in the case of Titan, where we have solved using the model input by {{setjy}}. We will set the flux of our secondary calibrator 3c279 with reference to Titan using {{fluxscale}}.
 
<source lang="python">
<source lang="python">
# in CASA
# in CASA
basename_all=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9",
os.system('rm -rf uid___A002_X1ff7b0_Xb.flux.cal')
    "uid___A002_X2181fb_X49","uid___A002_X1ff7b0_X1c8","uid___A002_X207fe4_X1f7",
myfluxes=fluxscale(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
    "uid___A002_X207fe4_X4d7","uid___A002_X215db8_X18","uid___A002_X215db8_X1d5",
                  caltable='uid___A002_X1ff7b0_Xb.amp.cal',
    "uid___A002_X215db8_X392"]
                  fluxtable='uid___A002_X1ff7b0_Xb.flux.cal',
 
                  reference='Titan',
for asdm in basename_all:
                  transfer='3c279')
    print "Scaling amplitude calibration to match Titan for "+asdm
    os.system('rm -rf '+asdm+'.flux.cal')
    fluxscale(vis = asdm+'.wvrtsys.ms',
                caltable = asdm+'.amp.cal',
                fluxtable = asdm+'.flux.cal',
                reference = 'Titan',
                transfer = '3c279')
</source>
</source>
where we capture the return values (the solved-for fluxes of the <tt>transfer</tt> sources) in the variable <tt>myfluxes</tt>.
<pre style="background-color: #fffacd;">
CASA <164>: myfluxes
  Out[164]:
{'0': {'fieldName': '3c279',
      'fluxd': array([ 10.42025463]),
      'fluxdErr': array([ 0.04186019]),
      'numSol': array([20], dtype=int32)},
'freq': array([  3.44845586e+11]),
'spwID': array([0], dtype=int32),
'spwName': array([''],
      dtype='|S1')}
</pre>
The new correctly-scaled flux table ".flux.cal" replaces the previous ".amp.cal" table as the correct amplitude calibration table to apply to the data, i.e., the ".flux.cal" contains both the time variability of the amplitude solved for in ".amp.cal" and the correct flux scaling set with {{fluxscale}}.


This new correctly-scaled flux table ".flux.cal" replaces the previous ".amp.cal" table as the correct amplitude calibration table to apply to the data, i.e., the ".flux.cal" contains both the time variability of the amplitude solved for in ".amp.cal" and the correct flux scaling set with {{fluxscale}}.
Fluxscale will output the derived flux for 3c279 to the CASA logger as well as to the return value. This information is worth noting. We find that the flux of 3c279 is 10.42 Jy for the first dataset. This value agrees within 10% with the most recent 0.850 millimeter measurements from the SMA calibrator list [http://sma1.sma.hawaii.edu/callist/callist.html] : (01 Jul 2011, SMA 9.75 ± 0.49).
 
Fluxscale will output the derived flux for 3c279 to the CASA logger. This information is worth noting. We find that the flux of 3c279 is 10.45 Jy, by averaging the fluxes obtained from the ten available datasets. This value agrees within 10% with the most recent 0.850 millimeter measurements from the SMA calibrator list [http://sma1.sma.hawaii.edu/callist/callist.html] : (01 Jul 2011, SMA 9.75 ± 0.49).
 
Now we plot the final phase and amplitude calibration tables for each data set. A well-behaved calibration table will show smooth variations as a function of time. Sudden jumps or wild variations among the antenna amplitude gains should prompt further investigation and possibly additional flagging.


Now we plot the final phase and amplitude calibration with {[plotms}}. A well-behaved calibration table will show smooth variations as a function of time. Sudden jumps or wild variations among the antenna amplitude gains should prompt further investigation and possibly additional flagging.
<source lang="python">
<source lang="python">
# in CASA
# in CASA
basename_all=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9",
plotcal(caltable='uid___A002_X1ff7b0_Xb.intphase.gcal',
    "uid___A002_X2181fb_X49","uid___A002_X1ff7b0_X1c8","uid___A002_X207fe4_X1f7",
        xaxis='time',yaxis='phase',
    "uid___A002_X207fe4_X4d7","uid___A002_X215db8_X18","uid___A002_X215db8_X1d5",
        antenna='DV02,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03',
    "uid___A002_X215db8_X392"]
        iteration='antenna',subplot=521,fontsize=6.0,
        plotrange=[0,0,-180,180],
        figfile='uid___A002_X1ff7b0_Xb.intphase.png')
#
plotcal(caltable='uid___A002_X1ff7b0_Xb.scanphase.gcal',
        xaxis='time',yaxis='phase',
        antenna='DV02,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03',
        iteration='antenna',subplot=521,fontsize=6.0,
        plotrange=[0,0,-180,180],
        figfile='uid___A002_X1ff7b0_Xb.scanphase.png')
#
plotcal(caltable='uid___A002_X1ff7b0_Xb.flux.cal',
        xaxis='time',yaxis='amp',
        antenna='DV02,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03',
        iteration='antenna',subplot=521,fontsize=6.0,
        figfile='uid___A002_X1ff7b0_Xb.fluxcal.amp.png')
</source>
You can see these to the right in <xr id="uid___A002_X1ff7b0_Xb.intphase.png"/>, <xr id="uid___A002_X1ff7b0_Xb.scanphase.png"/>, and <xr id="uid___A002_X1ff7b0_Xb.fluxcal.amp.png"/> respectively.


for asdm in basename_all:
=== Apply the Final Calibrations ===
    print "Plotting solutions for "+asdm
    plotcal(caltable = asdm+'.scanphase.gcal',
              xaxis = 'time', yaxis = 'phase',
              iteration = 'antenna', plotrange=[0,0,-180,180],
              showgui=False, subplot=421, figfile=asdm+'.scanphase.page1.png',
              antenna='0~7', fontsize=6.0)
    # dummy_string = raw_input("Hit <Enter> to see next plot.")
    plotcal(caltable = asdm+'.scanphase.gcal',
              xaxis = 'time', yaxis = 'phase',
              iteration = 'antenna', plotrange=[0,0,-180,180],
              showgui=False, subplot=421, figfile=asdm+'.scanphase.page2.png',
              antenna='8~15', fontsize=6.0)
    # dummy_string = raw_input("Hit <Enter> to see next plot.")
    plotcal(caltable = asdm+'.flux.cal',
              xaxis = 'time',yaxis = 'amp',
              plotrange = [0,0,0,0],
              antenna='0~7', iteration='antenna',
              showgui=False, subplot=421, figfile=asdm+'.flux.page1.png',
              fontsize=6.0)
    # dummy_string = raw_input("Hit <Enter> to see next plot.")
    plotcal(caltable = asdm+'.flux.cal',
              xaxis = 'time',yaxis = 'amp',
              plotrange = [0,0,0,0],
              antenna='8~15', iteration='antenna', fontsize=6.0,
              showgui=False, subplot=421, figfile=asdm+'.flux.page2.png')
    # dummy_string = raw_input("Hit <Enter> to see next plot.")
</source>


==Apply the Calibrations and Inspect ==
Now we will use {{applycal}} to apply the bandpass, phase, and amplitude calibration tables that we generated in the previous sections to the data. We apply the solutions separately to the bandpass and secondary ("phase") calibrator 3c279, the flux calibrator Titan, and the target source. In most data sets, the bandpass and secondary calibrator will not be the same and this step would include one additional {{applycal}}.
Now we will use {{applycal}} to apply the bandpass, phase, and amplitude calibration tables that we generated in the previous sections to the data. We apply the solutions separately to the bandpass and secondary ("phase") calibrator 3c279, the flux calibrator Titan, and the target source. In most data sets, the bandpass and secondary calibrator will not be the same and this step would include one additional {{applycal}}.


<source lang="python">
<source lang="python">
#In CASA
#In CASA
basename_north=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9","uid___A002_X2181fb_X49"]
applycal(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
        field='3c279',
for asdm in basename_north:
        gaintable=['uid___A002_X1ff7b0_Xb.bandpass.bcal',
    print "Applying calibrations for "+asdm
                    'uid___A002_X1ff7b0_Xb.intphase.gcal',
    applycal(vis=asdm+'.wvrtsys.ms',field='3c279',
                    'uid___A002_X1ff7b0_Xb.flux.cal'],
        gaintable=[asdm+'.bandpass.bcal',asdm+'.intphase.gcal',asdm+'.flux.cal'],
        interp=['nearest','nearest','nearest'],
        interp=['nearest','nearest','nearest'],
        gainfield=['3c279','3c279','3c279'],
        gainfield=['3c279','3c279','3c279'],flagbackup=F,calwt=F)
        flagbackup=False,calwt=False)
    applycal(vis=asdm+'.wvrtsys.ms',field='Titan',
#
        gaintable=[asdm+'.bandpass.bcal',asdm+'.intphase.gcal',asdm+'.flux.cal'],
applycal(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
        interp=['nearest','nearest','nearest'],
        field='Titan',
        gainfield=['3c279','Titan','Titan'],flagbackup=F,calwt=F)
        gaintable=['uid___A002_X1ff7b0_Xb.bandpass.bcal',
    applycal(vis=asdm+'.wvrtsys.ms',field='NGC*',
                    'uid___A002_X1ff7b0_Xb.intphase.gcal',
        interp=['nearest','linear','linear'],
                    'uid___A002_X1ff7b0_Xb.flux.cal'],
        gaintable=[asdm+'.bandpass.bcal',asdm+'.scanphase.gcal',asdm+'.flux.cal'],
        interp=['nearest','nearest','nearest'],
        gainfield=['3c279','3c279','3c279'],flagbackup=F,calwt=F)
        gainfield=['3c279','Titan','Titan'],
 
        flagbackup=False,calwt=False)
basename_south=["uid___A002_X1ff7b0_X1c8","uid___A002_X207fe4_X1f7","uid___A002_X207fe4_X4d7",
#
                          "uid___A002_X215db8_X18","uid___A002_X215db8_X1d5","uid___A002_X215db8_X392"]
applycal(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
        field='NGC*',
for asdm in basename_south:
        gaintable=['uid___A002_X1ff7b0_Xb.bandpass.bcal',
    print "Applying calibrations for "+asdm
                    'uid___A002_X1ff7b0_Xb.scanphase.gcal',
    applycal(vis=asdm+'.wvrtsys.ms',field='3c279',
                    'uid___A002_X1ff7b0_Xb.flux.cal'],
        gaintable=[asdm+'.bandpass.bcal',asdm+'.intphase.gcal',asdm+'.flux.cal'],
        interp=['nearest','linear','linear'],
        interp=['nearest','nearest','nearest'],
        gainfield=['3c279','3c279','3c279'],
        gainfield=['3c279','3c279','3c279'],flagbackup=F,calwt=F)
        flagbackup=False,calwt=False)
    applycal(vis=asdm+'.wvrtsys.ms',field='Titan',
        gaintable=[asdm+'.bandpass.bcal',asdm+'.intphase.gcal',asdm+'.flux.cal'],
        interp=['nearest','nearest','nearest'],
        gainfield=['3c279','Titan','Titan'],flagbackup=F,calwt=F)
    applycal(vis=asdm+'.wvrtsys.ms',field='Ant*',
        interp=['nearest','linear','linear'],
        gaintable=[asdm+'.bandpass.bcal',asdm+'.scanphase.gcal',asdm+'.flux.cal'],
        gainfield=['3c279','3c279','3c279'],flagbackup=F,calwt=F)
</source>
</source>


Line 1,248: Line 1,180:
* '''calwt''' indicates that the weights, which were derived from the Tsys measurements, should also be calibrated. Note that '''calwt''' is True by default.
* '''calwt''' indicates that the weights, which were derived from the Tsys measurements, should also be calibrated. Note that '''calwt''' is True by default.


Once calibrations are applied, it is important to go back and inspect the calibrated data. New problematic antennas or baselines may be visible after calibration. Repeat the steps above, focusing on the CORRECTED data column. Bear in mind that for any point source calibrators we now expect to find phase scattering around zero and to find flat amplitudes as a function of u-v distance. Look for outliers and other signatures of problematic data. As a general rule, you will want to incorporate these data into your overall flagging script then rerun the whole calibration process, so that reduction is iterative. If the data only represent a minor problem, however, it may not be terribly harmful to flag them after the fact so that they do not interfere with imaging but trust that the calibrations are mostly unaffected.
=== Final Data Inspection ===


As an example of this inspection, we cycle through the corrected amplitudes and phases of 3c279 and Titan as a function u-v distance, to check that the phases are close to zero and the amplitudes are constant.  
<figure id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.timeamp.png">
[[File:plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.timeamp.png|200px|thumb|right|<caption> Calibrated amplitude vs. time plot for 3c279 colored by baseline. Note residual baseline-based offsets. </caption>]]
</figure>


<figure id="xb-checkcal-pha-cha.png">
<figure id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.chanphase.png">
[[File:xb-checkcal-pha-cha.png|200px|thumb|right|<caption> Calibrated phase vs. channel plot for 3c279 (uid___A002_X1ff7b0_Xb dataset). </caption>]]
[[File:plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.chanphase.png|200px|thumb|right|<caption> Calibrated phase vs. channel plot for 3c279 colored by baseline. </caption>]]
</figure>
</figure>
<figure id="xb-checkcal-amp-time.png">
 
[[File:xb-checkcal-amp-time.png|200px|thumb|right|<caption> Calibrated amplitude vs. time plot for 3c279 (uid___A002_X1ff7b0_Xb dataset). </caption>]]
<figure id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.baseavg.ampfreq.png">
[[File:plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.baseavg.ampfreq.png|200px|thumb|right|<caption> Calibrated amplitude vs. frequency averaged over all baselines and times. Our average calibration is good. </caption>]]
</figure>
</figure>
<source lang="python">
# In CASA


basename_all=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9",
<figure id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.Antennae.ampfreq.png">
    "uid___A002_X2181fb_X49","uid___A002_X1ff7b0_X1c8","uid___A002_X207fe4_X1f7",
[[File:plotms.uid___A002_X1ff7b0_Xb.wvrtsys.Antennae.ampfreq.png|200px|thumb|right|<caption> Calibrated amplitude vs. frequency for the Antennae, clearly showing our CO(3-2) line. </caption>]]
    "uid___A002_X207fe4_X4d7","uid___A002_X215db8_X18","uid___A002_X215db8_X1d5",
</figure>
    "uid___A002_X215db8_X392"]
for asdm in basename_all:
    print "Examining calibrated data for "+asdm
    plotms(vis = asdm+'.wvrtsys.ms', xaxis='uvdist', yaxis='amp',
ydatacolumn='corrected', field='3c279',
averagedata=True, avgchannel='3840', avgtime='',
avgscan=F, avgbaseline=F, coloraxis='corr')
    dummy_string = raw_input("Hit <Enter> for next plot.")
    plotms(vis = asdm+'.wvrtsys.ms', xaxis='time', yaxis='amp',
ydatacolumn='corrected', field='3c279',
averagedata=True, avgchannel='3840', avgtime='',
avgscan=F, avgbaseline=F, coloraxis='corr')
    dummy_string = raw_input("Hit <Enter> for next plot.")
    plotms(vis = asdm+'.wvrtsys.ms', xaxis='freq', yaxis='amp',
ydatacolumn='corrected', field='3c279',avgtime='1e8',
avgchannel='', avgscan=F, avgbaseline=F, coloraxis='corr')
    dummy_string = raw_input("Hit <Enter> for next plot.")
    plotms(vis = asdm+'.wvrtsys.ms', xaxis='time', yaxis='phase',
ydatacolumn='corrected', field='3c279',
avgchannel='3840', avgscan=F, avgbaseline=F, coloraxis='corr')
    dummy_string = raw_input("Hit <Enter> for next plot [type 'stop'+<Enter> to break out].")
    # check if a stop has been requested
    if dummy_string == "stop":
        break


Once calibrations are applied, it is important to go back and inspect the calibrated data. New problematic antennas or baselines may be visible after calibration. Repeat the steps above, focusing on the CORRECTED data column. Bear in mind that for any point source calibrators we now expect to find phase scattering around zero and to find flat amplitudes as a function of u-v distance. Look for outliers and other signatures of problematic data. As a general rule, you will want to incorporate these data into your overall flagging script then rerun the whole calibration process, so that reduction is iterative. If the data only represent a minor problem, however, it may not be terribly harmful to flag them after the fact so that they do not interfere with imaging but trust that the calibrations are mostly unaffected.


for asdm in basename_all:
As an example of this inspection, we cycle through the corrected amplitudes and phases of 3c279 and Titan as a function u-v distance, to check that the phases are close to zero and the amplitudes are constant.
    print "Examining calibrated data for "+asdm
<source lang="python">
    plotms(vis = asdm+'.wvrtsys.ms', xaxis='uvdist', yaxis='amp',
# In CASA
ydatacolumn='corrected', field='Titan',
# First 3C279
averagedata=True, avgchannel='3840', avgtime='',
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
avgscan=F, avgbaseline=F, coloraxis='corr')
      xaxis='uvdist', yaxis='amp',  
    dummy_string = raw_input("Hit <Enter> for next plot.")
      ydatacolumn='corrected', field='3c279',
    plotms(vis = asdm+'.wvrtsys.ms', xaxis='uvdist', yaxis='phase',
      averagedata=True, avgchannel='3840', avgtime='',
ydatacolumn='corrected', field='Titan',
      avgscan=F, avgbaseline=F, coloraxis='baseline')
averagedata=True, avgchannel='3840', avgtime='',
#
avgscan=F, avgbaseline=F, coloraxis='corr')
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
    dummy_string = raw_input("Hit <Enter> for next plot.")
      xaxis='time', yaxis='amp',
    plotms(vis = asdm+'.wvrtsys.ms', xaxis='freq', yaxis='amp',
      ydatacolumn='corrected', field='3c279',
ydatacolumn='corrected', field='Titan',avgtime='1e8',
      averagedata=True, avgchannel='3840', avgtime='',
avgchannel='', avgscan=F, avgbaseline=F, coloraxis='corr')
      avgscan=F, avgbaseline=F, coloraxis='baseline',
    dummy_string = raw_input("Hit <Enter> for next plot [type 'stop'+<Enter> to break out].")
      plotfile='plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.timeamp.png')
    # check if a stop has been requested
#
    if dummy_string == "stop":
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
        break
      xaxis='freq', yaxis='amp',
      ydatacolumn='corrected', field='3c279',avgtime='1e8',
      avgchannel='', avgscan=F, avgbaseline=F, coloraxis='baseline')
#
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
      xaxis='channel', yaxis='phase',
      ydatacolumn='corrected', field='3c279',avgtime='1e8',
      avgchannel='', avgscan=F, avgbaseline=F, coloraxis='baseline',
      plotfile='plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.chanphase.png')
#
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
      xaxis='time', yaxis='phase',
      ydatacolumn='corrected', field='3c279',
      avgchannel='3840', avgscan=F, avgbaseline=F, coloraxis='baseline')
#
# And now Titan
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
      xaxis='uvdist', yaxis='amp',
      ydatacolumn='corrected', field='Titan',
      averagedata=True, avgchannel='3840', avgtime='',
      avgscan=F, avgbaseline=F, coloraxis='baseline')
#
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
      xaxis='uvdist', yaxis='phase',
      ydatacolumn='corrected', field='Titan',
      averagedata=True, avgchannel='3840', avgtime='',
      avgscan=F, avgbaseline=F, coloraxis='baseline')
#
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
      xaxis='freq', yaxis='amp',
      ydatacolumn='corrected', field='Titan',avgtime='1e8',
      avgchannel='', avgscan=F, avgbaseline=F, coloraxis='baseline')
</source>
</source>
In <xr id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.timeamp.png"/> and <xr id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.chanphase.png"/> we show the amp vs. time and phase vs. channel plots for 3c279 for the uid___A002_X1ff7b0_Xb dataset, colored by baseline.  These are generally well-calibrated (especially in phase) but there are still some minor residual baseline-based amplitude offsets.


In <xr id="xb-checkcal-pha-cha.png"/> and <xr id="xb-checkcal-amp-time.png"/> we plot phase vs. channel and amp vs. time for 3c279 for the uid___A002_X1ff7b0_Xb dataset.  
We can plot the data averaged over baselines to show our mean calibration is good.
 
<source lang="python">
Finally we can use {{plotms}} to examine the corrected amplitude and phase of Antennae galaxies as a function of time and uv-distance (plots not shown):
# In CASA
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
      xaxis='freq', yaxis='amp',
      ydatacolumn='corrected', field='3c279',avgtime='1e8',
      avgchannel='', avgscan=F, avgbaseline=T,
      coloraxis='corr',
      plotfile='plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.baseavg.ampfreq.png')
#
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
      xaxis='freq', yaxis='amp',
      ydatacolumn='corrected', field='Titan',avgtime='1e8',
      avgchannel='', avgscan=F, avgbaseline=T,
      coloraxis='corr')
</source>
The first of these is shown in <xr id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.baseavg.ampfreq.png"/>


Finally we can use {{plotms}} to examine the corrected amplitude and phase of Antennae galaxies as a function of time and uv-distance:
<source lang="python">
<source lang="python">
# In CASA
# In CASA
basename_north=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9","uid___A002_X2181fb_X49"]
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
for asdm in basename_north:
      xaxis='uvdist', yaxis='amp',
    print "Examining calibrated data for "+asdm
      ydatacolumn='corrected', field='NGC*',
    plotms(vis = asdm+'.wvrtsys.ms', xaxis='uvdist', yaxis='amp',
      averagedata=True, avgchannel='3840', avgtime='',
ydatacolumn='corrected', field='NGC*',
      avgscan=F, avgbaseline=F, coloraxis='baseline')
averagedata=True, avgchannel='3840', avgtime='',
#
avgscan=F, avgbaseline=F, coloraxis='corr')
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
    dummy_string = raw_input("Hit <Enter> for next plot.")
      xaxis='freq', yaxis='amp',
    plotms(vis = asdm+'.wvrtsys.ms', xaxis='freq', yaxis='amp',
      ydatacolumn='corrected', field='NGC*',
ydatacolumn='corrected', field='NGC*',
      avgtime='1e8', avgscan=T, avgbaseline=F,
avgtime='1e8', avgscan=T, avgbaseline=F, coloraxis='corr')
      coloraxis='baseline',
    dummy_string = raw_input("Hit <Enter> for next plot.")
      plotfile='plotms.uid___A002_X1ff7b0_Xb.wvrtsys.Antennae.ampfreq.png')
 
basename_south=["uid___A002_X1ff7b0_X1c8","uid___A002_X207fe4_X1f7","uid___A002_X207fe4_X4d7",
                          "uid___A002_X215db8_X18","uid___A002_X215db8_X1d5","uid___A002_X215db8_X392"]
for asdm in basename_south:
    print "Examining calibrated data for "+asdm
    plotms(vis = asdm+'.wvrtsys.ms', xaxis='uvdist', yaxis='amp',
ydatacolumn='corrected', field='Ant*',
averagedata=True, avgchannel='3840', avgtime='',
avgscan=F, avgbaseline=F, coloraxis='corr')
    dummy_string = raw_input("Hit <Enter> for next plot.")
    plotms(vis = asdm+'.wvrtsys.ms', xaxis='freq', yaxis='amp',
ydatacolumn='corrected', field='Ant*',
avgtime='1e8', avgscan=T,avgbaseline=F, coloraxis='corr')
    dummy_string = raw_input("Hit <Enter> for next plot.")
</source>
</source>
The last of these is shown in <xr id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.Antennae.ampfreq.png"/>.


==Processing the other Northern Mosaic datasets==
==Processing the other Northern Mosaic datasets==
In order to proceed to produce a final concatenated dataset, we need to process the remainder of the Antennae North blocks.  If you do not have the time (around 30min, possibly more) or inclination, you can proceed directly to the [[AntennaeBand7 North Imaging 3.4]] guide and start with an already processed and merged MS.  Or follow the instructions in this session (and the next) to create your own.


We first define a Python list containing the base names for the other Northern Mosaic datasets:
We first define a Python list containing the base names for the other Northern Mosaic datasets:
Line 1,353: Line 1,298:
basename_north_ext=["uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9","uid___A002_X2181fb_X49"]
basename_north_ext=["uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9","uid___A002_X2181fb_X49"]
</source>
</source>
This will be used to loop over all the operations on these MSes.
This will be used to loop over all the operations on these MSes, for example:
 
<source lang="python">
<source lang="python">
# In CASA
# In CASA
for asdm in basename_north_ext:
for asdm in basename_north_ext:
     os.system('rm '+asdm+'.listobs.txt')
     print 'asdm = '+asdm
    listobs(vis=asdm+'.ms', listfile=asdm+'.listobs.txt', verbose=True)
</source>
</source>


Note that after cutting and pasting a 'for' loop like this you often have to press return twice to execute. You may also want to take care to paste a line at a time if you are having trouble copy and pasting. Even better, you can use "cpaste" to paste blocks of code. To do so type "cpaste" at the CASA prompt, paste your commands, and then type "--" and hit return on the final (otherwise empty) line. This should look something like this:
Note that after cutting and pasting a 'for' loop like this you often have to press return twice to execute. You may also want to take care to paste a line at a time if you are having trouble copy and pasting. Even better, you can use "cpaste" to paste blocks of code. To do so type "cpaste" at the CASA prompt, paste your commands, and then type "--" and hit return on the final (otherwise empty) line. This should look something like this:
<pre style="background-color: #fffacd;">
<pre style="background-color: #fffacd;">


Line 1,382: Line 1,324:


</pre>
</pre>
cpaste should be ''much'' more robust than copying-and-pasting directly into the shell but if you have trouble, just carefully paste one line at a time directly into CASA and hit return until the desired command executes.


cpaste should be ''much'' more robust than copying-and-pasting directly into the shell but if you have trouble, just carefully paste one line at a time directly into CASA and hit return until the desired command executes.
We will break the commands we loop over into two, one loop (mandatory) for operations that do something, and a second (optional) that make plots or listings to look over.


Now we set up some variables and lists (analogous to what we did before manually)
<source lang="python">
<source lang="python">
#In CASA
#In CASA
for asdm in basename_north_ext:
basename_north_ext=["uid___A002_X207fe4_X3a",
    os.system('rm -rf '+asdm+'.tdm.tsys')
                    "uid___A002_X207fe4_X3b9",
    print "Creating TDM Tsys Table for "+asdm
                    "uid___A002_X2181fb_X49"]
    gencal(vis=asdm+'.ms',caltable=asdm+'.tdm.tsys',spw='5,7',caltype='tsys')
    #
    print "Plotting Tsys vs. time for "+asdm
    plotcal(caltable=asdm+'.tdm.tsys',
    xaxis="time",yaxis="tsys",
    spw='5:50~50',plotsymbol=".", subplot=421,
    antenna='0~7',
    iteration='antenna', figfile=asdm+'.tsys_vs_time.page1.png',
    fontsize=7.0)   
    #dummy_string = raw_input("First eight antennas for "+asdm+" . Hit <Enter> to continue.")
    plotcal(caltable=asdm+'.tdm.tsys',
    xaxis="time",yaxis="tsys",
    antenna='8~15',
    spw='5:50~50',plotsymbol=".", subplot=421,
    iteration='antenna', figfile=asdm+'.tsys_vs_time.page2.png',
    fontsize=7.0)   
    #dummy_string = raw_input("Remaining antennas for "+asdm+" . Hit <Enter> to continue.")
</source>
</source>


Next, this loop takes us from the split a-priori calibrated data through to just before final splitting:
<source lang="python">
<source lang="python">
#In CASA
#In CASA
for asdm in basename_north_ext:
for asdm in basename_north_ext:
  os.system('rm -rf cal_plots/Tsys_plots/'+asdm+'.tdm.tsys*')
    #
  tsysfields=['3c279','Titan','Antennae']
    print "Apply extra flags to "+asdm
  caltable=asdm+'.tdm.tsys'
    myextraflags = myflagdict[asdm]
  for field in tsysfields:
    flagcmd(vis=asdm+'.wvrtsys.ms',
     au.plotbandpass2(caltable=caltable,yaxis='amp',field=field,xaxis='freq',
            inpmode='cmd', command=myextraflags,
                showatm=True,overlay='time',
            action='apply', flagbackup=True)
                figfile='cal_plots/Tsys_plots/'+caltable+'.'+field,buildpdf=False,
    #
                interactive=False,chanrange='8~120',subplot=42)
    print "Saving flags for "+asdm
    flagmanager(vis=asdm+'.wvrtsys.ms',mode='save',versionname ='User')
    #
    print "Running a short solution interval phase calibration for "+asdm
    os.system('rm -rf '+asdm+'.bpphase.gcal')
    gaincal(vis = asdm+'.wvrtsys.ms',
            selectdata=T,field = '3c279',spw = '0:1100~1300',
            caltable = asdm+'.bpphase.gcal',
            solint = 'int',refant = 'DV11',calmode='p')
    #
    print "Running a bandpass calibration for "+asdm
    os.system('rm -rf '+asdm+'.bandpass.bcal')
    bandpass(vis=asdm+'.wvrtsys.ms',
            field = '3c279',
            gaintable = asdm+'.bpphase.gcal',
            caltable = asdm+'.bandpass.bcal',
            bandtype='B',
            solint = 'inf',combine = 'scan,field', solnorm=T,refant = 'DV11',
            minblperant=3,minsnr=2,fillgaps=62)
    #
    print "Flagging CO(3-2) in Titan for "+asdm
    tflagdata(vis=asdm+'.wvrtsys.ms',flagbackup=F,
              field='Titan',spw='0:1100~1700',
              mode='manual',action='apply',savepars=True)
    print "Saving Titan channel flags for "+asdm
    flagmanager(vis=asdm+'.wvrtsys.ms',mode='save',versionname='Calibration')
    #
    print "Reading model for Titan into "+asdm
    setjy(vis=asdm+'.wvrtsys.ms',field='Titan',
          usescratch=False,scalebychan=True,
          standard='Butler-JPL-Horizons 2010')
     #
    print "Carrying out short timescale phase solution for "+asdm
    os.system('rm -rf '+asdm+'.intphase.gcal')
    gaincal(vis=asdm+'.wvrtsys.ms',
            caltable=asdm+'.intphase.gcal',
            gaintable=asdm+'.bandpass.bcal',
            calmode='p',solint='int',minsnr=2.0,minblperant=4,
            field='Titan,3c279',spw='0:40~3800',
            refant='DV11')
    #
    print "Carrying out longer timescale phase solution for "+asdm
    os.system('rm -rf '+asdm+'.scanphase.gcal')
    gaincal(vis=asdm+'.wvrtsys.ms',
            caltable=asdm+'.scanphase.gcal',
            gaintable=asdm+'.bandpass.bcal',
            calmode='p',solint='inf',minsnr=2.0,minblperant=4,
            field='Titan,3c279',spw='0:40~3800',refant='DV11')
    #
    print "Solving for longer (scan) interval amplitude solution for "+asdm
    os.system('rm -rf '+asdm+'.amp.cal')
    gaincal(vis=asdm+'.wvrtsys.ms',
            gaintable=[asdm+'.bandpass.bcal',asdm+'.intphase.gcal'],
            caltable=asdm+'.amp.cal',
            calmode='ap',solint='inf',minblperant=4,
            field='Titan,3c279',spw='0:40~3800',refant='DV11')
    #
    print "Scaling amplitude calibration to match Titan for "+asdm
    os.system('rm -rf '+asdm+'.flux.cal')
    fluxscale(vis=asdm+'.wvrtsys.ms',
              caltable=asdm+'.amp.cal',
              fluxtable=asdm+'.flux.cal',
              reference='Titan',
              transfer='3c279')
    #
    print "Applying calibrations for "+asdm
    applycal(vis=asdm+'.wvrtsys.ms',field='3c279',
            gaintable=[asdm+'.bandpass.bcal',
                        asdm+'.intphase.gcal',
                        asdm+'.flux.cal'],
            interp=['nearest','nearest','nearest'],
            gainfield=['3c279','3c279','3c279'],
            flagbackup=False,calwt=False)
    #
    applycal(vis=asdm+'.wvrtsys.ms',field='Titan',
            gaintable=[asdm+'.bandpass.bcal',
                        asdm+'.intphase.gcal',
                        asdm+'.flux.cal'],
            interp=['nearest','nearest','nearest'],
            gainfield=['3c279','Titan','Titan'],
            flagbackup=False,calwt=False)
    #
    applycal(vis=asdm+'.wvrtsys.ms',field='NGC*',
            gaintable=[asdm+'.bandpass.bcal',
                        asdm+'.scanphase.gcal',
                        asdm+'.flux.cal'],
            interp=['nearest','linear','linear'],
            gainfield=['3c279','3c279','3c279'],
            flagbackup=False,calwt=False)
</source>
</source>


=== Optional Plotting and Listing Loop ===
If you want to make the plots and listings we did for the first dataset in our walkthrough, then use <tt>cpaste</tt> to execute the following loop:
<source lang="python">
<source lang="python">
#In CASA
#In CASA
#Removing existing WVR information
for asdm in basename_north_ext:
for asdm in basename_north_ext:
     os.system('rm -rf '+asdm+.wvrgcal')
     os.system('rm '+asdm+'.listobs.txt')
     wvrgcal(vis=asdm+'.ms',caltable=asdm+'.wvrgcal',toffset=-1)
     listobs(vis=asdm+'.ms', listfile=asdm+'.listobs.txt', verbose=True)
</source>
    #
 
    print "Antenna configuration for : "+asdm
<source lang="python">
    os.system('rm '+asdm+'.plotants.png')
#In CASA
    plotants(vis=asdm+'.ms', figfile=asdm+'.plotants.png')
#The measurement set we are refining the antenna positions for
    clearstat()
data='uid___A002_X207fe4_X3a.ms'
    #
#Removing existing antenna refinements
    print "Plotting Tsys vs. time for "+asdm
os.system('rm -rf '+data[0:22]+'.antpos')
    os.system('rm '+asdm+'.tsys_vs_time.page1.png')
antenna='DV02,DV04,DV05,DV06,DV07,DV08,DV09,DV10,DV11,DV12,PM01,PM03'
    plotcal(caltable=asdm+'.tdm.tsys',  
parameter = [
    xaxis="time",yaxis="tsys",
0.00000, 0.00000, 0.00000, #DV02-A015
    spw='5:50~50',plotsymbol=".", subplot=421,
-0.00004, 0.00059, 0.00024, #DV04-J505
    antenna='0~7',iteration='antenna',
-0.00019,-0.00003, 0.00035, #DV05-A067
            showgui=False,figfile=asdm+'.tsys_vs_time.page1.png',
-0.00027, 0.00033, 0.00022, #DV06-T704
    fontsize=7.0)   
0.00006, 0.00057, 0.00032, #DV07-A004
    #
-0.00027, 0.00025,-0.00003, #DV08-A072
    os.system('rm '+asdm+'.tsys_vs_time.page2.png')
-0.00037, 0.00025, 0.00003, #DV09-A008
    plotcal(caltable=asdm+'.tdm.tsys',  
-0.00056, 0.00028, 0.00026, #DV10-A009
    xaxis="time",yaxis="tsys",
-0.00028, 0.00024, 0.00011, #DV11-A016
    spw='5:50~50',plotsymbol=".", subplot=421,  
-0.00018, 0.00010,-0.00014, #DV12-A011
    antenna='8~15', iteration='antenna',  
-0.00017, 0.00013, 0.00030, #PM01-T702
    showgui=False,figfile=asdm+'.tsys_vs_time.page2.png',
-0.00007, 0.00034, -0.00004] #PM03-J504
    fontsize=7.0)
gencal(vis=data,caltable='%s.antpos'%(data.split('.')[0]),caltype='antpos',
    #
      antenna=antenna,parameter=parameter)
    tsysfields=['3c279','Titan','NGC4038*']
 
    os.system('rm -rf cal_plots/Tsys_plots/'+asdm+'.tdm.tsys*')
#In CASA
    caltable=asdm+'.tdm.tsys'
#The measurement set we are refining the antenna positions for
    for field in tsysfields:
data='uid___A002_X207fe4_X3b9.ms'
        au.plotbandpass2(caltable=caltable,yaxis='amp',field=field,xaxis='freq',
#Removing existing antenna refinements
                        showatm=True,overlay='time',
os.system('rm -rf '+data[0:23]+'.antpos')
                        figfile='cal_plots/Tsys_plots/'+caltable+'.'+field,buildpdf=False,
antenna='DV02,DV04,DV05,DV06,DV07,DV08,DV09,DV10,DV11,DV12,PM01,PM03'
                        interactive=False,chanrange='8~120',subplot=42)
parameter = [
    #
0.00000, 0.00000, 0.00000, #DV02-A015
    os.system('rm '+asdm+'.wvrtsys.listobs.txt')
-0.00004, 0.00059, 0.00024, #DV04-J505
    listobs(vis=asdm+'.wvrtsys.ms', listfile=asdm+'.wvrtsys.listobs.txt', verbose=True)
-0.00019,-0.00003, 0.00035, #DV05-A067
    #
-0.00027, 0.00033, 0.00022, #DV06-T704
    os.system('rm -rf cal_plots/'+asdm+'.bandpass.png')
0.00006, 0.00057, 0.00032, #DV07-A004
    au.plotbandpass2(caltable=asdm+'.bandpass.bcal',
-0.00027, 0.00025,-0.00003, #DV08-A072
                    field='',xaxis='freq',yaxis='both',
-0.00037, 0.00025, 0.00003, #DV09-A008
                    figfile='cal_plots/'+asdm+'.bandpass.png',
-0.00056, 0.00028, 0.00026, #DV10-A009
                    showatm=True,interactive=False,subplot=42)
-0.00028, 0.00024, 0.00011, #DV11-A016
    #
-0.00018, 0.00010,-0.00014, #DV12-A011
    print "Plotting solutions for "+asdm
-0.00017, 0.00013, 0.00030, #PM01-T702
    os.system('rm '+asdm+'.intphase.png')
-0.00007, 0.00034, -0.00004] #PM03-J504
    plotcal(caltable=asdm+'.intphase.gcal',
gencal(vis=data,caltable='%s.antpos'%(data.split('.')[0]),caltype='antpos',
            xaxis='time',yaxis='phase',
      antenna=antenna,parameter=parameter)
            antenna='DV02,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03',
#In CASA
            iteration='antenna',subplot=521,fontsize=6.0,
#The measurement set we are refining the antenna positions for
            plotrange=[0,0,-180,180],showgui=False,
data='uid___A002_X2181fb_X49.ms'
            figfile=asdm+'.intphase.png')
#Removing existing antenna refinements
    #
os.system('rm -rf '+data[0:22]+'.antpos')
    os.system('rm '+asdm+'.scanphase.png')
antenna='DV01,DV02,DV04,DV05,DV06,DV07,DV08,DV09,DV10,DV11,DV12,DV13,PM01,PM03'
    plotcal(caltable=asdm+'.scanphase.gcal',
parameter = [
            xaxis='time',yaxis='phase',
-0.00004, 0.00026, 0.00019, #DV01-A137
            antenna='DV02,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03',
0.00000, 0.00000, 0.00000, #DV02-A015
            iteration='antenna',subplot=521,fontsize=6.0,
-0.00004, 0.00059, 0.00024, #DV04-J505
            plotrange=[0,0,-180,180],showgui=False,
-0.00019,-0.00003, 0.00035, #DV05-A067
            figfile=asdm+'.scanphase.png')
-0.00027, 0.00033, 0.00022, #DV06-T704
    #
0.00006, 0.00057, 0.00032, #DV07-A004
    os.system('rm '+asdm+'.fluxcal.amp.png')
-0.00027, 0.00025,-0.00003, #DV08-A072
    plotcal(caltable=asdm+'.flux.cal',
-0.00037, 0.00025, 0.00003, #DV09-A008
            xaxis='time',yaxis='amp',
-0.00056, 0.00028, 0.00026, #DV10-A009
            antenna='DV02,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03',
-0.00028, 0.00024, 0.00011, #DV11-A016
            iteration='antenna',subplot=521,fontsize=6.0,showgui=False,
-0.00018, 0.00010,-0.00014, #DV12-A011
            figfile=asdm+'.fluxcal.amp.png')
0.00009, 0.00033, 0.00023, #DV13-A075
    #
-0.00017, 0.00013, 0.00030, #PM01-T702
    # Final plotms
-0.00007, 0.00034, -0.00004] #PM03-J504
    print "Plotting final calibrated data for "+asdm
gencal(vis=data,caltable='%s.antpos'%(data.split('.')[0]),caltype='antpos',
    os.system('rm plotms.'+asdm+'.wvrtsys.3c279.timeamp.png')
      antenna=antenna,parameter=parameter)
    plotms(vis=asdm+'.wvrtsys.ms',
 
          xaxis='time', yaxis='amp',
#In CASA
          ydatacolumn='corrected', field='3c279',
#The measurement set we are refining the antenna positions for
          averagedata=True, avgchannel='3840', avgtime='',
data='uid___A002_X1ff7b0_X1c8.ms'
          avgscan=F, avgbaseline=F, coloraxis='baseline',
#Removing existing antenna refinements
          plotfile='plotms.'+asdm+'.wvrtsys.3c279.timeamp.png')
os.system('rm -rf '+data[0:23]+'.antpos')
    #
antenna='DV02,DV04,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03'
    os.system('rm plotms.'+asdm+'.wvrtsys.3c279.chanphase.png')
parameter = [
    plotms(vis=asdm+'.wvrtsys.ms',
0.00000, 0.00000, 0.00000, #DV02-A015
          xaxis='channel', yaxis='phase',
-0.00004, 0.00059, 0.00024, #DV04-J505
          ydatacolumn='corrected', field='3c279',avgtime='1e8',
-0.00027, 0.00033, 0.00022, #DV06-T704
          avgchannel='', avgscan=F, avgbaseline=F, coloraxis='baseline',
0.00006, 0.00057, 0.00032, #DV07-A004
          plotfile='plotms.'+asdm+'.wvrtsys.3c279.chanphase.png')
-0.00027, 0.00025,-0.00003, #DV08-A072
    #
-0.00037, 0.00025, 0.00003, #DV09-A008
    os.system('rm plotms.'+asdm+'.wvrtsys.3c279.baseavg.ampfreq.png')
-0.00056, 0.00028, 0.00026, #DV10-A009
    plotms(vis=asdm+'.wvrtsys.ms',
-0.00028, 0.00024, 0.00011, #DV11-A016
          xaxis='freq', yaxis='amp',
-0.00017, 0.00013, 0.00030, #PM01-T702
          ydatacolumn='corrected', field='3c279',avgtime='1e8',
-0.00034, 0.00092, 0.00027, #PM02-A017 Before July 1
          avgchannel='', avgscan=F, avgbaseline=T,
-0.00007, 0.00034, -0.00004] #PM03-J504
          coloraxis='corr',
gencal(vis=data,caltable='%s.antpos'%(data.split('.')[0]),caltype='antpos',
          plotfile='plotms.'+asdm+'.wvrtsys.3c279.baseavg.ampfreq.png')
      antenna=antenna,parameter=parameter)
    #
 
    os.system('rm plotms.'+asdm+'.wvrtsys.Titan.baseavg.ampfreq.png')
#In CASA
    plotms(vis=asdm+'.wvrtsys.ms',
#The measurement set we are refining the antenna positions for
          xaxis='freq', yaxis='amp',
data='uid___A002_X207fe4_X1f7.ms'
          ydatacolumn='corrected', field='Titan',avgtime='1e8',
#Removing existing antenna refinements
          avgchannel='', avgscan=F, avgbaseline=T,
os.system('rm -rf '+data[0:23]+'.antpos')
          coloraxis='corr',
antenna='DV02,DV04,DV05,DV06,DV07,DV08,DV09,DV10,DV11,DV12,PM01,PM03'
          plotfile='plotms.'+asdm+'.wvrtsys.Titan.baseavg.ampfreq.png')
parameter = [
    #
0.00000, 0.00000, 0.00000, #DV02-A015
    os.system('rm plotms.'+asdm+'.wvrtsys.Antennae.ampfreq.png')
-0.00004, 0.00059, 0.00024, #DV04-J505
    plotms(vis=asdm+'.wvrtsys.ms',
-0.00019,-0.00003, 0.00035, #DV05-A067
          xaxis='freq', yaxis='amp',
-0.00027, 0.00033, 0.00022, #DV06-T704
          ydatacolumn='corrected', field='NGC*',
0.00006, 0.00057, 0.00032, #DV07-A004
          avgtime='1e8', avgscan=T, avgbaseline=F,
-0.00027, 0.00025,-0.00003, #DV08-A072
          coloraxis='baseline',
-0.00037, 0.00025, 0.00003, #DV09-A008
          plotfile='plotms.'+asdm+'.wvrtsys.Antennae.ampfreq.png')
-0.00056, 0.00028, 0.00026, #DV10-A009
-0.00028, 0.00024, 0.00011, #DV11-A016
-0.00018, 0.00010,-0.00014, #DV12-A011
-0.00017, 0.00013, 0.00030, #PM01-T702
-0.00007, 0.00034, -0.00004] #PM03-J504
gencal(vis=data,caltable='%s.antpos'%(data.split('.')[0]),caltype='antpos',
      antenna=antenna,parameter=parameter)
 
#In CASA
#The measurement set we are refining the antenna positions for
data='uid___A002_X207fe4_X4d7.ms'
#Removing existing antenna refinements
os.system('rm -rf '+data[0:23]+'.antpos')
antenna='DV02,DV04,DV05,DV06,DV07,DV08,DV09,DV11,DV12,PM01,PM03'
parameter = [
0.00000, 0.00000, 0.00000, #DV02-A015
-0.00004, 0.00059, 0.00024, #DV04-J505
-0.00019,-0.00003, 0.00035, #DV05-A067
-0.00027, 0.00033, 0.00022, #DV06-T704
0.00006, 0.00057, 0.00032, #DV07-A004
-0.00027, 0.00025,-0.00003, #DV08-A072
-0.00037, 0.00025, 0.00003, #DV09-A008
-0.00028, 0.00024, 0.00011, #DV11-A016
-0.00018, 0.00010,-0.00014, #DV12-A011
-0.00017, 0.00013, 0.00030, #PM01-T702
-0.00007, 0.00034, -0.00004] #PM03-J504
gencal(vis=data,caltable='%s.antpos'%(data.split('.')[0]),caltype='antpos',
      antenna=antenna,parameter=parameter)
 
 
#In CASA
#The measurement set we are refining the antenna positions for
data='uid___A002_X215db8_X18.ms'
#Removing existing antenna refinements
os.system('rm -rf '+data[0:22]+'.antpos')
antenna='DV02,DV04,DV05,DV06,DV07,DV08,DV09,DV10,DV11,DV12,DV13,PM01,PM03'
parameter = [
0.00000, 0.00000, 0.00000, #DV02-A015
-0.00004, 0.00059, 0.00024, #DV04-J505
-0.00019,-0.00003, 0.00035, #DV05-A067
-0.00027, 0.00033, 0.00022, #DV06-T704
0.00006, 0.00057, 0.00032, #DV07-A004
-0.00027, 0.00025,-0.00003, #DV08-A072
-0.00037, 0.00025, 0.00003, #DV09-A008
-0.00056, 0.00028, 0.00026, #DV10-A009
-0.00028, 0.00024, 0.00011, #DV11-A016
-0.00018, 0.00010,-0.00014, #DV12-A011
0.00009, 0.00033, 0.00023, #DV13-A075
-0.00017, 0.00013, 0.00030, #PM01-T702
-0.00007, 0.00034, -0.00004] #PM03-J504
gencal(vis=data,caltable='%s.antpos'%(data.split('.')[0]),caltype='antpos',
      antenna=antenna,parameter=parameter)
 
 
#In CASA
#The measurement set we are refining the antenna positions for
data='uid___A002_X215db8_X1d5.ms'
#Removing existing antenna refinements
os.system('rm -rf '+data[0:23]+'.antpos')
antenna='DV02,DV04,DV05,DV06,DV07,DV08,DV09,DV10,DV11,DV12,DV13,PM01,PM03'
parameter = [
0.00000, 0.00000, 0.00000, #DV02-A015
-0.00004, 0.00059, 0.00024, #DV04-J505
-0.00019,-0.00003, 0.00035, #DV05-A067
-0.00027, 0.00033, 0.00022, #DV06-T704
0.00006, 0.00057, 0.00032, #DV07-A004
-0.00027, 0.00025,-0.00003, #DV08-A072
-0.00037, 0.00025, 0.00003, #DV09-A008
-0.00056, 0.00028, 0.00026, #DV10-A009
-0.00028, 0.00024, 0.00011, #DV11-A016
-0.00018, 0.00010,-0.00014, #DV12-A011
0.00009, 0.00033, 0.00023, #DV13-A075
-0.00017, 0.00013, 0.00030, #PM01-T702
-0.00007, 0.00034, -0.00004] #PM03-J504
gencal(vis=data,caltable='%s.antpos'%(data.split('.')[0]),caltype='antpos',
      antenna=antenna,parameter=parameter)
 
#In CASA
#The measurement set we are refining the antenna positions for
data='uid___A002_X215db8_X392.ms'
#Removing existing antenna refinements
os.system('rm -rf '+data[0:23]+'.antpos')
antenna='DV02,DV04,DV05,DV06,DV07,DV08,DV09,DV10,DV11,DV12,DV13,PM01,PM03'
parameter = [
0.00000, 0.00000, 0.00000, #DV02-A015
-0.00004, 0.00059, 0.00024, #DV04-J505
-0.00019,-0.00003, 0.00035, #DV05-A067
-0.00027, 0.00033, 0.00022, #DV06-T704
0.00006, 0.00057, 0.00032, #DV07-A004
-0.00027, 0.00025,-0.00003, #DV08-A072
-0.00037, 0.00025, 0.00003, #DV09-A008
-0.00056, 0.00028, 0.00026, #DV10-A009
-0.00028, 0.00024, 0.00011, #DV11-A016
-0.00018, 0.00010,-0.00014, #DV12-A011
0.00009, 0.00033, 0.00023, #DV13-A075
-0.00017, 0.00013, 0.00030, #PM01-T702
-0.00007, 0.00034, -0.00004] #PM03-J504
gencal(vis=data,caltable='%s.antpos'%(data.split('.')[0]),caltype='antpos',
      antenna=antenna,parameter=parameter)
</source>
</source>


 
==Split and Concatenate Data for Northern Mosaic==
==Split and Concatenate Data for Northern and Southern Mosaics==


The individual data sets are now calibrated. We can safely split out the calibrated data for our science target and drop the calibrators. As we do so, we will smooth the data in frequency, averaging together groups of 23 channels by setting '''width=23''' in {{split}}. The new data will have a channel width corresponding to about ~10 km/s, very similar to the SMA data being verified. The factor of >20 drop in data volume will also make the imaging steps ''much'' more tractable.
The individual data sets are now calibrated. We can safely split out the calibrated data for our science target and drop the calibrators. As we do so, we will smooth the data in frequency, averaging together groups of 23 channels by setting '''width=23''' in {{split}}. The new data will have a channel width corresponding to about ~10 km/s, very similar to the SMA data being verified. The factor of >20 drop in data volume will also make the imaging steps ''much'' more tractable.
<source lang="python">
<source lang="python">
#In CASA
#In CASA
 
basename_north=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a",
basename_north=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9","uid___A002_X2181fb_X49"]
                "uid___A002_X207fe4_X3b9","uid___A002_X2181fb_X49"]
 
#
basename_south=["uid___A002_X1ff7b0_X1c8","uid___A002_X207fe4_X1f7","uid___A002_X207fe4_X4d7",
                          "uid___A002_X215db8_X18","uid___A002_X215db8_X1d5","uid___A002_X215db8_X392"]
 
for asdm in basename_north:
for asdm in basename_north:
     os.system('rm -rf '+asdm+'.cal.ms')
     os.system('rm -rf '+asdm+'.cal.ms')
     split(vis = asdm+'.wvrtsys.ms',outputvis = asdm+'.cal.ms',
     split(vis = asdm+'.wvrtsys.ms',outputvis = asdm+'.cal.ms',
            field = 'NGC*',spw='0',width=23, keepflags=False)
          field = 'NGC*',spw='0',width=23, keepflags=False)
    os.system('rm -rf '+asdm+'.cal.listobs.txt')
    listobs(asdm+'.cal.ms',listfile=asdm+'.cal.listobs.txt')
 
for asdm in basename_south:
    os.system('rm -rf '+asdm+'.cal.ms')
    split(vis = asdm+'.wvrtsys.ms',outputvis = asdm+'.cal.ms',
            field = 'Ant*',spw='0',width=23, keepflags=False)
     os.system('rm -rf '+asdm+'.cal.listobs.txt')
     os.system('rm -rf '+asdm+'.cal.listobs.txt')
     listobs(asdm+'.cal.ms',listfile=asdm+'.cal.listobs.txt')
     listobs(asdm+'.cal.ms',listfile=asdm+'.cal.listobs.txt')
</source>
</source>


For convenience we concatenate all data for the Northern Mosaic into a single big MS and place all data for the Southern Mosaic into another file. To do this, we construct a list that holds the names of all the Southern Mosaic MS files and another that holds the name of all the Northern Mosaic MS files then feed these into the {{concat}} task.  
For convenience we concatenate all data for the Northern Mosaic into a single big MS using the {{concat}} task.  


Before we do this, we'll take a brief aside to remove Pointing information from the calibrated data. Normally, the pointing information would apply important corrections to be used while imaging the data. However, some aspects of this are still under development and the pointing information in these data interacts poorly with CASA. We will remove the pointing information using the CASA toolkit Table tool (tb). ''This kind of operation is dangerous and should not be a regular feature of your CASA reduction.''
Before we do this, we'll take a brief aside to remove Pointing information from the calibrated data. Normally, the pointing information would apply important corrections to be used while imaging the data. However, some aspects of this are still under development and the pointing information in these data interacts poorly with CASA. We will remove the pointing information using the CASA toolkit Table tool (tb). ''This kind of operation is dangerous and should not be a regular feature of your CASA reduction.''


<source lang="python">
<source lang="python">
# In CASA
# In CASA  
for asdm in basename_north:
basename_all=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9",
    "uid___A002_X2181fb_X49","uid___A002_X1ff7b0_X1c8","uid___A002_X207fe4_X1f7",
    "uid___A002_X207fe4_X4d7","uid___A002_X215db8_X18","uid___A002_X215db8_X1d5",
    "uid___A002_X215db8_X392"]
for asdm in basename_all:
     print "Manually removing pointing table from "+asdm+".cal.ms ... Please be careful!"
     print "Manually removing pointing table from "+asdm+".cal.ms ... Please be careful!"
     tb.open(asdm+'.cal.ms/POINTING',nomodify=False)
     tb.open(asdm+'.cal.ms/POINTING',nomodify=False)
Line 1,682: Line 1,583:
</source>
</source>


And finally we run {{concat}}
<source lang="python">
<source lang="python">
# In CASA
# In CASA
cal_south_vis = [vis+'.cal.ms' for vis in basename_south]
cal_north_vis = [vis+'.cal.ms' for vis in basename_north]
cal_north_vis = [vis+'.cal.ms' for vis in basename_north]
 
#
os.system('rm -rf Antennae_South.cal.ms')
concat(vis=cal_south_vis, concatvis='Antennae_South.cal.ms', timesort=T)
 
os.system('rm -rf Antennae_North.cal.ms')
os.system('rm -rf Antennae_North.cal.ms')
concat(vis=cal_north_vis, concatvis='Antennae_North.cal.ms', timesort=T)
concat(vis=cal_north_vis, concatvis='Antennae_North.cal.ms', timesort=T)
</source>
</source>
The syntax used to construct the 'cal_north_vis' variable loops over basename_north and makes a list after adding '.cal.ms' to each member. To see the list 'print cal_north_vis'.


The syntax used to construct the 'cal_south_vis' variable loops over basename_south and makes a list after adding '.cal.ms' to each member. To see the list 'print cal_south_vis'.
The MS <tt>Antennae_North.cal.ms</tt> now contains all our calibrated data for the North mosaic, and is ready for imaging.


==Continue on to Imaging of the Science Target==
==Continue on to Imaging of the Science Target==
Now you can continue on to the [http://casaguides.nrao.edu/index.php?title=AntennaeBand7_Imaging_3.4 imaging guide].
Now you can continue on to the [http://casaguides.nrao.edu/index.php?title=AntennaeBand7_North_Imaging_3.4 imaging guide].
{{Checked 3.4.0}}
{{Checked 3.4.0}}

Latest revision as of 13:48, 5 June 2012


  • This casaguide covers the processing of a subset of the full Science Verification data; we consider only the the mosaic of the northern galaxy.
  • This portion of the guide covers calibration of the raw visibility data. To skip to the imaging portion of the guide, see: AntennaeBand7 North Imaging 3.4.

Overview

This part of the Antennae Band 7 CASA guide will step you through the calibration of the visibility data for the Northern mosaic. The bulk of this tutorial will walk you through the detailed processing of one of the four Measurement Sets corresponding to scheduling blocks for these observations. At the end there will be instructions for processing the other three blocks.

We will begin by flagging (marking as bad) data known to be useless before any inspection, for example data where one telescope blocks the line of sight of another. Then we will apply telescope-generated calibration tables to partially correct for atmospheric effects. After inspecting the data, we will flag some additional data that exhibit pathologies. Then we will use observations of the calibrators Titan and 3c279 to derive the phase and amplitude response of individual antennas as a function of time and frequency ("phase", "amplitude", and "bandpass" calibrations). We will apply these to the data and then extract the calibrated source data into a file appropriate for imaging.

The general procedure in this guide follows the other ALMA CASA guides: NGC3256Band3 and TWHydraBand7_3.4.

Getting Started

For the Synthesis Imaging school tutorial, we have provided you with the data you will need for this tutorial. For the Tuesday tutorials in the Speare building, the data live in "/var/nrao/ss_ant/calibration/"

For this portion of the guide change to the directory "ss_ant/calibration" and begin work from there. You will find a README file explaining the contents of the directory. These include the data, several calibration tables, and a directory of useful scripts ("analysis_scripts/"). Work on this portion of the guide from inside this directory.

From the "calibration/" directory, begin by starting CASA.

casapy

Note that this guide requires Python module analysisUtils. Test whether these are available inside of CASA (see below) by trying the following:

# In CASA
sys.path.append("analysis_scripts/")
import analysisUtils as au

if it works, you have the analysis_Utilities in the path and may proceed with the guide. The "sys.path.append" call adds the subdirectory "analysis_scripts/" to your path (so that python searches this directory when trying to import a module). If this does not work as for help or refer here: analysisUtils to learn how to retrieve these scripts on your own.

This guide has been written for CASA release 3.4.0. Please confirm your version before proceeding by pasting the following lines of code into your shell:

# In CASA
version = casalog.version()
print "You are using " + version
if (int(version.split()[4][1:-1]) < 19407):
    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."

Once you have verified that you have the right version of CASA and have access to the analysis utilities module, you can are ready to begin.

Initial Inspection and A Priori Flagging

Start here if you wish to step through the full guide (which we recommend). If you are pressed for time or want to move directly to imaging you may chose to start with the final flagging instead.

Initial Inspection

First we will take stock of what we have. If you have not already done so, begin by reviewing the description of the observations here: AntennaeBand7_3.4. In this tutorial we only deal with the 4 data sets for the Northern mosaic:

Northern Mosaic:

  • uid___A002_X1ff7b0_Xb.ms
  • uid___A002_X207fe4_X3a.ms
  • uid___A002_X207fe4_X3b9.ms
  • uid___A002_X2181fb_X49.ms

Detailed instructions and a walkthrough will be given only for the first of these uid___A002_X1ff7b0_Xb.ms.

We provide you with the "raw" data for only uid___A002_X1ff7b0_Xb.ms. For
the other three data sets we provide the data with the WVR and Tsys calibrations
already applied (but not other calibration). We recommend that you step through
the application of the WVR and Tsys calibration for this first data set, so that
you understand how it is done. The guide will then take you through the full
calibration of that first data set. At the end, you can find suggestions on how
to calibrate the other three. You may do so, or you may proceed to image
the provided calibrated data.".

The first step is to get basic information about the data: targets observed, time range, spectral setup, and so on. We do this using the task listobs, which will output a detailed summary of a dataset. Enter the following commands into CASA:

# In CASA
os.system('rm uid___A002_X1ff7b0_Xb.listobs.txt')
listobs(vis='uid___A002_X1ff7b0_Xb.ms', listfile='uid___A002_X1ff7b0_Xb.listobs.txt', verbose=True)

You can browse through the listobs output file as you would normally look at a text file (use emacs, vi, or another editor). You can also send the output to the terminal from inside of CASA. To do so type:

# In CASA
os.system('cat uid___A002_X1ff7b0_Xb.listobs.txt')

or

# In CASA
os.system('more uid___A002_X1ff7b0_Xb.listobs.txt')

CASA knows a few basic shell commands like 'cat', 'ls', and 'rm' but for more complex commands you will need to run them inside 'os.system("command")'. For more information see http://casa.nrao.edu/ .

Here is an example of the (abridged) output from listobs

================================================================================
 MeasurementSet Name:  uid___A002_X1ff7b0_Xb.ms      MS Version 2
================================================================================
   Observer: Unknown     Project: T.B.D.  
Observation: ALMA
Data records: 181357       Total integration time = 4931.71 seconds
   Observed from   28-May-2011/01:25:27.6   to   28-May-2011/02:47:39.3 (UTC)

   ObservationID = 0         ArrayID = 0
  Date        Timerange (UTC)          Scan  FldId FieldName           nRows   Int(s)   SpwIds      ScanIntent
  28-May-2011/01:25:30.7 - 01:26:17.1     1      0 3c279               1606   5.18     [1, 3, 2, 4, 0]  CALIBRATE_POINTING#ON_SOURCE,CALIBRATE_WVR#ON_SOURCE
              01:27:01.6 - 01:27:42.3     2      1 Titan               968    5.16     [5, 7, 6, 8, 0]             CALIBRATE_ATMOSPHERE#ON_SOURCE,CALIBRATE_WVR#ON_SOURCE
              01:28:13.9 - 01:31:36.2     3      1 Titan               9658   5.17     [1, 3, 2, 4, 0]             CALIBRATE_AMPLI#ON_SOURCE,CALIBRATE_PHASE#ON_SOURCE,CALIBRATE_WVR#ON_SOURCE
              01:32:05.0 - 01:32:45.3     4      0 3c279               979    5.11     [5, 7, 6, 8, 0]             CALIBRATE_ATMOSPHERE#ON_SOURCE,CALIBRATE_WVR#ON_SOURCE
              01:33:17.5 - 01:36:40.3     5      0 3c279               8712   5.23     [1, 3, 2, 4, 0]             CALIBRATE_BANDPASS#ON_SOURCE,CALIBRATE_PHASE#ON_SOURCE,CALIBRATE_WVR#ON_SOURCE
              01:37:08.3 - 01:37:49.4     6      0 3c279               968    5.16     [5, 7, 6, 8, 0]             CALIBRATE_ATMOSPHERE#ON_SOURCE,CALIBRATE_WVR#ON_SOURCE
              01:38:19.6 - 01:39:33.1     7      0 3c279               3861   5.17     [1, 3, 2, 4, 0]             CALIBRATE_PHASE#ON_SOURCE,CALIBRATE_WVR#ON_SOURCE
              01:40:03.3 - 01:40:44.5     8      2 NGC4038 - Antennae *968    5.16     [5, 7, 6, 8, 0]             CALIBRATE_ATMOSPHERE#ON_SOURCE,CALIBRATE_WVR#ON_SOURCE
              01:41:17.4 - 01:41:43.3     9      3 NGC4038 - Antennae *1606   5.18     [1, 3, 2, 4, 0]             OBSERVE_TARGET#ON_SOURCE
  <... abridged...>
              02:45:20.1 - 02:46:01.3    26      0 3c279               968    5.16     [5, 7, 6, 8, 0]             CALIBRATE_ATMOSPHERE#ON_SOURCE,CALIBRATE_WVR#ON_SOURCE
              02:46:25.6 - 02:47:39.3    27      0 3c279               3872   5.16     [1, 3, 2, 4, 0]             CALIBRATE_PHASE#ON_SOURCE,CALIBRATE_WVR#ON_SOURCE
           (nRows = Total number of rows per scan) 
Fields: 26
  ID   Code Name                RA              Decl          Epoch   SrcId nRows  
  0    none 3c279               12:56:11.16657 -05.47.21.5247 J2000   0     39116  
  1    none Titan               12:42:43.94813 -01.43.38.3190 J2000   1     10626  
  2    none NGC4038 - Antennae *12:01:53.17008 -18.52.37.9200 J2000   2     4818   
  3    none NGC4038 - Antennae *12:01:51.90301 -18.51.49.9437 J2000   2     6435   
  4    none NGC4038 - Antennae *12:01:52.43086 -18.51.49.9437 J2000   2     6424   
  5    none NGC4038 - Antennae *12:01:52.95871 -18.51.49.9437 J2000   2     5478   
  6    none NGC4038 - Antennae *12:01:53.48656 -18.51.49.9436 J2000   2     6435   
  7    none NGC4038 - Antennae *12:01:54.01441 -18.51.49.9436 J2000   2     6446   
  8    none NGC4038 - Antennae *12:01:52.16693 -18.51.56.4319 J2000   2     6435   
  9    none NGC4038 - Antennae *12:01:52.69478 -18.51.56.4318 J2000   2     6424   
  10   none NGC4038 - Antennae *12:01:53.22263 -18.51.56.4318 J2000   2     6446   
  11   none NGC4038 - Antennae *12:01:53.75049 -18.51.56.4318 J2000   2     6446   
  12   none NGC4038 - Antennae *12:01:51.90301 -18.52.02.9201 J2000   2     6435   
  13   none NGC4038 - Antennae *12:01:52.43086 -18.52.02.9200 J2000   2     6424   
  14   none NGC4038 - Antennae *12:01:52.95871 -18.52.02.9200 J2000   2     4818   
  15   none NGC4038 - Antennae *12:01:53.48656 -18.52.02.9200 J2000   2     4829   
  16   none NGC4038 - Antennae *12:01:54.01441 -18.52.02.9199 J2000   2     4829   
  17   none NGC4038 - Antennae *12:01:52.16694 -18.52.09.4082 J2000   2     4829   
  18   none NGC4038 - Antennae *12:01:52.69479 -18.52.09.4082 J2000   2     4829   
  19   none NGC4038 - Antennae *12:01:53.22264 -18.52.09.4082 J2000   2     3872   
  20   none NGC4038 - Antennae *12:01:53.75049 -18.52.09.4081 J2000   2     4829   
  21   none NGC4038 - Antennae *12:01:51.90301 -18.52.15.8964 J2000   2     4829   
  22   none NGC4038 - Antennae *12:01:52.43087 -18.52.15.8964 J2000   2     4829   
  23   none NGC4038 - Antennae *12:01:52.95872 -18.52.15.8963 J2000   2     4818   
  24   none NGC4038 - Antennae *12:01:53.48657 -18.52.15.8963 J2000   2     4818   
  25   none NGC4038 - Antennae *12:01:54.01442 -18.52.15.8963 J2000   2     4840   
Spectral Windows:  (9 unique spectral windows and 2 unique polarization setups)
  SpwID  #Chans Frame Ch1(MHz)    ChanWid(kHz)  TotBW(kHz)  Corrs  
  0           4 TOPO  184550      1500000       7500000     I   
  1        3840 TOPO  344845.586  488.28125     1875000     XX  YY  
  2           1 TOPO  343908.086  1875000       1875000     XX  YY  
  3        3840 TOPO  354971.074  488.28125     1875000     XX  YY  
  4           1 TOPO  343908.086  1875000       1875000     XX  YY  
  5         128 TOPO  344900.518  15625         2000000     XX  YY  
  6           1 TOPO  343892.705  1796875       1796875     XX  YY  
  7         128 TOPO  354916.143  15625         2000000     XX  YY  
  8           1 TOPO  343892.705  1796875       1796875     XX  YY  
Sources: 60
  ID   Name                SpwId RestFreq(MHz)  SysVel(km/s) 
  0    3c279               0     -              -
  <... abridged...>
  2    NGC4038 - Antennae *8     -              -            
Antennas: 11:
  ID   Name  Station   Diam.    Long.         Lat.         
  0    DV02  A015      12.0 m   -067.45.15.3  -22.53.26.0  
  1    DV04  J505      12.0 m   -067.45.18.0  -22.53.22.8  
  2    DV06  T704      12.0 m   -067.45.16.2  -22.53.22.1  
  3    DV07  A004      12.0 m   -067.45.15.9  -22.53.28.0  
  4    DV08  A072      12.0 m   -067.45.12.6  -22.53.24.0  
  5    DV09  A008      12.0 m   -067.45.15.4  -22.53.26.8  
  6    DV10  A009      12.0 m   -067.45.16.1  -22.53.26.1  
  7    DV11  A016      12.0 m   -067.45.16.4  -22.53.25.1  
  8    PM01  T702      12.0 m   -067.45.18.6  -22.53.24.1  
  9    PM02  A017      12.0 m   -067.45.15.9  -22.53.26.8  
  10   PM03  J504      12.0 m   -067.45.17.0  -22.53.23.0  
===============================================================================

This output shows that three sources were observed in each data set: 3c279, Titan, and the Antennae.

  • For the Northern Mosaic our target fields are named "NGC4038 - Antennae" where each field is an individual mosaic pointing. There are 23 for the Northern Mosaic.
  • Titan is observed once and will be used to set the absolute flux scale of the data.
  • 3c279 plays two roles: it will serve as our bandpass calibrator, to characterize the frequency response of the antennas, and because it is fairly close on the sky to the Antennae (18.6 degrees away) it will serve as our secondary calibrator (also referred to as the "phase calibrator" or "gain calibrator"), to track changes in the phase and amplitude response of the telescopes over time. Observations of 3c279 are interleaved with observations of the Antennae.

The output also shows that the data contain many spectral windows. Using the labeling scheme in the listobs above these are:

  • spw 0 targets ~185 GHz and holds water vapor radiometer data
  • spw 1 and spw 3 hold our science data. These are "Frequency Domain Mode" (FDM) data with small (0.49 MHz) channel width and wide (1.875 GHz) total bandwidth. As a result these have a lot of channels (3840). spw 1 holds the lower sideband (LSB) data and includes the CO(3-2) line. We will focus on these data. For the CO(3-2) line the channel width corresponds to 0.426 km/s and the bandwidth of spw 1 to 1634 km/s.
  • spw 2 and spw 4 hold frequency-averaged versions of spw 1 and 3 ("Channel 0" for those familiar with AIPS). These are used for some quick automated inspection. We will not use them here but we will carry out an equivalent inspection using spw 1.
  • spw 5 and spw 7 hold lower a resolution processing ("Time Domain Mode", TDM) of the data from the same part of the spectrum (baseband) as spws 1 and 3. These data have only 128 channels across 2 GHz bandwidth and so have a much coarser channel spacing than the FDM data. These were used to generate the calibration tables that we include in the tarball but will not otherwise appear in this guide.

The final column of the listobs output in the logger gives the scan intent. Later we will use this information to flag the pointing scans and the hot and ambient load calibration scans.

We'll now have a look at the configuration of the antennas used to take the data using the task plotants (<xr id="Uid_A002_X1ff7b0_Xb.ANT.png"/>).

<figure id="Uid_A002_X1ff7b0_Xb.ANT.png">

Position of antennas in dataset uid_A002_X1ff7b0_Xb obtained using task plotants

</figure>

# In CASA
plotants(vis='uid___A002_X1ff7b0_Xb.ms', figfile='uid___A002_X1ff7b0_Xb.plotants.png')
clearstat()

This will show you the antenna positions for the given dataset, and save that as a file named "uid___A002_X1ff7b0_Xb.plotants.png". The clearstat command will clear any lingering table locks from the plotting.

Aside: How to Deal With Multiple Measurement Sets

It should already be clear from the initial inspection that dealing with 4 (or more) data sets at the same time can be a bit problematic. The source name changes between these two scripts and there are different numbers of fields in the mosaic. We get around much of this issue by dealing with only the 4 Northern Mosaic datasets and ignoring the 6 Southern ones, as well as focusing on a single MS in the walthrough portion of this guide.

As a general rule one would reduce each individual observation separately or at the very least only group data observed in a uniform way and very close in time.

Near the end of the tutorial we will direct you to process the remainder of the Northern Mosaic fields using 'for' loops. We will not be able to show every diagnostic plot but we give an example of each and the syntax to generate the rest. Also please be aware that even on a very fast machine this whole process can take a while, we are simply dealing with a lot of data.

A Priori Flagging

Even before we look in detail, we know that there are some data that we wish to exclude. We will start by flagging "shadowed" data where one antenna blocks the line of sight of another. We will also flag scans that were used to carry out pointing and atmospheric calibration, identified by their scan intent. Finally, we will flag the autocorrelation data (the correlation of the signal from an antenna with itself) as we are only interested in cross-correlation data to make an interferometric image.

You may want to reset the flagging if you have tried this step before and are starting over though this is not necessary on your first time through. Do so using tflagdata:

# In CASA
tflagdata(vis='uid___A002_X1ff7b0_Xb.ms',mode='unflag',action='apply',flagbackup=F)

CASA 3.4 Note: here we use the new tflagdata which, although still experimental, is faster than flagdata for most operations.

To carry out the flagging, we will assemble a set of flagging commands and then use the flagcmd task to execute them. These commands will be stored in a Python list of strings called myflags, each of which will be a specific flagging command. The operation of flagcmd is decribed by help flagcmd (with examples), and the syntax for the flagging command modes is given in help tflagdata.

First, we designate mode='shadow' to remove data from a given antenna when another antenna is in front of it and blocking part of its aperture.

# In CASA
myflags = ["mode='shadow'"]

The relevant calibration information has already been extracted from the pointing and atmospheric scans and we will not need them below. Next we set up a command string to flag the pointing scans using mode='manual' selecting on the scan intent corresponding to pointing:

# In CASA
myflags.append("mode='manual' intent='*POINTING*'")

Note that because the atmospheric calibration scans contain only TDM spectral windows, they will be removed automatically when we separate out the FDM data below.

Now we wish to flag the autocorrelation data:

# In CASA
myflags.append("mode='manual' autocorr=True")

You can show the flags we have accumulated by printing the myflags variable, e.g.

CASA <24>: myflags
  Out[24]: 
["mode='shadow'",
 "mode='manual' intent='*POINTING*'",
 "mode='manual' autocorr=True"]

Finally we execute the same flagging commands our ms using flagcmd.

# In CASA
flagcmd(vis='uid___A002_X1ff7b0_Xb.ms', inpmode='cmd', command=myflags, action='apply', flagbackup=True)

Note that the flagging task makes a single pass through the data applying the union of all flagging commands. You see its progress reported in individual chunks of the data. The myflags command list can in fact be used on each of our MSes as-is.

As an added step, we use flagmanager to save a copy of the flags we just made in the MS to reflect the current state, in case we ever need to get back to this stage.

# In CASA
flagmanager(vis='uid___A002_X1ff7b0_Xb.ms', mode='save', versionname='Apriori')

Now if ever there is a reason to roll back the flags to match the current version, called 'Apriori', the syntax would be:

# In CASA
flagmanager(vis='uid___A002_X1ff7b0_Xb.ms', mode='restore', versionname='Apriori')

The flagmanager task will also allow you to view the saved flagging versions, including those created by running flagdata with flagbackup=T. For example try

# In CASA
flagmanager(vis='uid___A002_X1ff7b0_Xb.ms', mode='list')

The output in the logger should list the Apriori flagging that we have applied. It will also indicate versions associated with any flagdata command where you did not set flagbackup=F. Other tasks, for example applycal, will also create flag version tables.

Create and Apply Tsys, WVR, and Antenna Position Calibration Tables

We now carry out "a priori" calibration steps that need to occur before getting to data-derived calibrations.

<figure id="uid___A002_X1ff7b0_Xb.tsys_vs_time.page1.png">

Tsys vs. time plot for uid_A002_X1ff7b0_Xb (northern mosaic). First 8 antennas. Note the high y-axis values for DV04. The two different colors indicate the two polarizations (XX and YY).

</figure> <figure id="uid___A002_X1ff7b0_Xb.tsys_vs_time.page2.png">

Tsys vs. time plot for uid_A002_X1ff7b0_Xb (northern mosaic). Remaining antennas.

</figure> <figure id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.DV02.spw5.CASA3_4.png">

Tsys vs. frequency plot for uid_A002_X1ff7b0_Xb (northern mosaic). First 4 antennas. Note the high y-axis values for DV04 and the mesospheric line near 343.2 GHz.

</figure> <figure id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.DV08.spw5.CASA3_4.png">

Tsys vs. frequency plot for uid_A002_X1ff7b0_Xb (northern mosaic). Next 4 antennas.

</figure> <figure id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.PM01.spw5.CASA3_4.png">

Tsys vs. frequency plot for uid_A002_X1ff7b0_Xb (northern mosaic). Remaining antennas.

</figure>

<figure id="Uid___A002_X215db8_X392.tdm.tsys.3c279.DV11.spw5.CASA3_4.png">

Tsys vs. frequency plot for uid___A002_X215db8_X392. Note the pathological behavior for DV12.

</figure>

Tsys

The Tsys calibration gives a first-order correction for the atmospheric opacity as a function of time and frequency and associates weights with each visibility that persists through imaging.

Use gencal to create the Tsys calibration tables from the spectral windows with CALIBRATE_ATMOSPHERE intents in listobs (i.e. the TDM spectral windows with 128 channels), these are spectral windows 5 and 7.

#In CASA
os.system('rm -rf uid___A002_X1ff7b0_Xb.tdm.tsys')
gencal(vis='uid___A002_X1ff7b0_Xb.ms',
       caltable='uid___A002_X1ff7b0_Xb.tdm.tsys',
       spw='5,7',caltype='tsys')

Later in the applycal stage this TDM Tsys table will be interpolated to the FDM (3840 channels per spw) science spectral windows 1 and 3.

Next we inspect the Tsys tables for the spectral window spw=5 with the task plotcal. We want to check that Tsys data have reasonable values and identify any unexpected features as a function of either time or frequency. To get an idea of sensible Tsys under average atmospheric observations consult the ALMA sensitivity calculator, accessible from http://www.almascience.org (via the "Documents & Tools" link).

We start by plotting the Tsys for all the antennas and polarizations (XX and YY) as a function of time for each. Here and throughout we focus on spw 1, which contains CO(3-2):

#In CASA
plotcal(caltable='uid___A002_X1ff7b0_Xb.tdm.tsys', 
        xaxis="time",yaxis="tsys",
        spw='5:50~50',plotsymbol=".", subplot=421,
        antenna='0~7',
        iteration='antenna',
        figfile='uid___A002_X1ff7b0_Xb.tdm.tsys_vs_time.page1.png',
        fontsize=7.0)
plotcal(caltable='uid___A002_X1ff7b0_Xb.tdm.tsys', 
        xaxis="time",yaxis="tsys",
        antenna='8~15',
        spw='5:50~50',plotsymbol=".", subplot=421,
        iteration='antenna',
        figfile='uid___A002_X1ff7b0_Xb.tdm.tsys_vs_time.page2.png',
        fontsize=7.0)

This plots Tsys as a function of time for channel 50 in spectral window 5. In the call to plotcal:

  • subplot=421 parameter sets up a 4 x 2 panel grid.
  • iteration tells plotcal to make a separate plot for each antenna.
  • spw '5:50~50' selects spw '5' channel 50-50. This allows us to cleanly separate time variations from frequency variations.

Because 8 panels (2 panels for each antenna - LSB and USB) is not enough to show all antennas on one page, there are two plotcal calls: one for the first 8 antennas (antenna=0~7), and then for the remaining antennas (antenna=8~15). The fontsize needs to be set to a small value or the text overlaps.

The Tsys values in <xr id="uid___A002_X1ff7b0_Xb.tsys_vs_time.page1.png"/> and <xr id="uid___A002_X1ff7b0_Xb.tsys_vs_time.page2.png"/> look reliable, with typical values ~150 K except for some large values of Tsys at ~400 and 500 K for DV04. We will flag the data for that antenna later.

We will also want to look at Tsys as a function of frequency. This will use the analysisutils package mentioned at the beginning of this guide (called by the au. command) looping over field:

#In CASA
os.system('rm -rf cal_plots/Tsys_plots/uid___A002_X1ff7b0_Xb.tdm.tsys*')
tsysfields=['3c279','Titan','NGC4038*']
outfname={'3c279':'3c279','Titan':'Titan','NGC4038*':'NGC4038'}
for field in tsysfields:
    au.plotbandpass2(caltable='uid___A002_X1ff7b0_Xb.tdm.tsys',
                     field=field,yaxis='amp',xaxis='freq',
                     showatm=True,overlay='time',
                     figfile='cal_plots/Tsys_plots/uid___A002_X1ff7b0_Xb.tdm.tsys.'+outfname[field],
                     buildpdf=False,
                     interactive=False,chanrange='8~120',subplot=42)

Now have a look at the Tsys vs. frequency plots or see <xr id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.DV02.spw5.CASA3_4.png"/>, <xr id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.DV08.spw5.CASA3_4.png"/>, and <xr id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.PM01.spw5.CASA3_4.png"/> for examples on our first data set. You can see the effect of a close pair of atmospheric ozone absorption lines at about 343.2 GHz that makes Tsys larger near that frequency in all antennas. Applying the Tsys calibration tables will minimize the contribution of these atmospheric lines. Again DV04 stands out with its very high Tsys. Although not present in the first data sets, Antenna DV12 exhibits periodic spikes in Tsys vs. frequency for one polarization (see <xr id="Uid___A002_X215db8_X392.tdm.tsys.3c279.DV11.spw5.CASA3_4.png"/> for an example from a data set in Southern Mosaic). It may or may not be possible to calibrate that behavior out. We will make a note to look carefully at DV12 further on in the calibration process.

WVR

The WVR calibration uses observations of the wings of the 183 GHz atmospheric water line to correct for phase variations as a function of time. As noted in the tsys section, this run of gencal will append to existing WVR produced tables. To avoid this, preexisting wvrgcal data is removed.

#In CASA
os.system('rm -rf uid___A002_X1ff7b0_Xb.wvrgcal')
wvrgcal(vis='uid___A002_X1ff7b0_Xb.ms',caltable='uid___A002_X1ff7b0_Xb.wvrgcal',toffset=-1)

Antenna Positions

The antenna position table reflects refinements in the measured positions of the antennas from those stored in the data. gencal will now be used put antenna position data into each observation. Again, gencal will merely append to existing antenna position data, ruining any subsequent results. We start by removing any existing antenna position refinements, followed by defining the antenna names, then their refinements (both as arrays), finally running gencal to create the information CASA can refer to for antenna positions.

#In CASA
os.system('rm -rf uid___A002_X1ff7b0_Xb.antpos')
myantenna = 'DV02,DV04,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03'
myparameter = [ 0.00000, 0.00000, 0.00000, #DV02-A015
               -0.00004, 0.00059, 0.00024, #DV04-J505
               -0.00027, 0.00033, 0.00022, #DV06-T704
                0.00006, 0.00057, 0.00032, #DV07-A004
               -0.00027, 0.00025,-0.00003, #DV08-A072
               -0.00037, 0.00025, 0.00003, #DV09-A008
               -0.00056, 0.00028, 0.00026, #DV10-A009
               -0.00028, 0.00024, 0.00011, #DV11-A016
               -0.00017, 0.00013, 0.00030, #PM01-T702
               -0.00034, 0.00092, 0.00027, #PM02-A017 Before July 1
               -0.00007, 0.00034, -0.00004] #PM03-J504 
#
gencal(vis='uid___A002_X1ff7b0_Xb.ms',
       caltable='uid___A002_X1ff7b0_Xb.antpos',
       caltype='antpos',
       antenna=myantenna,parameter=myparameter)

Applycal

We are now ready to apply the Tsys and the WVR calibration tables to the data with applycal, which reads the specified gain calibration tables, applies them to the (raw) data column, and writes the calibrated results into the corrected column. It is important to only apply Tsys and WVR corrections obtained close in time to the data being corrected, so in addition to looping over data sets we define the list of unique source names and loop over these. Then by setting gainfield and field to the same value we ensure that Tsys and WVR calibrations are only applied to the source for which they are measured. We will only correct spw 1 and 3, our science windows, because we will drop the other data in a moment.

The applycal task now has much more flexibility for interpolating and applying calibrations derived in one spectral window to another, even if they do not share the same spectral shape (number of channels and channel width). This new functionality is used below to interpolate the TDM (128 channel) Tsys measurements to the FDM (3840 channel) spectral windows. This is controlled through the spectral window mapping parameter *spwmap*. Because this can be a bit confusing, we've written a "helper" function that will tell you what you should put for the Tsys calibration table part of spwmap. We only need to run it on one of the datasets because they are all the same in this regard. We will capture the output return value in a list:

# In CASA
from recipes.almahelpers import tsysspwmap
mytsysspwmap = tsysspwmap(vis='uid___A002_X1ff7b0_Xb.ms',
                          tsystable='uid___A002_X1ff7b0_Xb.tdm.tsys')

This will give you:

CASA <59>: mytsysspwmap
  Out[59]: [0, 5, 5, 7, 5, 5, 5, 7, 5]

Recall that the TDM spectral windows are spw=5 and 7 and the FDM spectral windows are 1 and 3. This spwmap tells applycal to use the Tsys information in spectral window 5 for spectral window 1; and to use the information in spectral window 7 for spectral window 3. Beyond that, it is only important that there are placeholders for the other spectral windows, its also useful to note that you need not give placeholders for spectral window ids larger than the largest spectral window you need to use, in this case 7. You will also need to put in placeholders for other tables that you give the gaintables. So if the Tsys table is 2nd in the list, you would use spwmap=[[],[0,5,5,7,5,5,5,7],[]].

Now run the applycal commands (this may take up to 10 minutes, maybe more depending on your workstation):

# In CASA
# A new list of file names that contain only data from the Northern Mosaic
field_names_north = ['Titan','3c279','NGC*']
for field in field_names_north:
    applycal(vis='uid___A002_X1ff7b0_Xb.ms', spw='1,3', 
             field=field, gainfield=['',field,field],
             interp=['','linear,spline','nearest'], 
             gaintable=['uid___A002_X1ff7b0_Xb.antpos',
                        'uid___A002_X1ff7b0_Xb.tdm.tsys',
                        'uid___A002_X1ff7b0_Xb.wvrgcal'],
             spwmap=[[],[0, 5, 5, 7, 5, 5, 5, 7],[]],
             flagbackup=F)

where:

  • field: the field to which we will apply the calibration,
  • gainfield: the field from which we wish to take the calibration table
  • interp = 'nearest' : apply the nearest solution from the calibration table rather than interpolating.

If you were to you browse through the whole data set, you will probably note some problems along the same lines as the DV04 issue we saw above. We'll apply these as additional data flagging in just a moment.

Inspect Data

<figure id="plotms_amp_vs_freq_example-data.png">

Example of Amplitude vs. Frequency before correction for the first Northern Mosaic data set.

</figure> <figure id="plotms_amp_vs_freq_example-corr.png">

Same baseline as <xr id="plotms_amp_vs_freq_example-data.png"/> but now after correction using WVR and Tsys calibrations.

</figure>

<figure id="plotms.uid___A002_X1ff7b0_Xb.All.ampvstime.png">

Amplitude vs. time for the first northern mosaic data set.

</figure> <figure id="plotms.uid___A002_X1ff7b0_Xb.3C279.ampvsuvdist.png">

Amplitude vs. uv-distance for 3c279 in the first northern mosaic data set.

</figure> <figure id="plotms.uid___A002_X1ff7b0_Xb.Titan.ampvsuvdist.png">

Amplitude vs. uv-distance for Titan in the first northern mosaic data set.

</figure>

<figure id="plotms.uid___A002_X1ff7b0_Xb.3C279.ampvsfreq.png">

Amplitude vs. frequency for 3c279 in the first northern mosaic data set.

</figure> <figure id="plotms.uid___A002_X1ff7b0_Xb.Titan.ampvsfreq.png">

Amplitude vs. frequency for Titan in the first northern mosaic data set. Note the strong line (this is CO 3-2)!

</figure> <figure id="plotms.uid___A002_X1ff7b0_Xb.Antennae.ampvsfreq.png">

Amplitude vs. frequency for the Antennae in the first northern mosaic data set. The CO(3-2) line is visible.

</figure>

We are not quite done with the original data set yet. Before going further it will be useful to use plotms to show the effects of applying the calibration. In the process we'll take a quick look at each antenna and search for pathologies in the data.

For this basic inspection, we want to compare the phase and amplitude as a function of frequency and time in the DATA and CORRECTED columns of each measurement set. The CORRECTED column has had the Tsys and WVR calibrations applied and so we expect lower phase scatter and flatter amplitude response as a function of time and frequency. We are looking for antenna-based issues, so cycling through a set of baselines that includes each antenna once will be a good start. We'll focus these plots on the phase+bandpass calibrator, 3c279, and on baselines that include antenna DV11, which we will make our reference antenna in just a bit.


Each CASA Measurement Set has up to three "columns" of data: DATA, CORRECTED, and MODEL (though it is possible
for a MS to hold only a DATA column if it has not been processed at all). 

A column entry exists for each data point (baseline, frequency, time). 

The DATA column holds the current raw data, though using split as we just did we can change the definition of
"raw" data. 

The CORRECTED column holds the result of applying one or more calibration tables (e.g., via applycal) to the
DATA column and so represents a corrected version of the DATA column. 

In CASA 3.4: the MODEL column is optional (though it is still possible to use them by explicitly setting usescratch=T).
Instead, if usescratch=F, the model is stored in the header of the ms. This is a great step forward in terms of saving 
space and time to create scratch columns  

To get an intuitive feel for the columns you may wish to explore using plotms (which can plot different data 
columns, as seen below) or the browsetable task.

Note: Not all the plots described below are shown to the right. Feel free to experiment also.

First, we plot amplitude as a function of frequency for 3c279. We start by plotting the DATA column, set color to indicate the two correlations (i.e., the XX and YY polarizations), and ask plotms to iterate over baseline. By setting antenna to 'DV11&*' we select only baselines that include DV11. We ask plotms to average all data over a very long timescale, avgtime = 1e8 seconds ~ 3 years or much longer than the time spanned by the whole data set. By setting avgscan = True we allow plotms to average across scan boundaries. The result is a plot of average amplitude per channel vs. frequency.

# In CASA
plotms(vis='uid___A002_X1ff7b0_Xb.ms', 
       field='3c279',
       xaxis='frequency', yaxis='amp',
       selectdata=T, spw='1', 
       avgtime='1e8',avgscan=T,
       coloraxis='corr',
       iteraxis='baseline',
       antenna='DV11&*',
       ydatacolumn='data')

Notice the green arrows along the bottom of the plotms window. We asked plotms to iterate over baseline. As you click the arrows, the plot will rotate from baseline to baseline, always with DV11 so that each antenna shows up once. To see the effect of the calibration, go to the "Axes" tab along the left of the plotms window and pull down the Data Column menu under the Y Axis. Set this from DATA to CORRECTED and you should see the effects of the calibration. You may need to ensure that the "Force Reload" box is checked before clicking "Plot" (both buttons lie at the bottom of the panel). For the most part things get better (flatter), but as we noted before DV04 is problematic.

You can now make analogous calls to examine the phase vs. frequency, amplitude vs. time, and phase vs. time.

# In CASA
plotms(vis='uid___A002_X1ff7b0_Xb.ms', 
       field='3c279',
       xaxis='frequency', yaxis='phase',
       selectdata=T, spw='1', 
       avgtime='1e8',avgscan=T,
       coloraxis='corr',
       iteraxis='baseline',
       antenna='DV11&*',
       ydatacolumn='data')
#
plotms(vis='uid___A002_X1ff7b0_Xb.ms', 
       field='3c279',
       xaxis='time', yaxis='amp',
       selectdata=T, spw='1:1200~1300', 
       avgchannel='1000',avgscan=F,
       coloraxis='corr',
       iteraxis='baseline',
       antenna='DV11&*',
       ydatacolumn='data')
#
plotms(vis='uid___A002_X1ff7b0_Xb.ms', 
       field='3c279',
       xaxis='time', yaxis='phase',
       selectdata=T, spw='1:1200~1300', 
       avgchannel='1000',avgscan=F,
       coloraxis='corr',
       iteraxis='baseline',
       antenna='DV11&*',
       ydatacolumn='data')

Where:

  • spw is set to cover only channels 1200~1300 for the time plots in order to isolate time dependent variations from frequency-dependent behavior. Those 101 channels represent only a small part of the total spw 1 bandpass.
  • avgchannel set to a large number causes the plots of phase and amplitude vs. time to average data at all frequencies into a single point for each measurement.
  • coloraxis corr sets the colors to correspond to the two polarizations of the data.

In each case, you will want to examine each baseline, alternating between the DATA and CORRECTED columns.

This is a lot of data inspection and that's only for one of 4 data sets for this mosaic! However you approach the logistics (either scripting or manual inspection), you are looking for:

  • Improved scatter and lower variability in phase and amplitude vs. frequency and time. This indicates that the WVR and Tsys calibrations helped.
  • Sudden jumps in phase or amplitude as a function of either time or frequency. These may indicate problems with the antenna during that observation.
  • Large gradients, especially full wraps, in phase as a function of frequency. This may indicate a problem in the delays, the signal path length to the telescopes.
  • Unusual magnitude, scatter, or patterns in any plot - though this may be better explored using plots that show all data together, which we'll make in a moment.
  • Missing data. For example, if the phase calibrator drops out for a period of time we will not be able to calibrate and will need to flag the data.

As you look through, note individual potentially problematic antennas. If all antennas in a data set appear problematic it may be that your "reference" antenna, DV11 in the example above, is the source of the problem. In this case swap this reference antenna for another and see whether the problem is isolated to your original reference antenna.

Some other plots to make:

# In CASA
# Amplitude versus time all fields baselines to DV11 avg all chan
plotms(vis='uid___A002_X1ff7b0_Xb.ms', 
       field='',
       xaxis='time', yaxis='amp',
       selectdata=T, spw='1',
       avgchannel='10000',avgscan=F,
       coloraxis='field',
       antenna='DV11&*',
       ydatacolumn='corrected',
       plotfile='plotms.uid___A002_X1ff7b0_Xb.All.ampvstime.png')
#
# Amplitude versus uvdist (m) 3c279 all baselines avg all chan
plotms(vis='uid___A002_X1ff7b0_Xb.ms', 
       field='3c279',
       xaxis='uvdist', yaxis='amp',
       selectdata=T, spw='1',
       avgchannel='10000',avgscan=F,
       coloraxis='baseline',
       antenna='',
       ydatacolumn='corrected',
       plotfile='plotms.uid___A002_X1ff7b0_Xb.3C279.ampvsuvdist.png')
#
# Amplitude versus uvdist (m) Titan all baselines avg all chan
plotms(vis='uid___A002_X1ff7b0_Xb.ms', 
       field='Titan',
       xaxis='uvdist', yaxis='amp',
       selectdata=T, spw='1',
       avgchannel='10000',avgscan=F,
       coloraxis='baseline',
       antenna='',
       ydatacolumn='corrected',
       plotfile='plotms.uid___A002_X1ff7b0_Xb.Titan.ampvsuvdist.png')
#
# Amplitude versus frequency 3c279 baselines to DV11
plotms(vis='uid___A002_X1ff7b0_Xb.ms', 
       field='3c279',
       xaxis='frequency', yaxis='amp',
       selectdata=T, spw='1', 
       avgtime='1e8',avgscan=T,
       coloraxis='baseline',
       antenna='DV11&*',
       ydatacolumn='corrected',
       plotfile='plotms.uid___A002_X1ff7b0_Xb.3C279.ampvsfreq.png')
#
# Amplitude versus frequency Titan baselines to DV11
plotms(vis='uid___A002_X1ff7b0_Xb.ms', 
       field='Titan',
       xaxis='frequency', yaxis='amp',
       selectdata=T, spw='1', 
       avgtime='1e8',avgscan=T,
       coloraxis='baseline',
       antenna='DV11&*',
       ydatacolumn='corrected',
       plotfile='plotms.uid___A002_X1ff7b0_Xb.Titan.ampvsfreq.png')
#
# Amplitude versus frequency Antennae baselines to DV11
plotms(vis='uid___A002_X1ff7b0_Xb.ms', 
       field='NGC4038*',
       xaxis='frequency', yaxis='amp',
       selectdata=T, spw='1', 
       avgtime='1e8',avgscan=T,
       coloraxis='baseline',
       antenna='DV11&*',
       ydatacolumn='corrected',
       plotfile='plotms.uid___A002_X1ff7b0_Xb.Antennae.ampvsfreq.png')

Here we direct the plotms output (since they are single panel plots) to plotfiles for future reference. Here look for:

  • Missing data. The source needs to be flanked by phase calibrator scans, if those are missing for any reason we need to flag the appropriate time range.
  • Dramatic outliers. Does the source suddenly get very bright or the otherwise bright calibrator appear anomalously faint for a brief time? This likely indicates problematic data that should be identified and flagged. You can use the "select" (box with green plus along the bottom row in plotms) and "locate" (magnifying glass) buttons in plotms to isolate and identify problem data (it will print to the log).
  • Smooth variation with time. A sudden jump may indicate a problem and often the safest approach is to flag data near a discontinuity.

First we plot amplitude versus time (see <xr id="plotms.uid___A002_X1ff7b0_Xb.All.ampvstime.png"/>), averaging over all channels (by setting avgchannel to the very large value 10,000). We colorize by field so that scans on Titan are red, the bandpass and phase calibrator 3c279 is black, and the Antennae mosaic appears as a range of colors (one per pointing). When processing your own data, look through the amplitudes vs. time for each data set.

There are two other very useful "averaging" plots worth making. First, we plot amplitude as a function of u-v distance (projected antenna separation). Discontinuities and spikes in this plot are often from non-astrophysical sources. In the phase analog to the plot, the effects of atmospheric decorrelation can be assessed from increased scatter at longer u-v distances. While using the moon Titan as our flux calibrator, we may want to watch for flaring amplitudes at short u-v distances. These may indicate that Saturn is contaminating our beam. For a perfect, bright point source, we expect flat amplitudes as a function of u-v distance at the source amplitudes. Figures <xr id="plotms.uid___A002_X1ff7b0_Xb.3C279.ampvsuvdist.png"/> and <xr id="plotms.uid___A002_X1ff7b0_Xb.Titan.ampvsuvdist.png"/> show examples of this plot, generated via the commands above.

It can also be useful to examine the average amplitude as a function of frequency for each target. This allows one to check for lingering atmospheric effects, unexpected line emission or absorption in the calibrators, or decreased sensitivity due to "roll-off" of the telescope sensitivity at the band edges. See figures <xr id="plotms.uid___A002_X1ff7b0_Xb.3C279.ampvsfreq.png"/> and <xr id="plotms.uid___A002_X1ff7b0_Xb.Titan.ampvsfreq.png"/> where you can clearly see the strong CO(3-2) line in Titan. This will need to be flagged before we can use Titan to calibrate the flux scale of our data. We can also plot our mosaic fields, shown in <xr id="plotms.uid___A002_X1ff7b0_Xb.Antennae.ampvsfreq.png"/>. You see the CO(3-2) line here also, even before calibration.

This section (Data Inspection) and the next (Apply Flags) are closely linked. We will present them as two separate steps. The idea here is that you look through your data, note problems, and then write commands to flag problematic data. This mimics one approach to writing data reduction scripts for CASA, where you will group all flagging together into one convenient place. Other CASA guides take a different approach, interleaving flagging and plotting. There is no "right" answer here. Find an approach to data inspection that works for you.

With the Tsys and WVR calibrations applied successfully and the a priori flagging taken care of we will now split out the corrected data. We will keep only the corrected data, specified via datacolumn, and only spectral window 1, which contains the FDM (high spectral resolution) observations of the CO(3-2) line. Setting keepflags=F tells split not to carry over any fully flagged rows from the original data set to the new MS. We give the new MS files the extension ".wvrtsys.ms" to indicate that they have been corrected for WVR and Tsys effects. Because split will not overwrite existing files, we remove any previous versions of the new MS before beginning.

# In CASA
os.system('rm -rf uid___A002_X1ff7b0_Xb.wvrtsys.ms')
split(vis='uid___A002_X1ff7b0_Xb.ms',
      outputvis='uid___A002_X1ff7b0_Xb.wvrtsys.ms', 
      datacolumn='corrected', spw='1', keepflags=F)

Be patient, split may take awhile. The WVR and Tsys-corrected data now sit in the DATA column of the new measurement sets, which have only one spectral window (now labeled spectral window 0 though it was spectral window 1 in the original data). You may wish to run listobs to illustrate the changes:

# In CASA
os.system('rm uid___A002_X1ff7b0_Xb.wvrtsys.listobs.txt')
listobs(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
        listfile='uid___A002_X1ff7b0_Xb.wvrtsys.listobs.txt',
        verbose=True)

Note the new spectral window information:

Spectral Windows:  (1 unique spectral windows and 1 unique polarization setups)
  SpwID  #Chans Frame Ch1(MHz)    ChanWid(kHz)  TotBW(kHz)  Corrs  
  0        3840 TOPO  344845.586  488.28125     1875000     XX  YY  

The suite of plots we generated above (along with the earlier inspection of the Tsys tables) gives us the tools we need to identify problematic data through the data sets. We use this to generate a set of inspection-driven flagdata commands for each data set. We apply these before the bandpass and gain calibration.

Final Flagging and Calibration

Starting from the .wvrtsys.ms data we just flagged, pre-calibrated, and split, we continue on with extra flagging and the main calibration.

Starting Point

If you went through the process of pre-calibration from the previous section, then you should have a .wvrtsys.ms dataset ready to go.

If you are starting the tutorial at this point, then you should download or copy (from a designated location) the tar-ball Antennae_Band7_North_PreCalibratedMS.tgz. When you unpack this

tar -xvzf Antennae_Band7_North_PreCalibratedMS.tgz

you will find the .wvrtsys.ms files in a sub-directory named Antennae_Band7_North_PreCalibratedMS. You will cd into this directory to run CASA, or move the files into your working directory.

Apply More Flagging: Search and Destroy

<figure id="plotms.uid___A002_X1ff7b0_Xb.3C279.ampvschan.png">

Amplitude vs. channel for baselines to DV11. This kind of plot can be inspected to get an idea of the presence or magnitude of any roll-off in sensitivity near the edges of the spectral window.

</figure> <figure id="amp_vs_uv_titan_obs.png">

Observed amplitude vs. uv-distance for observations of Titan in the first data set. Note the scatter for low projected antenna separations. We will flag these short-spacing data, which may reflect contamination by Saturn, and use only the more extended baselines for flux calibration.

</figure> <figure id="phase_vs_freq_DV13.png">

Phase vs. frequency for DV13 in a data set where this antenna shows evidence of imperfect delay calibration.

</figure> <figure id="amp_vs_time_missing_scans.png">

Amplitude vs. time colored by field for a data set where the final visit to the phase calibrator is missing. We will flag the last set of source data to ensure that each visit to the source is flanked in time by visits to the phase calibrator.

</figure> <figure id="phase_vs_time_DV09.png">

Phase vs. time for DV09 on a problematic day. It may prove problematic to calibrate the data near this discontinuity so we flag data near this time.

</figure> <figure id="amp_vs_uvdist_outliers.png">

Amplitude vs. u-v distance after calibration. Note the outlying data. We track these down using the select (box with green "+") and locate (magnifying glass) features inside plotms and identify several problematic baselines across our data. Note that you cannot make this plot at this point in the guide, these pathologies become evident after calibration, requiring an iterative approach to reduction.

</figure>


Based on this inspection and the other plots we have made, we now flag problematic portions of the data. We break up the flags by reason for flagging in order to illustrate the process. As you reduce your own data it may be more efficient to group flags by data set and make use of the flagcmd command. Except for the "post-calibration" flagging, the inspection plots that we just looked through have already revealed all of the problems that we flag. We structure the guide so that the flagging is grouped in one place.

As before, we may wish to reset our flags before beginning (particularly if one iterates this process) using tflagdata:

# In CASA
tflagdata(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms', mode='unflag', action='apply', flagbackup=F)

Remember that we dropped the flagged data when splitting out after the WVR and Tsys calibration, so this should not undo your "A Priori" flagging of shadowed data, autocorrelations, etc.. In any case this unflagging step is not necessary during the first iteration.

As before, we will accumulate our flagging commands in Python string list variables. However, because the flagging commands will in general depend upon the dataset, we will construct a dictionary indexed by asdm name prefix:

# In CASA
myflagdict = {'uid___A002_X1ff7b0_Xb':[],
              'uid___A002_X207fe4_X3a':[],
              'uid___A002_X207fe4_X3b9':[],
              'uid___A002_X2181fb_X49':[]}

Although we are walking you through only the first dataset, we will accumulate flags for all the datasets.

  • Edge Channels

ALMA's sensitivity decreases near the edge of the baseband and it is often useful to check for a 'roll-off' in sensitivity near the edge of the band. This will appear as a downturn in amplitude as a function of channel near the edge of the window in the uncalibrated data, as a flaring due to increased noise at the spw edges in the calibrated data. It will also be visible in the amplitude part of the bandpass calibration table. Because our FDM spw does not cover the full baseband, we do not see a strong roll off in our data (see <xr id="plotms.uid___A002_X1ff7b0_Xb.3C279.ampvschan.png"/>), where there is only a mild hint of a roll-off at the high end) but we do flag a (very) few channels at the high and low-frequency edge of the data set to be safe.

# In CASA
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms', 
       field='3c279',
       xaxis='channel', yaxis='amp',
       selectdata=T, spw='', 
       avgtime='1e8',avgscan=T,
       coloraxis='baseline',
       antenna='DV11&*',
       ydatacolumn='corrected',
       plotfile='plotms.uid___A002_X1ff7b0_Xb.3C279.ampvschan.png')

We construct the flag commands (same for all datasets:

# In CASA
myflagdict['uid___A002_X1ff7b0_Xb'].append("mode='manual' spw='0:0~7,0:3831~3839'")
myflagdict['uid___A002_X207fe4_X3a'].append("mode='manual' spw='0:0~7,0:3831~3839'")
myflagdict['uid___A002_X207fe4_X3b9'].append("mode='manual' spw='0:0~7,0:3831~3839'")
myflagdict['uid___A002_X2181fb_X49'].append("mode='manual' spw='0:0~7,0:3831~3839'")
  • Problematic Tsys measurements

Above we noted issues with the Tsys measurements for both DV04 and DV12. We flag the affected data. Each of these issues should be visible in the Tsys plots you made above (e.g., see <xr id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.DV02.spw5.CASA3_4.png"/> and <xr id="Uid___A002_X1ff7b0_Xb.tdm.tsys.3c279.PM01.spw5.CASA3_4.png"/>).

We add the flag:

# In CASA
myflagdict['uid___A002_X1ff7b0_Xb'].append("mode='manual' antenna='DV04'")

Note: As noted above DV12 has dodgy Tsys in YY, but is not present in the first SB. Thus, we will add the flags

# In CASA
myflagdict['uid___A002_X207fe4_X3a'].append("mode='manual' antenna='DV12' correlation='YY'")
myflagdict['uid___A002_X207fe4_X3b9'].append("mode='manual' antenna='DV12' correlation='YY'")
myflagdict['uid___A002_X2181fb_X49'].append("mode='manual' antenna='DV12' correlation='YY'")
  • Unreliable Short-Spacing Measurements on Titan

Saturn may contaminate the short u-v spacings from Titan. In any case these often show significant scatter (<xr id="amp_vs_uv_titan_obs.png"/>), so we flag them. There are still enough baselines to determine a good amplitude calibration for each antenna.

# In CASA
myflagdict['uid___A002_X1ff7b0_Xb'].append("mode='manual' field='Titan' uvrange='0~50'")

Note: For different scheduling blocks, this may show up at different uv-distances. We set these individually (you can make the plots if you want to see where we get the values):

# In CASA
myflagdict['uid___A002_X207fe4_X3a'].append("mode='manual' field='Titan' uvrange='0~40'")
myflagdict['uid___A002_X207fe4_X3b9'].append("mode='manual' field='Titan' uvrange='0~50'")
myflagdict['uid___A002_X2181fb_X49'].append("mode='manual' field='Titan' uvrange='0~30'")
  • Delay Issues

DV13 and a few other antennas show signatures of an imperfect delay calibration. This is most easily identified via strong "wrapping" of phase as a function of frequency (see <xr id="phase_vs_freq_DV13.png"/>). Such effects can be calibrated out with mild delay issues largely accounted for by the bandpass solution. The phase wrapping in DV13 seems weak enough that we will trust the calibrations to remove it. For a more extreme example see the CASA guide describing the calibration of NGC3256Band3.

  • Missing Phase Calibrator Observations

As a general rule, we want to be sure that observations of the phase calibrator (3c279) bracket each source observation. Two of the data sets do not include a final phase calibrator observation (see <xr id="amp_vs_time_missing_scans.png"/>) and for those two cases we flag the affected source observations.

# In CASA
myflagdict['uid___A002_X207fe4_X3b9'].append("mode='manual' timerange='00:53:47~01:08:00'")
  • Unexpected Scatter or Discontinuity in the Data

For several antennas we find sudden jumps in the phase of the phase calibrator as a function of time. These are visible in the plots of uncalibrated phase vs. time for single baselines above, and we show an example in <xr id="phase_vs_time_DV09.png"/>. It will not be possible to effectively interpolate the phase between measurements when we see these discontinuities. The safest approach is to flag the source data across these jumps. We do so here (though note that the last two flaggings are borderline cases).

# In CASA
myflagdict['uid___A002_X207fe4_X3a'].append("mode='manual' antenna='DV09' timerange='21:24:09~21:35:35'")
  • Outliers Visible After Calibration

Often issues with the data may become evident after calibration (i.e., after the next few steps that we apply). These data can appear as outliers in diagnostic plots for the calibrated data or even show up in the imaging stages. Once these are identified, best practice is to apply this new flagging then redo the calibration (if the issue is very minor, then re-calibrating may not be necessary).

# In CASA
myflagdict['uid___A002_X207fe4_X3a'].append("mode='manual' timerange='21:18:00~21:22:15'")
myflagdict['uid___A002_X2181fb_X49'].append("mode='manual' antenna='DV01&DV04'")

As before, we use flagcmd to apply our flags. Here we just apply to the first dataset. Our flags are:

# In CASA
myextraflags = myflagdict['uid___A002_X1ff7b0_Xb']

e.g.

CASA <116>: myextraflags
  Out[116]: 
["mode='manual' spw='0:0~7,0:3831~3839'",
 "mode='manual' antenna='DV04'",
 "mode='manual' field='Titan' uvrange='0~50'"]

Go ahead now:

# In CASA
flagcmd(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
        inpmode='cmd', command=myextraflags,
        action='apply', flagbackup=True)

Now that we've applied our flagging, back up the flags as version "User" using flagmanager:

# In CASA
flagmanager(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',mode='save',versionname ='User')

Applying this flagging will remove the most egregious pathologies from the data. We are now ready to calibrate the data.

Bandpass Calibration

<figure id="plotms_phase_vs_freq_example.png">

Phase vs. frequency for the bandpass calibrator, 3c279 in the first data set. We plot all baselines with DV02, averaged over time, and show only the 'XX' correlation.

</figure> <figure id="Uid_A002_X1ff7b0_Xb-phasecont.png">

Phase vs. time for the bandpass calibrator, 3c279. Averaged over channel. Only baselines with antenna DV02, and corr='XX'

</figure>

<figure id="plotcal.uid___A002_X1ff7b0_Xb.bpphase.gcal.png">

Short interval phase vs. time solution carried out and applied during bandpass calibration, here for the first data set. This solution removes any systematic variations in phase vs. time.

</figure> <figure id="plotbandpass.uid___A002_X1ff7b0_Xb.bandpass.DV02.spw0.t1.png">

Bandpass solutions for the first set of antennas and the first data set.

</figure> <figure id="plotbandpass.uid___A002_X1ff7b0_Xb.bandpass.DV09.spw0.t1.png">

Bandpass solutions for the second set of antennas and the first data set.

</figure> <figure id="plotbandpass.uid___A002_X1ff7b0_Xb.bandpass.PM02.spw0.t1.png">

Bandpass solutions for the final set of antennas and the first data set.

</figure>

We begin by calibrating the phase and amplitude response of each antenna as a function of frequency, called "bandpass calibration." We have already seen that the data contain smooth but systematic variations in both phase and amplitude as a function of frequency. We can see this again in a more compact form by plotting phase as a function of frequency for all baselines associated with each antenna (<xr id="plotms_phase_vs_freq_example.png"/>).

# In CASA
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms', 
       xaxis='freq', yaxis='phase', 
       selectdata=True, field='3c279', correlation='XX',
       avgtime='1e8', avgscan=T, antenna='*&*',
       coloraxis='baseline', iteraxis='antenna')

Each plot shows phase as a function of frequency for all baselines with one antenna for 3c279. We plot only the 'XX' correlation, colorizing by baseline. With iteraxis set to antenna the green arrows at the bottom of plotms will cycle through antennas. By using avgscan and a large avgtime we average all scans and integrations.

The phase (and amplitude) also varies as a function of time, as we saw before. Here are the similar plots for phase vs. time (see <xr id="Uid_A002_X1ff7b0_Xb-phasecont.png"/>).

# In CASA
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms', 
       xaxis='time', yaxis='phase', 
       selectdata=True, field='3c279', 
       spw='0:1200~1300', antenna='*&*',correlation='XX',
       avgchannel='1000',  avgscan=T, 
       coloraxis='baseline', iteraxis='antenna')

<xr id="Uid_A002_X1ff7b0_Xb-phasecont.png"/> shows that the phase varies with time. We need to take this temporal variation into account when we solve for the frequency variations. Therefore we carry out the bandpass calibration in two steps. First, we use gaincal to solve for the variation of phase as a function of time for 3c279 on very short timescales. We set gaincal to derive a separate phase solution for each antenna every integration by setting solint to 'int'. We solve, averaging together only a small fraction of the total bandpass (channels 1100-1300) to avoid the effects of the phase vs. frequency behavior. We will then apply this solution to remove time-dependent behavior when we solve for the frequency response of the antennas with bandpass.

An integration is the smallest time quantum of observation in the data, usually a few seconds. 
You can check the integration length for each scan in listobs. 
#In CASA
gaincal(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
        selectdata=T,field='3c279',spw='0:1100~1300',
        caltable='uid___A002_X1ff7b0_Xb.bpphase.gcal',
        solint='int',refant='DV11',calmode='p')

We can plot these using plotcal (since DV04 is flagged we can leave it out of the plot):

#In CASA
plotcal(caltable='uid___A002_X1ff7b0_Xb.bpphase.gcal',
        yaxis='phase',plotrange=[-1,-1,-180,180],
        iteration='antenna',subplot=521,
        antenna='DV02,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03',
        figfile='plotcal.uid___A002_X1ff7b0_Xb.bpphase.gcal.png')

See <xr id="plotcal.uid___A002_X1ff7b0_Xb.bpphase.gcal.png"/> to the right. Phase coherence looks good!

Now we use bandpass to solve for the frequency response of each antenna. To do this, we average all data in time by setting solint to 'inf' (that is, 'infinite'). We allow combination across scans and the different field IDs found for 3c279 by setting combine to "scan,field". We apply the phase vs. time calibration that we just derived on-the-fly using the parameter "gaintable".

bandpass(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
         field='3c279',
         gaintable='uid___A002_X1ff7b0_Xb.bpphase.gcal',
         caltable='uid___A002_X1ff7b0_Xb.bandpass.bcal',
         bandtype='B',
         solint='inf',combine='scan,field',solnorm=T,refant='DV11',
         minblperant=3,minsnr=2,fillgaps=62)

in these calls:

  • caltable specifies the output calibration table
  • gaintable specifies any calibration tables to be applied "on the fly" to the data before solving.
  • solint sets the time interval for which solutions are derived for each antenna.
  • refant set the reference antenna, here DV11, which is defined to have zero correction by construction.
  • calmode 'p' sets gaincal to calibrate the phase only, other options are 'a'mplitude or 'ap' - amplitude and phase.
  • minblperant sets the minimum baselines required per antenna for a successful solution.
  • minsnr sets the minimum signal-to-noise ratio required for a successful solution.
  • bandtype here 'B' tells bandpass to solve for the phase and frequency response of each antenna in each channel, averaging data in time across the solution interval.
  • fillgaps tells bandpass to interpolate across channel gaps 1 channel wide.
  • solnorm tells bandpass to normalize the bandpass amplitude and phase corrections to have magnitude unity. The absolute scale of the calibration will come from our later gaincal solutions.

Do not worry about the message "Insufficient unflagged antennas" when running the bandpass task. This indicates that bandpass is failing on the flagged edge channels, which is expected.

It is now a good idea to plot both sets of solutions to look for irregularities, especially:

  • discontinuities in the phase vs. time solution
  • rapid wrapping of phase in either phase vs. time or bandpass solution
  • large roll-off in the amplitude response near the band edge in the bandpass solution
  • large scatter in any solution.

We loop through and using analysis utils, again generating .png files of each calibration. As the bandpass plots take a while you may want to go have a cup of coffee and inspect them using your favorite image viewer. Otherwise, switch the interactive parameter to True to see them in real time instead.

#In CASA
os.system('rm -rf cal_plots/uid___A002_X1ff7b0_Xb.bandpass.png')
au.plotbandpass2(caltable='uid___A002_X1ff7b0_Xb.bandpass.bcal',
                 field='',xaxis='freq',yaxis='both',
                 figfile='cal_plots/uid___A002_X1ff7b0_Xb.bandpass.png',
                 showatm=True,interactive=False,subplot=42)

You can see the plots produced by this in <xr id="plotbandpass.uid___A002_X1ff7b0_Xb.bandpass.DV02.spw0.t1.png"/>, <xr id="plotbandpass.uid___A002_X1ff7b0_Xb.bandpass.DV09.spw0.t1.png"/> and <xr id="plotbandpass.uid___A002_X1ff7b0_Xb.bandpass.PM02.spw0.t1.png"/>.

Gain (Phase and Amplitude) Calibration

<figure id="Antennae-TitanLine.png">

Uncalibrated amplitude vs. channel plot for the flux calibrator, Titan (uid___A002_X1ff7b0_Xb dataset). Averaged over time, corr='XX', and colorized by baseline.

</figure> <figure id="uid___A002_X1ff7b0_Xb.intphase.png">

Plotcal for .intphase solutions. Note only minor sub-scan phase variations are present.

</figure> <figure id="uid___A002_X1ff7b0_Xb.scanphase.png">

Plotcal for .scanphase solutions. This is what we will apply to our data.

</figure> <figure id="uid___A002_X1ff7b0_Xb.fluxcal.amp.png">

Plotcal for .flux.cal/tt> solutions. These gain amplitudes have been adjusted by fluxscale to give the correct flux densities for the secondary calibrator 3C279.

</figure>

The bandpass calibration will account for the phase and amplitude response of our antennas as a function of frequency. We now solve for the absolute flux scale of the data by referencing to Titan and then calibrate the phase and amplitude behavior of the antennas as a function of time.

Before using Titan to set the flux, there is an important systematic to account for. When we looked at the integrated spectra of our targets above, remember that Titan showed a whopping spectral line, in fact the same CO(3-2) line that we wish to observe in the Antennae. We will set the flux of Titan (and thus all of our data) by referencing to a model in casa that does not account for this line. Therefore we need to flag the part of the Titan observations contaminated by the line before we calibrate (you can see the affected channel range in <xr id="Antennae-TitanLine.png"/>). We run the following additional flagging step (again using the new tflagdata task, which is faster than flagdata and undergoing testing this cycle):

# in CASA
tflagdata(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',flagbackup=F, 
          field='Titan',spw='0:1100~1700',
          mode='manual',action='apply',savepars=True)

flagmanager(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',mode='save',versionname='Calibration')

Next, we will use the setjy task to read the predicted complex visibilities for Titan into the MODEL column of each data set.

# in CASA
setjy(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',field='Titan',
      usescratch=False,scalebychan=True,
      standard='Butler-JPL-Horizons 2010')

By setting usescratch=False we are making use of the new scratchless mode of calibration (this mode is new, and can have problems with complicated models or MS structure, but we have only one spectral window and are not using a complicated model).

setjy will output the flux of Titan to the CASA logger and it is worth recording this information. The flux of Titan at these frequencies is about 2.9 Jy. For example, for dataset uid___A002_X1ff7b0_Xb.wvrtsys.ms:

  INFO setjy	       Titan (fld ind 1) spw 0  [I=2.8614, Q=0, U=0, V=0] Jy, (JPL-Butler Solar System Object)

We can use plotms to take a look at the Titan model

# in CASA
plotms(vis ='uid___A002_X1ff7b0_Xb.wvrtsys.ms', xaxis='uvdist', yaxis='amp',
       ydatacolumn='model', field='Titan',avgtime='1e8',
       plotfile='plotms.uid___A002_X1ff7b0_Xb.Titan.modelamp.png')
#
plotms(vis ='uid___A002_X1ff7b0_Xb.wvrtsys.ms', xaxis='uvdist', yaxis='phase',
       ydatacolumn='model', field='Titan',avgtime='1e8')

You can see the fall-off of the model visibilities with uv-distance (it is resolved), but the phases are zero (it is symmetric).

Next we will run a short-solution interval gaincal to solve for phase variation on short timescales during observations of our two calibrators, with solint set to "int". By applying this on-the-fly, we can remove any decorrelation in the data due to phase scatter when we solve for the amplitude calibration. However, there is no benefit to using this short-timescale solution to calibrate the source because we only have information on the gain during calibrator visits (though see the Imaging portion of this guide). Instead we will solve for the gains to apply to the source using a second run of gaincal longer solint.

First, for the calibrators using solint='int':

# in CASA
os.system('rm -rf uid___A002_X1ff7b0_Xb.intphase.gcal')
gaincal(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
        caltable='uid___A002_X1ff7b0_Xb.intphase.gcal',
        gaintable='uid___A002_X1ff7b0_Xb.bandpass.bcal', 
        calmode='p',solint='int',minsnr=2.0,minblperant=4,
        field='Titan,3c279',spw='0:40~3800',refant='DV11')

Note that we pre-apply only the bandpass solution and not the throw-away initial phase-cal.

Now we derive the longer timescale phase calibration table using solint='inf', but not allowing scan combination (so we get a single solution per scan). This calibration has higher signal to noise due to combining more data, and for the purposes of correcting the source, it is just as precise as the short timescale solution.

# in CASA
os.system('rm -rf uid___A002_X1ff7b0_Xb.scanphase.gcal')
gaincal(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
        caltable='uid___A002_X1ff7b0_Xb.scanphase.gcal',
        gaintable='uid___A002_X1ff7b0_Xb.bandpass.bcal', 
        calmode='p',solint='inf',minsnr=2.0,minblperant=4,
        field='Titan,3c279',spw='0:40~3800',refant='DV11')

Now we apply the short-timescale phase solution and carry out a scan length (solint='inf',combine=) calibration of the data for amplitude and phase (calmode='ap'):

# in CASA
os.system('rm -rf uid___A002_X1ff7b0_Xb.amp.cal')
gaincal(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
        caltable='uid___A002_X1ff7b0_Xb.amp.cal',
        gaintable=['uid___A002_X1ff7b0_Xb.bandpass.bcal',
                   'uid___A002_X1ff7b0_Xb.intphase.gcal'],
        calmode='ap',solint='inf',minblperant=4,
        field='Titan,3c279',spw='0:40~3800',refant='DV11')

This "amp.cal" solution gives us the amplitude variations as a function of time, but they are not yet pinned to a realistic scale except in the case of Titan, where we have solved using the model input by setjy. We will set the flux of our secondary calibrator 3c279 with reference to Titan using fluxscale:

# in CASA
os.system('rm -rf uid___A002_X1ff7b0_Xb.flux.cal')
myfluxes=fluxscale(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
                   caltable='uid___A002_X1ff7b0_Xb.amp.cal',
                   fluxtable='uid___A002_X1ff7b0_Xb.flux.cal',
                   reference='Titan',
                   transfer='3c279')

where we capture the return values (the solved-for fluxes of the transfer sources) in the variable myfluxes.

CASA <164>: myfluxes
  Out[164]: 
{'0': {'fieldName': '3c279',
       'fluxd': array([ 10.42025463]),
       'fluxdErr': array([ 0.04186019]),
       'numSol': array([20], dtype=int32)},
 'freq': array([  3.44845586e+11]),
 'spwID': array([0], dtype=int32),
 'spwName': array([''], 
      dtype='|S1')}

The new correctly-scaled flux table ".flux.cal" replaces the previous ".amp.cal" table as the correct amplitude calibration table to apply to the data, i.e., the ".flux.cal" contains both the time variability of the amplitude solved for in ".amp.cal" and the correct flux scaling set with fluxscale.

Fluxscale will output the derived flux for 3c279 to the CASA logger as well as to the return value. This information is worth noting. We find that the flux of 3c279 is 10.42 Jy for the first dataset. This value agrees within 10% with the most recent 0.850 millimeter measurements from the SMA calibrator list [1] : (01 Jul 2011, SMA 9.75 ± 0.49).

Now we plot the final phase and amplitude calibration with {[plotms}}. A well-behaved calibration table will show smooth variations as a function of time. Sudden jumps or wild variations among the antenna amplitude gains should prompt further investigation and possibly additional flagging.

# in CASA
plotcal(caltable='uid___A002_X1ff7b0_Xb.intphase.gcal',
        xaxis='time',yaxis='phase',
        antenna='DV02,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03',
        iteration='antenna',subplot=521,fontsize=6.0,
        plotrange=[0,0,-180,180],
        figfile='uid___A002_X1ff7b0_Xb.intphase.png')
#
plotcal(caltable='uid___A002_X1ff7b0_Xb.scanphase.gcal',
        xaxis='time',yaxis='phase',
        antenna='DV02,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03',
        iteration='antenna',subplot=521,fontsize=6.0,
        plotrange=[0,0,-180,180],
        figfile='uid___A002_X1ff7b0_Xb.scanphase.png')
#
plotcal(caltable='uid___A002_X1ff7b0_Xb.flux.cal',
        xaxis='time',yaxis='amp',
        antenna='DV02,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03',
        iteration='antenna',subplot=521,fontsize=6.0,
        figfile='uid___A002_X1ff7b0_Xb.fluxcal.amp.png')

You can see these to the right in <xr id="uid___A002_X1ff7b0_Xb.intphase.png"/>, <xr id="uid___A002_X1ff7b0_Xb.scanphase.png"/>, and <xr id="uid___A002_X1ff7b0_Xb.fluxcal.amp.png"/> respectively.

Apply the Final Calibrations

Now we will use applycal to apply the bandpass, phase, and amplitude calibration tables that we generated in the previous sections to the data. We apply the solutions separately to the bandpass and secondary ("phase") calibrator 3c279, the flux calibrator Titan, and the target source. In most data sets, the bandpass and secondary calibrator will not be the same and this step would include one additional applycal.

#In CASA
applycal(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
         field='3c279',
         gaintable=['uid___A002_X1ff7b0_Xb.bandpass.bcal',
                    'uid___A002_X1ff7b0_Xb.intphase.gcal',
                    'uid___A002_X1ff7b0_Xb.flux.cal'],
         interp=['nearest','nearest','nearest'],
         gainfield=['3c279','3c279','3c279'],
         flagbackup=False,calwt=False)
#
applycal(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
         field='Titan',
         gaintable=['uid___A002_X1ff7b0_Xb.bandpass.bcal',
                    'uid___A002_X1ff7b0_Xb.intphase.gcal',
                    'uid___A002_X1ff7b0_Xb.flux.cal'],
         interp=['nearest','nearest','nearest'],
         gainfield=['3c279','Titan','Titan'],
         flagbackup=False,calwt=False)
#
applycal(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
         field='NGC*',
         gaintable=['uid___A002_X1ff7b0_Xb.bandpass.bcal',
                    'uid___A002_X1ff7b0_Xb.scanphase.gcal',
                    'uid___A002_X1ff7b0_Xb.flux.cal'],
         interp=['nearest','linear','linear'],
         gainfield=['3c279','3c279','3c279'],
         flagbackup=False,calwt=False)

Here:

  • vis and field specify the measurement set and field to calibrate.
  • gaintable specifies the tables to apply to the data. There may be several tables applied all at once, here we apply the bandpass, phase, and flux calibrations.
  • interp specifies the type of interpolation used to match calibration tables to the data. If there are several gaintables then interp may be either a single value (e.g., "linear" or "nearest") or a list of values with size equal to the list of gaintables. In the case where interp is a list, applycal will match each element to the corresponding gaintable (e.g., first gaintable with first interp parameter).
  • gainfield specifies field from which to draw the calibration. As with interp, this can be a list of size matched to gaintable, so that the first element of gainfield will be the field used for the first table. For example, in the above commands the bandpass calibration (the first table) will always be applied from '3c279' (the first gainfield).
  • calwt indicates that the weights, which were derived from the Tsys measurements, should also be calibrated. Note that calwt is True by default.

Final Data Inspection

<figure id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.timeamp.png">

Calibrated amplitude vs. time plot for 3c279 colored by baseline. Note residual baseline-based offsets.

</figure>

<figure id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.chanphase.png">

Calibrated phase vs. channel plot for 3c279 colored by baseline.

</figure>

<figure id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.baseavg.ampfreq.png">

Calibrated amplitude vs. frequency averaged over all baselines and times. Our average calibration is good.

</figure>

<figure id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.Antennae.ampfreq.png">

Calibrated amplitude vs. frequency for the Antennae, clearly showing our CO(3-2) line.

</figure>

Once calibrations are applied, it is important to go back and inspect the calibrated data. New problematic antennas or baselines may be visible after calibration. Repeat the steps above, focusing on the CORRECTED data column. Bear in mind that for any point source calibrators we now expect to find phase scattering around zero and to find flat amplitudes as a function of u-v distance. Look for outliers and other signatures of problematic data. As a general rule, you will want to incorporate these data into your overall flagging script then rerun the whole calibration process, so that reduction is iterative. If the data only represent a minor problem, however, it may not be terribly harmful to flag them after the fact so that they do not interfere with imaging but trust that the calibrations are mostly unaffected.

As an example of this inspection, we cycle through the corrected amplitudes and phases of 3c279 and Titan as a function u-v distance, to check that the phases are close to zero and the amplitudes are constant.

# In CASA
# First 3C279
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
       xaxis='uvdist', yaxis='amp', 
       ydatacolumn='corrected', field='3c279',
       averagedata=True, avgchannel='3840', avgtime='',
       avgscan=F, avgbaseline=F, coloraxis='baseline')
#
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
       xaxis='time', yaxis='amp',
       ydatacolumn='corrected', field='3c279',
       averagedata=True, avgchannel='3840', avgtime='',
       avgscan=F, avgbaseline=F, coloraxis='baseline',
       plotfile='plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.timeamp.png')
#
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
       xaxis='freq', yaxis='amp',
       ydatacolumn='corrected', field='3c279',avgtime='1e8',
       avgchannel='', avgscan=F, avgbaseline=F, coloraxis='baseline')
#
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
       xaxis='channel', yaxis='phase',
       ydatacolumn='corrected', field='3c279',avgtime='1e8',
       avgchannel='', avgscan=F, avgbaseline=F, coloraxis='baseline',
       plotfile='plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.chanphase.png')
#
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
       xaxis='time', yaxis='phase',
       ydatacolumn='corrected', field='3c279',
       avgchannel='3840', avgscan=F, avgbaseline=F, coloraxis='baseline')
#
# And now Titan
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
       xaxis='uvdist', yaxis='amp',
       ydatacolumn='corrected', field='Titan',
       averagedata=True, avgchannel='3840', avgtime='',
       avgscan=F, avgbaseline=F, coloraxis='baseline')
#
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
       xaxis='uvdist', yaxis='phase',
       ydatacolumn='corrected', field='Titan',
       averagedata=True, avgchannel='3840', avgtime='',
       avgscan=F, avgbaseline=F, coloraxis='baseline')
#
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
       xaxis='freq', yaxis='amp',
       ydatacolumn='corrected', field='Titan',avgtime='1e8',
       avgchannel='', avgscan=F, avgbaseline=F, coloraxis='baseline')

In <xr id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.timeamp.png"/> and <xr id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.chanphase.png"/> we show the amp vs. time and phase vs. channel plots for 3c279 for the uid___A002_X1ff7b0_Xb dataset, colored by baseline. These are generally well-calibrated (especially in phase) but there are still some minor residual baseline-based amplitude offsets.

We can plot the data averaged over baselines to show our mean calibration is good.

# In CASA
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
       xaxis='freq', yaxis='amp',
       ydatacolumn='corrected', field='3c279',avgtime='1e8',
       avgchannel='', avgscan=F, avgbaseline=T,
       coloraxis='corr',
       plotfile='plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.baseavg.ampfreq.png')
#
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
       xaxis='freq', yaxis='amp',
       ydatacolumn='corrected', field='Titan',avgtime='1e8',
       avgchannel='', avgscan=F, avgbaseline=T,
       coloraxis='corr')

The first of these is shown in <xr id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.3c279.baseavg.ampfreq.png"/>

Finally we can use plotms to examine the corrected amplitude and phase of Antennae galaxies as a function of time and uv-distance:

# In CASA
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
       xaxis='uvdist', yaxis='amp',
       ydatacolumn='corrected', field='NGC*',
       averagedata=True, avgchannel='3840', avgtime='',
       avgscan=F, avgbaseline=F, coloraxis='baseline')
#
plotms(vis='uid___A002_X1ff7b0_Xb.wvrtsys.ms',
       xaxis='freq', yaxis='amp',
       ydatacolumn='corrected', field='NGC*',
       avgtime='1e8', avgscan=T, avgbaseline=F,
       coloraxis='baseline',
       plotfile='plotms.uid___A002_X1ff7b0_Xb.wvrtsys.Antennae.ampfreq.png')

The last of these is shown in <xr id="plotms.uid___A002_X1ff7b0_Xb.wvrtsys.Antennae.ampfreq.png"/>.

Processing the other Northern Mosaic datasets

In order to proceed to produce a final concatenated dataset, we need to process the remainder of the Antennae North blocks. If you do not have the time (around 30min, possibly more) or inclination, you can proceed directly to the AntennaeBand7 North Imaging 3.4 guide and start with an already processed and merged MS. Or follow the instructions in this session (and the next) to create your own.

We first define a Python list containing the base names for the other Northern Mosaic datasets:

# In CASA
basename_north_ext=["uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9","uid___A002_X2181fb_X49"]

This will be used to loop over all the operations on these MSes, for example:

# In CASA
for asdm in basename_north_ext:
    print 'asdm = '+asdm

Note that after cutting and pasting a 'for' loop like this you often have to press return twice to execute. You may also want to take care to paste a line at a time if you are having trouble copy and pasting. Even better, you can use "cpaste" to paste blocks of code. To do so type "cpaste" at the CASA prompt, paste your commands, and then type "--" and hit return on the final (otherwise empty) line. This should look something like this:


CASA <8>: cpaste
Pasting code; enter '--' alone on the line to stop.
:basename_north=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a","uid___A002_X207fe4_X3b9",
:     "uid___A002_X2181fb_X49"]
:
:for asdm in basename_north:
:    print asdm
:--
uid___A002_X1ff7b0_Xb
uid___A002_X207fe4_X3a
uid___A002_X207fe4_X3b9
uid___A002_X2181fb_X49

CASA <9>: 

cpaste should be much more robust than copying-and-pasting directly into the shell but if you have trouble, just carefully paste one line at a time directly into CASA and hit return until the desired command executes.

We will break the commands we loop over into two, one loop (mandatory) for operations that do something, and a second (optional) that make plots or listings to look over.

Now we set up some variables and lists (analogous to what we did before manually)

#In CASA
basename_north_ext=["uid___A002_X207fe4_X3a",
                    "uid___A002_X207fe4_X3b9",
                    "uid___A002_X2181fb_X49"]

Next, this loop takes us from the split a-priori calibrated data through to just before final splitting:

#In CASA
for asdm in basename_north_ext:
    #
    print "Apply extra flags to "+asdm
    myextraflags = myflagdict[asdm]
    flagcmd(vis=asdm+'.wvrtsys.ms',
            inpmode='cmd', command=myextraflags,
            action='apply', flagbackup=True)
    #
    print "Saving flags for "+asdm
    flagmanager(vis=asdm+'.wvrtsys.ms',mode='save',versionname ='User')
    #
    print "Running a short solution interval phase calibration for "+asdm
    os.system('rm -rf '+asdm+'.bpphase.gcal')
    gaincal(vis = asdm+'.wvrtsys.ms',
            selectdata=T,field = '3c279',spw = '0:1100~1300',
            caltable = asdm+'.bpphase.gcal',
            solint = 'int',refant = 'DV11',calmode='p')
    #
    print "Running a bandpass calibration for "+asdm
    os.system('rm -rf '+asdm+'.bandpass.bcal')
    bandpass(vis=asdm+'.wvrtsys.ms',
             field = '3c279',
             gaintable = asdm+'.bpphase.gcal',
             caltable = asdm+'.bandpass.bcal',
             bandtype='B',
             solint = 'inf',combine = 'scan,field', solnorm=T,refant = 'DV11',
             minblperant=3,minsnr=2,fillgaps=62)
    #
    print "Flagging CO(3-2) in Titan for "+asdm
    tflagdata(vis=asdm+'.wvrtsys.ms',flagbackup=F, 
              field='Titan',spw='0:1100~1700',
              mode='manual',action='apply',savepars=True)
    print "Saving Titan channel flags for "+asdm
    flagmanager(vis=asdm+'.wvrtsys.ms',mode='save',versionname='Calibration')
    #
    print "Reading model for Titan into "+asdm
    setjy(vis=asdm+'.wvrtsys.ms',field='Titan',
          usescratch=False,scalebychan=True,
          standard='Butler-JPL-Horizons 2010')
    #
    print "Carrying out short timescale phase solution for "+asdm
    os.system('rm -rf '+asdm+'.intphase.gcal')
    gaincal(vis=asdm+'.wvrtsys.ms',
            caltable=asdm+'.intphase.gcal',
            gaintable=asdm+'.bandpass.bcal', 
            calmode='p',solint='int',minsnr=2.0,minblperant=4,
            field='Titan,3c279',spw='0:40~3800',
            refant='DV11')
    #
    print "Carrying out longer timescale phase solution for "+asdm
    os.system('rm -rf '+asdm+'.scanphase.gcal')
    gaincal(vis=asdm+'.wvrtsys.ms',
            caltable=asdm+'.scanphase.gcal',
            gaintable=asdm+'.bandpass.bcal', 
            calmode='p',solint='inf',minsnr=2.0,minblperant=4,
            field='Titan,3c279',spw='0:40~3800',refant='DV11')
    #
    print "Solving for longer (scan) interval amplitude solution for "+asdm
    os.system('rm -rf '+asdm+'.amp.cal')
    gaincal(vis=asdm+'.wvrtsys.ms',
            gaintable=[asdm+'.bandpass.bcal',asdm+'.intphase.gcal'],
            caltable=asdm+'.amp.cal',
            calmode='ap',solint='inf',minblperant=4,
            field='Titan,3c279',spw='0:40~3800',refant='DV11')
    #
    print "Scaling amplitude calibration to match Titan for "+asdm
    os.system('rm -rf '+asdm+'.flux.cal')
    fluxscale(vis=asdm+'.wvrtsys.ms',
              caltable=asdm+'.amp.cal',
              fluxtable=asdm+'.flux.cal',
              reference='Titan',
              transfer='3c279')
    #
    print "Applying calibrations for "+asdm
    applycal(vis=asdm+'.wvrtsys.ms',field='3c279',
             gaintable=[asdm+'.bandpass.bcal',
                        asdm+'.intphase.gcal',
                        asdm+'.flux.cal'],
             interp=['nearest','nearest','nearest'],
             gainfield=['3c279','3c279','3c279'],
             flagbackup=False,calwt=False)
    #
    applycal(vis=asdm+'.wvrtsys.ms',field='Titan',
             gaintable=[asdm+'.bandpass.bcal',
                        asdm+'.intphase.gcal',
                        asdm+'.flux.cal'],
             interp=['nearest','nearest','nearest'],
             gainfield=['3c279','Titan','Titan'],
             flagbackup=False,calwt=False)
    #
    applycal(vis=asdm+'.wvrtsys.ms',field='NGC*',
             gaintable=[asdm+'.bandpass.bcal',
                        asdm+'.scanphase.gcal',
                        asdm+'.flux.cal'],
             interp=['nearest','linear','linear'],
             gainfield=['3c279','3c279','3c279'],
             flagbackup=False,calwt=False)

Optional Plotting and Listing Loop

If you want to make the plots and listings we did for the first dataset in our walkthrough, then use cpaste to execute the following loop:

#In CASA
for asdm in basename_north_ext:
    os.system('rm '+asdm+'.listobs.txt')
    listobs(vis=asdm+'.ms', listfile=asdm+'.listobs.txt', verbose=True)
    #
    print "Antenna configuration for : "+asdm
    os.system('rm '+asdm+'.plotants.png')
    plotants(vis=asdm+'.ms', figfile=asdm+'.plotants.png')
    clearstat()
    #
    print "Plotting Tsys vs. time for "+asdm
    os.system('rm '+asdm+'.tsys_vs_time.page1.png')
    plotcal(caltable=asdm+'.tdm.tsys', 
	    xaxis="time",yaxis="tsys",
	    spw='5:50~50',plotsymbol=".", subplot=421,
	    antenna='0~7',iteration='antenna',
            showgui=False,figfile=asdm+'.tsys_vs_time.page1.png',
	    fontsize=7.0)    
    #
    os.system('rm '+asdm+'.tsys_vs_time.page2.png')
    plotcal(caltable=asdm+'.tdm.tsys', 
	    xaxis="time",yaxis="tsys",
	    spw='5:50~50',plotsymbol=".", subplot=421, 
	    antenna='8~15', iteration='antenna', 
	    showgui=False,figfile=asdm+'.tsys_vs_time.page2.png',
	    fontsize=7.0)
    #
    tsysfields=['3c279','Titan','NGC4038*']
    os.system('rm -rf cal_plots/Tsys_plots/'+asdm+'.tdm.tsys*')
    caltable=asdm+'.tdm.tsys'
    for field in tsysfields:
        au.plotbandpass2(caltable=caltable,yaxis='amp',field=field,xaxis='freq',
                         showatm=True,overlay='time',
                         figfile='cal_plots/Tsys_plots/'+caltable+'.'+field,buildpdf=False,
                         interactive=False,chanrange='8~120',subplot=42)
    #
    os.system('rm '+asdm+'.wvrtsys.listobs.txt')
    listobs(vis=asdm+'.wvrtsys.ms', listfile=asdm+'.wvrtsys.listobs.txt', verbose=True)
    #
    os.system('rm -rf cal_plots/'+asdm+'.bandpass.png')
    au.plotbandpass2(caltable=asdm+'.bandpass.bcal',
                     field='',xaxis='freq',yaxis='both',
                     figfile='cal_plots/'+asdm+'.bandpass.png',
                     showatm=True,interactive=False,subplot=42)
    #
    print "Plotting solutions for "+asdm
    os.system('rm '+asdm+'.intphase.png')
    plotcal(caltable=asdm+'.intphase.gcal',
            xaxis='time',yaxis='phase',
            antenna='DV02,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03',
            iteration='antenna',subplot=521,fontsize=6.0,
            plotrange=[0,0,-180,180],showgui=False,
            figfile=asdm+'.intphase.png')
    #
    os.system('rm '+asdm+'.scanphase.png')
    plotcal(caltable=asdm+'.scanphase.gcal',
            xaxis='time',yaxis='phase',
            antenna='DV02,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03',
            iteration='antenna',subplot=521,fontsize=6.0,
            plotrange=[0,0,-180,180],showgui=False,
            figfile=asdm+'.scanphase.png')
    #
    os.system('rm '+asdm+'.fluxcal.amp.png')
    plotcal(caltable=asdm+'.flux.cal',
            xaxis='time',yaxis='amp',
            antenna='DV02,DV06,DV07,DV08,DV09,DV10,DV11,PM01,PM02,PM03',
            iteration='antenna',subplot=521,fontsize=6.0,showgui=False,
            figfile=asdm+'.fluxcal.amp.png')
    #
    # Final plotms
    print "Plotting final calibrated data for "+asdm
    os.system('rm plotms.'+asdm+'.wvrtsys.3c279.timeamp.png')
    plotms(vis=asdm+'.wvrtsys.ms',
           xaxis='time', yaxis='amp',
           ydatacolumn='corrected', field='3c279',
           averagedata=True, avgchannel='3840', avgtime='',
           avgscan=F, avgbaseline=F, coloraxis='baseline',
           plotfile='plotms.'+asdm+'.wvrtsys.3c279.timeamp.png')
    #
    os.system('rm plotms.'+asdm+'.wvrtsys.3c279.chanphase.png')
    plotms(vis=asdm+'.wvrtsys.ms',
           xaxis='channel', yaxis='phase',
           ydatacolumn='corrected', field='3c279',avgtime='1e8',
           avgchannel='', avgscan=F, avgbaseline=F, coloraxis='baseline',
           plotfile='plotms.'+asdm+'.wvrtsys.3c279.chanphase.png')
    #
    os.system('rm plotms.'+asdm+'.wvrtsys.3c279.baseavg.ampfreq.png')
    plotms(vis=asdm+'.wvrtsys.ms',
           xaxis='freq', yaxis='amp',
           ydatacolumn='corrected', field='3c279',avgtime='1e8',
           avgchannel='', avgscan=F, avgbaseline=T,
           coloraxis='corr',
           plotfile='plotms.'+asdm+'.wvrtsys.3c279.baseavg.ampfreq.png')
    #
    os.system('rm plotms.'+asdm+'.wvrtsys.Titan.baseavg.ampfreq.png')
    plotms(vis=asdm+'.wvrtsys.ms',
           xaxis='freq', yaxis='amp',
           ydatacolumn='corrected', field='Titan',avgtime='1e8',
           avgchannel='', avgscan=F, avgbaseline=T,
           coloraxis='corr',
           plotfile='plotms.'+asdm+'.wvrtsys.Titan.baseavg.ampfreq.png')
    #
    os.system('rm plotms.'+asdm+'.wvrtsys.Antennae.ampfreq.png')
    plotms(vis=asdm+'.wvrtsys.ms',
           xaxis='freq', yaxis='amp',
           ydatacolumn='corrected', field='NGC*',
           avgtime='1e8', avgscan=T, avgbaseline=F,
           coloraxis='baseline',
           plotfile='plotms.'+asdm+'.wvrtsys.Antennae.ampfreq.png')

Split and Concatenate Data for Northern Mosaic

The individual data sets are now calibrated. We can safely split out the calibrated data for our science target and drop the calibrators. As we do so, we will smooth the data in frequency, averaging together groups of 23 channels by setting width=23 in split. The new data will have a channel width corresponding to about ~10 km/s, very similar to the SMA data being verified. The factor of >20 drop in data volume will also make the imaging steps much more tractable.

#In CASA
basename_north=["uid___A002_X1ff7b0_Xb","uid___A002_X207fe4_X3a",
                "uid___A002_X207fe4_X3b9","uid___A002_X2181fb_X49"]
#
for asdm in basename_north:
    os.system('rm -rf '+asdm+'.cal.ms')
    split(vis = asdm+'.wvrtsys.ms',outputvis = asdm+'.cal.ms',
          field = 'NGC*',spw='0',width=23, keepflags=False)
    os.system('rm -rf '+asdm+'.cal.listobs.txt')
    listobs(asdm+'.cal.ms',listfile=asdm+'.cal.listobs.txt')

For convenience we concatenate all data for the Northern Mosaic into a single big MS using the concat task.

Before we do this, we'll take a brief aside to remove Pointing information from the calibrated data. Normally, the pointing information would apply important corrections to be used while imaging the data. However, some aspects of this are still under development and the pointing information in these data interacts poorly with CASA. We will remove the pointing information using the CASA toolkit Table tool (tb). This kind of operation is dangerous and should not be a regular feature of your CASA reduction.

# In CASA 
for asdm in basename_north:
    print "Manually removing pointing table from "+asdm+".cal.ms ... Please be careful!"
    tb.open(asdm+'.cal.ms/POINTING',nomodify=False)
    a = tb.rownumbers()
    tb.removerows(a)
    tb.close()

And finally we run concat

# In CASA
cal_north_vis = [vis+'.cal.ms' for vis in basename_north]
#
os.system('rm -rf Antennae_North.cal.ms')
concat(vis=cal_north_vis, concatvis='Antennae_North.cal.ms', timesort=T)

The syntax used to construct the 'cal_north_vis' variable loops over basename_north and makes a list after adding '.cal.ms' to each member. To see the list 'print cal_north_vis'.

The MS Antennae_North.cal.ms now contains all our calibrated data for the North mosaic, and is ready for imaging.

Continue on to Imaging of the Science Target

Now you can continue on to the imaging guide.

Last checked on CASA Version 3.4.0.