Markwardt Library

This page is a listing of the entire contents of this library for IDL. This listing is the long version. Viewing the much more compact listing may be handier.

[Go Back to Main IDL Libraries Search Page]


Last modified: Thu Dec 21 21:19:12 2000.

List of Routines


Routine Descriptions

CMAPPLY

[Next Routine] [List of Routines]
 NAME:
   CMAPPLY

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov

 PURPOSE:
   Applies a function to specified dimensions of an array

 MAJOR TOPICS:
   Arrays

 CALLING SEQUENCE:
   XX = CMAPPLY(OP, ARRAY, DIMS, [/DOUBLE], [TYPE=TYPE])

 DESCRIPTION:
   CMAPPLY will apply one of a few select functions to specified 
   dimensions of an array.  Unlike some IDL functions, you *do* have
   a choice of which dimensions that are to be "collapsed" by this
   function.  Iterative loops are avoided where possible, for 
   performance reasons.

   The possible functions are:             (and number of loop iterations:)
     +     - Performs a sum (as in TOTAL)       number of collapsed dimensions
     *     - Performs a product                 same
     AND   - Finds LOGICAL "AND" (not bitwise)  same
     OR    - Finds LOGICAL "OR"  (not bitwise)  same

     MIN   - Finds the minimum value            number of output elements
     MAX   - Finds the maximum value            same

 INPUTS:

   OP - The operation to perform, as a string.  May be upper or lower
        case.

   ARRAY - An array of values to be operated on.  Must not be of type
           STRING (7) or STRUCTURE (8).

 OPTIONAL INPUTS:

   DIMS - An array of dimensions that are to be "collapsed", where
          the the first dimension starts with 1 (ie, same convention
          as IDL function TOTAL).  Whereas TOTAL only allows one
          dimension to be added, you can specify multiple dimensions
          to CMAPPLY.  Order does not matter, since all operations
          are associative and transitive.  NOTE: the dimensions refer
          to the *input* array, not the output array.  IDL allows a 
          maximum of 8 dimensions.
          DEFAULT: 1 (ie, first dimension)

 KEYWORDS:

   DOUBLE - Set this if you wish the internal computations to be done
            in double precision if necessary.  If ARRAY is double 
            precision (real or complex) then DOUBLE=1 is implied.
            DEFAULT: not set

   TYPE - Set this to the IDL code of the desired output type (refer
          to documentation of SIZE()).  Internal results will be
          rounded to the nearest integer if the output type is an
          integer type.
          DEFAULT: same is input type

 RETURN VALUE:

   An array of the required TYPE, whose elements are the result of
   the requested operation.  Depending on the operation and number of
   elements in the input array, the result may be vulnerable to
   overflow or underflow.

 EXAMPLES:
   Shows how CMAPPLY can be used to total the second dimension of the
   array called IN.  This is equivalent to OUT = TOTAL(IN, 2)

   IDL> IN  = INDGEN(5,5)
   IDL> OUT = CMAPPLY('+', IN, [2])
   IDL> HELP, OUT
   OUT             INT       = Array[5]

   Second example.  Input is assumed to be an 5x100 array of 1's and
   0's indicating the status of 5 detectors at 100 points in time.
   The desired output is an array of 100 values, indicating whether
   all 5 detectors are on (=1) at one time.  Use the logical AND
   operation.

   IDL> IN = detector_status             ; 5x100 array
   IDL> OUT = CMAPPLY('AND', IN, [1])    ; collapses 1st dimension
   IDL> HELP, OUT
   OUT             BYTE      = Array[100]

   (note that MIN could also have been used in this particular case,
   although there would have been more loop iterations).

   Third example.  Shows sum over first and third dimensions in an
   array with dimensions 4x4x4:

   IDL> IN = INDGEN(4,4,4)
   IDL> OUT = CMAPPLY('+', IN, [1,3])
   IDL> PRINT, OUT
        408     472     536     600

 MODIFICATION HISTORY:
   Mar 1998, Written, CM

(See /host/bluemoon/usr2/idllib/contrib/markwardt/cmapply.pro)


CMCONGRID

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
	CMCONGRID

 PURPOSE:
       Shrink or expand the size of an array by an arbitrary amount.
       This IDL procedure simulates the action of the VAX/VMS
       CONGRID/CONGRIDI function.

	This function is similar to "REBIN" in that it can resize a
       one, two, or three dimensional array.   "REBIN", however,
       requires that the new array size must be an integer multiple
       of the original size.   CONGRID will resize an array to any
       arbitrary size (REBIN is somewhat faster, however).
       REBIN averages multiple points when shrinking an array,
       while CONGRID just resamples the array.

 CATEGORY:
       Array Manipulation.

 CALLING SEQUENCE:
	array = CONGRID(array, x, y, z)

 INPUTS:
       array:  A 1, 2, or 3 dimensional array to resize.
               Data Type : Any type except string or structure.

       x:      The new X dimension of the resized array.
               Data Type : Int or Long (greater than or equal to 2).

 OPTIONAL INPUTS:
       y:      The new Y dimension of the resized array.   If the original
               array has only 1 dimension then y is ignored.   If the
               original array has 2 or 3 dimensions then y MUST be present.

       z:      The new Z dimension of the resized array.   If the original
               array has only 1 or 2 dimensions then z is ignored.   If the
               original array has 3 dimensions then z MUST be present.

 KEYWORD PARAMETERS:
       INTERP: If set, causes linear interpolation to be used.
               Otherwise, the nearest-neighbor method is used.

	CUBIC:	If set, uses "Cubic convolution" interpolation.  A more
		accurate, but more time-consuming, form of interpolation.
		CUBIC has no effect when used with 3 dimensional arrays.

       MINUS_ONE:
               If set, will prevent CONGRID from extrapolating one row or
               column beyond the bounds of the input array.   For example,
               If the input array has the dimensions (i, j) and the
               output array has the dimensions (x, y), then by
               default the array is resampled by a factor of (i/x)
               in the X direction and (j/y) in the Y direction.
               If MINUS_ONE is present (AND IS NON-ZERO) then the array
               will be resampled by the factors (i-1)/(x-1) and
               (j-1)/(y-1).

       HALF_HALF:
               If set, will tell CONGRID to extrapolate a *half* row
               and column on either side, rather than the default of
               one full row/column at the ends of the array.  If you
               are interpolating images with few rows, then the
               output will be more consistent with this technique.
               This keyword is intended as a replacement for
               MINUS_ONE, and both keywords probably should not be
               used in the same call to CONGRID.

 OUTPUTS:
	The returned array has the same number of dimensions as the original
       array and is of the same data type.   The returned array will have
       the dimensions (x), (x, y), or (x, y, z) depending on how many
       dimensions the input array had.

 PROCEDURE:
       IF the input array has three dimensions, or if INTERP is set,
       then the IDL interpolate function is used to interpolate the
       data values.
       If the input array has two dimensions, and INTERP is NOT set,
       then the IDL POLY_2D function is used for nearest neighbor sampling.
       If the input array has one dimension, and INTERP is NOT set,
       then nearest neighbor sampling is used.

 EXAMPLE:
       ; vol is a 3-D array with the dimensions (80, 100, 57)
       ; Resize vol to be a (90, 90, 80) array
       vol = CONGRID(vol, 90, 90, 80)

 MODIFICATION HISTORY:
       DMS, Sept. 1988.
       DMS, Added the MINUS_ONE keyword, Sept. 1992.
 	Daniel Carr. Re-wrote to handle one and three dimensional arrays
                    using INTERPOLATE function.
 	DMS, RSI, Nov, 1993.  Added CUBIC keyword.
       Craig Markwardt, Dec, 1997.  Added halfhalf keyword to
                        more evenly distribute "dead" pixel row

(See /host/bluemoon/usr2/idllib/contrib/markwardt/cmcongrid.pro)


DEFSUBCELL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   DEFSUBCELL

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov

 PURPOSE:
   Returns a default subcell suitable for plotting in.

 CALLING SEQUENCE:
   sub = defsubcell( [default] )

 DESCRIPTION: 

   DEFSUBCELL returns a "nice" subcell, useful for plotting in.  It
   gives 8% margins on the left and bottom, and 5% margins on the
   right and top.

   A set of user-defined default values can be passed in.  Any that
   are negative are replaced by this function's.

 INPUTS:

   DEFAULT - a "default" subcell.  Any elements that are negative are
             replaced by DEFSUBCELL's notion of the proper margins.
             This feature is used, for example, by SUBCELLARRAY to
             make subcells that have special margins on certain sides
             and default ones on other sides.

 OPTIONAL INPUTS:
   NONE

 INPUT KEYWORD PARAMETERS:

   NONE

 RETURNS:
   The new subcell.

 PROCEDURE:

 EXAMPLE:

 SEE ALSO:

   DEFSUBCELL, SUBCELLARRAY

 EXTERNAL SUBROUTINES:

 MODIFICATION HISTORY:
   Written, CM, 1997

(See /host/bluemoon/usr2/idllib/contrib/markwardt/defsubcell.pro)


GAUSS1

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   GAUSS1

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov

 PURPOSE:
   Compute Gaussian curve given the mean, sigma and area.

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   YVALS = GAUSS1(XVALS, [MEAN, SIGMA, AREA], SKEW=skew)

 DESCRIPTION:

  This routine computes the values of a Gaussian function whose
  X-values, mean, sigma, and total area are given.  It is meant to be
  a demonstration for curve-fitting.

  XVALS can be an array of X-values, in which case the returned
  Y-values are an array as well.  The second parameter to GAUSS1
  should be an array containing the MEAN, SIGMA, and total AREA, in
  that order.

 INPUTS:
   X - Array of X-values.

   [MEAN, SIGMA, AREA] - the mean, sigma and total area of the 
                         desired Gaussian curve.

 INPUT KEYWORD PARAMETERS:

   SKEW - You may specify a skew value.  Default is no skew.

 RETURNS:

   Returns the array of Y-values.

 EXAMPLE:

   p = [2.2D, 1.4D, 3000.D]
   x = dindgen(200)*0.1 - 10.
   y = gauss1(x, p)

   Computes the values of the Gaussian at equispaced intervals
   (spacing is 0.1).  The gaussian has a mean of 2.2, standard
   deviation of 1.4, and total area of 3000.

 REFERENCES:

 MODIFICATION HISTORY:
   Written, Jul 1998, CM

(See /host/bluemoon/usr2/idllib/contrib/markwardt/gauss1.pro)


