; BPASS
;---------------------------------------------------------------
;! computes spectral bandpass correction table
;# TASK CALIBRATION AP SPECTRAL
;-----------------------------------------------------------------------
;;  Copyright (C) 1995-2006, 2008-2011
;;  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
;-----------------------------------------------------------------------
BPASS     LLLLLLLLLLLLUUUUUUUUUUUU CCCCCCCCCCCCCCCCCCCCCCCCCCCCC
BPASS     Task to generate a "Bandpass" (BP) table.
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
CALSOUR                            Bandpass calibrator sources.
QUAL            -10.0              Calibrator qualifier -1=>all
CALCODE                            Calibrator code '    '=>all
UVRANGE                            UV range to select
TIMERANG                           Time range to select
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
SUBARRAY          0.0     1000.0   Subarray, 0=>all
ANTENNAS                           Antennas to select

                                   CLEAN map (optional)
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)
SMODEL                             Source model, 1=flux,2=x,3=y
                                   See HELP SMODEL for details.

                                   Control options
DOCALIB          -1.0      101.0   > 0 calibrate data & weights
                                   > 99 do NOT calibrate weights
GAINUSE                            CL table to apply (SN table
                                   to apply to single-source)
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
SOLINT                             Solution interval (mins)
                                   -1 => do whole time range
SOLTYPE                            Soln type,'  ','L1','GCON',
                                      'R', 'L1R', 'GCOR'
REFANT                             Reference antenna
OUTVERS                            Output BP table version
                                   0 => a new table to be
                                        generated.
SMOOTH                             Smoothing function.
                                   BE VERY CAREFUL HERE.
ANTWT                              Ant. wts (0 => 1.)
WEIGHTIT          0.0        3.0   Modify data weights function
MINAMPER          0.0              Amplitude closure error
                                   regarded as excessive in %
MINPHSER          0.0              Phase closure error regarded
                                   as excessive in degrees
BPASSPRM                           Control information:
                                   1: if > 0 use only the
                                      autocorrelation data.
                                   2: print level - see help
                                   3: If > 0 do not divide data
                                      by source model
                                   4: If > 0 store phases only
                                      in the BP table.  If < 0
                                      store amplitudes only.
                                   5: Divide by 'channel 0'
                                      **** CHANGED MAY 2010 ****
                                   6: amp closure error limit -
                                      print channels averaging
                                      over this if (2) > 0
                                   7: phase closure error limit
                                      print channels averaging
                                      over this if (2) > 0
                                   8: > 0 => scalar average
                                   9: > 0 => interpolate over
                                      flagged channels if poss.
                                   10:1 => normalize amplitudes
                                        using all channels
                                      2 => normalize amplitudes
                                        using ICHANSEL channels
                                      3 => normalize amplitudes
                                        and zero average phase
                                        using ICHANSEL channels
                                      4 => normalize amplitudes
                                        and zero average phase
                                        using all channels
                                      0 => no deliberate norm.
                                   11: > 0 solution weights are
                                      independent of channel
                                      = -1 weights scaled
                                        by amplitude**2
                                      < -1.5 weights scaled by
                                        1 / amplitude**2
ICHANSEL                           Array of start and stop chan
                                   numbers, plus a channel
                                   increment and IF to be used
                                   to select channels to sum to
                                   find a 'channel 0'.  If all
                                   0, range set to inner 75% of
                                   observing band.
SPECINDX                           Spectral index to correct
SPECURVE                           Spectral index curvature
                                   'Channel 0' uv-data
IN3NAME                            Channel 0 uv name (name)
                                   must be '' to suppress option
IN3CLASS                           Channel 0 uv name (class)
                                   must be '' to suppress option
