; IMSCAL
;---------------------------------------------------------------
;! large image self-cal with IM2CC and OOCAL
;# PROCEDURE CALIBRATION AP UV OOP
;-----------------------------------------------------------------------
;;  Copyright (C) 2016
;;  Associated Universities, Inc. Washington DC, USA.
;;
;;  This program is free software; you can redistribute it and/or
;;  modify it under the terms of the GNU General Public License as
;;  published by the Free Software Foundation; either version 2 of
;;  the License, or (at your option) any later version.
;;
;;  This program is distributed in the hope that it will be useful,
;;  but WITHOUT ANY WARRANTY; without even the implied warranty of
;;  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;  GNU General Public License for more details.
;;
;;  You should have received a copy of the GNU General Public
;;  License along with this program; if not, write to the Free
;;  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge,
;;  MA 02139, USA.
;;
;;  Correspondence concerning AIPS should be addressed as follows:
;;         Internet email: aipsmail@nrao.edu.
;;         Postal address: AIPS Project Office
;;                         National Radio Astronomy Observatory
;;                         520 Edgemont Road
;;                         Charlottesville, VA 22903-2475 USA
;-----------------------------------------------------------------------
IMSCAL    LLLLLLLLLLLLUUUUUUUUUUUU CCCCCCCCCCCCCCCCCCCCCCCCCCCCC
IMSCAL:  Determines antenna complex gain from large image
                                   Input uv data.