MPFIT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   MPFIT

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov
   UPDATED VERSIONs can be found on my WEB PAGE: 
      http://astrog.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Perform Levenberg-Marquardt least-squares minimization (MINPACK-1)

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   parms = MPFIT(MYFUNCT, start_parms, FUNCTARGS=fcnargs, NFEV=nfev,
                 MAXITER=maxiter, ERRMSG=errmsg, NPRINT=nprint, QUIET=quiet, 
                 FTOL=ftol, XTOL=xtol, GTOL=gtol, NITER=niter, 
                 STATUS=status, ITERPROC=iterproc, ITERARGS=iterargs,
                 COVAR=covar, PERROR=perror, BESTNORM=bestnorm,
                 PARINFO=parinfo)

 DESCRIPTION:

  MPFIT uses the Levenberg-Marquardt technique to solve the
  least-squares problem.  In its typical use, MPFIT will be used to
  fit a user-supplied function (the "model") to user-supplied data
  points (the "data") by adjusting a set of parameters.

  For example, a researcher may think that a set of observed data
  points is best modelled with a Gaussian curve.  A Gaussian curve is
  parameterized by its mean, standard deviation and normalization.
  MPFIT will, within certain constraints, find the set of parameters
  which best fits the data.  The fit is "best" in the least-squares
  sense; that is, the sum of the weighted squared differences between
  the model and data is minimized.

  The Levenberg-Marquardt technique is a particular strategy for
  iteratively searching for the best fit.  This particular
  implementation is drawn from MINPACK-1 (see NETLIB), and seems to
  be more robust than routines provided with IDL.  This version
  allows upper and lower bounding constraints to be placed on each
  parameter, or the parameter can be held fixed.

  The IDL user-supplied function should return an array of weighted
  deviations between model and data.  In a typical scientific problem
  the residuals should be weighted so that each deviate has a
  gaussian sigma of 1.0.  If X represents values of the independent
  variable, Y represents a measurement for each value of X, and ERR
  represents the error in the measurements, then the deviates could
  be calculated as follows:

    DEVIATES = (Y - F(X)) / ERR

  where F is the analytical function representing the model.  The
  convenience functions MPFITFUN and MPFITEXPR calculate the deviates
  for you.  If ERR are the 1-sigma uncertainties in Y, then

    TOTAL( DEVIATES^2 ) 

  will be the total chi-squared value.  MPFIT will minimize the
  chi-square value.  The values of X, Y and ERR are passed through
  MPFIT to the user-supplied function via the FUNCTARGS keyword.

  MPFIT does not perform more general optimization tasks.  See TNMIN
  instead.  MPFIT is customized, based on MINPACK-1, to the
  least-squares minimization problem.

  In the search for the best-fit solution, MPFIT calculates
  derivatives numerically via a finite difference approximation, by
  default.  The user-supplied function need not calculate the
  derivatives explicitly, but can if AUTODERIVATIVE=0 is passed.
   
 INPUTS:
   MYFUNCT - a string variable containing the name of the function to
             be minimized.  The function should return the weighted
             deviations between the model and the data.  It should be
             declared in the following way (or in some equivalent):

             FUNCTION MYFUNCT, p, dp, X=x, Y=y, ERR=err
              ; Parameter values are passed in "p"
              ; Calculation of deviations occurs here
              model = F(x)
              ; Optionally compute derivatives -- NOT REQUIRED
              if n_params() GT 1 then dp = ...  ; NOT REQUIRED

              return, (y-model)/err
             END

             The keyword parameters X, Y, and ERR in the example 
             above are suggestive but not required.  Any parameters
             can be passed to MYFUNCT by using the FUNCTARGS keyword
             to MPFIT.  Use MPFITFUN and MPFITEXPR if you need ideas
             on how to do that.

             In general there are no restrictions on the number of
             dimensions in X, Y or ERR.  However the deviates *must*
             be returned in a one-dimensional array, and must have
             the same type (float or double) as the input arrays.

             You may wish to compute your own derivatives (rather
             than allowing MPFIT to compute them for you), if for
             example, it is straightforward to do it analytically.
             If so, then you should (1) pass AUTODERIVATIVE=0 (see
             below), (2) your function should compute the
             derivatives, and (3) return them in the parameter "dp".
             "dp" should be an m x n array, where m is the number of
             data points and n is the number of parameters.  dp(i,j)
             is the derivative at the ith point with respect to the
             jth parameter.
             
             The derivatives with respect to fixed parameters are
             ignored; zero is an appropriate value to insert for
             those derivatives.  If the data is higher than one
             dimensional, then the *last* dimension should be the
             parameter dimension.  Example: fitting an 50x50 image,
             "dp" should be 50x50xNPAR.

             User functions can know they are expected to provide
             derivatives if N_PARAMS() is greater than one.

   START_PARAMS - An array of starting values for each of the
                  parameters of the model.  The number of parameters
                  should be fewer than the number of measurements.
                  Also, the parameters should have the same data type
                  as the measurements (double is preferred).

                  This parameter is optional if the PARINFO keyword
                  is used.  See below.  The PARINFO keyword provides
                  a mechanism to fix or constrain individual
                  parameters.  If both START_PARAMS and PARINFO are
                  passed, then the starting *value* is taken from
                  START_PARAMS, but the *constraints* are taken from
                  PARINFO.
 
 INPUT KEYWORD PARAMETERS:

   FUNCTARGS - A structure which contains the parameters to be passed
               to the user-supplied function specified by MYFUNCT via
               the _EXTRA mechanism.  This is the way you can pass
               additional data to your user-supplied function without
               using common blocks.

               Consider the following example:
                if FUNCTARGS = { XVAL:[1.D,2,3], YVAL:[1.D,4,9],
                                 ERRVAL:[1.D,1,1] }
                then the user supplied function should be declared
                like this:
                FUNCTION MYFUNCT, P, XVAL=x, YVAL=y, ERRVAL=err

               By default, no extra parameters are passed to the
               user-supplied function.

   AUTODERIVATIVE - If this is set, derivatives of the function will
                    be computed automatically via a finite
                    differencing procedure.  If not set, then MYFUNCT
                    must provide the (analytical) derivatives.
                    Default: set (=1) 
                    NOTE: to supply your own analytical derivatives,
                      explicitly pass AUTODERIVATIVE=0

   MAXITER - The maximum number of iterations to perform.  If the
             number is exceeded, then the STATUS value is set to 5
             and MPFIT returns.
             Default: 200 iterations

   FTOL - a nonnegative input variable. Termination occurs when both
          the actual and predicted relative reductions in the sum of
          squares are at most FTOL.  Therefore, FTOL measures the
          relative error desired in the sum of squares.
          Default: 1D-10

   XTOL - a nonnegative input variable. Termination occurs when the
          relative error between two consecutive iterates is at most
          XTOL. therefore, XTOL measures the relative error desired
          in the approximate solution.
          Default: 1D-10

   GTOL - a nonnegative input variable. Termination occurs when the
          cosine of the angle between fvec and any column of the
          jacobian is at most GTOL in absolute value. Therefore, GTOL
          measures the orthogonality desired between the function
          vector and the columns of the jacobian.
          Default: 1D-10

   ITERPROC - The name of a procedure to be called upon each NPRINT
              iteration of the MPFIT routine.  It should be declared
              in the following way:

              PRO ITERPROC, MYFUNCT, p, iter, fnorm, FUNCTARGS=fcnargs, $
                PARINFO=parinfo, QUIET=quiet, ...
                ; perform custom iteration update
              END
         
              ITERPROC must either accept all three keyword
              parameters (FUNCTARGS, PARINFO and QUIET), or at least
              accept them via the _EXTRA keyword.
          
              MYFUNCT is the user-supplied function to be minimized,
              P is the current set of model parameters, ITER is the
              iteration number, and FUNCTARGS are the arguments to be
              passed to MYFUNCT.  FNORM should be the
              chi-squared value.  QUIET is set when no textual output
              should be printed.  See below for documentation of
              PARINFO.

              In implementation, ITERPROC, can perform updates to the
              terminal or graphical user interface, to provide
              feedback while the fit proceeds.  If the fit is to be
              stopped for any reason, then ITERPROC should set the
              system variable !ERR to a negative value.  In
              principle, ITERPROC should probably not modify the
              parameter values, because it may interfere with the
              algorithm's stability.  In practice it is allowed.

              Default: an internal routine is used to print the
                       parameter values.

   NPRINT - The frequency with which ITERPROC is called.  A value of
            1 indicates that ITERPROC is called with every iteration,
            while 2 indicates every other iteration, etc.  
            Default value: 1

   ITERARGS - The keyword arguments to be passed to ITERPROC via the
              _EXTRA mechanism.  This should be a structure, and is
              similar in operation to FUNCTARGS.
              Default: no arguments are passed.

   PARINFO - Provides a mechanism for more sophisticated constraints
             to be placed on parameter values.  When PARINFO is not
             passed, then it is assumed that all parameters are free
             and unconstrained.  In no case are values in PARINFO
             modified during a call to MPFIT.

             PARINFO should be an array of structures, one for each
             parameter.  Each parameter is associated with one
             element of the array, in numerical order.  The structure
             can have the following entries (none are required):

               - VALUE - the starting parameter value (but see
                         START_PARAMS above).

               - FIXED - a boolean value, whether the parameter is to 
                         be held fixed or not.  Fixed parameters are
                         not varied by MPFIT, but are passed on to 
                         MYFUNCT for evaluation.

               - LIMITED - a two-element boolean array.  If the
                 first/second element is set, then the parameter is
                 bounded on the lower/upper side.  A parameter can be
                 bounded on both sides.  Both LIMITED and LIMITS must
                 be given together.

               - LIMITS - a two-element float or double array.  Gives
                 the parameter limits on the lower and upper sides,
                 respectively.  Zero, one or two of these values can
                 be set, depending on the value of LIMITED.  Both 
                 LIMITED and LIMITS must be given together.

               - STEP - the step size to be used in calculating the
                 numerical derivatives.  If set to zero, then the
                 step size is computed automatically.

               - TIED - a string expression which "ties" the
                 parameter to other free or fixed parameters.  Any
                 expression involving constants and the parameter
                 array P are permitted.  Example: if parameter 2 is
                 always to be twice parameter 1 then use the
                 following: parinfo(2).tied = '2 * P(1)'.  Since they
                 are totally constrained, tied parameters are
                 considered to be fixed; no errors are computed for
                 them.
 
             Other tag values can also be given in the structure, but
             they are ignored.

             Example:
             parinfo = replicate({value:0.D, fixed:0, limited:[0,0], $
                                  limits:[0.D,0]}, 5)
             parinfo(0).fixed = 1
             parinfo(4).limited(0) = 1
             parinfo(4).limits(0)  = 50.D
             parinfo(*).value = [5.7D, 2.2, 500., 1.5, 2000.]

             A total of 5 parameters, with starting values of 5.7,
             2.2, 500, 1.5, and 2000 are given.  The first parameter
             is fixed at a value of 5.7, and the last parameter is
             constrained to be above 50.

             Default value:  all parameters are free and unconstrained.

   QUIET - set this keyword when no textual output should be printed
           by MPFIT

   NOCOVAR - set this keyword to prevent the calculation of the
             covariance matrix before returning (see COVAR)

 RETURNS:

   Returns the array of best-fit parameters.

 OUTPUT KEYWORD PARAMETERS:

   NFEV - the number of MYFUNCT function evaluations performed.

   NITER - number of iterations completed.

   ERRMSG - a string error or warning message is returned.

   BESTNORM - the value of the summed squared residuals for the
              returned parameter values.

   PERROR - The formal 1-sigma errors in each parameter, computed
            from the covariance matrix.  If a parameter is held
            fixed, or if it touches a boundary, then the error is
            reported as zero.

   COVAR - the covariance matrix for the set of parameters returned
           by MPFIT.  The matrix is NxN where N is the number of
           parameters.  The square root of the diagonal elements
           gives the formal 1-sigma statistical errors on the
           parameters IF errors were treated "properly" in MYFUNC.
           Parameter errors are also returned in PERROR.

           To compute the correlation matrix, PCOR, use this:
           IDL> PCOR = COV * 0
           IDL> FOR i = 0, n-1 DO FOR j = 0, n-1 DO $
                PCOR(i,j) = COV(i,j)/sqrt(COV(i,i)*COV(j,j))

           If NOCOVAR is set or MPFIT terminated abnormally, then
           COVAR is set to a scalar with value !VALUES.D_NAN.

   STATUS - an integer status code is returned.  All values other
            than zero can represent success.  It can have one of the
            following values:

	   0  improper input parameters.
         
	   1  both actual and predicted relative reductions
	      in the sum of squares are at most FTOL.
         
	   2  relative error between two consecutive iterates
	      is at most XTOL
         
	   3  conditions for STATUS = 1 and STATUS = 2 both hold.
         
	   4  the cosine of the angle between fvec and any
	      column of the jacobian is at most GTOL in
	      absolute value.
         
	   5  the maximum number of iterations has been reached
         
	   6  FTOL is too small. no further reduction in
	      the sum of squares is possible.
         
	   7  XTOL is too small. no further improvement in
	      the approximate solution x is possible.
         
	   8  GTOL is too small. fvec is orthogonal to the
	      columns of the jacobian to machine precision.

 EXAMPLE:

   p0 = [5.7D, 2.2, 500., 1.5, 2000.]
   fa = {X:x, Y:y, ERR:err}
   p = mpfit('MYFUNCT', p0, functargs=fa)

   Minimizes sum of squares of MYFUNCT.  MYFUNCT is called with the X,
   Y, and ERR keyword parameters that are given by FUNCTARGS.  The
   resulting parameter values are returned in p.

 REFERENCES:

   MINPACK-1, Jorge More', available from netlib (www.netlib.org).
   "Optimization Software Guide," Jorge More' and Stephen Wright, 
     SIAM, *Frontiers in Applied Mathematics*, Number 14.

 MODIFICATION HISTORY:
   Translated from MINPACK-1 in FORTRAN, Apr-Jul 1998, CM
   Fixed bug in parameter limits (x vs xnew), 04 Aug 1998, CM
   Added PERROR keyword, 04 Aug 1998, CM
   Added COVAR keyword, 20 Aug 1998, CM
   Added NITER output keyword, 05 Oct 1998
      D.L Windt, Bell Labs, windt@bell-labs.com;
   Made each PARINFO component optional, 05 Oct 1998 CM
   Analytical derivatives allowed via AUTODERIVATIVE keyword, 09 Nov 1998
   Parameter values can be tied to others, 09 Nov 1998
   Fixed small bugs (Wayne Landsman), 24 Nov 1998
   Added better exception error reporting, 24 Nov 1998 CM
   Cosmetic documentation changes, 02 Jan 1999 CM
   Changed definition of ITERPROC to be consistent with TNMIN, 19 Jan 1999 CM

 TODO:
   * Make more compatible with CURVEFIT
   * Look for performance increases.

