; BLCAL
;---------------------------------------------------------------
;! Compute closure offset corrections
;# TASK CALIBRATION
;-----------------------------------------------------------------------
;;  Copyright (C) 1995-2003, 2006-2007, 2009-2010, 2013
;;  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
;-----------------------------------------------------------------------
BLCAL     LLLLLLLLLLLLUUUUUUUUUUUU CCCCCCCCCCCCCCCCCCCCCCCCCCCCC
BLCAL   Task to compute closure offset 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 #
BLVER             0.0    46655.0   Output BL table version
                                   Data selection (multisource):
SOURCES                            Sources to calibrate with
TIMERANG                           Time range to use.
SELBAND                            Bandwidth to select (kHz)
SELFREQ                            Frequency to select (MHz)
FREQID                             Freq. ID to select.
ANTENNAS                           Antennas to solve for.
SUBARRAY          0.0     1000.0   Subarray, 0=>1
                                   Cal. info for input:
FLAGVER                            Flag table version
DOCALIB          -1.0      101.0   > 0 calibrate data & weights
                                   > 99 do NOT calibrate weights
GAINUSE                            CAL table to apply.
                                   CLEAN map (optional)
DOPOL            -1.0       10.0   If >0 correct polarization.
PDVER                              PD table to apply (DOPOL>0)
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.
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 flux included
NMAPS             0.0     4096.0   No. Clean map files
CMETHOD                            Modeling method:
                                   'DFT','GRID','    '
CMODEL                             Model type: 'COMP','IMAG'
                                   'SUBI' (see HELP re images)
SMODEL                             Source model, 1=flux,2=x,3=y
SOLINT                             Solution interval (min),
                                   0=>all times.
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.
BPARM                              Control info:
                                      1 > 0=> already divided
                                      2>0 => print statistics
BADDISK                            Disk no. not to use for
                                      scratch files.
---------------------------------------------------------------
BLCAL
Task:  This task reads a UV file, calibrates, divides by a model,
       averages the data for a specified interval on each baseline, and
       writes a BL table containing the resulting baseline calibration
       data.  For multi-source files the corrections can be applied by
       any task that applies calibration, by specifying BLVER>-1.  To
       correct data in a single source using a BL table from elsewhere,
       use TACOP to copy the BL table to the file that is to be
       corrected; then apply the corrections by running SPLIT with BLVER
       = the BL table version number.
            The uv data must have a well-determined antenna based
       calibration before BLCAL is run.  For single source files, the
       input data should be properly self-calibrated.  For multisource
       files, the antenna based gain solutions must be applied when
       running BLCAL; these solutions and the source models must be such
       that after the calibrated data are divided by the model, all data
       have amplitudes near 1 and phases near 0.  Source models input to
       BLCAL must describe ALL of the flux in the calibrators (including
       any significant confusing flux).  Images made with both values of
       IMAGR's DO3DIMAG option are handled correctly as models, as are
       multi-scale images.  Set NMAPS = NFIELD * NGAUSS.
wAdverbs:
  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.
  BLVER......BL table version number; new information can be appended to
             an existing table. 0=>create a new version.

The following are used for multi-source data files only:
  SOURCES....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.
  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, 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 overide that of FREQID.
             However, setting SELBAND and SELFREQ may result in
             an ambiguity, in which case the task will request
             that you use FREQID.
  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.