INNAME                                UV file name (name)
INCLASS                               UV file name (class)
INSEQ              0.0      9999.0    UV file name (seq. #)
INDISK             0.0         9.0    UV file disk drive #
                                   input image
IN2NAME                               Large image name (name)
IN2CLASS                              Large image name (class)
IN2SEQ                                Large image name (seq #)
IN2DISK                               Large image name (disk)
BLC             0.0      4096.0    Bottom left corner of image
                                     0=>1
TRC             0.0      4096.0    Top right corner of image
                                     0=>max allowed
ICUT            0.0                Include all points > ICUT in
                                     absolute value only
FLUX                               Discard all points < FLUX
NX              1.0                Number panels in X
NY              1.0                Number panels in Y
OUTNAME                            name to use for temporary
                                   files (CC, OOSUB output)
OUTDISK                            Disk to put subimages/CCs
                                   Solution control adverbs:
DOKEEP            -1.0         1.0 > 0 -> keep divided us data
                                   Data selection (multisource):
CALSOUR                            Calibrator sources
QUAL            -10.0              Calibrator qualifier -1=>all
CALCODE                            Calibrator code '    '=>all
SELBAND                            Bandwidth to select (kHz)
SELFREQ                            Frequency to select (MHz)
FREQID                             Freq. ID to select.
TIMERANG                           Time range to use.
ICHANSEL                           Array of start and stop chn
                                   numbers, plus a channel
                                   increment and IF to be used
                                   for channel selection in the
                                   averaging. See HELP ICHANSEL.
                                   Default = center 75% of band.
ANTENNAS                           Antennas to select. 0=all
DOFIT                              Subset of ANTENNAS list for
                                   which solns are desired.
ANTUSE                             Mean gain is calculated
                                   (CPARM(2)>0) using only the
                                   listed antennas. See explain.
SUBARRAY          0.0     1000.0   Subarray, 0=>all
UVRANGE                            Range of uv distance for full
                                   weight
WTUV                               Weight outside UVRANGE 0=0.
WEIGHTIT          0.0        3.0   Modify data weights function
                                   Cal. info for input:
DOCALIB          -1.0      101.0   > 0 calibrate data & weights
                                   > 99 do NOT calibrate weights
GAINUSE                            CL table to apply.
DOPOL            -1.0       10.0   If >0 correct polarization.
PDVER                              PD table to apply (DOPOL>0)
BLVER                              BL table to apply.
FLAGVER                            Flag table version
DOBAND           -1.0       10.0   If >0 apply bandpass cal.
                                   Method used depends on value
                                   of DOBAND (see HELP file).
BPVER                              Bandpass table version
SMOOTH                             Smoothing function. See
                                   HELP SMOOTH for details.
                                   CLEAN model controls:
CMETHOD                            Modeling method:
                                   'DFT','GRID','    '
CMODEL                             Model type: 'COMP','IMAG'
                                   'SUBI' (see HELP re images)
REFANT                             Reference antenna
SOLINT                             Solution interval (min)
SOLSUB                             Solution subinterval
SOLMIN                             Min solution interval
APARM                              General parameters
                                      1=min. no. antennas
                                      3 > 0 => avg. RR,LL
                                      5 > 0 => avg. IFs.
                                      6=print level, 1=good,
                                        2 closure, 3 SNR
                                      7=SNR cutoff (0=>5)
                                      8=max. ant. # (no AN)
                                      9 > 0 => pass failed soln
                                     10 < 99 cal output weights
                                   Phase-amplitude Parameters:
DOFLAG                             Flag on closure error?
SOLTYPE                            Soln type,'  ','L1','GCON',
                                      'R', 'L1R', 'GCOR'
SOLMODE                            Soln. mode: 'A&P','P','P!A',
                                   'GCON',
SOLCON                             Gain constraint factor.
MINAMPER          0.0              Amplitude closure error
                                   regarded as excessive in %
MINPHSER          0.0              Phase closure error regarded
                                   as excessive in degrees
NORMALIZ         -1.0         4.0  >0 => normalize gain:
                                     1 globally, 2 by subarray,
                                     3 by subarray,IF
                                     4 by subarray,IF,pol
CPARM                              Phase-amp. parameters
                                      1 = Min el for gain
                                           normalization (deg)
                                      2 > 0 normalize w median
                                           else use mean
                                      3 avg. amp. closure err
                                      4 avg. ph. closure err
                                      5  = 1 vector average
                                        channels, scalar avg
                                        between times
                                        >= 2 scalar average
                                      6 limit clipping in robust
                                      7 limit display of closure
                                        errors
ANTWT                              Ant. weights (0=>1.0)
GAINERR                            Std. Dev. of antenna gains.
BPARM                              Task enrichment parameters
                                   (1) Antenna diameter (m)
                                        0 -> no correction
                                   (2) Omit CC options
                                   (3) spectral index radius
                                        0 -> no correction
FQTOL                              Frequency tolerance in kHz
                                   (primary beam & spec index)
IN3NAME                            Spectral index image name
IN3CLASS                           Spectral index image class
IN3SEQ                             Spectral index image sequence
                                   number
IN3DISK                            Spectral index image disk
IN4NAME                            Spectral curvature name
IN4CLASS                           Spectral curvature class
IN4SEQ                             Spectral curvature sequence
                                   number
IN4DISK                            Spectral curvature disk
BADDISK                            Disk no. not to use for
                                      scratch files.
----------------------------------------------------------------
IMSCAL
Task:  IMSCAL is a procedure that combines IM2CC, OOSUB, CALIB, and
       finally TACOP.  IM2CC breaks a large (usually CASA) image into
       pieces, making both an image and a Clean components table for
       each piece.  This is needed to allow AIPS to use its geometries
       while CASA has used the W-projection geometry.  OOSUB divides
       the data for a calibration source by the model from these
       pieces plus options to permit frequency-dependent primary beam
       and spectral index corrections.  CALIB then determines an
       IF-dependent, spectral-channel independent antenna gain and
       phase, using the divided data.  A solution (SN) table is
       written and copied to the INPUT uv file by TACOP.  Finally the
       temporary, divided data set is deleted (optionally) and the
       image pieces are deleted..

       For multi-source data, any previously unapplied SN tables can
       be smoothed and applied to the specified CL table (multi-source
       data only).  This calibration (CL) table can be applied to the
       data before determining the new calibration constants.

       IMSCAL makes a number of temporary files all of which are
       assigned specific names including sequence number 1.  It will
       check for the presence of any of these on your disks before
       doing work.  If any are present, IMSCAL will list them and
       quit, allowing you to rename them or delete them.

       This procedure is obtained by entering RUN OOCAL.

Adverbs:
  INNAME.....Input UV file name (name).    Standard defaults.
  INCLASS....Input UV file name (class).   Standard defaults.
  INSEQ......Input UV file name (seq. #).  0 -> highest.
  INDISK.....Disk drive # of input UV file.  0 -> any.
        **** Model image in Jy/pixel (not convolved with beam) ****
  IN2NAME....Input image file name (name).    Standard defaults.
  IN2CLASS...Input image file name (class).   Standard defaults.
  IN2SEQ.....Input image file name (seq. #).  0 -> highest.
  IN2DISK....Disk drive # of input image.  0 -> any.
  BLC........The bottom left-hand pixel of the input image which
             becomes the bottom left corner of the subimage from
             which the NX x NY panels are taken.   0 -> 1.
  TRC........The top right-hand pixel of the input image which
             becomes the top right corner of the subimage from which
             the panels are taken.  0 -> max allowed value.
  ICUT.......CC components are made only from pixel values greater in
             absolute value than ICUT and
  FLUX.......CC components are made only from pixel values greater
             than FLUX (in actual value).  Thus FLUX=0 cuts off all
             negatives.
  NX.........The X axis is divided into NX nearly equal panels.
  NY.........The Y axis is divided in NY nearly equal panels.
             Be sure to make enough to account for any W term issues.
  OUTNAME....The output subimages are stored on OUTDISK with this name
             parameter.  The OUTSEQ=1 and OUTCLASS=IMCnnn.  The output
             from the OOSUB step in OOCAL also uses this name with
             OUTCLASS 'OOCAL1'.
  OUTDISK....The output subimages and CC files are put on OUTDISK, the
             OOSUB output file is put on INDISK.  It is better to
             avoid Lustre disks for the CC files.
  DOKEEP.....> 0 => keep the file produced by OOSUB containing the
                    input data divided by the model and the SN table
                    produced by CALIB
             <=0 => delete this temporary file after TACOP.

The following are used for multisource data files only:
  CALSOUR....List of sources for which calibration constants are to be
             determined, i.e. the calibrator sources.  All ' ' = all
             sources; a "-" before a source name means all except ANY
             source named.  You must specify one and only one CALSOUR
             if you want to apply a model using IN2NAME and IN2CLASS
             to a multi-source file.  Otherwise, for such files, the
             program will quit if both IN2NAME and IN2CLASS are
             specified.  Note: solutions for multiple sources can only
             be made if the sources are point sources at their assumed
             phase center and with the flux densities given in the
             source (SU) table.
  QUAL.......Only sources with a source qualifier number in the SU
             table matching QUAL will be used if QUAL is not -1.
  CALCODE....Calibrators may be selected on the basis of the
             calibrator code:
                  '    ' => any calibrator code selected
                  '*   ' => any non blank code (cal. only)
                  '-CAL' => blank codes only (no calibrators)
                  anything else = calibrator code to select.
             NB: The CALCODE test is applied in addition to the
             other tests, i.e. CALSOUR and QUAL, in the
             selection of sources for which to determine
             solutions.
  SELBAND....Bandwidth of data to be selected. If more than one IF is
             present SELBAND is the width of the first IF required.
             Units = kHz, 0=> all
  SELFREQ....Frequency of data to be selected. If more than one IF is
             present SELFREQ is the frequency of the first IF
             required. Units = MHz, 0=> all
  FREQID.....Frequency identifier to select (you may determine which
             is applicable from the OPTYPE='SCAN' listing produced by
             LISTR.  If either SELBAND or SELFREQ are set their values
             override that of FREQID, however setting SELBAND and
             SELFREQ may result in an ambiguity, in which case the
             task will request that you use FREQID.

The following may be used for all data files (except as noted):

  TIMERANG...Time range of the data to be used. In order:
             Start day, hour, min. sec,
             end day, hour, min. sec. Days relative to ref.
             date.
  ICHANSEL...Array of start and stop channels plus a channel increment
             and IF, used to select the channels to be averaged.  For
             instance, if you wished to exclude channels 1 - 10 and
             121 - 128 because of bandpass effects, and channels 56 -
             80 of IF 1 but not IF 2 because of interference, then you
             would set ICHANSEL = 11,55,1,1, 81,121,1,1, 11,121,1,2.
             If you only wished to use every other channel from the
             second IF then you would set ICHANSEL = 11,55,1,1,
             81,121,1,1, 11,121,2,2.  Up to 20 groups of start, stop
             and increment channel numbers plus IF numbers can be
             specified. The default (ICHANSEL = 0) is to average the
             center 75% of the band, i.e.
             ICHANSEL(1,1) = (# channels)/8 + 1
                       For example: # channels=16 => ICHANSEL(1,1)=3
             ICHANSEL(2,1) = (# channels + 1)*7/8
                       For example: # channels=16 => ICHANSEL(2,1)=14
             ICHANSEL(3,1) = 1
             ICHANSEL(4,1) = 0 (meaning all IFs).
             If ICHANSEL describes averaging explicitly for some IFs,
             but skips other IFs, then the center 75% of the band is
             averaged for the skipped IFs.  For example:
             ICHANSEL=2,6,1,2 => The channels 2-6 will be averaged for
             IF=2 and the center 75% of the band will be averaged for
             the rest of the IFs.
  ANTENNAS...A list of the antennas to  have solutions
             determined. If any number is negative then all
             antennas listed  are NOT to be used to determine
             solutions and all others are. All 0 => use all.
  DOFIT......A list of the antennas for which solutions should be
             determined. Only those antennas listed in DOFIT will be
             solved for; all data selected via ANTENNAS will be used to
             form the solutions.  If any antenna number in DOFIT is
             <= -1, then DOFIT is taken as the list of antennas for
             which no solution is desired; a solution is found for all
             antennas not in DOFIT.  Note that the REFANT, if specified,
             will _not_ be solved for even if it appears in the DOFIT
             list.  Selection via DOFIT can be disabled by setting DOFIT
             = 0 which defaults to solving for all antennas.
             NOTE: THIS OPTION MUST NOT BE USED UNLESS YOU UNDERSTAND
             IT FULLY.  Basically, it should be used to solve for the
             gains of "poor" antennas after the "good" antennas have
             been fully calibrated.  Antennas included in ANTENNAS but
             not in DOFIT are assumed to have a complex gain of (1,0)
             and the gains produced will be very wrong if this is not
             the case.  See HELP DOFIT.
  ANTUSE.....A list of the antennas to be used in the calculation of
             the mean gain modulus (NORMALIZ>0). If any number is
             negative then all antennas listed are NOT to be used
             to determine the gain normalization and all others are.
             All 0 => use all.  It can be useful to limit the
             antennas used for the gain normalization to those with
             good a priori calibration, especially when using
             VLBI-style calibration based on system temperatures
             and gains.  This prevents the flux scale from being
             dragged up or down by poorly calibrated antennas
             including antennas subjected to bad weather.  The
             normalization factor determined using the ANTUSE
             antennas is applied to all antennas.
  SUBARRAY...Subarray number to use. 0=>all.
  UVRANGE....The range of uv distance from the origin in
             kilowavelengths over  which the data will have
             full weight; outside of this annulus in the uv
             plane the data will be down weighted by a factor
             of WTUV.
  WTUV.......The weighting factor for data outside of the uv
             range defined by UVRANGE.
  WEIGHTIT...If > 0, change the data weights by a function of the
             weights just before doing the solution.  Choices are:
             0 - no change   weighting by 1/sigma**2
             1 - sqrt (wt)   weighting by 1/sigma may be more stable
             2 - (wt)**0.25
             3 - change all weights to 1.0
  DOCALIB....If true (>0), calibrate the data using information in the
             specified Cal (CL) table for multi-source or SN table for
             single-source data.  Also calibrate the weights unless
             DOCALIB > 99 (use this for old non-physical weights).
             Applied before determining new solutions.
  GAINUSE....Version number of the CL table to apply to the data.
             0 => highest.
  DOPOL......If > 0 then correct data for instrumental polarization as
             represented in the AN or PD table.  This correction is
             only useful if PCAL has been run or feed polarization
             parameters have been otherwise obtained.  See HELP DOPOL
             for available correction modes: 1 is normal, 2 and 3 are
             for VLBI.  1-3 use a PD table if available; 6, 7, 8 are
             the same but use the AN (continuum solution) even if a PD
             table is present.
  PDVER......PD table to apply if PCAL was run with SPECTRAL true and
             0 < DOPOL < 6.  <= 0 => highest.
  BLVER......Version number of the baseline based calibration
             (BL) table to apply. <0 => apply no BL table,
             0 => highest.
  FLAGVER....Specifies the version of the flagging table to be
             applied. 0 => highest numbered table.  <0 => no flagging
             to be applied.
  DOBAND.....(multi-source) If true (>0) then correct the data for the
             shape of the antenna bandpasses using the BP table
             specified by BPVER.  The correction has five modes:
             (a) if DOBAND=1 all entries for an antenna in the table
             are averaged together before correcting the data.
             (b) if DOBAND=2 the entry nearest in time (including
             solution weights) is used to correct the data.
             (c) if DOBAND=3 the table entries are interpolated in
             time (using solution weights) and the data are then
             corrected.
             (d) if DOBAND=4 the entry nearest in time (ignoring
             solution weights) is used to correct the data.
             (e) if DOBAND=5 the table entries are interpolated in
             time (ignoring solution weights) and the data are then
             corrected.
  BPVER......(multi-source) version of the BP table to be
             applied.    0 => highest.
             < 0 => no bandpass correction to be applied.
  SMOOTH.....Specifies the type of spectral smoothing to be applied to
             a uv database . The default is not to apply any smoothing.
             The elements of SMOOTH are as follows:
             SMOOTH(1) = type of smoothing to apply: 0 => no smoothing
               To smooth before applying bandpass calibration
                 1 => Hanning, 2 => Gaussian, 3 => Boxcar, 4 => Sinc
               To smooth after applying bandpass calibration
                 5 => Hanning, 6 => Gaussian, 7 => Boxcar, 8 => Sinc
             SMOOTH(2) = the "diameter" of the function, i.e. width
               between first nulls of Hanning triangle and sinc
               function, FWHM of Gaussian, width of Boxcar. Defaults
               (if < 0.1) are 4, 2, 2 and 3 channels for SMOOTH(1) =
               1 - 4 and 5 - 8, resp.
             SMOOTH(3) = the diameter over which the convolving
               function has value - in channels.  Defaults: 1,3,1,4
               times SMOOTH(2) used when input SMOOTH(3) < net
               SMOOTH(2).
  CMETHOD....This determines the method used to compute the
             model visibility values.
             'DFT' uses the direct Fourier transform, this
             method is the most accurate.
             'GRID' does a gridded-FFT interpolation model
             computation.
             '    ' allows the program to use the fastest
             method.
             NOTE: when using a model derived from data with
             difference uv sampling it is best to use 'DFT'
  CMODEL.....This indicates the type of input model; 'COMP' means that
             the input model consists of Clean components, 'IMAG'
             indicates that the input model consists of images.
             'SUBI' means that the model consists of a sub-image of
             the original IMAGR output.  If CMODEL is '   ' Clean
             components will be used if present and the image if not.
             SUBI should work for sub-images made with DO3DIM true and
             sub-images of the central facet made with DO3DIM false,
             but probably will not work well for shifted facets with
             DO3DIM false.  Use BLANK rather than SUBIM in such cases.
             OOCAL will set a scaling factor to correct image units
             from JY/BEAM to JY/PIXEL for image models.  If the source
             table contains a flux, then that flux will be used to
             scale the components model to obtain the stated total
             flux.  This is needed since initial Cleans may not obtain
             the full flux even though they represent all the
             essentials of the source structure.

The following control how the solutions are done, if you don't
understand what a parameter means leave it 0 and you will
probably get what you want.
  REFANT.....The desired reference antenna for phases.
  SOLINT.....The solution interval (min.)
             0 => scan average for multi-source,
             0 => 10 s for single source amp-phase solns. (VLA)
             0 => 10 min for delay-rate solutions (VLBA).
             OOCAL tries hard to make equal integrations within each
             scan but that is a problem that lacks a general solution.
             You can help by careful choice of SOLINT: assume you have
             data every 10 seconds.  Then, to get 1 sample per
             solution, set SOLINT=9/60.  To get 2 per solution, set
             SOLINT=19/60, 3 per solution SOLINT=29/60.  Each averaged
             interval will start with an actual data sample and will
             end just before the first sample at a time greater than
             the start + SOLINT + 0.1s.  At the end of the scan, the
             end time can be increased by up to 0.6 * SOLINT to
             prevent short final integrations.  For calibration that
             is not self-calibration, note that the 2-point
             interpolation will use ONLY the last integration of a
             calibrator scan with the first integration of the next
             calibrator sacn.  That is why the initial calibration
             normally uses scan averages for the calibrator sources.
                          -------------------------
             If the times in your data set are not at regular
             intervals due to flagging and averaging, you must be
             careful with SOLINT.  To get all data in 10 seconds (from
             0 through 9.999) set SOLINT to 9.999/60.  Use of 1 sec
             will do odd things with the records at odd times.
                          -------------------------
  SOLSUB.....The begin time for the next interval in advanced from the
             current one by SOLINT / SOLSUB where 1 <= SOLSUB <= 10.
             0 -> 1.  This is to produce solutions at sub-intervals of
             SOLINT based on SOLINT length of averaging.
  SOLMIN.....Minimum number of subintervals to be used in a solution.
             0 -> SOLSUB.
  APARM......General control parameters.
  APARM(1)...Minimum number of antennas allowed for a solution.
             0 => max (3, min (6, Numant/2))
  APARM(2)...If > 0 then the input data has already been
             divided by a model; only solutions will be
             determined.
  APARM(3)...If > 0 then average RR, LL
  APARM(5)...If > 0 then make a combined solution for the IFs;
             if <= 0 then make separate solutions.
  APARM(6)...Print flag, 0=none, 1=time, closure error statistics,
             2=individual closure failures (exceeding both CPARM(7)
             sigma and either MINAMPER or MINPHSER), 3=some additional
             info including the antenna signal to noise ratio,
             4=solutions, 5=data too.
  APARM(7)...The minimum allowed signal-to-noise ratio.   0 => 5
  APARM(8)...If there is no antenna (AN) table with the input file
             then the maximum antenna number in the file should be
             entered in APARM(8).
  APARM(9)...When solutions fail or there is insufficient data and
             APARM(9) > 0 then (1,0) is written to the SN table.  This
             will preserve the previous calibration but this option
             should be used with extreme care.
  APARM(10)..When writing a single-source output file, calibrate the
             output weights except when either DOCAL > 99 or
             APARM(10) > 99 or both.
  Phase-amplitude parameters:
  DOFLAG.....If DOFLAG > 0, those baselines with excessive closure
             error will be added to a new flag table along with all
             flags previously in FLAGVER.  If DOFLAG <= 0, no new data
             flags are generated and no flag table is written.  In
             either case, all SOLTYPEs below check the data for
             closure error and will report the fractions for which the
             closure error exceeds abs(DOFLAG) times the rms closure
             error.  Defaults for the reporting level are:
                  0.0 < DOFLAG <  2.0   ->   2.5
                 -1.0 < DOFLAG <= 0.0   ->  -2.5 if APARM(6) = 0
                                           -99.0 if APARM(6) >= 1
             Note that this checking of closure error is in addition
             to the checking done under control of MINAMPER, MINPHSER,
             and APARM(6) which do not flag the data.  Note that data
             marked as "bad" by the DOFLAG test will not be checked
             with the APARM(6) controlled tests.  The default on
             DOFLAG=0 is then meant to enable better printing of
             closure errors when not doing any actual flagging.
  SOLTYPE....Solution type:
               '    ' => normal least squares,
               'R   ' => as ' ' with robust iteration
               'L1  ' => L1 solution; a weighted sum of the moduli
                         of the residuals is minimized.
			 The computed gain solutions are less
			 influenced by wild data points, but there
			 is some loss of statistical efficiency.
	      		 See [F.R. Schwab, VLA scientific Memo #136]
			 for further details.
               'L1R ' => as 'L1' with robust iteration
               'GCON' => least squares which may include gain
                   constraint.
               'GCOR' => as 'GCON' with robust iteration
             SOLTYPE (other than the R) is ignored when the DOFIT
             option is used.  The robust versions iterate the
             solution, discarding data that does not fit the current
             solution well enough.  They should be less disturbed by
             bad data, but will be slower.
  SOLMODE....Solution mode:
              'A&P ' => amplitude and phase.
              'P   ' => phase only
              'P!A ' => phase only (no amplitude information)
              'GCON' => amplitude and phase with constraints on
                        amplitude.  This mode requires setting
                        SOLTYPE='GCON', uses GAINERR and
                        SOLCON may be used.
              '    ' => 'A&P ' for multisource (raw) data,
                     => 'P   ' for single source data.
  SOLCON.....Gain constraint factor; a value larger than 0 will
             increase the strength of the amplitude constraint
             in gain constrained solution with SOLMODE='GCON'
  MINAMPER...Amplitude closure error regarded as excessive in per cent.
             If APARM(6) > 0, summaries of the number of excessive
             errors by antenna are printed and, if APARM(6) > 1, up to
             1000 of the individual failures are printed.  0 => do not
             check or report "excessive" closure errors of any sort.
             Note that amplitude closure errors are accumulated using
             logarithms so that gains of 0.5 and 2.0 are both errors of
             100%.
  MINPHSER...Phase closure error regarded as excessive in degrees.
             If APARM(6) > 0, summaries of the number of excessive
             errors by antenna are printed and, if APARM(6) > 1, up to
             1000 of the individual failures are printed.  0 => do not
             check or report "excessive" closure errors of any sort.
  NORMALIZ...If > 0, constrain the mean gain modulus of the calibration
             applied to be unity.  This is mostly used in self
             calibration.  If NORMALIZ = 1, the mean is over all IFs,
             antennas, polarizations and subarrays.  If NORMALIZ =2,
             it is the same except separated by subarray.  If NORMALIZ
             = 3, it is averaged over all antennas and polarizations
             but separated by IF and subarray.  NORMALIZ=4 also
             separates by polarization.  If you select NORMALIZ= 1,
             the global scaling factor is written to the header of the
             SN table.  For options 2 - 4, the SN table is re-written
             with the final scaling applied.  If = 0, substitute
             CPARM(2) which was previously used for this information.
  CPARM......Phase-amplitude parameters.
  CPARM(1)...Minimum elevation in degrees for the solutions used to
             constrain the mean gain modulus.  0 or >80 => no
             constraint (actually -100 is used).
  CPARM(2)...If NORMALIZ > 0, CPARM(2) controls whether a mean value
             (CPARM(2) <= 0) or a median value (CPARM(2) > 0) is used.
  CPARM(3)...If > 0, the values of any amplitude closure errors whose
             average absolute percentage value exceeds CPARM(3) will be
             printed if APARM(6) > 0.
  CPARM(4)...If > 0, the values of any phase closure errors whose
             average absolute value exceeds CPARM(4) degrees will be
             printed if APARM(6) > 0..
  CPARM(5)...If > 0 then the amplitudes will be scalar averaged when
             averaging across times before determining the solutions.
             The averaging of spectral channels will be a vector
             average unless CPARM(5) > 1.5.  Vector averaging is
             preferred to avoid the Ricean bias in amplitudes, but not
             when phase instability will make the signal incoherent.If
             the atmospheric phase is very unstable, then it should be
             fine at any one time but may require the scalar averaging
             between times.
  CPARM(6)...The robust solution method discards data more than
                    f(iter) * rms(iter)
             from the current solution to find the iter+1 solution
             f(iter) = max (g(iter), CPARM(6)) and
             g = 7.0, 5.0, 4.0, 3.5, 3.0, 2.8, 2.6, 2.4, 2.2, 2.5.
             Thus CPARM(6) can be used to limit the discarding to less
             restrictive values.
  CPARM(7)...The printing of individual closure errors occurs only if
             APARM(6) >= 2 and the errors exceed MINAMPER percent in
             amplitude and/or MINPHSER degrees in phase.  That
             printing is also limited to those errors that are more
             than CPARM(7) times the 1 sigma expected error (based on
             the data weights).  0 -> 2.5.  If you want no limit,
             set CPARM(7) to something like 0.001.
  ANTWT......Antenna weights.  These are additional weights
             to be applied to the data before doing the
             solutions, one per antenna.  Use PRTAN to
             determine which antenna corresponds to each
             antenna number.
             0 => 1.0
  GAINERR....Estimates of the standard deviation of the modulus of the
             gains for each antenna.  These are used ONLY if SOLMODE
             and SOLTYPE='GCON'.  The solution will attempt to make
             the standard deviation  of the modulus of the antenna
             gains match these values so accurate values are
             essential.
  BPARM......Correction control parameters (SEE EXPLAIN IMAGR):
             (1) If > 0 then make frequency dependent primary beam
               corrections assuming an antenna diameter of IMAGRPRM(1)
               meters.  Note that VLA and ATCA arrays (TELESCOPE
               header parameter) use the default primary beam
               parameters defined elsewhere in AIPS, while other
               antennas actually use IMAGRPRM(1) as the diameter of a
               "standard" telescope.  See FQTOL below also.
             (2) If BPARM(1) > 0, you may omit selected CCs from the
               operation based on position:
                  BPARM(2) <= 0  : Include all CCs
                            = 1  : Omit CCs within the main beam at
                                   all frequencies
                            = 2  : Omit CCs within the main beam at
                                   some frequncies
                            = 3  : Omit Ccs outside the main beam at
                                   some frequencies
                            = 4  : Omit CCs outside the main beam at
                                   all frequencies
             (3) 1 => use a spectral-index image represented in
               IN3NAME, IN3CLASS, IN3SEQ, IN3DISK below to correct the
               Clean component model for each channel.  IN4NAME et al
               will also be used as a curvature image iff IN3NAME are
               specified.
               BPARM(3)-0.5 is used as a radius in pixels over which
               the spectral index image is averaged.  When it is small
               (0 < BPARM(3) <~ 1), the spectral index is interpolated
               rather than averaged.  See FQTOL below as well.  When
               doing spectral index, the primary beam correction
               (BPARM(1)) costs very little extra.  This parameter is
               IMAGRPRM(17) in IMAGR.
  FQTOL......Frequency tolerance in kHz.  Spectral channels with FQTOL
             are handled together (use the same average CC model) when
             applying the primary beam and spectral index
             corrections.  Default is to do each channel separately
             which can take a long time.
  IN3NAME....Image name of spectral index image; no default.
  IN3CLASS...Image class of spectral index image; no default.
  IN3SEQ.....Image sequence of spectral index image; 0 -> highest.
  IN3DISK....Disk of spectral image image; 0 -> any.
  IN4NAME....Image name of spectral index curvature image; no default.
             Curvature images should be base 10 rather than base e -
             they differ by a factor of 2.3.  Also the reference
             frequency is 1.0 GHz.  These are changes done 2010-07-13.
  IN4CLASS...Image class of spectral index curvature image; no
             default.
  IN4SEQ.....Image sequence of spectral index curvature image;
             0 -> highest.
  IN4DISK....Disk of spectral curvature image image; 0 -> any.
  BADDISK....Disk numbers on which scratch files are not to
             be placed.
----------------------------------------------------------------
OOCAL:  Task to determine antenna gains from calibrator data
Documentor:  A.H.Bridle
Related Programs: CLCAL, LISTR, SPLIT, UVFLG

This task is the central AIPS routine for calibrating multi-
source uv data sets using observations of calibration sources
that can either be assumed to be point sources or have well
determined structures.

OOCAL determines antenna voltage gain solutions (amplitude
and/or phase) from data for calibrator sources with well known
flux densities, positions and structures. It is the equivalent
of the VLA Dec-10 ANTSOL (with additional options) and of a
combination of the AIPS routines ASCAL and VSCAL.  Solutions
determined by OOCAL under control of the APARM, CPARM and DPARM
parameters are written to the solution (SN) extension table of
the input uv data set.  Solution tables may be merged, smoothed
and interpolated into calibration (CL) tables for multi-source
uv data files using CLCAL.

OOCAL may also be run on files containing data for only one
source, for self calibration.

To run OOCAL, you should specify at least:

The input uv data file (INNAME, INCLASS, INSEQ, INDISK).

The CALSOURces to be used for determining antenna gains, or
leave CALSOUR blank and specify a CALCODE and/or qualifier.

REFANT, the reference antenna for the solution (choose an
antenna with good signal to noise that was present through
as much of the observing as possible).

The defaults are set so that running OOCAL on a multi-
source uv data file setting only these inputs will make
a solution file for all IFs in the data over the entire
time range using the highest-numbered flag file.  All
antennas will be calibrated for amplitude and phase, using
data from the entire uv range.  All antennas will be equally
weighted. Point source models will be assumed for the
calibration sources.  The solution will be written to an
SN table.


Other useful options
====================

Use APARM(6)=3 to list the signal to noise ratio at each
antenna solution.  Solutions with signal to noise below
5:1 are probably not meaningful and will be discarded by
the default setting of APARM(7).  You may wish to apply
more stringent criteria with APARM(7).

Use SOLTYPE and SOLMODE='' to solve for both amplitude and
phase solutions simultaneously with no constraints on amplitude,
SOLTYPE and SOLMODE='GCON' for amplitude and phase with
constraints set by GAINERR and SOLCON.  Amplitude solutions
for point source models in multisource files will be based on
the flux densities entered for the sources in the source (SU)
table extension of the data set using task SETJY.

Use UVRANGE and WTUV to weight different uv ranges
differently (or to restrict the solution to some uv range
-- WTUV = 0 is read as zero weight).


"CLEAN" COMPONENT MODELS
========================

OOCAL does not restrict you to the use of point source models
for your calibrators.  Use IN2DISK, IN2NAME, IN2SEQ, INVERS,
NCOMP and NMAPS to specify a CLEAN component model for the
field or fields around a calibrator  and specify that
calibrator in SOURCE. OOCAL will create an SN table for that
calibrator alone.  This SN table may then be merged with SN
tables for other calibrators produced by other runs of OOCAL,
when the SN tables are smoothed and interpolated into a CL file
by CLCAL.

FLUX CALIBRATOR MODELS
======================
This is actually a subsection of CLEAN COMPONENT MODELS above.
You are strongly encouraged to use the flux calibrator models
available for all the primary flux calibrators (3C138, 3C147,
3C286 and 3C48).  Using calibrator models removes the need set
UVRANGE and ANTENNAS.  To see what calibrator models are available
in AIPS type CALDIR, to read them in use the task CALRD.  CALRD
loads in the selected model as an image file.  Then specify this
image in IN2DISK, IN2NAME, IN2CLASS and IN2SEQ.  OOCAL will
recognize these images as standard calibrator models and scale
the clean components in the central part of the field with the
flux in the SU table.

RESETTING YOUR CALIBRATION
==========================

The first version of the CL table attached to your uv data set
is protected from modification in CLCAL, so
that you can easily "undo" all calibration steps that have
taken place within AIPS.  To reset your calibration, delete all
CL tables with version numbers >1, and delete all SN tables.


POLARIZATION considerations (thanks to Robert Braun)
====================================================

The VLA measures approximately (neglecting the leakage terms):

RR=I+V, LL=I-V, RL=Q+iU, LR=Q-iU

The WSRT uses linear polarization but the equatorial mounts mean that
the feed orientation remains constant relative to the sky (no
parallactic angle change at all).  Thus, the WSRT measures
approximately:

XX=I-Q, YY=I+Q, XY=-U+iV and YX=-U-iV

If you compare these two sets of equations, you see that they have a
lot in common. If you simply pretend that you have measured
(RR,LL,RL,LR) by changing the Stokes value from -5 to -1 in the header
with PUTHD, you're almost in business, except you have -Q in the place
of V, -U in the place of Q, and V in the place of U.  This is fine for
most things, since you just have to request a slightly different
parameter from the one you really mean.

The biggest hassle comes from amplitude calibration of linearly
polarized sources, like:

3C286 (near 1.4 GHz) which has (I,Q,U,V)=(14.65,0.56,1.26,0.00) Jy

3C138 (near 1.4 GHz) which has (I,Q,U,V)=(8.30,0.63,-0.17,0.00) Jy

Since Q is non-zero, it means that the XX and YY correlations do not
correspond to the same real flux density (ie. XX=I-Q and YY=I+Q).

Now, since RR=I+V and LL=I-V, the idea is to have OOCAL use the
Stoke's V from the SU table.  The, for WSRT data, one can fudge the
right behavior, by putting the source's actual value of -Q in place
of V in the SU table.

This shouldn't harm any VLA users, since Stoke's V is near enough zero
for most sources anyway. And if it were non-negligible it should be
taken along in any case, since it really does affect the RR and LL
correlations, and therefore the derived gain of the R and the L IFs.


