; ZEMAN
;---------------------------------------------------------------
;! Fits 1-dimensional Zeeman model to data
;# TASK ANALYSIS PLOT SPECTRAL ONED MODELING TV-APPL POLARIZATION
;-----------------------------------------------------------------------
;;  Copyright (C) 2013-2017
;;  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
;-----------------------------------------------------------------------
ZEMAN     LLLLLLLLLLLLUUUUUUUUUUUU CCCCCCCCCCCCCCCCCCCCCCCCCCCCC
ZEMAN     Fits 1-dimensional Zeeman model to images of I and V
INNAME                             Input V image name (name)
INCLASS                            Input V image name (class)
INSEQ             0.0     9999.0   Input V image name (seq. #)
INDISK            0.0        9.0   Input V image disk unit #
IN2NAME                            Input I image name (name)
IN2CLASS                           Input I image name (class)
IN2SEQ            0.0     9999.0   Input I image name (seq. #)
IN2DISK           0.0        9.0   Input I image disk unit #
OUTNAME                            Output image name (name)
OUTCLASS                           Output image name (class)
OUTSEQ           -1.0     9999.0   Output image name (seq. #)
OUTDISK           0.0        9.0   Output image disk unit #.
BLC                                Bottom left corner of input
TRC                                Top right corner of input
FLUX              0.0              Flux cutoff (see HELP)
INVERS            0.0              ZE table versions
OPTYPE                             'GAUS', '2SID', other
IN2VERS           0.0              Mode GAUS: input XG table
DOOUTPUT         -1.0        7.0   Write corrected image: bit 1
                                   write parameter img: bit 2
                                   Write residual image: bit 3
DOTV             -1.0        2.0   Plot data on TV; 2 => use
                                   TV not terminal for questions
RMSLIMIT                           Switch from automatic to
                                   interactive if rms > RMSLIMIT
BADDISK                            Disk to avoid for scratch
----------------------------------------------------------------
ZEMAN
Task:  Fits one-dimensional Zeeman model to spectral cubes.  The
       simplest model is
           V(c) = A * I(c) + 0.5 * B * dI(c)/dc
       where c is spectral channel or frequency and A and B are
       determined for each celestial coordinate by a least-squares
       fitting routine.  If the I image has been through XGAUS, then a
       more complicated model may be fit:
           V(c) = A * I(c) + 0.5 * sum [ B_i * dI_i/dc ]
       where the i loops from 1 to the number of Gaussians fit at
       each celestial pixel.  I is the actual observed unpolarized
       brightness while I_i is the Gaussian brightness of the i'th
       component.

       ZEMAN can be run in a batch mode in which it simply finds the
       solution to the above models and writes out images of the
       parameters, of a corrected V cube, and of the residual.  If
       DOTV is true, it will use an interactive mode to display each
       fit and ask whether the solution should be kept or marked bad.
       When you get tired of the interaction, you can turn off the TV
       and fit the rest of the cube in the batch mode.  Interactivity
       will then resume, displaying images of the parameters and
       allowing you to flag more solutions interactively.

       Like XGAUS, ZEMAN works with a table of solutions called a ZE
       table for ZEMAN.  It begins by filling in the table with null
       solutions and then calls a routine to determine solutions pixel
       by pixel for those pixels which are strong enough (FLUX).  This
       can be run interactively or in batch and one can turn off
       interactivity after establishing that all is working well.
       After all pixels are fit, the task will go into an image
       display and editing phase using the TV, but only if the task is
       started with DOTV true.  You can refit or flag selected
       solutions at this stage.  Finally, selected output images are
       written from the fit.  Note, during interaction you may simply
       quit for now and resulme at some later time using the table
       which has already been partially (or fully) filled in.

       ZEMAN may be restarted using the ZE file either resuming the
       sequential fitting (if it was not completed or using a lower
       value of FLUX or a different region selected by BLC/TRC) or
       dropping into the edit stage directly.  Unlike XGAUS, ZEMAN
       does not allow changing the value of NGAUS - the fit is linear
       and the number of Gaussians is set in XGAUS in the XG table,
       not in ZEMAN, so this option would not be useful.

       NOTE: Always make a new ZE table if you are changing OPTYPE or
       the XG table version ID.

       Details of the interactive operation and options are described
       in the EXPLAIN file.  See also AIPS Memo 118, "Modeling
       spectral cubes in AIPS", January 2016 for a more detailed
       description of the use of this task.

Adverbs:
  INNAME.....Transposed V image name (name).       Standard defaults.
  INCLASS....Transposed V image name (class).      Standard defaults.
  INSEQ......Transposed V image name (seq. #).     0 => highest.
  INDISK.....Transposed V image disk #.   0 => any.
  IN2NAME....Transposed I image name (name).       Standard defaults.
  IN2CLASS...Transposed I image name (class).      Standard defaults.
  IN2SEQ.....Transposed I image name (seq. #).     0 => highest.
  IN2DISK....Transposed I image disk #.   0 => any.
  OUTNAME....Output image name (name).      Standard defaults.
  OUTCLASS...Output image name (class).     Standard defaults.
             Used only for the corrected V cube.  The OUTCLASSes for
             the fit parameters are GAIN and FIELDn for A and B_n.
  OUTSEQ.....Output image name (seq. #).   0 => highest unique.
  OUTDISK....Disk drive # of output image. 0 => highest number with
             sufficient space.
  BLC........Bottom right corner in input image of desired subimage.
             Default is entire image.  NOTE: the entire input image
             (axes 2 and 3) enters into the ZE table.  You may
             restrict the pixels fit in this execution with BLC and
             TRC, including which spectral channels are used.
  TRC........Top right corner in input image of desired subimage.
             Default is entire image.
  FLUX.......A flux cutoff in the same units as the input I image
             (i.e. Jy/beam).  If a row does not have three consecutive
             points in I polarization above this level, no fit is done
             to the row.
  INVERS.....ZE table version: 0 => make a new one.
  OPTYPE.....'GAUS' use a pre-computed XG table (from XGAUSS) to do
                    the second model above.
             '2SID' do the first model using a "2-sided" derivative:
                    dI(c)/dc = 0.5 * (I(c+1) - I(c-1))
             else:  do the first model using a "1-sided" derivative
                    dI(c)/dc = I(c) - I(c-1)
  IN2VERS....For OPTYPe='GAUS' only: Input XG table version 0 -> high
  DOOUTPUT...= 1,3,5, or 7 requests that the V image be corrected by
                      the solution for A and written out using class
                      OUTCLASS
             = 2,3,6, or 7 requests that the model images (A, B_i) be
                      written out as cataloged images with classes
                      GAIN and FIELDi.
             = 4,5,6, or 7 requests that the residual (data-model)
                      image be written out as a cataloged image with
                      class 'VRESID'
             Note that DOOUTPUT can be changed interactively during
             the imaging portion of the task (if DOTV > 0) and the
             value of the adverb at exit is all that matters.
  DOTV.......False (<= 0) causes the task to run in a batch mode.
             True (> 0) implies plot the data and fits on the TV
             > 1.5 => conduct most questions via TV menus rather than
             the terminal.
  RMSLIMIT...When the fitting has been told to continue without the
             TV, switch interactive mode back on whenever the Q
             and/or U rms exceeds RMSLIMIT.  0 -> 1000000.
  BADDISK....Disk drives to avoid for scratch files.
----------------------------------------------------------------
ZEMAN:  One-dimensional Zeeman fitting of I and V cubes
Documenter:  E. W. Greisen NRAO
Related Programs: CUBIT, GAL, IMFIT, JMFIT, SAD, SLFIT, XGAUS

At present, ZEMAN assumes that there are at most 3 axes with more than
one pixel in the input image.

ZEMAN begins by making a ZE table containing one row for every pixel
in the input plane from axes 2 and 3.  Each row of the table is
initialized with the peak value in each row of the input Ipol image,
where the "peak" is the largest value for 3 adjacent pixels.  Then
ZEMAN begins fitting those rows having a peak value above FLUX.
Initial guesses for each fit are found from the row data or from a
previous fit.  The interactive mode is recommended strongly to let you
watch the initial solutions.  You may turn the interactive fitting
mode off if all is going well.  After each input image row is fit, the
results are added to the ZE table immediately.  This allows the
interactive user to quit at any time and then restart the process
later (set INVERS to point at the pre-existing ZE table which you
intend to modify).

Finally, when all pixels have been fit, ZEMAN enters an interactive
routine designed to improve the results before any output images are
written.  However, before describing that function, we need to provide
details of the interactive fitting of each row of the input image.
This process is followed whenever a row is fit in the initial fitting
and in the result editing function.

For each row, the first step in the fitting process is to determine an
initial guess non-interactively.  If ZEMAN is currently in interactive
mode, the next steps are:
    1. The input data are plotted on the TV in graphics plane 1
       (usually yellow), with the I spectrum above and the V spectrum
       below.  The initial guess is added to the V spectrum using
       graphics plane 2 (usually green).
    2. ZEMAN then asks in the TV (DOTV=2) or the AIPS window for
       instructions.  If you click BAD on the TV or your answer in the
       terminal window begins with B or b, ZEMAN will mark this pixel
       as bad.  If you click QUIT or your answer begins with Q or q,
       ZEMAN will simply exit, allowing you to restart it at a later
       time.  If you click DO FIT or your answer is anything else,
       e.g. a simple carriage return ("Enter"), ZEMAN goes on.
    3. ZEMAN proceeds to call a **linear** least squares fitting
       routine to determine the parameters that appear to fit the data
       best.  The answers are then checked to see if they are
       "reasonable" - a small enough RMS and a gain under 25%.
    5. If the result is unreasonable and the current mode is not
       interactive, the interactive mode is turned back on (with a
       message and a display of the answers in the message terminal
       window) and ZEMAN returns to step 1.
    6. If the current mode is interactive, the final model is added to
       the plot using graphics channel 4 (usually cyan).  In the input
       terminal, you are then told if the answers are "unreasonable"
       and are shown the answers, reasonable or not.  You are then
       offered a variety of choices.  If your response begins with:
          a) B or b - the solution is marked as bad and ZEMAN goes on
                      to the next input row (BAD on the TV).
          b) Q or q - ZEMAN exits cleanly, leaving the XG table to be
                      worked on again at a later time (QUIT on the
                      TV).
          c) T or t - ZEMAN turns off the interactive mode and does
                      solutions in a batch-like fashion until an
                      unreasonable solution is found or it finishes
                      the current function (TVOFF on the TV).
          d) H or h - ZEMAN prompts you to enter the parameters for
                      each component.  You enter the gain (unitless,
                      from 0 to 1) and either the average "field" (in
                      pixels) when not using the 'GAUS' mmode or the
                      "field" for each Gaussian (also in pixels).
                      This is called HAND in the TV menu.
          e) Anything else - ZEMAN saves the answer (with
                      uncertainties) and goes on to the next input
                      row (called GOOD in the TV menu).

After all pixels that are strong enough have been given a solution,
ZEMAN enters a menu-driven function.  The menu has in the left column:
-------------------
| EXIT            |   Exit ZEMAN, writing output images if DOOUTPUT is
                      now > 0.
| SET MAX RES     |   Set maximum residual for okay solutions
| SET GAIN RANGE  |   Set range for okay gain solutions
| SET FIELD RANGE |   Set "field" range(s) for okay solutions
| SET MAX ERR FLD |   Set maximum error(s) in field for okay solutions
| REDO ALL        |   Re-do all solutions which are not okay
| FLAG ALL        |   Mark bad all solutions which are not okay
| OFF ZOOM        |   Turn of TV zoom
| OFF TRANSFER    |   Turn off black & white and color TV enhancements
| SET DOOUTPUT    |   Increment DOOUTPUT in loop 0-7 - with 1, 3, 5,
                      and 7 causing a gain-corrected V cube; 2, 3, 6,
                      and 7 parameter images; and 4, 5, 6, and 7
                      causing residual images to be written on EXIT
| ADD TO LIST     |   Type in output pixel coordinates to add to list
| SHOW LIST       |   Display coordinates in list
| REDO LIST       |   Re-do solutions for all pixels in list
| FLAG LIST       |   Flag solutions for all pixels in list
-------------------

Three editing concepts are present in this menu.  The first is to
establish what parameter values (peak residual, gain values, field
values, and error in fields) for each component constitute an "okay"
solution.  The selected limits are displayed above the menu.  Then you
can choose to try to REDO ALL solutions which are not okay or simply
FLAG ALL, marking them as bad.  The second concept is to create a list
of up to 1000 pixels which are thought to have some problem.  You can
enter these pixels by hand (or remove pixels from the list by hand)
with ADD TO LIST.  A faster way to add to the list is to show the
image of some parameter and then select interesting pixels while doing
CURVALUE (see below).  The list of pixels can be re-done (REDO LIST)
or marked as bad (FLAG LIST).  The list is cleared by these operations
so you can make a new list as needed.

The right hand column of options include:
------------------
| SHOW IMAGE G   |   Enter image interaction with gain
| SHOW IMAGE EG  |   Enter image interaction with error in gain
| SHOW IMAGE F1  |   Enter image interaction with "field" of
                     component 1
| SHOW IMAGE EF1 |   Enter image interaction with error in "field"
                     of component 1
------------------
For 'GAUS' mode, appropriate additional choices are offered.

When you select one of the above options, the above menus are turned
off, the image plane maintained in memory is displayed on the TV
screen, and a new menu is displayed.  If offers:
----------------
| RETURN       |  Return to the above menus, image stays displayed
| LOAD AS SQ   |  Re-load image with square root transfer function
| LOAD AS LG   |  Re-load image with log transfer function
| LOAD AS L2   |  Re-load image with extreme log transfer function
| LOAD AS LN   |  Re-load image with linear transfer function
| SET WINDOW   |  Set a sub-image to view
| RESET WINDOW |  Return to viewing the full image
| OFF TRANSF   |  Turn off enhancement done with TVTRANSF
| OFF COLOR    |  Turn off color enhancements
| TVTRANSF     |  Black & white image enhancement
| TVPSEUDO     |  Color enhancement of numerous sorts
| TVPHLAME     |  Color enhancement of flame type, multiple colors
| TVZOOM       |  Interactive zooming and centering of image
| CURVALUE     |  Display value under cursor, mark pixels for list
| NEXT WINDOW  |  Move to next window into large images
----------------

Only one of the LOAD AS xx options is offered - SQ when the current
function type is LN, LG when the current function type is SQ, L2 when
the current function type is LG, and LN when the current type is L2.
Selecting this option, reloads the image with the newly selection
function type and changes the menu option accordingly.  The options
OFF TRANSF through TVZOOM are essentially the same as the
corresponding verbs in AIPS.  CURVALUE is like the verb of that name,
but, when you press buttons A or B, the pixel under the cursor is
added to the editing list.

Very large images may not be able to fit on your TV.  When the image
exceeds the size of the TV, the top line will show the component
number followed by a subimage number in parentheses and the NEXT
WINDOW option will appear.  The first sub-images displayed is called
number 0 and shows the full image every n'th pixel in X and Y.
Sub-image 1 begins at the lower left, moves right, then back to the
left and up, and so forth until the top right is reached.  Every pixel
is displayed in these sub-images.  Use the NEXT WINDOW option to step
through the sub-images in a circular fashion.
