; PCAL
;---------------------------------------------------------------
;! Determines instrumental polarization for UV data
;# TASK UV CALIBRATION POLARIZATION
;-----------------------------------------------------------------------
;;  Copyright (C) 1995-1997, 1999-2004, 2006-2007, 2009-2011, 2014-2016,
;;  Copyright (C) 2018
;;  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
;-----------------------------------------------------------------------
PCAL      LLLLLLLLLLLLUUUUUUUUUUUU CCCCCCCCCCCCCCCCCCCCCCCCCCCCC
PCAL    Task to compute polarization corrections
INNAME                             Input UV file name (name)
INCLASS                            Input UV file name (class)
INSEQ             0.0     9999.0   Input UV file name (seq. #)
INDISK            0.0        9.0   Input UV file disk unit #
                                   Data selection (multisource):
CALSOUR                            Sources to calibrate with
QUAL            -10.0              Calibrator qualifier -1=>all
CALCODE                            Calibrator code '    '=>all
TIMERANG                           Time range to use.
SELBAND                            Bandwidth to select (kHz)
SELFREQ                            Frequency to select (MHz)
FREQID                             Freq. ID to select.
BIF               0.0      100.0   Lowest IF number 0=>all
EIF               0.0      100.0   Highest IF number 0=>all
ANTENNAS                           Antennas to solve for.
UVRANGE           0.0              UV range in kilolamdba
SUBARRAY          0.0     1000.0   Subarray, 0=>all
                                   Cal. info for input:
DOCALIB          -1.0      101.0   > 0 calibrate data & weights
                                   > 99 do NOT calibrate weights
GAINUSE                            CAL table to apply.
                                   CLEAN map (optional)
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.
ICHANSEL                           Array of start and stop chan
                                   numbers, plus a channel
                                   increment and IF to be used
                                   to select channels to sum to
                                   find the polarization.
                                   0 => all channels
IN2NAME                               Cleaned map name (name)
IN2CLASS                              Cleaned map name (class)
IN2SEQ            0.0     9999.0      Cleaned map name (seq. #)
IN2DISK           0.0        9.0      Cleaned map disk unit #
INVERS           -1.0    46655.0   CC file version #.
NCOMP                              # comps to use for model.
                                   1 value per field
FLUX                               Lowest CC component used.
NMAPS             0.0     4096.0   No. Clean map files
CMETHOD                            Modeling method:
                                   'DFT','GRID','    '
CMODEL                             Model type: 'COMP','IMAG'
                                   'SUBI' (see HELP re images)
DOMODEL          -1.0        2.0   > 0 => use model, do not
                                   fit source Q and U
                                   = 2 use CP table model
PMODEL                             Source poln. model
SPECPARM                           Spectral index: I Q U V for
                                   each CALSOUR
DOSCALE          -1.0        2.0   >= 0 use spectral index
                                   = 2 solve for curvature
SOLINT                             Soln. interval (min) 0=>5.
SOLTYPE                            Solution type:
                                   'ORI-', 'APPR', 'RAPR'
SPECTRAL         -1.0        1.0   > 0 do spectral PCAL
                                   <= 0 do continuum PCAL
INTPARM                            Smoothing parameters for
                                   spectral mode
PRTLEV            0.0       10.0   Print statistics 0=>none
                                   1 = some, 2 = lots. Use 1.
REFANT            0.0       90.0   Reference antenna, 0->pick
BPARM                              Task enrichment parameters
                                   for SOLTYPE 'ORI-' only:
                                   (1) if > 0 use default
                                       initial feed parameters.
                                   (2) > 0 -> no error calc.
                                   (3) if > 0 then fit for R-L
                                       phase difference
                                   (4) initial R-L phase
                                   (5) >0 solve for Vpol.
                                   (6) >0 fix ref. ori. 1
                                   (7) >0 fix ref. ori. 2
                                   (8) >0 fix all orientations
                                   (9) >0 fix all ellipticities
                                   (10) >0 fix source poln.
CPARM                              Task enrichment parameters
                                   (1) >0 => average in IF
                                      and find common solution.
                                   (2) >0 => update source
                                      table with pol. solution
                                   (3) >0 => do NOT interpolate
                                      over flagged channels
                                   (4) CP table version if
                                      DOMODEL = 2
                                   (5) >0 Use linear model for
                                      linear polarization data
                                   (7) >0 => use initial guess
                                       from AN or PD tables
                                   (8) >0 => max. no. iter
                                   (9) >0 => conv. tolerance
                                   (10) >0 => conv. tol.
DPARM                              (1) > 0 => take blanked
                                      Faraday rotation as 0
BADDISK            0.0         9.0 Disk no. not to use for
                                      scratch files.
---------------------------------------------------------------
PCAL
Task:  This task reads a UV file, calibrates, subtracts a model and
       determines the effective feed parameters for each antenna and
       IF.  These parameters are then placed in the antenna (AN)
       table.  Polarization corrections can then be applied by setting
       DOPOL=1 in LISTR or SPLIT.
            If a polarized model is given then only the feed
       parameters are determined.  If no model is given then a point
       source is assumed for SOLTYPE='APPR'.  For SOLTYPEs 'ORI-' and
       'RAPR' the source may be resolved but the polarized flux is
       assumed to have the same distribution as the total intensity
       and the polarization angle is assumed to be constant.
            Model images made with both values of IMAGR's DO3DIMAG
       option are handled correctly, as are multi-scale images.  Set
       NMAPS = NFIELD * NGAUSS.
            The frequencies within each IF are averaged by PCAL before
       doing the solutions. So the phase has to be flat within each
       IF. Therefore the data have to be phase calibrated by FRING or
       by PCCOR before PCAL.

       In 31DEC10, PCAL has two modes.  In the old, familiar one, PCAL
       averages spectral channels and determines antenna D terms and
       optionally source Q and U on a per IF basis.  The results are
       written to the antenna (AN) and optionally the source (SU)
       tables.  In the new mode, PCAL determines the D terms and
       optionally the source Q and U on a per spectral channel basis.
       Such results are written to the PD and CP tables, respectively.
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.

The following are used for multisource data files only:
  CALSOUR....List of sources for which calibration constants
             are to be determined.  '*' = all; a "-" before a
             source name means all except ANY source named.
             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. All '  ' =>all.
             No more than 50 calibrators may be selected using this
             and the following two adverbs.
  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.
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.
  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. For data which
             contain multiple bandwidths/frequencies the task
             will insist that some form of selection be made
             by frequency or bandwidth.
  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.
  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 that case, the task will request
             that you use FREQID.
  BIF........First IF to process. Old values for feed parameters
             and calibrator polarizations for unprocessed IFs
             are unchanged.  0=>all.
  EIF........Highest IF to process. 0=>all higher than BIF
  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.
  UVRANGE....Range of projected spacings to be included in
             1000's of wavelengths.  0  =>  1, 1.E10
  SUBARRAY...Subarray number to use. 0=>all.
  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).
  GAINUSE....version number of the CL or SN table to apply to
             the data.  0 => highest.
  BLVER......Version number of the baseline based calibration
             (BL) table to appply. <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.....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......Specifies the version of the BP table to be applied.
             <0 => no bandpass correction done.
  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).
  ICHANSEL.. Array of start, stop, and increment channel numbers plus
             an IF used for channel selection in the averaging to
             compute the average values used for solving for
             polarization.  Up to 20 sets if channels/IF may be
             entered.  The first having ICHANSEL(2,i) <= 0 terminates
             the list.  ICHANSEL(4,i) is the IF number, with <= 0
             meaning all IFs.  If an IF has no ICHANSEL set for it,
             then all channels are used.
             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.  if there are actually
             4 IFs, then IFs 3 and 4 would use channels 17 through
             112.  To set the channel range for all IFs to 14, 115
             enter ICHANSEL = 14,125.  To set the channel range for
             all IFs to 14-115 except IF 3 set ICHANSEL=14,115,1,0,
             23 45,1,3, 64,101,1,3 where the all IF part must come
             before the parts that partially override it.
  IN2NAME....Cleaned map name (name).      Standard defaults.
             Read DOMODEL (below) first.
             Note: a CLEAN image for only a single source may be given
             although it may be in a multi-source file.  An Ipol, Qpol,
             Upol, and Vpol image of the same name are expected.  If
             the first one of the polarization is missing, that
             polarization is taken to have a value of 0.0.  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.  NOTE: if a model
             image is given, then the task will not fit for source
             polarization if models for at least I, Q, and U are
             given.  IN2NAME and IN2CLASS cause PMODEL to be ignored.
  IN2CLASS...Cleaned map name (class).  The value given should be for
             the Ipol image, the Q, U, and V pol images will be
             assumed to be the same except for an initial Q, U, or V
             in the class.
  IN2SEQ.....Cleaned map name (seq. #).  These should be the same for
             I, Q, U,  and V images.
  IN2DISK....Disk drive # of cleaned map.  0 => any.
  INVERS.....CC file version #.  0=> highest numbered version
  NCOMP......Number of Clean components to use for the model, one
             value per field.  If all values are zero, then all
             components in all fields are used.  If any value is not
             zero, then abs(NCOMP(i)) (or fewer depending on FLUX and
             negativity) components are used for field i, even if
             NCOMP(i) is zero.  If any of the NCOMP is less than 0,
             then components are only used in each field i up to
             abs(NCOMP(i)), FLUX, or the first negative whichever
             comes first.  If abs(NCOMP(i)) is greater than the number
             of components in field i, the actual number is used.  For
             example
                   NCOMP = -1,0
             says to use one component from field one unless it is
             negative or < FLUX and no components from any other
             field.  This would usually not be desirable.
                   NCOMP = -1000000
             says to use all components from each field up to the
             first negative in that field.
                   NCOMP = -200 100 23 0 300 5
             says to use no more than 200 components from field 1, 100
             from field 2, 23 from field 3, 300 from field 5, 5 from
             field 6 and none from any other field.  Fewer are used if
             a negative is encountered or the components go below
             FLUX.
  FLUX.......Only components > FLUX in absolute value are used in the
             model.
  NMAPS......Number of image files to use for model.  For multi-scale
             models, set NMAPS = NFIELD * NGAUSS to include the Clean
             components of the extended resolutions.  If more than one
             file is to be used, the NAME, CLASS, DISK and SEQ of the
             subsequent image files will be the same as the first file
             except that the LAST 3 or 4 characters of the CLASS will
             be an increasing sequence above that in IN2CLASS.  Thus,
             if INCLASS='ICL005', classes 'ICL005' through 'ICLnnn'
             or 'ICnnnn', where nnn = 5 + NMAPS - 1 will be used.  Old
             names (in which the 4'th character is not a number) are
             also supported: the last two characters are '01' through
             'E7' for fields 2 through 512.  In old names, the highest
             field number allowed is 512; in new names it is 4096.
  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
             different 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
             sib-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.
             CALIB 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.
  DOMODEL....<= 0 => fit for the calibration source(s) Q and U.  This
                still requires knowledge of the source(s) I flux.  If
                there is only one source, this is given by PMODEL(1)
                if it is greater than 0 (required for single-source
                files) with a default of the fluxes in the source
                table for multi-source files.  An image model is also
                possible for a single source.  If there is more than
                one calibration source, then PMODEL and IN2NAME et al.
                are ignored and the I fluxes come from the source
                table.
             > 0 => use a model for the calibration source(s) I, Q,
                and U (and maybe even V) flux and do NOT fit for the
                source(s) Q and U.  For a single calibration source,
                image models may be used and/or PMODEL if PMODEL(1) >
                0.  One of these must be done for single-source files.
                For multi-source files, the source table may be used
                to provide the full model instead and is the only
                place to get models for more than one calibration
                source.
             = 2 => use the I, Q, U, V model contained in an attached
                CP table (version given by CPARM(4)).
  PMODEL.....See first DOMODEL above.  A single component model to be
             used instead of a CLEAN components model; if PMODEL(1) >
             0 amd DOMODEL > 0, then use of this model is requested
             when a single source is being used
                PMODEL(1) = I flux density (Jy)
                PMODEL(2) = Q flux density (Jy)
                PMODEL(3) = U flux density (Jy)
                PMODEL(4) = V flux density (Jy)
                PMODEL(5) = X offset in sky (arcsec)
                PMODEL(6) = Y offset in sky (arcsec)
             PMODEL(1) must be > 0 to give an I flux for single-source
             data sets independent of the value of DOMODEL.  The rest
             of PMODEL must be set intentionally when DOMODEL > 0 and
             IN2NAME is blank.  PMODEL is ignored if IN2NAME or
             IN2CLASS is not blank.
  SPECPARM...The spectral index in I, Q, U, and V for each source to
             be used mostly when DOMODEL > 0.  In the continuum case,
             it is applied only when PMODEL is used.  In the line
             case, it is also applied in I, Q, U, and V when PMODEL is
             used.  When DOMODEL <= 0, the I flux is still needed to
             solve for Q and U, so the I portion is still used.  Thus
             meaningful values for SPECPARM(1,i) are helpful.  Note
             that i is a sequential number assigned to all CALSOUR in
             the order of the source numbers in the source table (not
             their order in the adverb CALSOUR).
  DOSCALE....= -1 => do not use spectral index in the task
             >= 0 => use spectral index from SPECPARM or solve for
                     spectral indices using those for known sources
                     or fluxes in the SU table
             = 2  => when using SU table fluxes, solve for a curvature
                     as well as spectral index.
  SOLINT.....Time interval to average data before determining
             correction in minutes.  0 => 5 min.   If there is a
             single calibrator scan, the task will reset SOLINT to 0.333
             times the length of that scan.  SOLINT is an interesting
             parameter to explore if having difficulties with solutions.
  SOLTYPE....Solution type:
             'APPR' => linear approximation,
             'RAPR' => linear approximation but allowing
                       resolved sources.
             'ORI-' => orientation- ellipticity allowing
                       resolved  sources
             other values = 'APPR'
             Note: 'RAPR' and 'ORI-' require nonstandard
             calibration procedures, see EXPLAIN PCAL for
             details.
  SPECTRAL...>  0 => do the solution as a function of spectral channel
                     within each IF.  Answers go into a PD table and
                     source models, if they are part of the solution,
                     go into the CP table.
             <= 0 => do the solution only as a function of IF.
                     Antenna polarizations are placed into ther
                     antenna table and source models (if DOMODEL<=0
                     and CPARM(2)>0) go in the SU table.
  INTPARM....After the data are calibrated with all parameters
             including SMOOTH, they may be smoothed in frequency
             further using the INTPARM selected function while taking
             into account ICHANSEL.  This is to provide better S/N
             than one would have with unsmoothed single channels.
             INTPARM(1) = type of smoothing to apply:
               0 => no smoothing
               1 => Hanning
               2 => Gaussian
               3 => Boxcar
               4 => Sinc (i.e. sin(x)/x)
             INTPARM(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 INTPARM(1) =
               1 - 4.
             INTPARM(3) = the diameter over which the convolving
               function has value - in channels.  Defaults: 1, 3, 1, 4
               times INTPARM(2) used when input INTPARM(3) <
               INTPARM(2) (after application of defaults).
  PRTLEV.....If this value is larger than 0.0 then the
             intermediate diagnostics and solutions will be
             given on the monitor terminal and the message file.
  REFANT.....Reference antenna to use.  If none is specified, the task
             will pick the lowest numbered one with the most samples.
             Previous methods that allowed "none" gave suspect
             results and could not measure uncertainties.
  BPARM......Task enrichment parameters (SOLTYPE='ORI-' only):
             (1) If BPARM(1) is greater than 0 then the initial
                 values for the feed ellipticity and orientation
                 will be that for perfect RCP and LCP feeds.
                 Otherwise the values from the AN table, if any,
                 will be used.
             (2) > 0 => suppress error calculation - which can be
                 meaningless and can even get into an infinite loop.
             (3) If BPARM(3) is greater than 0 then fit for the
                 R-L phase difference using BPARM(4) as the
                 initial value. This option is only useful if at
                 least one source has a fixed polarization
                 model.
             (5) If BPARM(5) is greater than 0 then solve for
                 Vpol.
             (6) If BPARM(6) is greater than 0 then fix the value of
                 the orientation of the first polarization of the
                 reference antenna to 0.  (REFANT > 0)
             (7) If BPARM(7) is greater than 0 then fix the value of
                 the orientation of the second polarization of the
                 reference antenna to 0.  (REFANT > 0)
             (8) If BPARM(8) is greater than 0 then fix the
                 orientations at the values in the AN table.
             (9) If BPARM(9) is greater than 0 then fix the
                 ellipticities at the values in the AN table.
             (10) if (BPARM(10) is greater than 0 then fix the
                  source polarization parameters to the values
                  given in the SU table.
  CPARM......Task enrichment parameters:
             (1) If CPARM(1) is greater than 0 then data in the
                 selected IFs will be averaged before doing the
                 solutions.  NOTE: the IFs must be phase coherent for
                 this to be useful.  This is usually NOT the case for
                 VLA data.
             (2) > 0 => update the source table with the fit source
                 parameters.  Note, because of the RL phase
                 difference, the Q and U fit may not be correct.
             (3) In SPECTRAL > 0 mode, channels flagged either by
                 the usual flags or by ICHANSEL and not recovered by
                 smoothing with INTPARM will end up with solutions
                 which are 0.0.  The task will replace these incorrect
                 ones with interpolated or extrapolated ones unless
                 CPARM(3) > 0.
             (4) If DOMODEL = 2, the CP table version number to be
                 used.  0 => the highest.
             (5) The linear polarization model is not believed to work
                 correctly.  If you want to try it on your linearly
                 polarized data, set CPARM(5) > 0.  If DOMODEL is true
                 and the source polarization is zero, the circular
                 model (APPR) is thought to work well.
             (6) Not currently used.
             (7) An initial guess may be found by reading the AN table
                 (SPECTRAL <= 0) or the PD table if CPARM(7) > 0.  If
                 the latest values in the AN table or the highest
                 version of PD table are suspect, this is not a good
                 idea.  But it may help convergence if those values
                 are reasonable.
             (8) If CPARM(8) is greater than 0 then it will be
                 used as the maximum number of iterations for
                 the SOLTYPE='ORI-' solution.
             (9) If CPARM(9) is greater than 0 then it will be
                 used as a convergence criterion for the
                 SOLTYPE='ORI-' solution.  A value of 0 causes a
                 default criterion to be used.
             (10) If CPARM(10) is greater than 0 then it will be
                 used as a convergence criterion for the
                 SOLTYPE='ORI-' solution.  A value of 0 causes a
                 default criterion to be used.
  DPARM      (1) Missing Faraday rotation values can cause blanked
                 values to appear later on.  If DPARM(1)>0, the data
                 will not be flagged for this, i.e. PCAL will assume
                 that the correction is unimportant.
  BADDISK....Disk numbers on which scratch files are not to
             be placed.
---------------------------------------------------------------
PCAL:  Task to determine effective feed polarization parameters.
Documentor: W. D. Cotton (preliminary version).
Related Programs: CALIB, LISTR, SPLIT, CLCOR, LPCAL, SPCAL

     Use of PCAL is also described in EXPLAIN CALIBRAT.

     Polarization calibration of synthesis array visibility data
consists of two distinct parts: 1) the determination of the effective
response of the feed to the incident radiation and the correction of
the observations to the values which would have been obtained with
perfect feeds and 2) the determination and removal of systematic phase
delay differences between the right and left hand polarization
systems.  PCAL determines the effective response of the feeds, the
polarization of unknown calibrator(s) and stores this information in
the AN and SU tables.  Routines which can apply calibration tables can
then be instructed to apply the polarization corrections by setting
the adverb DOPOL=1.

     If the systematic phase delay differences between the right and
left hand systems is time variable (e.g. variable ionispheric Faraday
rotation) then these effects need to be removed before running PCAL
(see CLCOR).  If the systematic phase offsets are essentially constant
then they may be removed after running PCAL by using RLDIF or LISTR
with STOKES='POLC'; DOPOL=1 and appropriate calibration on a source
with known polarization angle to determine the phase offsets and then
applying them using CLCOR and OPCODE='POLR'.  Note: this later method
will modify the AN table as well as the CL table.

SINGLE SOURCE FILES:

     In principle, PCAL can work on a single-source file followed by
SPLIT to apply the correction.  However, in practice, it is preferable
to convert all of the files involved to multi-source files using task
MULTI followed by DBCON with DOARRAY=TRUE to glue the files together.
DBCON should be followed by INDXR to create an index table.  The flux
densities of the calibrator source(s) to be used by PCAL should be
entered in the Source (SU) table using SETJY.  Also, see the section
on parallactic angles.
     After PCAL has been successfully run and any phase offsets have
been removed, then single source, polarization corrected files can be
obtained using SPLIT with DOPOL=1;  DOCAL=TRUE and
GAINUSE=(relevant CL table).

PARALLACTIC ANGLE:

     When used with SOLTYPE='APPR', PCAL expects that the input data
has NOT had the parallactic angle removed from the phase of the cross
hand visibility data.  The AIPS software makes this correction when
the instrumental corrections are applied, i.e., when DOPOL=1. If
this correction has been made (e.g. any data which has been through
the VLA Dec-10) then PCAL will give invalid results.  (VLA data read
by the AIPS program FILLM has not had this correction made and can be
fed to PCAL as is.)
     If SOLTYPE='RAPR' or 'ORI-' then the parallactic angle correction
SHOULD have been made before phase calibration.  Also for
SOLTYPE='ORI-' the phase reference antenna used in the calibration
process should be the same as REFANT given to PCAL.
     If you are unsure about this correction then run LISTR with
OPTYPE='MATX'; STOKES='POLC'; DPARM(1)=1; SOURCES='(your calibrator
source)'; DOPOL=-1; DOCAL=TRUE; GAINUSE=appropriate CL (or SN for
single source files) table. The parallactic angle may be determined
from LISTR using OPTYPE='GAIN'; DPARM(1)=9.  If the parallactic angle
correction has NOT been applied then the phase of the RL correlations
will vary approximately as the negative of the parallactic angle.  If
the range of phase of the RL correlator is much less than the range of
the parallactic angle then the parallactic angle correction has been
made and needs to be removed.