(See /host/bluemoon/usr2/idllib/contrib/markwardt/mpfit.pro)


MPFITEXPR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   MPFITEXPR

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov
   UPDATED VERSIONs can be found on my WEB PAGE: 
      http://astrog.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Perform Levenberg-Marquardt least-squares fit to arbitrary expression

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   MYFUNCT = 'X*(1-X)+3'
   parms = MPFITEXPR(MYFUNCT, XVAL, YVAL, ERR, start_parms, ...)

 DESCRIPTION:

  MPFITEXPR fits a user-supplied model -- in the form of an arbitrary IDL
  expression -- to a set of user-supplied data.  MPFITEXPR calls
  MPFIT, the MINPACK-1 least-squares minimizer, to do the main
  work.

  Given the data and their uncertainties, MPFITEXPR finds the best set
  of model parameters which match the data (in a least-squares
  sense) and returns them in an array.
  
  The user must supply the following items:
   - An array of independent variable values ("X").
   - An array of "measured" *dependent* variable values ("Y").
   - An array of "measured" 1-sigma uncertainty values ("ERR").
   - A text IDL expression which computes Y given X.

  There are very few restrictions placed on X, Y or the expression of
  the model.  Simply put, the expression must map the "X" values into
  "Y" values given the model parameters.  The "X" values may
  represent any independent variable (not just Cartesian X), and
  indeed may be multidimensional themselves.  For example, in the
  application of image fitting, X may be a 2xN array of image
  positions.

  Some rules must be obeyed in constructing the expression.  First,
  the independent variable name *MUST* be "X" in the expression,
  regardless of the name of the variable being passed to MPFITEXPR.
  This is demonstrated in the above calling sequence, where the X
  variable passed in is called "XVAL" but the expression still refers
  to "X".  Second, parameter values must be referred to as an array
  named "P".

  If you do not pass in starting values for the model parameters,
  MPFITEXPR will attempt to determine the number of parameters you
  intend to have (it does this by looking for references to the array
  variable named "P").  When no starting values are passed in, the
  values are assumed to start at zero.

  MPFITEXPR carefully avoids passing large arrays where possible to
  improve performance.

  See below for an example of usage.

  This source module also provides a function called MPEVALEXPR.  You
  can use this function to evaluate your expression, given a list of
  parameters.  This is one of the easier ways to compute the model
  once the best-fit parameters have been found.  Here is an example:

       YMOD = MPEVALEXPR(MYFUNCT, XVAL, PARMS)

  where MYFUNCT is the expression (see MYFUNCT below), XVAL is the
  list of "X" values, and PARMS is an array of parameters.  The
  returned array YMOD contains the expression MYFUNCT evaluated at
  each point in XVAL.
   
 INPUTS:
   MYFUNCT - a string variable containing an IDL expression.  The
             only restriction is that the independent variable *must*
             be referred to as "X" and model parameters *must* be
             referred to as an array called "P".  Do not use symbol
             names beginning with the underscore, "_".

             The expression should calculate "model" Y values given
             the X values and model parameters.  Using the vector
             notation of IDL, this can be quite easy to do.  If your
             expression gets complicated, you may wish to make an IDL
             function which will improve performance and readibility.

             The resulting array should be of the same size and
             dimensions as the "measured" Y values.

   START_PARAMS - An array of starting values for each of the
                  parameters of the model.  The number of parameters
                  should be fewer than the number of measurements.
                  Also, the parameters should have the same data type
                  as the measurements (double is preferred).

                  This parameter is optional if the PARINFO keyword
                  is used (see MPFIT).  The PARINFO keyword provides
                  a mechanism to fix or constrain individual
                  parameters.  If both START_PARAMS and PARINFO are
                  passed, then the starting *value* is taken from
                  START_PARAMS, but the *constraints* are taken from
                  PARINFO.

                  If no parameters are given, then MPFITEXPR attempts
                  to determine the number of parameters by scanning
                  the expression.  Parameters determined this way
                  are initialized to zero.
 
 INPUT KEYWORD PARAMETERS:

   MAXITER - The maximum number of iterations to perform.  If the
             number is exceeded, then the STATUS value is set to 5
             and MPFIT returns.
             Default: 200 iterations

   FTOL - a nonnegative input variable. Termination occurs when both
          the actual and predicted relative reductions in the sum of
          squares are at most FTOL.  Therefore, FTOL measures the
          relative error desired in the sum of squares.
          Default: 1D-10

   XTOL - a nonnegative input variable. Termination occurs when the
          relative error between two consecutive iterates is at most
          XTOL. therefore, XTOL measures the relative error desired
          in the approximate solution.
          Default: 1D-10

   GTOL - a nonnegative input variable. Termination occurs when the
          cosine of the angle between fvec and any column of the
          jacobian is at most GTOL in absolute value. Therefore, GTOL
          measures the orthogonality desired between the function
          vector and the columns of the jacobian.
          Default: 1D-10

   ITERPROC - The name of a procedure to be called upon each NPRINT
              iteration of the MPFIT routine.  It should be declared
              in the following way:

              PRO ITERPROC, MYFUNCT, p, iter, FUNCTARGS=fcnargs, $
                PARINFO=parinfo, QUIET=quiet, ...
                ; perform custom iteration update
              END
         
              ITERPROC must either accept all three keyword
              parameters (FUNCTARGS, PARINFO and QUIET), or at least
              accept them via the _EXTRA keyword.
          
              MYFUNCT is the user-supplied function to be minimized,
              P is the current set of model parameters, ITER is the
              iteration number, and FUNCTARGS are the arguments to be
              passed to MYFUNCT.  QUIET is set when no textual output
              should be printed.  See below for documentation of
              PARINFO.

              In implementation, ITERPROC, can perform updates to the
              terminal or graphical user interface, to provide
              feedback while the fit proceeds.  If the fit is to be
              stopped for any reason, then ITERPROC should set the
              system variable !ERR to a negative value.  In
              principle, ITERPROC should probably not modify the
              parameter values, because it may interfere with the
              algorithm's stability.  In practice it is allowed.

              Default: an internal routine is used to print the
                       parameter values.

   NPRINT - The frequency with which ITERPROC is called.  A value of
            1 indicates that ITERPROC is called with every iteration,
            while 2 indicates every other iteration, etc.  
            Default value: 1

   ITERARGS - The keyword arguments to be passed to ITERPROC via the
              _EXTRA mechanism.  This should be a structure, and is
              similar in operation to FUNCTARGS.
              Default: no arguments are passed.

   PARINFO - Provides a mechanism for more sophisticated constraints
             to be placed on parameter values.  When PARINFO is not
             passed, then it is assumed that all parameters are free
             and unconstrained.  In no case are values in PARINFO
             modified during a call to MPFIT.

             PARINFO should be an array of structures, one for each
             parameter.  Each parameter is associated with one
             element of the array, in numerical order.  The structure
             can have the following entries (none are required):

               - VALUE - the starting parameter value (but see
                         START_PARAMS above).

               - FIXED - a boolean value, whether the parameter is to 
                         be held fixed or not.  Fixed parameters are
                         not varied by MPFIT, but are passed on to 
                         MYFUNCT for evaluation.

               - LIMITED - a two-element boolean array.  If the
                 first/second element is set, then the parameter is
                 bounded on the lower/upper side.  A parameter can be
                 bounded on both sides.  Both LIMITED and LIMTIS must
                 be given together.

               - LIMITS - a two-element float or double array.  Gives
                 the parameter limits on the lower and upper sides,
                 respectively.  Zero, one or two of these values can
                 be set, depending on the value of LIMITED.  Both 
                 LIMITED and LIMITS must be given together

               - STEP - the step size to be used in calculating the
                 numerical derivatives.  If set to zero, then the
                 step size is computed automatically.
 
               - TIED - a string expression which "ties" the
                 parameter to other free or fixed parameters.  Any
                 expression involving constants and the parameter
                 array P are permitted.  Example: if parameter 2 is
                 always to be twice parameter 1 then use the
                 following: parinfo(2).tied = '2 * P(1)'.  Since they
                 are totally constrained, tied parameters are
                 considered to be fixed; no errors are computed for
                 them.
 
             Other tag values can also be given in the structure, but
             they are ignored.

             Example:
             parinfo = replicate({value:0.D, fixed:0, limited:[0,0], $
                                  limits:[0.D,0]}, 5)
             parinfo(0).fixed = 1
             parinfo(4).limited(0) = 1
             parinfo(4).limits(0)  = 50.D
             parinfo(*).value = [5.7D, 2.2, 500., 1.5, 2000.]

             A total of 5 parameters, with starting values of 5.7,
             2.2, 500, 1.5, and 2000 are given.  The first parameter
             is fixed at a value of 5.7, and the last parameter is
             constrained to be above 50.

             Default value:  all parameters are free and unconstrained.

   QUIET - set this keyword when no textual output should be printed
           by MPFIT

   NOCOVAR - set this keyword to prevent the calculation of the
             covariance matrix before returning (see COVAR)

 RETURNS:

   Returns the array of best-fit parameters.

 OUTPUT KEYWORD PARAMETERS:

   Output keywords are the same as MPFIT.
   
   NFEV - the number of MYFUNCT function evaluations performed.

   NITER - number of iterations completed.

   YFIT - the best-fit model function, as returned by MYFUNCT.

   ERRMSG - a string error or warning message is returned.

   BESTNORM - the value of the summed squared residuals for the
              returned parameter values.

   PERROR - The formal 1-sigma errors in each parameter.  If a
            parameter is held fixed, or if it touches a boundary,
            then the error is reported as zero.

   COVAR - the covariance matrix for the set of parameters returned
           by MPFIT.  The matrix is NxN where N is the number of
           parameters.  The square root of the diagonal elements
           gives the formal 1-sigma statistical errors on the
           parameters IF errors were treated "properly" in MYFUNC.
           Parameter errors are also returned in PERROR.

           To compute the correlation matrix, PCOR, use this:
           IDL> PCOR = COV * 0
           IDL> FOR i = 0, n-1 DO FOR j = 0, n-1 DO $
                PCOR(i,j) = COV(i,j)/sqrt(COV(i,i)*COV(j,j))

           If NOCOVAR is set or MPFIT terminated abnormally, then
           COVAR is set to a scalar with value !VALUES.D_NAN.

   STATUS - an integer status code is returned.  All values other
            than zero can represent success.  It can have one of the
            following values:

	   0  improper input parameters.
         
	   1  both actual and predicted relative reductions
	      in the sum of squares are at most FTOL.
         
	   2  relative error between two consecutive iterates
	      is at most XTOL
         
	   3  conditions for STATUS = 1 and STATUS = 2 both hold.
         
	   4  the cosine of the angle between fvec and any
	      column of the jacobian is at most GTOL in
	      absolute value.
         
	   5  the maximum number of iterations has been reached
         
	   6  FTOL is too small. no further reduction in
	      the sum of squares is possible.
         
	   7  XTOL is too small. no further improvement in
	      the approximate solution x is possible.
         
	   8  GTOL is too small. fvec is orthogonal to the
	      columns of the jacobian to machine precision.

 EXAMPLE:

   ; First, generate some synthetic data
   x  = dindgen(200) * 0.1 - 10.                   ; Independent variable 
   yi = gauss1(x, [2.2D, 1.4, 3000.]) + 1000       ; "Ideal" Y variable
   y  = yi + randomn(seed, 200) * sqrt(yi)         ; Measured, w/ noise
   sy = sqrt(y)                                    ; Poisson errors

   ; Now fit a Gaussian to see how well we can recover
   p0 = [800.D, 1.D, 1., 500.]                     ; Initial guess
   p = mpfitexpr('P(0) + GAUSS1(X, P(1:3))', $
                 x, y, sy, p0)                     ; Fit the expression
   print, p

   Generates a synthetic data set with a Gaussian peak, and Poisson
   statistical uncertainty.  Then a model consisting of a constant
   plus Gaussian is fit to the data.

 REFERENCES:

   MINPACK-1, Jorge More', available from netlib (www.netlib.org).
   "Optimization Software Guide," Jorge More' and Stephen Wright, 
     SIAM, *Frontiers in Applied Mathematics*, Number 14.

 MODIFICATION HISTORY:
   Written, Apr-Jul 1998, CM
   Added PERROR keyword, 04 Aug 1998, CM
   Added COVAR keyword, 20 Aug 1998, CM
   Added NITER output keyword, 05 Oct 1998
      D.L Windt, Bell Labs, windt@bell-labs.com;
   Added ability to return model function in YFIT, 09 Nov 1998
   Parameter values can be tied to others, 09 Nov 1998
   Added MPEVALEXPR utility function, 09 Dec 1998

