array procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:25 2005.


List of Routines


Routine Descriptions

INDX2DIM

[List of Routines]
 NAME:
       INDX2DIM

 PURPOSE:
       Converts one-dimensional indices into multidimensional indices.

 CALLING SEQUENCE:
       Result = INDX2DIM(Array, Index_Array, [, 
       N_DIMENSIONS=variable][, DIMENSIONS=variable] )

 INPUTS:
       ARRAY: a multidimensional array 
       INDEX_ARRAY: array of one-dimensional indices in ARRAY

 OUTPUTS:
       Returns an N_DIMENSIONS by N_elements(index_array) array with
       the multidimensional array indices corresponding to each 
       one-dimensional array index stored in index_array.  If any of
       the input one-dimensional indices are greater than the number
       of total elements in the input array (or less than zero) then
       the multidimensional index returned for each such out-of-range
       index will be a row of -1L.

 OPTIONAL OUTPUTS:
       N_DIMENSIONS = the number of dimensions of ARRAY
       DIMENSIONS = the dimensions of ARRAY; a vector of length N_DIMENSIONS

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       None.

 EXAMPLE:
       Make a 4-D array...
       IDL> x = indgen(2,3,4,5)

       Use WHERE to get the 1-D indices for where array is multiple
       of 25...
       IDL> indx = where(x mod 25 eq 0, nindx)

       Return the multidimensional array indices 
       IDL> dim = indx2dim(x,indx,N_DIMENSIONS=ndim,DIMENSIONS=dims)

       Check the dimensions of the array x...
       IDL> print, dims
                  2           3           4           5

       Check the size of the returned multidimensional array; it should
       be N_DIMENSIONS by N_elements(indx)...
       IDL> help, ndim, nindx, dim
       NDIM            LONG      =            4
       NINDX           LONG      =            5
       DIM             LONG      = Array[4, 5]

       Finally, what are the multidimensional indices...
       IDL> print, dim
                  0           0           0           0
                  1           0           0           1
                  0           1           0           2
                  1           1           0           3
                  0           2           0           4

 NOTES:
       This routine now exists in IDL 6.0 and is named
       ARRAY_INDICES(). However, if you pass in an index that is out
       of bounds, ARRAY_INDICES() crashes and gives a warning.

       The returned array has size N_DIMENSIONS by N_elements(index_array).
       This is because the user will most likely be using a loop to access
       each of the returned multidimensional indices: it is faster to loop
       over the second dimension of the returned 2-D array. E.g., in the
       above example, you would access each of the multidimensional
       indices like this...

       IDL> for i = 0, nindx-1 do print, dim[*,i]

       We are accessing each row, which is faster than accessing each
       column, hence my choice for the orientation of the returned array.

 MODIFICATION HISTORY:
   15 Feb 2004  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/array/indx2dim.pro)


astro procs

astro procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:25 2005.


List of Routines


Routine Descriptions

CHDOPPLER

[Next Routine] [List of Routines]
 NAME: chdoppler
       
 PURPOSE: 
       computes the projected velocity of the telescope wrt 
       four coordinate systems: geo, helio, bary, lsr.
	negative velocities mean approach

       the standard LSR is defined as follows: the sun moves at 20.0 km/s
       toward ra=18.0h, dec=30.0 deg in 1900 epoch coords

 CALLING SEQUENCE:
        result = chdoppler( ra, dec, julday, obspos_deg=obspos_deg, path=path, light=light)

 INPUTS: fully vectorized...
       ra[n] - the source ra in decimal hours, equinox 2000
       dec[n] - the source dec in decimal hours, equinox 2000
	julday[n] - the julian day

 KEYWORDS:
	/obspos_deg: observatory [lat, wlong] in degrees. default is arecibo.
	/path - path for the station file. obspos_deg takes precedence.
       /light - returns the velocity as a fraction of c

 NOTE:
	if path is not specified, default long, lat are arecibo. if
path is specified, it reads long, lat from the file
		path + .station

 OUTPUTS: 
       program returns the velocity in km/s, or as a faction of c if
       the keyword /light is specified. the result is a 4-element
	vector whose elements are [geo, helio, bary, lsr]. quick
	comparison with phil's C doppler routines gives agreement to 
	better than 100 m/s one arbitrary case.

 REVISION HISTORY: carlh 29oct04. 
	from idoppler_ch; changed calculation epoch to 2000
	19nov04: correct bad earth spin calculation
	7 jun 2005: vectorize to make faster for quantity calculations.

(See /dzd2/heiles/idl/gen/astro/chdoppler.pro)


DOPPLER

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

PURPOSE:
	GIVE DOPPLER VELOCITY KM/S WITH RESPECT TO BARYCENTER AND ALSO LSR. 

CALLING SEQUENCE:
	doppler, ra_hrs, dec_deg, equinox, julday, obslongitude, obslatitude, $
	v_barycen, v_lsr

INPUTS:
	RA, DEC ARE OF THE SPECIFIED EQUINOX. UNITS ARE DECIMAL HOURS, DEGREES
	EQUINOX: EQUINOX OF THE RA, DEC, IN YEARS. E.G. 2000.	
	JULDAY: THE JULIAN DAY IN DBL PRECISION, TELLS THE EXACT TIME.
	OBSLONGITUDE, OBSLATITUDE: OBSERVER'S LONGITUDE, LATITUDE IN DEGREES.
		LONGITUDE IS WEST LONG, E.G. CALIFORNIA IS +122.
		IF LATITUDE LT ZERO, IT GIVES VELOCITY OF EARTH'S CENTER.

OUTPUTS:
	V_BARYCEN IS VELOCITY WRT BARYCENTER AND V_LSR IS WRT LSR. 
		NEGATIVE VELOCITIES MEAN APPROACH, OR
		HIGHER FREQUENCIES FROM THE DOPPLER SHIFT

COMMENTS, RESTRICTIONS, ETC:
	THE LSR IS BASED ON THE CLASSIC RADIO ASTRONOMY ONE, 
		20 KM/S TOWARDS (RA,DEC)_1900 = (18:00, 30:00)
	WE NEGLECT THE OBSERVER'S HEIGHT ABOVE SEA LEVEL. THIS ISN'T
		GOOD FOR HIGH PLACES LIKE MAUNA KEA!
	ACCURACY SHOULD BE 1 M/S. BASED ON GSFC BARYVEL.

TO COMPUTE JULDAY, YOU CAN USE JDCNV. EXAMPLE: GMT 5.5 HRS ON 15-FEB-1994,
	JDCNV, 1994, 2, 15, 5.5, JULDAY

(See /dzd2/heiles/idl/gen/astro/doppler.pro)


EQ2AZ

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

 PURPOSE:
       To convert between the HOUR ANGLE-DECLINATION and AZIMUTH-ZENITH 
       ANGLE coordinate systems.

 CALLING SEQUENCE:
       EQ2AZ, ha, dec, az, za, latitude [, /REVERSE]

 INPUTS:
       latitude  - the latitude (a scalar) of the observatory, measured 
                   in decimal degrees

 KEYWORD PARAMETERS:
       /REVERSE : if this keyword is set, the program takes the azimuth 
                  and zenith angle as inputs and returns the hour angle 
                  and the declination.  The default behavior, as the module 
                  name suggests, is to return the azimuth and zenith angle 
                  given the hour angle and declination.

 INPUTS OR OUTPUTS (DEPENDING ON /REVERSE KEYWORD) :
       ha  - hour angle, measured in decimal hours; scalar or array
       dec - declination, measured in decimal degrees; scalar or array
       az  - azimuth, measured in decimal degrees; scalar or array
       za  - zenith angle (the complementary angle to the elevation), 
             measured in decimal degrees; scalar or array

 COMMON BLOCKS:
       None.

 RESTRICTIONS:
       Hour angle must be given in decimal hours.  Declination, azimuth,
       zenith angle, and latitude must be given in decimal degrees.

 EXAMPLE:
       Find the azimuth and zenith angle of Altair [RA (J2000): 19 50 47 
       Dec (J2000): 08 52 06] at LST 19h at Arecibo [LONG: 66 45 10.8
       LAT: 18 21 14.2]

       IDL> eq2az, 19.0-ten(19,50,47), ten(08,52,06), az, za, $
       IDL> ten(18,21,14.2)
       IDL> help, az, za
       AZ              DOUBLE    =        125.90073
       ZA              DOUBLE    =        15.549609

 NOTES:
       Went through pain to assure that if a scalar is input, a scalar 
       is returned, but even more pain to allow multi-dimensional
       arrays to be input (and to make the output have the same 
       dimensions!) Also, if inputs are double precision, the calculations 
       will be done in double precision.  The azimuth is returned in the 
       range 0 -> 360 degrees.

 MODIFICATION HISTORY:
       20 May 2004  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/astro/eq2az.pro)


EQTOAZ -- CONVERT HA, DEC TO AZ, ZA OR VICE VERSA

[Previous Routine] [Next Routine] [List of Routines]
NAME:
eqtoaz -- CONVERT HA, DEC TO AZ, ZA or vice versa
CONVERT HA, DEC TO AZ, ZA IF DIRECTION=+1
CONVERT AZ, ZA TO ZA, DEC IF DIRECTION=-1
HA, DEC ARE IN DECIMAL HRS, DEG
AZ, ZA ARE IN DECIMAL DEG, DEG

IN COMMON ANGLESTUFF, OBSLONG AND OBSLAT ARE ASSUMED TO BE IN DEGREES.

(See /dzd2/heiles/idl/gen/astro/eqtoaz.pro)


LDS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       LDS
     
 PURPOSE:

     
 EXPLANATION:

     
 CALLING SEQUENCE:

     
 INPUTS:

     
 OPTIONAL INPUTS:

     
 OUTPUTS:


 OPTIONAL OUTPUTS:


 KEYWORDS:


 COMMON BLOCKS:


 SIDE EFFECTS:


 RESTRICTIONS:


 PROCEDURES CALLED:
       PLOTSPECTRUM
       ZOOMIN
       AVERAGE
       TZOOMIN
       FITSPEC
       PS_SPEC_EVENT
       PS_SPEC
       SELECT_EVENT
       SELECT

       ROUNDTOHALF
       VTOBIN

       GETMEAN
       CUTOFF
       MODEL
       INDIPLOT
       CLEAR
       FITLDS
       EDGECORRECTION
       GFIT
       GCURV

 EXAMPLE:


 NOTES:


 RELATED PROCEDURES:


 MODIFICATION HISTORY:
       Written Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/astro/lds.pro)


LSRVEL -- GIVE LSR VELOCITY TOWARDS AN RA, DEC

[Previous Routine] [Next Routine] [List of Routines]
NAME:
LSRVEL -- give LSR velocity towards an ra, dec

PURPOSE:
	GIVE THE COMPONENT OF LSR VELOCITY TOWARDS THE GIVEN ELL, BEE
	'LSR' MOVES WITH 20.000 KM/S TOWARDS ra1900, dec1900 = 18.000, 30.000

CALLING SEQUENCE:
	LSRVEL, RA_EPOCH, DEC_EPOCH, EQUINOX, VLSR

INPUTS:
	RA_EPOCH: the R.A. of the position, DECIMAL HOURS.
	DEC_EPOCH, THE DEC IN DECIMAL DEGREES.
	EQUINOX: THE EQUINOX OF THE POSITIONS, E.G. 2000.

OUTPUTS:
	DELVLSR: the velocity in the LSR frame.

HISTORY:
	Written by Carl Heiles. 12 JUN 2000.

IF YOU NEED TO CONVERT FROM GALACTIC TO EQUATORIAL BEFORE ENTERING THIS:
CONVERT INPUT GALACTIC COORDS TO 1900 EPOCH EQUATORIAL COORDS...
	glactc, ra1900, dec1900, 1900.0, ell, bee, 1

(See /dzd2/heiles/idl/gen/astro/lsrvel.pro)


MAKE_LDS_CUBE

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

 PURPOSE:
       To make an (l,b,v) cube of a subset of the Leiden/Dwingeloo Survey 
       of Galactic neutral hydrogen.

 CALLING SEQUENCE:
       make_lds_cube, lcen, bcen, dl, db [, VRANGE=[min,max]] 
                      [, FILENAME=string]

 INPUTS:
       lcen - central Galactic longitude of cube [degrees]
       bcen - central Galactic latitude of cube [degrees]
       dl - the half-width of the cube in the longitude direction[degrees]
       db - the half-width of the cube in the latitude direction [degrees]

 KEYWORD PARAMETERS:
       VRANGE = 2-element vector with minimum and maximum VLSR velocities 
                [km/s] in the cube.  Default is to use entire velocity
                range.
       FILENAME = name of the output FITS file.  Default is to write to a
                  file named lds_cube.fits in the current working directory.

 OUTPUTS:
       None.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       A FITS cube is written.

 PROCEDURES CALLED:
       TABINV, FITS_ADD_AXIS_PAR

 EXAMPLE:
       IDL> make_lds_cube, 90, 0, 30, 10, VRANGE=[-100,100]

 MODIFICATION HISTORY:
       15 Sep 2004  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/astro/make_lds_cube.pro)


MODANGLE360 -- CONVERT ANGLES TO THE INTERVAL 0 TO 360 DEG.

[Previous Routine] [Next Routine] [List of Routines]
NAME:
modangle360 --  CONVERT ANGLES TO THE INTERVAL 0 TO 360 DEG.
 CONVERT ANGLES TO THE INTERVAL 0 TO 360 DEG.
 ALL ANGLES ARE IN DEGREES.
 if negpos is set, interval is -180 to 180

(See /dzd2/heiles/idl/gen/astro/modangle360.pro)


SPHERICAL1_TO_SPHERICAL2

[Previous Routine] [Next Routine] [List of Routines]
NAME
spherical1_to_spherical2 -- CONVERTS LONGITUDE AND LATITUDE between 2 systems

purpose:
CONVERTS LONGITUDE AND LATITUDE IN SYSTEM 1 TO THOSE IN SYSTEM 2
USES THE ROTATION MATRIX RTOT
ALL ANGLES ARE IN ***DEGREES***.
VECTORIZED BUT REUTNRS ALL INPUTS IN 1-D.

(See /dzd2/heiles/idl/gen/astro/spherical1_to_spherical2.pro)


VTOBIN

[Previous Routine] [List of Routines]
 NAME:
   vtobin
     
 PURPOSE:
   Finds the bin number(s) in a velocity vector closest to some v.
     
 CALLING SEQUENCE:
   bin = vtobin(vlsr, v)
     
 INPUTS:
   vlsr : velocity vector
   v    : velocity or velocities whose corresponding bins you want
     
 REVISION HISTORY:
   17-Nov-2000 Written T. Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/astro/vtobin.pro)


color procs

color procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:25 2005.


List of Routines


Routine Descriptions

BGFILL

[Next Routine] [List of Routines]
 NAME:
       BGFILL
     
 PURPOSE:
       Fills the background of a plot window with a specified color.
     
 CALLING SEQUENCE:
       BGFILL, BGCOLOR
     
 INPUTS:
       BGCOLOR - Color table index (8-bit color) or 24-bit color
                 index of the color with which you would like to 
                 fill the background.

 OUTPUTS:
       None.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
        Display device is filled with the input color.

 RESTRICTIONS:
       The /NOERASE keyword MUST be sent to any plotting routine that
       you call after using this routine!
       This causes problems if you are using !p.multi values
       other than zero.  See example below for how to do this.

 EXAMPLE:
       Fill the background with the color in the 0th index of the
       color table, then plot a line:

        IDL> bgfill, 0
        IDL> plot, findgen(30), /NOERASE

       In order to use !p.multi with this method, you must explicitly
       place each plot with a !p.multi assignment (since you must include 
       the /NOERASE keyword when starting a new plot!)  Remember the
       first element of !p.multi is the number of empty sectors remaining
       on the page and the default order of placement (the 5th element of
       !p.multi) is left-right and top-bottom. Here's an example:

        IDL> bgfill, 0
        IDL> !p.multi=[4,2,2]
        IDL> plot, findgen(30), /NOERASE
        IDL> !p.multi=[3,2,2]
        IDL> plot, findgen(30)^2, /NOERASE
        IDL> !p.multi=[2,2,2]
        IDL> plot, findgen(30)^3, /NOERASE

 NOTES:
       Note that in order for this to work, you need to set the
       /NOERASE keyword to any plotting routine you call directly
       after using this routine!

 MODIFICATION HISTORY:
       01 Mar 2002  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/color/bgfill.pro)


COLOR24

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

 PURPOSE:
       Return the 24-bit color index for an RGB triplet.

 CALLING SEQUENCE:
       RESULT = COLOR24(R, G, B)

 INPUTS:
       R - 8-bit red color index.
       G - 8-bit green color index.
       B - 8-bit blue color index.

 KEYWORD PARAMETERS:
       None.

 OUTPUTS:
       RESULT - the 24-bit color index for the RGB triplet.

 COMMON BLOCKS:
       None.

 EXAMPLE:
       Return the 24-bit color index for pure green:

       IDL> print, color24(0,255,0)

 MODIFICATION HISTORY:
   02 Mar 2003  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/color/color24.pro)


CT_FIDDLE -- FIDDLE INDEPENDENTLY R,G,B COLORTABLES IN DIRECT COLOR.

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       ct_fiddle -- fiddle independently r,g,b colortables in direct color.

 PURPOSE:
       To fiddle with the color table.  The user can select which channels 
       of the color table to manipulate.  The user can change the gamma 
       correction and the range of the color table indices.

 CALLING SEQUENCE:
	CT_FIDDLE [, CHANNELS] [, LOW=value] [, HIGH=value] [,
	GAMMA=value] [, GRANGE=[min,max]]

 OPTIONAL INPUTS:
       CHANNELS: A string argument.  CHANNELS sets which color
                 channels ('R' for red, 'G' for green, 'B' for blue) 
                 will be manipulated in the color table.  The user
                 can manipulate one, two or all channels.  To fiddle
                 with the red and blue channels simultaneously,
                 set channels equal to the string 'rb'.

 KEYWORD PARAMETERS:
	LOW = The lowest pixel value to use.  If this parameter is omitted,
	      0 is assumed.  Appropriate values range from 0 to the number 
	      of available colors-1.

	HIGH = The highest pixel value to use.  If this parameter is omitted,
	       the number of colors-1 is assumed.  Appropriate values range 
	       from 0 to the number of available colors-1.

	GAMMA =	Gamma correction factor.  If this value is omitted, 1.0 is 
		assumed.  Gamma correction works by raising the color indices
		to the Gamma power, assuming they are scaled into the range 
		0 to 1.

       GRANGE = The desired range of the gamma axis, a 2-element
                vector.  The first element is the axis minimum, and 
                the second is the maximum. The default is [0.1,10.0].

 OUTPUTS:
       None.

 COMMON BLOCKS:
	COLORS:	The common block that contains R, G, and B color
		tables loaded by LOADCT, HSV, HLS and others.

 SIDE EFFECTS:
	Image display color tables are changed.

 RESTRICTIONS:
       If using TrueColor visual class, color decomposition must be 
       switched off in order for this routine to work.

 EXAMPLE:
       Load the BLUE/GREEN/RED/YELLOW color table and fiddle with 
       the red and blue channels:

       IDL> loadct, 4
       % LOADCT: Loading table BLUE/GREEN/RED/YELLOW
       IDL> ct_fiddle, 'rb'

 MODIFICATION HISTORY:
   08 May 2004  Written by Tim Robishaw, Berkeley
   Heavily modified version of Carl Heiles's DIDDLE.

(See /dzd2/heiles/idl/gen/color/ct_fiddle.pro)


CT_REVERSE

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

 PURPOSE:
	Reverse the image display color tables over a specified range.

 CATEGORY:
	Image processing, point operations.

 CALLING SEQUENCE:
	CT_REVERSE, Low, High [, /OVERWRITE]

 OPTIONAL INPUTS:
	Low:	The lowest pixel value to use.  If this parameter is omitted,
		0 is assumed.  Appropriate values range from 0 to the number 
		of available colors-1.

	High:	The highest pixel value to use.  If this parameter is omitted,
		the number of colors-1 is assumed.  Appropriate values range 
		from 0 to the number of available colors-1.

 KEYWORD PARAMETERS:
       /OVERWRITE: The original color table stored in the "colors"
                   common block is overwritten with the reversed
                   color table.

 OUTPUTS:
	No explicit outputs.

 COMMON BLOCKS:
	COLORS:	The common block that contains R, G, and B color
		tables loaded by LOADCT, HSV, HLS and others.

 SIDE EFFECTS:
	Image display color tables are loaded.

 RESTRICTIONS:
	Common block COLORS must be loaded before calling CT_REVERSE.

 EXAMPLE:
	Load the STD GAMMA-II color table by entering:

		LOADCT, 5

	Create and display an image by entering:

		TVSCL, DIST(300)

       Now reverse the color table:
               CT_REVERSE

       Now reverse just the color table indices between 50 and 100:
               CT_REVERSE, 50, 100

 MODIFICATION HISTORY:
       19 Mar 2004  Written by Tim Robishaw, Berkeley
       Added /OVERWRITE keyword. TR, 07 May 2004

(See /dzd2/heiles/idl/gen/color/ct_reverse.pro)


CT_STRETCH

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

 PURPOSE:
	Stretch the image display color tables so the full range 
	runs from one color index to another.

 CATEGORY:
	Image processing, point operations.

 CALLING SEQUENCE:
	CT_STRETCH, Low, High [, Gamma] [, /CHOP] [, /OVERWRITE]

 INPUTS:
	Low:	The lowest pixel value to use.  If this parameter is omitted,
		0 is assumed.  Appropriate values range from 0 to the number 
		of available colors-1.

	High:	The highest pixel value to use.  If this parameter is omitted,
		the number of colors-1 is assumed.  Appropriate values range 
		from 0 to the number of available colors-1.

 OPTIONAL INPUTS:
	Gamma:	Gamma correction factor.  If this value is omitted, 1.0 is 
		assumed.  Gamma correction works by raising the color indices
		to the Gamma power, assuming they are scaled into the range 
		0 to 1.

 KEYWORD PARAMETERS:
	/CHOP:	If this keyword is set, color values above the upper threshold
		are set to color index 0.  Normally, values above the upper 
		threshold are set to the maximum color index.

       /OVERWRITE: The original color table stored in the "colors"
                   common block is overwritten with the reversed
                   color table.

 OUTPUTS:
	No explicit outputs.

 COMMON BLOCKS:
	COLORS:	The common block that contains R, G, and B color
		tables loaded by LOADCT, HSV, HLS and others.

 SIDE EFFECTS:
	Image display color tables are loaded.

 RESTRICTIONS:
	Common block COLORS must be loaded before calling CT_STRETCH.

 PROCEDURE:
	New R, G, and B vectors are created by linearly interpolating
	the vectors in the common block from Low to High.  Vectors in the 
	common block are not changed.

	If NO parameters are supplied, the original color tables are
	restored.

 EXAMPLE:
	Load the STD GAMMA-II color table by entering:

		LOADCT, 5

	Create and display an image by entering:

		TVSCL, DIST(300)

	Now adjust the color table with CT_STRETCH.  Make the entire 
       color table fit in the range 0 to 70 by entering:

		CT_STRETCH, 0, 70

	Notice that pixel values above 70 are now colored white.
	Restore the original color table by entering:

		CT_STRETCH

       To reverse the color table:
               CT_STRETCH, !D.TABLE_SIZE-1, 0

       To reverse the color table over only the range 50 to 120:
               CT_STRETCH, 120, 50

 NOTES: 
       RSI's STRETCH routine didn't cut the mustard.  (a) If the
       color table hasn't been loaded, it creates a color table with
       maximum values of (!D.TABLE_SIZE-1) rather than 255; (b) it
       uses LONG() to interpolate the color table rather than
       BYTSCL().
 
 MODIFICATION HISTORY:
       19 Mar 2004  Written by Tim Robishaw, Berkeley
	Most of documentation from DMS, RSI.
       Added /OVERWRITE keyword. TR, 07 May 2004

(See /dzd2/heiles/idl/gen/color/ct_stretch.pro)


GETCOLOR -- RETURN THE COLOR TABLE INDEX OF THE COLOR CORRESPONDING TO THE COLOR NAME

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
GETCOLOR -- return the color table index of the color corresponding to the color name 
     
 PURPOSE:
       This function returns the color table index of the color
       corresponding to the color name which is input.  If the
       line plot color names and color table indices are not
       provided, SETCOLORS is called to set up basic line plot
       colors. Designed to work correctly on both X Window and 
       PostScript devices.
     
 CALLING SEQUENCE:
      color = getcolor(colorname, names, tableindx)

      OR

      color = getcolor(colorname[, DECOMPOSED=decomposed]) 
     
 INPUTS:
       COLORNAME: A string whose value is the name of a line plot
                  color.  Must not be an array.
     
 OPTIONAL INPUTS:
       COLORNAMES: An array of strings which correspond to line
                   plot colors that are available to the user.

       TABLEINDICES: An array of the color table indices (8-bit) or 
                     24-bit integers corresponding to the line plot colors.
     
 OUTPUTS:
       Function value returned = color table index of input color name.

 KEYWORDS:
       DECOMPOSED = Set this keyword to explicitly use decomposed color
                    on 24-bit machines. Has no effect on devices which 
                    do not support decomposed color. Set this keyword
                    to 0 to turn off decomposed color on 24-bit
                    devices. If COLORNAMES and TABLEINDICES are set,
                    this keyword has no effect.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       If the line plot color name COLORNAME is not found in the
       list of available line plot colors COLORNAMES, the value of
       the system plot color, !p.color, is returned.  If only
       COLORNAME is input and color decomposition is not on, the line 
       plot colors are added to the top of the current color table.

 RESTRICTIONS:
       Only supported by IDL v5.2 or higher. 

 PROCEDURES CALLED:
       FILE_WHICH
       SETCOLORS

 EXAMPLE:
       Once an array of line plot color names and their corresponding
       color table indices (8-bit) or 24-bit integers have been
       established, use GETCOLOR to obtain one of these values:

       IDL> setcolors, NAMES=cnames, VALUES=cindx
       IDL> plot, findgen(30), color=getcolor('orange',cnames,cindx)

       If no line plot color information exists, call GETCOLOR with
       only a color name and SETCOLORS will be called to establish
       a set of basic colors:

       IDL> plot, findgen(30), color=getcolor('cyan')

       If referencing many colors, this is much slower than the
       the previous example.  However, it's likely that if you're
       plotting something, you're not aiming for speed anyway!

 RELATED PROCEDURES:
       SETCOLORS

 MODIFICATION HISTORY:
   Written Tim Robishaw, Berkeley 13 Aug 2001

(See /dzd2/heiles/idl/gen/color/getcolor.pro)


SETCOLORS

[Previous Routine] [List of Routines]
 NAME: 
       SETCOLORS
     
 PURPOSE: 
       To set up device independent line plot colors. Designed to
       work correctly on both X Window and PostScript devices.
     
 CALLING SEQUENCE:
       SETCOLORS [, NAMES=string array][, VALUES=array][, 
                 NPLOTCOLORS=variable][, TABLESIZE=variable][,
                 DECOMPOSED={0|1}][,/SYSTEM_VARIABLES][,
                 /GETINFO][,/SILENT][,/TEST][,/START][,
                 PLOTCOLORS=string array, R_PLOT=array, G_PLOT=array, 
                 B_PLOT=array][,/PSEUDO256]
     
 INPUTS: 
       None.

 OPTIONAL INPUTS:
       (You can provide your own set of line plot colors, but you
        must provide all four of the following keywords and they
        must all have the same size! (See EXAMPLE.) If omitted,
        a set of 12 basic colors is used.)

       PLOTCOLORS = A string array of user-defined line plot color names.

       R_PLOT = The RED values of line plot colors.

       G_PLOT = The GREEN values of line plot colors.

       B_PLOT = The BLUE values of line plot colors.
     
 OUTPUTS:
       None.

 OPTIONAL OUTPUTS:
       NAMES = Returns a string array of the line plot color names.

       VALUES = Returns an array of the color table indices (8-bit) or 
                24-bit integers corresponding to the line plot colors.

       NPLOTCOLORS = Returns the number of line plot colors defined.

       TABLESIZE = Returns the number of color table indices.

 KEYWORDS:
       DECOMPOSED = Set this keyword to explicitly use decomposed color
                    on 24-bit machines. Has no effect on devices which 
                    do not support decomposed color. Set this keyword
                    to 0 to turn off decomposed color on 24-bit devices.

       /SYSTEM_VARIABLES: Define system variables with the name of each
                          color and the value of the color table index
                          or the 24-bit integer corresponding to each
                          color, i.e. for 24-bit color, !orange=32767L.
                          This is very useful since system variables have
                          global scope, therefore these colors can be
                          used in any procedure once defined.

       /GETINFO: Do not do anything to the color table, just print
                 out IDL color information.

       /SILENT: Do not print out IDL color information. Default is to 
                print info.

       /TEST: Display the entire color table and the names of
              the line plot colors in their respective colors.

       /START: Put the line plot colors at the start of the color 
               table. Default is to store them at the top.

       /NOCOLORS: Do not load line plot colors into color table!
                  Has no effect if color undecomposed.

       /PSEUDO256: Default is to establish PseudoColor visual using
                   only the available color indices when the first
                   window is created.  This keyword forces IDL to
                   use all 256 colors.

 COMMON BLOCKS:
       COLORS: The IDL color common block.

 SIDE EFFECTS:
       The color table may be modified.  If a window is not open, a
       pixmap is created then destroyed to establish the visual class
       and depth.  If the /TEST keyword is set and the device is X
       Windows, a free window is created to display the color table
       and line plot colors.

 RESTRICTIONS:
       Only supported by IDL v5.2 or higher. 

 PROCEDURES CALLED:
       None.

 EXAMPLE:
       To view the color table and line plot names and colors:

       IDL> setcolors, /test


       To define system variables with the names of each color
       and values of the corresponding color table index or 24-bit
       long integer:

       IDL> setcolors, /SYSTEM_VARIABLES


       To use the line plot colors (set DECOMPOSED=1 if 24-bit display):

       IDL> setcolors, NAMES=cnames, VALUES=cindx
       IDL> plot, findgen(30), co=cindx[(where(cnames eq 'yellow'))[0]]
       *OR*
       IDL> plot, findgen(30), co=getcolor('yellow',cnames,cindx)


       If you'd like to display an image but you've added line plot
       colors to the color table, you need to scale the image to
       avoid using the plotcolors:

       IDL> setcolors, NPLOTCOLORS=nplotcolors, TABLESIZE=tablesize
       IDL> tv, bytscl(image, top=tablesize-nplotcolors-1)
       If you load the line plot colors at the start of the color table:

       IDL> setcolors, NPLOTCOLORS=nplotcolors, TABLESIZE=tablesize, /START
       IDL> tv, bytscl(image, top=tablesize-nplotcolors-1)+nplotcolors

       (Do not use TVSCL!  "If color is important to you (and it almost
        always is), then you probably never want to use the TVScl command.
        Instead, you will want to scale your image data yourself, and use
        the TV command to display it." - David W. Fanning)


       To load your own line plot colors:

       IDL> setcolors, PLOTCOLORS=['red','yellow','blue','green'], $
       IDL> R_PLOT=[255,255,0,0], G_PLOT=[0,255,0,255], $
       IDL> B_PLOT=[0,0,255,0], NAMES=cnames, VALUES=cindx

       (Color 'WHITE' will be appended to the top of the color table
        to protect !p.color/!p.background.  If /START is set, color
        'BLACK' is appended to bottom of color table.)


       If you want to make a grayscale image and add colored
       annotation (when color decomposition is off):

       IDL> setcolors, NPLOTCOLORS=nplotcolors, TABLESIZE=tablesize, $
       IDL> NAMES=cnames, VALUES=cindx
       IDL> tv, bytscl(image, top=tablesize-nplotcolors-1)
       IDL> xyouts, 200, 150, 'M31', /dev, $
       IDL> co=cindx[(where(cnames eq 'cyan'))[0]]
       *OR*
       IDL> xyouts, 200, 150, 'M31', /dev, co=getcolor('cyan',cnames,cindx)

       WARNING!  After opening a PostScript file you should run
       SETCOLORS!  If you're using a 24-bit visual device,
       the system variables and color indices will be 24-bit longword
       integers (with values greater than 256) but PostScript is an
       8-bit device with only 256 colors available, so right after opening
       a PostScript file, you should run SETCOLORS to re-establish the
       color system variables color indices. Likewise, when you close
       a PostScript image, you should run SETCOLORS again in order to
       re-establish the colors for X Windows.

 NOTES:
       Once a window is open, the visual class is established for the IDL
       session.  There is no way to change it once it is established.
       However, if no window is open (there's no way to tell if one has
       been opened in the past) we open a pixmap and delete it just to
       establish the visual class and depth.

       I thought at first it would be convenient to store the color table
       indices of each color in a variable named after the corresponding
       color and storing each color variable in a common block.  However, I
       was convinced by two very bright folks that common blocks should be
       avoided, especially for this use.

 RELATED PROCEDURES:
       GETCOLOR

 MODIFICATION HISTORY:
       Written by Tim Robishaw, Berkeley 13 Aug 2001
       Added /NOCOLORS keyword. TR, Berkeley 03 Oct 2001
       Added /SYSTEM_VARIABLES keyword. TR, 07 Feb 2002
       Added /PSEUDO256 keyword. TR, 15 Feb 2002
       Removed IDL's STRETCH. TR, 19 Mar 2004
       Made sue r,g,b_curr get defined. TR, 07 May 2004

(See /dzd2/heiles/idl/gen/color/setcolors.pro)


colortest procs

colortest procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:25 2005.


List of Routines


Routine Descriptions

CT_FIDDLE

[List of Routines]
 NAME:
       ct_fiddle

 PURPOSE:
       To fiddle with the color table.  The user can select which channels 
       of the color table to manipulate.  The user can change the gamma 
       correction and the range of the color table indices.

 CALLING SEQUENCE:
	CT_FIDDLE [, CHANNELS] [, LOW=value] [, HIGH=value] [,
	GAMMA=value] [, GRANGE=[min,max]]

 OPTIONAL INPUTS:
       CHANNELS: A string argument.  CHANNELS sets which color
                 channels ('R' for red, 'G' for green, 'B' for blue) 
                 will be manipulated in the color table.  The user
                 can manipulate one, two or all channels.  To fiddle
                 with the red and blue channels simultaneously,
                 set channels equal to the string 'rb'.

 KEYWORD PARAMETERS:
	LOW = The lowest pixel value to use.  If this parameter is omitted,
	      0 is assumed.  Appropriate values range from 0 to the number 
	      of available colors-1.

	HIGH = The highest pixel value to use.  If this parameter is omitted,
	       the number of colors-1 is assumed.  Appropriate values range 
	       from 0 to the number of available colors-1.

	GAMMA =	Gamma correction factor.  If this value is omitted, 1.0 is 
		assumed.  Gamma correction works by raising the color indices
		to the Gamma power, assuming they are scaled into the range 
		0 to 1.

       GRANGE = The desired range of the gamma axis, a 2-element
                vector.  The first element is the axis minimum, and 
                the second is the maximum. The default is [0.1,10.0].

 OUTPUTS:
       None.

 COMMON BLOCKS:
	COLORS:	The common block that contains R, G, and B color
		tables loaded by LOADCT, HSV, HLS and others.

 SIDE EFFECTS:
	Image display color tables are changed.

 RESTRICTIONS:
       If using TrueColor visual class, color decomposition must be 
       switched off in order for this routine to work.

 EXAMPLE:
       Load the BLUE/GREEN/RED/YELLOW color table and fiddle with 
       the red and blue channels:

       IDL> loadct, 4
       % LOADCT: Loading table BLUE/GREEN/RED/YELLOW
       IDL> ct_fiddle, 'rb'

 MODIFICATION HISTORY:
   08 May 2004  Written by Tim Robishaw, Berkeley
   Heavily modified version of Carl Heiles's DIDDLE.

(See /dzd2/heiles/idl/gen/colortest/ct_fiddle.pro)


display procs

display procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:25 2005.


List of Routines


Routine Descriptions

CBLINK -- BLINK BETWEEN A SET OF WINDOWS WITH OPTION TO SAVE ONE.

[List of Routines]
 NAME:
CBLINK -- blink between a set of windows with option to save one.
 PURPOSE:
	To allow the user to alternatively examine two or more windows within
	a single window.
 CALLING SEQUENCE:
	BLINK, Wndw [, T]
 INPUTS:
	Wndw  A vector containing the indices of the windows to blink.
	T     The time to wait, in seconds, between blinks.  This is optional
	      and set to 1 if not present.  
 OUTPUTS:
	None.
 PROCEDURE:
	The images contained in the windows given are written to a pixmap.
	The contents of the the windows are copied to a display window, in 
	order, until a key is struck.
 EXAMPLE:
       Blink windows 0 and 2 with a wait time of 3 seconds

         IDL> blink, [0,2], 3 
 MODIFICATION HISTORY:
	Written by Michael R. Greason, STX, 2 May 1990.
       Allow different size windows   Wayne Landsman    August, 1991
	Retain the blink window Carl Heiles 2 nov 98

(See /dzd2/heiles/idl/gen/display/cblink.pro)


fits procs

fits procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:25 2005.


List of Routines


Routine Descriptions

FITS_ADD_AXIS_PAR

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

 PURPOSE:
       Add to FITS header the FITS parameters necessary to
       specify a coordinate axis.

 CALLING SEQUENCE:
       FITS_ADD_AXIS_PAR, axis, hdr, axisnum

 INPUTS:
       AXIS - vector containing values of coordinate axis.
       HDR - FITS header.
       AXISNUM - The number of the coordinate axis.

 KEYWORD PARAMETERS:
       CTYPE - name of the coordinate axis, a character string.
       CUNIT - name of units of coordinate, a character string.
       AXIS_PAR - Set this keyword to a variable in order to
                  return the AXIS_PAR stucture:
                  .NAXIS - size of the axis
                  .CDELT - coordinate increment along axis
                  .CRPIX - coordinate system reference pixel
                  .CRVAL - coordinate system value at reference pixel
                  .CTYPE - name of the coordinate axis

 OUTPUTS:
       None.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       The coordinate axis header keywords are added or changed in 
       the FITS header.

 PROCEDURES CALLED:
       FITS_GET_AXIS_PAR(), SXPAR(), SXADDPAR

 EXAMPLE:
       Create a header for a data cube...
       IDL> cube = bytarr(512,12,36)
       IDL> mkhdr, hdr, cube

       Now make coordinate axes for the cube...
       IDL> axis1 = findgen(512)*0.33 - 100
       IDL> axis2 = findgen(12)
       IDL> axis3 = findgen(36)*0.5 + 50

       Add the NAXISn, CRVALn, CRPIXn and CRDELTn header
       keywords to HDR...
       IDL> fits_add_axis_par, axis1, hdr, 1
       IDL> fits_add_axis_par, axis2, hdr, 2
       IDL> fits_add_axis_par, axis3, hdr, 3

       Also add the CTYPEn and CUNITn keywords...
       IDL> fits_add_axis_par, axis1, hdr, 1, $
       IDL> CTYPE='Right Ascension (B1950)', CUNIT='deg'

 RELATED PROCEDURES:
       FITS_MAKE_AXIS()

 MODIFICATION HISTORY:
   20 Aug 2003  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/fits/fits_add_axis_par.pro)


FITS_GET_AXIS_PAR

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

 PURPOSE:
       Return, in structure form, the FITS parameters necessary to
       specify a coordinate axis.

 CALLING SEQUENCE:
       Result = FITS_GET_AXIS_PAR(axis)

 INPUTS:
       AXIS - vector containing values of coordinate axis.

 OUTPUTS:
       Returns the AXIS_PAR structure:
       AXIS_PAR.NAXIS - size of the axis
               .CDELT - coordinate increment along axis
               .CRPIX - coordinate system reference pixel
               .CRVAL - coordinate system value at reference pixel
               .CTYPE - name of the coordinate axis

 COMMON BLOCKS:
       None.

 EXAMPLE:
       AXIS is vector containing the values of an axis...
       IDL> axis_par = fits_get_axis_par(axis)
       IDL> help, axis_par, /structure
       ** Structure <39fc40>, 4 tags, length=16, refs=1:
       NAXIS           LONG              2048
       CDELT           FLOAT           1.00000
       CRPIX           FLOAT           1025.00
       CRVAL           FLOAT           1024.00

 RELATED PROCEDURES:
       FITS_ADD_AXIS_PAR, FITS_MAKE_AXIS()

 MODIFICATION HISTORY:
   20 Aug 2003  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/fits/fits_get_axis_par.pro)


FITS_MAKE_AXIS -- CREATE AXIS VALUES FROM A FITS HEADER

[Previous Routine] [List of Routines]
 NAME:
FITS_MAKE_AXIS -- create axis values from a FITS header

 PURPOSE:
       To create the axis values from the NAXISn, CDELTn, CRPIXn, and
       CRVALn keyword values stored in a FITS header.

 CALLING SEQUENCE:
       Result = FITS_MAKE_AXIS(hdr, axisnum)

 INPUTS:
       HDR - FITS header (string array)
       AXISNUM - The number of the axis to be created.

 KEYWORD PARAMETERS:
       None.

 OUTPUTS:
       Returns a vector of length NAXISn containing the axis values.

 COMMON BLOCKS:
       None.

 PROCEDURES CALLED:
       SXPAR()

 EXAMPLE:
       Get the header from a FITS file...
       IDL> hdr = headfits('datacube.fits')

       Make the 1st and 2nd axes...
       IDL> xaxis = fits_make_axis(hdr,1)
       IDL> yaxis = fits_make_axis(hdr,2)

 RELATED PROCEDURES:
       FITS_ADD_AXIS_PAR

 MODIFICATION HISTORY:
   20 Aug 2003  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/fits/fits_make_axis.pro)


fitting procs

fitting procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:25 2005.


List of Routines


Routine Descriptions

GET_XLEG -- TRANSFORM XIN TO OPTIMUM RANGE FOR LEGENDRE FITTING

[Next Routine] [List of Routines]
NAME:
GET_XLEG -- transform xin to optimum range for legendre fitting

SEE DOC IN LEGENDREFIT OR LEGENDREFIT_SVD. REPEAT THOSE IMPORTANT NOTES:
       (1) GODDARD'S FLEGENDRE IS MUCH FASTER THAN IDL'S LEGENDRE!
       (2) TO EVALUATE: YFIT= POLYLEG( XDATA, COEFFS)
       (3) PAY ATTENTION TO DOUBLE PRECISION FOR HARD PROBLEMS!!!
       (4) THE XDATA MUST LIE BETWEEN 0 AND 1. WHAT'S MORE...
       (5) IF POINTS ARE UNIFORMLY SPACED, TO OBTAIN MAX ORTHOGONALITY:
               (A) YOU HAVE nrt POINTS
               (B) THESE nrt POINTS SPAN A TOTAL RANGE range
               (C) THEN THE INTERVAL BETWEEN POINTS IS delta= range/(nrt-1)
               (D) MAKE THE INPUT X VALUES BE...

                       XLEG = (2*findgen(nrt) - (nrt-1))/nrt

                   which corresponds to half a bin away from the (-1,1) ends.
                   suppose the original nrt uniformly-spaced values have values f=frt.
                   then an alternative set of equation (good for arbitrary f) is

                       frtspan= max( frt)- min( frt)
                       dfrtspan= frtspan/( nrt-1)
                       sfrtspan= max( frt)+ min( frt)
                       XLEG = (2.*frt - sfrtspan)/(frtspan+ dfrtspan)
       OR              XLEG = (2.*f - sfrtspan)/(frtspan+ dfrtspan)

HERE, SETTING QUICK USES EQN (1) ABOVE; OTHERWISE THE SET (2) IS USED.
	USING (1) IMPLIES XIN IS UNIFORMLY SPACED, WITH QUICK=NR OF POINTS.

CALLING SEQUANCE:
	RESULT= GET_XLEG( XIN, XMIN, XMAX, DELX, [QUICK=NPTS]

INPUTS:
	XIN, the x values for which transformed valuse of XLEG are desired
	XMIN, the minimum value of X for the transformation
	XMAX, the maximum value of X for the transformation
	DELX, the interval between x values for uniformly spaced array

OPTIONAL INPUT:
	QUICK. YOU CAN SET THIS EUAL TO NR OF POINTS FOR A UNIFORMLY 
SPACED ARRAY AND NOT USE THE OTHER STANDARD INPUTS.

OUTPUT:
	XLEG, the transformed values of the inputs.  For a uniformly
spaced array containing NRT elements, the values of XLEG lie between
[-(nrt-1)/nrt] and [+(nrt-1)/nrt]

EXAMPLE:

	you have NRT=512 uniformly spaced values of frequency (FRT) and
you want to do a legendre-nomial fit.  transform the original values to
the proper range (XLEG)

		xleg= get_xleg( quick=512)

altenatively, use 
		frtmin= min(frt)
		frtmax= frt(max)
		delfrt= (frtmax- frtmin)/( nrt-1)
		xleg= get_xleg( frt, frtmin, frtmax, delfrt)

then do the fit (you should use legendrefit_svd for hard problems)...

	legendrefit, xlegfit[indxwb_incl], spwb_c[ indxwb_incl], degree, $
        coeffs, sigcoeffs, yfit, residbad= 4., problem=problem

	after doing the fit you want to apply these coefficients to an
arbiTrary set of frequencies (FRA). 

		xra= get_xleg( fra, frtmin, frtmax, delfrt)
		xrafit = polyleg( xra, coeffs)

(See /dzd2/heiles/idl/gen/fitting/get_xleg.pro)


LEGENDREFIT -- LEGENDRE FIT USING STANDARD LEAST SQUARES

[Previous Routine] [Next Routine] [List of Routines]
NAME:
LEGENDREFIT -- legendre fit using standard least squares

IMPORTANT NOTES: 
	(1) GODDARD'S FLEGENDRE IS MUCH FASTER THAN IDL'S LEGENDRE!
	(2) TO EVALUATE: YFIT= POLYLEG( XDATA, COEFFS)
       (3) PAY ATTENTION TO DOUBLE PRECISION FOR HARD PROBLEMS!!!
       (4) THE XDATA MUST LIE BETWEEN 0 AND 1. WHAT'S MORE...
       (5) IF POINTS ARE UNIFORMLY SPACED, TO OBTAIN MAX ORTHOGONALITY:
               (A) YOU HAVE nrt POINTS
               (B) THESE nrt POINTS SPAN A TOTAL RANGE range
               (C) THEN THE INTERVAL BETWEEN POINTS IS delta= range/(nrt-1)
               (D) MAKE THE INPUT X VALUES BE...

                       X = (2*findgen(nrt) - (nrt-1))/nrt

                   which corresponds to half a bin away from the (-1,1) ends.
                   suppose the original nrt uniformly-spaced values have values f=frt.
                   then an alternative set of equation (good for arbitrary f) is

                       frtspan= max( frt)- min( frt)
                       dfrtspan= frtspan/( nrt-1)
                       sfrtspan= max( frt)+ min( frt)
                       x = (2.*frt - sfrtspan)/(frtspan+ dfrtspan)
       OR              x = (2.*f - sfrtspan)/(frtspan+ dfrtspan)

TIME:
       (1) LEGENDRE FIT IS ABOUT 20% SLOWER THAN POLYNOMIAL FIT.
       (2) FOR BOTH, SVD VERSION IS ABOUT 3 TIMES SLOWER THAN ORDINARY VERSION.

PURPOSE:
    like a polynomial fit but uses legendre functions, which are 
orthogonal over the interval (-1,1). the input data must be 
within this range.

CALLING SEQUENCE:
    LEGENDREFIT, xdata, ydata, degree, coeffs, sigcoeffs, yfit, $
	sigma, nr3bad, cov

INPUTS:
     xdata: the x-axis data points. 
     ydata: the y-axis data points.
     degree: the degree of the legendre fit. e.g. linear fit has degree=1.
KEYWORDS:
     residbad: if set, excludes points those residuals exceed residbad*sigma
	goodindx: the array of indices actually used in the fit.
	problem: nonzero if there was a problem with the fit.
OUTPUTS:
     coeffs: array of coefficients.
     sigcoeffs: me's of the coefficients.
     yfit: the fitted points evaluated at datax.
     sigma: the sigma (mean error) of the data points.
     nr3sig: the nr of datapoints lying more than 3 sigma away from the fit.
     ncov: the normalized covariance matrix.
     cov: the covariance matrix.

HISTORY;

(See /dzd2/heiles/idl/gen/fitting/legendrefit.pro)


LEGENDREFIT_SVD -- LEGENDRE FIT USING STANDARD LEAST SQUARES

[Previous Routine] [Next Routine] [List of Routines]
NAME:
LEGENDREFIT_SVD -- legendre fit using standard least squares

IMPORTANT NOTES:
       (1) GODDARD'S FLEGENDRE IS MUCH FASTER THAN IDL'S LEGENDRE!
       (2) TO EVALUATE: YFIT= POLYLEG( XDATA, COEFFS)
	(3) PAY ATTENTION TO DOUBLE PRECISION FOR HARD PROBLEMS!!!
	(4) THE XDATA MUST LIE BETWEEN 0 AND 1. WHAT'S MORE...
	(5) IF POINTS ARE UNIFORMLY SPACED, TO OBTAIN MAX ORTHOGONALITY:
		(A) YOU HAVE nrt POINTS
		(B) THESE nrt POINTS SPAN A TOTAL RANGE range
		(C) THEN THE INTERVAL BETWEEN POINTS IS delta= range/(nrt-1)
		(D) MAKE THE INPUT X VALUES BE...

			X = (2*findgen(nrt) - (nrt-1))/nrt

		    which corresponds to half a bin away from the (-1,1) ends.
		    suppose the original nrt uniformly-spaced values have values f=frt.
		    then an alternative set of equation (good for arbitrary f) is

			frtspan= max( frt)- min( frt)
			dfrtspan= frtspan/( nrt-1)
			sfrtspan= max( frt)+ min( frt)
			x = (2.*frt - sfrtspan)/(frtspan+ dfrtspan)
	OR		x = (2.*f - sfrtspan)/(frtspan+ dfrtspan)

TIME: 
	(1) LEGENDRE FIT IS ABOUT 20% SLOWER THAN POLYNOMIAL FIT.
	(2) FOR BOTH, SVD VERSION IS ABOUT 3 TIMES SLOWER THAN ORDINARY VERSION.

PURPOSE:
    like a SVD polynomial fit but uses legendre functions, which are 
orthogonal over the interval (-1,1). the input data must be 
within this range.

CALLING SEQUENCE:
    LEGENDREYFIT_SVD, xdata, ydata, degree, coeffs, sigcoeffs, yfit, $
	sigma, nr3bad, cov

INPUTS:
     xdata: the x-axis data points. 
     ydata: the y-axis data points.
     degree: the degree of the legendre fit. e.g. linear fit has degree=1.
KEYWORDS:
     residbad: if set, excludes points those residuals exceed residbad*sigma
	goodindx: the array of indices actually used in the fit.
	problem: nonzero if there was a problem with the fit.
OUTPUTS:
     coeffs: array of coefficients.
     sigcoeffs: me's of the coefficients.
     yfit: the fitted points evaluated at datax.
     sigma: the sigma (mean error) of the data points.
     nr3sig: the nr of datapoints lying more than 3 sigma away from the fit.
     ncov: the normalized covariance matrix.
     cov: the covariance matrix.

HISTORY;

(See /dzd2/heiles/idl/gen/fitting/legendrefit_svd.pro)


LSFIT_SVD -- DO LSFIT USING SVD INSTEAD OF INVERSE NORMAL EQUATIONS.

[Previous Routine] [Next Routine] [List of Routines]
NAME:
LSFIT_SVD -- do lsfit using SVD instead of inverse normal equations.

	The equations of condition are

	X a = y

where X is a the equation-of-conditon matrix, A is the vector of unknowns,
and y are the measured values.

	This returns the solution vector x, its variances and sigmas,
and the normalizedd covariance matrix. These are the standard ls fit things.
It also returns the vector of SVD weights and the V matrix (see NM section
2.6 ('SVD of a Square Matrix') and chapter 15 (least squares solution by SVD).

CALLING SEQUENCE:
lsfit_svd, X, y, U, V, $
	wgt, a, vara, siga, ncov, s_sq, $
	xxinv_svd=xxinv_svd, wgt_inv=wgt_inv, ybar=ybar, cov=cov

INPUTS:
	X, the equation-of-conditon matrix
	y, the vector of measured values
	U, NM's matrix U (input only if WGT_INV is used; see discussion below)
	V, NM's matrix V (input only if WGT_INV is used; see discussion below)

OUTPUTS:
	U, NM's U matrix. also an input; see discussion below
	V, NM's V matrix, the matrix whose columns are the 
orthonormal eigenvectors. also an input; see discussion below
	WGT, the vector of weights of V (see discussion below)
	A, the vector of unknowns
	vara, a vector containing the variance of a
	siga, a vector containing the sigma of a (sqrt variance)
	ncov, the normalized covariance matrix
	s_sq, the variance of the datapoints

KEYWORDS:
	WGT_INV, the vector of reciprocal weights (equal to 1/WGT unless you
change them yourself). If WGT_INV is specified, then the procedure assumes
that  you have already run it once, examined the weight vector WGT and
found a problem, and specified the new vector of WGT_INV=1/WGT. It uses this
modified WGT_INV and it uses the values of U and V given as inputs
(because they have already been computed). If WGT_INV is not specified, it
evaluates U and V and returns them as outputs.
See COMMENTARIES below.

	XXINV_SVD, the effective inverse of X obtained using WGT_INV. 
If WGT_INV is left unmodified, XXINV_SVD is the inverse of X. But the
whole point of SVD is to modify WGT_INV by setting certain elements to 
zero so a to eliminate an effectively degenerate inverse of X. 
See COMMENTARIES below.

	COV, the usual covariance matrix

	YBAR, the fitted values of the datapoints

IMPORTANT COMMENTARIES REGARDING USE OF SVD!!!
	Read NM's discussion of WGT. Each element of WGT refers to the 
corresponding column of V; consider each column of V to be an eigenvector
in the space defined by the X matrix. 
If a particular value of WGT is small, then the projection of the
corresponding eigenvector in V is small. 

	As discussed in NM, you should then rerun the solution with the 
corresponding elements of WGT_INV set equal to 1/WGT, except for the problem 
value which should be set equal to zero (yes, if a particular element of
WGT is small the corresponding WGT_INV element is large; you set it equal to
zero to remove it from the solution).

HISTORY: written by carl heiles while flying back from Arecibo in july 2004.
mistakes in covariance matrix and associated parameter errors 27 feb 05.
	29jun05: replace SVDC (which doesn't always converge) 
with LA_SVD (needs idl 5.6)
	23aug05: use !version to choose svd routine. warn if svdc.

(See /dzd2/heiles/idl/gen/fitting/lsfit_svd.pro)


LS_XY_3 -- FITS MULTIVARIATE SLOPES PLUS CONSTANT

[Previous Routine] [Next Routine] [List of Routines]
NAME: 
LS_XY_3 -- FITS MULTIVARIATE SLOPES PLUS CONSTANT

PURPOSE: FITS MULTIVARIATE SLOPES PLUS CONSTANT, E.G.
	ZZ = A0*U + A1*V + a2*W +...

assumes U, V, W... are the independent variables (or functions of 
independent variables)


************************* CAVAET ******************************
tests by my ay250 class in 2005 indicate that the variances of 
derived parameters may not be correct. however, there appears to
be no bias in the derived parameters.
****************************************************************

INPUTS:
	XXIN, the X matrix of the independent variables, of the form...
		 _                  _
		| u_0   v_0   w_0  ... |
		| u_1   v_1   w_1  ... |
		| u_2   v_2   w_2  ... |
		| ...   ...   ...  ... |
		|_                    _|

	SIGMAXX, the intrinsic sigmas (uncertainties) of the U, V values, 
	in which ONE of the independent variables can have nonzero errors.
	This makes SIGMAXX to be of the form...

		 _                       _
		| sig(u_0)    0    0  ... |
		| sig(u_0)    0    0  ... |
		| sig(u_0)    0    0  ... |
		|  ...       ...  ... ... |
		|_                       _|

	ZZIN, a 'horizontal' vector of the ZZ measurements
	SIGMAZZ, the intrinsic measurement errors (sigmas) of the ZZ values.

KEYWORDS:
	TOLERANCE, the maximum change in any derived parameter. 
	default is 1e-3
OUTPUTS:
	A_LS, the vector of results for the 'conventional' ls fit 
		(the one that assumes no errors in U,  V...
	ATRY, the vector of results for the ls fit
	CHISQ, the chisq of the fit
	CHISQ_REDUCED, the reduced chisq of the fit
	SIGSQA, the sigma-squared of ATRY
	ZZBAR, the predicted z-values from the derived ls parameters

COMMENTS, RESTRICTIONS: See lsfit2005 writeup. max nr iterations is
nr_iterate_max, currently set for max of 100.

chisq definition is questionable (divided by
	number of variables).

	I'm not sure about the exact value of chisq...seems to be off 
	(too small) by a little bit.

HISTORY: 10 June 2002 by Carl Heiles
updated mar2004...extraneous stuff removed and documentation firmed up.
	tested only one a single independent variable.
updated feb2005...more testing, realized errors can exist only for one
	independent variable. For more generasl solns see Jefferys AJ 85, 177.

(See /dzd2/heiles/idl/gen/fitting/ls_xy_3.pro)


POLYFIT -- POLYNOMIAL FIT USING STANDARD LEAST SQUARES

[Previous Routine] [Next Routine] [List of Routines]
NAME:
POLYFIT -- polynomial fit using standard least squares

PURPOSE:
    Polynomial fits, like IDL's POLY_FIT, but returns sigmas of
	the coefficients, the fitted line, and the normalized covariance
	matrix also.

CALLING SEQUENCE:
    POLYFIT, xdata, ydata, degree, coeffs, sigcoeffs, yfit, sigma, nr3bad, cov

INPUTS:
     xdata: the x-axis data points. 
     ydata: the y-axis data points.
     degree: the degree of the polynomial. e.g. linear fit has degree=1.
KEYWORDS:
     residbad: if set, excludes points those residuals exceed residbad*sigma
	goodindx: the array of indices actually used in the fit.
	problem: nonzero if there was a problem with the fit.
OUTPUTS:
     coeffs: array of coefficients.
     sigcoeffs: me's of the coefficients.
     yfit: the fitted points evaluated at datax.
     sigma: the sigma (mean error) of the data points.
     nr3sig: the nr of datapoints lying more than 3 sigma away from the fit.
     ncov: the normalized covariance matrix.
     cov: the covariance matrix.

HISTORY;
	30 sep i tested to see if la_invert is better than invert.
there is no essential diff, so we stick with invert.

(See /dzd2/heiles/idl/gen/fitting/polyfit.pro)


POLYFIT_MEDIAN -- PERFORM A LEAST-ABS-DEV (MEDIAN) POLYNOMIAL FIT

[Previous Routine] [Next Routine] [List of Routines]
NAME:
   POLYFIT_MEDIAN -- perform a least-abs-dev (median) polynomial fit

PURPOSE:
    Polynomial MEDIAN fits.

CALLING SEQUENCE:
    POLYFIT_MEDIAN, xdata, ydata, degree, $
	coeffs, sigcoeffs, yfit, sigma, ncov

INPUTS:
     XDATA: the x-axis data points. 
     YDATA: the y-axis data points.
     DEGREE: the degree of the polynomial. e.g. linear fit has degree=1.

OUTPUTS:
     COEFFS: array of coefficients.
     SIGCOEFFS: me's of the coefficients. SEE NOTE BELOW
     YFIT: the fitted points evaluated at datax.
     SIGMA: the sigma (mean error) of the data points. SEE NOTE BELOW
     NCOV: the normalized covariance matrix.

NOTE ON SIGMA AND SIGCOEFFS:
	SIGMA and SIGCOEFFS are calculated as if we were doing a least
squares fit.  this is appropriate for Gaussian statistics, but not for
others, so this is relatively meaningless. For example, a single large
discrepant point will contribute a lot to sigma, and to sigcoeffs, but
because this is a median fit it is ignored.

(See /dzd2/heiles/idl/gen/fitting/polyfit_median.pro)


POLYFIT_SVD -- POLYNOMIAL FIT USING SVD.

[Previous Routine] [Next Routine] [List of Routines]
NAME:
   POLYFIT_SVD -- polynomial fit  using SVD.

PURPOSE:
    Polynomial fits USING SVD. like IDL's POLY_FIT and my POLYFIT, 
	but uses SVD. POLYFIT is less accurrate thaN POLY_FIT, which
	in turn is less accurate than POLYFIT_SVD. Returns sigmas of
	the coefficients, the fitted line, and the normalized covariance
	matrix also.

TIME: SVD VERSION IS ABOUT 3 TIMES SLOWER THAN ORDINARY VERSION.

   Has an option to exclude points whose residuals exceed RESIDBAD.

CALLING SEQUENCE:
    POLYFIT_SVD, xdata, ydata, degree, $
	coeffs, sigcoeffs, yfit, sigma, nr3bad, ncov, cov, 
	[residbad], [goodindx], [problem], $
	wgts=wgts, u=u, wgt_inv=wgt_inv, v=v, auto=auto
INPUTS:
     XDATA: the x-axis data points. 
     YDATA: the y-axis data points.
     DEGREE: the degree of the polynomial. e.g. linear fit has degree=1.
KEYWORDS:
     RESIDBAD: if set, excludes points those residuals exceed residbad*sigma
	GOODINDX, the indices of the points included in the fit
       PROBLEM: nonzero if a problem. -2 means too many points discarded
	WGTS, the svd weights.
	WGT_INV: you can modify these to eliminate degeneracies; see
documentation for LSFIT_SVD 
	U, the returned U matrix from LSIT_SVD
	V, the returned V matrix from LSIT_SVD
	AUTO: if nonzero, does the WGT_INV business automatically, zeroing the
inverse weights when the ratio is smaller than AUTO. if AUTO is set equal
to >= one, it defaults to 1e-12

OUTPUTS:
     COEFFS: array of coefficients.
     SIGCOEFFS: me's of the coefficients.
     YFIT: the fitted points evaluated at datax.
     SIGMA: the sigma (mean error) of the data points.
     NR3SIG: the nr of datapoints lying more than 3 sigma away from the fit.
     NCOV: the normalized covariance matrix.
     COV: the covariance matrix.

HOW TO USE YOUR OWN WGT_INV: (it's easier to use AUTO keyword!)

	first invoke this procedure. it returns the native WGTS and
WGT_INV, and also the U and V as optional outputs. 
	then modify WGT_INV and call this proc again using the 
modified WGT_INV, U and V as optional inputs

suppose WGTS spans a huge range, say 10^20. do something like...
	indx= where( wgts/max( wgts) lt 1e-12)
	wgt_inv= 1./wgts
	wgt_inv[ indx]= 0.
and then call this proc again, specifying U, V, and WGT_INV as optional inputs.

(See /dzd2/heiles/idl/gen/fitting/polyfit_svd.pro)


POLYFIT_WGT -- POLYNOMIAL FITS OF WEIGHTED DATAPOINTS

[Previous Routine] [Next Routine] [List of Routines]
NAME:
POLYFIT_WGT -- polynomial fits of weighted datapoints

PURPOSE:
    Polynomial fits, like IDL's POLY_FIT, but allows weighting the input eq's of cond.
	returns sigmas of
	the coefficients, the fitted line, and the normalized covariance
	matrix also.

CALLING SEQUENCE:
    POLYFIT_WGT, xdata, ydata, wgts, degree, coeffs, sigcoeffs, yfit, sigma, nr3bad, cov

INPUTS:
     xdata: the x-axis data points. 
     ydata: the y-axis data points.
	wgts, the weighting factors applied to eqns of cond. these get squared
		then the normal equations are calculated.
     degree: the degree of the polynomial. e.g. linear fit has degree=1.
KEYWORDS:
     residbad: if set, excludes points those residuals exceed residbad*sigma
	goodindx: the array of indices actually used in the fit.
	problem: nonzero if there was a problem with the fit.
OUTPUTS:
     coeffs: array of coefficients.
     sigcoeffs: me's of the coefficients.
     yfit: the fitted points evaluated at datax.
     sigma: the sigma (mean error) of the data points.
     nr3sig: the nr of datapoints lying more than 3 sigma away from the fit.
     ncov: the normalized covariance matrix.
     cov: the covariance matrix.

IMPORTANT COMMENT: i have not checked whether the returned errors are right, nor whether it 
behaves properly when eliminating bad points.

(See /dzd2/heiles/idl/gen/fitting/polyfit_wgt.pro)


POLY_COS_CALC

[Previous Routine] [Next Routine] [List of Routines]
PURPOSE: calculate the fits generated ty poly_cos_fit_svd for any set of frequencies.
INPUTS:
	POLYCOEFFS, the array of polynomial coefficients
	TIMES, the times at which the fourier coeffs coscoeffs are evaluated
	coscoeffs, the array of fourier coefficients
	FRQS, the freq arraay for which  you want result;

RETURNS: the calculated fitted spectrum.

OUTPUTS:
	res_poly, the polynomial portion of the fit
	res_cos, the fourier portion of the fit
	cospower, the fourier power versus time

(See /dzd2/heiles/idl/gen/fitting/poly_cos_calc.pro)


POLY_COS_FIT_SVD

[Previous Routine] [Next Routine] [List of Routines]
POLY_FT_FIT -- fit polynomial plus cosine terms to a spectrum.

CALLING SEQUENCE: 
POLY_FT_FIT, frqin, ydata, degree, times, $
	coeffs, sigcoeffs, yfit, sigma, nr3bad, ncov, cov, $
	residbad=residbad, goodindx=goodindx, problem=problem, $
        polycoeffs=polycoeffs, coscoeffs=coscoeffs, cospower=cospower, $
	yfit_poly= yfit_poly, yfit_cos=yfit_cos

INPUTS:
	FRQIN, the array of input freqs for the spectrum
	YDATA, the array of spectral points
	DEGREE, the degree of the polynomial to fit
	TIMES, the times for whichi the fourier components are fitted

OUTPUTS:
	COEFFS, the array of fitted coefficients. the first (degree+1)
coefficients are for the polynomial; the remaining ones are for the
cosines, the numbver of which is equal to the nr of elements in times. 
	SIGCOEFFS, sigmas of coeffs
	YFIT, the fitted datapoints
	SIGMA, the sigma of the fitted points
	NR3BAD, the nr of bad points on the last iteration. should be zero.
	NCOV, the normalized covariance matrix
	COV, the covariance matrix

OPTIONALS:
	RESIDBAD: toss out points that depart by more that this times sigma.
e.g., if residbad is 3, it eliminates points haveing resids gt 3 sigma
	GOODINDX, the indx of good points (the points that it actually 
included in the fit)
	PROBLEM, nonzero if there is a problem
	POLYCOEFFS, the set of coeffs in the polynomial fit
	COSCOEFFS, the set of coeffs for the cosines
	SIGCOSCOEFFS, sigmas of coscoeffs
	COSPOWER, the power in each cosine component (square of coefficient)
	SIGCOSPOWER, the power in each cosine component (square of coefficient)
	YFIT_POLY, THE fitted polynomial curve
	YFIT_COS, THE fitted cosine curve
	ITMAX, the max nr of iterations in svdc.
	NOTE: yfit= yfit_poly+ yfit_cosine

EXAMPLE OF USE:
	you've got a lousy ripple in the spectrum. the ripple is represented
by yfit_cos. ydata-yfit_cos is the ripple-free spectrum.

HISTORY: carl h, 11june2005, adapted from poly_ft_fit_svd

(See /dzd2/heiles/idl/gen/fitting/poly_cos_fit_svd.pro)


POLY_FT_CALC

[Previous Routine] [Next Routine] [List of Routines]
PURPOSE: calculate the fits generated ty poly_ft_fit_svd for any set of frequencies.
INPUTS:
	POLYCOEFFS, the array of polynomial coefficients
	TIMES, the times at which the fourier coeffs FCOEFFS are evaluated
	FCOEFFS, the array of fourier coefficients
	FRQS, the freq arraay for which  you want result;

RETURNS: the calculated fitted spectrum.

OUTPUTS:
	res_poly, the polynomial portion of the fit
	res_f, the fourier portion of the fit
	fpower, the fourier power versus time

(See /dzd2/heiles/idl/gen/fitting/poly_ft_calc.pro)


POLY_FT_EVAL

[Previous Routine] [Next Routine] [List of Routines]
POLY_FT_EVAL -- using results from poly_ft_fit, calculate the fitted spectrum 

CALLING SEQUENCE: 
poly_ft_eval, frqin, degree, times, coeffs, sigcoeffs, $
	yeval, yeval_poly, yeval_fourier

INPUTS:
	FRQIN, the array of input freqs at which to evaluate the spectrum
	DEGREE, the degree of the polynomial to fit
	COEFFS, the set of coeffs from the original fit
	TIMES, the times for whichi the fourier components are fitted

OUTPUTS:
	YEVAL, the evaluated points
	YEVAL_POLY, the contribution to YEVAL from the polynomial part
	YEVAL_FOURIER, the contribution to YEVAL from the fourier part

HISTORY: carl h, 02sep2005

(See /dzd2/heiles/idl/gen/fitting/poly_ft_eval.pro)


POLY_FT_FIT_SVD

[Previous Routine] [List of Routines]
POLY_FT_FIT -- fit polynomial plus fourier terms to a spectrum.

CALLING SEQUENCE: 
POLY_FT_FIT, frqin, ydata, degree, times, $
	coeffs, sigcoeffs, yfit, sigma, nr3bad, ncov, cov, $
	residbad=residbad, goodindx=goodindx, problem=problem, $
        polycoeffs=polycoeffs, fcoeffs=fcoeffs, fpower=fpower, $
	yfit_poly= yfit_poly, yfit_fourier=yfit_fourier

INPUTS:
	FRQIN, the array of input freqs for the spectrum
	YDATA, the array of spectral points
	DEGREE, the degree of the polynomial to fit
	TIMES, the times for whichi the fourier components are fitted

OUTPUTS:
	COEFFS, the array of fitted coefficients. the first (degree+1)
coefficients are for the polynomial; the remaining ones are paired,
the number of pairs is equal to the nr of elements in times. the first
member of each pair is the cosine term, the second the sine.
	YFIT, the fitted datapoints
	SIGMA, the sigma of the fitted points
	NR3BAD, the nr of bad points on the last iteration. should be zero.
	NCOV, the normalized covariance matrix
	COV, the covariance matrix

OPTIONALS:
	RESIDBAD: toss out points that depart by more that this times sigma.
e.g., if residbad is 3, it eliminates points haveing resids gt 3 sigma
	GOODINDX, the indx of good points (the points that it actually 
included in the fit)
	PROBLEM, nonzero if there is a problem
	POLYCOEFFS, the set of coeffs in the polynomial fit
	FCOEFFS, the set of coeffs that are fourier pairs
	FPOWER, the power in each fourier component (quad sum of cos and sin)
	YFIT_POLY, THE fitted polynomial curve
	YFIT_FOURIER, THE fitted fourier curve
	ITMAX, the max nr of iterations in svdc.
	NOTE: yfit= yfit_poly_ yfit_fourier

EXAMPLE OF USE:
	you've got a lousy ripple in the spectrum. the ripple is represented
by yfit_fourier. ydata-yfit_fourier is the ripple-free spectrum.

HISTORY: carl h, 24june2005

(See /dzd2/heiles/idl/gen/fitting/poly_ft_fit_svd.pro)


gaussians procs

gaussians procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

GCURV -- CALCULATE MULTIPLE (N) GAUSSIANS + OFFSET.

[Next Routine] [List of Routines]
NAME:
GCURV --  Calculate multiple (N) Gaussians + offset.

PURPOSE:
    Calculate multiple (N) Gaussians + offset.

CALLING SEQUENCE:
    GCURV, xdata, zro1, hgt1, cen1, wid1, tfit

INPUTS:
     xdata: the x-values at which the data points exist.
     zro1: the estimated constant zero offset of the data points.
     hgt1: the array of N estimated heights of the Gaussians.
     cen1: the array of N estimated centers of the Gaussians.
     wid1: the array of N estimated halfwidths of the Gaussians.

OUTPUTS:
     tfit: the calculated points.

EXAMPLE:
    You have two Gaussians.
     The heights are hgt1=[1.5, 2.5], the centers cen1=[12., 20.],
     and the widths are wid1=[5., 6.]. There are  
     100 values of x (xdata). 

	GCURV, xdata, zro1, hgt1, cen1, wid1, tfit

RELATED PROCEDURES:
	GFIT 
HISTORY:
	Written by Carl Heiles. 21 Mar 1998.

(See /dzd2/heiles/idl/gen/gaussians/gcurv.pro)


GCURV2D

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

PURPOSE:
    Calculate multiple (N) Gaussians + offset.

CALLING SEQUENCE:
    GCURV2D, xdata, ydata, zro1, hgt1, cenx1, ceny1, wid1, tfit

INPUTS:
     xdata: the x-values at which the data points exist.
     ydata: the y-values at which the data points exist.
     zro1: the estimated constant zero offset of the data points.
     hgt1: the array of N estimated heights of the Gaussians.
     cenx1: the array of N estimated x-centers of the Gaussians.
     ceny1: the array of N estimated y-centers of the Gaussians.
     wid1: the array of N estimated halfwidths of the Gaussians.

OUTPUTS:
     tfit: the calculated points.

EXAMPLE:
    You have two Gaussians.
     The heights are hgt1=[1.5, 2.5], the centers cen1=[12., 20.],
     and the widths are wid1=[5., 6.]. There are  
     100 values of x (xdata). 

	GCURV, xdata, zro1, hgt1, cen1, wid1, tfit

RELATED PROCEDURES:
	GFIT2D 
HISTORY:
	GCURV Written by Carl Heiles. 21 Mar 1998.
       Upgraded to 2D by Paul Demorest 6 jan 2003

(See /dzd2/heiles/idl/gen/gaussians/gcurv2d.pro)


GCURVSLOPE -- CALCULATE MULTIPLE (N) GAUSSIANS + OFFSET + SLOPE

[Previous Routine] [Next Routine] [List of Routines]
NAME:
GCURVSLOPE --  Calculate multiple (N) Gaussians + offset + SLOPE

PURPOSE:
    Calculate multiple (N) Gaussians + offset + SLOPE

CALLING SEQUENCE:
    GCURV, xdata, zro1, slp1, hgt1, cen1, wid1, tfit

INPUTS:
     xdata: the x-values at which the data points exist.
     zro1: the zero offset of the data points.
     slp1: the slope.
     hgt1: the array of N estimated heights of the Gaussians.
     cen1: the array of N estimated centers of the Gaussians.
     wid1: the array of N estimated halfwidths of the Gaussians.

OUTPUTS:
     tfit: the calculated points.

EXAMPLE:
    You have two Gaussians.
     The heights are hgt1=[1.5, 2.5], the centers cen1=[12., 20.],
     and the widths are wid1=[5., 6.]. There are  
     100 values of x (xdata). 

	GCURV, xdata, zro1, slp1, hgt1, cen1, wid1, tfit

RELATED PROCEDURES:
	GFITSLOPE
HISTORY:
	Written by Carl Heiles. 21 Mar 1998.

(See /dzd2/heiles/idl/gen/gaussians/gcurvslope.pro)


GFIT -- FIT MULTIPLE (N) GAUSSIANS + AN OFFSET TO A ONE-D ARRAY OF DATA POINTS

[Previous Routine] [Next Routine] [List of Routines]
NAME:
GFIT --  Fit multiple (N) Gaussians + an offset to a one-d array of data points

PURPOSE:
    Fit multiple (N) Gaussians to a one-d array of data points

CALLING SEQUENCE:
    GFIT, look, xdata, tdata, zro0, hgt0, cen0, wid0, tfit, sigma,
         zro1, hgt1, cen1, wid1, sigzro1, sighgt1, sigcen1, sigwid1, 
	  problem, cov

INPUTS:
     look: if >=0, plots the iteratited values for the Gaussian
     whose number is equal to look. Then it prompts you to plot 
     a different Gaussian number.

     xdata: the x-values at which the data points exist.
     tdata: the data points.

     zro0: the estimated constant zero offset of the data points.
     hgt0: the array of N estimated heights of the Gaussians.
     cen0: the array of N estimated centers of the Gaussians.
     wid0: the array of N estimated halfwidths of the Gaussians.

OUTPUTS:
     tfit: the fitted values of the data at the points in xdata.
     sigma: the rms of the residuals.
     zro1: the fitted zero offset.
     hgt1: the array of N fitted heights. 
     cen1: the array of N fitted centers.
     wid1: the array of N fitted half-power widths.
     sigzro1: the 'error of the mean' of the fitted zero offset.
     sighgt1: the array of errors of the N fitted heights.
     sigcen1: the array of errors of the N fitted centers.
     sigwid1: the array of errors of the N fitted widths.
     problem: 0, OK; -1, excessive width; -2, >50 loops; -3, negative sigmas,
; 4, bad derived values.
     cov: the normalized covariance matrix of the fitted coefficients.

RESTRICTIONS:
    The data and x values NO LONGER NEED be in asympototic x order, 
    either increasing or decreasing.
    Gaussians are not an orthogonal set of functions! 
    This doesn't matter for many cases; convergence is unique UNLESS...
    Convergence is NOT unique when Gaussians are close together or when
    multiple Gaussians lie within a single peak. In these cases, you
    can get different outputs from different inputs.
    And sometimes in these cases the fits will not converge!

    This procedure uses the classical nonlinear least squares technique,
    which utilizes analytically-calculated derivatives, to iteratively
    solve for the least squares coefficients. Some criteria on the
    parameters used to update the iterated coefficients are used to
    make the fit more stable (and more time-consuming). The number
    of iterations is limited to 50; if you need more, enter the routing
    again, using the output parameters as input for the next attampt.

EXAMPLE:
    You have two Gaussians that are well-separated. This counts as an
    easy case; for the estimated parameters, you need not be accurate
    at all. The heights are hgt0=[1.5, 2.5], the centers cen0=[12., 20.],
    and the widths are [5., 6.]. There are 100 data points (tdata) at 
     100 values of x (xdata). You don't wish to see plots of the iterations,
     you don't care about the uncertainties, but you want the fitted
     points and also the rms of the residuals.

	gfit, look, xdata, tdata, zro0, hgt0, cen0, wid0, tfit, sigma

    If you have two Gaussians that are mixed, you must be careful in
    your estimates!

RELATED PROCEDURES:
	GCURV
HISTORY:
	Written by Carl Heiles. 21 Mar 1998.
	Modified 16 jul 98, with 'problems' enhancement.
	Modified 7 apr 2002, restriction on asymptotic x removed.

(See /dzd2/heiles/idl/gen/gaussians/gfit.pro)


GFIT2D

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

PURPOSE:
    Fit multiple (N) Gaussians to a 2-d array of data points

CALLING SEQUENCE:
    GFIT2D, look, xdata, ydata, tdata, zro0, hgt0, cenx0, ceny0, wid0, 
         tfit, sigma,
         zro1, hgt1, cenx1, ceny1, wid1, 
         sigzro1, sighgt1, sigcenx1,sigceny1, sigwid1, 
	  problem, cov

INPUTS:
     look: if >=0, plots the iteratited values for the Gaussian
     whose number is equal to look. Then it prompts you to plot 
     a different Gaussian number.

     xdata: the x-values at which the data points exist.
     ydata: the y-values at which the data points exist.
     tdata: the data points.

     zro0: the estimated constant zero offset of the data points.
     hgt0: the array of N estimated heights of the Gaussians.
     cenx0: the array of N estimated x-centers of the Gaussians.
     ceny0: the array of N estimated y-centers of the Gaussians.
     wid0: the array of N estimated halfwidths of the Gaussians.

OUTPUTS:
     tfit: the fitted values of the data at the points in xdata.
     sigma: the rms of the residuals.
     zro1: the fitted zero offset.
     hgt1: the array of N fitted heights. 
     cenx1: the array of N fitted x-centers.
     ceny1: the array of N fitted y-centers.
     wid1: the array of N fitted half-power widths.
     sigzro1: the 'error of the mean' of the fitted zero offset.
     sighgt1: the array of errors of the N fitted heights.
     sigcenx1: the array of errors of the N fitted x-centers.
     sigceny1: the array of errors of the N fitted y-centers.
     sigwid1: the array of errors of the N fitted widths.
     problem: 0, OK; -1, excessive width; -2, >50 loops; -3, negative sigmas,
; 4, bad derived values.
     cov: the normalized covariance matrix of the fitted coefficients.

RESTRICTIONS:
    The data and x values NO LONGER NEED be in asympototic x order, 
    either increasing or decreasing.
    Gaussians are not an orthogonal set of functions! 
    This doesn't matter for many cases; convergence is unique UNLESS...
    Convergence is NOT unique when Gaussians are close together or when
    multiple Gaussians lie within a single peak. In these cases, you
    can get different outputs from different inputs.
    And sometimes in these cases the fits will not converge!

    This procedure uses the classical nonlinear least squares technique,
    which utilizes analytically-calculated derivatives, to iteratively
    solve for the least squares coefficients. Some criteria on the
    parameters used to update the iterated coefficients are used to
    make the fit more stable (and more time-consuming). The number
    of iterations is limited to 50; if you need more, enter the routing
    again, using the output parameters as input for the next attampt.

EXAMPLE:
    You have two Gaussians that are well-separated. This counts as an
    easy case; for the estimated parameters, you need not be accurate
    at all. The heights are hgt0=[1.5, 2.5], the centers cen0=[12., 20.],
    and the widths are [5., 6.]. There are 100 data points (tdata) at 
     100 values of x (xdata). You don't wish to see plots of the iterations,
     you don't care about the uncertainties, but you want the fitted
     points and also the rms of the residuals.

	gfit, look, xdata, tdata, zro0, hgt0, cen0, wid0, tfit, sigma

    If you have two Gaussians that are mixed, you must be careful in
    your estimates!

RELATED PROCEDURES:
	GCURV2D
HISTORY:
	GFIT Written by Carl Heiles. 21 Mar 1998.
	Modified 16 jul 98, with 'problems' enhancement.
	Modified 7 apr 2002, restriction on asymptotic x removed.
       Upgraded to 2D by Paul Demorest 6 jan 2003.

(See /dzd2/heiles/idl/gen/gaussians/gfit2d.pro)


GFITCFIX

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

PURPOSE:
    Fit multiple (N) Gaussians to a one-d array of data points; 
    THIS VERSION KEEPS THE CENTER FIXED but **DOES** FIT THE ZERO OFFSET.

CALLING SEQUENCE:
    GFITCFIX, look, xdata, tdata, zro0, hgt0, cen0, wid0, tfit, sigma,
         zro1, hgt1, cen1, wid1, sigzro1, sighgt1, sigcen1, sigwid1, cov

INPUTS:
     look: if >=0, plots the iteratited values for the Gaussian
     whose number is equal to look. Then it prompts you to plot 
     a different Gaussian number.

     xdata: the x-values at which the data points exist.
     tdata: the data points.

     zro0: the estimated zero offset of the data points.
     hgt0: the array of N estimated heights of the Gaussians.
     cen0: the array of N estimated centers of the Gaussians.
     wid0: the array of N estimated halfwidths of the Gaussians.

OUTPUTS:
     tfit: the fitted values of the data at the points in xdata.
     sigma: the rms of the residuals.
     zro1: the fitted zero offset.
     hgt1: the array of N fitted heights. 
     cen1: the array of N fitted centers.
     wid1: the array of N fitted half-power widths.
     sigzro1: the error in the fitted zero offset.
     sighgt1: the array of errors of the N fitted heights.
     sigcen1: the array of errors of the N fitted centers.
     sigwid1: the array of errors of the N fitted widths.
     cov: the normalized covariance matrix of the fitted coefficients.

RESTRICTIONS:
    The data and x values should be in asympototic x order, 
    either increasing or decreasing.
    Gaussians are not an orthogonal set of functions! 
    This doesn't matter for many cases; convergence is unique UNLESS...
    Convergence is NOT unique when Gaussians are close together or when
    multiple Gaussians lie within a single peak. In these cases, you
    can get different outputs from different inputs.
    And sometimes in these cases the fits will not converge!

    This procedure uses the classical nonlinear least squares technique,
    which utilizes analytically-calculated derivatives, to iteratively
    solve for the least squares coefficients. Some criteria on the
    parameters used to update the iterated coefficients are used to
    make the fit more stable (and more time-consuming). The number
    of iterations is limited to 50; if you need more, enter the routing
    again, using the output parameters as input for the next attampt.

EXAMPLE:
    You have two Gaussians that are well-separated. This counts as an
    easy case; for the estimated parameters, you need not be accurate
    at all. The heights are hgt0=[1.5, 2.5], the centers cen0=[12., 20.],
    and the widths are [5., 6.]. There are 100 data points (tdata) at 
     100 values of x (xdata). You don't wish to see plots of the iterations,
     you don't care about the uncertainties, but you want the fitted
     points and also the rms of the residuals.

	gfit, look, xdata, tdata, zro0, hgt0, cen0, wid0, tfit, sigma
    If you have two Gaussians that are mixed, you must be careful in
    your estimates!

RELATED PROCEDURES:
	GCURV
HISTORY:
	Written by Carl Heiles. 21 Mar 1998.

(See /dzd2/heiles/idl/gen/gaussians/gfitcfix.pro)


GFITCWFIX

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

PURPOSE:
    Fit multiple (N) Gaussians to a one-d array of data points; 
    THIS VERSION KEEPS THE CENTER AND THE WIDTH FIXED.

CALLING SEQUENCE:
    GFITCWFIX, look, xdata, tdata, zro0, hgt0, cen0, wid0, tfit, sigma,
         zro1, hgt1, cen1, wid1, sigzro1, sighgt1, sigcen1, sigwid1, cov

INPUTS:
     look: if >=0, plots the iteratited values for the Gaussian
     whose number is equal to look. Then it prompts you to plot 
     a different Gaussian number.

     xdata: the x-values at which the data points exist.
     tdata: the data points.

     zro0: the estimated zero offset of the data points.
     hgt0: the array of N estimated heights of the Gaussians.
     cen0: the array of N estimated centers of the Gaussians.
     wid0: the array of N estimated halfwidths of the Gaussians.
     BECAUSE THIS IS NOT A NONLINEAR FIT, THE NUMERICAL VALUES OF THE
	ABOVE DON'T MATTER AT ALL...

OUTPUTS:
     tfit: the fitted values of the data at the points in xdata.
     sigma: the rms of the residuals.
     zro1: the fitted zero offset.
     hgt1: the array of N fitted heights. 
     cen1: the array of centers--equal to cen0.
     wid1: the array of widths--equal to wid0.
     sigzro1: the error in the fitted zero offset.
     sighgt1: the array of errors of the N fitted heights.
     sigcen1: meaningless--equal to 0.
     sigwid1: meaningless--equal to 0.
     cov: the normalized covariance matrix of the fitted coefficients.

RESTRICTIONS:
    none--this is not a nonlinear fit, so no iterations are required.

EXAMPLE:
    You have two Gaussians whose centers, widths are known.
	you think that The heights are hgt0=[1.5, 2.5], 
	the centers cen0=[12., 20.],
    and the widths are [5., 6.]. There are 100 data points (tdata) at 
     100 values of x (xdata). 

	gfitcwfix, look, xdata, tdata, zro0, hgt0, cen0, wid0, tfit, sigma
    If you have two Gaussians that are mixed, you must be careful in
    your estimates!

RELATED PROCEDURES:
	GCURV
HISTORY:
	Written by Carl Heiles. 21 Mar 1998.

(See /dzd2/heiles/idl/gen/gaussians/gfitcwfix.pro)


GFITCWZFIX

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

PURPOSE:
    Fit multiple (N) Gaussians to a one-d array of data points; 
    THIS VERSION KEEPS THE CENTER, WIDTH, and ZERO POINT FIXED.

CALLING SEQUENCE:
    GFITCWZFIX, look, xdata, tdata, zro0, hgt0, cen0, wid0, tfit, sigma,
         zro1, hgt1, cen1, wid1, sigzro1, sighgt1, sigcen1, sigwid1, cov

INPUTS:
     look: if >=0, plots the iteratited values for the Gaussian
     whose number is equal to look. Then it prompts you to plot 
     a different Gaussian number.

     xdata: the x-values at which the data points exist.
     tdata: the data points.

     zro0: the zero offset of the data points.
     hgt0: the array of N estimated heights of the Gaussians.
     cen0: the array of N estimated centers of the Gaussians.
     wid0: the array of N estimated halfwidths of the Gaussians.
     BECAUSE THIS IS NOT A NONLINEAR FIT, THE NUMERICAL VALUES OF THE
	ABOVE DON'T MATTER AT ALL...

OUTPUTS:
     tfit: the fitted values of the data at the points in xdata.
     sigma: the rms of the residuals.
     zro1: the zero offset, equal to zro0.
     hgt1: the array of N fitted heights. 
     cen1: the array of centers--equal to cen0.
     wid1: the array of widths--equal to wid0.
     sigzro1: meaningless--equal to 0.
     sighgt1: the array of errors of the N fitted heights.
     sigcen1: meaningless--equal to 0.
     sigwid1: meaningless--equal to 0.
     cov: the normalized covariance matrix of the fitted coefficients.

RESTRICTIONS:
    none--this is not a nonlinear fit, so no iterations are required.

EXAMPLE:
    You have two Gaussians whose centers, widths are known.
	you think that The heights are hgt0=[1.5, 2.5], 
	the centers cen0=[12., 20.],
    and the widths are [5., 6.]. There are 100 data points (tdata) at 
     100 values of x (xdata). 

	gfitcwfix, look, xdata, tdata, zro0, hgt0, cen0, wid0, tfit, sigma
    If you have two Gaussians that are mixed, you must be careful in
    your estimates!

RELATED PROCEDURES:
	GCURV
HISTORY:
	Written by Carl Heiles. 21 Mar 1998.

(See /dzd2/heiles/idl/gen/gaussians/gfitcwzfix.pro)


GFITCZFIX

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

PURPOSE:
    Fit multiple (N) Gaussians to a one-d array of data points; 
    THIS VERSION KEEPS THE CENTER FIXED AND ALSO THE ZERO OFFSET FIXED.

CALLING SEQUENCE:
    GFITCZFIX, look, xdata, tdata, zro0, hgt0, cen0, wid0, tfit, sigma,
         zro1, hgt1, cen1, wid1, sigzro1, sighgt1, sigcen1, sigwid1, cov

INPUTS:
     look: if >=0, plots the iteratited values for the Gaussian
     whose number is equal to look. Then it prompts you to plot 
     a different Gaussian number.

     xdata: the x-values at which the data points exist.
     tdata: the data points.

     zro0: the  zero offset of the data points.
     hgt0: the array of N estimated heights of the Gaussians.
     cen0: the array of N estimated centers of the Gaussians.
     wid0: the array of N estimated halfwidths of the Gaussians.

OUTPUTS:
     tfit: the fitted values of the data at the points in xdata.
     sigma: the rms of the residuals.
     zro1: equal to zro0, the inputted zero offset.
     hgt1: the array of N fitted heights. 
     cen1: the array of N fitted centers.
     wid1: the array of N fitted half-power widths.
     sigzro1: meaningless. Set equal to zero.
     sighgt1: the array of errors of the N fitted heights.
     sigcen1: the array of errors of the N fitted centers.
     sigwid1: the array of errors of the N fitted widths.
     cov: the normalized covariance matrix of the fitted coefficients.

RESTRICTIONS:
    The data and x values should be in asympototic x order, 
    either increasing or decreasing.
    Gaussians are not an orthogonal set of functions! 
    This doesn't matter for many cases; convergence is unique UNLESS...
    Convergence is NOT unique when Gaussians are close together or when
    multiple Gaussians lie within a single peak. In these cases, you
    can get different outputs from different inputs.
    And sometimes in these cases the fits will not converge!

    This procedure uses the classical nonlinear least squares technique,
    which utilizes analytically-calculated derivatives, to iteratively
    solve for the least squares coefficients. Some criteria on the
    parameters used to update the iterated coefficients are used to
    make the fit more stable (and more time-consuming). The number
    of iterations is limited to 50; if you need more, enter the routing
    again, using the output parameters as input for the next attampt.

EXAMPLE:
    You have two Gaussians that are well-separated. This counts as an
    easy case; for the estimated parameters, you need not be accurate
    at all. The heights are hgt0=[1.5, 2.5], the centers cen0=[12., 20.],
    and the widths are [5., 6.]. There are 100 data points (tdata) at 
     100 values of x (xdata). You don't wish to see plots of the iterations,
     you don't care about the uncertainties, but you want the fitted
     points and also the rms of the residuals.

	gfit, look, xdata, tdata, zro0, hgt0, cen0, wid0, tfit, sigma
    If you have two Gaussians that are mixed, you must be careful in
    your estimates!

RELATED PROCEDURES:
	GCURV
HISTORY:
	Written by Carl Heiles. 21 Mar 1998.

(See /dzd2/heiles/idl/gen/gaussians/gfitczfix.pro)


GFITFLEX -- FIT N GAUSSIANS KEEPING ANY ARRBITRARY SET OF PARAMETERS FIXED

[Previous Routine] [Next Routine] [List of Routines]
NAME:
GFITFLEX -- fit N gaussians keeping any arrbitrary set of parameters fixed

PURPOSE:
    Fit multiple (N) Gaussians to a one-d array of data points, 
	keeping any arbitrary set of parameters fixed and not included
	in the fit.

CALLING SEQUENCE:
    GFITFLEX, look, xdata, tdata, zro0, hgt0, cen0, wid0, $
	zro0yn, hgt0yn, cen0yn, wid0yn, $
	tfit, sigma, zro1, hgt1, cen1, wid1, $
	sigzro1, sighgt1, sigcen1, sigwid1, cov

INPUTS:
     look: if >=0, plots the iteratited values for the Gaussian
     whose number is equal to look. Then it prompts you to plot 
     a different Gaussian number.

     xdata: the x-values at which the data points exist.
     tdata: the data points.
     xrange: 2n-element vector: 2 values for each of n index ranges
	specifying which indices of tdata to include in the fit.

     zro0: the estimated constant zero offset of the data points.
     hgt0: the array of N estimated heights of the Gaussians.
     cen0: the array of N estimated centers of the Gaussians.
     wid0: the array of N estimated halfwidths of the Gaussians.

     zr0yn: if 0, does not fit zero level; if 1, it does.
     hgt0yn: array of N 0 or 1; 0 does not fit the hgt, 1 does.
     cen0yn: array of N 0 or 1; 0 does not fit the hgt, 1 does.
     wid0yn: array of N 0 or 1; 0 does not fit the hgt, 1 does.

OUTPUTS:
     tfit: the fitted values of the data at the points in xdata.
     sigma: the rms of the residuals.
     zro1: the fitted zero offset (held constant if zro0yn=0).
     hgt1: the array of N fitted heights. 
     cen1: the array of N fitted centers.
     wid1: the array of N fitted half-power widths.
     sigzro1: the error of the fitted zero offset; zero if zr0yn=0.
     sighgt1: the array of errors of the N fitted heights; zero if hgt0yn=0).
     sigcen1: the array of errors of the N fitted centers; zero if cen0yn=0).
     sigwid1: the array of errors of the N fitted widths; zero if wid0yn=0).
     problem: 0, OK; -1, excessive width; -2, >50 loops; -3, negative sigmas,
	; 4, bad derived values.
     cov: the normalized covariance matrix of the fitted coefficients.

RESTRICTIONS:
    The data and x values should be in asympototic x order, 
    either increasing or decreasing.
    Gaussians are not an orthogonal set of functions! 
    This doesn't matter for many cases; convergence is unique UNLESS...
    Convergence is NOT unique when Gaussians are close together or when
    multiple Gaussians lie within a single peak. In these cases, you
    can get different outputs from different inputs.
    And sometimes in these cases the fits will not converge!

    This procedure uses the classical nonlinear least squares technique,
    which utilizes analytically-calculated derivatives, to iteratively
    solve for the least squares coefficients. Some criteria on the
    parameters used to update the iterated coefficients are used to
    make the fit more stable (and more time-consuming). The number
    of iterations is limited to 50; if you need more, enter the routing
    again, using the output parameters as input for the next attampt.

EXAMPLE:
    You have two Gaussians that are well-separated. This counts as an
	easy case; for the estimated parameters, you need not be accurate
	at all. The heights are hgt0=[1.5, 2.5], the centers cen0=[12., 20.],
	and the widths are [5., 6.]. You wish to hold the width of the second
    Gaussian fixed in the fit, so you set wid0yn=[1,0]. 
    There are 100 data points (tdata) at 
	100 values of x (xdata) and you want to fit indices 25-75 and
	77-80 only, so
	you set xrange=[50,75,77,80]. 
    You don't wish to see plots of the iterations,
	you don't care about the uncertainties, but you want the fitted
	 points and also the rms of the residuals.

    If you have two Gaussians that are mixed, you must be careful in
    your estimates!

RELATED PROCEDURES:
	GCURV
HISTORY:
	Original GFIT Written by Carl Heiles. 21 Mar 1998.
	FLEX options added 4 feb 00.

(See /dzd2/heiles/idl/gen/gaussians/gfitflex.pro)


GFITSLOPE -- FIT N GAUSSIANS PLUS AN OFFSET AND SLOPE

[Previous Routine] [Next Routine] [List of Routines]
NAME:
GFITSLOPE -- fit n gaussians plus an offset and slope

PURPOSE:
    Fit multiple (N) Gaussians to a one-d array of data points.
	ALSO FITS A ZERO OFFSET AND SLOPE.

CALLING SEQUENCE:
    GFITSLOPE, look, xdata, tdata, zro0, slp0, hgt0, cen0, wid0, 
	tfit, sigma, zro1, slp1, hgt1, cen1, wid1, 
	sigzro1, sigslp1, sighgt1, sigcen1, sigwid1, problem, cov

INPUTS:
     look: if >=0, plots the iterated values for the Gaussian
     whose component number is equal to look. Then it prompts you to plot 
     a different Gaussian component number.

     xdata: the x-values at which the data points exist.
     tdata: the data points.

     zro0: the estimated constant zero offset of the data points.
     slp0: the estimated slope.
     hgt0: the array of N estimated heights of the Gaussians.
     cen0: the array of N estimated centers of the Gaussians.
     wid0: the array of N estimated halfwidths of the Gaussians.

OUTPUTS:
     tfit: the fitted values of the data at the points in xdata.
     sigma: the rms of the residuals.
     zro1: the fitted zero offset
     slp1: the fitted slope
     hgt1: the array of N fitted heights. 
     cen1: the array of N fitted centers.
     wid1: the array of N fitted half-power widths.
     sigzro1: the 'error of the mean' of the fitted zero offset.
     sigslp1: the 'error of the mean' of the fitted slope.
     sighgt1: the array of errors of the N fitted heights.
     sigcen1: the array of errors of the N fitted centers.
     sigwid1: the array of errors of the N fitted widths.
     problem: 0, OK; -1, excessive width; -2, >50 loops; -3, negative sigmas,
; 4, bad derived values.
     cov: the normalized covariance matrix of the fitted coefficients.

RESTRICTIONS:
    The data and x values should be in asympototic x order, 
    either increasing or decreasing.
    Gaussians are not an orthogonal set of functions! 
    This doesn't matter for many cases; convergence is unique UNLESS...
    Convergence is NOT unique when Gaussians are close together or when
    multiple Gaussians lie within a single peak. In these cases, you
    can get different outputs from different inputs.
    And sometimes in these cases the fits will not converge!

    This procedure uses the classical nonlinear least squares technique,
    which utilizes analytically-calculated derivatives, to iteratively
    solve for the least squares coefficients. Some criteria on the
    parameters used to update the iterated coefficients are used to
    make the fit more stable (and more time-consuming). The number
    of iterations is limited to 50; if you need more, enter the routing
    again, using the output parameters as input for the next attampt.

EXAMPLE:
    You have two Gaussians that are well-separated. This counts as an
    easy case; for the estimated parameters, you need not be accurate
    at all. The heights are hgt0=[1.5, 2.5], the centers cen0=[12., 20.],
    and the widths are [5., 6.]. There are 100 data points (tdata) at 
     100 values of x (xdata). You don't wish to see plots of the iterations,
     you don't care about the uncertainties, but you want the fitted
     points and also the rms of the residuals.

    gfitslope, look, xdata, tdata, zro0, slp0, hgt0, cen0, wid0, tfit, sigma

    If you have two Gaussians that are mixed, you must be careful in
    your estimates!

RELATED PROCEDURES:
	GCURVSLOPE
HISTORY:
	Written by Carl Heiles. 11 Jul 1998.
	Modified 16 jul 98, with 'problems' enhancement.

(See /dzd2/heiles/idl/gen/gaussians/gfitslope.pro)


GFITWZFIX

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

PURPOSE:
    Fit multiple (N) Gaussians to a one-d array of data points.
    The WFIX means that the Widths are FIXED to be the values in wid0.

CALLING SEQUENCE:
    GFIT, look, xdata, tdata, zro0, hgt0, cen0, wid0, tfit, sigma,
         zro1, hgt1, cen1, wid1, sigzro1, sighgt1, sigcen1, sigwid1, cov

INPUTS:
     look: if >=0, plots the iteratited values for the Gaussian
     whose number is equal to look. Then it prompts you to plot 
     a different Gaussian number.

     xdata: the x-values at which the data points exist.
     tdata: the data points.

     zro0: the estimated constant zero offset of the data points.
     hgt0: the array of N estimated heights of the Gaussians.
     cen0: the array of N estimated centers of the Gaussians.
     wid0: the array of N estimated halfwidths of the Gaussians.

OUTPUTS:
     zro1: the array of N fitted heights. 
     cen1: the array of N fitted centers.
     wid1: the array of N half-power widths; they are equal to wid0.
     tfit: the fitted values of the data at the points in xdata.
     sigma: the rms of the residuals.
     sigzro1: the 'error of the mean' of the fitted zero offset.
     sighgt1: the array of errors of the N fitted heights.
     sigcen1: the array of errors of the N fitted centers.
     sigwid1: the array of errors of the N fitted widths.
     cov: the normalized covariance matrix of the fitted coefficients.

RESTRICTIONS:
    The data and x values should be in asympototic x order, 
    either increasing or decreasing.
    Gaussians are not an orthogonal set of functions! 
    This doesn't matter for many cases; convergence is unique UNLESS...
    Convergence is NOT unique when Gaussians are close together or when
    multiple Gaussians lie within a single peak. In these cases, you
    can get different outputs from different inputs.
    And sometimes in these cases the fits will not converge!

    This procedure uses the classical nonlinear least squares technique,
    which utilizes analytically-calculated derivatives, to iteratively
    solve for the least squares coefficients. Some criteria on the
    parameters used to update the iterated coefficients are used to
    make the fit more stable (and more time-consuming). The number
    of iterations is limited to 50; if you need more, enter the routing
    again, using the output parameters as input for the next attampt.

EXAMPLE:
    You have two Gaussians that are well-separated. This counts as an
    easy case; for the estimated parameters, you need not be accurate
    at all. The heights are hgt0=[1.5, 2.5], the centers cen0=[12., 20.],
    and the widths are [5., 6.]. There are 100 data points (tdata) at 
     100 values of x (xdata). You don't wish to see plots of the iterations,
     you don't care about the uncertainties, but you want the fitted
     points and also the rms of the residuals.

	gfit, look, xdata, tdata, zro0, hgt0, cen0, wid0, tfit, sigma
    If you have two Gaussians that are mixed, you must be careful in
    your estimates!

RELATED PROCEDURES:
	GCURV
HISTORY:
	Written by Carl Heiles. 24 Mar 1998.

(See /dzd2/heiles/idl/gen/gaussians/gfitwzfix.pro)


general procs

general procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

DEL_VAR

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

 PURPOSE:
       Program deletes an IDL variable from memory management.
       Unlike DELVAR, it can be called from program modules.

 CALLING SEQUENCE:
       DEL_VAR, variable

 INPUTS:
       variable: variable to be deleted

 OUTPUTS:
       None.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       The variable is now undefined.

 EXAMPLE:
       Define a variable...
       IDL> f = 1024
       IDL> help, f
       F               INT       =     1024

       Delete the variable...
       IDL> del_var, f
       IDL> help, f
       F               UNDEFINED = 

 MODIFICATION HISTORY:
   15 Feb 2004  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/general/del_var.pro)


DOC

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

 PURPOSE:
       Shorthand for doc_library.

 CALLING SEQUENCE:
       doc, name

 INPUTS:
       Name - A string containing the name of the IDL routine in question. 

 KEYWORD PARAMETERS:
       All keywords accepted by DOC_LIBRARY are also accepted here.

 OUTPUTS:
       None.

 NOTES:
       If a routine is compiled but the directory of the routine is not
       in !PATH, then in order to get the documentation, you need to specify
       the DIRECTORY keyword must be set to the directory of the routine.

 MODIFICATION HISTORY:
   26 Feb 2003  Written by Tim Robishaw, Berkeley
   03 Oct 2005  TR.  Added _REF_EXTRA options.

(See /dzd2/heiles/idl/gen/general/doc.pro)


GETNCOL

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

 PURPOSE:
       Read data array of given number of columns from an ASCII data file.

 CALLING SEQUENCE:
       GETNCOL, FNAME, NUMCOL, RESULT, [,/BYTE|/INT|/LONG|/FLOAT|/DOUBLE]
       [,SKIP=skip][,LINES=lines][,/SILENT]

 INPUTS:
       FNAME - File name.
       NUMCOL - Number of columns in the file.

 KEYWORD PARAMETERS:
       /BYTE - if set, data read as byte type.
       /INT - if set, data read as integer type.
       /LONG - if set, data read as long integer type.
       /FLOAT - if set, data read as floating-point type.
       /DOUBLE - if set, data read as double-precision 
                 floating-point type.
       SKIP - The number of lines to skip at the start of the file.
       LINES - Set this keyword to a named variable that stores the
               number of lines read into the data array.
       /SILENT - Set this keyword to prevent messages.

 OUTPUTS:
       RESULT - Array containing the data read from file.

 COMMON BLOCKS:
       None.

 RESTRICTIONS:
       All data are assumed to be of the same data type.

 EXAMPLE:
       Read in 12 columns of byte type data from the file file.dat,
       skipping the first 3 lines and suppressing messages:

       IDL> GETNCOL, 'file.dat', 12, data, /BYTE, /SILENT

 NOTES:
       If no data type keyword is specifies, then floating-point 
       is assumed.

 MODIFICATION HISTORY:
   02 Mar 2003  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/general/getncol.pro)


idlutils_carl procs

idlutils_carl procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

BAR

[Next Routine] [List of Routines]

 A program to create a progress bar within a loop.

 Call sequence:
   BAR, I, IMAX

 Inputs:
   I - The index being advanced in the loop.
   IMAX - The value at the loop's finish.

 Outputs:
   Prints out a simple empty bar that fills up with 10 dashes as the
   loop completes.

 Calls:
   DELVARX (Goddard Routine)

Katie Peek August 2004

(See /dzd2/heiles/idl/gen/idlutils_carl/bar.pro)


COUNT

[Previous Routine] [Next Routine] [List of Routines]
NAME
COUNT -- This procedure exists only as example of overwriting the screen in place
with a running number without skipping lines.

(See /dzd2/heiles/idl/gen/idlutils_carl/count.pro)


FILLARR -- GENERATE AN ARRAY FROM MIN TO MAX WITH STEP SIZE DEL.

[Previous Routine] [Next Routine] [List of Routines]
 NAME: 
FILLARR --  generate an array from MIN to MAX with step size DEL. 


 PURPOSE:
       This function generates an array from MIN to MAX with
       step size DEL. If an integer number of steps cannot be
       fit between MIN and MAX, then MAX will be adjusted to
       be as close as the specified maximum as possible.
 CATEGORY:



 CALLING SEQUENCE:
       f = fillarr(n, min, max [,fan=, transfan=, /double])


 INPUTS:

       DEL:  The desired step size
       MIN:  The value of the first array element in F
       MAX:  The value of the last array element in F if
             (MAX-MIN)/DEL is an integer. Adjusted otherwise.

 OPTIONAL INPUTS:

 KEYWORD PARAMETERS:

       FAN:        Number of times the array is to be repeated.
                   The final dimensions of F  will be 
                   fix((MAX-MIN)/DEL) + 1 columns by FAN rows.

       /TRANSPOSE  Final dimensions of F wil be FAN columns by 
                   fix((MAX-MIN)/DEL) + 1 rows if FAN is specified. 

 OUTPUTS:

       F:    Final array. If input parameters are double precision,
             then F will be double as well. F is float otherwise.


 OPTIONAL OUTPUTS:



 COMMON BLOCKS:



 SIDE EFFECTS:



 RESTRICTIONS:



 PROCEDURE:



 EXAMPLE:

         For an array that runs from 2 to 5 in steps of .7

         IDL> f = fillarr(.7,2,5)
         IDL> print, f
            2.00000      2.70000      3.40000     4.10000    4.80000
         
 MODIFICATION HISTORY:
 Written by John "JohnJohn" Johnson 21-Feb-2002
 22-Feb-2002 JohnJohn- Fixed precision bug
 23-Feb-2002 JohnJohn- Calculations performed in double precision. 
                       Output in double precision if input is 
                       double.
 01-Mar-2002 JohnJohn- Much props to Tim Robishaw (Tdogg) for helping
                       me understand machine precision and truly fix
                       the precision bug.

(See /dzd2/heiles/idl/gen/idlutils_carl/fillarr.pro)


INDXTODIMS -- CONVERT BETWEEN A 1-D INDEX AND AN N-DIMENSIONAL INDEX OR VICE-VERSA

[Previous Routine] [Next Routine] [List of Routines]
NAME:
INDXTODIMS --  convert between a 1-d index and an n-dimensional index or vice-versa

PURPOSE:
    converts between a 1-d index and an n-dimensional index for an
	array of the given size. Goes either direction.

CALLING SEQUENCE:
	INDXTODIMS, array, indx, dims, direction

INPUTS:
	array: an N-dimensional input array. Not changed or used except
to define the dimensions for which the outputs are computed.
	indx: the one-d index. an INPUT if direction=+1, an OUTPUT otherwise.
	dims: a vector of size N containing the three indices in N-d space.
An INPUT if direction=-1, an OUTPUT otherwise.
	direction: the direction of conversion: 
		+1 to go from INDX ---> DIMS
		-1 to go from DIMS ---> INDX

IMPORTANT: INDX can be an N-element array, where N is the nr of indices
		to treat.
	    DIMS can be an N by M element array, where N is the nr of indices
		to treat and M is the nr of dimensions in ARRAY.
OUTPUTS:
	indx: the one-d index. an INPUT if direction=+1, an OUTPUT otherwise.
If indx is an INPUT, it may be a 1-d array, in which case dims will
be an array whose first dimension is that of indx.
	dims: a vector of size N containing the three indices in N-d space.
An INPUT if direction=-1, an OUTPUT otherwise.

EXAMPLE:
	you have a 3-d vector X(541,541,9) and a 1-d index returned from
the 'where' function equal to 880212.

	INDXTODIMS, X, 880212, dims, +1

returns dims=[5,4,3].
HISTORY:
	Written by Carl Heiles. 18 Sep 1998.

(See /dzd2/heiles/idl/gen/idlutils_carl/indxtodims.pro)


LOOP_BAR

[Previous Routine] [Next Routine] [List of Routines]

 LOOP_BAR
 A program to create a progress bar within a loop.

 Call sequence:
   BAR, I, IMAX [, IMIN=integer]

 Inputs:
   I - The index being advanced in the loop.
   IMAX - The value at the loop's finish.

 Outputs:
   Prints out a simple empty bar that fills up with 10 dashes as the
   loop completes.  Also prints percent complete and estimates time
   remaining.

 Keyword:
   IMIN - Include if IMIN is nonzero.  Default IMIN = 0.

 Calls:
   DELVARX (Goddard Routine)

 Katie Peek / August 2004
  Updated to include remaining time estimate - August 2005

(See /dzd2/heiles/idl/gen/idlutils_carl/loop_bar.pro)


MAKEARR -- GENERATE AN N-EL ARRAY RUNNING FROM VALUES MIN TO MAX

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
MAKEARR -- generate an N-el array running from values MIN to MAX


 PURPOSE:
       This procedure will generate an array of lenght N which
       runs from values MIN to MAX

 CATEGORY:



 CALLING SEQUENCE:
       f = makearr(n, min, max [,fan=, transfan=, /double])


 INPUTS:

       N:    The number of desired array elements in F
       MIN:  The value of the first array element in F
       MAX:  The value of the last array element in F

 OPTIONAL INPUTS:

 KEYWORD PARAMETERS:

       FAN:        Number of times the array is to be repeated.
                   The final dimensions of F  will be N columns 
                   by FAN rows.
       /TRANSPOSE  Final dimensions of F wil be FAN columns by N 
                   rows if FAN is specified. 

 OUTPUTS:

       F:    Final array

 OPTIONAL OUTPUTS:



 COMMON BLOCKS:



 SIDE EFFECTS:



 RESTRICTIONS:



 PROCEDURE:



 EXAMPLE:

      If you want a 5 element array which runs from 2 to 4:

         IDL> f = makearr(5,2,4)
         IDL> print, f
             2.00000      2.50000      3.00000      3.50000      4.00000
         
 MODIFICATION HISTORY:
 Written by John "JohnJohn" Johnson somewhere around Oct-2001
 20 Feb 2002 JohnJohn- Added /FAN and /TRANSPOSE keywords.
 23 Feb 2002 JohnJohn- Calculations performed in double precision. 
                       Output in double precision if input is 
                       double.
 01 Mar 2002 Tim Robishaw- Spiffed up with a little Tim. 

(See /dzd2/heiles/idl/gen/idlutils_carl/makearr.pro)


RDPLOT (TR_RDPLOT) -- LIKE CURSOR BUT WITH FULL-SCREEN CURSOR AND CONTINUOUS READOUT.

[Previous Routine] [Next Routine] [List of Routines]
NAME:
RDPLOT (tr_rdplot) -- like CURSOR but with full-screen cursor and continuous readout.

 PURPOSE:
   Like CURSOR but with a full-screen cursor and continuous readout option
 EXPLANATION:
   This program is designed to essentially mimic the IDL CURSOR command,
   but with the additional options of continuously printing out the data
   values of the cursor's position, and using a full-screen cursor rather 
   than a small cross cursor.  The Full screen cursor uses OPLOT and 
   X-windows graphics masking to emulate the cursor.
      One difference is that IF the PRINT keyword is set but the DOWN, WAIT,
   or CHANGE keywords are not set, then the leftmost mouse button will 
   print a "newline" line-feed, but not exit.

 CALLING SEQUENCE:
   RDPLOT, [X, Y, WaitFlag], [/DATA, /DEVICE, /NORMAL,
      /NOWAIT, /WAIT, /DOWN, /CHANGE, ERR=,
      PRINT=, XTITLE=, YTITLE=, XVALUES=, YVALUES=,
      /FULLCURSOR, /NOCLIP, LINESTYLE=, THICK=, COLOR=, BACKGROUND=, /CROSS]

 REQUIRED INPUTS:
   None.

 OPTIONAL INPUTS: 
   WAITFLAG = Uses the same table as the intrinsic CURSOR command, But note
	that unlike the CURSOR command, there is no UP keyword.
		WaitFlag=0 sets the NOWAIT keyword
		WaitFlag=1 sets the WAIT keyword {default}
		WaitFlag=2 sets the CHANGE keyword
		WaitFlag=3 sets the DOWN keyword

 OPTIONAL OUTPUTS:
    X - a named variable to receive the final cursor X position, scalar
    Y - a named variable to receive the final cursor Y position, scalar
 OPTIONAL KEYWORD INPUT PARAMETERS:
   /DATA = Data coordinates are displayed and returned.
   /DEVICE = device coordinates are displayed and returned.
   /NORMAL = normal coordinates are displayed and returned.
          Default is to use DATA coordinates if available (see notes).
   /NOWAIT = if non-zero the routine will immediately return the cursor's
      present position.
   WAIT = if non-zero will wait for a mouse key click before returning.  If
      cursor key is already down, then procedure immediately exits.
   DOWN = equivalent to WAIT *except* that if the mouse key is already down
      when the procedure is called, the procedure will wait until the mouse
      key is clicked down again.
   CHANGE = returns when the mouse is moved OR a key is clicked up or down.
   PRINT = if non-zero will continuously print out (at the terminal) the data 
      values of the cursor's position.  If PRINT>1, program will printout a 
      brief header describing the mouse button functions.  However, note that 
      the button functions are overridden if any of the DOWN, WAIT, mouse
      or CHANGE values are non-zero.
   XTITLE = label used to describe the values of the abscissa if PRINT>0.
   YTITLE = label used to describe the values of the ordinate if PRINT>0.
   XVALUES = a vector corresponding to the values to be printed when the
	PRINT keyword is set.  This allows the user the option of printing
	out other values rather than the default X coordinate position of
	the cursor.  E.g., if XVALUES is a string vector of dates such as
	['May 1', 'May 2', ...], then those dates will be printed rather than
	the X value of the cursor's position: if X=1 then 'May 2' would be
	printed, etc.  This requires that the values of the X coordinate read
	by the cursor must be positive (can't access negative elements).
       If XVALUES=-1, then NO values for X will be printed.
   YVALUES = analagous to the XVALUES keyword.
   FULLCURSOR = if non-zero default cursor is blanked out and full-screen 
      (or full plot window, depending on the value of NOCLIP) lines are
      drawn; their intersecton is centered on the cursor position.
   NOCLIP = if non-zero will make a full-screen cursor, otherwise it will
      default to the value in !P.NOCLIP.
   LINESTYLE = style of line that makes the full-screen cursor.
   THICK = thickness of the line that makes the full-screen cursor.
   COLOR = color of the full-screen cursor.
   BACKGROUND = color of the background of the plot device.  If this has
      been set to !P.BackGround, then this keyword is unnecessary.
   CROSS = if non-zero will show the regular cross AND full screen cursors.

 OPTIONAL KEYWORD OUTPUT PARAMETER:
   ERR = returns the most recent value of the !mouse.button value.

 NOTES:
   Note that this procedure does not allow the "UP" keyword/flag...which 
   doesn't seem to work too well in the origianl CURSOR version anyway.

   If a data coordinate system has not been established, then RDPLOT will
   create one identical to the device coordinate system.   Note that this
   kluge is required even if the user specified /NORMAL coordinates, since
   RDPLOT makes use of the OPLOT procedure.  This new data coordinate system
   is effectively "erased" (!X.CRange and !Y.CRange are both set to zero)
   upon exit of the routine so as to not change the plot status from the
   user's point of view.

   Only tested on X-windows systems.  If this program is interrupted, the
   graphics function might be left in a non-standard state; in that case,
   run the program RESET_RDPLOT to return the standard graphics functions,
   or type the command:   DEVICE, /CURSOR_CROSS, SET_GRAPHICS=3, BYPASS=0

 BUGS:
   NOTE: (1/27/05) These bugs have been fixed by Robishaw and tested
   on Solaris, Linux and OS-X.

   It is assumed that the current background of the plot is correctly
   defined by the value in !P.Background.  Otherwise, the color of the
   long cursor probably will not be correct.  Sometimes the color doesn't
   work anyway, and I'm not sure why.
   NOTE: Robishaw fixed this 1/27/05.

   There may be some cases (e.g., when THICK>1 and NOCLIP=0) when the
   full-screen cursor is not correctly erased, leaving "ghost images" on the
   plot.  It just seems that the screen updates get slow or the positions
   ambiguous with a thick line and the cursor off the plot.
   NOTE: Robishaw fixed this 1/27/05.

 PROCEDURE:
   Basically is a bells-n-whistles version of the CURSOR procedure.  All
   the details are covered in the above discussion of the keywords.

 EXAMPLE (a silly, but informative one):
   Months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', $
             'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
   plot, indgen(12), xrange=[-5, 15]
   rdplot, /FULL, /PRINT, XTITLE='Month: ', YTITLE='Y-value per month = ', $
      xvalues=Months

 MODIFICATION HISTORY:
   Written (originally named CURFULL) by J.Wm.Parker  1993 Nov 22 
   Created data coordinates if not already present, W. Landsman Nov. 93
   Added continuous printout of data values, COLOR and FULLCURSOR keywords
      (so that default is that it acts just like the cursor command).
      Changed name from CURFULL to RDPLOT.   J.Wm.Parker  1994 Apr 20
   Modified (with some translation table assistance from the IDL support 
      group) to correctly plot the crosshair with the desired IDL 
      color using the device's translation table to determine the XOR 
      function and using the BYPASS function.  Added the RESET_RDPLOT
      procedure to cleanup crashes that might occur while running
      RDPLOT.  Other minor changes/bug fixes.  J.Wm.Parker  1994 May 21
   Modified DOWN, WAIT, CHANGE functions to behave more similar to the
      generic CURSOR procedure.   J.Wm.Parker  1995 April 24
   Added XVALUES, YVALUES keywords and cleanup.   J.Wm.Parker  1995 April 24
   Convert to IDL V5.0,  W. Landsman    July 1998
   Change !D.NCOLORS to !D.TABLE_SIZE for 24 bit displays W. Landsman May 2000
   Skip translation table for TrueColor visuals   W. Landsman  March 2001
   Fixed /FULLCURSOR ghosts. Fixed to properly deal with background colors
      in 24-bit visual classes (TrueColor and DirectColor).
      Tim Robishaw 2005 Jan 27       

(See /dzd2/heiles/idl/gen/idlutils_carl/tr_rdplot.pro)


SHOWFONT -- DISPLAY VECTOR-DRAWN FONTS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
SHOWFONT -- display vector-drawn fonts

 PURPOSE:
	This procedure displays a vector-drawn font on the current
	graphics device.

 CATEGORY:
	Fonts.

 CALLING SEQUENCE:
	SHOWFONT, Font [, Name]

 INPUTS:
	Font:	 The index number of the font (may range from 3 to 29)
		 or, if the TT_FONT keyword is set, a string representing
                the name of the TrueType font to display.
	Name:	 Title text to appear at top of display.

 KEYWORD PARAMETERS:
	ENCAPSULATED:	If this keyword is set, and if the current graphics
			device is "PS", makes encapsulated PostScript output.
	TT_FONT:	If this keyword is set, the Font argument is 
			interpreted as the name of a TrueType font.

 OUTPUTS:
	No explicit outputs.

 SIDE EFFECTS:
	A display is made.

 RESTRICTIONS:
	Not very flexible.

 PROCEDURE:
	Straightforward.

 EXAMPLE:
	To create a display of Font 3 for PostScript:
		SET_PLOT, 'PS'
		SHOWFONT, 3, "Simplex Roman"

	To create a display of the Times Roman TrueType font:
		SHOWFONT, 'Times', 'Times Roman', /TT_FONT

 MODIFICATION HISTORY:
 	Written by:
	DMS, Nov, 1992
	WSO, 1/95, Updated for new directory structure
	DD, 12/97, Updated to handle TrueType fonts
       Erik Rosolowsky, added forward subscripts in roman and trapped
       the passage of an empty name string. (1/26/05)

(See /dzd2/heiles/idl/gen/idlutils_carl/showfont.pro)


TRC

[Previous Routine] [List of Routines]
name:
TRC -- tim's full-screen cursos with carl's preferred features.

(See /dzd2/heiles/idl/gen/idlutils_carl/trc.pro)


image procs

image procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

DISPLAY2PAR -- DISPLAY INTENSITY/COLOR (2D COLOR IMAGE) USING PSEUDOCOLOR TABLE

[Next Routine] [List of Routines]
NAME:
display2par -- display intensity/color (2d color image) using pseudocolor table
 KEYWORDS: ENCAPSULATED

style =1 means put axes on the image; 5 means not.
xaxlbl and yaxlbl are the x and y axis labels.

 !!!!!!
 leave the ps device open!

 !!!!! PROBABLY SMARTER WAY TO DO CONGRID THAN JUST TAKING 541 PIXELS???
 !!!!! WHAT DO WE DO ABOUT VALUES WE REALLY WANT TO IGNORE?
 A COLOR FIELD WITH VALUES FROM -320 TO -200 WILL HAVE A BUNCH
 OF ZEROS WHERE THERE'S NO DATA.  WHAT IF COLOR STRETCHED FROM -10 TO
 +10, THEN TROUBLE CITY.  --> NAN!!!!

 MAKE A COLORBAR AND IMAGE WITH COLOR/INTENSITY
 USE 24 BIT COLOR

 how would figure out what xsize/ysize (before you get here) to feed
 psopen in order to make correct aspect ratio???

 EXAMPLES:
 IDL> psopen, 'color_inensity.ps', /COLOR
 IDL> display2par, vimage, timage, ra, dec, epoch=2002
 IDL> psclose

 assumes rectangular region of sky.  if curvature is important (high
 latitude) then you have to modify this routine.

 CHECK TO MAKE SURE BOTH PARAMETER MAPS HAVE THE SAME SIZE...

(See /dzd2/heiles/idl/gen/image/display2par.pro)


DSPLY2D -- DISPLAY INTENSITY/COLOR (2D COLOR IMAGE) USING PSEUDOCOLOR TABLE

[Previous Routine] [Next Routine] [List of Routines]
NAME:
dsply2d -- display intensity/color (2d color image) using pseudocolor table
 KEYWORDS: ENCAPSULATED

style =1 means put axes on the image; 5 means not.
xaxlbl and yaxlbl are the x and y axis labels.

 !!!!!!
 leave the ps device open!

 !!!!! PROBABLY SMARTER WAY TO DO CONGRID THAN JUST TAKING 541 PIXELS???
 !!!!! WHAT DO WE DO ABOUT VALUES WE REALLY WANT TO IGNORE?
 A COLOR FIELD WITH VALUES FROM -320 TO -200 WILL HAVE A BUNCH
 OF ZEROS WHERE THERE'S NO DATA.  WHAT IF COLOR STRETCHED FROM -10 TO
 +10, THEN TROUBLE CITY.  --> NAN!!!!

gryrev: set if this is a negative (bright means small) instead of pos (bright means large)

 MAKE A COLORBAR AND IMAGE WITH COLOR/INTENSITY
 USE 24 BIT COLOR

 how would figure out what xsize/ysize (before you get here) to feed
 psopen in order to make correct aspect ratio???

 EXAMPLES:
 IDL> psopen, 'color_inensity.ps', /COLOR
 IDL> dsply2dcbl, vimage, timage, ra, dec, epoch=2002
 IDL> psclose

 assumes rectangular region of sky.  if curvature is important (high
 latitude) then you have to modify this routine.

 CHECK TO MAKE SURE BOTH PARAMETER MAPS HAVE THE SAME SIZE...

(See /dzd2/heiles/idl/gen/image/dsply2d.pro)


IMAGEALIGN -- ALIGN TWO IMAGES OF THE SAME FIELD

[Previous Routine] [Next Routine] [List of Routines]
NAME:
IMAGEALIGN -- align two images of the same field

PURPOSE:
	This procedure take two images of the same field and aligns them
exactly. 

CALLING SEQUENCE:
	IMAGEALIGN, Im1, Im2, Boxsize

INPUTS:
	Im1: The image used as the 'standard' to which Im2 will be
aligned. 

	Im2: The image that should be moved to be aligned with Im1. 

OPTIONAL INPUTS:

	Boxsize: This is the size of the area used in the cross
correlation calculation.  A larger Boxsize means a larger area is
included in the calculation, which includes more stars in the cross
correlation, which usually leads to more accurate alignment. 

	However, the computation time goes as Boxsize SQUARED.  The
default boxsize is 128. 

OUTPUTS:
	There are no outputs.  The amount by which Im2 needs to be moved
is printed on the screen and you are given the choice as to whether to
move Im2 by this amount or not. 

RESTRICTIONS:
	The input images must be FLOATING POINT (i.e., REAL) numbers. 

	You are asked to move the cursor onto a star and click; this
defines the center of the box used in the cross correlation.  This
center doesn't HAVE to be a star; it can be any point.  But this point
must be at least as far from the edge of the image as Boxsize. 

PROCEDURE:
	This routine first removes the sky background by convolving each
image with a small second-derivative type of kernal (6 X 6 pixels). 
Then it cross-correlates the two images and finds the position where the
cross-correlation is maximum.  Then it prints out the amount by which
the Im2 needs to be shifted and asks you if you want to actually move
Im2 by this amount.  When doing the moving, we use the IDL SHIFT
procedure, in which the edges of Im2 are 'wrapped around' so that no
information is lost; you can move it back to the original position with
SHIFT and no information is lost. 

EXAMPLE:
	Get Im1 into a window.  Then type IMAGEALIGN, Im1, Im2, Boxsize. 

HISTORY:
	Written by Carl Heiles.  Documented 13 Dec 1997.  Modified 13
Dec 1997 to check if images are real numbers. 
Modified 9 Nov 1998 to do images of arbitrary size (it was 512)
Updated documentation 19 Oct 99.

(See /dzd2/heiles/idl/gen/image/imagealign.pro)


OPLOTBEAM

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

 PURPOSE:
       Draw a half-power beam ellipse on an already-existing plot.

 CALLING SEQUENCE:
       OPLOTBEAM, xcenter, ycenter, hpbw_major [, hpbw_minor] [,
       /NOFILL] [, ANGLE=ccw_degrees_from_horiz]

 Other keywords accepted by both PLOTS and POLYFILL:
       [, CLIP=[X0, Y0, X1, Y1]] [, COLOR=value] 
       [, /DATA | , /DEVICE | , /NORMAL] 
       [, LINESTYLE={0 | 1 | 2 | 3 | 4 | 5}] [, /NOCLIP] [, THICK=value]

 Other POLYFILL keywords accepted:
       [, /LINE_FILL] [, ORIENTATION=ccw_degrees_from_horiz]  
       [, PATTERN=array] [, SPACING=centimeters] 

 INPUTS:
       XCENTER - Horizontal coordinate used to position the center of
                 the beam area.  Assumed to be in DATA coordinates;
                 override this with /NORMAL or /DEVICE keywords.

       YCENTER - Vetical coordinate used to position the center of
                 the beam area. Assumed to be in DATA coordinates;
                 override this with /NORMAL or /DEVICE keywords.

       HPBW_MAJOR - The half-power beamwidth of the major axis of the 
                    telescope beam.  If the beam is circular, then this
                    parameter is all that is necessary to define the beam.
                    Must be given in the same coordinate system (DATA,
                    DEVICE, NORMAL) as the XCENTER and YCENTER
                    parameters.  Assumed to be in DATA coordinates;
                    override this with /NORMAL or /DEVICE keywords.

 OPTIONAL INPUTS:
       HPBW_MINOR - If the beam is elliptical, then this is the half-power 
                    beamwidth of the minor axis of the telescope beam.

 KEYWORD PARAMETERS:
       /NOFILL: Set this keyword if you want only the boundary of the beam
                area to be drawn.

       ANGLE = Specifies the counterclockwise angle in degrees from 
               horizontal of the major axis of the beam ellipse.
               Remember that astronomical position angles are
               measured from the North towards the East.  If you've
               displayed your map correctly, and you know the PA of
               your beam, set ANGLE to 90+PA.

 OUTPUTS:
       None.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       A beam ellipse is drawn on the current display device.

 EXAMPLE:
       A map has been established on the display device.  Choose a
       nice uncluttered place to draw the beam ellipse using the
       cursor:

       IDL> cursor, x, y

       Try the default, a filled ellipse with the major axis along
       the horizontal (the values of hpbw_maj and hpbw_min must be in
       the same coordinates as x and y, in this case DATA coordinates):

       IDL> oplotbeam, x, y, hpbw_maj, hpbw_min

       Get fancy by adding a line fill at an orientation of 30
       degrees ccw from the horizontal, increasing the line
       thickness, and drawing the beam in color:

       IDL> oplotbeam, x, y, hpbw_maj, hpbw_min, THICK=3, $
       IDL> COLOR=green, ORIENTATION=-30

       Now, also tilt the major axis of the beam at an angle
       of 30 degrees ccw from horizontal:

       IDL> oplotbeam, x, y, hpbw_maj, hpbw_min, THICK=3, $
       IDL> COLOR=green, ORIENTATION=-30, ANGLE=-30

 NOTES:
       Defaults:
       (1) Plots major axis of the beam ellipse parallel to the
           horizontal.  Use ANGLE keyword to change this orientation
           of the ellipse.
       (2) Fills the ellipse with a solid pattern.  To prevent the
           ellipse from being filled, set the /NOFILL keyword.  To
           fill the ellipse with lines, set the /LINE_FILL keyword
           and/or the ORIENTATION keyword.

 RELATED PROCEDURES:
       OPLOTSCALE

 MODIFICATION HISTORY:
   26 Mar 2004  Written by Tim Robishaw, Berkeley
   31 Mar 2004  Fixed angle so that CCW is always CCW, even if X axis
                or Y axis is running backwards. TR

(See /dzd2/heiles/idl/gen/image/oplotbeam.pro)


OPLOTSCALE

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

 PURPOSE:
       Draw a scale bar on an already-existing plot.

 CALLING SEQUENCE:
       OPLOTSCALE, xcenter, ycenter, scale, scale_string [,
       /ABOVE | /BELOW | /LEFT | /RIGHT] [, /NOHAT] [, THICK=value] [, 
       COLOR=value] [, CHARSIZE=value] [, CHARTHICK=value] [, 
       FONT=integer]

 INPUTS:
       XCENTER - Horizontal coordinate used to position the center
                 of the scale bar.  Must be given in DATA coordinates.

       YCENTER - Vertical coordinate used to position the center
                 of the scale bar.  Must be given in DATA coordinates.

       SCALE - The length of the scale bar in DATA coordinates.

       SCALE_STRING - String containing the scale size and units of
                      the scale bar.

 OUTPUTS:
       None.

 KEYWORD PARAMETERS:
       /ABOVE - Places the scale bar annotation ABOVE the scale bar;
                this is the default.

       /BELOW - Places the scale bar annotation BELOW the scale bar.

       /LEFT - Places the scale bar annotation to the left of the
               scale bar.

       /RIGHT - Places the scale bar annotation to the right of the
                scale bar.

       /NOHAT - If this keyword is set, the scale bar is drawn without 
                hats at each end.  Default is to draw hats.

       THICK = The line thickness.

       COLOR = The color index of the scale bar and the scale text.

       CHARSIZE = The overall character size for the annotation of the 
                  scale.

       CHARTHICK = An integer value specifying the line thickness of 
                   characters.

       FONT = An integer that specifies the graphics text font system to 
              use. Set FONT equal to 0 (zero) to select the device font 
              (e.g., PostScript font).

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       A scale bar is drawn on the current display device.

 RESTRICTIONS:
       A plot must already be established.  All inputs must be in
       DATA coordinates.

 EXAMPLE:
       A map has been established on the display device.  Choose a
       nice uncluttered place to draw the scale bar using the
       cursor:

       IDL> cursor, x, y

       Now display the scale bar and its annotation:

       IDL> oplotscale, x, y, scale, scale_string

       To place the annotation to the right of the scale bar, set the
       /RIGHT keyword:

       IDL> oplotscale, x, y, scale, scale_string, /RIGHT

       To place the annotation below the scale bar, set the /BELOW
       keyword; to remove the hats at each end of the scale bar, set
       the /NOHAT keyword:

       IDL> oplotscale, x, y, scale, scale_string, /BELOW, /NOHAT

 NOTES:
       Defaults:
       (1) Plots hats at the each end of scale bar.  The hats will
           have the height of one character.  Set the /NOHAT keyword
           to exclude the hats.

       (2) Places the scale annotation above the scale bar.  Set the
           /LEFT, /RIGHT, or /BELOW keywords to place the text to the
           right of, to the left of, or below the scale bar,
           respectively.

 RELATED PROCEDURES:
       OPLOTBEAM

 MODIFICATION HISTORY:
   26 Mar 2004  Written by Tim Robishaw, Berkeley
   31 Mar 2004  Added /LEFT, /RIGHT, /BELOW keywords. TR

(See /dzd2/heiles/idl/gen/image/oplotscale.pro)


PROFILES

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

 PURPOSE:
	Interactively draw row or column profiles of an image in a separate
	window.

 CATEGORY:
	Image analysis.

 CALLING SEQUENCE:
	PROFILES, Image [, SX = sx, SY = sy] [, /AXIS] [, ORDER=order]
        [, WSIZE=wsize | , XSIZE=xsize, YSIZE=ysize]
        [, PSYM=psym] [, SSIZE=ssize] [, COLOR=color] 
        [, CCOLOR=ccolor] [, CLENGTH=clength] [, /CCLIP]

 INPUTS:
	Image:	The variable that represents the image displayed in current
		window.  This data need not be scaled into bytes.
		The profile graphs are made from this array.

 KEYWORD PARAMETERS:
       ORDER:	Set this keyword param to 1 for images written top down or
		0 for bottom up.  Default is the current value of !ORDER.

       /AXIS:  Set this keyword if the image intensities are to be plotted 
               against axis value rather the pixel number.  The image
               must be bordered by an axis for this to work properly.

	SX:	Starting X position (in device coordinates) of the
               image in the window.  The default value is 0.

	SY:	Starting Y position (in device coordinates) of the
               image in the window.  The default value is 0.

       WSIZE:	The size of the PROFILES window as a fraction or multiple
		of 640 by 512.

       XSIZE:  The width of the profiles window in pixels.

       YSIZE:  The height of the profiles window in pixels.

       PSYM:   The plotting symbol used to plot the profile.

       SSIZE:  The symbol size of the plot symbols.

       COLOR:  The color of the plot symbols.

       CCOLOR: The color of the cross marking the cursor position.

       CLENGTH: The length of the cross marking the cursor position,
                expressed as a fraction of the window size.  Default
                size is 0.1.  A value of >1.0 produces a cursor that
                extends to each axis.

       /CCLIP: Set this keyword to force cursor-position cross to be
               clipped at the axes.  Especially useful when setting
               CLENGTH to a value > 1.

 OUTPUTS:
	No explicit outputs.

 COMMON BLOCKS:
	None.

 SIDE EFFECTS:
	A new window and two new pixmap windows are created and used
	for the profiles.  When done, the new windows are deleted and
	the system variables !p, !x, and !y are restored for the image
	window.

 RESTRICTIONS:
	None.

 PROCEDURE:
	A new window is created and the mouse location in the original
	window is used to plot profiles in the new window.  Pressing the
	left mouse button toggles between row and column profiles.
	The right mouse button exits.

 EXAMPLE:
	Create and display an image and use the PROFILES routine on it.
	Create and display the image by entering:

		A = BYTSCL(DIST(256))
		TV, A

	Run the PROFILES routine by entering:

		PROFILES, A

	The PROFILES window should appear.  Move the cursor over the original
	image to see the profile at the cursor position.  Press the left mouse
	button to toggle between row and column profiles.  Press the right
	mouse button (with the cursor over the original image) to exit the
	routine.


       Take advantage of new bells and whistles.  Display an image
       and surround it with axes...
       IDL> loadct, 5
       IDL> image = findgen(250,250)
       IDL> tv, bytscl(image), 101, 101
       IDL> plot, [0], POSITION=[100,100,351,351], /DEVICE, /NOERASE

       Make sure it's backwards compatible! Does it work like it used to?
       IDL> profiles, image, sx=101, sy=101

       Now add some new keywords; make the data blue and the cross red: 
       IDL> device, DECOMPOSED=0
       IDL> profiles, image, sx=101, sy=101, COLOR=48, CCOLOR=110

       Now add the /AXIS keyword to plot the profiles against axis values 
       rather than pixel number, and make the PROFILES window larger:
       IDL> profiles, image, sx=101, sy=101, /AXIS, XSIZE=500, YSIZE=500

       Now plot the data as small diamonds; also, make the cross fill the 
       entire axis range and clip the cross at the axes:
       IDL> profiles, image, sx=101, sy=101, /AXIS, XSIZE=500, YSIZE=500, $
       IDL> COLOR=48, PSYM=4, SSIZE=0.1, CCOLOR=110, CLENGTH=1.5, /CCLIP

 NOTES:
       The IDL routine PROFILES has been rewritten to reflect 16 years of 
       IDL development, and a little cleverness.  

       Here is what has been changed:
       (1) Rather than redrawing the plot every time the cursor is moved,
       a pixmap is created to store a template of the axes, then the 
       template is dumped to another pixmap in which the plot data are 
       drawn; finally, this pixmap is dumped into the display window.
       This allows for a smooth animation of the profiles.
       This also prevents the gradual erasing of your axes and labels
       by the cursor-position cross that was a "feature" of the 
       previous PROFILES.
       (2) The axis styles are chosen more intelligently to not waste
       space and to leave a little buffer between the axes and data.
       (3) Unlike the previous version, does not turn the cursor off after 
       the profile window is closed.  I never understood this behavior!
       (4) Restores the !p, !x, and !y system variables for the image 
       window upon exiting; the previous version lost this information.

       Here is what has been added:
       (1) The axes are labelled to minimize the amount of user thought.
       (2) Added XSIZE and YSIZE keywords for manually setting the
       width and height (in pixels) of the PROFILES window.
       (2) Added the PSYM, SSIZE, and COLOR keywords to allow the profile 
       data to be plotted with the user's choice of symbol, size and 
       color, respectively.
       (3) Added the CCOLOR keyword to allow the cursor-position cross
       to have a different color than the data, making it easier to see.
       (4) Added the CLENGTH keyword to allow the user to change the
       size of the cursor-position cross.  A value > 1.0 will cause
       the cross to extend to each axis.
       (5) Added the /CCLIP keyword to prevent the cursor-position
       cross from extending beyond the axes; useful when CLENGTH>1.
       (6) Added the /AXIS keyword.  When set, rather than plotting
       the profile as a function of row number or column number, the
       profile is plotted as a function of the row or column values.
       The image must be bounded by axes for this option to produce
       meaningful results.

       All the changes and additions leave PROFILES backwards compatible
       such that any routines that called PROFILES will not need to be
       changed and the performance of the routine will not be changed!

 MODIFICATION HISTORY:
	DMS, Nov, 1988.
       16 Mar 2004  Complete overhaul. Tim Robishaw, Berkeley
       09 Jun 2004  If /AXIS is set, use the lower left corner of
                    the axes instead of setting SX and SY.

(See /dzd2/heiles/idl/gen/image/profiles.pro)


math procs

math procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

BINOMIALDIST

[Next Routine] [List of Routines]
 NAME:
       binomialdist
     
 PURPOSE:
       Return the binomial distribution 
     
 CALLING SEQUENCE:
       RESULT = BINOMIALDIST(N)
     
 INPUTS:
       N : Number of Bernoulli trials to consider.

 OUTPUTS:
       Returns a vector containing the binomial distribution.

 RESTRICTIONS:
       N must be less than the value which makes N! larger than the
       largest usable floating point value on your machine!
       That's N < 151 on my machine, but will likely be different
       for you.

 PROCEDURES CALLED:
       FACTORIAL

 EXAMPLE:
       distribution = binomialdist(134)

 NOTES:
       The binomial distribution gives the probability distribution of 
       obtaining exactly i successes out of N Bernoulli trials (where the 
       result of each Bernoulli trial is true with probability p and false
       with probability q=1-p).

 MODIFICATION HISTORY:
   Written Tim Robishaw, Berkeley 01 Dec 2001.

(See /dzd2/heiles/idl/gen/math/binomialdist.pro)


ORDER

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        ORDER
     
 PURPOSE:
        To return the order of magnitude of a number.
     
 CALLING SEQUENCE:
        result = ORDER(value)
     
 INPUTS:
        value : a number.
     
 OUTPUTS:
        Returns the order of magnitude of the input value.

 EXAMPLE:
        IDL> print, order(1.989d33)
                  33

 NOTES:
       The "order of magnitude" of a number is defined as the floor
       of the base-10 logarithm of that number.

 MODIFICATION HISTORY:
    21 Jun 2002  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/math/order.pro)


SIGN

[Previous Routine] [List of Routines]
 NAME:
       SIGN
   
 PURPOSE:
       Returns the sign of the input value(s).

 CALLING SEQUENCE:
       Result = SIGN(value)

 INPUTS:
       value : a number.

 KEYWORD PARAMETERS:
       None.

 OUTPUTS:
       Returns the sign of the input value(s).

 COMMON BLOCKS:
       None.

 EXAMPLE:
       IDL> print, sign([-3,0,3])
            -1.00000      0.00000      1.00000

 MODIFICATION HISTORY:
   10 Feb 2004  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/math/sign.pro)


mpfit procs

mpfit procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

GAUSS1

[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.

   PEAK - if set then AREA is interpreted as the peak value rather
          than the area under the peak.

 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
   Correct bug in normalization, CM, 01 Nov 1999
   Optimized for speed, CM, 02 Nov 1999
   Added copyright notice, 25 Mar 2001, CM
   Added PEAK keyword, 30 Sep 2001, CM

  $Id: gauss1.pro,v 1.4 2001/10/13 17:41:48 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/gauss1.pro)


GAUSS1P

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

 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 (procedure).

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   GAUSS1, XVALS, [MEAN, SIGMA, AREA], YVALS, 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.

   YVALS - returns the array of Y-values.


 KEYWORD PARAMETERS:

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

 EXAMPLE:

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

   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:
   Transcribed from GAUSS1, 13 Dec 1999, CM
   Added copyright notice, 25 Mar 2001, CM

  $Id: gauss1p.pro,v 1.2 2001/03/25 18:55:12 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/gauss1p.pro)


GAUSS2

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

 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 = GAUSS2(X, Y, [XCENT, YCENT, SIGMA, PEAK])

 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 - 2-dimensional array of "X"-values.
   Y - 2-dimensional array of "Y"-values.

   XCENT - X-position of gaussian centroid.
   YCENT - Y-position of gaussian centroid.

   SIGMA - sigma of the curve (X and Y widths are the same).

   PEAK - the peak value of the gaussian function.

 RETURNS:

   Returns the array of Y-values.

 EXAMPLE:

   p = [2.2D, -0.7D, 1.4D, 3000.D]
   x = (dindgen(200)*0.1 - 10.) # (dblarr(200) + 1)
   y = (dblarr(200) + 1) # (dindgen(200)*0.1 - 10.)
   z = gauss2(x, y, p)

   Computes the values of the Gaussian at equispaced intervals in X
   and Y (spacing is 0.1).  The gaussian has a centroid position of
   (2.2, -0.7), standard deviation of 1.4, and peak value of 3000.

 REFERENCES:

 MODIFICATION HISTORY:
   Written, 02 Oct 1999, CM
   Added copyright notice, 25 Mar 2001, CM

  $Id: gauss2.pro,v 1.2 2001/03/25 18:55:13 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/gauss2.pro)


MPCHILIM

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

 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://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Compute confidence limits for chi-square statistic

 MAJOR TOPICS:
   Curve and Surface Fitting, Statistics

 CALLING SEQUENCE:
   DELCHI = MPCHILIM(PROB, DOF, [/SIGMA, /CLEVEL, /SLEVEL ])

 DESCRIPTION:

  The function MPCHILIM() computes confidence limits of the
  chi-square statistic for a desired probability level.  The returned
  values, DELCHI, are the limiting chi-squared values: a chi-squared
  value of greater than DELCHI will occur by chance with probability
  PROB:

    P_CHI(CHI > DELCHI; DOF) = PROB

  In specifying the probability level the user has three choices:

    * give the confidence level (default);

    * give the significance level (i.e., 1 - confidence level) and
      pass the /SLEVEL keyword; OR

    * give the "sigma" of the probability (i.e., compute the
      probability based on the normal distribution) and pass the
      /SIGMA keyword.

  Note that /SLEVEL, /CLEVEL and /SIGMA are mutually exclusive.

 INPUTS:

   PROB - scalar or vector number, giving the desired probability
          level as described above.

   DOF - scalar or vector number, giving the number of degrees of
         freedom in the chi-square distribution.

 RETURNS:

  Returns a scalar or vector of chi-square confidence limits.

 KEYWORD PARAMETERS:

   SLEVEL - if set, then PROB describes the significance level.

   CLEVEL - if set, then PROB describes the confidence level
            (default).

   SIGMA - if set, then PROB is the number of "sigma" away from the
           mean in the normal distribution.

 EXAMPLES:

   print, mpchilim(0.99d, 2d, /clevel)

   Print the 99% confidence limit for a chi-squared of 2 degrees of
   freedom.

   print, mpchilim(5d, 2d, /sigma)

   Print the "5 sigma" confidence limit for a chi-squared of 2
   degrees of freedom.  Here "5 sigma" indicates the gaussian
   probability of a 5 sigma event or greater. 
       P_GAUSS(5D) = 1D - 5.7330314e-07

 REFERENCES:

   Algorithms taken from CEPHES special function library, by Stephen
   Moshier. (http://www.netlib.org/cephes/)

 MODIFICATION HISTORY:
   Completed, 1999, CM
   Documented, 16 Nov 2001, CM
   Reduced obtrusiveness of common block and math error handling, 18
     Nov 2001, CM

  $Id: mpchilim.pro,v 1.4 2001/11/18 12:59:16 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/mpchilim.pro)


MPCHITEST

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

 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://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Compute the probability of a given chi-squared value

 MAJOR TOPICS:
   Curve and Surface Fitting, Statistics

 CALLING SEQUENCE:
   PROB = MPCHITEST(CHI, DOF, [/SIGMA, /CLEVEL, /SLEVEL ])

 DESCRIPTION:

  The function MPCHITEST() computes the probability for a value drawn
  from the chi-square distribution to equal or exceed the given value
  CHI.  This can be used for confidence testing of a measured value
  obeying the chi-squared distribution.

    P_CHI(X > CHI; DOF) = PROB

  In specifying the returned probability level the user has three
  choices:

    * return the confidence level when the /CLEVEL keyword is passed;
      OR

    * return the significance level (i.e., 1 - confidence level) when
      the /SLEVEL keyword is passed (default); OR

    * return the "sigma" of the probability (i.e., compute the
      probability based on the normal distribution) when the /SIGMA
      keyword is passed.

  Note that /SLEVEL, /CLEVEL and /SIGMA are mutually exclusive.

 INPUTS:

   CHI - chi-squared value to be tested.

   DOF - scalar or vector number, giving the number of degrees of
         freedom in the chi-square distribution.

 RETURNS:

  Returns a scalar or vector of probabilities, as described above,
  and according to the /SLEVEL, /CLEVEL and /SIGMA keywords.

 KEYWORD PARAMETERS:

   SLEVEL - if set, then PROB describes the significance level
            (default).

   CLEVEL - if set, then PROB describes the confidence level.

   SIGMA - if set, then PROB is the number of "sigma" away from the
           mean in the normal distribution.

 EXAMPLES:

   print, mpchitest(1300d,1252d)

   Print the probability for a chi-squared value with 1252 degrees of
   freedom to exceed a value of 1300, as a confidence level.

 REFERENCES:

   Algorithms taken from CEPHES special function library, by Stephen
   Moshier. (http://www.netlib.org/cephes/)

 MODIFICATION HISTORY:
   Completed, 1999, CM
   Documented, 16 Nov 2001, CM
   Reduced obtrusiveness of common block and math error handling, 18
     Nov 2001, CM

  $Id: mpchitest.pro,v 1.5 2001/11/18 12:59:16 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/mpchitest.pro)


MPCURVEFIT

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

 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://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Perform Levenberg-Marquardt least-squares fit (replaces CURVEFIT)

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   YFIT = MPCURVEFIT(X, Y, WEIGHTS, P, [SIGMA,] FUNCTION_NAME=FUNC, 
                     ITER=iter, ITMAX=itmax, 
                     CHISQ=chisq, NFREE=nfree, DOF=dof, 
                     NFEV=nfev, COVAR=covar, [/NOCOVAR, ] [/NODERIVATIVE, ]
                     FUNCTARGS=functargs, PARINFO=parinfo,
                     FTOL=ftol, XTOL=xtol, GTOL=gtol, TOL=tol,
                     ITERPROC=iterproc, ITERARGS=iterargs,
                     NPRINT=nprint, QUIET=quiet, 
                     ERRMSG=errmsg, STATUS=status)

 DESCRIPTION:

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

  Given the data and their uncertainties, MPCURVEFIT finds the best
  set of model parameters which match the data (in a least-squares
  sense) and returns them in the parameter P.  

  MPCURVEFIT returns the best fit function.
  
  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 weighting values ("WEIGHTS").
   - The name of an IDL function which computes Y given X ("FUNC").
   - Starting guesses for all of the parameters ("P").

  There are very few restrictions placed on X, Y or FUNCT.  Simply
  put, FUNCT 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.

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

  See below for an example of usage.
   
 USER FUNCTION

  The user must define a function which returns the model value.  For
  applications which use finite-difference derivatives -- the default
  -- the user function should be declared in the following way:

    PRO MYFUNCT, X, P, YMOD
     ; The independent variable is X
     ; Parameter values are passed in "P"
     YMOD = ... computed model values at X ...
    END

  The returned array YMOD must have the same dimensions and type as
  the "measured" Y values.

  User functions may also indicate a fatal error condition
  using the ERROR_CODE common block variable, as described
  below under the MPFIT_ERROR common block definition.

  See the discussion under "ANALYTIC DERIVATIVES" and AUTODERIVATIVE
  in MPFIT.PRO if you wish to compute the derivatives for yourself.
  AUTODERIVATIVE is accepted and passed directly to MPFIT.  The user
  function must accept one additional parameter, DP, which contains
  the derivative of the user function with respect to each parameter
  at each data point, as described in MPFIT.PRO.

 CONSTRAINING PARAMETER VALUES WITH THE PARINFO KEYWORD

  The behavior of MPFIT can be modified with respect to each
  parameter to be fitted.  A parameter value can be fixed; simple
  boundary constraints can be imposed; limitations on the parameter
  changes can be imposed; properties of the automatic derivative can
  be modified; and parameters can be tied to one another.

  These properties are governed by the PARINFO structure, which is
  passed as a keyword parameter 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 the START_PARAMS
              parameter for more information).
  
     .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 values of LIMITED.  Both LIMITED
               and LIMITS must be given together.
  
     .PARNAME - a string, giving the name of the parameter.  The
                fitting code of MPFIT does not use this tag in any
                way.  However, the default ITERPROC will print the
                parameter name if available.
  
     .STEP - the step size to be used in calculating the numerical
             derivatives.  If set to zero, then the step size is
             computed automatically.  Ignored when AUTODERIVATIVE=0.
             This value is superceded by the RELSTEP value.

     .RELSTEP - the *relative* step size to be used in calculating
                the numerical derivatives.  This number is the
                fractional size of the step, compared to the
                parameter value.  This value supercedes the STEP
                setting.  If the parameter is zero, then a default
                step size is chosen.

     .MPSIDE - the sidedness of the finite difference when computing
               numerical derivatives.  This field can take four
               values:

                  0 - one-sided derivative computed automatically
                  1 - one-sided derivative (f(x+h) - f(x)  )/h
                 -1 - one-sided derivative (f(x)   - f(x-h))/h
                  2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)

              Where H is the STEP parameter described above.  The
              "automatic" one-sided derivative method will chose a
              direction for the finite difference which does not
              violate any constraints.  The other methods do not
              perform this check.  The two-sided method is in
              principle more precise, but requires twice as many
              function evaluations.  Default: 0.

     .MPMAXSTEP - the maximum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will never be changed by more than this value in
                  one iteration.

                  A value of 0 indicates no maximum.  Default: 0.
  
     .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.
             [ NOTE: the PARNAME can't be used in expressions. ]

     .MPPRINT - if set to 1, then the default ITERPROC will print the
                parameter value.  If set to 0, the parameter value
                will not be printed.  This tag can be used to
                selectively print only a few parameter values out of
                many.  Default: 1 (all parameters printed)

  
  Future modifications to the PARINFO structure, if any, will involve
  adding structure tags beginning with the two letters "MP".
  Therefore programmers are urged to avoid using tags starting with
  the same letters; otherwise they are free to include their own
  fields within the PARINFO structure, and they will be ignored.
  
  PARINFO 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.

 INPUTS:
   X - Array of independent variable values.

   Y - Array of "measured" dependent variable values.  Y should have
       the same data type as X.  The function FUNCT should map
       X->Y.

   WEIGHTS - Array of weights to be used in calculating the
             chi-squared value.  If WEIGHTS is specified then the ERR
             parameter is ignored.  The chi-squared value is computed
             as follows:

                CHISQ = TOTAL( (Y-FUNCT(X,P))^2 * ABS(WEIGHTS) )

             Here are common values of WEIGHTS:

                1D/ERR^2 - Normal weighting (ERR is the measurement error)
                1D/Y     - Poisson weighting (counting statistics)
                1D       - Unweighted

   P - 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).

       Upon successful completion the new parameter values are
       returned in P.

       If both START_PARAMS and PARINFO are passed, then the starting
       *value* is taken from START_PARAMS, but the *constraints* are
       taken from PARINFO.
 
   SIGMA - 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.

           If the fit is unweighted (i.e. no errors were given, or
           the weights were uniformly set to unity), then SIGMA will
           probably not represent the true parameter uncertainties.

           *If* you can assume that the true reduced chi-squared
           value is unity -- meaning that the fit is implicitly
           assumed to be of good quality -- then the estimated
           parameter uncertainties can be computed by scaling SIGMA
           by the measured chi-squared value.

              DOF     = N_ELEMENTS(X) - N_ELEMENTS(P) ; deg of freedom
              CSIGMA  = SIGMA * SQRT(CHISQ / DOF)     ; scaled uncertainties

 RETURNS:

   Returns the array containing the best-fitting function.

 KEYWORD PARAMETERS:

   CHISQ - the value of the summed, squared, weighted residuals for
           the returned parameter values, i.e. the chi-square value.

   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.

   DOF - number of degrees of freedom, computed as
             DOF = N_ELEMENTS(DEVIATES) - NFREE
         Note that this doesn't account for pegged parameters (see
         NPEGGED).

   ERRMSG - a string error or warning message is returned.

   FTOL - a nonnegative input variable. Termination occurs when both
          the actual and predicted relative reductions in the sum of
          squares are at most FTOL (and STATUS is accordingly set to
          1 or 3).  Therefore, FTOL measures the relative error
          desired in the sum of squares.  Default: 1D-10

   FUNCTION_NAME - a scalar string containing the name of an IDL
                   procedure to compute the user model values, as
                   described above in the "USER MODEL" section.

   FUNCTARGS - A structure which contains the parameters to be passed
               to the user-supplied function specified by FUNCT 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.

   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 (and STATUS is
          accordingly set to 4). Therefore, GTOL measures the
          orthogonality desired between the function vector and the
          columns of the jacobian.  Default: 1D-10

   ITER - the number of iterations completed.

   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.

   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, FUNCT, 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.
          
              FUNCT 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 FUNCT.  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
              common block variable ERROR_CODE to negative value (see
              MPFIT_ERROR common block below).  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.

   ITMAX - 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

   NFEV - the number of FUNCT function evaluations performed.

   NFREE - the number of free parameters in the fit.  This includes
           parameters which are not FIXED and not TIED, but it does
           include parameters which are pegged at LIMITS.

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

   NODERIVATIVE - if set, then the user function will not be queried
                  for analytical derivatives, and instead the
                  derivatives will be computed by finite differences
                  (and according to the PARINFO derivative settings;
                  see above for a description).

   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.  Note that
            several Levenberg-Marquardt attempts can be made in a
            single iteration.
            Default value: 1

   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.  Values in PARINFO are never 
             modified during a call to MPFIT.

             See description above for the structure of PARINFO.

             Default value:  all parameters are free and unconstrained.

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

   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.

   TOL - synonym for FTOL.  Use FTOL instead.

   XTOL - a nonnegative input variable. Termination occurs when the
          relative error between two consecutive iterates is at most
          XTOL (and STATUS is accordingly set to 2 or 3).  Therefore,
          XTOL measures the relative error desired in the approximate
          solution.  Default: 1D-10

   YERROR - upon return, the root-mean-square variance of the
            residuals.


 EXAMPLE:

   ; First, generate some synthetic data
   npts = 200
   x  = dindgen(npts) * 0.1 - 10.                  ; Independent variable 
   yi = gauss1(x, [2.2D, 1.4, 3000.])              ; "Ideal" Y variable
   y  = yi + randomn(seed, npts) * 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
   yfit = mpcurvefit(x, y, 1/sy^2, p0, $
                   FUNCTION_NAME='GAUSS1P')        ; 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.  GAUSS1 and GAUSS1P are
   available from the same web page.


 COMMON BLOCKS:

   COMMON MPFIT_ERROR, ERROR_CODE

     User routines may stop the fitting process at any time by
     setting an error condition.  This condition may be set in either
     the user's model computation routine (MYFUNCT), or in the
     iteration procedure (ITERPROC).

     To stop the fitting, the above common block must be declared,
     and ERROR_CODE must be set to a negative number.  After the user
     procedure or function returns, MPFIT checks the value of this
     common block variable and exits immediately if the error
     condition has been set.  By default the value of ERROR_CODE is
     zero, indicating a successful function/procedure call.

 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 MPFITFUN, 25 Sep 1999, CM
   Alphabetized documented keywords, 02 Oct 1999, CM
   Added QUERY keyword and query checking of MPFIT, 29 Oct 1999, CM
   Check to be sure that X and Y are present, 02 Nov 1999, CM
   Documented SIGMA for unweighted fits, 03 Nov 1999, CM
   Changed to ERROR_CODE for error condition, 28 Jan 2000, CM
   Copying permission terms have been liberalized, 26 Mar 2000, CM
   Propagated improvements from MPFIT, 17 Dec 2000, CM
   Corrected behavior of NODERIVATIVE, 13 May 2002, CM
   Documented RELSTEP field of PARINFO (!!), CM, 25 Oct 2002
   Make more consistent with comparable IDL routines, 30 Jun 2003, CM
   Minor documentation adjustment, 03 Feb 2004, CM

  $Id: mpcurvefit.pro,v 1.6 2004/02/26 04:18:16 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/mpcurvefit.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://cow.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.  MPFIT is
  based upon MINPACK-1 (LMDIF.F) by More' and collaborators.

  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.  You are
  recommended to use the convenience functions MPFITFUN and
  MPFITEXPR, which are driver functions that 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.

  Simple constraints can be placed on parameter values by using the
  PARINFO keyword to MPFIT.  See below for a description of this
  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.

 USER FUNCTION

  The user must define a function which returns the appropriate
  values as specified above.  The function should return the weighted
  deviations between the model and the data.  For applications which
  use finite-difference derivatives -- the default -- the user
  function should be declared in the following way:

    FUNCTION MYFUNCT, p, X=x, Y=y, ERR=err
     ; Parameter values are passed in "p"
     model = F(x, p)
     return, (y-model)/err
    END

  See below for applications with analytical derivatives.

  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.  The function *must*
  accept a parameter list, P.
  
  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.

  User functions may also indicate a fatal error condition using the
  ERROR_CODE common block variable, as described below under the
  MPFIT_ERROR common block definition (by setting ERROR_CODE to a
  number between -15 and -1).

 ANALYTIC DERIVATIVES
 
  In the search for the best-fit solution, MPFIT by default
  calculates derivatives numerically via a finite difference
  approximation.  The user-supplied function need not calculate the
  derivatives explicitly.  However, if you desire to compute them
  analytically, then the AUTODERIVATIVE=0 keyword must be passed.  As
  a practical matter, it is often sufficient and even faster to allow
  MPFIT to calculate the derivatives numerically, and so
  AUTODERIVATIVE=0 is not necessary.

  Also, the user function must be declared with one additional
  parameter, as follows:

    FUNCTION MYFUNCT, p, dp, X=x, Y=y, ERR=err
     model = F(x, p)
     
     if n_params() GT 1 then begin
       ; Compute derivatives
       dp = make_array(n_elements(x), n_elements(p), value=x(0)*0)
       for i = 0, n_elements(p)-1 do $
         dp(*,i) = FGRAD(x, p, i)
     endif
    
     return, (y-model)/err
    END

  where FGRAD(x, p, i) is a user function which must compute the
  derivative of the model with respect to parameter P(i) at X.  When
  finite differencing is used for computing derivatives (ie, when
  AUTODERIVATIVE=1), the parameter DP is not passed.  Therefore
  functions can use N_PARAMS() to indicate whether they must compute
  the derivatives or not.

  Derivatives should be returned in the DP array. 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.  Upon
  input to the user function, DP is set to a vector with the same
  length as P, with a value of 1 for a parameter which is free, and a
  value of zero for a parameter which is fixed (and hence no
  derivative needs to be calculated).  This input vector may be
  overwritten as needed.

  If the data is higher than one dimensional, then the *last*
  dimension should be the parameter dimension.  Example: fitting a
  50x50 image, "dp" should be 50x50xNPAR.
  
 CONSTRAINING PARAMETER VALUES WITH THE PARINFO KEYWORD

  The behavior of MPFIT can be modified with respect to each
  parameter to be fitted.  A parameter value can be fixed; simple
  boundary constraints can be imposed; limitations on the parameter
  changes can be imposed; properties of the automatic derivative can
  be modified; and parameters can be tied to one another.

  These properties are governed by the PARINFO structure, which is
  passed as a keyword parameter 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 the START_PARAMS
              parameter for more information).
  
     .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 values of LIMITED.  Both LIMITED
               and LIMITS must be given together.
  
     .PARNAME - a string, giving the name of the parameter.  The
                fitting code of MPFIT does not use this tag in any
                way.  However, the default ITERPROC will print the
                parameter name if available.
  
     .STEP - the step size to be used in calculating the numerical
             derivatives.  If set to zero, then the step size is
             computed automatically.  Ignored when AUTODERIVATIVE=0.
             This value is superceded by the RELSTEP value.

     .RELSTEP - the *relative* step size to be used in calculating
                the numerical derivatives.  This number is the
                fractional size of the step, compared to the
                parameter value.  This value supercedes the STEP
                setting.  If the parameter is zero, then a default
                step size is chosen.

     .MPSIDE - the sidedness of the finite difference when computing
               numerical derivatives.  This field can take four
               values:

                  0 - one-sided derivative computed automatically
                  1 - one-sided derivative (f(x+h) - f(x)  )/h
                 -1 - one-sided derivative (f(x)   - f(x-h))/h
                  2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)

              Where H is the STEP parameter described above.  The
              "automatic" one-sided derivative method will chose a
              direction for the finite difference which does not
              violate any constraints.  The other methods do not
              perform this check.  The two-sided method is in
              principle more precise, but requires twice as many
              function evaluations.  Default: 0.

     .MPMAXSTEP - the maximum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will never be changed by more than this value in
                  one iteration.

                  A value of 0 indicates no maximum.  Default: 0.
  
     .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.
             [ NOTE: the PARNAME can't be used in expressions. ]

     .MPPRINT - if set to 1, then the default ITERPROC will print the
                parameter value.  If set to 0, the parameter value
                will not be printed.  This tag can be used to
                selectively print only a few parameter values out of
                many.  Default: 1 (all parameters printed)

     .MPFORMAT - IDL format string to print the parameter within
                 ITERPROC.  Default: '(G20.6)' An empty string will
                 also use the default.

  
  Future modifications to the PARINFO structure, if any, will involve
  adding structure tags beginning with the two letters "MP".
  Therefore programmers are urged to avoid using tags starting with
  the same letters; otherwise they are free to include their own
  fields within the PARINFO structure, and they will be ignored.
  
  PARINFO 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.


 HARD-TO-COMPUTE FUNCTIONS: "EXTERNAL" EVALUATION

  The normal mode of operation for MPFIT is for the user to pass a
  function name, and MPFIT will call the user function multiple times
  as it iterates toward a solution.

  Some user functions are particularly hard to compute using the
  standard model of MPFIT.  Usually these are functions that depend
  on a large amount of external data, and so it is not feasible, or
  at least highly impractical, to have MPFIT call it.  In those cases
  it may be possible to use the "(EXTERNAL)" evaluation option.

  In this case the user is responsible for making all function *and
  derivative* evaluations.  The function and Jacobian data are passed
  in through the EXTERNAL_FVEC and EXTERNAL_FJAC keywords,
  respectively.  The user indicates the selection of this option by
  specifying a function name (MYFUNCT) of "(EXTERNAL)".  No
  user-function calls are made when EXTERNAL evaluation is being
  used.

  At the end of each iteration, control returns to the user, who must
  reevaluate the function at its new parameter values.  Users should
  check the return value of the STATUS keyword, where a value of 9
  indicates the user should supply more data for the next iteration,
  and re-call MPFIT.  The user may refrain from calling MPFIT
  further; as usual, STATUS will indicate when the solution has
  converged and no more iterations are required.

  Because MPFIT must maintain its own data structures between calls,
  the user must also pass a named variable to the EXTERNAL_STATE
  keyword.  This variable must be maintained by the user, but not
  changed, throughout the fitting process.  When no more iterations
  are desired, the named variable may be discarded.


 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, as described
             above.

             For EXTERNAL evaluation of functions, this parameter
             should be set to a value of "(EXTERNAL)".

   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 (but see PARINFO).  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.
 
 RETURNS:

   Returns the array of best-fit parameters.


 KEYWORD PARAMETERS:

   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

   BESTNORM - the value of the summed squared weighted residuals for
              the returned parameter values, i.e. TOTAL(DEVIATES^2).

   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 example:
           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.

   DOF - number of degrees of freedom, computed as
             DOF = N_ELEMENTS(DEVIATES) - NFREE
         Note that this doesn't account for pegged parameters (see
         NPEGGED).

   ERRMSG - a string error or warning message is returned.

   EXTERNAL_FVEC - upon input, the function values, evaluated at
                   START_PARAMS.  This should be an M-vector, where M
                   is the number of data points.

   EXTERNAL_FJAC - upon input, the Jacobian array of partial
                   derivative values.  This should be a M x N array,
                   where M is the number of data points and N is the
                   number of parameters.  NOTE: that all FIXED or
                   TIED parameters must *not* be included in this
                   array.

   EXTERNAL_STATE - a named variable to store MPFIT-related state
                    information between iterations (used in input and
                    output to MPFIT).  The user must not manipulate
                    or discard this data until the final iteration is
                    performed.

   FASTNORM - set this keyword to select a faster algorithm to
              compute sum-of-square values internally.  For systems
              with large numbers of data points, the standard
              algorithm can become prohibitively slow because it
              cannot be vectorized well.  By setting this keyword,
              MPFIT will run faster, but it will be more prone to
              floating point overflows and underflows.  Thus, setting
              this keyword may sacrifice some stability in the
              fitting process.
              
   FTOL - a nonnegative input variable. Termination occurs when both
          the actual and predicted relative reductions in the sum of
          squares are at most FTOL (and STATUS is accordingly set to
          1 or 3).  Therefore, FTOL measures the relative error
          desired in the sum of squares.  Default: 1D-10

   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, but your function should
               accept *at least* one keyword parameter.  [ This is to
               accomodate a limitation in IDL's _EXTRA
               parameter-passing mechanism. ]

   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 (and STATUS is
          accordingly set to 4). Therefore, GTOL measures the
          orthogonality desired between the function vector and the
          columns of the jacobian.  Default: 1D-10

   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.

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

              PRO ITERPROC, MYFUNCT, p, iter, fnorm, FUNCTARGS=fcnargs, $
                PARINFO=parinfo, QUIET=quiet, DOF=dof, ...
                ; 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.  DOF is the number of degrees of freedom,
              normally the number of points less the number of free
              parameters.  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
              common block variable ERROR_CODE to negative value
              between -15 and -1 (see MPFIT_ERROR common block
              below).  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.

   ITERSTOP - Set this keyword if you wish to be able to stop the
              fitting by hitting the predefined ITERKEYSTOP key on
              the keyboard.  This only works if you use the default
              ITERPROC.

   ITERKEYSTOP - A keyboard key which will halt the fit (and if
                 ITERSTOP is set and the default ITERPROC is used).
                 ITERSTOPKEY may either be a one-character string
                 with the desired key, or a scalar integer giving the
                 ASCII code of the desired key.  
                 Default: 7b (control-g)

                 NOTE: the default value of ASCI 7 (control-G) cannot
                 be read in some windowing environments, so you must
                 change to a printable character like 'q'.

   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

   NFEV - the number of MYFUNCT function evaluations performed.

   NFREE - the number of free parameters in the fit.  This includes
           parameters which are not FIXED and not TIED, but it does
           include parameters which are pegged at LIMITS.

   NITER - the number of iterations completed.

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

   NPEGGED - the number of free parameters which are pegged at a
             LIMIT.

   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.  Be aware
            that several Levenberg-Marquardt attempts can be made in
            a single iteration.  Also, the ITERPROC is *always*
            called for the final iteration, regardless of the
            iteration number.
            Default value: 1

   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.  Values in PARINFO are never 
             modified during a call to MPFIT.

             See description above for the structure of PARINFO.

             Default value:  all parameters are free and unconstrained.

   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.

            If the fit is unweighted (i.e. no errors were given, or
            the weights were uniformly set to unity), then PERROR
            will probably not represent the true parameter
            uncertainties.  

            *If* you can assume that the true reduced chi-squared
            value is unity -- meaning that the fit is implicitly
            assumed to be of good quality -- then the estimated
            parameter uncertainties can be computed by scaling PERROR
            by the measured chi-squared value.

              DOF     = N_ELEMENTS(X) - N_ELEMENTS(PARMS) ; deg of freedom
              PCERROR = PERROR * SQRT(BESTNORM / DOF)   ; scaled uncertainties

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

   RESDAMP - a scalar number, indicating the cut-off value of
             residuals where "damping" will occur.  Residuals with
             magnitudes greater than this number will be replaced by
             their logarithm.  This partially mitigates the so-called
             large residual problem inherent in least-squares solvers
             (as for the test problem CURVI, http://www.maxthis.com/-
             curviex.htm).  A value of 0 indicates no damping.
             Default: 0

             Note: RESDAMP doesn't work with AUTODERIV=0

   STATUS - an integer status code is returned.  All values greater
            than zero can represent success (however STATUS EQ 5 may
            indicate failure to converge).  It can have one of the
            following values:

        -16  a parameter or function value has become infinite or an
             undefined number.  This is usually a consequence of
             numerical overflow in the user's model function, which
             must be avoided.

        -15 to -1 
             these are error codes that either MYFUNCT or ITERPROC
             may return to terminate the fitting process (see
             description of MPFIT_ERROR common below).  If either
             MYFUNCT or ITERPROC set ERROR_CODE to a negative number,
             then that number is returned in STATUS.  Values from -15
             to -1 are reserved for the user functions and will not
             clash with MPFIT.

	   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.

          9  A successful single iteration has been completed, and
             the user must supply another "EXTERNAL" evaluation of
             the function and its derivatives.  This status indicator
             is neither an error nor a convergence indicator.

   XTOL - a nonnegative input variable. Termination occurs when the
          relative error between two consecutive iterates is at most
          XTOL (and STATUS is accordingly set to 2 or 3).  Therefore,
          XTOL measures the relative error desired in the approximate
          solution.  Default: 1D-10


 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.


 COMMON BLOCKS:

   COMMON MPFIT_ERROR, ERROR_CODE

     User routines may stop the fitting process at any time by
     setting an error condition.  This condition may be set in either
     the user's model computation routine (MYFUNCT), or in the
     iteration procedure (ITERPROC).

     To stop the fitting, the above common block must be declared,
     and ERROR_CODE must be set to a negative number.  After the user
     procedure or function returns, MPFIT checks the value of this
     common block variable and exits immediately if the error
     condition has been set.  This value is also returned in the
     STATUS keyword: values of -1 through -15 are reserved error
     codes for the user routines.  By default the value of ERROR_CODE
     is zero, indicating a successful function/procedure call.

   COMMON MPFIT_PROFILE
   COMMON MPFIT_MACHAR
   COMMON MPFIT_CONFIG

     These are undocumented common blocks are used internally by
     MPFIT and may change in future implementations.

 THEORY OF OPERATION:

   There are many specific strategies for function minimization.  One
   very popular technique is to use function gradient information to
   realize the local structure of the function.  Near a local minimum
   the function value can be taylor expanded about x0 as follows:

      f(x) = f(x0) + f'(x0) . (x-x0) + (1/2) (x-x0) . f''(x0) . (x-x0)
             -----   ---------------   -------------------------------  (1)
     Order    0th          1st                      2nd

   Here f'(x) is the gradient vector of f at x, and f''(x) is the
   Hessian matrix of second derivatives of f at x.  The vector x is
   the set of function parameters, not the measured data vector.  One
   can find the minimum of f, f(xm) using Newton's method, and
   arrives at the following linear equation:

      f''(x0) . (xm-x0) = - f'(x0)                            (2)

   If an inverse can be found for f''(x0) then one can solve for
   (xm-x0), the step vector from the current position x0 to the new
   projected minimum.  Here the problem has been linearized (ie, the
   gradient information is known to first order).  f''(x0) is
   symmetric n x n matrix, and should be positive definite.

   The Levenberg - Marquardt technique is a variation on this theme.
   It adds an additional diagonal term to the equation which may aid the
   convergence properties:

      (f''(x0) + nu I) . (xm-x0) = -f'(x0)                  (2a)

   where I is the identity matrix.  When nu is large, the overall
   matrix is diagonally dominant, and the iterations follow steepest
   descent.  When nu is small, the iterations are quadratically
   convergent.

   In principle, if f''(x0) and f'(x0) are known then xm-x0 can be
   determined.  However the Hessian matrix is often difficult or
   impossible to compute.  The gradient f'(x0) may be easier to
   compute, if even by finite difference techniques.  So-called
   quasi-Newton techniques attempt to successively estimate f''(x0)
   by building up gradient information as the iterations proceed.

   In the least squares problem there are further simplifications
   which assist in solving eqn (2).  The function to be minimized is
   a sum of squares:

       f = Sum(hi^2)                                         (3)

   where hi is the ith residual out of m residuals as described
   above.  This can be substituted back into eqn (2) after computing
   the derivatives:

       f'  = 2 Sum(hi  hi')     
       f'' = 2 Sum(hi' hj') + 2 Sum(hi hi'')                (4)

   If one assumes that the parameters are already close enough to a
   minimum, then one typically finds that the second term in f'' is
   negligible [or, in any case, is too difficult to compute].  Thus,
   equation (2) can be solved, at least approximately, using only
   gradient information.

   In matrix notation, the combination of eqns (2) and (4) becomes:

        hT' . h' . dx = - hT' . h                          (5)

   Where h is the residual vector (length m), hT is its transpose, h'
   is the Jacobian matrix (dimensions n x m), and dx is (xm-x0).  The
   user function supplies the residual vector h, and in some cases h'
   when it is not found by finite differences (see MPFIT_FDJAC2,
   which finds h and hT').  Even if dx is not the best absolute step
   to take, it does provide a good estimate of the best *direction*,
   so often a line minimization will occur along the dx vector
   direction.

   The method of solution employed by MINPACK is to form the Q . R
   factorization of h', where Q is an orthogonal matrix such that QT .
   Q = I, and R is upper right triangular.  Using h' = Q . R and the
   ortogonality of Q, eqn (5) becomes

        (RT . QT) . (Q . R) . dx = - (RT . QT) . h
                     RT . R . dx = - RT . QT . h         (6)
                          R . dx = - QT . h

   where the last statement follows because R is upper triangular.
   Here, R, QT and h are known so this is a matter of solving for dx.
   The routine MPFIT_QRFAC provides the QR factorization of h, with
   pivoting, and MPFIT_QRSOLV provides the solution for dx.
   
 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.
   More', Jorge J., "The Levenberg-Marquardt Algorithm:
     Implementation and Theory," in *Numerical Analysis*, ed. Watson,
     G. A., Lecture Notes in Mathematics 630, Springer-Verlag, 1977.

 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
   Fixed bug when AUTDERIVATIVE=0.  Incorrect sign, 02 Feb 1999 CM
   Added keyboard stop to MPFIT_DEFITER, 28 Feb 1999 CM
   Cosmetic documentation changes, 14 May 1999 CM
   IDL optimizations for speed & FASTNORM keyword, 15 May 1999 CM
   Tried a faster version of mpfit_enorm, 30 May 1999 CM
   Changed web address to cow.physics.wisc.edu, 14 Jun 1999 CM
   Found malformation of FDJAC in MPFIT for 1 parm, 03 Aug 1999 CM
   Factored out user-function call into MPFIT_CALL.  It is possible,
     but currently disabled, to call procedures.  The calling format
     is similar to CURVEFIT, 25 Sep 1999, CM
   Slightly changed mpfit_tie to be less intrusive, 25 Sep 1999, CM
   Fixed some bugs associated with tied parameters in mpfit_fdjac, 25
     Sep 1999, CM
   Reordered documentation; now alphabetical, 02 Oct 1999, CM
   Added QUERY keyword for more robust error detection in drivers, 29
     Oct 1999, CM
   Documented PERROR for unweighted fits, 03 Nov 1999, CM
   Split out MPFIT_RESETPROF to aid in profiling, 03 Nov 1999, CM
   Some profiling and speed optimization, 03 Nov 1999, CM
     Worst offenders, in order: fdjac2, qrfac, qrsolv, enorm.
     fdjac2 depends on user function, qrfac and enorm seem to be
     fully optimized.  qrsolv probably could be tweaked a little, but
     is still <10% of total compute time.
   Made sure that !err was set to 0 in MPFIT_DEFITER, 10 Jan 2000, CM
   Fixed small inconsistency in setting of QANYLIM, 28 Jan 2000, CM
   Added PARINFO field RELSTEP, 28 Jan 2000, CM
   Converted to MPFIT_ERROR common block for indicating error
     conditions, 28 Jan 2000, CM
   Corrected scope of MPFIT_ERROR common block, CM, 07 Mar 2000
   Minor speed improvement in MPFIT_ENORM, CM 26 Mar 2000
   Corrected case where ITERPROC changed parameter values and
     parameter values were TIED, CM 26 Mar 2000
   Changed MPFIT_CALL to modify NFEV automatically, and to support
     user procedures more, CM 26 Mar 2000
   Copying permission terms have been liberalized, 26 Mar 2000, CM
   Catch zero value of zero a(j,lj) in MPFIT_QRFAC, 20 Jul 2000, CM
      (thanks to David Schlegel )
   MPFIT_SETMACHAR is called only once at init; only one common block
     is created (MPFIT_MACHAR); it is now a structure; removed almost
     all CHECK_MATH calls for compatibility with IDL5 and !EXCEPT;
     profiling data is now in a structure too; noted some
     mathematical discrepancies in Linux IDL5.0, 17 Nov 2000, CM
   Some significant changes.  New PARINFO fields: MPSIDE, MPMINSTEP,
     MPMAXSTEP.  Improved documentation.  Now PTIED constraints are
     maintained in the MPCONFIG common block.  A new procedure to
     parse PARINFO fields.  FDJAC2 now computes a larger variety of
     one-sided and two-sided finite difference derivatives.  NFEV is
     stored in the MPCONFIG common now.  17 Dec 2000, CM
   Added check that PARINFO and XALL have same size, 29 Dec 2000 CM
   Don't call function in TERMINATE when there is an error, 05 Jan
     2000
   Check for float vs. double discrepancies; corrected implementation
     of MIN/MAXSTEP, which I still am not sure of, but now at least
     the correct behavior occurs *without* it, CM 08 Jan 2001
   Added SCALE_FCN keyword, to allow for scaling, as for the CASH
     statistic; added documentation about the theory of operation,
     and under the QR factorization; slowly I'm beginning to
     understand the bowels of this algorithm, CM 10 Jan 2001
   Remove MPMINSTEP field of PARINFO, for now at least, CM 11 Jan
     2001
   Added RESDAMP keyword, CM, 14 Jan 2001
   Tried to improve the DAMP handling a little, CM, 13 Mar 2001
   Corrected .PARNAME behavior in _DEFITER, CM, 19 Mar 2001
   Added checks for parameter and function overflow; a new STATUS
     value to reflect this; STATUS values of -15 to -1 are reserved
     for user function errors, CM, 03 Apr 2001
   DAMP keyword is now a TANH, CM, 03 Apr 2001
   Added more error checking of float vs. double, CM, 07 Apr 2001
   Fixed bug in handling of parameter lower limits; moved overflow
     checking to end of loop, CM, 20 Apr 2001
   Failure using GOTO, TERMINATE more graceful if FNORM1 not defined,
     CM, 13 Aug 2001
   Add MPPRINT tag to PARINFO, CM, 19 Nov 2001
   Add DOF keyword to DEFITER procedure, and print degrees of
     freedom, CM, 28 Nov 2001
   Add check to be sure MYFUNCT is a scalar string, CM, 14 Jan 2002
   Addition of EXTERNAL_FJAC, EXTERNAL_FVEC keywords; ability to save
     fitter's state from one call to the next; allow '(EXTERNAL)'
     function name, which implies that user will supply function and
     Jacobian at each iteration, CM, 10 Mar 2002
   Documented EXTERNAL evaluation code, CM, 10 Mar 2002
   Corrected signficant bug in the way that the STEP parameter, and
     FIXED parameters interacted (Thanks Andrew Steffl), CM, 02 Apr
     2002
   Allow COVAR and PERROR keywords to be computed, even in case of
     '(EXTERNAL)' function, 26 May 2002
   Add NFREE and NPEGGED keywords; compute NPEGGED; compute DOF using
     NFREE instead of n_elements(X), thanks to Kristian Kjaer, CM 11
     Sep 2002
   Hopefully PERROR is all positive now, CM 13 Sep 2002
   Documented RELSTEP field of PARINFO (!!), CM, 25 Oct 2002
   Error checking to detect missing start pars, CM 12 Apr 2003
   Add DOF keyword to return degrees of freedom, CM, 30 June 2003
   Always call ITERPROC in the final iteration; add ITERKEYSTOP
     keyword, CM, 30 June 2003
   Correct bug in MPFIT_LMPAR of singularity handling, which might
     likely be fatal for one-parameter fits, CM, 21 Nov 2003
     (with thanks to Peter Tuthill for the proper test case)
   Minor documentation adjustment, 03 Feb 2004, CM
   Correct small error in QR factorization when pivoting; document
     the return values of QRFAC when pivoting, 21 May 2004, CM
   Add MPFORMAT field to PARINFO, and correct behavior of interaction
     between MPPRINT and PARNAME in MPFIT_DEFITERPROC (thanks to Tim
     Robishaw), 23 May 2004, CM

  $Id: mpfit.pro,v 1.33 2004/05/23 07:36:21 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/mpfit.pro)


MPFIT2DFUN

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

 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://cow.physics.wisc.edu/~craigm/idl/idl.html

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

 MAJOR TOPICS:
   Curve and Surface Fitting

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

 DESCRIPTION:

  MPFIT2DFUN fits a user-supplied model -- in the form of an IDL
  function -- to a set of user-supplied data.  MPFIT2DFUN calls
  MPFIT, the MINPACK-1 least-squares minimizer, to do the main
  work.  MPFIT2DFUN is a specialized version for two-dimensional 
  data.

  Given the data and their uncertainties, MPFIT2DFUN 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:
   - Two arrays of independent variable values ("X", "Y").
   - An array of "measured" *dependent* variable values ("Z").
   - An array of "measured" 1-sigma uncertainty values ("ERR").
   - The name of an IDL function which computes Z given (X,Y) ("MYFUNCT").
   - Starting guesses for all of the parameters ("START_PARAMS").

  There are very few restrictions placed on X, Y, Z, or MYFUNCT.
  Simply put, MYFUNCT must map the (X,Y) values into Z values given
  the model parameters.  The (X,Y) values are usually the independent
  X and Y coordinate positions in the two dimensional plane, but need
  not be.

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

  See below for an example of usage.
   
 USER FUNCTION

  The user must define a function which returns the model value.  For
  applications which use finite-difference derivatives -- the default
  -- the user function should be declared in the following way:

    FUNCTION MYFUNCT, X, Y, P
     ; The independent variables are X and Y
     ; Parameter values are passed in "P"
     ZMOD = ... computed model values at (X,Y) ...
     return, ZMOD
    END

  The returned array YMOD must have the same dimensions and type as
  the "measured" Z values.

  User functions may also indicate a fatal error condition
  using the ERROR_CODE common block variable, as described
  below under the MPFIT_ERROR common block definition.

  See the discussion under "ANALYTIC DERIVATIVES" and AUTODERIVATIVE
  in MPFIT.PRO if you wish to compute the derivatives for yourself.
  AUTODERIVATIVE is accepted and passed directly to MPFIT.  The user
  function must accept one additional parameter, DP, which contains
  the derivative of the user function with respect to each parameter
  at each data point, as described in MPFIT.PRO.

 CREATING APPROPRIATELY DIMENSIONED INDEPENDENT VARIABLES

  The user must supply appropriate independent variables to
  MPFIT2DFUN.  For image fitting applications, this variable should
  be two-dimensional *arrays* describing the X and Y positions of
  every *pixel*.  [ Thus any two dimensional sampling is permitted,
  including irregular sampling. ]
  
  If the sampling is regular, then the x coordinates are the same for
  each row, and the y coordinates are the same for each column.  Call
  the x-row and y-column coordinates XR and YC respectively.  You can
  then compute X and Y as follows:
  
      X = XR # (YC*0 + 1)             eqn. 1
      Y = (XR*0 + 1) # YC             eqn. 2
  
  For example, if XR and YC have the following values:
  
    XR = [  1, 2, 3, 4, 5,]  ;; X positions of one row of pixels
    YC = [ 15,16,17 ]        ;; Y positions of one column of
                                pixels
  
  Then using equations 1 and 2 above will give these values to X and
  Y:
  
     X :  1  2  3  4  5       ;; X positions of all pixels
          1  2  3  4  5
          1  2  3  4  5
  
     Y : 15 15 15 15 15       ;; Y positions of all pixels
         16 16 16 16 16
         17 17 17 17 17
  
  Using the above technique is suggested, but *not* required.  You
  can do anything you wish with the X and Y values.  This technique
  only makes it easier to compute your model function values.

 CONSTRAINING PARAMETER VALUES WITH THE PARINFO KEYWORD

  The behavior of MPFIT can be modified with respect to each
  parameter to be fitted.  A parameter value can be fixed; simple
  boundary constraints can be imposed; limitations on the parameter
  changes can be imposed; properties of the automatic derivative can
  be modified; and parameters can be tied to one another.

  These properties are governed by the PARINFO structure, which is
  passed as a keyword parameter 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 the START_PARAMS
              parameter for more information).
  
     .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 values of LIMITED.  Both LIMITED
               and LIMITS must be given together.
  
     .PARNAME - a string, giving the name of the parameter.  The
                fitting code of MPFIT does not use this tag in any
                way.  However, the default ITERPROC will print the
                parameter name if available.
  
     .STEP - the step size to be used in calculating the numerical
             derivatives.  If set to zero, then the step size is
             computed automatically.  Ignored when AUTODERIVATIVE=0.
             This value is superceded by the RELSTEP value.

     .RELSTEP - the *relative* step size to be used in calculating
                the numerical derivatives.  This number is the
                fractional size of the step, compared to the
                parameter value.  This value supercedes the STEP
                setting.  If the parameter is zero, then a default
                step size is chosen.

     .MPSIDE - the sidedness of the finite difference when computing
               numerical derivatives.  This field can take four
               values:

                  0 - one-sided derivative computed automatically
                  1 - one-sided derivative (f(x+h) - f(x)  )/h
                 -1 - one-sided derivative (f(x)   - f(x-h))/h
                  2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)

              Where H is the STEP parameter described above.  The
              "automatic" one-sided derivative method will chose a
              direction for the finite difference which does not
              violate any constraints.  The other methods do not
              perform this check.  The two-sided method is in
              principle more precise, but requires twice as many
              function evaluations.  Default: 0.

     .MPMINSTEP - the minimum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will be changed by multiples of this value.  The
                  actual step is computed as:

                     DELTA1 = MPMINSTEP*ROUND(DELTA0/MPMINSTEP)

                  where DELTA0 and DELTA1 are the estimated parameter
                  changes before and after this constraint is
                  applied.  Note that this constraint should be used
                  with care since it may cause non-converging,
                  oscillating solutions.

                  A value of 0 indicates no minimum.  Default: 0.

     .MPMAXSTEP - the maximum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will never be changed by more than this value.

                  A value of 0 indicates no maximum.  Default: 0.
  
     .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.
             [ NOTE: the PARNAME can't be used in expressions. ]
  
  Future modifications to the PARINFO structure, if any, will involve
  adding structure tags beginning with the two letters "MP".
  Therefore programmers are urged to avoid using tags starting with
  the same letters; otherwise they are free to include their own
  fields within the PARINFO structure, and they will be ignored.
  
  PARINFO 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.

 INPUTS:
   MYFUNCT - a string variable containing the name of an IDL
             function.  This function computes the "model" Z values
             given the X,Y values and model parameters, as described above.

   X - Array of "X" independent variable values, as described above.
       These values are passed directly to the fitting function
       unmodified.

   Y - Array of "Y" independent variable values, as described
       above. X and Y should have the same data type.

   Z - Array of "measured" dependent variable values.  Z should have
       the same data type as X and Y.  The function MYFUNCT should
       map (X,Y)->Z.

   ERR - Array of "measured" 1-sigma uncertainties.  ERR should have
         the same data type as Z.  ERR is ignored if the WEIGHTS
         keyword is specified.

   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.
 
 RETURNS:

   Returns the array of best-fit parameters.

 KEYWORD PARAMETERS:

   BESTNORM - the value of the summed, squared, weighted residuals
              for the returned parameter values, i.e. the chi-square value.

   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.

   DOF - number of degrees of freedom, computed as
             DOF = N_ELEMENTS(DEVIATES) - NFREE
         Note that this doesn't account for pegged parameters (see
         NPEGGED).

   ERRMSG - a string error or warning message is returned.

   FTOL - a nonnegative input variable. Termination occurs when both
          the actual and predicted relative reductions in the sum of
          squares are at most FTOL (and STATUS is accordingly set to
          1 or 3).  Therefore, FTOL measures the relative error
          desired in the sum of squares.  Default: 1D-10

   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.

   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 (and STATUS is
          accordingly set to 4). Therefore, GTOL measures the
          orthogonality desired between the function vector and the
          columns of the jacobian.  Default: 1D-10

   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.

   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
              common block variable ERROR_CODE to negative value (see
              MPFIT_ERROR common block below).  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.

   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

   NFEV - the number of MYFUNCT function evaluations performed.

   NITER - the number of iterations completed.

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

   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.  Note that
            several Levenberg-Marquardt attempts can be made in a
            single iteration.
            Default value: 1

   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.  Values in PARINFO are never 
             modified during a call to MPFIT.

             See description above for the structure of PARINFO.

             Default value:  all parameters are free and unconstrained.

   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.

            If the fit is unweighted (i.e. no errors were given, or
            the weights were uniformly set to unity), then PERROR
            will probably not represent the true parameter
            uncertainties.  *If* you can assume that the true reduced
            chi-squared value is unity -- meaning that the fit is
            implicitly assumed to be of good quality -- then the
            estimated parameter uncertainties can be computed by
            scaling PERROR by the measured chi-squared value.

              DOF     = N_ELEMENTS(Z) - N_ELEMENTS(PARMS) ; deg of freedom
              PCERROR = PERROR * SQRT(BESTNORM / DOF)   ; scaled uncertainties

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

   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.

   WEIGHTS - Array of weights to be used in calculating the
             chi-squared value.  If WEIGHTS is specified then the ERR
             parameter is ignored.  The chi-squared value is computed
             as follows:

                CHISQ = TOTAL( (Z-MYFUNCT(X,Y,P))^2 * ABS(WEIGHTS) )

             Here are common values of WEIGHTS:

                1D/ERR^2 - Normal weighting (ERR is the measurement error)
                1D/Z     - Poisson weighting (counting statistics)
                1D       - Unweighted

   XTOL - a nonnegative input variable. Termination occurs when the
          relative error between two consecutive iterates is at most
          XTOL (and STATUS is accordingly set to 2 or 3).  Therefore,
          XTOL measures the relative error desired in the approximate
          solution.  Default: 1D-10

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

 EXAMPLE:

   p  = [2.2D, -0.7D, 1.4D, 3000.D]
   x  = (dindgen(200)*0.1 - 10.) # (dblarr(200) + 1)
   y  = (dblarr(200) + 1) # (dindgen(200)*0.1 - 10.)
   zi = gauss2(x, y, p)
   sz = sqrt(zi)
   z  = zi + randomn(seed, 200, 200) * sz

   p0 = [0D, 0D, 1D, 10D]
   p = mpfit2dfun('GAUSS2', x, y, z, sz, p0)
   
   Generates a synthetic data set with a Gaussian peak, and Poisson
   statistical uncertainty.  Then the same function (but different
   starting parameters) is fitted to the data to see how close we can
   get.

   It is especially worthy to notice that the X and Y values are
   created as full images, so that a coordinate is attached to each
   pixel independently.  This is the format that GAUSS2 accepts, and
   the easiest for you to use in your own functions.


 COMMON BLOCKS:

   COMMON MPFIT_ERROR, ERROR_CODE

     User routines may stop the fitting process at any time by
     setting an error condition.  This condition may be set in either
     the user's model computation routine (MYFUNCT), or in the
     iteration procedure (ITERPROC).

     To stop the fitting, the above common block must be declared,
     and ERROR_CODE must be set to a negative number.  After the user
     procedure or function returns, MPFIT checks the value of this
     common block variable and exits immediately if the error
     condition has been set.  By default the value of ERROR_CODE is
     zero, indicating a successful function/procedure call.


 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, transformed from MPFITFUN, 26 Sep 1999, CM
   Alphabetized documented keywords, 02 Oct 1999, CM
   Added example, 02 Oct 1999, CM
   Tried to clarify definitions of X and Y, 29 Oct 1999, CM
   Added QUERY keyword and query checking of MPFIT, 29 Oct 1999, CM
   Check to be sure that X, Y and Z are present, 02 Nov 1999, CM
   Documented PERROR for unweighted fits, 03 Nov 1999, CM
   Changed to ERROR_CODE for error condition, 28 Jan 2000, CM
   Copying permission terms have been liberalized, 26 Mar 2000, CM
   Propagated improvements from MPFIT, 17 Dec 2000, CM
   Documented RELSTEP field of PARINFO (!!), CM, 25 Oct 2002
   Add DOF keyword to return degrees of freedom, CM, 23 June 2003
   Minor documentation adjustment, 03 Feb 2004, CM

  $Id: mpfit2dfun.pro,v 1.5 2004/02/26 04:18:16 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/mpfit2dfun.pro)


MPFIT2DPEAK

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

 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://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Fit a gaussian, lorentzian or Moffat model to data

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   yfit = MPFIT2DPEAK(Z, A [, X, Y, /TILT ...] )

 DESCRIPTION:

   MPFIT2DPEAK fits a gaussian, lorentzian or Moffat model using the
   non-linear least squares fitter MPFIT.  MPFIT2DPEAK is meant to be
   a drop-in replacement for IDL's GAUSS2DFIT function (and requires
   MPFIT and MPFIT2DFUN).

   The choice of the fitting function is determined by the keywords
   GAUSSIAN, LORENTZIAN and MOFFAT.  By default the gaussian model
   function is used.  [ The Moffat function is a modified Lorentzian
   with variable power law index. ]  The two-dimensional peak has
   independent semimajor and semiminor axes, with an optional
   rotation term activated by setting the TILT keyword.  The baseline
   is assumed to be a constant.

      GAUSSIAN      A(0) + A(1)*exp(-0.5*u)
      LORENTZIAN    A(0) + A(1)/(u + 1)
      MOFFAT        A(0) + A(1)/(u + 1)^A(7)

      u = ( (x-A(4))/A(2) )^2 + ( (y-A(5))/A(3) )^2

         where x and y are cartesian coordinates in rotated
         coordinate system if TILT keyword is set.

   The returned parameter array elements have the following meanings:

      A(0)   Constant baseline level
      A(1)   Peak value
      A(2)   Peak half-width (x) -- gaussian sigma or half-width at half-max
      A(3)   Peak half-width (y) -- gaussian sigma or half-width at half-max
      A(4)   Peak centroid (x)
      A(5)   Peak centroid (y)
      A(6)   Rotation angle (radians) if TILT keyword set
      A(7)   Moffat power law index if MOFFAT keyword set

   By default the initial starting values for the parameters A are
   estimated from the data.  However, explicit starting values can be
   supplied using the ESTIMATES keyword.  Also, error or weighting
   values can optionally be provided; otherwise the fit is
   unweighted.

 RESTRICTIONS:

   If no starting parameter ESTIMATES are provided, then MPFIT2DPEAK
   attempts to estimate them from the data.  This is not a perfect
   science; however, the author believes that the technique
   implemented here is more robust than the one used in IDL's
   GAUSS2DFIT.  The author has tested cases of strong peaks, noisy
   peaks and broad peaks, all with success.


 INPUTS:

   Z - Two dimensional array of "measured" dependent variable values.
       Z should be of the same type and dimension as (X # Y).

   X - Optional vector of x positions for a single row of Z.

          X(i) should provide the x position of Z(i,*)

       Default: X values are integer increments from 0 to NX-1

   Y - Optional vector of y positions for a single column of Z.

          Y(j) should provide the y position of Z(*,j)

       Default: Y values are integer increments from 0 to NY-1

 OUTPUTS:
   A - Upon return, an array of best fit parameter values.  See the
       table above for the meanings of each parameter element.


 RETURNS:

   Returns the best fitting model function as a 2D array.

 KEYWORDS:

   ** NOTE ** Additional keywords such as PARINFO, BESTNORM, and
              STATUS are accepted by MPFIT2DPEAK but not documented
              here.  Please see the documentation for MPFIT for the
              description of these advanced options.

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

   CIRCULAR - if set, then the peak profile is assumed to be
              azimuthally symmetric.  When set, the parameters A(2)
              and A(3) will be identical and the TILT keyword will
              have no effect.

   DOF - number of degrees of freedom, computed as
             DOF = N_ELEMENTS(DEVIATES) - NFREE
         Note that this doesn't account for pegged parameters (see
         NPEGGED).

   ERROR - upon input, the measured 1-sigma uncertainties in the "Z"
           values.  If no ERROR or WEIGHTS are given, then the fit is
           unweighted.

   ESTIMATES - Array of starting values for each parameter of the
               model.
               Default: parameter values are estimated from data.

   GAUSSIAN - if set, fit a gaussian model function.  The Default.
   LORENTZIAN - if set, fit a lorentzian model function.
   MOFFAT - if set, fit a Moffat model function.

   MEASURE_ERRORS - synonym for ERRORS, for consistency with built-in
                    IDL fitting routines.

   NEGATIVE - if set, and ESTIMATES is not provided, then MPFIT2DPEAK
              will assume that a negative peak is present -- a
              valley.  Specifying this keyword is not normally
              required, since MPFIT2DPEAK can determine this
              automatically.

   NFREE - the number of free parameters in the fit.  This includes
           parameters which are not FIXED and not TIED, but it does
           include parameters which are pegged at LIMITS.

   PERROR - upon return, the 1-sigma uncertainties of the parameter
            values A.  These values are only meaningful if the ERRORS
            or WEIGHTS keywords are specified properly.

            If the fit is unweighted (i.e. no errors were given, or
            the weights were uniformly set to unity), then PERROR
            will probably not represent the true parameter
            uncertainties.  

            *If* you can assume that the true reduced chi-squared
            value is unity -- meaning that the fit is implicitly
            assumed to be of good quality -- then the estimated
            parameter uncertainties can be computed by scaling PERROR
            by the measured chi-squared value.

              DOF     = N_ELEMENTS(Z) - N_ELEMENTS(A)   ; deg of freedom
              PCERROR = PERROR * SQRT(BESTNORM / DOF)   ; scaled uncertainties

   QUIET - if set then diagnostic fitting messages are suppressed.
           Default: QUIET=1 (i.e., no diagnostics)

   SIGMA - synonym for PERROR (1-sigma parameter uncertainties), for
           compatibility with GAUSSFIT.  Do not confuse this with the
           Gaussian "sigma" width parameter.

   TILT - if set, then the major and minor axes of the peak profile
          are allowed to rotate with respect to the image axes.
          Parameter A(6) will be set to the clockwise rotation angle
          of the A(2) axis in radians.

   WEIGHTS - Array of weights to be used in calculating the
             chi-squared value.  If WEIGHTS is specified then the ERR
             parameter is ignored.  The chi-squared value is computed
             as follows:

                CHISQ = TOTAL( (Z-MYFUNCT(X,Y,P))^2 * ABS(WEIGHTS) )

             Here are common values of WEIGHTS:

                1D/ERR^2 - Normal weighting (ERR is the measurement error)
                1D/Y     - Poisson weighting (counting statistics)
                1D       - Unweighted

             The ERROR keyword takes precedence over any WEIGHTS
             keyword values.  If no ERROR or WEIGHTS are given, then
             the fit is unweighted.


 EXAMPLE:

 ; Construct a sample gaussian surface in range [-5,5] centered at [2,-3]
   x = findgen(100)*0.1 - 5. & y = x
   xx = x # (y*0 + 1)
   yy = (x*0 + 1) # y
   rr = sqrt((xx-2.)^2 + (yy+3.)^2)

 ; Gaussian surface with sigma=0.5, peak value of 3, noise with sigma=0.2
   z = 3.*exp(-(rr/0.5)^2) + randomn(seed,100,100)*.2

 ; Fit gaussian parameters A
   zfit = mpfit2dpeak(z, a, x, y)

 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:

   New algorithm for estimating starting values, CM, 31 Oct 1999
   Documented, 02 Nov 1999
   Small documentation fixes, 02 Nov 1999
   Documented PERROR for unweighted fits, 03 Nov 1999, CM
   Copying permission terms have been liberalized, 26 Mar 2000, CM
   Small cosmetic changes, 21 Sep 2000, CM
   Corrected bug introduced by cosmetic changes, 11 Oct 2000, CM :-)
   Added POSITIVE keyword, 17 Nov 2000, CM
   Removed TILT in common, in favor of FUNCTARGS approach, 23 Nov
     2000, CM
   Added SYMMETRIC keyword, documentation for TILT, and an example,
     24 Nov 2000, CM
   Changed SYMMETRIC to CIRCULAR, 17 Dec 2000, CM
   Really change SYMMETRIC to CIRCULAR!, 13 Sep 2002, CM
   Add error messages for SYMMETRIC and CIRCLE, 08 Nov 2002, CM
   Make more consistent with comparable IDL routines, 30 Jun 2003, CM

  $Id: mpfit2dpeak.pro,v 1.5 2003/06/30 21:48:01 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/mpfit2dpeak.pro)


MPFITELLIPSE

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

 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://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Approximate fit to points forming an ellipse

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   parms = MPFITELLIPSE(X, Y, start_parms, [/TILT, WEIGHTS=wts, ...])

 DESCRIPTION:

   MPFITELLIPSE fits a closed elliptical or circular curve to a two
   dimensional set of data points.  The user specifies the X and Y
   positions of the points, and an optional set of weights.  The
   ellipse may also be tilted at an arbitrary angle.

   The best fitting ellipse parameters are returned from by
   MPFITELLIPSE as a vector, whose values are:

      P(0)   Ellipse semi axis 1
      P(1)   Ellipse semi axis 2   ( = P(0) if CIRCLE keyword set)
      P(2)   Ellipse center - x value
      P(3)   Ellipse center - y value
      P(4)   Ellipse rotation angle (radians) if TILT keyword set

   The user may specify an initial set of trial parameters, but by
   default MPFITELLIPSE will estimate the parameters automatically.

   Users should be aware that in the presence of large amounts of
   noise, namely when the measurement error becomes significant
   compared to the ellipse axis length, then the estimated parameters
   become unreliable.  Generally speaking the computed axes will
   overestimate the true axes.  For example when (SIGMA_R/R) becomes
   0.5, the radius of the ellipse is overestimated by about 40%.

   Users can weight their data as they see appropriate.  However, the
   following prescription for the weighting appears to be the correct
   one, and produces values comparable to the typical chi-squared
   value.

     WEIGHTS = 0.75/(SIGMA_X^2 + SIGMA_Y^2)

   where SIGMA_X and SIGMA_Y are the measurement error vectors in the
   X and Y directions respectively.  However, it should be pointed
   out that this weighting is only appropriate for a set of points
   whose measurement errors are comparable.  If a more robust
   estimation of the parameter values is needed, the so-called
   orthogonal distance regression package should be used (ODRPACK,
   available in FORTRAN at www.netlib.org).

 INPUTS:

   X - measured X positions of the points in the ellipse.
   Y - measured Y positions of the points in the ellipse.

   START_PARAMS - an array of starting values for the ellipse
                  parameters, as described above.  This parameter is
                  optional; if not specified by the user, then the
                  ellipse parameters are estimated automatically from
                  the properties of the data.

 RETURNS:

   Returns the best fitting model ellipse parameters.

 KEYWORDS:

   ** NOTE ** Additional keywords such as PARINFO, BESTNORM, and
              STATUS are accepted by MPFITELLIPSE but not documented
              here.  Please see the documentation for MPFIT for the
              description of these advanced options.

   PERROR - upon return, the 1-sigma uncertainties of the returned
            ellipse parameter values.  These values are only
            meaningful if the WEIGHTS keyword is specified properly.

            If the fit is unweighted (i.e. no errors were given, or
            the weights were uniformly set to unity), then PERROR
            will probably not represent the true parameter
            uncertainties.  

   QUIET - if set then diagnostic fitting messages are suppressed.
           Default: QUIET=1 (i.e., no diagnostics)

   CIRCULAR - if set, then the curve is assumed to be a circle
              instead of ellipse.  When set, the parameters P(0) and
              P(1) will be identical and the TILT keyword will have
              no effect.

   TILT - if set, then the major and minor axes of the ellipse
          are allowed to rotate with respect to the data axes.
          Parameter P(4) will be set to the clockwise rotation angle
          of the P(0) axis in radians.

   WEIGHTS - Array of weights to be used in calculating the
             chi-squared value.  If WEIGHTS is specified then the ERR
             parameter is ignored.  The chi-squared value is computed
             as follows:

                CHISQ = TOTAL( (Z-MYFUNCT(X,Y,P))^2 * ABS(WEIGHTS)^2 )

             Users may wish to follow the guidelines for WEIGHTS
             described above.


 EXAMPLE:

 ; Construct a set of points on an ellipse, with some noise
   ph0 = 2*!pi*randomu(seed,50)
   x =  50. + 32.*cos(ph0) + 4.0*randomn(seed, 50)
   y = -75. + 65.*sin(ph0) + 0.1*randomn(seed, 50)

 ; Compute weights function
   weights = 0.75/(4.0^2 + 0.1^2)

 ; Fit ellipse and plot result
   p = mpfitellipse(x, y)
   plot, x, y, psym=1
   phi = dindgen(101)*2D*!dpi/100
   oplot, p(2)+p(0)*cos(phi), p(3)+p(1)*sin(phi)

 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:

   Ported from MPFIT2DPEAK, 17 Dec 2000, CM
   More documentation, 11 Jan 2001, CM
   Example corrected, 18 Nov 2001, CM
   Change CIRCLE keyword to the correct CIRCULAR keyword, 13 Sep
      2002, CM
   Add error messages for SYMMETRIC and CIRCLE, 08 Nov 2002, CM
   Found small error in computation of _EVAL (when CIRCULAR) was set;
      sanity check when CIRCULAR is set, 21 Jan 2003, CM

  $Id: mpfitellipse.pro,v 1.8 2003/01/24 04:04:30 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/mpfitellipse.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://cow.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.
   - Starting guesses for all of the parameters ("START_PARAMS").

  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.

 EVALUATING EXPRESSIONS

  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.

 PASSING PRIVATE DATA TO AN EXPRESSION

  The most complicated optimization problems typically involve other
  external parameters, in addition to the fitted parameters.  While
  it is extremely easy to rewrite an expression dynamically, in case
  one of the external parameters changes, the other possibility is to
  use the PRIVATE data structure.

  The user merely passes a structure to the FUNCTARGS keyword.  The
  user expression receives this value as the variable PRIVATE.
  MPFITEXPR nevers accesses this variable so it can contain any
  desired values.  Usually it would be an IDL structure so that any
  named external parameters can be passed to the expression.


 CONSTRAINING PARAMETER VALUES WITH THE PARINFO KEYWORD

  The behavior of MPFIT can be modified with respect to each
  parameter to be fitted.  A parameter value can be fixed; simple
  boundary constraints can be imposed; limitations on the parameter
  changes can be imposed; properties of the automatic derivative can
  be modified; and parameters can be tied to one another.

  These properties are governed by the PARINFO structure, which is
  passed as a keyword parameter 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 the START_PARAMS
              parameter for more information).
  
     .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 values of LIMITED.  Both LIMITED
               and LIMITS must be given together.
  
     .PARNAME - a string, giving the name of the parameter.  The
                fitting code of MPFIT does not use this tag in any
                way.  However, the default ITERPROC will print the
                parameter name if available.
  
     .STEP - the step size to be used in calculating the numerical
             derivatives.  If set to zero, then the step size is
             computed automatically.  Ignored when AUTODERIVATIVE=0.
             This value is superceded by the RELSTEP value.

     .RELSTEP - the *relative* step size to be used in calculating
                the numerical derivatives.  This number is the
                fractional size of the step, compared to the
                parameter value.  This value supercedes the STEP
                setting.  If the parameter is zero, then a default
                step size is chosen.

     .MPSIDE - the sidedness of the finite difference when computing
               numerical derivatives.  This field can take four
               values:

                  0 - one-sided derivative computed automatically
                  1 - one-sided derivative (f(x+h) - f(x)  )/h
                 -1 - one-sided derivative (f(x)   - f(x-h))/h
                  2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)

              Where H is the STEP parameter described above.  The
              "automatic" one-sided derivative method will chose a
              direction for the finite difference which does not
              violate any constraints.  The other methods do not
              perform this check.  The two-sided method is in
              principle more precise, but requires twice as many
              function evaluations.  Default: 0.

     .MPMINSTEP - the minimum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will be changed by multiples of this value.  The
                  actual step is computed as:

                     DELTA1 = MPMINSTEP*ROUND(DELTA0/MPMINSTEP)

                  where DELTA0 and DELTA1 are the estimated parameter
                  changes before and after this constraint is
                  applied.  Note that this constraint should be used
                  with care since it may cause non-converging,
                  oscillating solutions.

                  A value of 0 indicates no minimum.  Default: 0.

     .MPMAXSTEP - the maximum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will never be changed by more than this value.

                  A value of 0 indicates no maximum.  Default: 0.
  
     .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.
             [ NOTE: the PARNAME can't be used in expressions. ]
  
  Future modifications to the PARINFO structure, if any, will involve
  adding structure tags beginning with the two letters "MP".
  Therefore programmers are urged to avoid using tags starting with
  the same letters; otherwise they are free to include their own
  fields within the PARINFO structure, and they will be ignored.
  
  PARINFO 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.

 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.

   X - Array of independent variable values.

   Y - Array of "measured" dependent variable values.  Y should have
       the same data type as X.  The function MYFUNCT should map
       X->Y.

   ERR - Array of "measured" 1-sigma uncertainties.  ERR should have
         the same data type as Y.  ERR is ignored if the WEIGHTS
         keyword is specified.

   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.  This technique is not fully
                  reliable, so users are advised to pass explicit
                  parameter starting values.
 

 RETURNS:

   Returns the array of best-fit parameters.


 KEYWORD PARAMETERS:

   BESTNORM - the value of the summed, squared, weighted residuals
              for the returned parameter values, i.e. the chi-square value.

   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.

   DOF - number of degrees of freedom, computed as
             DOF = N_ELEMENTS(DEVIATES) - NFREE
         Note that this doesn't account for pegged parameters (see
         NPEGGED).

   ERRMSG - a string error or warning message is returned.

   FTOL - a nonnegative input variable. Termination occurs when both
          the actual and predicted relative reductions in the sum of
          squares are at most FTOL (and STATUS is accordingly set to
          1 or 3).  Therefore, FTOL measures the relative error
          desired in the sum of squares.  Default: 1D-10

   FUNCTARGS - passed directly to the expression as the variable
               PRIVATE.  Any user-private data can be communicated to
               the user expression using this keyword.
               Default: PRIVATE is undefined in user expression

   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 (and STATUS is
          accordingly set to 4). Therefore, GTOL measures the
          orthogonality desired between the function vector and the
          columns of the jacobian.  Default: 1D-10

   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.

   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
              common block variable ERROR_CODE to negative value (see
              MPFIT_ERROR common block below).  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.

   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

   NFEV - the number of MYFUNCT function evaluations performed.

   NFREE - the number of free parameters in the fit.  This includes
           parameters which are not FIXED and not TIED, but it does
           include parameters which are pegged at LIMITS.

   NITER - the number of iterations completed.

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

   NPEGGED - the number of free parameters which are pegged at a
             LIMIT.

   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.  Note that
            several Levenberg-Marquardt attempts can be made in a
            single iteration.
            Default value: 1

   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.  Values in PARINFO are never 
             modified during a call to MPFIT.

             See description above for the structure of PARINFO.

             Default value:  all parameters are free and unconstrained.

   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.

            If the fit is unweighted (i.e. no errors were given, or
            the weights were uniformly set to unity), then PERROR
            will probably not represent the true parameter
            uncertainties.  

            *If* you can assume that the true reduced chi-squared
            value is unity -- meaning that the fit is implicitly
            assumed to be of good quality -- then the estimated
            parameter uncertainties can be computed by scaling PERROR
            by the measured chi-squared value.

              DOF     = N_ELEMENTS(X) - N_ELEMENTS(PARMS) ; deg of freedom
              PCERROR = PERROR * SQRT(BESTNORM / DOF)   ; scaled uncertainties

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

   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.

   WEIGHTS - Array of weights to be used in calculating the
             chi-squared value.  If WEIGHTS is specified then the ERR
             parameter is ignored.  The chi-squared value is computed
             as follows:

                CHISQ = TOTAL( (Y-MYFUNCT(X,P))^2 * ABS(WEIGHTS) )

             Here are common values of WEIGHTS:

                1D/ERR^2 - Normal weighting (ERR is the measurement error)
                1D/Y     - Poisson weighting (counting statistics)
                1D       - Unweighted

   XTOL - a nonnegative input variable. Termination occurs when the
          relative error between two consecutive iterates is at most
          XTOL (and STATUS is accordingly set to 2 or 3).  Therefore,
          XTOL measures the relative error desired in the approximate
          solution.  Default: 1D-10

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


 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
   expr = 'P(0) + GAUSS1(X, P(1:3))'               ; fitting function
   p0 = [800.D, 1.D, 1., 500.]                     ; Initial guess
   p = mpfitexpr(expr, x, y, sy, p0)               ; Fit the expression
   print, p

   plot, x, y                                      ; Plot data
   oplot, x, mpevalexpr(expr, x, p)                ; Plot model

   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.


 COMMON BLOCKS:

   COMMON MPFIT_ERROR, ERROR_CODE

     User routines may stop the fitting process at any time by
     setting an error condition.  This condition may be set in either
     the user's model computation routine (MYFUNCT), or in the
     iteration procedure (ITERPROC).

     To stop the fitting, the above common block must be declared,
     and ERROR_CODE must be set to a negative number.  After the user
     procedure or function returns, MPFIT checks the value of this
     common block variable and exits immediately if the error
     condition has been set.  By default the value of ERROR_CODE is
     zero, indicating a successful function/procedure call.


 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
   Cosmetic documentation updates, 16 Apr 1999, CM
   More cosmetic documentation updates, 14 May 1999, CM
   Made sure to update STATUS value, 25 Sep 1999, CM
   Added WEIGHTS keyword, 25 Sep 1999, CM
   Changed from handles to common blocks, 25 Sep 1999, CM
     - commons seem much cleaner and more logical in this case.
   Alphabetized documented keywords, 02 Oct 1999, CM
   Added QUERY keyword and query checking of MPFIT, 29 Oct 1999, CM
   Check to be sure that X and Y are present, 02 Nov 1999, CM
   Documented PERROR for unweighted fits, 03 Nov 1999, CM
   Removed ITERPROC='' when quiet EQ 1, 10 Jan 2000, CM
   Changed to ERROR_CODE for error condition, 28 Jan 2000, CM
   Updated the EXAMPLE, 26 Mar 2000, CM
   Copying permission terms have been liberalized, 26 Mar 2000, CM
   Propagated improvements from MPFIT, 17 Dec 2000, CM
   Correct reference to _WTS in MPFITEXPR_EVAL, 25 May 2001, CM
      (thanks to Mark Fardal)
   Added useful FUNCTARGS behavior (as yet undocumented), 04 Jul
      2002, CM
   Documented FUNCTARGS/PRIVATE behavior, 22 Jul 2002, CM
   Added NFREE and NPEGGED keywords, 13 Sep 2002, CM
   Documented RELSTEP field of PARINFO (!!), CM, 25 Oct 2002
   Add DOF keyword, CM, 31 Jul 2003
   Add FUNCTARGS keyword to MPEVALEXPR, CM 08 Aug 2003
   Minor documentation adjustment, 03 Feb 2004, CM

  $Id: mpfitexpr.pro,v 1.11 2004/02/26 04:18:16 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/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://cow.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_params, ...)

 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").
   - Starting guesses for all of the parameters ("START_PARAMS").

  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.

 USER FUNCTION

  The user must define a function which returns the model value.  For
  applications which use finite-difference derivatives -- the default
  -- the user function should be declared in the following way:

    FUNCTION MYFUNCT, X, P
     ; The independent variable is X
     ; Parameter values are passed in "P"
     YMOD = ... computed model values at X ...
     return, YMOD
    END

  The returned array YMOD must have the same dimensions and type as
  the "measured" Y values.

  User functions may also indicate a fatal error condition
  using the ERROR_CODE common block variable, as described
  below under the MPFIT_ERROR common block definition.

  See the discussion under "ANALYTIC DERIVATIVES" and AUTODERIVATIVE
  in MPFIT.PRO if you wish to compute the derivatives for yourself.
  AUTODERIVATIVE is accepted by MPFITFUN and passed directly to
  MPFIT.  The user function must accept one additional parameter, DP,
  which contains the derivative of the user function with respect to
  each parameter at each data point, as described in MPFIT.PRO.

 CONSTRAINING PARAMETER VALUES WITH THE PARINFO KEYWORD

  The behavior of MPFIT can be modified with respect to each
  parameter to be fitted.  A parameter value can be fixed; simple
  boundary constraints can be imposed; limitations on the parameter
  changes can be imposed; properties of the automatic derivative can
  be modified; and parameters can be tied to one another.

  These properties are governed by the PARINFO structure, which is
  passed as a keyword parameter 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 the START_PARAMS
              parameter for more information).
  
     .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 values of LIMITED.  Both LIMITED
               and LIMITS must be given together.
  
     .PARNAME - a string, giving the name of the parameter.  The
                fitting code of MPFIT does not use this tag in any
                way.  However, the default ITERPROC will print the
                parameter name if available.
  
     .STEP - the step size to be used in calculating the numerical
             derivatives.  If set to zero, then the step size is
             computed automatically.  Ignored when AUTODERIVATIVE=0.
             This value is superceded by the RELSTEP value.

     .RELSTEP - the *relative* step size to be used in calculating
                the numerical derivatives.  This number is the
                fractional size of the step, compared to the
                parameter value.  This value supercedes the STEP
                setting.  If the parameter is zero, then a default
                step size is chosen.

     .MPSIDE - the sidedness of the finite difference when computing
               numerical derivatives.  This field can take four
               values:

                  0 - one-sided derivative computed automatically
                  1 - one-sided derivative (f(x+h) - f(x)  )/h
                 -1 - one-sided derivative (f(x)   - f(x-h))/h
                  2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)

              Where H is the STEP parameter described above.  The
              "automatic" one-sided derivative method will chose a
              direction for the finite difference which does not
              violate any constraints.  The other methods do not
              perform this check.  The two-sided method is in
              principle more precise, but requires twice as many
              function evaluations.  Default: 0.

     .MPMINSTEP - the minimum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will be changed by multiples of this value.  The
                  actual step is computed as:

                     DELTA1 = MPMINSTEP*ROUND(DELTA0/MPMINSTEP)

                  where DELTA0 and DELTA1 are the estimated parameter
                  changes before and after this constraint is
                  applied.  Note that this constraint should be used
                  with care since it may cause non-converging,
                  oscillating solutions.

                  A value of 0 indicates no minimum.  Default: 0.

     .MPMAXSTEP - the maximum change to be made in the parameter
                  value.  During the fitting process, the parameter
                  will never be changed by more than this value.

                  A value of 0 indicates no maximum.  Default: 0.
  
     .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.
             [ NOTE: the PARNAME can't be used in expressions. ]
  
  Future modifications to the PARINFO structure, if any, will involve
  adding structure tags beginning with the two letters "MP".
  Therefore programmers are urged to avoid using tags starting with
  the same letters; otherwise they are free to include their own
  fields within the PARINFO structure, and they will be ignored.
  
  PARINFO 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.

 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, as desribed above.

   X - Array of independent variable values.

   Y - Array of "measured" dependent variable values.  Y should have
       the same data type as X.  The function MYFUNCT should map
       X->Y.

   ERR - Array of "measured" 1-sigma uncertainties.  ERR should have
         the same data type as Y.  ERR is ignored if the WEIGHTS
         keyword is specified.

   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.
 

 RETURNS:

   Returns the array of best-fit parameters.


 KEYWORD PARAMETERS:

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

   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.

   CASH - when set, the fit statistic is changed to a derivative of
          the CASH statistic.  The model function must be strictly
          positive.

   DOF - number of degrees of freedom, computed as
             DOF = N_ELEMENTS(DEVIATES) - NFREE
         Note that this doesn't account for pegged parameters (see
         NPEGGED).

   ERRMSG - a string error or warning message is returned.

   FTOL - a nonnegative input variable. Termination occurs when both
          the actual and predicted relative reductions in the sum of
          squares are at most FTOL (and STATUS is accordingly set to
          1 or 3).  Therefore, FTOL measures the relative error
          desired in the sum of squares.  Default: 1D-10

   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.

   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 (and STATUS is
          accordingly set to 4). Therefore, GTOL measures the
          orthogonality desired between the function vector and the
          columns of the jacobian.  Default: 1D-10

   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.

   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
              common block variable ERROR_CODE to negative value (see
              MPFIT_ERROR common block below).  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.

   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

   NFEV - the number of MYFUNCT function evaluations performed.

   NFREE - the number of free parameters in the fit.  This includes
           parameters which are not FIXED and not TIED, but it does
           include parameters which are pegged at LIMITS.

   NITER - the number of iterations completed.

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

   NPEGGED - the number of free parameters which are pegged at a
             LIMIT.

   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.  Note that
            several Levenberg-Marquardt attempts can be made in a
            single iteration.
            Default value: 1

   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.  Values in PARINFO are never 
             modified during a call to MPFIT.

             See description above for the structure of PARINFO.

             Default value:  all parameters are free and unconstrained.

   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.

            If the fit is unweighted (i.e. no errors were given, or
            the weights were uniformly set to unity), then PERROR
            will probably not represent the true parameter
            uncertainties.  

            *If* you can assume that the true reduced chi-squared
            value is unity -- meaning that the fit is implicitly
            assumed to be of good quality -- then the estimated
            parameter uncertainties can be computed by scaling PERROR
            by the measured chi-squared value.

              DOF     = N_ELEMENTS(X) - N_ELEMENTS(PARMS) ; deg of freedom
              PCERROR = PERROR * SQRT(BESTNORM / DOF)   ; scaled uncertainties

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

   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.

   WEIGHTS - Array of weights to be used in calculating the
             chi-squared value.  If WEIGHTS is specified then the ERR
             parameter is ignored.  The chi-squared value is computed
             as follows:

                CHISQ = TOTAL( (Y-MYFUNCT(X,P))^2 * ABS(WEIGHTS) )

             Here are common values of WEIGHTS:

                1D/ERR^2 - Normal weighting (ERR is the measurement error)
                1D/Y     - Poisson weighting (counting statistics)
                1D       - Unweighted

   XTOL - a nonnegative input variable. Termination occurs when the
          relative error between two consecutive iterates is at most
          XTOL (and STATUS is accordingly set to 2 or 3).  Therefore,
          XTOL measures the relative error desired in the approximate
          solution.  Default: 1D-10

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

   
 EXAMPLE:

   ; First, generate some synthetic data
   npts = 200
   x  = dindgen(npts) * 0.1 - 10.                  ; Independent variable 
   yi = gauss1(x, [2.2D, 1.4, 3000.])              ; "Ideal" Y variable
   y  = yi + randomn(seed, npts) * 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 (cent, width, area)
   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 (with different starting parameters) to see how close we can
   get.


 COMMON BLOCKS:

   COMMON MPFIT_ERROR, ERROR_CODE

     User routines may stop the fitting process at any time by
     setting an error condition.  This condition may be set in either
     the user's model computation routine (MYFUNCT), or in the
     iteration procedure (ITERPROC).

     To stop the fitting, the above common block must be declared,
     and ERROR_CODE must be set to a negative number.  After the user
     procedure or function returns, MPFIT checks the value of this
     common block variable and exits immediately if the error
     condition has been set.  By default the value of ERROR_CODE is
     zero, indicating a successful function/procedure call.

 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
   Cosmetic documentation updates, 16 Apr 1999, CM
   More cosmetic documentation updates, 14 May 1999, CM
   Made sure to update STATUS, 25 Sep 1999, CM
   Added WEIGHTS keyword, 25 Sep 1999, CM
   Changed from handles to common blocks, 25 Sep 1999, CM
     - commons seem much cleaner and more logical in this case.
   Alphabetized documented keywords, 02 Oct 1999, CM
   Added QUERY keyword and query checking of MPFIT, 29 Oct 1999, CM
   Corrected EXAMPLE (offset of 1000), 30 Oct 1999, CM
   Check to be sure that X and Y are present, 02 Nov 1999, CM
   Documented PERROR for unweighted fits, 03 Nov 1999, CM
   Changed to ERROR_CODE for error condition, 28 Jan 2000, CM
   Corrected errors in EXAMPLE, 26 Mar 2000, CM
   Copying permission terms have been liberalized, 26 Mar 2000, CM
   Propagated improvements from MPFIT, 17 Dec 2000, CM
   Added CASH statistic, 10 Jan 2001
   Added NFREE and NPEGGED keywords, 11 Sep 2002, CM
   Documented RELSTEP field of PARINFO (!!), CM, 25 Oct 2002
   Add DOF keyword to return degrees of freedom, CM, 23 June 2003

  $Id: mpfitfun.pro,v 1.6 2003/06/30 21:47:36 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/mpfitfun.pro)


MPFITPEAK

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

 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://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Fit a gaussian, lorentzian or Moffat model to data

 MAJOR TOPICS:
   Curve and Surface Fitting

 CALLING SEQUENCE:
   yfit = MPFITPEAK(X, Y, A, NTERMS=nterms, ...)

 DESCRIPTION:

   MPFITPEAK fits a gaussian, lorentzian or Moffat model using the
   non-linear least squares fitter MPFIT.  MPFITPEAK is meant to be a
   drop-in replacement for IDL's GAUSSFIT function (and requires
   MPFIT and MPFITFUN).

   The choice of the fitting function is determined by the keywords
   GAUSSIAN, LORENTZIAN and MOFFAT.  By default the gaussian model
   function is used.  [ The Moffat function is a modified Lorentzian
   with variable power law index. (Moffat, A. F. J. 1969, Astronomy &
   Astrophysics, v. 3, p. 455-461) ]

   The functional form of the baseline is determined by NTERMS and
   the function to be fitted.  NTERMS represents the total number of
   parameters, A, to be fitted.  The functional forms and the
   meanings of the parameters are described in this table:

                 GAUSSIAN#          Lorentzian#         Moffat#

   Model     A(0)*exp(-0.5*u^2)   A(0)/(u^2 + 1)   A(0)/(u^2 + 1)^A(3)

   A(0)         Peak Value          Peak Value        Peak Value
   A(1)        Peak Centroid       Peak Centroid     Peak Centroid
   A(2)       Gaussian Sigma           HWHM%             HWHM%
   A(3)         + A(3)    *          + A(3)   *      Moffat Index
   A(4)         + A(4)*x  *          + A(4)*x *         + A(4)   *
   A(5)                                                 + A(5)*x *

   Notes: # u = (x - A(1))/A(2)
          % Half-width at half maximum
          * Optional depending on NTERMS

   By default the initial starting values for the parameters A are
   estimated from the data.  However, explicit starting values can be
   supplied using the ESTIMATES keyword.  Also, error or weighting
   values can optionally be provided; otherwise the fit is
   unweighted.

   MPFITPEAK fits the peak value of the curve.  The area under a
   gaussian peak is A(0)*A(2)*SQRT(2*!DPI); the area under a
   lorentzian peak is A(0)*A(2)*!DPI.

 RESTRICTIONS:

   If no starting parameter ESTIMATES are provided, then MPFITPEAK
   attempts to estimate them from the data.  This is not a perfect
   science; however, the author believes that the technique
   implemented here is more robust than the one used in IDL's
   GAUSSFIT.  The author has tested cases of strong peaks, noisy
   peaks and broad peaks, all with success.

   Users should be aware that if the baseline term contains a strong
   linear component then the automatic estimation may fail.  For
   automatic estimation to work the peak amplitude should dominate
   over the the maximum baseline.

 INPUTS:
   X - Array of independent variable values, whose values should
       monotonically increase.

   Y - Array of "measured" dependent variable values.  Y should have
       the same data type and dimension as X.


 OUTPUTS:
   A - Upon return, an array of NTERMS best fit parameter values.
       See the table above for the meanings of each parameter
       element.


 RETURNS:

   Returns the best fitting model function.

 KEYWORDS:

   ** NOTE ** Additional keywords such as PARINFO, BESTNORM, and
              STATUS are accepted by MPFITPEAK but not documented
              here.  Please see the documentation for MPFIT for the
              description of these advanced options.

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

   DOF - number of degrees of freedom, computed as
             DOF = N_ELEMENTS(DEVIATES) - NFREE
         Note that this doesn't account for pegged parameters (see
         NPEGGED).

   ERROR - upon input, the measured 1-sigma uncertainties in the "Y"
           values.  If no ERROR or WEIGHTS are given, then the fit is
           unweighted.

   ESTIMATES - Array of starting values for each parameter of the
               model.  The number of parameters should at least be
               three (four for Moffat), and if less than NTERMS, will
               be extended with zeroes.
               Default: parameter values are estimated from data.

   GAUSSIAN - if set, fit a gaussian model function.  The Default.
   LORENTZIAN - if set, fit a lorentzian model function.
   MOFFAT - if set, fit a Moffat model function.

   MEASURE_ERRORS - synonym for ERRORS, for consistency with built-in
                    IDL fitting routines.

   NEGATIVE / POSITIVE - if set, and ESTIMATES is not provided, then
                         MPFITPEAK will assume that a
                         negative/positive peak is present.
                         Default: determined automatically

   NFREE - the number of free parameters in the fit.  This includes
           parameters which are not FIXED and not TIED, but it does
           include parameters which are pegged at LIMITS.

   NTERMS - An integer describing the number of fitting terms.
            NTERMS must have a minimum value, but can optionally be
            larger depending on the desired baseline.  

            For gaussian and lorentzian models, NTERMS must be three
            (zero baseline), four (constant baseline) or five (linear
            baseline).  Default: 4

            For the Moffat model, NTERMS must be four (zero
            baseline), five (constant baseline), or six (linear
            baseline).  Default: 5

   PERROR - upon return, the 1-sigma uncertainties of the parameter
            values A.  These values are only meaningful if the ERRORS
            or WEIGHTS keywords are specified properly.

            If the fit is unweighted (i.e. no errors were given, or
            the weights were uniformly set to unity), then PERROR
            will probably not represent the true parameter
            uncertainties.  

            *If* you can assume that the true reduced chi-squared
            value is unity -- meaning that the fit is implicitly
            assumed to be of good quality -- then the estimated
            parameter uncertainties can be computed by scaling PERROR
            by the measured chi-squared value.

              DOF     = N_ELEMENTS(X) - N_ELEMENTS(PARMS) ; deg of freedom
              PCERROR = PERROR * SQRT(BESTNORM / DOF)   ; scaled uncertainties

   QUIET - if set then diagnostic fitting messages are suppressed.
           Default: QUIET=1 (i.e., no diagnostics)

   SIGMA - synonym for PERROR (1-sigma parameter uncertainties), for
           compatibility with GAUSSFIT.  Do not confuse this with the
           Gaussian "sigma" width parameter.

   WEIGHTS - Array of weights to be used in calculating the
             chi-squared value.  If WEIGHTS is specified then the ERROR
             keyword is ignored.  The chi-squared value is computed
             as follows:

                CHISQ = TOTAL( (Y-MYFUNCT(X,P))^2 * ABS(WEIGHTS) )

             Here are common values of WEIGHTS:

                1D/ERR^2 - Normal weighting (ERR is the measurement error)
                1D/Y     - Poisson weighting (counting statistics)
                1D       - Unweighted

             The ERROR keyword takes precedence over any WEIGHTS
             keyword values.  If no ERROR or WEIGHTS are given, then
             the fit is unweighted.

   YERROR - upon return, the root-mean-square variance of the
            residuals.


 EXAMPLE:

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

   ; Now fit a Gaussian to see how well we can recover the original
   yfit = mpfitpeak(x, y, a, error=sy)
   print, p

   Generates a synthetic data set with a Gaussian peak, and Poisson
   statistical uncertainty.  Then the same function is fitted 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:

   New algorithm for estimating starting values, CM, 31 Oct 1999
   Documented, 02 Nov 1999
   Small documentation fixes, 02 Nov 1999
   Slight correction to calculation of dx, CM, 02 Nov 1999
   Documented PERROR for unweighted fits, 03 Nov 1999, CM
   Copying permission terms have been liberalized, 26 Mar 2000, CM
   Change requirements on # elements in X and Y, 20 Jul 2000, CM
      (thanks to David Schlegel )
   Added documentation on area under curve, 29 Aug 2000, CM
   Added POSITIVE and NEGATIVE keywords, 17 Nov 2000, CM
   Added reference to Moffat paper, 10 Jan 2001, CM
   Added usage message, 26 Jul 2001, CM
   Documentation clarification, 05 Sep 2001, CM
   Make more consistent with comparable IDL routines, 30 Jun 2003, CM
   Assumption of sorted data was removed, CM, 06 Sep 2003, CM

  $Id: mpfitpeak.pro,v 1.7 2003/09/06 16:29:44 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/mpfitpeak.pro)


MPFTEST

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

 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://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Compute the probability of a given F value

 MAJOR TOPICS:
   Curve and Surface Fitting, Statistics

 CALLING SEQUENCE:
   PROB = MPFTEST(F, DOF1, DOF2, [/SIGMA, /CLEVEL, /SLEVEL ])

 DESCRIPTION:

  The function MPFTEST() computes the probability for a value drawn
  from the F-distribution to equal or exceed the given value of F.
  This can be used for confidence testing of a measured value obeying
  the F-distribution (i.e., for testing the ratio of variances, or
  equivalently for the addition of parameters to a fitted model).

    P_F(X > F; DOF1, DOF2) = PROB

  In specifying the returned probability level the user has three
  choices:

    * return the confidence level when the /CLEVEL keyword is passed;
      OR

    * return the significance level (i.e., 1 - confidence level) when
      the /SLEVEL keyword is passed (default); OR

    * return the "sigma" of the probability (i.e., compute the
      probability based on the normal distribution) when the /SIGMA
      keyword is passed.

  Note that /SLEVEL, /CLEVEL and /SIGMA are mutually exclusive.

  For the ratio of variance test, the two variances, VAR1 and VAR2,
  should be distributed according to the chi-squared distribution
  with degrees of freedom DOF1 and DOF2 respectively.  The F-value is
  computed as:

     F = (VAR1/DOF1) / (VAR2/DOF2)

  and then the probability is computed as:

     PROB = MPFTEST(F, DOF1, DOF2, ... )


  For the test of additional parameters in least squares fitting, the
  user should perform two separate fits, and have two chi-squared
  values.  One fit should be the "original" fit with no additional
  parameters, and one fit should be the "new" fit with M additional
  parameters.

    CHI1 - chi-squared value for original fit

    DOF1 - number of degrees of freedom of CHI1 (number of data
           points minus number of original parameters)

    CHI2 - chi-squared value for new fit

    DOF2 - number of degrees of freedom of CHI2

  Note that according to this formalism, the number of degrees of
  freedom in the "new" fit, DOF2, should be less than the number of
  degrees of freedom in the "original" fit, DOF1 (DOF2 < DOF1); and
  also CHI2 < CHI1.

  With the above definition, the F value is computed as:

    F = ( (CHI1-CHI2)/(DOF1-DOF2) )   /  (CHI2/DOF2)

  where DOF1-DOF2 is equal to M, and then the F-test probability is
  computed as:

     PROB = MPFTEST(F, DOF1-DOF2, DOF2, ... )

  Note that this formalism assumes that the addition of the M
  parameters is a small peturbation to the overall fit.  If the
  additional parameters dramatically changes the character of the
  model, then the first "ratio of variance" test is more appropriate,
  where F = (CHI1/DOF1) / (CHI2/DOF2).

 INPUTS:

   F - ratio of variances as defined above.

   DOF1 - number of degrees of freedom in first variance component.

   DOF2 - number of degrees of freedom in second variance component.


 RETURNS:

  Returns a scalar or vector of probabilities, as described above,
  and according to the /SLEVEL, /CLEVEL and /SIGMA keywords.

 KEYWORD PARAMETERS:

   SLEVEL - if set, then PROB describes the significance level
            (default).

   CLEVEL - if set, then PROB describes the confidence level.

   SIGMA - if set, then PROB is the number of "sigma" away from the
           mean in the normal distribution.

 EXAMPLE:

   chi1 = 62.3D & dof1 = 42d
   chi2 = 54.6D & dof2 = 40d

   f = ((chi1-chi2)/(dof1-dof2)) / (chi2/dof2)
   print, mpftest(f, dof1-dof2, dof2)

   This is a test for addition of parameters.  The "original"
   chi-squared value was 62.3 with 42 degrees of freedom, and the
   "new" chi-squared value was 54.6 with 40 degrees of freedom.
   These values reflect the addition of 2 parameters and the
   reduction of the chi-squared value by 7.7.  The significance of
   this set of circumstances is 0.071464757.

 REFERENCES:

   Algorithms taken from CEPHES special function library, by Stephen
   Moshier. (http://www.netlib.org/cephes/)

 MODIFICATION HISTORY:
   Completed, 1999, CM
   Documented, 16 Nov 2001, CM
   Reduced obtrusiveness of common block and math error handling, 18
     Nov 2001, CM
   Added documentation, 30 Dec 2001, CM
   Documentation corrections (thanks W. Landsman), 17 Jan 2002, CM
   Example docs were corrected (Thanks M. Perez-Torres), 17 Feb 2002,
     CM
   Example corrected again (sigh...), 13 Feb 2003, CM

  $Id: mpftest.pro,v 1.7 2003/02/13 23:41:16 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/mpftest.pro)


MPNORMLIM

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

 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://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Compute confidence limits for normally distributed variable

 MAJOR TOPICS:
   Curve and Surface Fitting, Statistics

 CALLING SEQUENCE:
   Z = MPNORMLIM(PROB, [/CLEVEL, /SLEVEL ])

 DESCRIPTION:

  The function MPNORMLIM() computes confidence limits of a normally
  distributed variable (with zero mean and unit variance), for a
  desired probability level.  The returned values, Z, are the
  limiting values: a the magnitude of a normally distributed value
  is greater than Z by chance with a probability PROB:

    P_NORM(ABS(X) > Z) = PROB

  In specifying the probability level the user has two choices:

    * give the confidence level (default);

    * give the significance level (i.e., 1 - confidence level) and
      pass the /SLEVEL keyword; OR

  Note that /SLEVEL and /CLEVEL are mutually exclusive.

 INPUTS:

   PROB - scalar or vector number, giving the desired probability
          level as described above.

 RETURNS:

  Returns a scalar or vector of normal confidence limits.

 KEYWORD PARAMETERS:

   SLEVEL - if set, then PROB describes the significance level.

   CLEVEL - if set, then PROB describes the confidence level
            (default).

 EXAMPLE:

   print, mpnormlim(0.99d, /clevel)

   Print the 99% confidence limit for a normally distributed
   variable.  In this case it is about 2.58 sigma.

 REFERENCES:

   Algorithms taken from CEPHES special function library, by Stephen
   Moshier. (http://www.netlib.org/cephes/)

 MODIFICATION HISTORY:
   Completed, 1999, CM
   Documented, 16 Nov 2001, CM
   Reduced obtrusiveness of common block and math error handling, 18
     Nov 2001, CM

  $Id: mpnormlim.pro,v 1.3 2001/11/18 12:59:17 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/mpnormlim.pro)


MPNORMTEST

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

 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://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Compute the probability of a given normally distributed Z value

 MAJOR TOPICS:
   Curve and Surface Fitting, Statistics

 CALLING SEQUENCE:
   PROB = MPNORMTEST(Z, [/CLEVEL, /SLEVEL ])

 DESCRIPTION:

  The function MPNORMTEST() computes the probability for the
  magnitude of a value drawn from the normal distribution to equal or
  exceed the given value Z.  This can be used for confidence testing
  of a measured value obeying the normal distribution.

    P_NORM(ABS(X) > Z) = PROB

  In specifying the returned probability level the user has two
  choices:

    * return the confidence level when the /CLEVEL keyword is passed;
      OR

    * return the significance level (i.e., 1 - confidence level) when
      the /SLEVEL keyword is passed (default).

  Note that /SLEVEL and /CLEVEL are mutually exclusive.

 INPUTS:

   Z - the value to best tested.  Z should be drawn from a normal
       distribution with zero mean and unit variance.  If a given
       quantity Y has mean MU and standard deviation STD, then Z can
       be computed as Z = (Y-MU)/STD.

 RETURNS:

  Returns a scalar or vector of probabilities, as described above,
  and according to the /SLEVEL and /CLEVEL keywords.

 KEYWORD PARAMETERS:

   SLEVEL - if set, then PROB describes the significance level
            (default).

   CLEVEL - if set, then PROB describes the confidence level.

 EXAMPLES:

   print, mpnormtest(5d, /slevel)

   Print the probability for the magnitude of a randomly distributed
   variable with zero mean and unit variance to exceed 5, as a
   significance level.

 REFERENCES:

   Algorithms taken from CEPHES special function library, by Stephen
   Moshier. (http://www.netlib.org/cephes/)

 MODIFICATION HISTORY:
   Completed, 1999, CM
   Documented, 16 Nov 2001, CM
   Reduced obtrusiveness of common block and math error handling, 18
     Nov 2001, CM
   Corrected error in handling of CLEVEL keyword, 05 Sep 2003

  $Id: mpnormtest.pro,v 1.5 2003/09/06 16:30:02 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/mpnormtest.pro)


SETFITPARM.PRO

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   SetFitParm.pro

 AUTHOR:
	F.Bringezu, denet - Internetservice, Halle Germany,
	bringezu@denet.de

 PURPOSE:
   Provide a widget interface for creating a parinfo structure.
   This parinfo structure can by used by mpfit routines of Craig B. Markwardt.

 MAJOR TOPICS:
   Widget, mpfit.

 CALLING SEQUENCE:
   parinfo=SetFitParm(used_parinfo)

 DESCRIPTION:

   SetFitParm creates PARINFO using a widget interface.
   PARINFO provides constraints for paramters used by the mpfit routines.

   PARINFO is an array of structures, one for each parameter.

   A detailed description can be found in the documentation of mpcurvefit.pro
   This routine creates an array that contains a structure for each element.
   The structure has the following entries.

   - VALUE (DOUBLE): The starting parameter
   - FIXED (BOOLEAN): 1 fix the parameter, 0 don't fix it at the
     point given in VALUE.
   - LIMITS (DBLARRAY(2)): Set upper and lower limit.
   - LIMITED (BOOLEAN ARRAY 2):  Fix the limit.


   The parameter OLDPARINFO is optional. OLDPARINFO is used to set
   the default values in the widget.

   You can simply run:
   test=SetFitParm() to create the array for the first time.
   Once the array is created it can be used to set the default values
   in the widget by calling

   test2=SetFitParm(test)

 INPUTS:


 OPTIONAL INPUTS:

   OLDFITPARM - The default values of the new array

 INPUT KEYWORD PARAMETERS:

   PARENT - if this widget is to be a child, set this keyword to the
            parent widget ID.

 OUTPUT KEYWORD PARAMETERS:

   CANCEL - if the user selected the cancel button on the SETFITPARM
            widget, then this keyword will be set upon exit.

 OUTPUTS:
   PARINFO array of structures

 SEE ALSO:
   mpcurvefit

 MODIFICATION HISTORY:
   Written, FB, 12/1999
   Documented, FB, Jan 2000
   Generalized positioning code, CM 01 Feb 2000

(See /dzd2/heiles/idl/gen/mpfit/setfitparm.pro)


TNMIN

[Previous 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://cow.physics.wisc.edu/~craigm/idl/idl.html

 PURPOSE:
   Performs function minimization (Truncated-Newton Method)

 MAJOR TOPICS:
   Optimization and Minimization

 CALLING SEQUENCE:
   parms = TNMIN(MYFUNCT, X, 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.  TNMIN is based on TN.F (TNBC) by Stephen Nash.

  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 constrained
  and unconstrained optimization problems with a medium number of
  variables.  Function *maximization* can be performed using the
  MAXIMIZE keyword.

  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.

 USER FUNCTION

  The user must define an IDL function which returns the desired
  value as a single scalar.  The IDL function must accept a list of
  numerical parameters, P.  Additionally, keyword parameters may be
  used to pass more data or information to the user function, via the
  FUNCTARGS keyword.

  The user function should be declared in the following way:

     FUNCTION MYFUNCT, p, dp [, keywords permitted ]
       ; Parameter values are passed in "p"
       f  = ....   ; Compute function value
       dp = ....   ; Compute partial derivatives (optional)
       return, f
     END

  The function *must* accept at least one argument, the parameter
  list P.  The vector P is implicitly assumed to be a one-dimensional
  array.  Users may pass additional information to the function by
  composing and _EXTRA structure and passing it in the FUNCTARGS
  keyword.

  User functions may also indicate a fatal error condition using the
  ERROR_CODE common block variable, as described below under the
  TNMIN_ERROR common block definition (by setting ERROR_CODE to a
  number between -15 and -1).

  ANALYTIC vs. NUMERICAL DERIVATIVES

  By default, the user must compute gradient components analytically
  using AUTODERIVATIVE=0.  As explained below, numerical derivatives
  can also be calculated using AUTODERIVATIVE=1.  

  For analytic derivatives, the user should call TNMIN using the
  default keyword value AUTODERIVATIVE=0.  [ This is different
  behavior from MPFIT, where AUTODERIVATIVE=1 is the default. ] The
  IDL user 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.  Upon
  input to the user function, DP is set to a vector with the same
  length as P, with a value of 1 for a parameter which is free, and a
  value of zero for a parameter which is fixed (and hence no
  derivative needs to be calculated).  This input vector may be
  overwritten as needed.

  For numerical derivatives, a finite differencing approximation is
  used to estimate the gradient values.  Users can activate this
  feature by passing the keyword AUTODERIVATIVE=1.  Fine control over
  this behavior can be achieved using the STEP, RELSTEP and TNSIDE
  fields of the PARINFO structure.

  When finite differencing is used for computing derivatives (ie,
  when AUTODERIVATIVE=1), the parameter DP is not passed.  Therefore
  functions can use N_PARAMS() to indicate whether they must compute
  the derivatives or not.  However there is no penalty (other than
  computation time) for computing the gradient values and users may
  switch between AUTODERIVATIVE=0 or =1 in order to test both
  scenarios.

 CONSTRAINING PARAMETER VALUES WITH THE PARINFO KEYWORD

  The behavior of TNMIN can be modified with respect to each
  parameter to be optimized.  A parameter value can be fixed; simple
  boundary constraints can be imposed; limitations on the parameter
  changes can be imposed; properties of the automatic derivative can
  be modified; and parameters can be tied to one another.

  These properties are governed by the PARINFO structure, which is
  passed as a keyword parameter to TNMIN.

  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 the START_PARAMS
              parameter for more information).
  
     .FIXED - a boolean value, whether the parameter is to be held
              fixed or not.  Fixed parameters are not varied by
              TNMIN, 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 values of LIMITED.  Both LIMITED
               and LIMITS must be given together.
  
     .PARNAME - a string, giving the name of the parameter.  The
                fitting code of TNMIN does not use this tag in any
                way.
  
     .STEP - the step size to be used in calculating the numerical
             derivatives.  If set to zero, then the step size is
             computed automatically.  Ignored when AUTODERIVATIVE=0.

     .MPSIDE - the sidedness of the finite difference when computing
               numerical derivatives.  This field can take four
               values:

                  0 - one-sided derivative computed automatically
                  1 - one-sided derivative (f(x+h) - f(x)  )/h
                 -1 - one-sided derivative (f(x)   - f(x-h))/h
                  2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)

              Where H is the STEP parameter described above.  The
              "automatic" one-sided derivative method will chose a
              direction for the finite difference which does not
              violate any constraints.  The other methods do not
              perform this check.  The two-sided method is in
              principle more precise, but requires twice as many
              function evaluations.  Default: 0.

     .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.
             [ NOTE: the PARNAME can't be used in expressions. ]
  
  Future modifications to the PARINFO structure, if any, will involve
  adding structure tags beginning with the two letters "MP" or "TN".
  Therefore programmers are urged to avoid using tags starting with
  these two combinations of letters; otherwise they are free to
  include their own fields within the PARINFO structure, and they
  will be ignored.
  
  PARINFO 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.


 INPUTS:

   MYFUNCT - a string variable containing the name of the function to
             be minimized (see USER FUNCTION above).  The IDL routine
             should return the value of the function and optionally
             its gradients.

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

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

 RETURNS:

   Returns the array of best-fit parameters.


 KEYWORD PARAMETERS:

   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: 0 (analytical derivatives required)

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

   EPSABS - a nonnegative real variable.  Termination occurs when the
            absolute error between consecutive iterates is at most
            EPSABS.  Note that using EPSREL is normally preferable
            over EPSABS, except in cases where ABS(F) is much larger
            than 1 at the optimal point.  A value of zero indicates
            the absolute error test is not applied.  If EPSABS is
            specified, then both EPSREL and EPSABS tests are applied;
            if either succeeds then termination occurs.
            Default: 0 (i.e., only EPSREL is applied).

   EPSREL - a nonnegative input variable. Termination occurs when the
            relative error between two consecutive iterates is at
            most EPSREL.  Therefore, EPSREL measures the relative
            error desired in the function.  An additional, more
            lenient, stopping condition can be applied by specifying
            the EPSABS keyword.
            Default: 100 * Machine Precision

   ERRMSG - a string error or warning message is returned.

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

   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.

   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.

   ITERDERIV - Intended to print function gradient information.  If
               set, then the ITERDERIV keyword is set in each call to
               ITERPROC.  In the default ITERPROC, parameter values
               and gradient information are both printed when this
               keyword is set.

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

              PRO ITERPROC, MYFUNCT, p, iter, fnorm, FUNCTARGS=fcnargs, $
                PARINFO=parinfo, QUIET=quiet, _EXTRA=extra
                ; perform custom iteration update
              END
         
              ITERPROC must accept the _EXTRA keyword, in case of
              future changes to the calling procedure.
          
              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
              common block variable ERROR_CODE to negative value
              between -15 and -1 (see TNMIN_ERROR common block
              below).  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.

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

   MAXIMIZE - If set, the function is maximized instead of
              minimized.

   MAXNFEV - The maximum number of function evaluations to perform.
             If the number is exceeded, then the STATUS value is set
             to -17 and TNMIN returns.  A value of zero indicates no
             maximum.
             Default: 0 (no maximum)

   NFEV - upon return, the number of MYFUNCT function evaluations
          performed.

   NITER - upon return, number of iterations completed.

   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

   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.  Values in PARINFO are never modified
             during a call to TNMIN.

             See description above for the structure of PARINFO.

             Default value:  all parameters are free and unconstrained.

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

   STATUS - an integer status code is returned.  All values greater
            than zero can represent success (however STATUS EQ 5 may
            indicate failure to converge).  Gaps in the numbering
            system below are to maintain compatibility with MPFIT.
            Upon return, STATUS can have one of the following values:

        -18  a fatal internal error occurred during optimization.

        -17  the maximum number of function evaluations has been
             reached without convergence.

        -16  a parameter or function value has become infinite or an
             undefined number.  This is usually a consequence of
             numerical overflow in the user's function, which must be
             avoided.

        -15 to -1 
             these are error codes that either MYFUNCT or ITERPROC
             may return to terminate the fitting process (see
             description of MPFIT_ERROR common below).  If either
             MYFUNCT or ITERPROC set ERROR_CODE to a negative number,
             then that number is returned in STATUS.  Values from -15
             to -1 are reserved for the user functions and will not
             clash with MPFIT.

	   0  improper input parameters.
         
	   1  convergence was reached.

          2-4 (RESERVED)
         
	   5  the maximum number of iterations has been reached

          6-8 (RESERVED)
         

 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.


 COMMON BLOCKS:

   COMMON TNMIN_ERROR, ERROR_CODE

     User routines may stop the fitting process at any time by
     setting an error condition.  This condition may be set in either
     the user's model computation routine (MYFUNCT), or in the
     iteration procedure (ITERPROC).

     To stop the fitting, the above common block must be declared,
     and ERROR_CODE must be set to a negative number.  After the user
     procedure or function returns, TNMIN checks the value of this
     common block variable and exits immediately if the error
     condition has been set.  By default the value of ERROR_CODE is
     zero, indicating a successful function/procedure call.


 REFERENCES:

   TRUNCATED-NEWTON METHOD, TN.F
      Stephen G. Nash, Operations Research and Applied Statistics
      Department
      http://www.netlib.org/opt/tn

   Nash, S. G. 1984, "Newton-Type Minimization via the Lanczos
      Method," SIAM J. Numerical Analysis, 21, p. 770-778
      

 MODIFICATION HISTORY:
   Derived from TN.F by Stephen Nash with many changes and additions,
      to conform to MPFIT paradigm, 19 Jan 1999, CM
   Changed web address to COW, 25 Sep 1999, CM
   Alphabetized documented keyword parameters, 02 Oct 1999, CM
   Changed to ERROR_CODE for error condition, 28 Jan 2000, CM
   Continued and fairly major improvements (CM, 08 Jan 2001):
      - calling of user procedure is now concentrated in TNMIN_CALL,
        and arguments are reduced by storing a large number of them
        in common blocks;
      - finite differencing is done within TNMIN_CALL; added
        AUTODERIVATIVE=1 so that finite differencing can be enabled,
        both one and two sided;
      - a new procedure to parse PARINFO fields, borrowed from MPFIT;
        brought PARINFO keywords up to date with MPFIT;
      - go through and check for float vs. double discrepancies;
      - add explicit MAXIMIZE keyword, and support in TNMIN_CALL and
        TNMIN_DEFITER to print the correct values in that case;
        TNMIN_DEFITER now prints function gradient values if
        requested;
      - convert to common-based system of MPFIT for storing machine
        constants; revert TNMIN_ENORM to simple sum of squares, at
        least for now;
      - remove limit on number of function evaluations, at least for
        now, and until I can understand what happens when we do
        numerical derivatives.
   Further changes: more float vs double; disable TNMINSTEP for now;
     experimented with convergence test in case of function
     maximization, 11 Jan 2001, CM
   TNMINSTEP is parsed but not enabled, 13 Mar 2001
   Major code cleanups; internal docs; reduced commons, CM, 08 Apr
     2001
   Continued code cleanups; documentation; the STATUS keyword
     actually means something, CM, 10 Apr 2001
   Added reference to Nash paper, CM, 08 Feb 2002
   Fixed 16-bit loop indices, D. Schelgel, 22 Apr 2003

 TODO
  - scale derivatives semi-automatically;
  - ability to scale and offset parameters;
  
  $Id: tnmin.pro,v 1.12 2003/04/22 23:42:49 craigm Exp $

(See /dzd2/heiles/idl/gen/mpfit/tnmin.pro)


path procs

path procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

ADDPATH -- ADD A PATH TO THE !PATH IDL ENVIRONMENT SYSTEM VARIABLE.

[Next Routine] [List of Routines]
 NAME:
ADDPATH -- add a path to the !path idl environment system variable.
     
 PURPOSE:
       To add a path to the !PATH IDL environment system variable. 
     
 EXPLANATION:
       !PATH is a string variable listing the directories IDL will search 
       for libraries, include files, and executive commands.  This
       routine allows the user to add a new path to !PATH.  If a
       directory already exists in !PATH, then this directory is moved
       to the front of !PATH.
     
 CALLING SEQUENCE:
       ADDPATH, Newpath [,/EXPAND][,/ALL_DIRS]
     
 INPUTS:
       NEWPATH : The string containing the name of the directory to be
                 added to !PATH.  If the directory specified in the string 
                 does not have a "+" character prepended to it, it is 
                 copied to the output string verbatim. However, 
                 if it does have a leading "+" then EXPAND_PATH searches 
                 the directory and all of its subdirectories for files of 
                 the appropriate type for the path. This can be accomplished 
                 by setting the EXPAND keyword also.
     
 OUTPUTS:
       None.

 KEYWORDS:
       /EXPAND : Default is for ADDPATH not to expand the added directory. 
                 If this keyword is set, any directory below the specified 
                 directory is added to the path if it contains an IDL file 
                 (either a .pro or a .sav file.) Setting this keyword is 
                 equivalent to prepending a "+" to the directory to be added.

       /ALL_DIRS : Set this keyword to return all directories without 
                   concern for their contents, otherwise, EXPAND_PATH 
                   only returns those directories that contain .pro or 
                   .sav files.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       !PATH system variable is changed.

 EXAMPLES:
       Suppose you have a directory with no .pro or .sav files in it,
       and you'd like to add this, and only this, directory to !path:

       IDL> addpath, '/hvc/robishaw/hvc', /ALL_FILES

       To add all the directories below /hvc/robishaw/hvc regardless of
       whether any has a .pro or .sav file, either of the following
       will work:

       IDL> addpath, '/hvc/robishaw/hvc', /EXPAND, /ALL_FILES
       IDL> addpath, '+/hvc/robishaw/hvc', /ALL_FILES


 PROCEDURES CALLED:
       EXPAND_PATH
       ARRAY_EQUAL

 MODIFICATION HISTORY:
   Written Tim Robishaw, Berkeley  26 Jul 2001

(See /dzd2/heiles/idl/gen/path/addpath.pro)


DUPLIX -- FIND IDL FILES WITH THE SAME NAME IN YOUR IDL PATH.

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
DUPLIX -- find IDL files with the same name in your IDL path.

 PURPOSE:
       To find IDL files with the same name in your IDL path.

 CALLING SEQUENCE:
       DUPLIX [, string][, AVOID=string][, /MORE]

 INPUTS:
       FILEGREP : string (scalar); file names with containing this string
                  will be looked for

 KEYWORD PARAMETERS:
       AVOID = string (scalar or array); paths containing this string 
               will not be searched.
       /MORE : Set this keyword to list duplications in style of MORE.

 OUTPUTS:
       None.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       A list of duplicate IDL file names (with full paths) is
       printed to the screen.

 EXAMPLE:
       The following will look for all files with names matching
       'calc' and will avoid any path with 'homework' or 'goddard'
       in its name:

       IDL> duplix, 'calc', AVOID=['homework','goddard']

 NOTES:
       Tested for UNIX and Linux.

 MODIFICATION HISTORY:
   24 May 2003  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/path/duplix.pro)


GETPATH -- PRINT OUT THE CURRENT !PATH SYSTEM VARIABLE AS A LIST OF DIRECTORIES

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
GETPATH -- print out the current !path system variable as a list of directories
     
 PURPOSE:
       To print out the current !path system variable as a list
       of directories, rather than a character-separated string.
     
 CALLING SEQUENCE:
       GETPATH [,/MORE]
     
 INPUTS:
       None.
     
 OUTPUTS:
       None.

 KEYWORDS:
       MORE : Set this keyword to list !PATH in style of MORE.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       The entire IDL path is printed to the screen.

 NOTES:
       Tested for UNIX and Linux.

 MODIFICATION HISTORY:
       Written Tim Robishaw, Berkeley 18 Feb 2002

(See /dzd2/heiles/idl/gen/path/getpath.pro)


WHICH

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

 PURPOSE: 
       To search for any file in the IDL !path that contains the
       user-supplied IDL routine (procedure or function) name.  Also
       returns compilation status of each routine (in IDL lingo,
       whether or not the routine is "resolved".)

 CALLING SEQUENCE:
       WHICH, file

 INPUTS:
       FILE - file name to search for.  The suffix .pro will be
              appended if not included.

 KEYWORD PARAMETERS:
       None.

 OUTPUTS:
       None.

 COMMON BLOCKS:
       None.

 RESTRICTIONS: 
       The IDL !path is searched for file names that are simply the
       module (in IDL documentation, "module" and "routine" are used
       interchangeably) name with a ".pro" suffix appended to them.
       A module stored inside a file whose name is different than the
       module name (followed by a ".pro") will not be found UNLESS
       that module happens to be the currently-resolved module!
       E.g., if the module "pro test_proc" lives in a file named
       "dumb_name.pro", then it will not be found:

       IDL> which, 'test_proc'
       Module TEST_PROC Not Compiled.
       % WHICH: test_proc.pro not found on IDL !path.

       unless it happens to be resolved:

       IDL> .run dumb_name
       % Compiled module: TEST_PROC.
       IDL> which, 'test_proc'
       Currently-Compiled Module TEST_PROC in File:
       /home/robishaw/dumb_name.pro

       However, this is terrible programming style and sooner or
       later, if you hide generically-named modules in
       inappropriately-named files, bad things will (deservedly)
       happen to you.

       The routine further assumes that a file named "dumb_name.pro"
       actually contains a module named "dumb_name"!  If it doesn't,
       then you are a bad programmer and should seek professional
       counseling.
 
 PROCEDURES CALLED:
       STRSPLIT(), WHICH_FIND_ROUTINE()

 EXAMPLES:
       You haven't yet resolved (compiled) the routine (module)
       DEFROI.  Let's look for it anyway:

         IDL> which, 'defroi
         Module DEFROI Not Compiled.

         Other Files Containing Module DEFROI in IDL !path:
         /usr/local/rsi/idl/lib/defroi.pro

       For some reason you have two modules with the same name.
       (This can occur in libraries of IDL routines such as the
       Goddard IDL Astronomy User's Library; an updated version of a
       routine is stored in a special directory while the old version
       is stored in its original directory.) Let's see which version
       of the module ADSTRING we are currently using:

         IDL> which, 'adstring.pro'
         Currently-Compiled Module ADSTRING in File:
         /home/robishaw/idl/goddard/pro/v5.4+/adstring.pro

         Other Files Containing Module ADSTRING in IDL !path:
         /home/robishaw/idl/goddard/pro/astro/adstring.pro

 NOTES:
       First, all currently-compiled procedures and functions are searched.
       Then the remainder of the IDL !path is searched.

 MODIFICATION HISTORY:
   30 May 2003  Written by Tim Robishaw, Berkeley
   17 Feb 2004  Fixed oddity where user tries to call a function as
                if it were a procedure, thus listing the module in both
                the Compiled Functions and Compiled Procedures list.

(See /dzd2/heiles/idl/gen/path/which.pro)


plotting procs

plotting procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

ERRPLOT_X -- PLOT ERROR BARS IN THE X DIRECTION OVER A PREVIOUSLY DRAWN PLOT.

[Next Routine] [List of Routines]
 NAME:
ERRPLOT_X -- Plot error bars IN THE X DIRECTION over a previously drawn plot.

 PURPOSE:
	Plot error bars IN THE X DIRECTION over a previously drawn plot.

 CATEGORY:
	J6 - plotting, graphics, one dimensional.

 CALLING SEQUENCE:
	ERRPLOT_X, Low, High, Y

 INPUTS:
	Low:	A vector of lower estimates, equal to Xdata - error.
	High:	A vector of upper estimates, equal to Xdata + error.
	Y:	A vector containing the ordinate (Y-values).

 KEYWORD Parameters:
	WIDTH:	The width of the error bars, in units of the width of
	the plot area.  The default is 1% of plot width.

 OUTPUTS:
	None.

 COMMON BLOCKS:
	None.

 SIDE EFFECTS:
	An overplot is produced.

 RESTRICTIONS:
	Logarithmic restriction removed.

 PROCEDURE:
	Error bars are drawn for each element.

 EXAMPLES:
	To plot symmetrical error bars where X = data values and 
	ERR = symmetrical error estimates, enter:

		PLOT, X, Y			;Plot data
		ERRPLOT_x, X-ERR, X+ERR, Y	;Overplot error bars.

	If error estimates are non-symetrical, enter:

		PLOT, X, Y
		ERRPLOT, Upper, Lower, Y	;Where Upper & Lower are bounds.

 MODIFICATION HISTORY:
	DMS, RSI, June, 1983.

	Joe Zawodney, LASP, Univ of Colo., March, 1986. Removed logarithmic
	restriction.

	DMS, March, 1989.  Modified for Unix IDL.
       KDB, March, 1997.  Modified to used !p.noclip
       RJF, Nov, 1997.    Removed unnecessary print statement
			   Disable and re-enable the symbols for the bars
	DMS, Dec, 1998.	   Use device coordinates.  Cleaned up logic.
	Carl Heiles nov 26 2001. Pirated idl's errplot, which does
	the y direction, and changed it to do the x direction.

(See /dzd2/heiles/idl/gen/plotting/errplot_x.pro)


GRAPHSELECT

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

 PURPOSE:
	Select points within an area of a graph defined by the cursor.
       Return the indices of these points.

 CALLING SEQUENCE:
       Result = GRAPHSELECT(X, Y [,N][,/NOFILL][,/RESTORE])

 INPUTS:
       X: array of x values on the plot.
       Y: array of y values on the plot.

 KEYWORD PARAMETERS:
       /NOFILL - Set this keyword to inhibit filling of the 
                 defined region on completion. 
       /RESTORE - Set this keyword to restore the display to its 
                  original state upon completion.  N.B., this
                  doesn't do such a great job, but that's DEFROI's
                  fault!

 OUTPUTS:
       Returns the indices of the points that are within the 
       selected area.

 OPTIONAL OUTPUTS:
       N: the number of points inside the selected area.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       The area selected is drawn on the plot window and, unless the 
       /NOFILL keyword is set, filled in.

 RESTRICTIONS:
       Only works for interactive, pixel oriented devices with a cursor.
       Selected region must have less than 1001 vertices.
       Can only be used in most recently created window.

 PROCEDURES CALLED:
       DEFROI()

 EXAMPLE:
       Create some x and y values... 
       IDL> x = indgen(20)
       IDL> y = randomn(seed,20)

       Plot the points...
       IDL> plot, x, y, psym=4

       Select a region of the plot and return the indices 
       of these points...
       IDL> indx = graphselect(x,y,n_indx)

 NOTES:
       If you are trying to obtain the indices of an image, you need to
       pass in arrays of x and y values, e.g., they should be arrays of
       size N_elements(x) by N_elements(y) in which the x array is 
       repeated in N_elements(y) rows and the y array is repeated in
       N_elements(x) columns.  The routine will return the indices of
       points within the selected polygon.

 MODIFICATION HISTORY:
	Written by Carl Heiles. 12 Sep 1998.
       Souped up by Tim Robishaw 19 Aug 2003.

(See /dzd2/heiles/idl/gen/plotting/graphselect.pro)


HOR -- SET HORIZONTAL SCALE FOR ALL PLOTS

[Previous Routine] [Next Routine] [List of Routines]
NAME:
hor -- set horizontal scale for all plots

(See /dzd2/heiles/idl/gen/plotting/hor.pro)


POINTSINSIDE -- FIND POINTS INSIDE CURVE THAT HAS BEEN PLOTTED ON THE TERMINAL WINDOW.

[Previous Routine] [Next Routine] [List of Routines]
NAME:
POINTSINSIDE -- Find points inside curve that has been plotted on the terminal window.

PURPOSE:
	Find the indices of points inside a defined curve that has been
plotted on the terminal window.

CALLING SEQUENCE:
	POINTSINSIDE, x, y, xcurve, ycurve, indx

INPUTS:
	X: the array of x-values of the points on the plot.
	Y: the array of y-values of the points on the plot.
	XCURVE: the array of x-values of the points that define the curve.
	YCURVE: the array of y-values of the points that define the curve.

OUTPUTS:
	INDX: the indices of x and y that lie within the curve defined
	by XCURVE, YCURVE.
indx is equivalent to what you get with the "where" function.

RESTRICTIONS:
	You cannot use this on any plot except for the most recently
defined plot. That is, if you made a plot (nr 1) and then another one
(nr 2), you can use it on nr 2 but not on nr 1.

EXAMPLE:

	You made a contour plot and want to find all points within the 
contour. FIRST, get the vertices of the contour plot:

CONTOUR, delchisq_n, dela0_v, dela1_v, levels=[ 2.3], $  
        xtit='!4d!Xa!D0!N', ytit= '!4d!Xa!D1!N'    , $
        xra = [-1.5,1.5], /xsty, yra=[-0.6,0.6], /ysty  $
        , path_xy=path_xy, /path_data_coords, path_info=path_info 

	NEXT, get rid of the points in path_xy that are garbage at the 
beginning:

xypath = fltarr( (path_info.n)[1], (path_info.n)[1])
for nr=0,1 do xypath[ nr,*] = path_xy[ nr, (path_info.offset)[1]:*]    

	FINALLY, to find the points inside the 2.3 contour, call this routine:

POINTSINSIDE, xpoints, ypoints, xypath[0,*], xypath[1,*], INDX

	after all this, INDX contains the indices of (XPOINTS, YPOINSTS) 
that lie inside the contour.

RELATED PROCEDURES:
	my GRAPHSELECT; IDL'S DEFROI
HISTORY:
	Written by Carl Heiles. 12 Sep 1998.

(See /dzd2/heiles/idl/gen/plotting/pointsinside.pro)


VER -- CHANGE VERTICAL SCALE FOR ALL PLOTS.

[Previous Routine] [List of Routines]
NAME:
ver -- change vertical scale for all plots.

(See /dzd2/heiles/idl/gen/plotting/ver.pro)


ps procs

ps procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

HARDIMAGE -- COPY WINDOW TO POSTSCRIPT FOR 8-BIT COLOR TABLE.

[Next Routine] [List of Routines]
NAME:
hardimage -- copy window to postscript for 8-bit color table. 

PURPOSE:
	This procedure makes a postscript file of the image on the
current window and gives EXACTLY what you see on your workstation
window, including the contrast selected with (for example) XLOADCT, 
OPTIONS, REVERSE TABLE. 
Thus, if you see white on a black background and on your final printed
output you want black on a white background (AND THIS IS THE RECOMMENDED
STYLE!!! IT LOOKS BETTER AND SAVES TONER!!!), then go into XLOADCT and
use it to reverse the color table before using HARDIMAGE. 

CALLING SEQUENCE:
	HARDIMAGE
The name of the postscript file is prompted for.

REQUIRED INPUTS:
	None.


KEYWORDS:

       FILENM: the filename of the ps file. If not given, it is
prompted for; hitting return gives default name test.ps.

	NOINTERP: If undefined or zero, the byte values are scaled up to
255. If nonzero, the byte values are left unchanged.

       LANDSCAPE: The default is to produce a 'portrait' plot. If
you set landscape, it will produce a 'landscape' plot.

       XSIZE: The width of the printed plot in the X direction. See
note under YSIZE. The default is 7 inch in portrait, 9.5 inch in landscape.

       YSIZE: The width of the printed plotin the Y direction. The
default is 9.5 inch in portrait, 7.0 in landscape.
NOTE: IN ALL CASES THE ASPECT RATIO OF THE PLOT WILL BE PRESERVED.
Thus, either XSIZE or YSIZE will determine the maximum size of the plot,
depending on which is smaller.

       XOFFSET: The x offset. See code for defaults.
       YOFFSET: The y offset. See code for defaults. Be careful if
you specify this...you need to know how it is defined!

       EPS: set for encapsulated ps. Note that once it is set, it remains
set until explicitly un-set. Therefore, we explicitly un-set if it is not set.

       OUTPUTS:
       The only output is the postscript file.

COMMON BLOCKS: 
	Uses the IDL common block 'colors'.  The user doesn't need to
know anything about this. 

EXAMPLE:
	First create the grey scale image in the window and make it look
EXACTLY as you want it to look on paper. If you want the width to be
6binches, then type HARDIMAGE, xsize=6.  
Afterwards, check the postscript file using the UNIX command xv.  
If it looks OK, then make the hard copy with the UNIX command lp. 

HISTORY:
	Written by Carl Heiles. Documented 13 Dec 1997. Further work 1 Oct 98.
More revision and documentation 7 jan 00. Fixed for 24 bits 22 jan 01.

(See /dzd2/heiles/idl/gen/ps/hardimage.pro)


HARDIMAGE24 -- COPY WINDOW TO PS FOR 24 BIT COLOR

[Previous Routine] [Next Routine] [List of Routines]
NAME:
HARDIMAGE24 -- copy window to ps for 24 bit color

PURPOSE:
	THIS IS THE 24 BIT VERSION.
	This procedure makes a postscript file of the image on the
current window and gives EXACTLY what you see on your workstation
window.

CALLING SEQUENCE:
	HARDIMAGE24

REQUIRED INPUTS:
	none

KEYWORDS:

       LANDSCAPE: The default is to produce a 'portrait' plot. If
you set landscape, it will produce a 'landscape' plot.

       XSIZE: The width of the printed plot in the X direction. See
note under YSIZE. The default is 7 inch in portrait, 9.5 inch in landscape.

       YSIZE: The width of the printed plotin the Y direction. The
default is 9.5 inch in portrait, 7.0 in landscape.
NOTE: IN ALL CASES THE ASPECT RATIO OF THE PLOT WILL BE PRESERVED.
Thus, either XSIZE or YSIZE will determine the maximum size of the plot,
depending on which is smaller.

       XOFFSET: The x offset. See code for defaults.
       YOFFSET: The y offset. See code for defaults. Be careful if
you specify this...you need to know how it is defined!

OUTPUTS:
	The postscript file, whose name is prompted for.

EXAMPLE:
	First create the 24-bit color image in the window and make it look
EXACTLY as you want it to look on paper.  Then type HARDIMAGE24.  Then
check the postscript file using the UNIX command xv.  If it looks OK,
then make the hard copy with the UNIX command lp. 

HISTORY:
	Written by Carl Heiles. Origin is hardimage. 14 Oct 1999
	mofified and documented 8jan 00

(See /dzd2/heiles/idl/gen/ps/hardimage24.pro)


HARDPLOT -- COPY GRAPH ON CURRENT WINDOW TO PS, 8 BIT COLORTABLE

[Previous Routine] [Next Routine] [List of Routines]
NAME: 
HARDPLOT -- copy graph on current window to ps, 8 bit colortable

PURPOSE:
	This procedure makes a postscript file of what is displayed on
the current window. 
It prompts for the name of the output file.  Unless specified otherwise,
the postscript interchanges black/white so that plots are dark lines on 
a white background. You can specify the size and whether to make the
output image include just black/white or also grey. 

	If NBITS=1, then any nonzero pixel is given the value 255. Thus, 
if you have a graph with several colors, they all come out looking the 
same.

CALLING SEQUENCE:
	HARDPLOT
The name of the postscript file is prompted for.

REQUIRED INPUTS: 
	None.

KEYWORDS:
       FILENM: the filename of the ps file. If not given, it is
prompted for; hitting return gives default name test.ps.

	NBITS: The number of bits used to to write the postscript file. 
For a strictly black/white graph use NBITS=1 to save disk space; this
is the default. If there is shading, then use NBITS=8. For 24 bit 
color, NBITS is always 8, set internally.

	NOREVERSE: Normally the colors are interchanged, with the 
black X-windows background becoming white on the postscript plot and
the white X-window lines becoming black. This saves our toner!!
If Noreverse is specified
as nonzero, then the colors are NOT reversed. This is usually not
recommended--it uses lots of toner and makes bad-looking plots.

	LANDSCAPE: The default is to produce a 'portrait' plot. If
you set landscape, it will produce a 'landscape' plot.

	XSIZE: The width of the printed plot in the X direction. See 
note under YSIZE. The default is 7 inch in portrait, 9.5 inch in landscape.

	YSIZE: The width of the printed plotin the Y direction. The
default is 9.5 inch in portrait, 7.0 in landscape.
NOTE: IN ALL CASES THE ASPECT RATIO OF THE PLOT WILL BE PRESERVED.
Thus, either XSIZE or YSIZE will determine the maximum size of the plot,
depending on which is smaller.

	XOFFSET: The x offset. See code for defaults.
	YOFFSET: The y offset. See code for defaults. Be careful if
you specify this...you need to know how it is defined!

       EPS: set for encapsulated ps. Note that once it is set, it remains
set until explicitly un-set. Therefore, we explicitly un-set if it is not set.

	OUTPUTS: 
	The only output is the postscript file.

	EXAMPLE:
	After the plot is the way you want it, and you want the width 
to be 6 inches, type...HARDPLOT, XSIZE=8

	MODICATION HISTORY:
	Written by Carl Heiles. Modified and redocumented 1 Sep 1998.
	Modified and redocumented 7 jan 2000.

(See /dzd2/heiles/idl/gen/ps/hardplot.pro)


PSCLOSE -- CLOSE PS, OPEN X.

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
PSCLOSE -- close ps, open X.
     
 PURPOSE:
       To close the Postscript device and set the graphics output
       device back to X Windows.
     
 CALLING SEQUENCE:
       PSCLOSE
     
 INPUTS:
       None.
     
 OUTPUTS:
       None.

 KEYWORDS:
       None.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       The device is changed.

 RESTRICTIONS:
       A PostScript file must be open.

 RELATED PROCEDURES:
       PSOPEN

 MODIFICATION HISTORY:
       Written by Tim Robishaw in ancient times.

(See /dzd2/heiles/idl/gen/ps/psclose.pro)


PSOPEN -- OPEN THE POSTSCRIPT DEVICE FOR OUTPUTTING GRAPHICS TO A FILE.

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
PSOPEN -- open the PostScript device for outputting graphics to a file.
     
 PURPOSE:
       To open the PostScript device for outputting graphics to a file.
     
 CALLING SEQUENCE:
       PSOPEN, FILENAME [, /LANDSCAPE] [, XSIZE=width] [, YSIZE=height] [,
       /INCHES] [, /COLOR] [, BITS_PER_PIXEL={1 | 2 | 4 | 8}] [, 
       /ENCAPSULATED]

 Other DEVICE keywords accepted:
       [, /AVANTGARDE | , /BKMAN | , /COURIER | , /HELVETICA | ,
          /ISOLATIN1 | , /PALATINO | , /SCHOOLBOOK | , /SYMBOL | , 
          /TIMES | , /ZAPFCHANCERY | , /ZAPFDINGBATS ] [, 
        /BOLD] [, /BOOK] [, /DEMI] [, FONT_INDEX=integer] [, 
       FONT_SIZE=points] [,  GLYPH_CACHE=number_of_glyphs] [,
       /ITALIC] [, /LIGHT] [, /MEDIUM] [, /NARROW] [, /OBLIQUE] [, 
       OUTPUT=scalar string] [, SCALE_FACTOR=value] [, 
       SET_CHARACTER_SIZE=[font size, line spacing]] [, 
       SET_FONT=scalar string] [, /TT_FONT] [, 
       XOFFSET=value] [, YOFFSET=value]

	CARL: if set, selects HELVETICA/BOLD
 INPUTS:
       FILENAME : String with the name of the PostScript file to be opened.
     
 OUTPUTS:
       None.

 KEYWORDS:
       /LANDSCAPE: If set, landscape orientation is used. Portrait 
                   orientation is the default.

       XSIZE = The width of output generated by IDL. XSIZE is specified 
               in centimeters, unless /INCHES is set. def 8.0in, portrait

       YSIZE = The height of output generated by IDL. YSIZE is specified 
               in centimeters, unless /INCHES is set. def 10.5in, portrait
       
       XOFFSET = The X position, on the page, of the lower left corner of 
                 output generated by IDL. XOFFSET is specified in 
                 centimeters, unless /INCHES is set.

       YOFFSET = The Y position, on the page, of the lower left corner of 
                 output generated by IDL. YOFFSET is specified in 
                 centimeters, unless /INCHES is set.

       /INCHES : Normally, the XOFFSET, XSIZE, YOFFSET, and YSIZE keywords 
                 are specified in centimeters. However, if INCHES is 
                 present and non-zero, they are taken to be in inches 
                 instead.

       /COLOR: Set this keyword to enable color PostScript output.

       BITS_PER_PIXEL = The number of bits per pixel to use. IDL is capable 
                        of producing PostScript images with 1, 2, 4, or 8 
                        bits per pixel. Using more bits per pixel gives 
                        higher resolution at the cost of generating larger 
                        files.  The default value is 8 bits per pixel.

       /ENCAPSULATED: Set this keyword to create an encapsulated 
                      PostScript file, suitable for importing into another 
                      document (e.g., LaTeX). The file extension will be 
                      ".eps" rather than the default ".ps".

       See "Keywords Accepted by the IDL Devices" in the IDL Online Help.  
       Only keywords followed by {PS} are applicable to the PostScript 
       device.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
	The graphics device is set to PostScript.
       If FILENAME is sent in without a ".ps" or ".eps" suffix, it is
       returned with one appended to it.  Also, if the requested
       filename has a ".ps" suffix and the /ENCAPSULATED keyword is
       set, the file will be saved with a ".eps" suffix.  It is
       standard operating procedure for encapsulated PostScript
       files to end with ".eps" and this is enforced by ApJ, so
       we make it so.

 RESTRICTIONS:
       PSOPEN assumes letter-sized pages.
       PSOPEN sets the graphics device to PostScript and leaves a
       file open upon completion.  Therefore, after all graphics
       have been created for this file, it is necessary to close
       the file (DEVICE, /CLOSE_FILE) and set the graphics device
       back to the default for your machine (probably X Windows).
       PSCLOSE will do all of this for you.

 EXAMPLE:
       Make a PostScript file 5in by 5in:
         IDL> psopen, 'foo.ps', XSIZE=5, YSIZE=5, /INCHES
         IDL> plot, findgen(30)^2
         IDL> psclose

       Make a color PostScript image:
         IDL> psopen, 'foo.ps', /COLOR
         IDL> setcolors, /SYSTEM_VARIABLES
         IDL> plot, findgen(30), color=!red
         IDL> oplot, findgen(30)^2, color=!blue
         IDL> xyouts, 0.25, 0.5, /normal, 'Parabola', color=!green
         IDL> xyouts, 0.55, 0.5, /normal, 'Line', color=!magenta
         IDL> psclose
         IDL> setcolors, /SYSTEM_VARIABLES

       Make a PostScript image taking advantage of PostScript fonts
       AND the ability (unique in IDL fontdom) of PS fonts to have
       embedded formatting command indices changed:
         IDL> psopen, 'foo.ps', /HELVETICA, /BOLD, /OBLIQU, /ISOLATIN1
         IDL> device, /BKMAN, /DEMI, /ITALIC, /ISOLATIN1, FONT_INDEX=10
         IDL> plot, findgen(3), FONT=0, $
         IDL>   xtit='Galactic Radius !10'+string(174B)+'!X [kpc]', $
         IDL>   ytit='Density !10'+string(181B)+'!X [cm!E-3!N]'
         IDL> psclose

 NOTES:
       Add device keywords if you want to change font characteristics
       but remember that in order to use PostScript fonts you must either 
       set the !P.FONT system variable to 0 (so that IDL uses the 
       hardware fonts) or send any of the plotting routines the 
       FONT keyword set to 0.
       
       Remember that the PostScript device is 8-bit and has exactly
       256 color table indices.  So, on your X-windows device, if
       you're running 8-bit PseudoColor, you've probably got less
       than 256 color table indices available... if you're running
       24-bit TrueColor or DirectColor, you've got 16 million color
       indices and no color table at all.  If you're storing color
       table indices in variables, you'll need to reassign these
       variables with the correct color table indices after you've
       opened the PostScript device (and again when you've closed
       it!)

 RELATED PROCEDURES:
       PSCLOSE

 MODIFICATION HISTORY:
       Written by Tim Robishaw in ancient times.
       27 Feb 2002  Spiffed up by TR
       28 Jan 2004  Cosmetic changes. TR

(See /dzd2/heiles/idl/gen/ps/psopen.pro)


SHARPCORNERS

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

 PURPOSE:
       If you look closely, especially if you make your axes thick,
       the corners of your plots are not sharp.  (Try example below.)
       This procedure makes sharp corners on your plot.

 CALLING SEQUENCE:
       SHARPCORNERS [, COLOR=value] [, THICK=value]

 INPUTS:
       None.

 KEYWORD PARAMETERS:
       COLOR = color index of the axes.
       THICK = thickness of the axes.

 OUTPUTS:
       None.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       Plot corners are now sharp!

 RESTRICTIONS:
       The thickness of the X and Y axes must be the same.

 EXAMPLE:
       IDL> plot, findgen(5), XTHICK=5, YTHICK=5
       IDL> sharpcorners, THICK=5

 MODIFICATION HISTORY:
   26 Apr 2004  Written by Tim Robishaw, Berkeley
   19 Aug 2005  TR: have to redraw the first leg after the other four in order
                for PostScript plots to have the first corner sharp.  This is
                weird since it's not necessary for X windows.

(See /dzd2/heiles/idl/gen/ps/sharpcorners.pro)


sig_processing procs

sig_processing procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

CLEAN_SP

[Next Routine] [List of Routines]
PURPOSE: DO CLEAN ON DATA, USING PSF.

INPUTS:
XDATA, the x values of the data, a 1 d array of length M
DATA, the data stream, a 1 d array of length M
PSFFCN, a function name that evaluates the psf
GAIN, the loop gain
NITER, the nr of iterations to do 

OUTPUTS:
CLEAN_COMP, the list of clean components. A 2-d array of size
	2 X NITER. SECOND comp is amplitude actually subtracted, 
	FIRST is the position xdata.
	DATA_CLEAN, the current version of the cleaned data

(See /dzd2/heiles/idl/gen/sig_processing/clean_sp.pro)


CUMFILTER -- FILTER BAD DATA USING CUMULATIVE DISTRIBUTION FUNCTION.

[Previous Routine] [Next Routine] [List of Routines]
NAME:
CUMFILTER -- filter bad data using cumulative distribution function.

PURPOSE: filter spikes from a distribution. uses the cumulative
distribution to define the effective sigma of the pdf so that outliers
don't artificially incrrease the sigmaa.

CALLING SEQUENCE:

	CUMFILTER, data, range, limit, indxgood, indxbad, countbad, $
	correct=correct, median=median

INPUTS:

	DATA, the vector of data to filter; can be output, too, if
CORRECT is set..

	RANGE, the number of elements to use for defining the non-noise
distribution. For now, set this equal to n_elements(data)/4

	LIMIT, the limit above which to define points as bad. For now,
set equal to 3. Phil tested this--the number should be bigger, but this
works reasonably well. IF LIMIT IS SET EQUAL TO OR LT ZERO, THEN THE
DEFAULT IS twice Chauvenet's criterion.

KEYWORDS:

	CORRECT: returns the corrected version of the data in place as
DATA. 

	MEDIAN: does running median filter before doing the
distribution. Set median when there are systematic departures from
flatness. In fact, you might as well ALWAYS set it.

	SIGMA_EMPIRICAL: the sigma derived empirically from the slope
of the cdf. If the input is a true Gaussian pdf, this sigma should 
equal that of the Gaussian.

OUTPUTS:

	INDXGOOD, the indx numbers of the good points.

	INDXBAD, the indx numbers of the bad points.

	COUNTBAD, the number of bad points found

METHOD:

	Loosely based on looking at the central portion of the
cumulative distribution, which is unaffeced by outliers. Use this to
define the sigma above which you discard points.

(See /dzd2/heiles/idl/gen/sig_processing/cumfilter.pro)


DFT -- DIRECT FT USING IDL CONVENTION FOR FORWARD/REVERSE

[Previous Routine] [Next Routine] [List of Routines]
NAME:
DFT -- DIRECT FT USing IDL CONVENTION FOR FORWARD/REVERSE

CALLING SEQUENCE: dft, inputx, inputy, outputx, outputy, [/inverse]

INPUTS:
	inputx, x-value at which input sig is sampled
	inputy, amplitude of input sig
	outputx, x-values at which you want the ft computed.
KEYWORD: 
	INVERSE. if set, does the idl inverse equivalent.
OUTPUTS
	outputy, ft of sig evaluated at outputx. complex.

TO TEST AND COMPARE WTIH THE FFT: see the attached 

	pro dfttst_2


IN PARTICULAR, NOTE HOW THE ORDER OF THE INPUT AND OUTPUT ARRAYS FOR THE
FFT MUST BE REARRANGED SO AS TO BE MONOTINICALLY INCREASING

MODS
	11nov04, carlh added check to see which method is faster in for loop.

(See /dzd2/heiles/idl/gen/sig_processing/dft.pro)


FSHIFT -- LIKE IDL'S SHIFT, BUT DOES FRACTIONAL SHIFTS

[Previous Routine] [Next Routine] [List of Routines]
NAME:
fshift -- like idl's shift, but does fractional shifts
PURPOSE:
	LIKE IDL'S SHIFT, BUT WORKS FOR **FRACTIONAL** CHANNELS 
USING LINEAR INTERPOLATION.

(See /dzd2/heiles/idl/gen/sig_processing/fshift.pro)


HISTO_WRAP -- WRAPPER FOR HISTOGRAM THAT RETURNS THE BIN EDGES AND CENTERS

[Previous Routine] [Next Routine] [List of Routines]
NAME:
histo_wrap -- wrapper for histogram that returns the bin edges and centers

PURPOSE: wrapper for histogram that returns the bin edges and centers
note fixed inputs: max, min, nbins. 

CALLING SEQUENCE:
	histo_wrap, x, min, max, nbins, bin_edges, bin_cntrs, hx

INPUTS:
	X, the input array
	MIN, the min value in the histogram
	MAX, the max value in the histogram
	NBINS, the nr of bins in the histogram

OUTPUTS
	BIN_EDGES
	BIN_CNTRS
	HX, the histogram of the input array x

(See /dzd2/heiles/idl/gen/sig_processing/histo_wrap.pro)


LOMB -- EVALUATE LOMB PERIODOGRAM

[Previous Routine] [Next Routine] [List of Routines]
NAME:
lomb -- evaluate lomb periodogram

LOMB METHOD FOR PWR SPECTRUM
INPUTS:
	time, time at which input sig is sampled
	tsig, amplitude of input sig
	frqout, freqs at which you want the ft computed.
OUTPUTS
	Pftsig, PWR SPECT of sig evaluated at frqout. complex.

(See /dzd2/heiles/idl/gen/sig_processing/lomb.pro)


LSCLEAN_CARL, DO A 'LEAST-SQUARES' 1D CLEAN.

[Previous Routine] [Next Routine] [List of Routines]
NAME:
LSCLEAN_CARL, DO A 'LEAST-SQUARES' 1D CLEAN.

CALLING SEQUENCE: lsclean_carl, inputx, inputy, gain, nitermax, $
	outputx, outputy, clean_comp, cleanoutputy, clean_iny, $
	plot_clean=plot_clean,  print_clean_comp=print_clean_comp

INPUTS:
WE DESCRIBE THE INPUTS AND OUTPUTS AS IF THE INPUTS ARE FREQ, OUTPUTS ARE TIME
INPUTX[], the input x values (e.g. freqs)
INPUTY[], the input y values (normally amplitude--real, not complex)
GAIN, the loop gain. should be high. should be adjusted inside for s/n of fit.
NITERMAX, the max nr of iterations, equal to nr of clean components that
	will be generated
OUTPUTX[] is the set of output x values (times) that will be searched for peaks

KEYWORDS:
PLOT_CLEAN. if set, plots each iteration and asks for key input to continue.
PRINT_CLEAN_COMP if set, print list of clean comp.

OUTPUTS:
OUTPUTY[] is the dirty y values correspondinig to OUTPUTX (complex)
CLEAN_COMP[ 2,NITERMAX], the list of clean components. clean_comp[0,*]
	is the X-value of the clean component (time), 
	clean_comp[1,*] are the [cos, sin] amplitudes.
CLEANOUTPUTY, the current version of the cleaned OUTPUTY values, equal to
	OUTPUTY minus the sum of the currently-existing clean components.
CLEAN_INY, the cleaned version of INPUTY obtained from the clean components
OUTPUTY_RECON, the output y values reconstructed from the clean components
       by adding them. Thus, this is a series of spikes that represent
       the complex clean components.

METHOD AND COMMENTS:
(1) calculate the digital fourier transorm (DFT) amplitude spectrum. 
that is, use INPUTX, CLEANY to calculate a straight dirty Y array.
then picks the max amplitude and remembers its X-value OUTPUTX_PEAK

(2) Does a ls fit: CLEANY = A + B COS( outputx_peak) + C SIN( outputx_peak)

(3) Sets clean_comp[ 0,nr]=outputx_peak ; clean_comp[ 1,nr]= complexarr( B,C)

(4) Loop back to (1) and repeat until done.

NOTE: to calculate values of cleaned input signal CLEAN_INY 
	for any input x value XV (even one that wasn't in the original array):

clean_iny= fltarr( n_elements( XV))
FOR NR= 0, NITERMAX-1 DO BEGIN
coeffs= [ 0., float( clean_comp[ 1, nr]), imaginary( clean_comp[ 1,nr])]
poly_ft_eval, XV, 0, coeffs, float( clean_comp[ 0,nr]), $
        yeval, yeval_poly, yeval_fourier
clean_iny= clean_iny+ yeval_fourier
ENDFOR

(See /dzd2/heiles/idl/gen/sig_processing/lsclean_carl.pro)


STDCLEAN_CARL, DO A STANDARD 1D CLEAN. (A/LA DREHER ET AL PAPER)

[Previous Routine] [List of Routines]
NAME:
STDCLEAN_CARL, DO A STANDARD 1D CLEAN. (a/la dreher et al paper)

CALLING SEQUENCE: stdclean_carl, inputx, inputy, gain, nitermax, $
	outputx, outputy, clean_comp, cleanoutputy, clean_iny, $
	plot_clean=plot_clean,  print_clean_comp=print_clean_comp

INPUTS:
WE DESCRIBE THE INPUTS AND OUTPUTS AS IF THE INPUTS ARE FREQ, OUTPUTS ARE TIME
INPUTX[], the input x values (e.g. freqs)
INPUTY[], the input y values (normally amplitude--real, not complex)
GAIN, the loop gain. try 0.3??
NITERMAX, the max nr of iterations, equal to nr of clean components that
	will be generated
OUTPUTX[] is the set of output x values (times) that will be searched for peaks
	************ IMPORTANT ******************
	OUTPUTX MUST RANGE FROM 0 TO +TMAX WITH UNIFORM STEP SIZE.

KEYWORDS:
PLOT_CLEAN. if set, plots each iteration and asks for key input to continue.
PRINT_CLEAN_COMP if set, print list of clean comp.

OUTPUTS:
OUTPUTY[] the straight DFT-calculated (dirty) y values correspondinig to OUTPUTX,
	normally known as the 'dirty output' 
CLEAN_COMP[ 2,NITERMAX], the list of clean components. clean_comp[0,*]
	is the OUTPUTX-value of the clean component (time), 
	clean_comp[1,*] are the [cos, sin] amplitudes.
CLEANOUTPUTY, the current version of the cleaned OUTPUTY values, equal to
	OUTPUTY minus the sum of the currently-existing clean components.
CLEAN_INY, the version of INPUTY calculated from the clean components
OUTPUTY_RECON, the output y values reconstructed from the clean components
	by adding them. Thus, this is a series of spikes that represent 
	the complex clean components.

METHOD AND COMMENTS:

CLEAN_COMP are defined only for positive outputx.

NOTE: to calculate values of cleaned input signal CLEAN_INY 
	for any input x value XV (even one that wasn't in the original array):

clean_iny= fltarr( n_elements( XV))
FOR NR= 0, NITERMAX-1 DO BEGIN
coeffs= [ 0., float( clean_comp[ 1, nr]), imaginary( clean_comp[ 1,nr])]
poly_ft_eval, XV, 0, coeffs, float( clean_comp[ 0,nr]), $
        yeval, yeval_poly, yeval_fourier
clean_iny= clean_iny+ yeval_fourier
ENDFOR

(See /dzd2/heiles/idl/gen/sig_processing/stdclean_carl.pro)


stat procs

stat procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

CHAUVENET

[Next Routine] [List of Routines]
 NAME:
       CHAUVENET
     
 PURPOSE:
       Given the residuals of a fit, this routine returns the indices
       of points that pass Chauvenet's criterion.  You can also return
       the number of points that passed, the indices of the points
       that failed, the number of points that failed, and a byte mask
       where 1B represents a passing point and 0B represents a failing
       point.
     
 EXPLANATION:
       Chauvenet's criterion states that a datum should be discarded if 
       less than half an event is expected to be further from the mean of 
       the data set than the suspect datum.  You should only use this
       criterion if the data are normally distributed.  Many authorities
       believe Chauvenet's criterion should never be applied a second
       time.  Not me.
     
 CALLING SEQUENCE:
       RESULT = CHAUVENET(X [,NPASS][,REJECT=reject][,
                          NREJECTS=nrejects][,MASK=mask][,/ITERATE])
     
 INPUTS:
       residuals : The residuals of a fit to data.
     
 OUTPUTS:
       The indices of the data that passed Chauvenet's criterion.

 OPTIONAL OUTPUTS:
       NPASS : The number of data that passed Chauvenet's criterion.

 KEYWORDS:
       /ITERATE : Iterate until there are no data that fail
                  Chauvenet's criterion.

       REJECT : The indices of data that failed Chauvenet's criterion.

       NREJECTS: The number of data that failed Chauvenet's criterion.

       MASK : A byte mask which is set to 1B where a datum passed
              Chauvenet's criterion and 0B where a datum failed.

 RESTRICTIONS:
       Only works for IDL versions 5.4 and above!!!
       (Uses COMPLEMENT keyword for WHERE function.)

 PROCEDURES CALLED:
      INVERF 

 EXAMPLE:
       RESIDUALS is an array with the difference between DATA and
       a fit to these data.  Find the indices of 

       IDL> passed = chauvenet(RESIDUALS,NPASS,REJECT=failed)

       Plot the data points and highlight the data that failed:

       IDL> plot, DATA, ps=3
       IDL> oplot, DATA[failed], ps=4

 NOTES:
       See Taylor's Intro to Error Analysis pp 142-144 OR
       Bevington & Robinson's Data Reduction & Error Analysis for the
       Physical Sciences p 58.

       Any non-finite values are ignored... rather than throwing
       them out, the user should think about why they have non-
       finite values and deal with them on their own terms.

       If the data you are testing are not drawn from a Gaussian
       parent distribution, then you have no business using this
       routine!

 MODIFICATION HISTORY:
       Written by Tim Robishaw, Berkeley  Dec 13, 2001

(See /dzd2/heiles/idl/gen/stat/chauvenet.pro)


GAUSSDIST

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       GAUSSDIST
     
 PURPOSE:
       Creates Gaussian distribution(s) with the width, center and
       height as specified.  
     
 CALLING SEQUENCE:
       RESULT = GAUSSDIST(X, ZRO, CEN, WID, HGT)
     
 INPUTS:
       X : Vector of abscissa values.

       ZRO : The zero offset of the Gaussian distribution. A scalar.

       CEN : Array (or scalar) of centers of Gaussian components.

       WID : Array (or scalar) of widths of Gaussian components.

       HGT : Array (or scalar) of heights of Gaussian components.

 OUTPUTS:
       Returns the Gaussian distribution of the input parameters.

 EXAMPLE:
  Plot two Gaussians:
    IDL> plot, gaussdist(findgen(2000)/100., 0, [10,15], [6,3], [6,3])

 MODIFICATION HISTORY:
       Written Tim Robishaw, Berkeley 01 Dec 2001.

(See /dzd2/heiles/idl/gen/stat/gaussdist.pro)


GAUSSNOISE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       GAUSSNOISE
     
 PURPOSE:
       Creates pseudo-random Gaussian distribution with specified
       mean and standard deviation.
     
 CALLING SEQUENCE:
       RESULT = GAUSSNOISE(DIMENSION, MEAN, SIGMA)
     
 INPUTS:
       DIMENSION - Number of elements for desired noise distribution. 
       MEAN - Mean of desired distribution.
       SIGMA - Standard deviation of desired distribution.

 KEYWORDS:
       /DOUBLE - Return distribution in double-precision floating-point.

 OUTPUTS:
       Returns pseudo-random Gaussian distribution with specified
       mean and standard deviation.

 EXAMPLE:
    IDL> plot, gaussnoise(1024, 10.0, 0.07)

 MODIFICATION HISTORY:
   15 Jul 2003  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/stat/gaussnoise.pro)


INVERF -- INVERSE ERROR FUNCTION

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
INVERF -- inverse error function
     
 PURPOSE:
       Returns the inverse error function for a given probabality.
       
     
 CALLING SEQUENCE:
       RESULT = INVERF(X)
     
 INPUTS:
       X : Number representing the integrated Gaussian probability 
           distribution between -N standard deviations and +N standard
           deviations.
     
 OUTPUTS:
       Returns the inverse error function of X.  This is the number of
       standard deviations that the error function needs to be integrated 
       over in order to yield the value X.

 KEYWORDS:
       None.

 COMMON BLOCKS:
       None.

 RESTRICTIONS:
       The error function is normalized to unity, so it is meaningless
       to ask for the inverse error function of a value larger than
       one or less than zero.  If you do, the function will stop and 
       tell you to contemplate your mistake.

       To check behavior visually:
         IDL> x = dindgen(10001)/10000.
         IDL> plot, x, abs(x-errorf(inverf(x))), /ylog, yr=[1d-9,1d-1]
         IDL> oplot, !x.crange, 4.5d-4*[1,1], lines=1

       Hasting's approximation (see NOTES below) is accurate to
       4.5d-4, and we see this is indeed the case.

       Alternatively, check how large x can become before
       inverf(errorf(x)) fails, i.e. the difference between
       x and inverf(errorf(x)) becomes larger than 4.5d-4:

         IDL> x = dindgen(10001)/10000.*6
         IDL> plot, x, abs(x-inverf(errorf(x))), /ylog, yr=[1d-9,1d-1]
         IDL> oplot, !x.crange, 4.5d-4*[1,1], lines=1

       So, if x is double precision, inverf(errorf(x)) is accurate
       up to x=5.34.  If x is floating precision, it is accurate up to
       x=3.11.  This makes plenty of sense, since beyond this limit out in 
       the wings of the normal distribution, the error function is exactly 
       one to machine precision. So the inverse error function can't be
       expected to differentiate between the error function of 7 and the
       error function of 200!

 NOTES:
       Using notation from Abramowitz & Stegun, page 931, we see:

         erf(x) = 2*P(x*sqrt(2)) - 1
         P(x*sqrt(2)) = 1 - Q(x*sqrt(2))

       Given Q(x*sqrt(2))=p, we can use Hasting's approximation 
       for digital computers (Abramowitz & Stegun, page 933) to get:

         x*sqrt(2) = t - (c0+c1*t+c2*t^2)/(1+d1*t+d2*t^2+d3*t^3) + e(p)

       where |e(p)| < 4.5d-4 and the constants appear in the code below.

 MODIFICATION HISTORY:
       Written Tim Robishaw, Berkeley  22 Feb 2002
       Stole idea from Carl Heiles.
       Added machine precision considerations. TR 23 Feb 2002

(See /dzd2/heiles/idl/gen/stat/inverf.pro)


P_CHISQ -- CALCULATE THE CHI SQUARE PDF GIVEN CHISQ AND NU.

[Previous Routine] [Next Routine] [List of Routines]
NAME:
p_chisq -- CALCULATE the CHI SQuare pdf GIVEN CHISQ AND NU.
CALCULATE CHI SQ PROB DIST GIVEN CHISQ AND NU.
CALLIING SEQUENCE:
	PCHISQ= P_CHIS1Q( CHISQ, NU)

INPUTS:
	CHISQ, the value of chisquared
	NU, the degrees of freedom

OUTPUTS: 
	P_CHISQ, the probability of finding chisq given nu.

COMMENTS:

	for nu le 30, uses the exact formula. however, factors of this
formula go to infinity for large nu, so we revert to a logarithmic
approximation for large nu.

(See /dzd2/heiles/idl/gen/stat/p_chisq.pro)


THETA_RANDOM -- GENERATE RANDOM NUMBERS DISTRIBUTED ACCORDING TO SIN THETA.

[Previous Routine] [Next Routine] [List of Routines]
NAME:
theta_random -- generate random numbers distributed according to sin theta.

PURPOSE: generate random numbers distributed according to sin theta.
CALLING SYNTAX:
	theta_random, nr, theta_random, seed=seed, pi_over2=pi_over2

INPUT:
	nr, nr of random theta's to generate.
KEYWORDS:
	seed--the usual
	pi_over2--restricts theta range to 0 --> pi/2 instead of 0 --> pi.
OUTPUT:
	theta_random, the set of random theta's.

(See /dzd2/heiles/idl/gen/stat/theta_random.pro)


WT_AVG

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

 PURPOSE:
       To take a simple weighted average of data.

 CALLING SEQUENCE:
       Result = WT_AVG(data, weight [, dimension] [, /SIGMA] [, /DOUBLE] [,
       WT_SIGMA=variable]

 INPUTS:
       data - an array of data.
       weight - an array of weights. If the /SIGMA keyword is set, these
                values are assumed to be the uncertainties in each datum.

 OPTIONAL INPUTS:
       dimension - the dimension over which to average.

 KEYWORD PARAMETERS:
       /SIGMA: set this keyword when inputing the uncertaintied in each 
               datum. The weight will then be set to 1/sigma^2.
       /DOUBLE: return the result in double precision.
       WT_SIGMA - set this keyword to a named variable that will contain
                  uncertainty of the weighted mean.

 COMMON BLOCKS:
       None.

 EXAMPLE:
       The example from Bevington:

       IDL> d = [fltarr(40)+1.022,fltarr(10)+1.018]
       IDL> s = [fltarr(40)+0.01,fltarr(10)+0.004]
       IDL> print, wt_avg(d,s,/SIGMA,WT_SIGMA=wt_sigma)
             1.01956
       IDL> print, wt_sigma
         0.000987730

 MODIFICATION HISTORY:
   17 Jun 2004  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/stat/wt_avg.pro)


textoidl procs

textoidl procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

MATCHDELIM

[Next Routine] [List of Routines]
 NAME:
       MATCHDELIM
 PURPOSE:
        Match open/close delimiters in a string.
 CATEGORY:
        text/strings
 CALLING SEQUENCE:
        position = matchdelim( strn, [openpos])
 INPUTS:
        strn        -- a string containing an open                 in
                       delimiter (e.g. '{') in which you 
                       want to find the matching closing  
                       delimiter (e.g. '}')
 KEYWORD PARAMETERS:
        OPEN_DELIM  -- A single character containing the opening   in
                       delimiter (e.g. '(').  Default is '{'
        CLOSE_DELIM -- A single character containing the closing   in
                       delimiter (e.g. ')').  Default is '}'
 OUTPUTS:
        position -- returns the position in strn of the            out
                    closing delimiter, -1 if no closing found.
        openpos  -- Set to a named variable to receive the         out
                    position of the first opening delimiter.
                    Optional.
 COMMON BLOCKS:
 SIDE EFFECTS:
 NOTES:
        - Any pair of (nonidentical) characters can be used as
          delimiters. 
 EXAMPLE:
        matchdelim('{one{two}}three') returns 9, the character just
        before 'three'.  
 MODIFICATION HISTORY:
       $Id: matchdelim.pro,v 1.3 1996/06/14 20:00:27 mcraig Exp $
       $Log: matchdelim.pro,v $
       Revision 1.3  1996/06/14 20:00:27  mcraig
       Updated Copyright info.

       Revision 1.2  1996/05/09 00:22:17  mcraig
       Removed restriction that open delim must be first char.  Added argument
       to allow for return of position of open delim.

       Revision 1.1  1996/01/31 18:41:06  mcraig
       Initial revision

 RELEASE:
       $Name: Rel_2_1_2 $

 COPYRIGHT:
  Copyright (C) 1996 The Regents of the University of California, All
  Rights Reserved.  Written by Matthew W. Craig.
  See the file COPYRIGHT for restrictions on distrubting this code.
  This code comes with absolutely NO warranty; see DISCLAIMER for details.

(See /dzd2/heiles/idl/gen/textoidl/matchdelim.pro)


NEXTTOK

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       NEXTTOK
 PURPOSE:
       Find the next occurance of any of a set of characters in a
       string and return the character which occurs next.
 CATEGORY:
       text/strings
 CALLING SEQUENCE:
       tok = nexttok( strn, tokens )
 INPUTS:
       strn   -- string to be searched for sub/superscripts    in
       tokens -- string containing characters to be found.     in
 KEYWORD PARAMETERS:
       POSITION -- Set to a named variable to get position     out
                   of next token, or -1 if none found.
       /HELP    -- Print useful message and exit.
 OUTPUTS:
       tok    -- Contains the character among tokens which     out
                 occurs next in strn, or null '' if none found.
 COMMON BLOCKS:
 SIDE EFFECTS:
 NOTES:
 EXAMPLE:
       nexttok( 'x^2 + N_j^3', '^_', position=pos ) returns '^' and sets
       pos to 1.
 MODIFICATION HISTORY:
       $Id: nexttok.pro,v 1.4 2004/06/15 17:25:54 mcraig Exp $
       $Log: nexttok.pro,v $
       Revision 1.4  2004/06/15 17:25:54  mcraig
       Fixed bug in regular expression, changed array notation to square brackets

       Revision 1.3  1996/06/14 20:00:27  mcraig
       Updated Copyright info.

       Revision 1.2  1996/05/09 00:22:17  mcraig
       Generalized so that the next occurence of any of a set of characters will
       be returned.

       Revision 1.1  1996/01/31 18:41:06  mcraig
       Initial revision

 RELEASE:
       $Name: Rel_2_1_2 $

 COPYRIGHT:
  Copyright (C) 1996 The Regents of the University of California, All
  Rights Reserved.  Written by Matthew W. Craig.
  See the file COPYRIGHT for restrictions on distrubting this code.
  This code comes with absolutely NO warranty; see DISCLAIMER for details.

(See /dzd2/heiles/idl/gen/textoidl/nexttok.pro)


SHOWTEX

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       SHOWTEX
 PURPOSE:
       Display TeX sequence translation table on current graphics device.
 CATEGORY:
       text/strings
 CALLING SEQUENCE:
       showtex
 INPUTS:
 KEYWORD PARAMETERS:
       /HELP -- print out info on use of the function
                and exit.
       FONT  -- Set to 0 to use hardware font, -1 to use vector.
                Note that the only hardware font supported is
                Postscript
 OUTPUTS:
 COMMON BLOCKS:
 SIDE EFFECTS:
       Plot is created.
 NOTES:
       Hardware fonts are supported only for device PS (PostScript)
 EXAMPLE:
 MODIFICATION HISTORY:
       $Id: showtex.pro,v 1.4 2004/06/15 17:25:54 mcraig Exp $
       $Log: showtex.pro,v $
       Revision 1.4  2004/06/15 17:25:54  mcraig
       Fixed bug in regular expression, changed array notation to square brackets

       Revision 1.3  1996/06/14 20:00:27  mcraig
       Updated Copyright info.

       Revision 1.2  1996/05/09 00:22:17  mcraig
       Added error handling and updated built in help.

       Revision 1.1  1996/02/08 18:55:12  mcraig
       Initial revision

 RELEASE:
       $Name: Rel_2_1_2 $

 COPYRIGHT:
  Copyright (C) 1996 The Regents of the University of California, All
  Rights Reserved.  Written by Matthew W. Craig.
  See the file COPYRIGHT for restrictions on distrubting this code.
  This code comes with absolutely NO warranty; see DISCLAIMER for details.

(See /dzd2/heiles/idl/gen/textoidl/showtex.pro)


STRCNT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       STRCNT
 PURPOSE:
       Count number of occurrences of a substring in a string.
 CATEGORY:
       text/strings
 CALLING SEQUENCE:
       num = strcnt(strn, substring, [pos])
 INPUTS:
       string    -- The string in which to count occurences.     in
       substring -- The substring to count occurrences of.       in
       pos       -- the position at which to begin the search.   [in]
                    If not supplied, start at beginning of
                    string.
 KEYWORD PARAMETERS:
       /HELP     -- Print useful message and return.
 OUTPUTS:
       num       -- Number of occurances of substring in string. out
 COMMON BLOCKS:
 SIDE EFFECTS:
 NOTES:
       Overlapping occurances are not counted separately.  For
       example, counting occurances of 'bb' in 'blah bbb' returns one
       occurance. 
 EXAMPLE:
 MODIFICATION HISTORY:
       $Id: strcnt.pro,v 1.3 1996/06/14 20:00:27 mcraig Exp $
       $Log: strcnt.pro,v $
       Revision 1.3  1996/06/14 20:00:27  mcraig
       Updated Copyright info.

       Revision 1.2  1996/05/09 00:22:17  mcraig
       Added fast processing using BYTE arrays if we are counting occurences of
       a single character.  Added error handling.

       Revision 1.1  1996/01/31 18:47:37  mcraig
       Initial revision

 RELEASE:
       $Name: Rel_2_1_2 $

 COPYRIGHT:
  Copyright (C) 1996 The Regents of the University of California, All
  Rights Reserved.  Written by Matthew W. Craig.
  See the file COPYRIGHT for restrictions on distrubting this code.
  This code comes with absolutely NO warranty; see DISCLAIMER for details.

(See /dzd2/heiles/idl/gen/textoidl/strcnt.pro)


STRTRANS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       STRTRANS
 PURPOSE:
       Translate all occurences of one substring to another.
 CATEGORY:
       text/strings
 CALLING SEQUENCE:
       new = strtrans(oldstr,from,to,ned)
 INPUTS:
       oldstr -- string on which to operate.              in
                 May be an array.
       from   -- substrings to be translated. May be      in
                 an array.
       to     -- what strings in from should be           in
                 translated to. May be an array.
 KEYWORD PARAMETERS:
       /HELP  -- Set this to print useful message and 
                 exit.
 OUTPUTS:
       new    -- Translated string. Array if oldstr is    out          
                 an array.
       ned    -- number of substitutions performed in     out
                 oldstr.  Array if oldstr is an array.
 COMMON BLOCKS:
 SIDE EFFECTS:
 NOTES:
       - Any of old, from, and to can be arrays.  
       - from and to must have the same number of elements.
 EXAMPLE:
       inp='Many*bad!chars+in_here'
       from=['*','!','+','_']
       to  =[' ',' ',' ',' ']
       out = strtrans(inp,from,to,ned)
       Will produce out='Many bad chars in here', and set ned to 4.
 MODIFICATION HISTORY:
       $Id: strtrans.pro,v 1.7 2004/06/15 17:25:54 mcraig Exp $
       $Log: strtrans.pro,v $
       Revision 1.7  2004/06/15 17:25:54  mcraig
       Fixed bug in regular expression, changed array notation to square brackets

       Revision 1.6  2004/01/11 01:49:00  mcraig
       Changed format of one array to newer [] style to avoidf conflict with function name in astro library.

       Revision 1.5  2001/11/23 21:14:35  mcraig
       Added keywords /EXTRACT, /PRESERVE_NULL, /REGEX to call to
       strsplit. This comes very close to reproducing the behavior of the
       obsolete routine str_sep.

       Revision 1.4  2001/11/21 19:13:23  mcraig
       Changed str_sep to strsplit. The former is now considered obsolete by RSI.

       Revision 1.3  1996/06/14 20:00:27  mcraig
       Updated Copyright info.

       Revision 1.2  1996/05/09 00:22:17  mcraig
       Sped up significantly by using str_sep to handle the translation.  No longer
       relies on routines fromother user libraries.

       Revision 1.1  1996/01/31 18:47:37  mcraig
       Initial revision

 RELEASE:
       $Name: Rel_2_1_2 $

 COPYRIGHT:
  Copyright (C) 1996 The Regents of the University of California, All
  Rights Reserved.  Written by Matthew W. Craig.
  See the file COPYRIGHT for restrictions on distrubting this code.
  This code comes with absolutely NO warranty; see DISCLAIMER for details.

(See /dzd2/heiles/idl/gen/textoidl/strtrans.pro)


STR_TOKEN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       STR_TOKEN
 PURPOSE:
       Retrieve portion of string up to token.
 CATEGORY:
       text/strings
 CALLING SEQUENCE:
       new = str_token( old, token )
 INPUTS:
       old   -- String to be split.  Contains text after    in, out
                token on output.
       token -- Token to use in splitting old.              in
 KEYWORD PARAMETERS:
       /TRIM -- set to remove leading blanks from old 
                before returning.
       /HELP -- print useful message and exit.
 OUTPUTS:
       new   -- portion of string up to token.              out
       old   -- portion of old after token.                 out, in
 COMMON BLOCKS:
 SIDE EFFECTS:
       Input parameter old is modified.
 NOTES:
       Token may be one or more characters.
       If token is not found, returns old and sets old to ''.
 EXAMPLE:
       If old is 'foo44 bar', then str_token( old, '44' ) would return
       'foo', and upon return, old will be left with ' bar'.  If /TRIM
       were set, old would be 'bar' on return.

       If old='xyz', then new=str_token(old,'a') would return with
       new='xyz' and old=''.
 THANKS:
       To D. Linder who wrote GETTOK, part of the goddard library,
       upon which this is based.
 MODIFICATION HISTORY:
       $Id: str_token.pro,v 1.1 2000/06/14 19:09:22 mcraig Exp $
       $Log: str_token.pro,v $
       Revision 1.1  2000/06/14 19:09:22  mcraig
       Changed name of strtok str_token to avoid conflict in IDL 5.3.

       Revision 1.3  1996/06/14 20:00:27  mcraig
       Updated Copyright info.

       Revision 1.2  1996/05/09 00:22:17  mcraig
       Added built in help.

       Revision 1.1  1996/01/31 18:47:37  mcraig
       Initial revision

 RELEASE:
       $Name: Rel_2_1_2 $

 COPYRIGHT:
  Copyright (C) 1996 The Regents of the University of California, All
  Rights Reserved.  Written by Matthew W. Craig.
  See the file COPYRIGHT for restrictions on distrubting this code.
  This code comes with absolutely NO warranty; see DISCLAIMER for details.

(See /dzd2/heiles/idl/gen/textoidl/str_token.pro)


SUB_SUP_IDL[1]

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       SUB_SUP_IDL
 PURPOSE:
       Return the proper IDL font positioning command for TeX
       sub/superscripts. 
 CATEGORY:
 CALLING SEQUENCE:
       fnt = sub_sup_idl( strn )
 INPUTS:
       strn -- Either '^' or '_', the TeX super/subscript       in
               characters
 KEYWORD PARAMETERS:
       /FORCE_UD -- Set this to use !U/!D instead of !E/!I for
                    sub/superscripts .
 OUTPUTS:
       fnt -- Either '!U' or !E' for superscripts,              out
              or '!D' or '!I' for subscripts.
 COMMON BLOCKS:
 SIDE EFFECTS:
 NOTES:
 EXAMPLE:
 LIBRARY FUNCTIONS CALLED:
        
 MODIFICATION HISTORY:
       $Id: sub_sup_idl.pro,v 1.1 1996/01/31 18:47:37 mcraig Exp $
       $Log: sub_sup_idl.pro,v $
       Revision 1.1  1996/01/31 18:47:37  mcraig
       Initial revision

 RELEASE:
       $Name: Rel_2_1_2 $

(See /dzd2/heiles/idl/gen/textoidl/sub_sup_idl.pro)


SUB_SUP_IDL[2]

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       SUB_SUP_IDL
 PURPOSE:
       Return the proper IDL font positioning command for TeX
       sub/superscripts. 
 CATEGORY:
       TeXtoIDL
 CALLING SEQUENCE:
       fnt = sub_sup_idl( strn )
 INPUTS:
       strn      -- Either '^' or '_', the TeX super/subscript       in
                    characters
 KEYWORD PARAMETERS:
       /FORCE_UD -- Set this to use !U/!D instead of !E/!I for
                    sub/superscripts .
       /HELP     -- Set to print useful message and exit.
 OUTPUTS:
       fnt       -- Either '!U' or !E' for superscripts,             out
                    or '!D' or '!I' for subscripts.
 COMMON BLOCKS:
 SIDE EFFECTS:
 NOTES:
       Used only by translate_sub_super.  Should be kept in same
       file. 
 EXAMPLE:
 MODIFICATION HISTORY:
       $Id: translate_sub_super.pro,v 1.5 2000/06/14 19:09:22 mcraig Exp $
       $Log: translate_sub_super.pro,v $
       Revision 1.5  2000/06/14 19:09:22  mcraig
       Changed name of strtok str_token to avoid conflict in IDL 5.3.

       Revision 1.4  1996/06/14 20:00:27  mcraig
       Updated Copyright info.

       Revision 1.3  1996/05/09 00:22:17  mcraig
       Changed some function calls to reflect changes in those functions, moved
       some code out of the main loop that didn't need to be there, added
       documentation.

       Revision 1.1  1996/01/31 18:47:37  mcraig
       Initial revision

 RELEASE:
       $Name: Rel_2_1_2 $
 COPYRIGHT:
  Copyright (C) 1996 The Regents of the University of California, All
  Rights Reserved.  Written by Matthew W. Craig.
  See the file COPYRIGHT for restrictions on distrubting this code.
  This code comes with absolutely NO warranty; see DISCLAIMER for details.

(See /dzd2/heiles/idl/gen/textoidl/translate_sub_super.pro)


TEXTABLE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       TEXTABLE
 PURPOSE:
       Returns a translation table from TeX to IDL.
 CATEGORY:
       text/strings
 CALLING SEQUENCE:
       table = textable()
 INPUTS:
       None
 KEYWORD PARAMETERS:
       /POSTSCRIPT -- If set, return postscript translation
                      table rather than vector fonts table.
                      Default is translations for vector
                      fonts.
       /HELP       -- Print help and exit.
 OUTPUTS:
       table -- a 2D text array.  table(0,*) contains          out
                the words to be translated away, table(1,*)
                contains the words to translate them to.   
 COMMON BLOCKS:
 SIDE EFFECTS:
 NOTES:
       To find out what TeX sequences are available, look at
       table(0,*).
 EXAMPLE:
 MODIFICATION HISTORY:
       $Id: textable.pro,v 1.7 1996/07/22 23:56:08 mcraig Exp $
       $Log: textable.pro,v $
       Revision 1.7  1996/07/22 23:56:08  mcraig
       Added \vartheta.

       Revision 1.6  1996/07/12 21:31:42  mcraig
       Fixed \varphi in vector font, added \circ.

       Revision 1.5  1996/06/14 20:00:27  mcraig
       Updated Copyright info.

       Revision 1.4  1996/05/09 00:22:17  mcraig
       Added command to return to previous font after switching to Greek or
       symbol font.

       Revision 1.3  1996/02/08 19:49:35  mcraig
       Removed control sequence \perp because the postscript code for it is '^'.

       Revision 1.2  1996/02/08 18:53:38  mcraig
       Added translations for PostScript fonts, and added several new TeX
       control sequences.

       Revision 1.1  1996/01/31 18:47:37  mcraig
       Initial revision

 RELEASE:
       $Name: Rel-2-1-1 $

 COPYRIGHT:
  Copyright (C) 1996 The Regents of the University of California, All
  Rights Reserved.  Written by Matthew W. Craig.
  See the file COPYRIGHT for restrictions on distrubting this code.
  This code comes with absolutely NO warranty; see DISCLAIMER for details.

(See /dzd2/heiles/idl/gen/textoidl/textable.pro)


TEXTOIDL

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
       TEXTOIDL
 PURPOSE:
       Convert a valid TeX string to a valid IDL string for plot labels.
 CATEGORY:
       text/strings
 CALLING SEQUENCE:
       new = textoidl(old)
 INPUTS:
       old            -- TeX string to be converted.  Will not be     in
                         modified.  old may be a string array.
 KEYWORD PARAMETERS:
       FONT           -- Set to 0 to use hardware font, -1 to use 
                         vector.  Note that the only hardware font 
                         supported is PostScript.
       /TEX_SEQUENCES -- return the available TeX sequences
       /HELP          -- print out info on use of the function
                         and exit.
 OUTPUTS:
       new            -- IDL string corresponding to old.             out
 COMMON BLOCKS:
 SIDE EFFECTS:
 NOTES:
       - Use the procedure SHOWTEX to get a list of the available TeX
         control sequences.  
       - The only hardware font for which translation is available is
         PostScript. 
       - The only device for which hardware font'
         translation is available is PostScript.'
       - The FONT keyword overrides the font selected'
         by !p.font'
 EXAMPLE:
       out = TeXtoIDL('\Gamma^2 + 5N_{ed}')
       The string out may be used in XYOUTS or other IDL text
       display routines.  It will be an uppercase Gamma, with an
       exponent of 2, then a plus sign, then an N with the subscript
       ed.
 MODIFICATION HISTORY:
       $Id: textoidl.pro,v 1.7 2004/06/15 17:25:54 mcraig Exp $
       $Log: textoidl.pro,v $
       Revision 1.7  2004/06/15 17:25:54  mcraig
       Fixed bug in regular expression, changed array notation to square brackets

       Revision 1.6  2004/01/11 01:49:00  mcraig
       Changed format of one array to newer [] style to avoidf conflict with function name in astro library.

       Revision 1.5  2001/11/23 21:10:55  mcraig
       Added backslash '\' to tex sequences in translation table to protect them during regexp search in strsplit.

       Revision 1.4  1996/06/14 20:00:27  mcraig
       Updated Copyright info.

       Revision 1.3  1996/05/09 00:22:17  mcraig
       Added error handling, cleaned up documentation.

       Revision 1.2  1996/02/08 18:52:50  mcraig
       Added ability to use hardware fonts for PostScript device.

       Revision 1.1  1996/01/31 18:47:37  mcraig
       Initial revision

 RELEASE:
       $Name: Rel_2_1_2 $

 COPYRIGHT:
  Copyright (C) 1996 The Regents of the University of California, All
  Rights Reserved.  Written by Matthew W. Craig.
  See the file COPYRIGHT for restrictions on distrubting this code.
  This code comes with absolutely NO warranty; see DISCLAIMER for details.

(See /dzd2/heiles/idl/gen/textoidl/textoidl.pro)


TRANSLATE_SUB_SUPER[1]

[Previous Routine] [Next Routine] [List of Routines]
 SPECIAL NOTE: 
       The file translate_sub_super.pro contains two functions,
       translate_sub_super, and sub_sup_idl.  The former is the
       generic routine for processing TeX sub/superscripts, the
       latter is used only by translate_sub_super and has no general
       utility.  Hence it lives here.  You will see documentation for
       translate_sub_super second if you use DOC_LIBRARY.

(See /dzd2/heiles/idl/gen/textoidl/translate_sub_super.pro)


TRANSLATE_SUB_SUPER[2]

[Previous Routine] [List of Routines]
 NAME:
       TRANSLATE_SUB_SUPER
 PURPOSE:
       Translate TeX sub/superscripts to IDL sub/superscripts.
 CATEGORY:
       text/strings
 CALLING SEQUENCE:
       new = translate_sub_super( old )
 INPUTS:
       old       -- string to be translated from TeX to IDL.   in
 KEYWORD PARAMETERS:
       /RECURSED -- set if this function is being called 
                    recursively.                  
       /HELP     -- Set to print useful message and exit.
 OUTPUTS:
       new       -- string old converted from TeX to IDL       out
 COMMON BLOCKS:
 SIDE EFFECTS:
 NOTES:
       - For best results, when both a sub and superscript are used,
         place the shorter of the two first (e.g. 'N^{a}_{bbbb}' is
         better than 'N_{bbbb}^{a}').
       - Single character sub/super scripts do not need to be
         protected by braces.
       - Sub/superscripts may be nested (e.g. 'N^{N_1^N}').
 EXAMPLE:
       out = translate_sub_super( 'N^2_{big}' )
       Then out='N!U2!N!Dbig!N' which looks like it should on the
       display. 
 LIBRARY FUNCTIONS CALLED:
       str_token      -- Text/string (mcraig)
       sub_sup_idl -- contained in this file
 MODIFICATION HISTORY:
       $Id: translate_sub_super.pro,v 1.5 2000/06/14 19:09:22 mcraig Exp $
       $Log: translate_sub_super.pro,v $
       Revision 1.5  2000/06/14 19:09:22  mcraig
       Changed name of strtok str_token to avoid conflict in IDL 5.3.

       Revision 1.4  1996/06/14 20:00:27  mcraig
       Updated Copyright info.

       Revision 1.3  1996/05/09 00:22:17  mcraig
       Changed some function calls to reflect changes in those functions, moved
       some code out of the main loop that didn't need to be there, added
       documentation.

       Revision 1.2  1996/02/08 18:54:20  mcraig
       Changed default sub/superscript size to be !D/!U rather than !I/!E to
       improve readability of plat annotations.

       Revision 1.1  1996/01/31 18:47:37  mcraig
       Initial revision

 RELEASE:
       $Name: Rel_2_1_2 $

 COPYRIGHT:
  Copyright (C) 1996 The Regents of the University of California, All
  Rights Reserved.  Written by Matthew W. Craig.
  See the file COPYRIGHT for restrictions on distrubting this code.
  This code comes with absolutely NO warranty; see DISCLAIMER for details.

(See /dzd2/heiles/idl/gen/textoidl/translate_sub_super.pro)


unix procs

unix procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

BELL

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

 PURPOSE:
       To beep and alert the user.

 CALLING SEQUENCE:
       BELL [, N][, WAIT=wait] 

 INPUTS:
       None.

 OPTIONAL INPUTS:
       N - number of times the bell should be rung.

 KEYWORD PARAMETERS:
       WAIT - the number of seconds between beeps. 

 OUTPUTS:
       None.

 NOTES:
       Beep beep!

 MODIFICATION HISTORY:
   28 Feb 2003  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/unix/bell.pro)


CLEAR

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

 PURPOSE:
       Clear the screen.

 CALLING SEQUENCE:
       CLEAR

 INPUTS:
       None.

 OUTPUTS:
       None.

 SIDE EFFECTS:
       The terminal screen is cleared.

 MODIFICATION HISTORY:
   01 Mar 2003  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/unix/clear.pro)


HOST

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

 PURPOSE:
       Print the host name IDL session is running on.

 CALLING SEQUENCE:
       HOST

 INPUTS:
       None.

 KEYWORD PARAMETERS:
       None.

 OUTPUTS:
       None.

 COMMON BLOCKS:
       None.

 MODIFICATION HISTORY:
   04 Mar 2003  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/unix/host.pro)


LS

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

 PURPOSE:
       List the contents of the current directory.

 CALLING SEQUENCE:
       LS

 INPUTS:
       None.

 KEYWORD PARAMETERS:
       None.

 OUTPUTS:
       None.

 MODIFICATION HISTORY:
   01 Mar 2003  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/unix/ls.pro)


PWD

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

 PURPOSE:
       Return the absolute path to the working directory.

 CALLING SEQUENCE:
       PWD [,NAME]

 INPUTS:
       None.

 KEYWORD PARAMETERS:
       None.

 OUTPUTS:
       None.

 OPTIONAL OUTPUTS:
       NAME - the name of the directory.

 MODIFICATION HISTORY:
   01 Mar 2003  Written by Tim Robishaw, Berkeley

(See /dzd2/heiles/idl/gen/unix/pwd.pro)


wavelets procs

wavelets procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

WAVELET -- COMPUTE THE WAVELET TRANSFORM OF A 1D TIME SERIES.

[Next Routine] [List of Routines]
NAME:
WAVELET --  Compute the WAVELET transform of a 1D time series.
PURPOSE:   Compute the WAVELET transform of a 1D time series.
       

 CALLING SEQUENCE:

      wave = WAVELET(Y,DT)


 INPUTS:

    Y = the time series of length N.

    DT = amount of time between each Y value, i.e. the sampling time.


 OUTPUTS:

    WAVE is the WAVELET transform of Y. This is a complex array
    of dimensions (N,J+1). FLOAT(WAVE) gives the WAVELET amplitude,
    ATAN(IMAGINARY(WAVE),FLOAT(WAVE)) gives the WAVELET phase.
    The WAVELET power spectrum is ABS(WAVE)^2.


 OPTIONAL KEYWORD INPUTS:

    S0 = the smallest scale of the wavelet.  Default is 2*DT.

    DJ = the spacing between discrete scales. Default is 0.125.
         A smaller # will give better scale resolution, but be slower to plot.

    J = the # of scales minus one. Scales range from S0 up to S0*2^(J*DJ),
        to give a total of (J+1) scales. Default is J = (LOG2(N DT/S0))/DJ.

    MOTHER = A string giving the mother wavelet to use.
            Currently, 'Morlet','Paul','DOG' (derivative of Gaussian)
            are available. Default is 'Morlet'.

    PARAM = optional mother wavelet parameter.
            For 'Morlet' this is k0 (wavenumber), default is 6.
            For 'Paul' this is m (order), default is 4.
            For 'DOG' this is m (m-th derivative), default is 2.

    PAD = if set, then pad the time series with enough zeroes to get
         N up to the next higher power of 2. This prevents wraparound
         from the end of the time series to the beginning, and also
         speeds up the FFT's used to do the wavelet transform.
         This will not eliminate all edge effects (see COI below).

    LAG1 = LAG 1 Autocorrelation, used for SIGNIF levels. Default is 0.0

    SIGLVL = significance level to use. Default is 0.95

    VERBOSE = if set, then print out info for each analyzed scale.

    RECON = if set, then reconstruct the time series, and store in Y.
            Note that this will destroy the original time series,
            so be sure to input a dummy copy of Y.

    FFT_THEOR = theoretical background spectrum as a function of
                Fourier frequency. This will be smoothed by the
                wavelet function and returned as a function of PERIOD.


 OPTIONAL KEYWORD OUTPUTS:

    PERIOD = the vector of "Fourier" periods (in time units) that corresponds
           to the SCALEs.

    SCALE = the vector of scale indices, given by S0*2^(j*DJ), j=0...J
            where J+1 is the total # of scales.

    COI = if specified, then return the Cone-of-Influence, which is a vector
        of N points that contains the maximum period of useful information
        at that particular time.
        Periods greater than this are subject to edge effects.
        This can be used to plot COI lines on a contour plot by doing:
            IDL>  CONTOUR,wavelet,time,period
            IDL>  PLOTS,time,coi,NOCLIP=0

    YPAD = returns the padded time series that was actually used in the
         wavelet transform.

    DAUGHTER = if initially set to 1, then return the daughter wavelets.
         This is a complex array of the same size as WAVELET. At each scale
         the daughter wavelet is located in the center of the array.

    SIGNIF = output significance levels as a function of PERIOD

    FFT_THEOR = output theoretical background spectrum (smoothed by the
                wavelet function), as a function of PERIOD.


 [ Defunct INPUTS:
 [   OCT = the # of octaves to analyze over.           ]
 [         Largest scale will be S0*2^OCT.             ]
 [         Default is (LOG2(N) - 1).                   ]
 [   VOICE = # of voices in each octave. Default is 8. ]
 [          Higher # gives better scale resolution,    ]
 [          but is slower to plot.                     ]
 ]

(See /dzd2/heiles/idl/gen/wavelets/wavelet.pro)


WV_FN_CRL -- RETURN MOTHER WAVELET AT SPECIFIED TIMES; ALSO ITS FT, OTHER STUFF TOO

[Previous Routine] [List of Routines]
NAME:
wv_fn_crl -- return mother wavelet at specified times; also its ft, other stuff too

PURPOSE: return mother wavelet at specified times; also its ft; also
the times and frequencies.

CALLING SEQUENCE: wv_fn_crl, mother, nrpts, tsmpl, order, scale, $
	time, fhz, tw, fw, wf

INPUTS:
	MOTHER, the mother wavelet name. morlet, psul, gaussian.

	NRPTS, the nr of time points. the generated time points are returned.
make this EVEN, a power of two.
	TSMPL, the time interval between points. 

	ORDER: the order of the wavelet. acceptable ranges are:
		gaussian: 1 to 10 inclusive
		paul: 1 to 20 inclusive
		morlet: 3 to 24 inclusive.

	SCALE: the scale parameter, 'a' in eros writeup.

OUTPUTS:
	TIME, the time array. returned as FFT convention, 0 first elemetn
	fhz, the corresponding frequency array. these are Hz, not radians/sec.
returned as FFT convention, zero first element
	TW, the wavelet points versus time. 
	FW, the waveleet points veresus fsrequency
	WF, idl's wavelet structure--basically meaningless...

(See /dzd2/heiles/idl/gen/wavelets/wv_fn_crl.pro)


window procs

window procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

POS

[Next Routine] [List of Routines]
 NAME:
       POS
     
 PURPOSE:
       To return the cursor position.
     
 CALLING SEQUENCE:
       POS [,X, Y] [, /SILENT] 
           [, /DATA | , /DEVICE, | , /NORMAL]
           [, /CHANGE | , /DOWN | , /NOWAIT | , /UP | , /WAIT] 
     
 INPUTS:
       None.

 OUTPUTS:
       None.

 OPTIONAL OUTPUTS:
       X - the cursor's current column position.
       Y - the cursor's current row position.

 KEYWORDS:
       /SILENT : Do not print cursor position.
       /DATA : Set this keyword to return X and Y in data coordinates.
               This is the default.
       /NORMAL : Return the normalized cursor position.
       /DEVICE : Return the cursor position in device units.
       /CHANGE : Set this keyword to wait for pointer movement or 
                 button transition within the currently selected window.
       /DOWN : Set this keyword to wait for a button down transition
               within the currently selected window.
       /NOWAIT : Set this keyword to read the pointer position and 
                 button status and return immediately. If the pointer 
                 is not within the currently selected window, the device 
                 coordinates -1, -1 are returned.
       /UP : Set this keyword to wait for a button up transition within 
             the current window.
       /DOWN : Set this keyword to wait for a button down transition within 
               the currently selected window.

 COMMON BLOCKS:
       None.

 MODIFICATION HISTORY:
       Written by Tim Robishaw, Berkeley in ancient times.

(See /dzd2/heiles/idl/gen/window/pos.pro)


WD -- DELETE ALL OPEN WINDOWS

[Previous Routine] [List of Routines]
NAME:
WD -- delete all open windows
     
 PURPOSE:
       Quick way to delete open windows.
     
 EXPLANATION:
       Deletes the open window the user specifies.
       Can delete all windows by just calling WD with no parameters.
       Can just print open windows by setting the /OPEN keyword.
     
 CALLING SEQUENCE:
       WD [,WINDOW][,/OPEN]
     
 INPUTS:
       WINDOW : The number(s) of the window(s) you want to delete. 
                If no number is input, then all the windows are
                deleted.
     
 OUTPUTS:
       None.

 KEYWORDS:
       /OPEN : Just print the window number of each open window.

 COMMON BLOCKS:
       None.

 SIDE EFFECTS:
       Windows will be deleted.

 RESTRICTIONS:
       The current device must be X Windows.

 PROCEDURES CALLED:
       WDELETE

 EXAMPLE:
       Print all the open windows:
          IDL> wd, /open

       Kill all windows:
          IDL> wd

       Kill windows 4, 5, & 6:
          IDL> wd, [4,5,6]

 MODIFICATION HISTORY:
       Written Tim Robishaw, Berkeley in ancient times.

(See /dzd2/heiles/idl/gen/window/wd.pro)


zeeman procs

zeeman procs

This page was created by the IDL library routine mk_html_help. For more information on this routine, refer to the IDL Online Help Navigator or type:

     ? mk_html_help

at the IDL command line prompt.

Last modified: Tue Dec 20 11:48:26 2005.


List of Routines


Routine Descriptions

ZFIT -- FIT B FIELDS TO STOKES V AND I/2 DATA

[Next Routine] [List of Routines]
NAME:
ZFIT -- Fit B fields to Stokes V and I/2 data

PURPOSE:
    Fit B fields to Stokes V and I/2 data in the channel range
         chnl1a to chnl2a. Fits the V spectrum to the derivative
         of the I/2 spectrum (providing the field) and, also, to
         the I/2 spectrum itself (providing the 'gain' error).

CALLING SEQUENCE:
    ZFIT, v0, i0, chnl1a, chnl2a, bfld, berr, gain, gainerr, $
	vpredicted, vmodified, a

INPUTS:
     v0: the data points of the Stokes V spectrum.
     i0: the data points of the Stokes I/2 (***NOT Stokes I***) spectrum.
     chnl1a: the first channel nr to include in the fit.
     chnl2a: the last channel nr to include in the fit.

OUTPUTS:
     bfld: the fitted magnetic field. UNITS ARE CHANNELS; SEE BELOW
     berr: the uncertainty in the fitted field.
     gain: the 'gain error', the fraction of residual I/2 leaked into V.
     gainerr: the uncertainty in the gain error.
     vpredicted: the V spectrum predicted from the bfld (all channels) 
     vmodified: measured V spectrum with the 'gain error' removed.
     a: the array of solved-for coefficients
 
UNITS OF FITTED FIELD:
	Bfld is the frequency separation betweeen the RHC and LHC 
components in units of channels. Thus, if the channel width is 2800 Hz
and bfld is returned as 1.00, and if the splitting is 2.8 Hz per microG
as it is for HI, then the freq separation between the two components is
2800 Hz and the field is 1000 Microg.

RESTRICTIONS:
    None...that we know of.
EXAMPLE:
    You have measured a V and an I spectrum and you want to 
         derive the associated field strength. 

    ZFIT, v0, i0, chnl1a, chnl2a, bfld, berr, gain, gainerr, $
	vpredicted, vmodified, a

(See /dzd2/heiles/idl/gen/zeeman/zfit.pro)


ZGFIT -- FIT B FIELDS TO STOKES V DATA, ASSUMING EMITTING GAUSSIANS AND ONE ABSORBING GAUSSIAN

[Previous Routine] [List of Routines]
NAME:
ZGFIT -- Fit B fields to Stokes V data, assuming emitting Gaussians and one absorbing gaussian

PURPOSE:
    Fit B fields to Stokes V data, assuming Gaussians are the
         total intensity spectrum and assuming one absorbing gaussian.
CALLING SEQUENCE:
    ZG_EA_FIT, xdata, tdata, hgt0, cen0, wid0, hgttau, centau, widtau, $
	bfld, berr, cov

INPUTS:
     tdata: the data points of the Stokes V spectrum.
     hgt0: the array of N Gaussian heights of the Stokes I/2 spectrum.
     cen0: the array of N Gaussian centers of the Stokes I/2 spectrum.
     wid0: the array of N Gaussian widths of the Stokes I/2 spectrum.
	hgttau: the absorbing gaussian height
	centau, the absorbing gaussian centr
	widtau, the absorbing gaussian halfpower width

NOTE:
	ABSORBTION ASSUMED TO BE OF THE FORM
	optical depth = hgttau * exp[ (xdata - centau)/(0.6005612*widtau))^2]

OUTPUTS:
     bfld: the array of N fields of the Gaussians. 
     berr: the array of N fitted centers.
     cov: the normalized covariance matrix.

RESTRICTIONS:
    None...that we know of.
EXAMPLE:
    You have fit N Gaussians to a total intensity profile; their
         parameters are in the N-element arrays hgt, cen, wid. 
         You also have the Stokes V spectrum, which is the array 
         tdata, and you want to derive the associated field strengths. 
         ZGFIT, tdata, hgt0, cen0, wid0, bfld, berr, cov

(See /dzd2/heiles/idl/gen/zeeman/zg_ea_fit.pro)