REMOVAL OF THE PARALLACTIC ANGLE CORRECTION:

     Before removing the parallactic angle correction by modifying the
CL table it is best to copy the current working CL table to the next
available sequence number with TACOP and modify the copy.  If
something goes wrong you can start over using the previous version
(also CLCOR refuses to modify CL table version 1).  Remember to set
the OUTNAME etc. in TACOP.
     If you have determined that the parallactic angle correction has
already been made to your data then it can be removed using CLCOR with
SOURCES=''; STOKES=''; BIF=1; EIF=0 TIMERANG=0; ANTENNAS=0; CLCORP=0;
SUBARRAY=subarray number; GAINVER=CL table no. to modify;
OPCODE='PANG'; BPARM=0.  CLCOR will remove the parallactic angle
correction by rotating the phases of the complex gains to be applied
the the data. If there is more than one subarray present then CLCOR
must be run for each subarray; the number of subarrays can be
determined from the number of AN tables present in the file as shown
by IMHEAD. After this correction is made, then PCAL should be run with
DOCAL=TRUE and GAINUSE=(the CL table modified by CLCOR).  To add the
parallactic angle correction for SOLTYPEs RAPR and ORI-, use PANG in
CLCOR with CLCORP(1)=1.

CALIBRATION DATA MEASURED WITH LINEARLY POLARIZED FEEDS

     Data obtained with systems using linearly polarized feeds