(See /host/bluemoon/usr2/idllib/contrib/markwardt/mpfitexpr.pro)


MPFITFUN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   MPFITFUN

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov
   UPDATED VERSIONs can be found on my WEB PAGE: 
      http://astrog.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Perform Levenberg-Marquardt least-squares fit to IDL function

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   parms = MPFITFUN(MYFUNCT, X, Y, ERR, start_parms, ...)

 DESCRIPTION:

  MPFITFUN fits a user-supplied model -- in the form of an IDL
  function -- to a set of user-supplied data.  MPFITFUN calls
  MPFIT, the MINPACK-1 least-squares minimizer, to do the main
  work.

  Given the data and their uncertainties, MPFITFUN finds the best set
  of model parameters which match the data (in a least-squares
  sense) and returns them in an array.
  
  The user must supply the following items:
   - An array of independent variable values ("X").
   - An array of "measured" *dependent* variable values ("Y").
   - An array of "measured" 1-sigma uncertainty values ("ERR").
   - The name of an IDL function which computes Y given X ("MYFUNCT").

  There are very few restrictions placed on X, Y or MYFUNCT.  Simply
  put, MYFUNCT must map the "X" values into "Y" values given the
  model parameters.  The "X" values may represent any independent
  variable (not just Cartesian X), and indeed may be multidimensional
  themselves.  For example, in the application of image fitting, X
  may be a 2xN array of image positions.

  MPFITFUN carefully avoids passing large arrays where possible to
  improve performance.

  See below for an example of usage.
   
 INPUTS:
   MYFUNCT - a string variable containing the name of an IDL function.
             This function computes the "model" Y values given the
             X values and model parameters.  It should be declared in
             the following way:

             FUNCTION MYFUNCT, X, parms
               ; X are the independent variable values
               ; parms are the parameter values
               YMOD = ....
               RETURN, YMOD
             END

             The returned array YMOD should be of the same size and
             dimensions as the "measured" Y values.  

             See the discussion of AUTODERIVATIVE and MYFUNCT in
             MPFIT.PRO if you wish to compute your derivatives for
             yourself.  AUTODERIVATIVE is accepted by MPFITFUN and
             passed directly to MPFIT.

   START_PARAMS - An array of starting values for each of the
                  parameters of the model.  The number of parameters
                  should be fewer than the number of measurements.
                  Also, the parameters should have the same data type
                  as the measurements (double is preferred).

                  This parameter is optional if the PARINFO keyword
                  is used (see MPFIT).  The PARINFO keyword provides
                  a mechanism to fix or constrain individual
                  parameters.  If both START_PARAMS and PARINFO are
                  passed, then the starting *value* is taken from
                  START_PARAMS, but the *constraints* are taken from
                  PARINFO.
 
 INPUT KEYWORD PARAMETERS:

   FUNCTARGS - A structure which contains the parameters to be passed
               to the user-supplied function specified by MYFUNCT via
               the _EXTRA mechanism.  This is the way you can pass
               additional data to your user-supplied function without
               using common blocks.

               By default, no extra parameters are passed to the
               user-supplied function.

   MAXITER - The maximum number of iterations to perform.  If the
             number is exceeded, then the STATUS value is set to 5
             and MPFIT returns.
             Default: 200 iterations

   FTOL - a nonnegative input variable. Termination occurs when both
          the actual and predicted relative reductions in the sum of
          squares are at most FTOL.  Therefore, FTOL measures the
          relative error desired in the sum of squares.
          Default: 1D-10

   XTOL - a nonnegative input variable. Termination occurs when the
          relative error between two consecutive iterates is at most
          XTOL. therefore, XTOL measures the relative error desired
          in the approximate solution.
          Default: 1D-10

   GTOL - a nonnegative input variable. Termination occurs when the
          cosine of the angle between fvec and any column of the
          jacobian is at most GTOL in absolute value. Therefore, GTOL
          measures the orthogonality desired between the function
          vector and the columns of the jacobian.
          Default: 1D-10

   ITERPROC - The name of a procedure to be called upon each NPRINT
              iteration of the MPFIT routine.  It should be declared
              in the following way:

              PRO ITERPROC, MYFUNCT, p, iter, FUNCTARGS=fcnargs, $
                PARINFO=parinfo, QUIET=quiet, ...
                ; perform custom iteration update
              END
         
              ITERPROC must either accept all three keyword
              parameters (FUNCTARGS, PARINFO and QUIET), or at least
              accept them via the _EXTRA keyword.
          
              MYFUNCT is the user-supplied function to be minimized,
              P is the current set of model parameters, ITER is the
              iteration number, and FUNCTARGS are the arguments to be
              passed to MYFUNCT.  QUIET is set when no textual output
              should be printed.  See below for documentation of
              PARINFO.

              In implementation, ITERPROC, can perform updates to the
              terminal or graphical user interface, to provide
              feedback while the fit proceeds.  If the fit is to be
              stopped for any reason, then ITERPROC should set the
              system variable !ERR to a negative value.  In
              principle, ITERPROC should probably not modify the
              parameter values, because it may interfere with the
              algorithm's stability.  In practice it is allowed.

              Default: an internal routine is used to print the
                       parameter values.

   NPRINT - The frequency with which ITERPROC is called.  A value of
            1 indicates that ITERPROC is called with every iteration,
            while 2 indicates every other iteration, etc.  
            Default value: 1

   ITERARGS - The keyword arguments to be passed to ITERPROC via the
              _EXTRA mechanism.  This should be a structure, and is
              similar in operation to FUNCTARGS.
              Default: no arguments are passed.

   PARINFO - Provides a mechanism for more sophisticated constraints
             to be placed on parameter values.  When PARINFO is not
             passed, then it is assumed that all parameters are free
             and unconstrained.  In no case are values in PARINFO
             modified during a call to MPFIT.

             PARINFO should be an array of structures, one for each
             parameter.  Each parameter is associated with one
             element of the array, in numerical order.  The structure
             can have the following entries (none are required):

               - VALUE - the starting parameter value (but see
                         START_PARAMS above).

               - FIXED - a boolean value, whether the parameter is to 
                         be held fixed or not.  Fixed parameters are
                         not varied by MPFIT, but are passed on to 
                         MYFUNCT for evaluation.

               - LIMITED - a two-element boolean array.  If the
                 first/second element is set, then the parameter is
                 bounded on the lower/upper side.  A parameter can be
                 bounded on both sides.  Both LIMITED and LIMTIS must
                 be given together.

               - LIMITS - a two-element float or double array.  Gives
                 the parameter limits on the lower and upper sides,
                 respectively.  Zero, one or two of these values can
                 be set, depending on the value of LIMITED.  Both 
                 LIMITED and LIMITS must be given together

               - STEP - the step size to be used in calculating the
                 numerical derivatives.  If set to zero, then the
                 step size is computed automatically.
 
               - TIED - a string expression which "ties" the
                 parameter to other free or fixed parameters.  Any
                 expression involving constants and the parameter
                 array P are permitted.  Example: if parameter 2 is
                 always to be twice parameter 1 then use the
                 following: parinfo(2).tied = '2 * P(1)'.  Since they
                 are totally constrained, tied parameters are
                 considered to be fixed; no errors are computed for
                 them.
 
             Other tag values can also be given in the structure, but
             they are ignored.

             Example:
             parinfo = replicate({value:0.D, fixed:0, limited:[0,0], $
                                  limits:[0.D,0]}, 5)
             parinfo(0).fixed = 1
             parinfo(4).limited(0) = 1
             parinfo(4).limits(0)  = 50.D
             parinfo(*).value = [5.7D, 2.2, 500., 1.5, 2000.]

             A total of 5 parameters, with starting values of 5.7,
             2.2, 500, 1.5, and 2000 are given.  The first parameter
             is fixed at a value of 5.7, and the last parameter is
             constrained to be above 50.

             Default value:  all parameters are free and unconstrained.

   QUIET - set this keyword when no textual output should be printed
           by MPFIT

   NOCOVAR - set this keyword to prevent the calculation of the
             covariance matrix before returning (see COVAR)

 RETURNS:

   Returns the array of best-fit parameters.

 OUTPUT KEYWORD PARAMETERS:

   Output keywords are the same as MPFIT.
   
   NFEV - the number of MYFUNCT function evaluations performed.

   NITER - number of iterations completed.

   YFIT - the best-fit model function, as returned by MYFUNCT.

   ERRMSG - a string error or warning message is returned.

   BESTNORM - the value of the summed squared residuals for the
              returned parameter values.

   PERROR - The formal 1-sigma errors in each parameter.  If a
            parameter is held fixed, or if it touches a boundary,
            then the error is reported as zero.

   COVAR - the covariance matrix for the set of parameters returned
           by MPFIT.  The matrix is NxN where N is the number of
           parameters.  The square root of the diagonal elements
           gives the formal 1-sigma statistical errors on the
           parameters IF errors were treated "properly" in MYFUNC.
           Parameter errors are also returned in PERROR.

           To compute the correlation matrix, PCOR, use this:
           IDL> PCOR = COV * 0
           IDL> FOR i = 0, n-1 DO FOR j = 0, n-1 DO $
                PCOR(i,j) = COV(i,j)/sqrt(COV(i,i)*COV(j,j))

           If NOCOVAR is set or MPFIT terminated abnormally, then
           COVAR is set to a scalar with value !VALUES.D_NAN.

   STATUS - an integer status code is returned.  All values other
            than zero can represent success.  It can have one of the
            following values:

	   0  improper input parameters.
         
	   1  both actual and predicted relative reductions
	      in the sum of squares are at most FTOL.
         
	   2  relative error between two consecutive iterates
	      is at most XTOL
         
	   3  conditions for STATUS = 1 and STATUS = 2 both hold.
         
	   4  the cosine of the angle between fvec and any
	      column of the jacobian is at most GTOL in
	      absolute value.
         
	   5  the maximum number of iterations has been reached
         
	   6  FTOL is too small. no further reduction in
	      the sum of squares is possible.
         
	   7  XTOL is too small. no further improvement in
	      the approximate solution x is possible.
         
	   8  GTOL is too small. fvec is orthogonal to the
	      columns of the jacobian to machine precision.

 EXAMPLE:

   ; First, generate some synthetic data
   x  = dindgen(200) * 0.1 - 10.                   ; Independent variable 
   yi = gauss1(x, [2.2D, 1.4, 3000.])              ; "Ideal" Y variable
   y  = yi + randomn(seed, 200) * sqrt(1000. + yi) ; Measured, w/ noise
   sy = sqrt(1000.D + y)                           ; Poisson errors

   ; Now fit a Gaussian to see how well we can recover
   p0 = [1.D, 1., 1000.]                           ; Initial guess
   p = mpfitfun('GAUSS1', x, y, sy, p0)            ; Fit a function
   print, p

   Generates a synthetic data set with a Gaussian peak, and Poisson
   statistical uncertainty.  Then the same function is fitted to the
   data to see how close we can get.

 REFERENCES:

   MINPACK-1, Jorge More', available from netlib (www.netlib.org).
   "Optimization Software Guide," Jorge More' and Stephen Wright, 
     SIAM, *Frontiers in Applied Mathematics*, Number 14.

 MODIFICATION HISTORY:
   Written, Apr-Jul 1998, CM
   Added PERROR keyword, 04 Aug 1998, CM
   Added COVAR keyword, 20 Aug 1998, CM
   Added ITER output keyword, 05 Oct 1998
      D.L Windt, Bell Labs, windt@bell-labs.com;
   Added ability to return model function in YFIT, 09 Nov 1998
   Analytical derivatives allowed via AUTODERIVATIVE keyword, 09 Nov 1998
   Parameter values can be tied to others, 09 Nov 1998

 TODO:
   * Add WEIGHTS keyword, and allow to substitute for ERROR.
   * Add GUI.
   * Make a CURVEFIT drop-in replacement.