The following may be used for all data files (except as noted):
  SUBARRAY...Subarray number to use. 0=>1
  FLAGVER....(multisource) specifies the version of the
             flagging table to be applied. 0 => highest
             numbered table.  <0 => no flagging to be applied.
  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.
  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.
  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).
  IN2NAME....Cleaned map name (name).      Standard defaults.
             Note: a CLEAN image for only a single source may be given
             although it may be in a multi-source file.
             For a multi-source file, the flux of the clean components
             selected for the model are summed and scaled to the source
             flux found in the SU table.  If that flux is zero, no
             scaling is done.
  IN2CLASS...Cleaned map name (class).     Standard defaults.
  IN2SEQ.....Cleaned map name (seq. #).    0 -> highest.
  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.
  SMODEL.....A single component model to be used instead of a CLEAN
             components model; if abs (SMODEL) > 0 then use of this
             model is requested.
                SMODEL(1) = flux density (Jy)
                SMODEL(2) = X offset in sky (arcsec)
                SMODEL(3) = Y offset in sky (arcsec)
                SMODEL(4) = Model type:
                  0 => point model (only model inplemented)
             NOTE: If neither a CLEAN nor a point model is given then
             a point model using the flux densities given in the
             source table is used.
  SOLINT.....Time interval to average data for baseline
             correction in minutes. 0 => all times.
  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.
  BPARM......Control information:
  BPARM(1)...If > 0 then the data has already been divided by the model.
             No division by the model will be done.
  BPARM(2)...If this value is larger than 0.0, then the correlator
             averages and their RMSs will be printed on the monitor
             terminal and the message file.
  BADDISK....Disk numbers on which scratch files are not to be placed.
---------------------------------------------------------------
BLCAL:  Task to collect baseline-based (closure) corrections.
DOCUMENTOR: R.C.Walker (modified by W.Cotton & A.Bridle)
RELATED PROGRAMS:  CALIB, ASCAL, UVSUB, TACOP, SPLIT

                   PURPOSE

     Most modern interferometers are calibrated under the assumption
that the gains needed to calibrate each baseline are simply the
geometric means of the gains of the two antennas involved in the
baseline, i.e. that a single gain can be determined for each antenna
and can then be used to calibrate all baselines to that antenna.  This
assumption can break down at levels involved when large dynamic ranges
are required.  Possible reasons for the breakdown are mis-matched
bandpasses, pointing errors on large sources, offsets in the
correlator etc.  Errors introduced by such effects are often called
"closure errors" because they invalidate the assumption that phase and
amplitude errors are antenna based and therefore "close" around some
loop of baselines.

     The VLA often has closure errors between 0.5 and 1 percent.
These errors vary in time in ways that are not yet fully understood,
but they are sufficiently constant that measurements of closure
offsets made within a few hours of observations can be used to improve
high dynamic range maps significantly (see Walker, VLA Scientific Memo
152). If the dynamic range (measured as the ratio of peak to
off-source rms) is less than 10,000, closure offsets are probably not
causing problems.  If the dynamic range is near 10,000:1 and the map
is not noise-limited, closure offsets may be the limiting effect.
Correction of closure offsets may always be needed to obtain dynamic
ranges >10,000:1.  With closure offset corrections, dynamic ranges
>10,000:1 have been achieved (see Lecture 11 in the Course Notes of
the NRAO Summer School on "Synthesis Imaging", held on August 5-9
1985).

     Closure offsets are best measured by observing a strong, compact
source.  The observing time and source strength should be such that
the data on each baseline has a SNR of nearly 1000.  The data from the
compact source should be accurately calibrated before running BLCAL;
the data will be divided by the specified model before averaging.  If
multiple compact sources are used for calibration in a given run of
BLCAL, they should be pointlike to high accuracy.  Since this will
seldom be the case, BLCAL can be run once for each source and the
solutions put in the BL table specified by BLVER (unless you set
BLVER=0,in which case each run will generate a separate table).

     VLA data provided to BLCAL should have amplitudes within a few
percent of 1.0 and phases within a degree or two of 0 after division
by the model; deviations may be worse for other (especially VLBI)
arrays. The data should be examined carefully using LISTR or PRTUV
before running BLCAL.

     Once a properly calibrated and edited data set is available,
BLCAL can be run to average the data and to generate BL table that the
standard calibration software can use for baseline based corrections.

     To apply baseline based corrections from elsewhere to a single
source file, first use TACOP to copy the BL table to the file to be
corrected.  Then run task SPLIT, with BLVER set to the BL table
version number.

     For multi-source files, setting BLVER to the BL table version
number, and applying calibration, will apply the baseline corrections
along with the antenna based corrections.

     BLCAL calculates means and rms's for the baseline corrections and
writes the results in the form of amplitudes and phases in the message
file.

     Division of the data by the model may be done in one of four
ways.  1) External to BLCAL, this is indicated by BPARM(1)=1.  2)
Division by a CLEAN model, this is indicated by filling in IN2NAME
etc.  3) Specifying a point model, this is indicated by the
appropriate values in SMODEL.  4) Using a point source at the phase
center with the flux density given in the source (SU) table.  This
method is used when either none of the above methods are requested or
multiple sources are requested.
