; WFCLN
;---------------------------------------------------------------
;! Wide field and/or widefrequency  CLEANing/imaging task.
;# Task AP Imaging OOP
;-----------------------------------------------------------------------
;;  Copyright (C) 1995-1997, 1999, 2002
;;  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
;-----------------------------------------------------------------------
WFCLN     LLLLLLLLLLLLUUUUUUUUUUUU CCCCCCCCCCCCCCCCCCCCCCCCCCCCC
WFCLN:  Wide field imaging/CLEAN task - use IMAGR instead
INNAME                             Input UV data (name)
INCLASS                            Input UV data (class)
INSEQ                              Input UV data (seq. #)
INDISK                             Input UV data disk drive #
IN2NAME                            UV work file name
IN2CLASS                           UV work file class
IN2SEQ           0.0        0.0    UV work file seq - MUST BE 0
IN2DISK                            UV work file disk
BCHAN            0.0     8192.0    Low freq. channel 0 for cont.
ECHAN            0.0     8192.0    Highest freq channel
CHANNEL                            Restart channel number
NCHAV                              Number of chan. to average.
CHINC                              Channel incr. between maps.
STOKES                             Stokes parameters (see HELP)
BIF                                First IF in average.
EIF                                Last IF in average.
OUTNAME                            Output image name (name)
OUTDISK                            Output image disk drive #
OUTSEQ          -1.0     9999.0    Output seq. no.
OUTVER                             CC ver. no (Continuum only)
CELLSIZE      1.E-12               (X,Y) size of grid in asec
IMSIZE          0.0      4096.     Minimum image size
NFIELD          0.       4096.     Number of fields (max 4096)
FLDSIZE         0.       4096.     Size of each field.
RASHIFT                            RA shift per field (asec)
DECSHIFT                           DEC shift per field (asec)
NBOXES             0.0        50.0 Number of boxes for CLEAN
                                   NB: field 1 only.
CLBOX             -2.0      4096.0 Four coordinates for each box
UVTAPER         0.                 (U,V) Gaussian taper
                                     units are kilo-lambda
UVRANGE         0.                 Min & max baseline (klambda)
UVWTFN                             UV dist. weight function
                                     blank => uniform
UVBOX           0.        128.     Additional rows and columns
                                   used in weighting.
ZEROSP                             0-spacing fluxes and weights
XTYPE           0.         10.     Conv. function type in x
                                     default spheroidal
YTYPE           0.         10.     Conv. function type in y
                                     default spheroidal
XPARM                              Conv. function parms for x
YPARM                              Conv. function parms for y
GAIN               0.0         2.0 CLEAN loop gain
FLUX                               Minimum CLEAN component (Jy)
MINPATCH           0.0             Min. BEAM half-width in AP.
NITER              0.0             Maximum # of CLEAN components
BCOMP                              Begin at BCOMP component
                                   Specify for each field.
BMAJ            -999.9             FWHM(asec) major axis CLEAN
                                   restoring beam.
BMIN            -999.9             FWHM(asec) minor axis CLEAN
                                   restoring beam.
BPA             -360.0       360.0 CLEAN beam position angle
PHAT               0.0       999.0 Prussian hat height.
FACTOR            -5.0         5.0 Speedup factor see HELP
CMETHOD                            Modeling method:
                                   'DFT','GRID','    '
CPARM                              Task enrichment parameters
                                   (1) Antenna diameter (m)
                                   (2) Source Spectral index
                                   (3) Frequency scaling factor
                                   (4) >0 => do DFT imaging
                                   (5) >0 => scale residuals
                                   (6) Halfwidth in x of beam
                                   (7) Halfwidth in y of beam
GUARD             -1.0         0.9 x,y guard band fractional
                                   radius
MAXPIXEL           0.0    500000.0 Maximum pixels searched in
                                   each major cycle.
BADDISK           -1.0      1000.0 Disks to avoid for scratch.
BOXFILE                            Input file for clean boxes
                                   ' ' => use NBOXES, CLBOX
----------------------------------------------------------------
WFCLN
Type:  Task
 Use:  Wide field imaging/CLEANing task.  WFCLN has been replaced by
       IMAGR for all uses.

       WFCLN does a visibility base CLEAN similar to MX but
       offers a variety of corrections related to imaging wide
       fields and/or multi or wideband frequency observations.
       These are:
         1) Relative frequency dependent primary beam
       corrections in the CLEAN subtractions from the visibility
       data.
         2) Simple correction for source spectral index.
         3) Correct errors in assumed center frequency.
         4) Uses double size beam if possible for CLEANs.
         5) Labels images with average zenith and parallactic
       angles so that snapshot VLA images can be corrected with
       OHGEO for misaligned coplanar array geometric distortion.
         6) Supports 3-D DFT imaging to avoid noncoplanar array
       image distortion. (THIS IS REALLY SLOW!)
         7) After CLEANing the residuals may be scaled by the
       ratio of the restoring beam area to the dirty beam area.
       CPARM(5) > 0 enables this option.  The dirty beam area is
       determined in a box centered on the peak of half width
       CPARM(6) in x (RA) and CPARM(7) in y (dec).