(See /host/bluemoon/usr2/idllib/contrib/markwardt/mpfitfun.pro)


OPLOTIMAGE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   OPLOTIMAGE

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov

 PURPOSE:
   Overlays an image on an existing plot.

 CALLING SEQUENCE:
   OPLOTIMAGE, img

 DESCRIPTION: 

   OPLOTIMAGE overlays an image on an already-existing set of plot
   axes.  It should not matter what plot elements have already be
   displayed, but at least one command is needed to set up the plot
   axes.

   Only the IMGXRANGE and IMGYRANGE keywords, specifying the extent
   of the image, can be given in a call to OPLOTIMAGE.

   See PLOTIMAGE for more detailed information.

 INPUTS:

   IMG - A byte array to be displayed.  An image declared as
         ARRAY(M,N) will be M pixels in the x-direction and N pixels
         in the y-direction.  The image is resampled via
         interpolation to fill the desired display region.
 
 OPTIONAL INPUTS:
   NONE

 INPUT KEYWORD PARAMETERS:

   IMGXRANGE, IMGYRANGE - Each is a two component vector that
                          describes the X and Y position of the first
                          and last pixels.
                          Default: the size of the image in pixels

 OUTPUTS:
   NONE

 PROCEDURE:

 EXAMPLE:

   This example first constructs an image whose values are found by
       z(x,y) = cos(x) * sin(y)
   and x and y are in the range [-2,2] and [4,8], respectively.
   The image is then plotted in the range [-10, 10] in both x and
   y directions.
   
   x = findgen(20)/5. - 2.
   y = findgen(20)/5. + 4.
   zz = cos(x) # sin(y)
   imgxrange = [min(x), max(x)]
   imgyrange = [min(y), max(y)]
   xr=[-10.,10]
   yr=[-10.,10]
   plotimage, bytscl(zz), imgxrange=imgxrange, imgyrange=imgyrange

   Now for the overlay.  A new image is created in the ranges between
   -10 and 0:
      z(x,y) = x y

   x = findgen(20)/2 - 10.
   y = findgen(20)/2 - 10.
   imgxrange = [min(x), max(x)]
   imgyrange = [min(y), max(y)]
   zz = x # y
   oplotimage, bytscl(zz), imgxrange=imgxrange, imgyrange=imgyrange

 SEE ALSO:

   PLOTIMAGE, BYTSCL

 EXTERNAL SUBROUTINES:

   SUBCELL, DEFSUBCELL, TVIMAGE

 MODIFICATION HISTORY:
   Written, CM, 1997

(See /host/bluemoon/usr2/idllib/contrib/markwardt/oplotimage.pro)


PLOTCOLORFILL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   PLOTCOLORFILL

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov

 PURPOSE:
   Plots colorful bar charts

 CALLING SEQUENCE:
   PLOTCOLORFILL, x, y, COLOR=col, BOTTOM=bot, WIDTH=wid, ...

 DESCRIPTION: 

   PLOTCOLORFILL plots a colorful vertical bar chart.  This may be
   useful in cases where two dimensions of information need to be
   conveyed in one plot.  [ I use it to show total intensity as a
   function of time on the vertical axis, and temperature is coded
   with color. ]

   Most aspects of the bars are configurable.  The color is specified
   by an array of colors, one for each bar.  [ Alternatively, a
   single color for the entire plot can be given. ] Also, one color
   can be designated as transparent.

   Stacked bar charts can be constructed using two calls to
   PLOTCOLORFILL.  See the example.

 INPUTS:

   X, Y - Two arrays which give the X and Y position of the points.
          In this style of plot, the x values should be monotonically
          increasing, but not necessarily monospaced (see WIDTH).

 OPTIONAL INPUTS:
   NONE

 INPUT KEYWORD PARAMETERS:

   COLOR - an array giving the color of each bar, or alternatively a
           scalar color for all of the bars.  The current color table
           is not changed.  Default is color "1"

   BOTTOM - normally the bottom of the bars is set to be zero.  You
            may either specify a scalar bottom value for all of the
            bars, or an array giving the bottom of each bar
            individually.  See the example to see how stacked bar
            charts can be constructed with this keyword.

   WIDTH - sets the width of each bar, globally or individually.
           Bars are centered on the "X" value, and extend 0.5 * WIDTH
           to either side.  Default is to assume monospacing, using
           the separation between the first two x values.

   TRANSPARENT - designates a color which is "transparent".  Any bars
                 with this color are simply not plotted.  Default is
                 no transparent color.

   PANEL, SUBPANEL - An alternate way to more precisely specify the
                     plot and annotation positions.  See SUBCELL.
                     Default is full-screen.

   POSITION - Position of the bar chart in normal coordinates.
              Overrides position given by PANEL/SUBPANEL.

   XRANGE, YRANGE - gives plot range for each dimension, as for other
                    plot commands.  Default is range of data.

   Other keywords are passed to the plot command directly.
           
 OUTPUTS:
   NONE

 PROCEDURE:

 EXAMPLE:

   Stacked barcharts can be constructed by first making one chart
   with a flat bottom, and then a second chart whose bottom is top of
   the first.

   x = findgen(30)
   y1 = x^2
   y2 = 400.-x
   c1 = bindgen(30)*3+1b
   c2 = 100b-bindgen(30)*3+1b
   plotcolorfill, x, y1,    color=c1, bottom=0.
   plotcolorfill, x, y1+y2, color=c2, bottom=y1, /noerase

 SEE ALSO:

   PLOTPAN

 EXTERNAL SUBROUTINES:

   SUBCELL, DEFSUBCELL, PLOTPAN

 MODIFICATION HISTORY:
   Written, CM, 1997

(See /host/bluemoon/usr2/idllib/contrib/markwardt/plotcolorfill.pro)


PLOTCUBE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   PLOTCUBE

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov

 PURPOSE:
   Plots a three dimensional data that can be printed and made into a cube

 CALLING SEQUENCE:
   PLOTCUBE, x, y, z

 DESCRIPTION: 

   PLOTCUBE plots a three dimensional data set so that it can be
   printed on paper, cut out, and folded together to make a real-life
   three dimensional cube.  This may be useful in visualization
   applications.  The six faces of the cube contain a projection of
   the data onto that face.

   The output consists of a flat matrix of six plots, which are
   joined together at the proper edges of the cube.  Your task,
   should you choose to accept it, is to cut out the cube and
   assemble it.

   Before folding the cube together, it will look like the diagram
   below.  You need to match together edges labelled with the same
   letter.

                            A
                          +----+
                         B|    |G
                      B   |    |   G
                     +----+----+----+
                     |    |    |    |
                    C|    |    |    |E
                     +----+----+----+
                      D   |    |   F
                         D|    |F
                          +----+
                          |    |
                         C|    |E
                          +----+
                            A

   HINT 1: When printing, be sure that the XSIZE and YSIZE are given
           in the ratio of 3 to 4.  A size of 6 in by 8 in is
           suitable.

   HINT 2: As a practical matter for assembling the cube once it has
           been printed, you should leave some extra paper tabs so
           that adhesive can be applied.

 INPUTS:

   X, Y, Z - Three arrays which specify position in three dimensional
             space.  All three arrays should be of the same length.

 OPTIONAL INPUTS:
   NONE

 INPUT KEYWORD PARAMETERS:

   PANEL, SUBPANEL - An alternate way to more precisely specify the
                     plot and annotation positions.  See SUBCELL.
                     Default is full-screen.

   XRANGE, YRANGE, ZRANGE - gives plot range for each dimension, as
                            for other plot commands.  Default is
                            range of data.

   XTITLE, YTITLE, ZTITLE - gives title for each axis.  The title
                            labels each face of the cube where
                            possible.

   NOERASE - If set, the display is not erased before graphics
             operations.

   Other options are passed along to the PLOT command directly.

 OUTPUTS:
   NONE

 PROCEDURE:

 EXAMPLE:

   This example takes some synthetic data and makes a cube out of it.
   Visualizing the trace of the curve is more convenient when it can
   be projected on the cube in each dimension.

   t = findgen(200)/20. - 10.
   x = cos(t)
   y = sin(t) + 0.05*t
   z = exp(t) + 0.05*randomn(seed, 200)
   plotcube, x, y, z, xrange=[-1.5,1.5], yrange=[-1.5,1.5], zrange=[-1.5,1.5]

 SEE ALSO:

   DEFSUBCELL, SUBCELLARRAY

 EXTERNAL SUBROUTINES:

   SUBCELL, DEFSUBCELL, PLOTPAN

 MODIFICATION HISTORY:
   Written, CM, 1997

(See /host/bluemoon/usr2/idllib/contrib/markwardt/plotcube.pro)


PLOTIMAGE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   PLOTIMAGE

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov

 PURPOSE:
   Displays an image via a "PLOT"-like interface.

 CALLING SEQUENCE:
   PLOTIMAGE, img, [xrange=xrange,] [yrange=yrange,] ...

 DESCRIPTION: 

   PLOTIMAGE displays an image (or slice of an image) on the current
   graphics device.  The syntax is very similar to the PLOT command,
   in the sense that an XRANGE and YRANGE for the plot can be
   specified.  

   More importantly, coordinate ranges can be specified for the
   *image* itself, and then PLOTIMAGE will intelligently crop the
   image so that only the part that falls within the XRANGE and
   YRANGE is displayed.  Images often have physical units (other than
   pixels) assigned to their X and Y dimensions.  PLOTIMAGE allows
   you to slice the image appropriately and display appropriate
   coordinate axes.

   Image coordinates are specified via the IMGXRANGE and IMGYRANGE
   keywords.  IMGXRANGE specifies the x-values for the first and last
   pixels in each row.  IMGYRANGE gives the y-values for the first
   and last pixels in each column.  Default image coordinates are in
   units of pixels.

   Plot coordinates are specified in the usual XRANGE and YRANGE
   keywords.  The [XY]RANGE may specify a range smaller than the
   image size, so that the image is cropped; or a range larger than
   the image size, in which case the appropriate portion of the image
   is displayed.

 INPUTS:

   IMG - A byte array to be displayed.  An image declared as
         ARRAY(M,N) will be M pixels in the x-direction and N pixels
         in the y-direction.  The image is resampled via
         interpolation to fill the desired display region.
 
 OPTIONAL INPUTS:
   NONE

 INPUT KEYWORD PARAMETERS:

   XRANGE, YRANGE - Each is a two component vector that specifies the
                    X and Y plot ranges, respectively.  These values
                    are not required to coincide with IMG[XY]RANGE.
                    Default: the image ranges

   IMGXRANGE, IMGYRANGE - Each is a two component vector that
                          describes the X and Y position of the first
                          and last pixels.
                          Default: the size of the image in pixels

   POSITION - Position of the inner plot window in the standard
              graphics keyword format.  Overrides PANEL and SUBPANEL.

   PANEL, SUBPANEL - An alternate way to more precisely specify the
                     plot and annotation positions.  See SUBCELL.

   NOERASE - If set, the display is not erased before graphics
             operations.

   NODATA - If set, the image is not actually displayed, but
            coordinate axes may be drawn.

   NOAXES - An attempt is made to render the image without coordinate
            axes.  This is possible if POSITION, PANEL, or SUBPANEL
            are  given.

   PLOTIMAGE will pass other keywords directly to the PLOT command
   used for generating the plot axes.  XSTYLE=1 and YSTYLE=1 are
   enforced.

 OUTPUTS:
   NONE

 PROCEDURE:

 EXAMPLE:

   This example constructs an image whose values are found by
       z(x,y) = cos(x) * sin(y)
   and x and y are in the range [-2,2] and [4,8], respectively.
   The image is then plotted, with appropriate axes.
   
   x = findgen(20)/5. - 2.
   y = findgen(20)/5. + 4.
   zz = cos(x) # sin(y)
   imgxrange = [min(x), max(x)]
   imgyrange = [min(y), max(y)]
   plotimage, bytscl(zz), imgxrange=imgxrange, imgyrange=imgyrange

   This second example plots the same image, but with a plot range
   much larger than the image's.

   xr=[-10.,10]
   yr=[-10.,10]
   plotimage, bytscl(zz), imgxrange=imgxrange, imgyrange=imgyrange, $
      xrange=xr, yrange=yr

 SEE ALSO:

   OPLOTIMAGE, BYTSCL

 EXTERNAL SUBROUTINES:

   SUBCELL, DEFSUBCELL, TVIMAGE

 MODIFICATION HISTORY:
   Written, CM, 1997