IN3SEQ            0.0     9999.0   Channel 0 uv name (seq. #)
IN3DISK           0.0        9.0   Channel 0 uv disk unit #
BADDISK           0.0     9999.0   Disks to avoid for scratch
----------------------------------------------------------------
BPASS
Task:  To create a 'BP' (bandpass) table which will contain the bandpass
   response functions of the antennas. The program can form the
   functions in two ways: a) by decomposing the baseline-based functions
   (using a least-squares method) into the antenna-based complex
   bandpass function, or b) by using the autocorrelation data as the
   amplitude part of the function and setting the phase of the function
   to zero.  The default is to divide the data by the so-called 'channel
   0' before determining the bandpasses, this removes the requirement of
   calibrating the data first.  Data from the VLBA correlator undergo
   another operation within BPASS.  The correlator uses a geocentric
   reference frame and so all data are lobe-rotated to the centre of the
   Earth rather than to a reference station for a given baseline, this
   means that the diurnal aberration is added to the lobe-rotation
   resulting in a shift of the bandpass away from the RF frequency. This
   shift varies from source to source. BPASS will remove this additional
   frequency shift and store the bandpasses in the traditional manner,
   as though no extra diurnal lobe-rotation was applied.
   Model images made with both values of IMAGR's DO3DIMAG option are
   handled correctly, as are multi-scale images.
   Set NMAPS = NFIELD * NGAUSS.

   Unless you normalize the output bandpass with BPASSPRM(5) and/or
   BPASSPRM(10), it is important that SETJY or GETJY have been used on
   the calibrator source in advance.  This is particularly true if you
   choose to use the spectral index parameters (the default for 3C286,
   3C48, 3C147, and 3C138).
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.
  CALSOUR....List of sources for which bandpass response functions are
             to be determined.  All ' ' = all sources; a "-" before a
             source name means all except ANY source named. If the data
             file is a single-source file no source name need be
             specified.  If both IN2NAME and IN2CLASS are specified,
             but multiple sources are selected, BPASS will quit.
  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.
  UVRANGE....Range (min, max) of projected baselines to include
             0,0 => all baselines (units: klamda)
  TIMERANG...Time range of the data to be selected. In order: Start day,
             hour, min. sec, end day, hour, min. sec. Days relative to
             reference 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
             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.
  BIF........First IF to select. 0=>1
  EIF........Highest IF to select. 0=>all higher than BIF
             WARNING: if you make a BP table with varying selections of
             BIF and EIF, then some records will contain some good IFs
             and some blanked ones and other records, potentially at
             about the same time will contain different good IFs and
             different blanked ones.  This can confuse DOBAND > 1
             bandpass application methods.  Task BPSMO should be used
             to fill in the balnked solutions either in existing records
             or in a regularly spaced set of records.
  SUBARRAY...Subarray number to select. 0=>all.
  ANTENNAS...A list of the antennas for which bandpasses are to be
             determined.  If any number is negative then all antennas
             listed are NOT to be used and all others are.