(especially the Australia Telescope) may determine the instrumental
polarization using a linear approximation.  This type of solution is
indicated in the AN table as POLTYPE='X-Y LIN '.  The standard
calibration routines will apply these corrections if adverb
DOPOL=1.
   NOTE: X-Y linear data (STOKES = -5) MUST be polarization before
attempting to use Q, U or V polarization.

SOLTYPE:
   SOLTYPE='APPR' does a fits a linear approximation to the feed
parameters and source polarizations using one or more unresolved
calibrator sources.
   SOLTYPE='RAPR' also fits a linear approximation to the feed
parameters but allows the sources to be resolved.  The method
explicitly assumes that the polarization structure has constant
position angle and is the same as the total intensity structure
with a scaling factor.  This assumption will seriously break
down if the source is significantly resolved (larger that 1 - 2
synthesized beam widths).
   SOLTYPE='ORI' fits for feed ellipticity and orientation.
Since this procedure can be quite expensive in compute time it
should only be used in cases where the linear approximation
breaks down (more than a few percent instrumental polarization).
This method can optionally solve for the R-L phase offset if a
polarization model is given.

USING RESOLVED CALIBRATORS

   Although SOLTYPEs 'RAPR' and 'ORI-' allow resolved
calibrators the assumptions inherent in their use break down in
cases of significant resolution.  In this case it may be useful
to make a few iterations of PCAL, image, and deconvolve to
develop a accurate model to give to PCAL (IN2NAME etc.).

For calibrators that are very resolved, and/or have polarization
structure, PCAL will not work well.  LPCAL was designed for
this case.

LPCAL and SPCAL

LPCAL allows you to put in multiple models for multiple source
components.  These are allowed to have different polarizations.
If you have VLBI data it is likely you will have a resolved
calibrator with varying polarization structure.  If you have
spectral line data or if you suspect that the D-terms vary
across the frequency band try using SPCAL.  However SPCAL does
not allow the polarization to vary across the calibrator (like
LPCAL).  Both LPCAL and SPCAL will work for unpolarized
calibrators.