(See /host/bluemoon/usr2/idllib/contrib/markwardt/plotimage.pro)


PLOTPAN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   PLOTPAN

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov

 PURPOSE:
   Same as PLOT command, but respects PANEL and SUBPANEL

 CALLING SEQUENCE:
   PLOTPAN, x, y, ...

 DESCRIPTION: 

   PLOTPAN is almost identical to PLOT, except that it accounts for
   panels and subpanels in the display.  In fact, after a short
   calculation, PLOTPAN calls PLOT to do its dirty work.

   Once the coordinate grid has been set up by PLOTPAN, other plots
   can be overlaid by calling OPLOT.

 INPUTS:

   X, Y - Two arrays which give the x and y position of each point.

 OPTIONAL INPUTS:
   NONE

 INPUT KEYWORD PARAMETERS:

   PANEL, SUBPANEL - An alternate way to more precisely specify the
                     plot and annotation positions.  See SUBCELL.
                     Default is full-screen.  Overridden by POSITION.

   Other options are passed along to the PLOT command directly.

 OUTPUTS:
   NONE

 PROCEDURE:

 EXAMPLE:

 SEE ALSO:

   SUBCELL, DEFSUBCELL, SUBCELLARRAY

 EXTERNAL SUBROUTINES:

   PLOT, SUBCELL

 MODIFICATION HISTORY:
   Written, CM, 1997

(See /host/bluemoon/usr2/idllib/contrib/markwardt/plotpan.pro)


PS_FORM

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   PS_FORM

 PURPOSE:
   This function puts up a form the user can configure a PostScript
   device driver. The function result (if the user selects either the
   ACCEPT or CREATE FILE buttons) can be sent directly to the DEVICE
   procedure by means of its _Extra keyword.  User's predefined
   configurations may be retrieved from a common block.

 AUTHOR:
   *********** CM 19 Jan 1999 VERSION *************
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov

   Based almost entirely on, but a totally revamped version of, PS_FORM by 
   FANNING SOFTWARE CONSULTING
   David Fanning, Ph.D.
   2642 Bradbury Court
   Fort Collins, CO 80521 USA
   Phone: 970-221-0438
   E-mail: davidf@dfanning.com
   Coyote's Guide to IDL Programming: http://www.dfanning.com

 MAJOR TOPICS:
   Device Drivers, Hardcopy Output, PostScript Output

 PROCEDURE:
   This is a pop-up form widget. It is a modal or blocking widget.
   Keywords appropriate for the PostScript DEVICE command are returned.

   Use your LEFT mouse button to move the "Plot Window" around the page.
   Use your RIGHT mouse button to draw your own "Plot Window" on the page.

 HELP:
   formInfo = PS_FORM(/Help)

 CALLING SEQUENCE:
    formInfo = PS_FORM(xoffset, yoffset, Cancel=cancelButton)

 OPTIONAL INPUTS:

    XOFFSET -- Optional xoffset of the top-level base of PS_Form. Default is
    to try to center the form on the display.

    YOFFSET -- Optional yoffset of the top-level base of PS_Form. Default is
    to try to center the form on the display.

 INPUT KEYWORD PARAMETERS:

    BITS_PER_PIXEL -- The initial configuration of the bits per pixel button.

    BLOCKING -- Set this keyword to make this a blocking widget under IDL 5.0.
    (All widget programs block under IDL 4.0.)

    COLOR -- The initial configuration of the color switch.

    DEFAULTS -- A stucture variable of the same type and structure as the
    RETURN VALUE of PS_FORM. It will set initial conditions. This makes
    it possible to start PS_FORM up again with the same values it had the
    last time it was called. For example:

       mysetup = PS_FORM()
       newsetup = PS_FORM(Defaults=mysetup)

    ENCAPSULATED -- The initial configuration of the encapsulated switch.

    FILENAME -- The initial filename to be used on the form.

    HELP -- Prints a helpful message in the output log.

    INCHES -- The initial configuration of the inches/cm switch.

    INITIALIZE -- If this keyword is set, the program immediately returns the
    "localdefaults" structure. This gives you the means to configue the
    PostScript device without interrupting the user.

    SELECT -- used only when INITIALIZE is set.  Set SELECT to a
              string which identifies the predefined configuration to
              be returned by PS_FORM when INITIALIZE is set.  This is
              a convenient way to select a predefined config
              non-interactively.

    LANDSCAPE -- The initial configuration of the landscape/portrait switch.

    LOCALDEFAULTS -- A structure like the DEFAULTS structure. If specified,
    then it is added as a predefined configuration entry called "Local".
    See below for a further discussion of predefined configurations.

    PREDEFINED -- An alternate way to specify predefined
                  configurations.  Pass an array of structures to
                  populate the "predefined" dropbox in the
                  dialog. This array, if specified, overrides the the
                  common block technique.

    XOFFSET -- The initial XOffSet of the PostScript page.

    YOFFSET -- The initial YOffSet of the PostScript page.

    XSIZE -- The initial XSize of the PostScript page.

    YSIZE -- The initial YSize of the PostScript page.

    NOCOMMON -- If set, PS_FORM will not attempt to access a common block
    in its quest for predefined configurations.  Default is for common
    to be accessed.

    PAPERSIZE -- If set, allows user to specify the size of the paper
                 media to be printed on, as a scalar string.  NOTE:
                 this specification cannot be passed to DEVICE, but
                 can be selected for completeness's sake.  Default is
                 'Letter'.

    MARGINSIZE -- Size of the margins on all sides.  Default is 0.25 inches.
                  When MARGINSIZE is non-zero, a graphic cannot directly
                  abut the edge of the page.  This is normally a good thing,
                  since there is often a  non-printable region which borders
                  the page.

   DEFAULTPAPER -- Default paper size to use, when it is unspecified
                   in a predefined, "local", or "default"
                   configuration.  This value also overrides any
                   configuration from common blocks.  European users
                   will probably set this to 'A4'.

   PARENT -- if this widget is invoked by another widget program,
             then this keyword parameter must be set to the top level
             widget which is to serve as the group leader.  Failure
             to do so will result in unexpected behavior.  IDL 4
             programs do not need to pass this parameter.  Default:
             NONE.

 OUTPUT KEYWORD PARAMETERS

    CANCEL -- This is an OUTPUT keyword. It is used to check if the user
    selected the "Cancel" button on the form. Check this variable rather
    than the return value of the function, since the return value is designed
    to be sent directly to the DEVICE procedure. The varible is set to 1 if
    the user selected the "Cancel" button. Otherwise, it is set to 0.

    CREATE -- This output keyword can be used to determine if the user
    selected the 'Create File' button rather than the 'Accept' button.
    The value is 1 if selected, and 0 otherwise.

    PAPERSIZE -- If set to a named variable, any newly selected paper
    size is returned in that variable.

 RETURN VALUE:

     formInfo = { PS_FORM_INFO, $
                  xsize:0.0, $        ; The x size of the plot
                  xoff:0.0, $         ; The x offset of the plot
                  ysize:0.0, $        ; The y size of the plot
                  yoff:0.0 $          ; The y offset of the plot
                  filename:'', $      ; The name of the output file
                  inches:0 $          ; Inches or centimeters?
                  color:0, $          ; Color on or off?
                  bits_per_pixel:0, $ ; How many bits per image pixel?
                  encapsulated:0,$    ; Encapsulated or regular PostScript?
                  isolatin1:0,$       ; Encoded with ISOLATIN1?
                  landscape:0 }       ; Landscape or portrait mode?

 USAGE:

  The calling procedure for this function in a widget program will look something
  like this:

     info.ps_config = PS_FORM(/Initialize)

     formInfo = PS_FORM(Cancel=canceled, Create=create, Defaults=info.ps_config)

     IF NOT canceled THEN BEGIN
        IF create THEN BEGIN
           thisDevice = !D.Name
           Set_Plot, "PS"
           Device, _Extra=formInfo

           Enter Your Graphics Commands Here!

           Device, /Close
           Set_Plot, thisDevice
           info.ps_config = formInfo
        ENDIF ELSE
           info.ps_config = formInfo
     ENDIF

 MAJOR FUNCTIONS and PROCEDURES:

   None. Designed to work originally in conjunction with XWindow, a
   resizable graphics window.  [ NOTE: this modified version of
   PS_FORM, by Craig Markwardt, is incompatible with the original
   version of XWINDOW. ]

 MODIFICATION HISTORY:

   Based on PS_FORM of : David Fanning, RSI, March 1995.
   Major rewrite by: Craig Markwardt, October 1997.
     - Drawing and updating of form and sample box are now modular
     - Option of storing more than one predefined postscript configuration
     - Selection of paper size by name
     - Access to predfined configurations through (optional) common
       block
   Several additions, CM, April 1998  VERSION CM2.0
     - better integration of paper sizes throughout program.
       Predefined configurations now also know about paper.
     - allow passing predefined configurations instead of using
       common block
     - addition of ISOLATIN selection, and streamlining of dialog
       appearance
   Fixed bug in INITIALIZE w.r.t. paper sizes, CM, Nov 1998
   Added SELECT keyword, CM, 09 Dec 1998
   Added Parent keyword to allow modal widgets in IDL 5, 19 Jan 1999

 COMMON BLOCKS:
 
   The user may store frequently used or helpful configurations in a 
   common block, and PS_FORM() will attempt to access them.  This
   provides a way for the user to have persistent, named,
   configurations.

   NOTE: this format has changed since the last version.  You may
   have to quit your IDL session for the changes to take effect
   properly.  If you have place a predefined configuration in your
   startup file, you should review the new format.
   
     COMMON PS_FORM_CONFIGS, PS_FORM_DEFAULT_PAPERSIZE, PS_FORM_STDCONFIGS

        PS_FORM_DEFAULT_PAPERSIZE - a string designating the default
                                    paper size, when none is given.
                                    The predefined configurations
                                    offerred by this program will
                                    respect the default value.  (See
                                    also the DEFAULTPAPER keyword.)

        PS_FORM_STDCONFIGS - An array of PS_FORM_CONFIG structures,
                             each containing information about one
                             predefined configuration, such as its
                             name and size of paper.  Each "config"
                             element is a PS_FORM_INFO structure,
                             which contains the actual postscript
                             configuration.

   See the IDL source code PS_FORM_LOAD_CONFIGS for an example of how
   to make a list of configurations.  One possibility would be to
   declare and populate the common block from within the user's
   start-up script, allowing the same configurations to appear in
   every session.

   PS_FORM() takes its initial list of configurations from this
   common block if it exists.  A default list is provided ala the
   procedure PS_FORM_LOAD_CONFIGS.  Any modifications that take place
   during the PS_FORM() widget session are not transferred back to
   the common block upon return.  It might be useful to be able to do
   this, through some form of 'save' procedure.

   If the keyword NOCOMMON is set, then the access of the common
   block is bypassed altogether.  The default list is accessed
   directly.

   Also, if the PREDEFINED keyword is used, then the common block is
   not consulted.

(See /host/bluemoon/usr2/idllib/contrib/markwardt/ps_form.pro)


SUBCELL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   SUBCELL

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov

 PURPOSE:
   Finds the position of a subwindow within a reference window.

 CALLING SEQUENCE:
   sub = subcell(panel, refposition)

 DESCRIPTION: 

   SUBCELL finds the position of a subwindow within another window.
   This could be useful in cases where the position of one window is
   specified relative to another one.

   When plotting, one often wants to describe the position of the
   plot box with respect to another box on the screen.  In that
   respect, the reference window can be thought of as a virtual
   display, and the SUBPOS as virtual a position on that display.
   The SUBCELL function transforms the relative coordinates of the
   virtual position back to normal screen coordinates.

 INPUTS:

   SUBPOS - A four-element array giving the position of the
            subwindow, *relative* to a reference window given by
            POSITION.  Given as [XS1, YS1, XS2, YS2], which describes
            the lower left and upper right corners of the subwindow.
            Each value is a number between zero and one, zero being
            the lower/left and one being the upper/right corners of
            the reference window.

   POSITION - A four-element array giving the position of the
              reference window on the screen.  Equivalent to the
              graphics keyword of the same name.
 
 OPTIONAL INPUTS:
   NONE

 INPUT KEYWORD PARAMETERS:

   MARGIN - If set, then a default value for SUBPOS is found using
            the DEFSUBCELL function.

 RETURNS:
   The position of the subwindow, in normal coordinates.

 PROCEDURE:

 EXAMPLE:


 SEE ALSO:

   DEFSUBCELL, SUBCELLARRAY

 EXTERNAL SUBROUTINES:

   DEFSUBCELL

 MODIFICATION HISTORY:
   Written, CM, 1997