Adverbs:
  INNAME.....Input UV data file (name).       Standard defaults.
  INCLASS....Input UV data file (class).      Standard defaults.
  INSEQ......Input UV data file (seq. #).     0 => highest.
  INDISK.....Input UV data file disk drive #. 0 => any.
  IN2NAME....UV data work file name.  This file is used as the
             scratch file and may be used when restarting WFCLN
             or to examine the final residuals. Default=OUTNAME.
             RESTARTING WITH A PRE-EXISTING FILE APPEARS NEVER
             TO BE QUICK IN WFCLN AND IS REPORTED TO CAUSE THE
             TASK TO FAIL SOMETIMES.  THEREFORE, YOU WILL ALWAYS
             BE GIVEN A NEW WORK FILE.
  IN2CLASS...UV work file class. Default='WFCLN'
  IN2SEQ.....UV work data file sequence number.
             <= 0 => highest existing + 1.
             IN2SEQ IS FORCED TO BE 0 TO CREATE A NEW WORK FILE
             EVERY TIME.  (See above)
  IN2DISK....UV work data file disk number.
  BCHAN......First channel number to image, 0=>1.
             Channel numbers are 1 relative as defined in the
             input data file.
  ECHAN......Highest channel number to to include in image,
             0=>MAX   The actual # of output channels will be
                  (BCHAN-ECHAN+1-NCHAV)/CHINC + 1
             Thus, ECHAN is the highest channel in the input
             averaged into the output.
             There is a limit of 46655 channels.
  CHANNEL....To restart a map/CLEAN with a given frequency
             channel, specify that (input) channel in CHANNEL
  NCHAV......NCHAV is the number of channels to be averaged
             together in in the gridding process.  0 => 1.
             If this value is less than the total number of
             channels, then a multi-channel image will result.
  CHINC......Number of input channels to skip between images.
             0 => 1
  STOKES.....Make images with this STOKES parameter.  Unlike
             UVMAP only one STOKES is permitted per execution.
             (A beam is made for each frequency channel)
             'I', 'Q','U', 'V', 'R' (=RCP), 'L' (=LCP)
  BIF........The lowest numbered IF to include.  Multiple IFs
             can be included in a bandwidth synthesis average.
             0 => 1.
  EIF........The highest numbered IF to include. 0 =>highest.
             Note: not all data sets will have IFs.
  OUTNAME....Output image name (name).       Standard defaults.
  OUTDISK....The disk drive # of output images.  0 => highest with
             space (note: map and Beam go on same disk.  Note:
             OUTCLASS='xCLnnn' where x=Stokes, nnn=field number and
             'xBM001' is the beam CLASS.  If NITER=0,
             OUTCLASS='xIMnnn'
  OUTSEQ.....Output sequence number.
             Note: All maps and beam have same sequence number.
             0 => highest to produce unique maps and beam.
  OUTVER.....CC table version number for continuum data only.
             For line data the channel number is used for the
             version number.
  CELLSIZE...(X,Y) pixel separation in asec.
  IMSIZE.....(X,Y) The minimum desired size of the fields, regardless
             of the FLDSIZE for component search.
  NFIELD.....The number of fields to map in the antenna beam.
             Up to 4096 are allowed but should be non overlapping.
  FLDSIZE....(X,Y) field size in pixels for the component search
             during cleaning; one per field. Should be in the range
             32X32 to 4096X4096. Output image size will be increased
             to the next highest power of two, but only the region
             specified will be searched for components.  Default is
             IMSIZE-10
  RASHIFT....RA shift of the phase center of each field from the tangent
             point of the uv data in asec.  Map center = tangent point +
             shift. If X>0 shifts map center to east.  NOTE: RASHIFT is
             a shift in RA scaled by cos (Dec_0) as
                Ra_new = RA_0 + RASHIFT/cos (Dec_0)
             where _0 => the tangent point in the uv data.  If the UV
             data have been rotated then RASHIFT and DECSHIFT refer to X
             and Y in the new coordinate system.
             The DO3DIMAG option in IMAGR is not supported by WFCLN.
  DECSHIFT...Declination shift of map center from tangent point of each
             field in asec.  Map center = tangent point + shift.  If Y>0
             shifts map center to north.
  NBOXES.....Number (<=50) of rectangular search boxes to search
             on the first field; the clean window in all other
             fields is given by  FLDSIZE.  0 => use FLDSIZE to
             determine windows on field 1.
  CLBOX......A 4x50 array with the BLC and TRC of each box.
             0 => use window specified in FLDSIZE.
             CLBOX(1,i)=-1 indicates a circle of radius
             CLBOX(2,i) pixels centered on (CLBOX(3,i),
             CLBOX(4,i)).  CLBOX(1,i) >= 0 indicates a
             rectangular box.  NOTE: CLBOX is not used to
             determine the size of the image to be made;  IMSIZE
             or FLDSIZE must set the size of the image.
  UVTAPER....(U,V) Gaussian taper (kilo-lambda) at 30% level
  UVRANGE....(Minimum,Maximum) baseline (kilo-lambda) in map.
  UVWTFN.....Weighting function of (u-v) place.
             blank=>Uniform; 'NA'=>Natural
             'O '=> Set weights to One and do uniform weighting.
             'V '=>VLBI weighting, forth root of input weight,
              and do uniform weighting.
             'NO'=>Set weights to one and use natural weighting.
             'NV'=>VLBI weight and use natural weighting.
              Note: uniform weighting in WFCLN corrects by the
              sum of the weights in the box rather than the
              number of visibilities as in MX.
  UVBOX......(U,V) box size for smoothing.  See HELP UVBOX.
  ZEROSP.....(1)= zero spacing flux density for the
             polarization being processed.  Zero spacing flux is
             placed at the center of FIELD 1.
             (2)= FWHM size of major axis for Zero spacing flux
             component (in arc seconds).
             (3)= FWHM size of minor axis for Zero spacing flux
             (4)= Position angle (north through east, degrees)
             If (2) is zero, source is assumed bigger than image.
             ZEROSP(5) is the weight for zero spacing flux.
  XTYPE......Convolution function type in X-direction
             1=Pill-box, 2=exponential, 3=Sinc, 4=Exp*Sinc,
             5=Spheroidal, 6=exp*BESSJ1(x)/x.
              <= 0 or > 5  -> 5.
  YTYPE.....Convolution function type in Y-direction
  XPARM.....Array containing parameters for XTYPE.
            See HELP UVnTYPE when n=convolution type.
  YPARM.....Array containing parameters for YTYPE.
  GAIN......The CLEAN loop gain.  0 => 0.10.
  FLUX......Stop CLEAN when abs(resid. image max) < FLUX (Jy)
            IF FLUX < 0 then Clean stops at first negative
            Clean Component.
  MINPATCH..Minimum half width of the portion of the beam
            which is used in the AP minor CLEAN. (init 51)
            Use 51 for deep CLEANs of extended sources.  Use
            a large value if the beam has big side-lobes.
  NITER.....CLEAN iteration limit. 0 => no CLEANing.
  BCOMP.....Restart CLEAN using BCOMP(i) components for each
            field i. If >0, you must completely specify the
            OUTNAME and OUTSEQ of the clean map(s).
  BMAJ......The FWHM (asec) major axis of the restoring beam.
            If 0; value obtained from fitting to the beam.
            If <0; output will contain the residual image.
  BMIN......The FWHM (asec) minor axis of the restoring beam.
  BPA.......The position angle in the unrotated image of BMAJ.
  PHAT......The offset added to the pixel at the beam peak.
            Should be about <noise**2>/2*<signal**2> but
            you may well need to experiment.
  FACTOR....FACTOR>0 causes deeper CLEAN in each major cycle,
            speeding CLEAN, maybe "eating" extended structure.
            FACTOR=0 => the normal Clark CLEAN. FACTOR=-0.3 is
            good for deep CLEANs of extended structure.
  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.
  CPARM.....Correction control parameters (SEE EXPLAIN WFCLN):
            (1) If > 0 then make frequency dependent primary
            beam corrections assuming an antenna diameter of
            CPARM(1) meters.
            (2) Visibility amplitudes will be corrected to the
            average frequency assuming a spectral index of
            CPARM(2). Note: the typical optically thin
            synchrotron spectral index is about -0.7.
            (3) If this value is larger than 0 then the u,v and
            w terms are scaled by CPARM(3) before imaging.
            (4) If this value is larger than 0 then use a DFT
            onto the celestial sphere.  THIS IS VERY SLOW.
            (5-7)  If (5) > 0 then scaling od residuals is
            requested and
            CPARM(6) = Halfwidth in x of box to determine the
            dirty beam area (default = 5)
            CPARM(7) = Halfwidth in y of box to determine the
            dirty beam area (default = 5)
  GUARD.....Fraction of the x and y radius for which uv samples
            are not allowed.  < 0 => just enough to avoid
            mathematical errors in the convolution.
              0 => 0.3 * SQRT(taper weight at 0.3 from edge).
  MAXPIXEL..The maximum number of pixels that are searched
            for components inside the ``AP'' in each major
            cycle.  < 3000 => 20050.  This number affects the
            cpu usage significantly.  Too many causes the task
            to search over many points it will never use.  Too
            few causes the task to do many more small major
            cycles, also at great expense.  Use this with great
            caution, but big wins are possible using larger
            sizes on very large cleans.
  BADDISK...This array contains the numbers of disks on which
            it is desired that scratch files not be located.
            BADDISK has no effect on input and output maps.
  BOXFILE...Input file of clean box definitions . This is a text
            file containing the coordinates of clean boxes for
            all fields. The format is one box per line, as
            follows:
            field blc-x blc-y trc-x trc-y   (5 integers)
            e.g.
            1 200 205 220 222
            1 230 232 240 241
            2 100 100 130 121
            ...
            Fields with no boxes specified default to the size
            specified by IMSIZE and FLDSIZ (see above). Use of
            this input overrides all other clean box information.
            E.g.  BOXFILE 'FITS:BOXES'
            If BOXFILE = ' ', NBOXES and CLBOX apply.
----------------------------------------------------------------
WFCLN:  Widefield or wideband imaging/CLEANing task.
Documentor:  W. D. Cotton, NRAO
Related Programs: MX, OHGEO, UBAVG

   This task does a visibility based CLEAN similar to MX but
contains a number of optional corrections and enhancements which
are useful for imaging a wide field of view and/or using
multiple or wide frequency bands.

Frequency Dependent Primary beam corrections:

     If multiple, widely spaced frequencies are used in a making
a single image then the differences in the primary beam size can
vary signifigantly with frequency.  This causes problem in
CLEANing objects far from the pointing center as the primary
beam differences cause the subtraction of the combined model
from the visibility data at the different frequencies to be
incorrect.  There will be residuals in the visibility data that
cannot be CLEANed as the data does not correspond to a possible
sky brightness distribution.
  If CPARM(1) is larger than 0 then a correction is made in the
subtraction to remove the effects of the frequency dependence of
the primary beam.  The primary beam is assumed to be a uniformly
illuminated disk of diameter CPARM(1) meters.  This correction
is made out to the 5% power point of the beam with a flat
correction further out.
   Note: this correction is only for the relative primary beam
to correct to a common frequency and DOES NOT correct for the
primary beam pattern at this frequency.

Simple Correction for Spectral Index:

   If the sources observed do not have a flat spectrum then the
source spectrum will have effects on the CLEANing of a similar
nature to the frequency dependent primary beam problem described
above.  This problem does not depend on position in the field
except in the the spectral index can vary across the field.
In general the spectral index does vary in an image but in many
cases the spectral index is usually closer to -.7 than to 0.  To
the degree that the structure in the field can be characterized
by a single spectral index the amplitudes of the data can be
scaled to the average frequency.
   Before imaging the amplitudes of the uv data are scaled to
the average frequency using a spectral index of CPARM(2).  For
optically thin synchrotron sources this spectral index is
typically between -0.6 and -1.0.  This correction cannot remove
the effects of variable spectral index but allows a single
correction.

Error in the Assumed Central Frequency:

   If the frequency used to compute the u, v a, w terms is in
error then there will be a misscaling of the image due to this
error.  Central frequencies are frequently computed on the basis
of unrealistic models of the bandpass shape.
   If CPARM(3) is larger than 0 it is assumed to be a frequency
scaling factor for the u, v, and w that is to be applied before
imaging.

Array Misorientation Effects

   Images made with a coplanar array not oriented towards the
instrumental zenith will have a distortion of the geometry which
increases in severity away from the phase tracking center.  For
noncoplanar arrays the image is distorted rather than just the
geometry.  VLA snapshots are misaligned coplanar arrays whereas
VLA synthesis images cannot be considered to be made with a
coplanar array.
   Images made with misaligned coplanar arrays can be corrected
using task OHGEO to remove the effects of this misalignment.
This correction requires the knowledge of the observing
geometry; in particular, the average parallactic and zenith
angles.  WFCLN computes these values and leaves then as header
keywords where OHGEO can use them.

Noncoplanar Effects

   If the observing array is not confined to a plane during the
observations then images produced from a 2-D FFT will be
increasing distorted from the phase center.  If this is a
serious problem then using a direct Fourier transform (DFT) to
image onto the celestial sphere can eliminate this problem.
However, THIS IS VERY SSSLLLOOOWWW. In addition, the dirty beam
is no longer a stationary function of position in the field and
a very conservative visibility based CLEAN is needed making this
EVEN SLOWER.
   If CPARM(4) is greater than 0 then imaging and model
subtraction will be done using a DFT.  Be prepared to wait.
There is also a limit of 1 field in this mode.  There are
several other changes in the cleaning for this mode; especially,
the beam patch used is fixed at a small value.
   Since the speed of the DFT imaging is directly proportional
to the number of visibilities time averaging is advised.  Task
UBAVG can be used to time average to the maximum possible extent
without distorting a specified field of view.

Scaling residuals

   In general the units of the residuals are different than
those of the restored components; either being Jy per beam area.
If the dirty beam area is similar to the restoring beam area
then this effect is negliglible.  Similarly, if the CLEAN has
proceeded well into the noise then this difference is of little
consequence.  However, if there is signifigant unCLEANed flux
left in the image then this difference may be important.
   If CPARM(5) > 0 then WFCLN will attempt to scale the
residuals to the same units as the restored components.  The
principle difficulty is determining the effective area of the
dirty beam.  Operationally this is done inside a box centered on
the peak in the beam with halfwidth CPARM(6) in x and CPARM(7)
in y.