The following specify a CLEAN model to be used if a single source was
specified in SOURCES:
  IN2NAME....Cleaned map name (name).      ' ' => no Clean model
             Note: a CLEAN image for only a single source may be given
             although the uv data may be in a multi-source file.
             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.
  IN2CLASS...Cleaned map name (class).     ' ' => no Clean model
             If a Clean model is specified, then only one source may
             be selected (multi-source files) and no SMODEL may be
             specified (single-source files).
  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.....For single-source files only: a single component model to
             be used instead of a CLEAN components model; if SMODEL(1)
             > 0 then use of this model is requested.  Note that
             IN2NAME or IN2CLASS must be blank if SMODEL(1) > 0 and
             both must be specified if SMODEL(1) <= 0 for
             single-source files.
                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
                  1 => elliptical Gaussian and
                       SMODEL(5) = major axis size (arcsec)
                       SMODEL(6) = minor axis size (arcsec)
                       SMODEL(7) = P. A. of major axis (degrees)
                  2 => uniform sphere and
                       SMODEL(5) = radius (arcsec)
  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).
             The calibration is applied prior to the bandpass
             determination.  This is useful even when dividing by
             channel 0 determined from the same data set since the
             data amplitude enters into the weights used in solving
             for the bandpass.
             ** N.B. This option must be used with care when also using
             ** the IN3NAME (external channel 0 file) option.  AIPS
             ** cannot apply calibration to 2 files at the same time.
             ** Therefore, if you use the IN3NAME option you must set
             ** DOCALIB to the calibration state of the external file
             ** (false if it is uncalibrated, true if it has been
             ** calibrated e.g. by SPLIT).
  GAINUSE....Version number of the CL table to apply to multi-source
             files or the SN table for single-source files.
             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 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.
             ** NOTE - AIPS does not now have a way to "concatanate"
             ** BP tables.  Thus, if one determines a BP table having
             ** applied a BP table, one has no way to get that net
             ** calibration applied to the data.  Nonetheless, it may
             ** be of interest, for example, to use DOBAND=1 for
             ** example and then to see what is left as a
             ** time-variable BP, examining it with BPLOT.
  SOLINT.....The interval over which to average the data before solving
             for the bandpasses (MINS).  (0 => scan FOR MULTI-SOURCE
             files, whole time range for single-source files,
             < 0 => whole time range)
  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
             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.
  REFANT.....The antenna to use as a reference in the least-squares
             solution.
  OUTVERS....The version of the BP table to fill. The default
             (OUTVERS = 0) will cause a new table to be generated.
  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).
             Note that any use of SMOOTH in BPASS will require that
             the same SMOOTH values be used when accessing any data to
             be calibrated by the BP table produced by BPASS.
  ANTWT......Antenna weights for up to 30 antennas. (0=>1.0)
  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
  MINAMPER...Amplitude closure error regarded as excessive in per cent.
             Summaries of the number of excessive errors by antenna and
             by channel are printed and, if BPASSPRM(2) > 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.
             Summaries of the number of excessive errors by antenna and
             by channel are printed and, if BPASSPRM(2) > 1, up to 1000
             of the individual failures are printed.  0 => do not check
             or report "excessive" closure errors of any sort.
  BPASSPRM...Control information:
             (1) > 0 => fill BP table with autocorrelation data only,
                   setting the phases to 0..
             (2) print level: 0 -> no diagnostic information except
                           for a count by antenna of closure errors
                           exceeding MINAMPER and/or MINPHSER (if the
                           adverbs and the count are > 0).
                   > 0  => statistics on closure error by channel (but
                           only those exceeding BPASSPRM(6) % or
                           BPASSPRM(7) degrees) and counts of errors
                           exceeding MINAMPER and/or MINPHSER.
                   > 1  => plus explicit closure failures (MINAMPER and
                           MINPHSER above)
                   > 11 => plus antenna solutions for each channel
                   > 13 => plus rms at each iteration
                   > 14 => plus input data and gains
                   RECOMMENDATION: Set MINAMPER and MINPHSER moderately
                   high to make a big deal only about serious
                   excursions, but set BPASSPRM(6 and 7) fairly low
                   since the noise spectrum in the final images seems to
                   mimick the closure error spectrum.  Set BPASSPRM(2) =
                   1 to get a modest amount of output.
             (3) > 0 => do not divide data by a model of the source. The
                   default is that the data will be divided by a source
                   model.  The model used will be (in order of
                   decreasing priority):
                       (a)  the flux density specified in the SU table
                       (b)  a point source model (SMODEL)
                       (c)  CLEAN components,
                   If BPASSPRM(5) <= 0, the data will not be divided by
                   a source model.
             (4) > 0 => store only the phase of the complex bandpass
                   function in the BP table. You may want to do this if,
                   for instance, your data have been normalized by the
                   autocorrelation data as is possible at the VLA.
                 < 0 => store only amplitudes of the complex bandpass
                   function in the BP table.  May be needed to correct
                   aliasing at the VLA.
             (5) Divide by channel 0 option. *** CHANGED MAY 2010 ***
                   If 0 (-0.5 to 0.5) the value of "channel 0" is
                   determined and applied (divided into the data) on a
                   record-by-record basis, either from the average of
                   channels specified by ICHANSEL or from an external
                   file (if IN3NAME and IN3CLASS are specified).  If
                   -1 (-1.5 to -0.5), the same is done but the
                   amplitude of channel 0 is made 1.0 so a phase-only
                   correction is made.  If -2 (< -1.5), divide by the
                   average of channels specified by ICHANSEL (no
                   external file) after the time averaging.  This
                   option allows a normalized bandpass to be found
                   correcting for any uncalibrated variations in the
                   continuum.  If you have poor phase stability use 0
                   or -1, if you have decent phase stability use -2.
                   If you have good phase stablility use +1.  Note
                   that division by channel 0 adds biased noise
                   because the channel-averaged amplitude is by its
                   very nature biased;  the -2 option should be less
                   biased since the data have been vector averaged in
                   time first and so are less noisy. the -1 (phase
                   only) division should avoid the amplitude bias but
                   then the banddpasses are not normalized.  That can
                   be corrected later with BPASSPRM(10) options.

                   If > 0.5, do no normalization before determining the
                   solutions.  This requires good stability during
                   each integration period.  BPASSP(10)=3 still allows
                   a normalized solution which may be even less biased
                   since it is on an antenna rather than a baseline
                   basis.

                   Note also that a channel 0 may not be determined
                   sensibly if the phase changes a lot across the pass
                   band except by setting ICHANSEL to select a very few
                   channels.

                   ********  Note, if normalization is not done on a
                   record-by-record basis, users must be very careful
                   about averaging different calibration sources.  Any
                   channel-dependent flagging will cause the different
                   sources to be differently weighted in the partly
                   flagged channels than in the completely unflagged
                   ones.  The shape of the bandpass in this case will
                   not be correct.  Therefore, if channel-dependent
                   flagging is done and multiple calibrators averaged,
                   the normalization must be done on a record basis.
             (6) > 0 => if the average amplitude closure error in a
                   channel exceeds BPASSPRM(6) per cent in a scan, a
                   message will be generated if  BPASSPRM(2) > 0.  Thus,
                   if BPASSPRM(6) = 2, corrected relative calibrator
                   data averaging outside the range 0.98 - 1.02 in a
                   channel/scan will be printed.
             (7) > 0 => if the average phase closure errors in a channel
                   and scan exceed BPASSPRM(7) degrees, they will be
                   printed if BPASSPRM(2) > 0.
             (8) > 0 => the amplitudes will be scalar averaged before
                   determining the solutions.
             (9) > 0 => the task will attempt to interpolate over
                   flagged channels in the antenna bandpass spectra. It
                   will inform the user if it does this. If this is
                   necessary you should examine your data carefully, it
                   is usually indicative of a problem of some sort.
                   The interpolation is done atutomatically with the
                   VLBA since flagged channels would destroy the
                   necessary shifting algorithm.  For the VLBA, this
                   may be left 0.
            (10) The BPASS solution may be used to apply changes to
                 the average amplitude and phase.  If this is not
                 intended, then it is essential to normalize the
                 solutions in some way, by dividing by channel 0
                 (BPASSPRM(5)) and/or normalizing after the solution
                 is determined.  Note that modes 1 and 2 below may
                 shift the average phase although the average
                 amplitude will remain unchanged.
                 = 1 => normalize the amplitude portion of the bandpass
                   function by the area under the curve using all
                   spectral channels. This is useful for VLBI data
                   where amplitudes are scaled by the full bandwidth
                   and a useful 'channel 0' is sometimes difficult
                   to obtain.
                 = 2 => do the same but using only the channels in
                   ICHANSEL.
                 = 3 => normalize amplitudes and shift the average
                   phase to zero in each antenna bandpass using the
                   channels specified in ICHANSEL.
                 = 4 => normalize amplitudes and shift the average
                   phase to zero in each antenna bandpass using all
                   channels.  This is for VLBI and allows ICHANSEL to
                   be used solely for selecting "channel 0".
            (11) > 0 => make weights given to the solution be
                   independent of channel.  They will depend on IF,
                   baseline, and polarizations in any case.  This option
                   saves on dynamic memory.
                 = -1 => use weights scaled by amplitude**2 (Probably
                         not needed - weights are adjusted for
                         division by channel zero in any case)
                 < -1.5 => use weights scaled by 1/amplitude**2
                 Note that the weights actually used in the solution
                 are further adjusted by WEIGHTIT.
  ICHANSEL.. Array of start, stop, and increment channel numbers plus
             an IF used for channel selection in the averaging to
             compute a channel 0.  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 the inner 75% of that IF is used.  Note that these
             are absolute channel numbers; they are not relative to
             BCHAN.
  SPECINDX...The fit bandpasses are corrected for a calibrator
             spectral index.  The calibrator flux is assumed to be
             frequency^SPECINDX so the bandpass is multiplied by
             (freq/f0) ** SPECINDX when SPECINDX is not zero.
             If SPECINDX = 0 and the calibrator source is one of
             3C286, 3C48, 3C147, or 3C138, SPECINDX and SPECURVE will
             be set to the known (Perley 2010) values from SETJY.
             To prevent this, set SPECINDX < -5 or > 5.
  SPECURVE...If SPECINDX is not zero and is between 5 and -5, a
             curvature term may be added to the above correction as
                 A = log(f/f0) * SPECINDX + log(f/f0)^2 * SPECURVE(1)
                   + log(f/f0)^3 * SPECURV(2) + log(f/f0)^3 * SPECURV(2)
             and then multiply by 10^(-A/2.) where the 2 is because
             the BP tables are voltages rather than powers.  f0 is
             taken to be 1.0 GHz for simplicity and all logs are base
             10.0.  Needless to say, the spectral index option should
             be used on only one calibrator source at a time.