(See /host/bluemoon/usr2/idllib/contrib/markwardt/subcell.pro)


SUBCELLARRAY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   SUBCELLARRAY

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov

 PURPOSE:
   Returns a set of subcells, suitable for creating a matrix of plots.

 CALLING SEQUENCE:
   subcellarray, xdivs, ydivs, newpanels, newsubpanels

 DESCRIPTION: 

   SUBCELLARRAY generates a group of subcells.  The subcells are
   useful for plotting a matrix of functions.

   It takes a list of subdivisions in X and Y, designating the
   subdivision of the plot into num(X) X panels and num(Y) Y panels,
   and creates a new batch of panels and subpanels, which can be used
   in the individual plot commands of the array.

 INPUTS:

   XDIVS - list of subdivisions in the X-direction.  Example: [1,1,2]
           will create three panels in the X-direction such that
           their sizes are in the ratio of 1:1:2.  These are the
           subdivisions of the SUBPANEL, the inner plot box boundary,
           not divisions of the PANEL, which is the boundary that
           includes axis labels.

   YDIVS - same, for Y direction

 OPTIONAL INPUTS:
   NONE

 INPUT KEYWORD PARAMETERS:

   PANEL - Original panel (outer margin) of plot. Default is to fill
           screen.

   SUBPANEL - Original subpanel (inner margin) of plot.  Default is
              to use defsubcell().

 OUTPUTS:

   NEWPANELS - output array of panels.  The output is 4 x M x N where
               M is the number of X divisions and N is the number of
               Y divisions.

   NEWSUBPANELS - output array of subpanels, with correct adjustment
                  for margins, same format as NEWPANELS.

 PROCEDURE:

 EXAMPLE:

   See PLOTCUBE for an example usage.

 SEE ALSO:

   DEFSUBCELL, SUBCELLARRAY, PLOTCUBE

 EXTERNAL SUBROUTINES:

   DEFSUBCELL

 MODIFICATION HISTORY:
   Written, CM, 1997

(See /host/bluemoon/usr2/idllib/contrib/markwardt/subcellarray.pro)


TNMIN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   TNMIN

 AUTHOR:
   Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
   craigm@lheamail.gsfc.nasa.gov
   UPDATED VERSIONs can be found on my WEB PAGE: 
      http://astrog.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Performs Truncated-Newton function minimization (with gradients).

 MAJOR TOPICS:
   Optimization and Minimization

 CALLING SEQUENCE:
   parms = TNMIN(MYFUNCT, start_parms, FUNCTARGS=fcnargs, NFEV=nfev,
                 MAXITER=maxiter, ERRMSG=errmsg, NPRINT=nprint,
                 QUIET=quiet, XTOL=xtol, STATUS=status, 
                 FGUESS=fguess, PARINFO=parinfo, BESTMIN=bestmin,
                 ITERPROC=iterproc, ITERARGS=iterargs, niter=niter)

 DESCRIPTION:

  TNMIN uses the Truncated-Newton method to minimize an arbitrary IDL
  function with respect to a given set of free parameters.  The
  user-supplied function must compute the gradient with respect to
  each parameter.

  If you want to solve a least-squares problem, to perform *curve*
  *fitting*, then you will probably want to use the routines MPFIT,
  MPFITFUN and MPFITEXPR.  Those routines are specifically optimized
  for the least-squares problem.  TNMIN is suitable for cases where a
  single function depends on several (possibly many) parameters and
  it should be minimized.  [ Maximization can also be performed if
  the IDL routine returns the *negative* of the desired function. ]

  TNMIN is similar to MPFIT in that it allows parameters to be fixed,
  simple bounding limits to be placed on parameter values, and
  parameters to be tied to other parameters.  See PARINFO below for
  discussion and examples.

  There are a few simple constraints on the IDL function.  It must
  accept a list of "parameters" (and optionally other data wich aids
  in computing the function), and compute the value of the function
  and its derivatives (see MYFUNCT below).

  TNMIN is based on TN.F by Stephen Nash.

 INPUTS:
   MYFUNCT - a string variable containing the name of the function to
             be minimized.  The IDL routine should return the value
             of the function and its gradients.  It should be
             declared in the following way (or in some equivalent):

             ** MYFUNCT must accept at least one keyword parameter ***
             FUNCTION MYFUNCT, p, dp, X=x, Y=y
              ; Parameter values are passed in "p"
              ; Calculation of the function value
              f = p(0)+2*p(2)-17*p(1)^2
              dp = dblarr(n_elements(p))
              ; Calculation of each gradient component
              dp(0) = 1 & dp(1) = 2 & dp(3) = -34D*p(1)
              ; Return the function value
              return, f
             END
             ** MYFUNCT must accept at least one keyword parameter ***

             The keyword parameters X, Y in the example above are
             suggestive but not required (if for example the function
             depends on X and Y data).  Any parameters can be passed
             to MYFUNCT by using the FUNCTARGS keyword to TNMIN.

             You must compute gradient components analytically (TNMIN
             does not have any provision to perform a numerical
             derivative).  The IDL routine should compute the
             gradient of the function as a one-dimensional array of
             values, one for each of the parameters.  They are passed
             back to TNMIN via "dp" as shown above.
             
             The derivatives with respect to fixed parameters are
             ignored; zero is an appropriate value to insert for
             those derivatives.  

   START_PARAMS - An array of starting values for each of the
                  parameters of the model.

                  This parameter is optional if the PARINFO keyword
                  is used.  See below.  The PARINFO keyword provides
                  a mechanism to fix or constrain individual
                  parameters.  If both START_PARAMS and PARINFO are
                  passed, then the starting *value* is taken from
                  START_PARAMS, but the *constraints* are taken from
                  PARINFO.
 
 INPUT KEYWORD PARAMETERS:

   FUNCTARGS - A structure which contains the parameters to be passed
               to the user-supplied function specified by MYFUNCT via
               the _EXTRA mechanism.  This is the way you can pass
               additional data to your user-supplied function without
               using common blocks.

               Consider the following example:
                if FUNCTARGS = { XVAL:[1.D,2,3], YVAL:[1.D,4,9]}
                then the user supplied function should be declared
                like this:
                FUNCTION MYFUNCT, P, XVAL=x, YVAL=y

               By default, no extra parameters are passed to the
               user-supplied function.

   MAXITER - The maximum number of iterations to perform.  If the
             number is exceeded, then the STATUS value is set to 5
             and MPFIT returns.
             Default: 200 iterations

   XTOL - a nonnegative input variable. Termination occurs when the
          relative error between two consecutive iterates is at most
          XTOL. therefore, XTOL measures the relative error desired
          in the approximate solution.
          Default: 1D-10

   FGUESS - provides the routine a guess to the minimum value.
            Default: 0

   ITERPROC - The name of a procedure to be called upon each NPRINT
              iteration of the MPFIT routine.  It should be declared
              in the following way:

              PRO ITERPROC, MYFUNCT, p, iter, fnorm, FUNCTARGS=fcnargs, $
                PARINFO=parinfo, QUIET=quiet, ...
                ; perform custom iteration update
              END
         
              ITERPROC must either accept all three keyword
              parameters (FUNCTARGS, PARINFO and QUIET), or at least
              accept them via the _EXTRA keyword.
          
              MYFUNCT is the user-supplied function to be minimized,
              P is the current set of model parameters, ITER is the
              iteration number, and FUNCTARGS are the arguments to be
              passed to MYFUNCT.  FNORM is should be the function
              value.  QUIET is set when no textual output should be
              printed.  See below for documentation of PARINFO.

              In implementation, ITERPROC, can perform updates to the
              terminal or graphical user interface, to provide
              feedback while the fit proceeds.  If the fit is to be
              stopped for any reason, then ITERPROC should set the
              system variable !ERR to a negative value.  In
              principle, ITERPROC should probably not modify the
              parameter values, because it may interfere with the
              algorithm's stability.  In practice it is allowed.

              Default: an internal routine is used to print the
                       parameter values.

   NPRINT - The frequency with which ITERPROC is called.  A value of
            1 indicates that ITERPROC is called with every iteration,
            while 2 indicates every other iteration, etc.  
            Default value: 1

   ITERARGS - The keyword arguments to be passed to ITERPROC via the
              _EXTRA mechanism.  This should be a structure, and is
              similar in operation to FUNCTARGS.
              Default: no arguments are passed.

   PARINFO - Provides a mechanism for more sophisticated constraints
             to be placed on parameter values.  When PARINFO is not
             passed, then it is assumed that all parameters are free
             and unconstrained.  In no case are values in PARINFO
             modified during a call to MPFIT.

             PARINFO should be an array of structures, one for each
             parameter.  Each parameter is associated with one
             element of the array, in numerical order.  The structure
             can have the following entries (none are required):

               - VALUE - the starting parameter value (but see
                         START_PARAMS above).

               - FIXED - a boolean value, whether the parameter is to 
                         be held fixed or not.  Fixed parameters are
                         not varied by MPFIT, but are passed on to 
                         MYFUNCT for evaluation.

               - LIMITED - a two-element boolean array.  If the
                 first/second element is set, then the parameter is
                 bounded on the lower/upper side.  A parameter can be
                 bounded on both sides.  Both LIMITED and LIMITS must
                 be given together.

               - LIMITS - a two-element float or double array.  Gives
                 the parameter limits on the lower and upper sides,
                 respectively.  Zero, one or two of these values can
                 be set, depending on the value of LIMITED.  Both 
                 LIMITED and LIMITS must be given together.

               - TIED - a string expression which "ties" the
                 parameter to other free or fixed parameters.  Any
                 expression involving constants and the parameter
                 array P are permitted.  Example: if parameter 2 is
                 always to be twice parameter 1 then use the
                 following: parinfo(2).tied = '2 * P(1)'.  Since they
                 are totally constrained, tied parameters are
                 considered to be fixed; no errors are computed for
                 them.
 
             Other tag values can also be given in the structure, but
             they are ignored.

             Example:
             parinfo = replicate({value:0.D, fixed:0, limited:[0,0], $
                                  limits:[0.D,0]}, 5)
             parinfo(0).fixed = 1
             parinfo(4).limited(0) = 1
             parinfo(4).limits(0)  = 50.D
             parinfo(*).value = [5.7D, 2.2, 500., 1.5, 2000.]

             A total of 5 parameters, with starting values of 5.7,
             2.2, 500, 1.5, and 2000 are given.  The first parameter
             is fixed at a value of 5.7, and the last parameter is
             constrained to be above 50.

             Default value:  all parameters are free and unconstrained.

   QUIET - set this keyword when no textual output should be printed
           by MPFIT

 RETURNS:

   Returns the array of best-fit parameters.

 OUTPUT KEYWORD PARAMETERS:

   NFEV - the number of MYFUNCT function evaluations performed.

   NITER - number of iterations completed.

   ERRMSG - a string error or warning message is returned.

   BESTMIN - the best minimum function value that TNMIN could find.

   STATUS - NOT IMPLEMENTED

 EXAMPLE:

   FUNCTION F, X, DF, _EXTRA=extra  ;; *** MUST ACCEPT KEYWORDS
     F  = (X(0)-1)^2 + (X(1)+7)^2
     DF = [ 2D * (X(0)-1), 2D * (X(1)+7) ] ; Gradient
     RETURN, F
   END

   P = TNMIN('F', [0D, 0D], BESTMIN=F0)
   Minimizes the function F(x0,x1) = (x0-1)^2 + (x1+7)^2.

 REFERENCES:

   TRUNCATED-NEWTON METHOD, TN.F
      Stephen G. Nash, Operations Research and Applied Statistics
      Department

 MODIFICATION HISTORY:
   Derived from TN.F by Stephen Nash with many changes and additions,
      to conform to MPFIT paradigm, 19 Jan 1999, CM

(See /host/bluemoon/usr2/idllib/contrib/markwardt/tnmin.pro)


TVIMAGE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
     TVIMAGE

 PURPOSE:
     This purpose of TVIMAGE is to allow you to display an image
     on the display or in a PostScript file in a particular position.
     The position is specified by means of the POSITION keyword. In
     this respect, TVIMAGE works like other IDL graphics commands.
     Moreover, the TVIMAGE command works identically on the display
     and in a PostScript file. You don't have to worry about how to
     "size" the image in PostScript. The output on your display and
     in the PostScript file will be identical. The major advantage of
     TVIMAGE is that it can be used in a natural way with other IDL
     graphics commands in resizeable IDL graphics windows. TVIMAGE
     is a replacement for TV and assumes the image has been scaled
     correctly when it is passed as an argument.

 AUTHOR:
       FANNING SOFTWARE CONSULTING:
       David Fanning, Ph.D.
       2642 Bradbury Court
       Fort Collins, CO 80521 USA
       Phone: 970-221-0438
       E-mail: davidf@dfanning.com
       Coyote's Guide to IDL Programming: http://www.dfanning.com

 CATEGORY:
     Graphics display.

 CALLING SEQUENCE:

     TVIMAGE, image

 INPUTS:
     image:    A 2D or 3D image array. It should be byte data.

 KEYWORD PARAMETERS:
     _EXTRA:   This keyword picks up any TV keywords you wish to use.

     KEEP_ASPECT_RATIO: Normally, the image will be resized to fit the
               specified position in the window. If you prefer, you can
               force the image to maintain its aspect ratio in the window
               (although not its natural size) by setting this keyword.
               The image width is fitted first. If, after setting the
               image width, the image height is too big for the window,
               then the image height is fitted into the window. The
               appropriate values of the POSITION keyword are honored
               during this fitting process. Once a fit is made, the
               POSITION coordiates are re-calculated to center the image
               in the window. You can recover these new position coordinates
               as the output from the POSITION keyword.

     MINUS_ONE: The value of this keyword is passed along to the CMCONGRID
               command. It prevents CMCONGRID from adding an extra row and
               column to the resulting array.
     HALF_HALF: The value of this keyword is passed along to the
               CMCONGRID command, causing the "extra" row and column to
               be split evenly between both sides.

     POSITION: The location of the image in the output window. This is
               a four-element floating array of normalized coordinates of
               the type given by !P.POSITION or the POSITION keyword to
               other IDL graphics commands. The form is [x0, y0, x1, y1].
               The default is [0.15, 0.15, 0.85, 0.85]. Note that this can
               be an output parameter if the KEEP_ASPECT_RATIO keyword is
               used.

 OUTPUTS:
     None.

 SIDE EFFECTS:
     Unless the KEEP_ASPECT_RATIO keyword is set, the displayed image
     may not have the same aspect ratio as the input data set.

 RESTRICTIONS:
     If the POSITION keyword and the KEEP_ASPECT_RATIO keyword are
     used together, there is an excellent chance the POSITION
     parameters will change. If the POSITION is passed in as a
     variable, the new positions will be returned as an output parameter.

 EXAMPLE:
     To display an image with a contour plot on top of it, type:

        filename = FILEPATH(SUBDIR=['examples','data'], 'worldelv.dat')
        image = BYTARR(360,360)
        OPENR, lun, filename, /GET_LUN
        READU, image
        FREE_LUN, lun

        TVIMAGE, image, POSITION=thisPosition, /KEEP_ASPECT_RATIO
        CONTOUR, image, POSITION=thisPosition, /NOERASE, XSTYLE=1, $
            YSTYLE=1, XRANGE=[0,360], YRANGE=[0,360], NLEVELS=10

 MODIFICATION HISTORY:
      Written by:     David Fanning, 20 NOV 1996.
      Fixed a small bug with the resizing of the image. 17 Feb 1997. DWF.
      Removed BOTTOM and NCOLORS keywords. This reflects my growing belief
         that this program should act more like TV and less like a "color
         aware" application. I leave "color awareness" to the program
         using TVIMAGE. Added 24-bit image capability. 15 April 1997. DWF.
      Fixed a small bug that prevented this program from working in the
          Z-buffer. 17 April 1997. DWF.
      Fixed a subtle bug that caused me to think I was going crazy!
          Lession learned: Be sure you know the *current* graphics
          window! 17 April 1997. DWF.
      Added support for the PRINTER device. 25 June 1997. DWF.
      Extensive modifications. 27 Oct 1997. DWF
          1) Removed PRINTER support, which didn't work as expected.
          2) Modified Keep_Aspect_Ratio code to work with POSITION keyword.
          3) Added check for window-able devices (!D.Flags AND 256).
          4) Modified PostScript color handling.
      Craig Markwart points out that Congrid adds an extra row and column
          onto an array. When viewing small images (e.g., 20x20) this can be
          a problem. Added a Minus_One keyword whose value can be passed
          along to the Congrid keyword of the same name. 28 Oct 1997. DWF

(See /host/bluemoon/usr2/idllib/contrib/markwardt/tvimage.pro)


XWINDOW

[Previous Routine] [List of Routines]
 NAME:
       XWINDOW

 PURPOSE:
       This routine implements a "smart" resizeable graphics window.
       It is used as a wrapper for built-in IDL graphics procedures
       such as SURFACE, CONTOUR, PLOT, SHADE_SURF, etc. In additon,
       it can be used to display any user-written graphics procedure
       so long as that procedure follows three simple rules: (1) It
       does not open it's own graphics windows, (2) It is defined with
       no more than ten positional arguments (an unlimited number
       of keyword arguments are allowed), and (3) It is defined
       with an _EXTRA keyword.

       Keyword arguments permit the window to have its own portion
       of a color table and to be able to change the colors loaded in
       that portion of the color table. Colors are updated
       automatically on both 8-bit and 24-bit color displays. In
       addition, the window colors can "protect" themselves. I mean
       by this that the window can re-load its own colors into the
       color table when the cursor is moved over the window. This
       prevents other applications from changing the colors used to
       display data in this window. (This is an issue mainly in
       IDL 5.x applications where widget applications can run
       concurrently with commands from the IDL command line.)

       Keyword arguments also permit the window to create output
       files of its contents. These files can be color and
       gray-scale PostScript, GIF, TIFF, or JPEG files.

 AUTHOR:
       ************* CM 19 Jan 1999 VERSION **********
       Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
       craigm@lheamail.gsfc.nasa.gov

       Originally by:
       FANNING SOFTWARE CONSULTING
       David Fanning, Ph.D.
       2642 Bradbury Court
       Fort Collins, CO 80521 USA
       Phone: 970-221-0438
       E-mail: davidf@dfanning.com
       Coyote's Guide to IDL Programming: http://www.dfanning.com

 CATEGORY:
       Widgets, Graphics.

 CALLING SEQUENCE:
       XWINDOW, command, P1, P2, ... , keywords=..., ...

 REQUIRED INPUTS:
       COMMAND: The graphics procedure command to be executed. This parameter
       must be a STRING. Examples are 'SURFACE', 'CONTOUR', 'PLOT', etc.

 OPTIONAL INPUTS:
       Pn: A positional parameter appropriate for the graphics command.
           Any number of parameters between 0 and 10 may be given.

 INPUT KEYWORD PARAMETERS:
       CPMENU: Setting this keyword adds a "Color Protection" button to the
       "Controls" menu. Color protection can then be turned ON or OFF for the
       window. Otherwise, the color protection scheme used to open the window
       cannot be changed once the window is open. (See the PROTECT keyword.)
       The default is to have this keyword OFF.

       ERASE: Setting this keyword "erases" the contents of the current
       graphics window before re-executing the graphics command. For example,
       this keyword might need to be set if the graphics "command" is TVSCL.
       The default is to NOT erase the display before reissuing the graphics
       command.

       _EXTRA: This keyword forms an anonymous structure of any unrecognized
       keywords passed to the program. The keywords must be appropriate
       for the graphics command being executed.

       GROUP_LEADER: The group leader for this program. When the group leader
       is destroyed, this program will be destroyed.

       OUTPUT: Set this keyword if you want a "File Output" menu on
       the menu bar. The default is to have this item turned OFF.

       JUST_REGISTER: If this keyword is set, the XWINDOW program is just
       registered with XMANAGER, but XMANAGER doesn't run. This is
       useful, for example, if you want to open an XWINDOW window in
       the widget definition module of another widget program.

       NO_CHANGE_CONFIG: Normally as the XWINDOW graphics window is resized
       the size (or aspect ratio, in the case of PostScript) of the
       hardware configuration dialogs change to reflect the new size of
       the graphics window. This results in file output that resembles
       the current graphics window in size and aspect ratio. If you want
       the file output dialogs to remember their current configuration
       even as the window is resized, set this keyword.

       NOMENU: Setting this keyword results in a graphics window without
       menu items. The default is to have a "Controls" menu item in the
       window menu bar with a "Quit" button. Setting this keyword
       automatically turns of the COLORS, OUTPUT, and CPMENU menu
       choices. (Note that the values specified by the COLORS keyword
       will still be valid for color protection, but no "Change Colors..."
       menu item will appear.)

       PROTECT: If this keyword is set, color protection for the draw
       widget is turned ON. What this means is that the window colors
       (see the XCOLOR keyword) will be restored when the cursor enters
       the draw widget window. This prevents someone at the IDL command
       line in IDL 5.0 from changing the window display colors permanently.

       WTITLE: This is the window title. It is the string "Resizeable
       COMMAND Window (1)" by default, where COMMAND is the input
       parameter. And the number (1 in this case) is the window
       index number of the draw widget.

       WXPOS: This is the initial X offset of the window. Default is to
       position the window in the approximate middle of the display.

       WYPOS: This is the initial Y offset of the window. Default is to
       position the window in the approximate middle of the display.

       WXSIZE: This is the initial X size of the window. Default is 400
       pixels.

       WYSIZE: This is the initial Y size of the window. Default is 400
       pixels.

       XCOLORS: Using this keyword adds a "Change Colors..." button to the
       "Controls" menu. Set this keyword to the number of colors available
       in the window and the starting index of the first color. For example,
       to allow the window access to 100 colors, starting at color index 50
       (i.e., color indices 50 to 149), use XColor=[100, 50]. If you use the
       keyword syntax "/XColor", all the colors available will be used, not just
       one color. If the keyword is set to a scalar value greater than 1, the
       starting color index is set to 0. The default value for this keyword
       is [(!D.N_COLORS < 256), 0]. Note that color "protection" may be
       turned on (via the PROTECT keyword) even if this keyword is NOT used.

 OUTPUT KEYWORD PARAMETERS:
       DRAWID: This keyword returns the draw widget identifier of the draw
       widget created in XWINDOW.

       TOP: This keyword returns the identifier of the top-level base widget
       created by XWINDOW.

       WID: This keyword returns the window index number of the draw widget
       created in XWINDOW.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       If color protection is ON, the window colors are reloaded when the
       cursor enters the XWINDOW graphics windows.

 RESTRICTIONS: This program requires three additional programs from
       the Fanning Software Consulting library: PSWINDOW, PS_FORM (CM
       version; available at
       http://astrog.physics.wisc.edu/~craigm/idl), and XCOLORS. You
       might also want to get the program TVIMAGE if you will be
       displaying images in XWINDOW graphics windows.

       If the "command" program requires keywords that are also keywords
       to XWINDOW, then you must use the keyword twice on the command line.

 EXAMPLE:
       To display a surface in the window, type:

       XWINDOW, 'SURFACE', Dist(20), Charsize=1.5

       To enable the Change Colors and File Output menu items, type:

       XWINDOW, 'SHADE_SURF', Dist(30), /XColors, /Output

 MODIFICATION HISTORY:
       Written by: David Fanning, October 96.
       XSIZE and YSIZE keywords changed to WXSIZE and WYSIZE so as not to
          conflict with these keywords on other programs. 14 April 1997, DWF.
        Updated as non-blocking widget for IDL 5.0. 14 April 1997, DWF.
        Extensively modified to work on either 8-bit or 24-bit displays,
          to enable color protection schemes, to send the contents to a
          number of different output files, and to give the user choices
          about which menu items to enable. 21 April 1997, DWF.
        Renamed COLORS keyword to XCOLORS and fixed a problem cancelling
           out of File Configuration dialogs. 23 April 1997, DWF.
        Modification: Craig Markwardt, 21 October 1997
           Added capability for up to ten positional parameters
        Modification: CM 15 May 1998
           PS_FORM dependencies are not hardcoded now.  Requires
           CM version of PS_FORM function.
        Modification: CM 19 Jan 1999
           Added Parent keyword to widget invocation of PS_FORM, and
           make widgets MODAL-safe.

(See /host/bluemoon/usr2/idllib/contrib/markwardt/xwindow.pro)