The following specify a uv-file which can be used as an external
'channel 0'. If all the IN3* adverbs are blank, then the task will
determine channel 0 from the line data itself, unless BPASSPRM(5) = 1,
in which case no channel 0 division will be done.  Note that this option
is used unless IN3NAME and IN3CLASS are both = ' '.
  IN3NAME....Channel 0 uv name (name).      Standard defaults.
  IN3CLASS...Channel 0 uv name (class).     Standard defaults.
  IN3SEQ.....Channel 0 uv name (seq. #).    0 -> highest.
  IN3DISK....Disk drive # of Channel 0 uv   0 => any.
             ** N.B. This option must be used with care when also using
             ** the IN3NAME (external channel 0 file) option.  AIPS
             ** cannot apply calibration to 2 files at the same time.
             ** Therefore, if you use the IN3NAME option you must set
             ** DOCALIB to the calibration state of the external file
             ** (false if it is uncalibrated, true if it has been
             ** calibrated e.g. by SPLIT).
  BADDISK....A list of disks on which scratch files are not to
             be placed.  This will not affect the output file.
----------------------------------------------------------------
BPASS:  Task to determine antenna bandpass functions from calibrator
        data
Documentor:  P.J.Diamond
Related Programs: CALIB, POSSM, LISTR, SPLIT, TVFLG

This task is the AIPS routine for generating the bandpass correction
file which can be applied to spectral line format data. The program has
two modes of operation:
 (1) It is able to generate a full complex bandpass response function
     for each antenna by decomposing the baseline-based functions (i.e.
     the cross-power spectra) into antenna-based complex functions using
     a least-squares method analagous to self-calibration.
 (2) It can can generate the real (amplitude only) part of the bandpass
     response function using autocorrelation data, if available. In this
     mode it sets the phase of the bandpass function to zero.

The calibration sources that are used to generate the bandpass
response functions need not be point sources. The generality
of the routine is such that if the user has determined the
structure of the calibrator source the visibility data can be
divided by the source model prior to the bandpass determination.
In addition if the bandpass calibrator is strong enough to be
detected at all times on all baselines (typical VLA case) then
the spectral line data may be divided by the so-called 'channel
0' before the bandpasses are determined, this is the default
mode of operation.

The bandpass solutions determined by BPASS are written to the
BP table extension of the input uv data set. They can then be
applied in a variety of ways to the data through the use of the
adverb DOBAND.

To run BPASS you should specify at least:
  (1) the input uv data set (INNAME, INCLASS, INSEQ, INDISK)
  (2) the sources you wish to use in order to determine the
      bandpass shapes (SOURCES)
  (3) any data selection parameters:
      UVRANGE   -> a range (min,max) of projected baselines to
                   include, the default is all data
                   (units: klambda)
      TIMERANG  -> a time range of data to select, default = all
      BIF, EIF  -> the IF numbers to determine bandpasses for,
                   default = all.
      ANTENNAS  -> the antennas to determine the bandpasses for,
                   default = all.

"CLEAN" component models:
BPASS 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.

Normalization:
In most cases you will want to normalize the bandpass, particularly if
your data is VLBI where the amplitude scale is based on system temperatures.
This can be done in one of two ways, either divide by "channel 0" (BPASSPRM(5))
or normalize the amplitudes and, possibly, shift the phases (BPASSPRM(10).
Channel 0 can be defined in two ways, either by averaging all or some portion
of the channels for the bandpass calibrator or useing an external channel 0.
If there is poor phase stability over the bandpass calibrator scan(s) then
BPASSPRM(5)=0 should be used, even though it will add some noise, since it
does the channel 0 on a record by record bases before averaging in time.
Otherwise BPASSPRM(5)=-1 is recommended.  For VLBI it may be necessary to
use BPASSPRM(10) which does not produce a complex channel 0 but normalizes
the amplitudes and can also shift the phases to zero.  NOTE THAT BPASSPRM(10)
(AND BPASSPRM(5)=-1) SHOULD ONLY BE USED IF THE PHASES FOR THE BANDPASS
CALIBRATOR ARE STABLE ACROSS THE ENTIRE SCAN(S).  When the bandpass is
applied the bandpass is averaged (by default) over all time, if the phases
are not stable then the normalization will be go haywire.

The control parameters:
The program is controlled by a series of adverbs , the default setting
of which should give the user sensible results. The adverbs and their
effect on the data are described below.

DOCALIB:
If DOCALIB is set to 1 then BPASS will calibrate the data selected
before attempting to determine any bandpass response functions.  The
default (DOCALIB = 0) is no calibration.  If you have a useful CL table,
it should be applied.  The amplitude of channel 0 scales the weights
of the ratios used in the bandpass solutions.  If one antenna has a
significantly different gain than another, leaving out the gain
correction will significantly alter the relative weights.  Applying
delay and rate corrections in VLBI data sets is also important prior to
determining channel 0.
N.B. This option must be used with care when also using the IN3NAME
(external channel 0 file) option.  AIPS cannot apply calibration to 2
files at the same time.  Therefore, if you use the IN3NAME option you
must set DOCALIB to the calibration state of the external file (false if
it is uncalibrated, true if it has been calibrated e.g. by SPLIT).

GAINUSE:
GAINUSE specifies the version of the CL table to be applied in the
calibration. If GAINUSE = 0 then the highest numbered version will be
used.

FLAGVER:
If FLAGVER is .ge. 0 then if a flagging (FG) table is present the data
will be flagged before any other operation.  The default (FLAGVER = 0)
is to use the highest numbered version.

SOLINT:
SOLINT defines the time interval over which to average the uv-data
before solving for the bandpasses.  The default (SOLINT = 0) is the
whole scan defined by the NX table.  SOLINT = -1 will average all data
selected before determing the bandpass functions.

REFANT:
REFANT defines the antenna to be used as the reference in the least
sqaures solution. Try to choose an antenna with good signal to noise and
that was present for as long as possible through the observing run. The
default (REFANT = 0) causes the program to choose a reference antenna
itself, it tries to do this sensibly.

OUTVERS:
The version of the BP table to fill.  The default (OUTVERS = 0) will
cause a new table to be generated.

SMOOTH:
Specifies the type of spectral smoothing that can be applied
to the data before the bandpasses are determined. See
HELP SMOOTH for more details.

** WARNING ** If SMOOTH is specified then all channels of
the database must be present in a single file, it will not
work properly if for instance you have split your data into
4 files each of 16 channels. The rest of BPASS will work
with no problem in that mode but the SMOOTH option will
result in corrupted data.

ANTWT:
Each antenna can be assigned a weight which only affects its
weighting in the least-squares solution. So if you have an
antenna which is noisy you can set its weight to 0.1 and all
the others to 1 and it will have a very small effect on the
bandpass determination.

BPASSPRM:
The BPASSPRM parameters control various options within the
program.  See the help section too for details:
  BPASSPRM(1): if > 0 then only the autocorrelation data are used to
            determine the bandpasses, the phases of the bandpass
            functions are then not determined and are set to zero.
            This is sometimes useful for VLBI, especially prior to
            corrections for fring rates and delays.
  BPASSPRM(2): print level, the higher it is set the more tedious crap
            will be printed on your terminal.  Level 1 is useful for
            statistical reports on closure errors exceeding
            BPASSPRM(6) (%) and BPASSPRM(7) (degrees).  Level 2 gets
            explicit closure failures > MINAMPER and/or MINPHSERR.
            Levels 11, 13, 14 are for debugging.
  BPASSPRM(3): if > 0 do not divide the data by a source model.  If
            BPASSPRM(5) > 0, then the point source model (if SMODEL >
            0), the point source model (SU table flux), or a Clean
            image (Celan components) model will be used.
  BPASSPRM(4): if > 0 store the phases only in the BP table.
  BPASSPRM(5): if = 0 then calculate channel 0 by vector averaging
            channels ICHANSEL (default = centre 75% of the observing
            band) and divide the line data by the result on a record
            by record basis.  This compensates for continuum shifts in
            phase and amplitude over the averaging period (which can
            average the data to nearly zero) at the cost of adding
            some noise.  If you have very good phase stability, set
            BPASSPRM(5)=-1 to do the channel zero division on the
            averaged data (over SOLINT) rather than on the individual
            records.  This adds less noise.
            Warning: if channel-dependent flagging has been done and
            multiple sources are being averaged, then record-by-record
            division by channel zero must be done.
            Further warning: if the phase changes a lot across the
            band (i.e due to uncalibrated delay errors), then channel
            zero may be used only if ICHANSEL selects only a very few
            channels.
  BPASSPRM(6): amplitude closure allowed level before triggering the
            displays selected by BPASSPRM(2) > 0 in per cent.
  BPASSPRM(7): phase closure allowed level before triggering the
            displays selected by BPASSPRM(2) > 0 in degrees.
  BPASSPRM(8): > 0 => use scalar averaging for the amplitude in
            determining the gain solutions in each SOLINT.
  BPASSPRM(9): > 0 => use interpolation to determine solutions for
            failed (e.g. all flagged) channels.
  BPASSPRM(10): > 0 => normalize the output, antenna solutions.
             =1  normalize amplitude over all channels.
             =2  normalize amplitude using channels in ICHANSEL to
                 determine normalization.
             =3  normalize amplitude and phase using channels in
                 ICHANSEL to determine normalization.  For VLBI, set
                 ICHANS = 1,Nchan where Nchan is the total number of
                 channels.
             Note that VLBI is normalized over the full bandwidth
             (using Tsys measurements) while the VLA traditionally
             uses the center 75% only (using "channel 0" data sets).
