PINTofALE: Stellar Coronal Analysis Routines

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 Nov 24 14:18:20 2009.


List of Routines


Routine Descriptions

ACISS_GAPS

[Next Routine] [List of Routines]
procedure	aciss_gaps
	calculate the wavelength (or energy) locations of the CXO chip gaps

	the outputs are all in the following sequence:
	[left edge of S0, right edge of S0,
	 left edge of S1, right edge of S1,
	 left edge of S2, right edge of S2,
	 left edge of S3, right edge of S3,
	 left edge of S4, right edge of S4,
	 left edge of S5, right edge of S5]

syntax
	aciss_gaps,hgap,mgap,lgap,onchip=onchip,offset=offset,$
		order=order,/ikeV,/mm,/pix

parameters
	hgap	[OUTPUT] HEG gaps (ACIS-S/HETG) [Ang]
	mgap	[OUTPUT] MEG gaps (ACIS-S/HETG) [Ang]
	lgap	[OUTPUT] LEG gaps (ACIS-S/LETG) [Ang]

keywords
	onchip	[OUTPUT] the number of the chip on which the 0th order
		position lies.
		* 0=>S0, 1=>S1, .. 5=>S5
		* 0.5=>in gap between S0 & S1, etc.
	offset	[INPUT (default=0)] offset of source position from
		nominal aim point [arcmin]
		* nominal offset is 6.04-0.024 mm from first active column
		* +ve is towards center of S3
	order	[INPUT (default=1] grating order
	ikeV	[INPUT] if set, outputs are in [keV] (default is [Ang])
	mm	[INPUT] if set, OFFSET is assumed to be in [mm]
	pix	[INPUT] if set, OFFSET is assumed to be in [pix]
		* PIX overrides MM
	_ref_extra	[JUNK] here only to prevent crashing the program

history
	9/9/97 dd Written for Fred Seward for PG
	11/27/99 dd Updated values for NRA2
	MIM.XII -- vk copied from
	  http://space.mit.edu/HETG/technotes/chip_gaps/hetgs_gaps.pro
	  and modified the interface to be more useful to acisgarf.pro
	changed value of Rowland diameter (VK; FebMM)
	changed keyword KEV to IKEV (VK; JanMMI)
	changed focal length and Rowland diameter (VK; Sep01)
	changed leg_ang to -0.07 (VK; Jan04)

(See /data/fubar/SCAR/pro/specific/aciss_gaps.pro)


ADDLINCON

[Previous Routine] [Next Routine] [List of Routines]
ADDLINCON.PRO
	example script to demonstrate adding lines to continuum spectra

subroutines
	GETABUND [SETABUND]
	RD_CONT [SYMB2ZION [LAT2ARAB]
	LINEFLX [GETABUND, WHEE]
	LINESPEC [RD_LINE [KILROY, SYMB2ZION [LAT2ARAB],
	  FOLD_IONEQ [WHEE, GETLOCMAX, RD_IONEQ [READ_IONEQ (CHIANTI)]]],
	  LINEFLX [WHEE]
	  HASTOGRAM [KILROY]]
	REBINW [KILROY]

vinay k (Jan 98)

(See /data/fubar/SCAR/pro/scrypt/addlincon.pro)


ADDRSP

[Previous Routine] [Next Routine] [List of Routines]
function	addrsp
	combine two response matrices to make a composite RSP and
	return a structure in the same format as RD_OGIP_RMF()

	steps through each row of an RMF and tacks on the array
	from a 2nd RMF, updating the N_GRP, N_CHAN, F_CHAN elements
	as appropriate.

syntax
	rsp=addrsp(rm1,rm2,ea1=ea1,ea2=ea2,eps=eps,verbose=verbose)

parameters
	rm1	[INPUT; required] response matrix structure as
		read in by RD_OGIP_RMF
	rm2	[INPUT; required] response matrix structure to
		be added to RM1
		* RM1 and RM2 are expected to have the following fields:
	        NNRG,ELO,EHI,NCHAN,EMN,EMX,N_GRP,F_CHAN,N_CHAN,MATRIX,FIRSTCHAN

keywords
	ea1	[INPUT] if set to a scalar or size matches RM1.ELO,
		then multiplies RM1 by EA1 prior to addition
	ea2	[INPUT] as EA1, but for RM2
		* default for EA1 and EA2 is 1.0
	eps	[INPUT] a small number, below which to set everything
		to zero
		* default is 1e-6
	morecol	[INPUT] designed as a buffer so that a matrix won't
		overflow the bounds automatically set.  by default,
		the new matrix is defined at an early stage to be
		max(RM1.N_CHAN)+max(RM2.N_CHAN)+100+MORECOL.
		* note that MORECOL can even be negative.
		* use wisely.
	verbose	[INPUT] controls chatter
	ea3	[JUNK] here just to prevent user error
	ea4	[JUNK] here just to prevent user error
	ea5	[JUNK] here just to prevent user error
	ea6	[JUNK] here just to prevent user error
		* if EA3, EA4, EA5, or EA6 are set, the program will
		  complain and quit.  this is done to avoid the obvious
		  user error of trying to specify EA3=EA3, etc. if
		  adding a third RMF/ARF to a preexisting one.

	_extra	[JUNK] here only to avoid crashing the program

subroutines
	KILROY
	OGIPZIP

history
	vinay kashyap (Nov2001)
	bug correction re max possible matrix elements when NGROUP>>1;
	  added dummy keywords EA3, EA4, EA5, EA6 and extra checks
	  against tricky inputs (VK; Aug02)
	bug correction: wasn't handling N_GRP=1 (VK; Aug04)

(See /data/fubar/SCAR/pro/addrsp.pro)


ADJUSTIE

[Previous Routine] [Next Routine] [List of Routines]
procedure	adjustie
	adjust the parameters to account for any ties among them, and
	return the corrected set

syntax
	adjustie,a,ties=ties,vname=vname

parameters
	a	[I/O; required] parameters to be updated

keywords
	ties	[INPUT] string array describing how a parameter is tied to
		other parameters.
		* must be a mathematical expression of the form
		  "a0 = a1/10.", "a2=a3+a4", "a5 = a5 < 0", etc.
	vname	[INPUT; default='a'] in case TIES contains variable names
		such as "p0=p2^2", etc, then set VNAME='p'

		NOTE:  the following keywords are generated in situ the first
		time the function is called.  on subsequent calls they are
		used instead of EXECUTEing TIES in order to improve speed.

		NOTE2: actually, they are not implemented yet.  someday.

	ifit	[I/O] integer array describing which parameters are frozen
		(0's) and which are not (1's).  updated upon exit to include
		information given in TIES
	itie	[I/O] integer array showing which parameters are tied.
	tieto	[I/O] linked list showing which parameters each of the
		ITIE are tied to which parameter
	tieops	[I/O] as TIETO, but containing information on which operator
		is used, e.g., "+", "-", "*", "/", "<", ">", etc.
	_extra	[JUNK] here only to prevent crashing the program

history
	vinay kashyap (Oct98)
	converted to IDL5 (VK; OctMM)

(See /data/fubar/SCAR/pro/adjustie.pro)


APEDANCE

[Previous Routine] [Next Routine] [List of Routines]
procedure	apedance
	remove or correct the abundance dependance of APED emissivities

	APED emissivities as stored on disk include both ion balance
	(Mazzotta et al.) and abundances (Anders & Grevesse).  This
	can be inconvenient in some PINTofALE tasks since other line
	emissivity databases in PINTofALE do not include either factor.
	It is not possible to remove the effects of the included ion
	balance, but removing the abundance dependance is simply a
	matter of dividing the emissivity of each line by the abundance
	appropriate to the element producing that line.

syntax
	apedance,line,Z,abund=abund,apabref=apabref,verbose=verbose

parameters
	line	[I/O] APED line emissivities
		* emissivity structure out of RD_LINE()
		* if 2D array, assumed to be an array of size (T,Wvl)
	Z	[INPUT] atomic numbers
		* required if LINE is an array and not a structure
		* must match size of 2nd dimension in LINE

keywords
	abund	[INPUT] if given, updates LINE by multiplying by
		the ratio of ABUND/(Anders & Grevesse)
		* the default is to just divide by Anders & Grevesse
		  abundances, effectively removing the abundance
		  dependance from the emissivities
	apabref	[INPUT] if set to a reference other than Anders & Grevesse,
		it is assumed that the input LINE emissivities need to be
		corrected according to the specified abundances.
		* WARNING: do not set this unless you know exactly
		 what you are doing
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to avoid crashing the program

warning
	no checks are made to verify that the emissivities have
	have already had the abundances taken out, or that the
	abundances are corrected according to some other baseline.
	USE CAREFULLY!

history
	vinay kashyap (Apr2004)

(See /data/fubar/SCAR/pro/apedance.pro)


ARIA

[Previous Routine] [Next Routine] [List of Routines]
function	aria
	puts together the effective areas and corresponding wavelengths
	into a single structure and returns that structure

syntax
	A=aria(p1,p2,p3,p4,pickar=pickar,comment=comment)

parameters
	P1..P4	[INPUT] see USAGE below for description

keywords
	pickar	[INPUT] if vector, AND only one structure (and nothing else)
		is input, then returns all the components specified
		* if scalar, on the other hand, returns ALL BUT the
		  specified component
	comment	[INPUT] tacks on comment if given
	_extra	[JUNK] here only to prevent crashing the program

usage
	the effective area is defined by the wavelengths, the area at said
	wavelengths, and the grating order for which this is valid.  so if
	AREA(WVL;ORDER) are input, out should come a new structure of the
	form {AREA:AREA, WVL:WVL, ORDER:ORDER, COMMENT:COMMENT}.
		OUTPUT.(0).AREA		<== AREA
		OUTPUT.(0).WVL		<== WVL
		OUTPUT.(0).ORDER	<== ORDER
		OUTPUT.(0).COMMENT	<== COMMENT

	If such a structure already exists, the supplied AREA(WVL;ORDER) must
	be concatenated to it.  hence:

	to create a brand new structure
		arstr=aria(AREA,WVL,ORDER)

	to append AREA(WVL;ORDER) to pre-existing area structure (note that
	it doesn't matter just where "OLDARSTR" is in the calling sequence)
		arstr=aria(OLDARSTR, AREA,WVL,ORDER)
		arstr=aria(AREA, OLDARSTR, WVL,ORDER)
		arstr=aria(AREA,WVL, OLDARSTR, ORDER)
		arstr=aria(AREA,WVL,ORDER, OLDARSTR)

	to append ARSTR2 to ARSTR1 by calling this program recursively, once
	for each segment of ARSTR2
		arstr=aria(ARSTR1,ARSTR2)

	to selectively choose (with vector PICKAR)
	or delete (with scalar PICKAR)
	compoenents (works only when just one parameter is supplied)
		arstr=aria(OLDARSTR,PICKAR=PICKAR)

subroutines
	ARIA (recursive calls while adding two structures)

history
	vinay kashyap (Nov98)
	changed keyword PICK to PICKAR (VK; JunMM)

(See /data/fubar/SCAR/pro/aria.pro)


ARITHTOGRAM

[Previous Routine] [Next Routine] [List of Routines]
function	arithtogram
	return the result of an arithmetical operation on the
	frequency distributions of two lists

syntax
	hx=arithtogram(x1,x2,xout,operator,/plus,/minus,/divide,$
	w1=w1,w2=w2,nbin=nbin,xmin=xmin,xmax=xmax,/nonorm)

parameters
	x1	[INPUT; required] list of numbers whose frequency
		distribution must be multiplied with that of X2
	x2	[INPUT; required] list of numbers whose frequency
		distribution must be multiplied with that of X1
		* it is assumed that X1 and X2 both have the same units
		  because otherwise this kind of multiplication makes
		  no sense
	xout	[OUTPUT; required] the list of numbers at which the
		output is tabulated
		* by default, this is the sorted unique set of [X1,X2]
		* if NBIN is set, generates a logarithmic or linear
		  grid of that size
	oper	[INPUT] must be one of '+', '-', '/', '*':
		the arithmetical operation to carry out on the
		frequency distributions of X1 and X2, i.e.,
			result = X1 OPER X2
		* if not given, assumed to be '*', unless one of
		  keywords PLUS, MINUS, or DIVIDE are set 

keywords
	plus	[INPUT] if set, OPER is assumed to be '+'
	minus	[INPUT] if set, OPER is assumed to be '-'
	divide	[INPUT] if set, OPER is assumed to be '/'
		* DIVIDE takes precedence over MINUS takes precedence
		  over PLUS
	w1	[INPUT] optional weight to be applied to histogram(X1)
	w2	[INPUT] optional weight to be applied to histogram(X2)
		* if not given, W1 and W2 are assumed to be 1
	nbin	[INPUT] number of bins in the output
		* if not set, will be the sorted unique set of [X1,X2]
		* if -ve, will produce logarithmic gridding
	xmin	[INPUT] minimum value in the output grid
		* by default, uses min(X1)>min(X2)
	xmax	[INPUT] maximum value in the output grid
		* by default, uses max(X1)<max(X2)
	nonorm	[INPUT] if set, does not make a correction for the
		width of the bins in XOUT.
	_extra	[JUNK] here only to prevent crashing the program

description
	this program does not create histograms as intermediate products
	but rather produces an operation at the best available data
	resolution.  this is of great use in Monte Carlo calculations
	or in creating probability distributions in MCMC.  the algorithm
	is straightforward: build up a cdf for each list, and interpolate
	onto a common grid, and multiply, divide, add, or subtract the
	d(cdf)'s, suitably normalized for the bin widths and number of
	elements.

example
	x1=randomn(seed,10000L) & x2=randomn(seed,10000L)+2.
	xmin=-2. & xmax=3. & nbin=101L
	hh=arithtogram(x1,x2,xout,'*',xmin=xmin,xmax=xmax,nbin=nbin,/nonorm)
	hp=arithtogram(x1,x2,xout,'+',xmin=xmin,xmax=xmax,nbin=nbin,/nonorm)
	hd=arithtogram(x1,x2,xout,'/',xmin=xmin,xmax=xmax,nbin=nbin,/nonorm)
	hm=arithtogram(x1,x2,xout,'-',xmin=xmin,xmax=xmax,nbin=nbin,/nonorm)
	h1=histogram(x1,min=xmin,max=xmax,binsize=median(xout[1:*]-xout))
	h2=histogram(x2,min=xmin,max=xmax,binsize=median(xout[1:*]-xout))
	plot,xout,hh,psym=10 & oplot,xout,h1,col=2 & oplot,xout,h2,col=3
		oplot,xout,h1*h2,psym=10,col=4
	plot,xout,hp,psym=10 & oplot,xout,h1,col=2 & oplot,xout,h2,col=3
		oplot,xout,h1+h2,psym=10,col=4
	plot,xout,hd,psym=10 & oplot,xout,h1,col=2 & oplot,xout,h2,col=3
		oplot,xout,float(h1)/float(h2),psym=10,col=4
	plot,xout,hm,psym=10 & oplot,xout,h1,col=2 & oplot,xout,h2,col=3
		oplot,xout,h1-h2,psym=10,col=4

history
	vinay kashyap (Jun2005)

(See /data/fubar/SCAR/pro/misc/arithtogram.pro)


ARMADILLO

[Previous Routine] [Next Routine] [List of Routines]
function	armadillo
	returns the quantiles of a background contaminated histogram

	they say that there is nothin in the middle of the road except
	yellow stripes and dead armadillos.  here however are medians
	with error bars.

syntax
	x=armadillo(src,bkg,quantil=quantil,quaup=quaup,quadn=quadn,$
	quasig=quasig,clev=clev,asrc=asrc,abkg=abkg,nsim=nsim,$
	verbose=verbose,simsrc=simsrc,simcdf=simcdf,simxx=simxx,$
	funit=funit,agamma=agamma,bgamma=bgamma,priorbg=priorbg,$
	nsgrid=nsgrid,srcmin=srcmin,srcmax=srcmax)

parameters
	src	[INPUT; required] source spectrum
	bkg	[INPUT] background spectrum
		* size must match SRC.  if it does not,
		-- if 0-element, assumed to be 0
		-- if 1-element, assumed to be constant
		-- if >1 and .NE. N(SRC), returns with error

keywords
	quantil	[INPUT] the quantile(s) to compute
		* default is the median, quantile=0.5
		* may be an array
		* must be in the range 0..1. if not,
		-- if >1 and <100, taken to be percentage number
		-- if >100, taken to be (1 - reciprocal fraction)
		-- if <0, abs value is taken to be reciprocal fraction
	quaup	[OUTPUT] the upper bound on the quantile(s) at
		confidence level CLEV
	quadn	[OUTPUT] the lower bound on the quantile(s) at
		confidence level CLEV
	quasig	[OUTPUT] the std.dev. on the quantile(s)
	clev	[INPUT] confidence level at which to get QUAUP and QUADN
	asrc	[INPUT] area of the source region
		* default=1
	abkg	[INPUT] area of the background region
		* default=1
	nsim	[INPUT] number of simulations to run
	verbose	[INPUT] controls chatter
	simsrc	[OUTPUT] stores the counts from all the simulations,
		returned in an array of size (NSIM,N(SRC))
	simcdf	[OUTPUT] stores the cdfs from all the simulations,
		returned in an array of size (NSIM,N(SRC))
	simxx	[OUTPUT] stores the quantiles from all the simulations,
		returned in an array of size (NSIM,N(QUANTIL))
	_extra	[INPUT ONLY] pass defined keywords to
		PPD_SRC: FUNIT,AGAMMA,BGAMMA,PRIORBG,NSGRID,SRCMIN,SRCMAX

description
	given counts histograms from a source region and an estimate
	of the background contamination, computes the posterior probability
	distribution at each bin, generates sample counts from the ppd,
	and uses these monte carlo samples to estimate an average value
	of the quantiles and errors on them.

subroutines
	PPD_SRC
	PROB_GAMMADIST

history
	vinay kashyap (Mar2005)

(See /data/fubar/SCAR/pro/stat/armadillo.pro)


ARRAYEQ

[Previous Routine] [Next Routine] [List of Routines]
function	arrayeq
	checks whether two input arrays are equal, and returns
	1: if they are identical
	0: if at least one element differs past tolerance
	-1: if sizes differ, but one array is a simple subset of the other

syntax
	AeqB=arrayeq(A,B,tol=tol)

parameters
	A	[INPUT; required] first array
	B	[INPUT; required] second array
		* arrays must be of some >numerical< type

keywords
	tol	[INPUT; default: 1e-4] tolerance within which two numbers
		are said to be identical
	_extra	[JUNK] here only to avoid crashing the program

history
	vinay kashyap (Nov98)
	converted to IDL5 notation (VK; OctMM)

(See /data/fubar/SCAR/pro/misc/arrayeq.pro)


ASCII_PARSE

[Previous Routine] [Next Routine] [List of Routines]
procedure	ascii_parse
	parse an ascii format template to figure out how many
	columns, of what type, are in the ascii file.

syntax
	ascii_parse,fmtline,colname,coltype,sep=sep,idict=idict,fdict=fdict,$
	ldict=ldict,sdict=sdict,templat=templat,escape=escape,/fold_case,$
	regex=regex,verbose=verbose

parameters
	fmtline	[INPUT; required] a line describing the columns expected
		to be a SEP-separated list of column names and formats,
		with each field in the form "NAME FORMAT_CODE"
		* if NAME is missing, or is illegal, then "COL#" is assigned
		  to be the column name
		* if FORMAT_CODE is missing or ununderstandable, then some
		  obvious cases such as 'RA', 'Dec', etc. are recognized
		  as floats and the rest are taken to be strings.
		* FORMAT_CODEs are:
		  'b' for I*1
		  'i' for I*2
		  'l' for I*4
		  'f' or 'r' for R*4
		  'd' for R*8
		  'a' or 's' for strings
		* if array, will be concatenated
	colname	[OUTPUT; required] column names derived from FMTLINE
	coltype	[OUTPUT; required] column types derived from FMTLINE
		* will be one of
		  byte, integer, long, float, double, or char
		* will be char by default

keywords
	sep	[INPUT] field separator, taken to be "|" by default
	idict	[INPUT] user-defined array of column names that are
		to be considered integers
	fdict	[INPUT] user-defined array of column names that are
		to be considered float
	fdict	[INPUT] user-defined array of column names that are
		to be considered long integers
	sdict	[INPUT] user-defined array of column names that are
		to be considered char
		* IDICT, FDICT, LDICT, and SDICT override internal directory
		* SDICT takes precedence over LDICT takes precedence
		  over FDICT takes precedence over IDICT
	templat	[OUTPUT] a structure of the same form as generated by
		ASCII_TEMPLATE()
	escape	[INPUT] passed straight to STRSPLIT with no checks
	fold_case	[INPUT] passed straight to STRSPLIT with no checks
	regex	[INPUT] passed straight to STRSPLIT with no checks
	_extra	[INPUT ONLY] pass defined keywords to subroutines
		STRSPLIT: ESCAPE, FOLD_CASE, REGEX
		LEGALVAR: VERBOSE

example
	fmtline = 'InputRA | InputDec | offset | obsid | srcid | ra |'+$
	  'dec | netB | error_netB | flag | x | y | error_x | error_y |'+$
	  'srcB | bkgB | barea_ratio | mean_ea | mean_bk_ea | srcS |'+$
	  'bkgS | srcH | bkgH | srcS1 | bkgS1 | srcS2 | bkgS2 |'
	ascii_parse,fmtline,colname,coltype,fdict=['src[^i]','bkg']
	for i=0,n_elements(colname)-1 do print,colname[i],':',coltype[i]

subroutines
	LEGALVAR

history
	vinay kashyap (Jun03)
	added _EXTRA in call to LEGALVAR (VK; Jul03)
	added keyword SDICT (VK; Aug03)
	added keyword TEMPLAT (VK; Apr04)
	added keyword LDICT (VK; May04)
	added keywords ESCAPE, FOLD_CASE, and REGEX to catch and pass on
	  to STRSPLIT, because somebody has rather inconveniently gone
	  and changed the STRSPLIT call to STRICT_EXTRA from plain EXTRA
	  in IDL 6.2 (VK; Apr06)

(See /data/fubar/SCAR/pro/misc/ascii_parse.pro)


AUTO_DA_FIT

[Previous Routine] [Next Routine] [List of Routines]
function    auto_da_fit 
       command line-based function to fit Gaussians and Lorentzians (or
       combinations, or other 3-parameter functions) to lines in a spectrum 
       and determine line fluxes. This is done automatically at the command
       line, not interactivley with a GUI as in FITLINES() 

       Given a set of lines, AUTO_DA_FIT() will identify which lines are
       blended (hardcoded as 5*wdt from pos). Individual lines and blended 
       groups are then fit successively and errors are computed for each.
       Parameter freezing and thawing can be controlled with keyword THAW.
       Otherwise, all parameters are considered free. A second blended group 
       identificatin is performed after the preliminary fit to ensure that 
       there are no components mistakingly left out because of an initial
       wdt value that is too small. 
       
       It is HIGHLY RECOMMENDED that  routines LINEID(), ID_TO_FITPAR() are
       used to prepare inputs. It is also advisable to visually inspect fits 
       using FITLINES() after automatic fits are made. See USAGE EXAMPLES

       returns a structure of the form, identical to FITLINES():  
          {POS,PERRP,PERRM,PERRC,$
	   FLX,FERRP,FERRM,FERRC,$
	   WDT,WERRP,WERRM,WERRC,$
	   THAW,TYPE,TIES,EPITHET,CONLEVX,CONLEV,CONSIGX,CONSIG,COMMENT}
	All these are also available as output individually as keywords.
	See keyword descriptions for what the variables mean.

syntax  
     fitstr = auto_da_fit(x,y,ysig=ysig,pos=pos,wdt=wdt,flx=flx,thaw=thaw,$
     effar=effar,effwgrid=effwgrid,perrp=perrp,perrm=perrm,perrc=perrc,$
     werrp=werrp,werrm=werrm,werrc=werrc,ties=ties,epithet=epithet,$
     ferrp=ferrp,ferrm=ferrm,ferrc=ferrc,crng=crng, algo_type=algo_type,$
     conlev=conlev)

parameters
	x	[INPUT; required] absissa, e.g., wavelength or energy
	y	[INPUT; required] count spectrum Y(X)
		* size of Y must match that of X
keywords
	ysig	[INPUT] errors on Y
		* default is sqrt(abs(Y)+0.75)+1.
	pos	[I/O] best-fit line positions
		* length of vector shows number of components
	perrp	[I/O] 1-sided error on POS (POS+PERRP is upper bound)
	perrm	[I/O] 1-sided error on POS (POS-PERRM is lower bound)
	perrc	[I/O] DCHI threshold used in computing PERR?
	flx	[I/O] best-fit fluxes in the lines
	ferrp	[I/O] 1-sided error on FLX (FLX+FERRP is upper bound)
	ferrm	[I/O] 1-sided error on FLX (FLX-FERRM is lower bound)
	ferrc	[I/O] DCHI threshold used in computing FERR?
	wdt	[I/O] best-fit widths (sigma, core-radius, etc.) of the lines
	werrp	[I/O] 1-sided error on WDT (WDT+WERRP is upper bound)
	werrm	[I/O] 1-sided error on WDT (WDT-WERRM is lower bound)
	werrc	[I/O] DCHI threshold used in computing WERR?
		* on input, FLX, WDT, and ?ERR? are forced to match the length
		  of POS: excess elements are thrown away, and insufficient
		  lengths are made up by padding with first elements, 1s, etc.
		* on output ?ERRM are identical to ?ERRP >unless< the
		  projected errors have been calculated using ERORS, in
		  which case the values may be different
		* on output, places where ?ERRC contain 0's are those where
		  the computed errors are 1-sigma formal curvature errors
	thaw	[I/O] integer array signaling frozen (0) or thawed parameter (1)
		* refers to sequences of {POS,WDT,FLX} for each component in
		  a 3-parameter model (cf. X3MODEL) -- whatever goes for the
		  appropriate user-defined function.
		* length must match 3*length(POS)
		* default is to freeze defined input, thaw all new additions
	type	[I/O] type of model ('gauss', 'lorentz', etc.)
		* default is 'gauss'
	epithet	[I/O] label for each component
		* labels, obtained, for example, with IDLABEL
		* Merriam-Webster> a characterizing word or phrase accompanying
		  or occurring in place of the name of a person or thing
	ties	[I/O] any ties between parameters?
	conlev	[I/O] the continuum that was taken out of the spectrum
		* CONLEV must match the size of X and Y else ignored
	consig	[I/O] error on CONLEV
		* default for CONSIG is sqrt(abs(CONLEV)+0.75)+1.
		* NOTE: CONLEV and CONSIG are compressed using SPLAC in
		  the output that gets returned via the structure.  That
		  structure therefore also has appropriate abscissae
		  CONLEVX and CONSIGX.
	comment	[OUTPUT] descriptive string
	_extra	[INPUT ONLY] use this to pass defined keywords to subroutines
		PICKRANGE: XSIZE, YSIZE, WID, DYNRNG
		LINEREM: POSve, NEGve
		FIT_LEVMAR: ITMAX, CHITHR, DUMB
		LEVMARQ: JUMPUP, JUMPDN, SVDTHR
		MK_3MODEL: MISSING
		MK_SLANT: ANGLE, BETAP
		ERORS: VERBOSE
		STAMPLE: NUTHIN, NODAY, NOTIME, NOUSER, NOPACK, STACOL,
			 STASIZ, STATHK
		MK_LORENTZ: BETAP, MISSING, NORM
               MCERROR
		IS_KEYWORD_SET

usage example
       
       PoA> ;      restore V711 Tau spectrum 
       PoA> restore, !ARDB+'demo_v711Tau.save',/v ; restore V711 Tau spectrum 
       PoA> 
       PoA> ;      restore PoA line ID structure 
       PoA> restore, !ARDB+'example_2.save',   /v ; restore PoA line ID structure    
       PoA> 
       PoA> ;      prepare inputs with ID_TO_FITPAR()
       PoA> id_to_fitpar, lineid_idstr, pars, ties, thaw, pos=pos,wdt=wdt,$
       PoA>  epithet=epithet ,shackle='flux,position',flx=flx,ties=ties, leeway = 'position,width',$ 
       PoA>  perr = 0.6,/numer, lsfwdt = '0.01',werr=0.003,nozero=1
       PoA>
       PoA> ;      call AUTO_DA_FIT() 
       PoA> fstr = auto_da_fit( LAM_M1P_V711TAU,SPC_M1P_V711TAU, pos=pos, wdt=wdt ,flx=flx                 
       PoA>           effar=EFFAR_M1P,effwgrid=WVLAR_M1P ,crng = [2.4,3.4], verbose = 0,$             
       PoA>           funcs = 'x3model',function_name='x3model',conlev=conlev ,/normflx,$            
       PoA>           type = replicate('beta=2.5',n_elements(pos)),ties=ties ,thaw = thaw ,mciter = 10.0) 
       PoA> 
       PoA> ;      visually inspect with FITLINES() 
       PoA> newstr = fitlines(LAM_M1P_V711TAU,SPC_M1P_V711TAU,oldstr=fstr,/dumb) 
       
history          
        liwei lin (Jul05) some code lifted directly from FITLINES()
	updated for IDL5.6 keyword_set([0]) behavior change for vectors
	  (VK; 20Mar2006)
	changed name from AUTO_DA_FET to AUTO_DA_FIT (VK; Apr2006)
	some bug fixes (VK; Apr2009)

(See /data/fubar/SCAR/pro/auto_da_fit.pro)


AXAF_WGRID

[Previous Routine] [Next Routine] [List of Routines]
function	axaf_wgrid
	return wavelength grid of bin-beginning values and the final bin-ending
	value in which the sampling follows the optimal binning for AXAF
	transmission grating spectra to accurately reflect higher resolution
	in higher orders.

syntax
	ww=axaf_wgrid(wmin,/LEG,/MEG,/HEG,detlen=detlen,PixSize=PixSize,$
	OverSampl=OverSampl,TG_period=TG_period,X_Rowland=X_Rowland,$
	MaxOrd=MaxOrd,WavCtr=WavCtr,WavBinSize=WavBinSize)

parameters
	wmin	[INPUT; required] minimum wavelength for output array [Ang]

keywords
	leg		[INPUT] if set, sets all keyword defaults to the
			Low-Energy Transmission Grating specific numbers.
			* default
	meg		[INPUT] if set, sets all keyword defaults to the
			Medium-Energy Transmission Grating specific numbers.
			* overrides LEG
	heg		[INPUT] if set, sets all keyword defaults to the
			High-Energy Transmission Grating specific numbers.
			* overrides MEG and LEG
	detlen		[INPUT] Approximate length of detector array,
			from zero-order to outer limit [mm]
	PixSize		[INPUT] Pixel size of the array (not necessarily a
			resolution element) [mm]
	OverSampl	[INPUT] Amount of oversampling of pixels of size
			PIXSIZE (e.g., if dithering gives half-pixel
			resolution, then specify OverSampl of 2); value
			is factor to divide PixSize by.
	TG_period	[INPUT] Period of the diffraction grating [Ang]
	X_Rowland	[INPUT] Rowland diameter of the grating [mm]
			(canonically 8635mm, but larger at XRCF)
	MaxOrd		[INPUT] Maximum order to consider
	WavCtr		[OUTPUT] Array of bin central wavelengths [Ang]
	WavBinSize	[OUTPUT] Array of bin full widths, corresponding
			to the WAVCTR bins [Ang]

description
	In order to accurately model the higher diffraction orders of a
	predicted spectrum, the input model spectrum must have sufficient
	resolution to be sampled by the detector.  A grid which matches the
	first order spectrum will be undersampled in higher orders, since
	higher orders are increasingly dispersed by a factor of m, the
	diffraction order.  If the grid were set to match the highest order
	to be considered, then the input spectrum would have a very large
	number of grid points.  This is unnecessary, since much of the
	spectrum is diffracted distances greater than the length of the
	detector.  This procedure constructs a grid which has increasingly
	finer resolution at progressively shorter wavelengths.  The grid
	spacing is discontinuous at boundaries where the next higher order
	will fall off the detector.

	Gridding is as follows:
	* From DetLen to DetLen/2, grid at the first order resolution
	  (essentially the detector pixel size, possibly oversampled a bit).
	* From DetLen/2 to DetLen/3, grid at half the first order.
	* From DetLen/3 to DetLen/4, grid at one-third the first order.
	* ... and so forth.

	The general form is:
	  n_m = the number of grid points for order m,
	  n = the number of grid points required to span from wavelength=0
	    (zero-order centroid) to DetLen at the first order resolution. 
	  n_m = [ 1/m - 1/(m+1) ] * m  * n  =   n / (m+1) 
	Thus the total number of grid-points required is: 
	  N = sum_{m=1..MaxOrd} { [1/m - 1/(m+1)] * m  * n} 
	    = n * sum_{m=1..MaxOrd} {1 / (m+1)} 
	    = n * { Psi(2+MaxOrd) - 1 + gamma}, 
	where Psi(x) is the digamma function, and gamma is Euler's constant.

	This is a diverging but slowly increasing function.  For MaxOrd of
	10, 20, and 30, N is 2.0*n, 2.6*n, and 3.0*n, respectively.  (If the
	spectrum were gridded at the highest resolution required, N would
	scale directly with MaxOrd.)

	Given some reasonable MaxOrd (such as 30 for LETGS), the minimum
	wavelength grid point calculated as outlined above will still be
	above the minimum needed in model spectra.  Thus, we have added a
	minimum wavelength as a parameter, and the grid will be filled from
	the minimum grid point to the specified minimum at the gridding of
	the MaxOrd segment.

history
	v1.0 as WAVE_GRID.PRO by Dave Huenemoerder (2 december 1995)
	%=====================================================================
	% Time-stamp: <97/04/24 10:00:48 dph>
	% MIT Directory: ~dph/h1/Model-Spec/pro
	% CfA Directory: /dev/null
	% Mac Directory: :Bruno:science:Model-Spec:pro
	% File: line_spectrum.pro
	% Author: D. Huenemoerder
	% original version: 951202
	%=====================================================================
	modified to make it SCAR-friendly, changed WMIN to mean minimum of
	  bin-beginning values rather than minimum of bin-center values
	  (VK;Jan98)
	corrected spelling mistake w. OVERSAMPL (VK;Jun99)
	corrected spike at WAVE_MIN at end of MAXORD (VK; Jun99)
	changed default value of X_ROWLAND (VK; FebMM)

(See /data/fubar/SCAR/pro/specific/axaf_wgrid.pro)


BAMABS

[Previous Routine] [Next Routine] [List of Routines]
function	bamabs
	return photoelectric absorption cross-sections in energy range
	30 eV - 10 keV using the polynomial fit coefficients determined
	by Monika Balucinska-Church and Dan McCammon (Balucinska-Church,
	M.\ and McCammon, D.\ 1992, ApJ 400, 699).  This is an update
	to Morrison & McCammon 1983.

syntax
	sigabs=bamabs(w,abund=abund,/ikeV,/Fano,verbose=v)

parameters
	w	[INPUT; required] photon energy values at which to compute
		the absorption
		* default units are [Ang], unless IKEV is set, when they are
		  assumed to be [keV]

keywords
	abund	[INPUT] abundances relative to H=1
		* default is to use Anders & Grevesse 1982
	ikeV	[INPUT] if set, assumes that W are in units of keV
	Fano	[INPUT] if set, the 4 strongest auto-ionizing resonances
		of He I are included; numbers come from Oza (1986, Phys
		Rev A, 33, 824), and Fernley et al. (1987, J.Phys B 20, 6457).
	noHeH	[INPUT] if set to any number other than 1 or 2, excludes
		H and He from the cross-sections
		* if set to 1, only excludes H
		* if set to 2, only excludes He
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to avoid crashing the program

subroutines
	GETABUND
	INICON

restrictions
	works only in energy range 30 eV - 10 keV
	be warned that the edges are idealized and thus unrealistic
	  for high resolution spectra because they do not include
	  any resonance structure

history
	vinay kashyap (OctMM; based on TOTLXS.FOR and XSCTNS.FOR of
	  Balucinska-Church & McCammon, obtained from ADC catalog VI/62A,
	  ftp://adc.gsfc.nasa.gov/pub/adc/archives/catalogs/6/6062A/ )
	bug corrections (Brian Kern, 5Dec2001): Ne cross-section was
	  missing "^3"; Fano calc had EPSj[j] (VK; Dec2001)
	force calculations only in valid energy range; added keyword
	  NOHEH (VK; Jun03)
	bug correction: "exclude=0" means "include" (VK; Jul03)
	bug correction: lambda selection for He (Andy Ptak; VK Jun05)
	edge lambda correction: O, N, C changed acc. to numbers in
	  Atomic Data Booklet (2nd Edition), Thompson, A., et al., 2001,
	  LBL/PUB-490 Rev. 2 (Jeremy Drake; VK Sep2006)

(See /data/fubar/SCAR/pro/bamabs.pro)


BECCA

[Previous Routine] [Next Routine] [List of Routines]
BECCA.PRO

example program for calling LINESPEC and CONT_CIE
							vinay kashyap

(See /data/fubar/SCAR/pro/esempio/becca.pro)


BEHR_HUG

[Previous Routine] [Next Routine] [List of Routines]
function	BEHR_hug
	IDL wrapper to Bayesian Estimate of Hardness Ratios (BEHR)
	returns a structure containing the relevant outputs neatly
	summarized into fields for IDL consumption

	references:

	"Bayesian Estimation of Hardness Ratios: Modeling and Computations",
	  Park, T., Kashyap, V.L., Siemiginowska, A., van Dyk, D., Zezas, A.,
	  Heinke, C., and Wargelin, B., 2006, ApJ, 652, 610

	"BEHR: Bayesian Estimation of Hardness Ratios", Park, T., Kashyap, V.,
	  Zezas, A., Siemiginowska, A., van Dyk, D., Connors, A., and Heinke, C.,
	  2005, at Six Years of Science with Chandra Symposium, Nov 2-5, 2005, #5.6

	"Computing Hardness Ratios with Poissonian Errors",
	  van Dyk, D.A., Park, T., Kashyap, V.L., \& Zezas, A.,
	  2004, AAS-HEAD #8, 16.27
	  http://www.aas.org/publications/baas/v36n3/head2004/137.htm

syntax
	behr=behr_hug(softsrc,hardsrc,softbkg,hardbkg,softarea,hardarea,$
	softeff=softeff,hardeff=hardeff,softidx=softidx,hardidx=hardidx,$
	softscl=softscl,hardscl=hardscl,softtbl=softtbl,hardtbl=hardtbl,/post,$
	level=level,algo=algo,details=details,nsim=nsim,nburnin=nburnin,$
	/hpd,nbins=nbins,outputf=outputf,outputR=outputR,outputHR=outputHR,$
	outputC=outputC,outputMC=outputMC,outputPr=outputPr,BEHRdir=BEHRdir,$
	verbose=verbose)

parameters
	softsrc	[INPUT; required] counts in source region in soft (S) band
	hardsrc	[INPUT; required] counts in source region in hard (H) band
	softbkg	[INPUT; required] counts in background region in S band
	hardbkg	[INPUT; required] counts in background region in H band
	softarea[INPUT; required] background scaling factor in S band
	hardarea[INPUT; required] background scaling factor in H band
		* (background region area)/(source region area)
		* can also include differences in exposure time into
		  the ratio, in the same manner as geometric area

keywords
	softeff	[INPUT] effective area in soft (S) band
		* if not set, then set equal to HARDEFF if given, or
		  1 otherwise
	hardeff	[INPUT] effective area in hard (H) band
		* if not set, then set equal to SOFTEFF if given, or
		  1 otherwise
		* can also be the effective area relative to some
		  special point on the detector (e.g., aimpoint)
		  or even some specific detector (e.g., ACIS-I v/s ACIS-S)
	softidx	[INPUT] index of prior on S (range = 0+)
		* if not set, then set equal to HARDIDX if given, or
		  0.5 otherwise
	hardidx	[INPUT] index of prior on H (range = 0+)
		* if not set, then set equal to SOFTIDX if given, or
		  0.5 otherwise
		* similar to AGAMMA of PPD_SRC()
	softscl	[INPUT] scaling index of prior on S
		* if not set, then set to HARDSCL if given, or
		  0 otherwise
	hardscl	[INPUT] scaling index of prior on H
		* if not set, then set to SOFTSCL if given, or
		  0 otherwise
		* similar to BGAMMA of PPD_SRC()
	softtbl	[INPUT] filename containing a tabulated prior for S
	hardtbl	[INPUT] filename containing a tabulated prior for H
		* the table prior must be an ascii file with the following format:
		  line 1: number of entries, say NLIN
		  line 2: labels for the columns, ignored
		  lines 3..NLIN+2: two whitespace separated columns of numbers,
	            with each row containing the source intensity and the posterior
	            density, in that order
		* the default filenames are "./tblprior_{soft|hard}.txt"
		* the default filenames are used iff SOFTTBL and HARDTBL are set
		  but do not appear to exist
		* WARNING: if regex is used in the filename specification, only the
		  first file from the list will be used.  furthermore, if specified,
		  the table priors are applied to _all_ SOFTSRC and HARDSRC
	post	[INPUT] if set, suggests the values of (SOFTIDX,SOFTSCL)
		and (HARDIDX,HARDSCL) going forward, i.e., what you should
		set the priors to in your next calculation for the same
		source
	level	[INPUT] percentage confidence level at which to report error
		(default = 68)
	details	[INPUT] compute various ratios (true/false)?
		(default = true)
	algo	[INPUT] calculation method, GIBBS (default) or QUAD
		* if set to AUTO or AUTO=N, then uses GIBBS for any
		  case where {SOFT|HARD}SRC > N, and QUAD below that
		  unless one of {SOFT|HARD}SRC > 99, in which case
		  GIBBS is set automatically
		  - if N is not set, assumed to be 15
		  - N can be set to any integer less than 100
	nsim	[INPUT] number of draws if algo=gibbs (default=10000)
	nburnin	[INPUT] number of burn-in draws if algo=gibbs
		(default=5000 or NSIM/2, whichever is smaller)
	nbins	[INPUT] number of bins in integration if algo=quad (default=500)
	hpd	[INPUT] if set, computes the highest posterior density interval,
		which also is the smallest interval that includes the mode.
		* this is set by default
		* only has an effect if ALGO=QUAD
	outputF	[INPUT] root of filename in which to place output
		(default = 'none')
		* output will be placed in the file, OUTPUTF.txt
		* unless OUTPUTF='none', in which case nothing is written out,
		    unless one of OUTPUT{R|C|HR|MC|PR} are set, in which case
		    the corresponding output is put in file BEHR_{R|C|HR|MC|PR}.txt
	outputR	[INPUT] if set, writes output for R in OUTPUTF_R.txt
	outputC	[INPUT] if set, writes output for C in OUTPUTF_C.txt
	outputHR[INPUT] if set, writes output for HR in OUTPUTF_HR.txt
	outputMC[INPUT] if set, writes Monte Carlo draws for lamS and lamH
		to OUTPUTF_draws.txt when algo=gibbs
	outputPr[INPUT] if set, writes the probability distributions for
		R, HR, C, lamS, and lamH to OUTPUTF_prob.txt when algo=quad
	BEHRdir	[INPUT] full path to directory where BEHR executable resides
		(default = '/data/fubar/kashyap/AstroStat/BEHR')
	verbose	[INPUT] controls chatter

requirements
	BEHR executable must be installed in BEHRDIR
	BEHR should be executable under the shell via SPAWN
	BEHR output assumed to be compatible with 12-19-2005 version

side-effects
	potentially creates numerous ascii files in $cwd

history
	vinay kashyap (SepMMV)
	bugfix: output file format was overflowing; force NBURNIN < NSIM;
	  outputF for 1st iteration; added more references (VK; NovMMV)
	added keywords SOFTSCL,HARDSCL,POST,HPD; changed DETAILS default
	  to true, OUTPUTF default to none; added extra fields to output
	  structure; added ALGO option AUTO (VK; DecMMV)
	altered behavior of ALGO=AUTO to use GIBBS if counts in one of the
	  bands exceeds 100 (VK; OctMMVI)
	added keywords SOFTTBL and HARDTBL (VK; FebMMVIII)

(See /data/fubar/SCAR/pro/stat/behr_hug.pro)


BINERSP

[Previous Routine] [Next Routine] [List of Routines]
function	binErsp
	returns position indices of input energ(y/ies) appropriately
	binned into the specified binning scheme

	returns -1 where E is outside the bin range

syntax
	iE=binersp(nrg,binmn,maxbin,bstr=bstr,nbin=nbin)

parameters
	nrg	[INPUT; required] photon energies for which to find
		the binning numbers
	binmn	[INPUT] array of bin minimum values
		* overrides all keywords
		* if not given, see description below on how it is
		  derived from BSTR.ELO, and NBIN & NRG.
	binmx	[INPUT] maximum of the bin max values.
		* if not a scalar, then the last element of array is used
		* see description below for how it is determined if
		  not given.

keywords
	bstr	[INPUT] structure containing the following pieces of
		information, as obtained from an OGIP-compliant response
		matrix (see RDRESP.PRO/RDARF.PRO): {NNRG, ELO, EHI}
	nbin	[INPUT; default=101] number of equally spaced bins into
		which to split the input array of photon energies
		* if -ve, binning will be logarithmic!
	_extra	[JUNK] here only to prevent crashing the program

description
	if BINMN is not given, then BINMN=BSTR.ELO
	  if BSTR is also not given (or is incorrect), then
	  	BINMN=FINDGEN(ABS(NBIN))*DE+EMIN
	  where DE=(EMAX-EMIN)/(ABS(NBIN)-1), EMIN=MIN(EE,MAX=EMAX),
	  and EE=NRG if NBIN>0, EE=ALOG10(NRG) if NBIN<0
	if BINMX < MAX(BINMN), BINMN is truncated
	if BINMX < MIN(BINMN), BINMX is reset to MIN(BINMN)
	if BINMX is not given, then BINMX=MAX(BINMN)+BINMX(LAST)-BINMX(LAST-1)
	  if BINMN is not given, BINMX=MAX(BSTR.EHI)
	    if BSTR is also not given (or is incorrect), then BINMX=EMAX

history
	vinay kashyap (Jul97)
	converted to IDL5 notation (VK; OctMM)

(See /data/fubar/SCAR/pro/binersp.pro)


BLAND

[Previous Routine] [Next Routine] [List of Routines]
function	bland
	returns a "blending factor" for each line in the emissivity list,
	defined as the ratio of the flux in the line to that within the
	given range.  (i.e., small values mean heavily blended lines)

syntax
	b=bland(flstr,dwvl,flx=flx,wflx=wflx,arstr=arstr,$
	dem=dem,abund=abund,effar=effar,wvlar=wvlar,$
	/temp,/noph,/ikev,/regrid)

parameters
	flstr	[INPUT; required] structure containing emissivity and
		wavelength information.  see RD_LINE for details.
		* ion-balance assumed to be included
		* if FLX and WFLX are set on input, FLSTR is ignored --
		  still required, but ignored.
	dwvl	[INPUT; default=median(delta(FLSTR.WVL))] the spectral
		"resolution" -- any line nearer than this value at any
		given wavelength is considered to be blended in to this.
		* if array of size FLSTR.WVL (or twice that size), set to
		  different values (with possible asymmetric ranges) at
		  each wavelength.

keywords
	arstr	[INPUT] structure of structures containing effective
		area information (see ARIA or GRATFLX)
		* if given in the right format, overrides call to LINEFLX
		  with call to GRATFLX
	flx	[I/O] contains the calculated flux due to each line
		* may be given on input and if WFLX is also set, FLSTR and
		  ARSTR are ignored
	wflx	[INPUT] if size matches that of FLX, assumed to be the
		wavelengths of the lines.
		* if FLX and WFLX are set on input, FLSTR and ARSTR are
		  ignored.
	_extra	[INPUT] pass defined keywords to
		GRATFLX (DEM, ABUND, TEMP, NOPH, IKEV, REGRID)
		LINEFLX (DEM, ABUND, EFFAR, WVLAR, TEMP, NOPH, IKEV, REGRID)

subroutines
	ARIA
	GRATFLX
	LINEFLX

history
	vinay kashyap (Sep98)
	bug fix for when FLSTR is ignored (VK; Oct98)
	added keyword ARSTR, added call to GRATFLX (VK; Nov98)
	converted to IDL5 notation (VK; OctMM)
	bug fix: crashed if FLX and WFLX set, but DWVL not set (VK;JanMMI)
	bug fix: FLSTR can have more than 8 tags (JJD; MayMMVII)

(See /data/fubar/SCAR/pro/bland.pro)


CAT_ID

[Previous Routine] [Next Routine] [List of Routines]
function	cat_id
	returns a concatenated structure of Line IDs

syntax
	C=cat_id(A,B,pick=pick,ask=ask,/okev,comm=comm,flst=flst,dbdir=dbdir,$
	fluxes=fluxes,fluxerr=fluxerr)

parameters
	A	[INPUT; required] output of LINEID
	B	[INPUT] output of LINEID to be merged with A
		* if any wavelengths are common, the IDs in A take
		  precedence (but see keyword ASK)
		* if not given, then the program *prints* a summary
		  of the IDs to the screen

keywords
	pick	[INPUT; default: all] position indices of elements in A
		to be selected (or not).
		* if scalar, returns all elements EXCEPT the specified one
		* has no effect on B
		* use these two to delete entries, for e.g.
	ask	[INPUT] if set, asks for confirmation before throwing
		away an ID from B that also exists in A.  allows overriding
		the default action.
		* ASK='n' will reverse the default by throwing away the
		  ID from A instead of the one from B
		* ASK='r' *reverses* the default, in that if there is a
		  component in B that's also in A, the one in A is >replaced<
		  by the one in B (as opposed to if ASK='n', then the one in
		  A is deleted, and B is just appended at the end)
		* ASK='k' overrides the default by keeping BOTH
	okev	[INPUT] if set, converts wavelengths [Ang] to energy [keV]
	comm	[INPUT] appends a comment to each line while printing
		* takes the comments from A.LABL(1,i)+A.LABL(0,i)
		* truncates the comment to a maximum of 30 characters
		  unless COMM is set to a higher number
		* for this to work when FLST is set, make sure DBDIR is
		  also defined
	flst	[INPUT] if set, prints out the line list in the form that
		RD_LIST likes
		* if FLST is a string, writes to file FLST
       mplet   [OUTPUT] if set, will contain on output a 2 dimensional MPLET
               string array as prescribed by MIXIE()
	dbdir	[INPUT] if set and FLST is set, appends DBDIR to IDs
		* 1 => $SCAR , 2 => $SPEX , 3 => $CHIANTI
	fluxes	[INPUT] if set and matches either the number of components
		or the number of matches, then renormalizes/overwrites the
		line fluxes in the output.
		* ONLY if IDs are being printed
	fluxerr	[INPUT] if set and matches either the number of components
		or the number of matches, then appends an error to output
		* ignored if FLST is not set
		* if FLUXERR is given for each match, square-adds the errors
		  for the components
		* if single element, but there are more than 1 component to
		  ID structure, this is assumed to be the fractional error
		  (if < 1) or S/N (if > 1) for each match
	_extra	[JUNK] here only to prevent crashing the program

restrictions
	* works ONLY on the outputs of LINEID
	* requires subroutines:
	  -- INICON
	  -- CREATE_STRUCT
	  -- LINEID

history
	vinay kashyap (Feb97)
	bug -- was breaking down in simplest case (VK; Mar97)
	was breaking down if ID was unknown (VK; Jul97)
	added keyword FLST (VK; Oct98)
	added call to INITSTUFF; added Tmax to output; added keywords DBDIR,
	  FLUXES, FLUXERR; corrected bug re undefined output when FLST was set;
	  increased number of significant digits in FLST output; generalized
	  ASK to "Yes/No/Replace/Keep" (VK; Nov98)
	updated FLUXERR behavior to account for new field (VK; Dec98)
	modified to allow for field NOTES to be printed out (VK; Mar99)
	changed call to INITSTUFF to INICON (VK; 99May)
	added FLUXERR to output (VK; MarMM)
	converted to IDL5 array notation (VK; OctMM)
	changed keyword KEV to OKEV (VK; JanMMI)
	now /COMM also works when FLST (and DBDIR) are defined (VK;Nov01)
       added MPLET keyword (LL; Feb04) 

(See /data/fubar/SCAR/pro/cat_id.pro)


CAT_LN

[Previous Routine] [Next Routine] [List of Routines]
function	cat_ln
	returns a concatenated structure of Line emissivities

syntax
	C=cat_ln(A,B,pick=pick,ask=ask,comm=comm,reord=reord,/okev,$
	abund=abund,/noph,effar=effar,wvlar=wvlar,dem=dem,/temp,/ikev,/regrid)

parameters
	A	[INPUT; required] output of RD_LINE
	B	[INPUT] output of RD_LINE to be merged with A
		* if any wavelengths are common, the IDs in A take
		  precedence (but see keyword ASK)
		* if the temperature grids do not match, the emissivities
		  in B are interpolated to the same grid as in A
		* if not given, then the program *prints* a summary
		  of the lines to the screen

keywords
	pick	[INPUT; default: all] position indices of elements in A
		to be selected (or not).
		* if scalar, returns all elements EXCEPT the specified one
		* has no effect on B
		* use these two to delete entries, for e.g.
	ask	[INPUT] specifies how to handle duplicate lines
		* if not set, doesn't care about duplicates and keeps all
		* if set (see exceptions below), will discard duplicates
		  from B
		* ASK='n' will reverse the normal by throwing away the
		  line from A instead of the one from B
		* ASK='r' will >replace< the emissivity, etc. in A with
		  that of B
		* ASK='k' will act just as though ASK has not been set
	okeV	[INPUT] if set, converts wavelengths [Ang] to energy [keV]
		in the screen listing
	comm	[INPUT] appends a comment to each line while printing
		* takes the comments from A.DESIG[1,i]+A.DESIG[0,i]
		* truncates the comment to a maximum of 30 characters
		  unless COMM is set to a higher number
	flst	[INPUT] if set, prints out the line list in the form that
		RD_LIST likes
		* if FLST is a string, writes to file FLST
	reord	[INPUT] if set, rearrange the order of the output
		* +ve: descending order of fluxes
		* -ve: ascending order of fluxes
		* if abs(REORD) .NE. 1, limit output to first REORD entries
	_extra	[INPUT ONLY] use to pass defined keywords to
		LINEFLX: ABUND, NOPH, EFFAR, WVLAR, DEM, TEMP, REGRID

restrictions
	* works ONLY on the outputs of RD_LINE
	* requires subroutines:
	  -- LINEFLX [GETABUND, WHEE]
	  -- RD_LINE
	  -- CREATE_STRUCT
	  -- INICON

history
	vinay kashyap (Jun98, based on CAT_ID)
	changed keyword LNLST to FLST, added ABUND and REORD (VK; Jul98)
	delete keyword ABUND, and added call to LINEFLX (VK; Aug98)
	corrected bug that was skipping B because of roundoff error in
	  first element; bug in handling ECONF (VK; Nov98)
	changed keyword KEV to OKEV to avoid conflict with LINEFLX keyword
	  of same name (VK; 99Apr)
	added support for structure field JON (VK; 99May)
	allowed merging of mismatched LOGT grids (VK; 99Jul)
	converted to IDL5 array notation (VK; OctMM)
	added full RD_LIST compatible printout for FLST; changed output
	  file wavelength format from f8.4 to f10.5 (VK; JanMMI)
	bug -- crashing on <empty> for FLST -- fixed (VK; Jul04)
	added extra columns (FLUX, logTMAX) to output of FLST (VK; Feb08)

(See /data/fubar/SCAR/pro/cat_ln.pro)


CECF

[Previous Routine] [Next Routine] [List of Routines]
function	cecf
	compute and return a counts-to-energy conversion factor
	as [ergs/cm^2/ct] for a variety of temperatures

syntax
	f=cecf(wvlar,effar,wrange=wrange,chnrng=chnrng,NH=NH,$
	rmfile=rmfile,rmstr=rmstr,lstr=lstr,cstr=cstr,abund=abund,$
	ldbdir=ldbdir,cdbdir=cdbdir,ceroot=ceroot,verbose=verbose,$
	logT=logT,lspec=lspec,cspec=cspec,ctrate=ctrate,eps=eps,$
	logp=logp,n_e=n_e,eqfile=eqfile,chifil=chifil,$
	fH2=fH2,He1=He1,HeII=HeII,/fano,/wam,/bam,/mam,noHeH=noHeH)

parameters
	wvlar	[INPUT; required] array of wavelengths [Ang]
		at which effective area is defined
	effar	[INPUT] effective area [cm^2]
		* must be >0; all -ve values will be set to 0
		* size must match WVLAR.  if it does not:
		-- if N(EFFAR)=0, then EFFAR=fltarr(N(WVLAR))+1.
		-- if N(EFFAR)=1, then EFFAR=fltarr(N(WVLAR))+abs(EFFAR[0])
		-- if N(EFFAR)>1 and .ne.N(WVLAR), interpolated onto
		   minmax(WVLAR) assuming a regular grid

keywords
	wrange	[INPUT] wavelength range of spectral energy distribution
		to include in the calculation
		* ignored if not 2-element array
		* if smaller than minmax(WVLAR), the overhanging parts
		  of the effective area are thrown away
	chnrng	[INPUT] if given, totals counts within the specified
		channel range
		* ignored if not 2-element array
		* if RMF is available (see RMFILE and RMSTR below), then
		  -- if integers, assumed to be the range in PI or PHA
		     (whatever is defined in the RMF), else
		  -- assumed to be the range in [keV]
		* if RMF is not available, then assumed to be the range
		  in [keV] if given, and corresponds to WRANGE if not given
	NH	[INPUT] H column density
		* default is 1e18 cm^-2; explicitly set to 0 to not use NH
		* if value is between 10 and 30, then assumed to have been
		  given in log10(NH)
	rmfile	[INPUT] name of response matrix file
		* ignored if RMSTR is valid
	rmstr	[I/O] a response matrix structure of the type
		output by RD_OGIP_RMF()
		* if it exists on input, this is used instead of
		  trying to read in from RMFILE; once read in, is
		  returned as output via this keyword 
	lstr	[I/O] line emissivity structure of the type read
		in from RD_LINE()
		* if it exists on input, this is used instead of
		  trying to read it in from the line emissivity
		  database; once read in, is returned as output
		  via this keyword
		* WARNING: the output emissivity matrix will include
		  ion balance (but not abundances; do not use output
		  elsewhere unless you know what you are doing)
	cstr	[I/O] as with LSTR, for continuum emissivities
	abund	[INPUT] abundances (see GETABUND() for details)
		* default is Grevesse et al. (1992)
	ldbdir	[INPUT] line emissivity database location
		* default is '$CHIANTI'
		* used only if LSTR is not defined on input
	cdbdir	[INPUT] continuum emissivity database location
		* default is '$CONT'
		* used only if CSTR is not defined on input
	ceroot	[INPUT] continuum emissivity files rootname
		* default is 'cie'
		* used only if CSTR is not defined on input
	verbose	[INPUT] controls chatter
	logT	[OUTPUT] the temperature grid for which the cecf is
		calculated
	lspec	[OUTPUT] the contribution from line emission to the [erg/s/cm^2]
	cspec	[OUTPUT] like LSPEC, for continuum emission [erg/s/cm^2]
	ctrate	[OUTPUT] the countrate that correspond to LSPEC+CSPEC [ct/s]
	eps	[INPUT] a small number; set all values below
		EPS*max(LSPEC+CSPEC) or EPS*max(CTRATE) to !VALUES.NAN
		* explicitly set to 0 to avoid doing this
		* default is 1e-6
	metal	[JUNK] here to trap and discard possible keyword to RD_CONT()
	_extra	[INPUT ONLY] pass defined inputs to subroutines:
		RD_LINE: LOGP, N_E
		FOLD_IONEQ: EQFILE, CHIFILE
		RD_CONT: LOGP, N_E
		ISMTAU: FH2, HE1, HEII, FANO, WAM, BAM, MAM, NOHEH

description

requires subroutines
	RD_LINE, SYMB2ZION, KILROY, WHEE, FOLD_IONEQ, READ_IONEQ, RD_IONEQ,
	RD_CONT, RD_OGIP_RMF, ISMTAU, BAMABS, MID2BOUND, GETABUND, INICON,
	IDL-Astro

history
	vinay kashyap (MMV.III)
	modified behaviour of CHNRNG to work even in absence
	  of RMF (VK; MMV.IX)

(See /data/fubar/SCAR/pro/cecf.pro)


CHAIM

[Previous Routine] [Next Routine] [List of Routines]
function	chaim
	find and return Chandra ObsIDs that contain observations
	of list of RA,Dec

syntax
	chmatch=chaim(ra,dec,ChGEOM=ChGEOM,ChOCAT=ChOCAT,sobs=sobs,$
	verbose=verbose, caldb=caldb,version=version)

parameters
	RA	[INPUT; required] RA_2000.0 in [deg]
	Dec	[INPUT; required] Dec_2000.0 in [deg]
		* size of DEC must match that of RA

keywords
	ChGEOM	[I/O] Chandra geometry file
		* read in from CALDB location if not present on input
	ChOCAT	[I/O] name of file containing the Chandra Observation CATalog,
		or output of RDB structure containing the same -- contains list
		of Chandra ObsIDs and and attendant information such as RA_NOM,
		Dec_NOM, ROLL_NOM, and which chips are on, etc.
		* if valid structure, will use it as is; otherwise:
		-- if filename, will read from that file and return
		   the output structure in this keyword
		* if not specified, will look to read from file 'axafocat.rdb'
	sobs	[INPUT] an integer list of ObsIDs to consider as a
		subset of ChOCAT
	verbose	[INPUT] controls chatter
		* if .GE.5, makes a plot displaying the locations
		  of the matches on the detector
	_extra	[INPUT ONLY] pass defined keywords to subroutines
		CALDB [rd_chandra_geom]
		VERSION [rd_chandra_geom]

warning
	spacecraft roll is approximated in Euclidean space.  this will
	result in some deviations from true, especially for those
	observations involving the grating arrays and aligned N-S.
	however, this will be an issue only for the extreme chips edges
	and is unlikely to have a practical effect.

subroutines
	RD_CHANDRA_GEOM
	RDB

history
	vinay kashyap (Jul2005)
	bug correction: roll off by -90 deg (VK; Aug2005)

(See /data/fubar/SCAR/pro/specific/chaim.pro)


CHANARF

[Previous Routine] [Next Routine] [List of Routines]
function	chanarf
	compute the average effective area over each channel, as a
	weighted average of the effective area from all the energies
	that contribute to that channel.

	makes a difference mainly for low and medium spectral
	resolution data.  for high-res grating data, not so much.

syntax
	carf=chanarf(rmfstr,effar,spec=spec)

parameters
	rmfstr	[INPUT; required] response matrix structure, in the
		same format as returned from RD_OGIP_RMF()
	effar	[INPUT] effective area as a function of energy [cm^2]
		* assumed to be on the same grid as the input energies
		  of RMFSTR, i.e., RMFSTR.ELO and RMFSTR.EHI
		* ignored if size doesn't match RMFSTR

keywords
	spec	[INPUT] a spectrum to further weight the contribution
		of EFFAR
		* assumed to be on the same grid as RMFSTR.ELO and RMFSTR.EHI
		* ignored if size doesn't match EFFAR
		* ideally should be in units of [ph/keV/...]
	chnrg	[OUTPUT] the average energy of a photon in this channel
		* it should be similar to 0.5*(RMFSTR.EMN+RMFSTR.EMX), and
		  serves as a check on the gain calibration
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to prevent crashing

history
	vinay kashyap (MMVI.IX)

(See /data/fubar/SCAR/pro/chanarf.pro)


CHANDRA_PSFSIZE

[Previous Routine] [Next Routine] [List of Routines]
function	chandra_psfsize
	read in the Chandra PSF size table and return the radius [arcsec]
	that encloses a specified energy of the PSF 

syntax
	psfsize=chandra_psfsize(skyx,skyy,eefrac=eefrac,energy=energy,$
	instrum=instrum,psftbl=psftbl,verbose=verbose)

parameters
	skyx	[INPUT; required] the x pixel locations of the points at
		which to compute the size of the PSF
		* or off-axis angles in [arcmin] if SKYY is illegal
	skyy	[INPUT] the y pixel locations corresponding to SKYX
		* sizes of SKYX and SKYY _must_ match.  if they don't --
		  -- if N(SKYY)=1, SKYY[0] is expanded out to N(SKYX)
		  -- if N(SKYY)=0 or N(SKYY)>N(SKYX), then SKYY is ignored
		     and SKYX is assumed to be the offaxis angle in [arcmin]

keywords
	x0	[INPUT] x-location of the aimpoint [pixel]
	y0	[INPUT] y-location of the aimpoint [pixel]
		* if not given, X0 and Y0 are presumed to be at the
		  nominal Chandra aimpoints
		* they are ignored if SKYY is not given
	eefrac	[INPUT; default=0.9] the fraction of energy enclosed
	energy	[INPUT; default=1.5 keV] the energy at which to determine
		the PSF size
		* note: there is no interpolation -- the entries closest
		  to the specified value will be chosen.  any interpolation
		  can always be done post facto by the user.
	instrum	[INPUT; default='HRC-I'] the detector
	psftbl	[INPUT; default='/soft/ciao/data/psfsize20010416.fits']
		full path name to the wavdetect-compatible FITS file that
		contains the PSF size information
	defoc	[INPUT; default=0] the defocus value [mm] at which to
		determine the PSF size
		* note that the default Chandra PSFTBL only lists DEFOC=0
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to prevent crashing the program

history
	vinay kashyap (Apr2006)

(See /data/fubar/SCAR/pro/specific/chandra_psfsize.pro)


CHIPOACOM

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

       Compares emissivities in PoA database to emissivities
       calculated in real time with CHIANTI.
 
	The CHIANTI calculation is done with CH_SYNTHETIC.PRO,
	a major component of CHIANTI's flagship spectral-synthesis
	program CH_SS.PRO.  CH_SYNTHETIC is used to calculate G(T),
	after which PoA's LINEFLX() is used to calculate intensities.
	These intensities are compared to intensities generated
	using PoA's RD_LINE(), FOLD_IONEQ(), and LINEFLX().
	Comparisons of the binned spectra are plotted.
	VOORSMOOTH() is used to smooth binned spectra.

syntax
        .run chipoacom
 
inputs 
	!IONEQF	ion-balance file
	!LDBDIR	atomic database to use default =!LDBDIR 
	!EDENS	electron density
	V_EM	emission measure components corresponding 
	        to each T [cm^5/logK]
	        default is [6.1d11, 6.1d11, 7.1e11]         
	V_LOGT	temperatures at which emission measures are defined 
	        default is [6.1, 6.8, 7.2] 
	V_WMIN	minimum wavelength default = 5.0
	V_WMAX	maximum wavelength default = 15.0
	V_NWBIN	number of bins in output spectra default = 8000
	V_Np	number of plots with which the resulting spectra 
	        are displayed. The wavelength range in each plot
	        is determined by signal strength. 
	V_SMOOT	smoothing scale used to smooth binned spectra 
outputs 
	V_OUTPS	name of ps output file 
        
how to use 
        1. initialize PINTofALE using INITALE
        2. parameters set with initale are: 
           -- ATOMIC: !LDBDIR, !IONEQF, !CHIDIR
           -- STELLAR: !EDENS
        3. set the wavelength range of interest 
              V_WMIN = 5.0 
              V_WMAX = 180.0
        4. set the emission measures and corresponding temperatures
        5. set the output filename if output ps is desired
              V_OUTPS ='CHI4PoAcomparison.ps'
        6. run this script

history 
	Liwei Lin (Jun03)  
	bug fix noclip=0 and polyfill could result in 'inverse' polyfill
	  (LL; Jul03)
	bug fix using floating point precission when defining wgrid
	  is inadequate and results in incongruous specrtal binning
	  results via hastogram(). use double precission instead (LL; Jul03)
	couple of bug fixes (VK; Apr04)
       add check for CHIANTI and IDL version compatiblity (LL; Dec05) 
	updated for IDL5.6 keyword_set([0]) behavior change for vectors
	  (VK; 20Mar2006)
       bug fix extraneous /2 after call to lineflx (LL; Aug08)  

(See /data/fubar/SCAR/pro/esempio/chipoacom.pro)


CHUMMARIZER

[Previous Routine] [Next Routine] [List of Routines]
function	chummarizer
	analyzes a high-resolution Chandra grating spectrum and
	extracts some meaningful summarizing quantities from it,
	such as the ratio of lines-to-continuum fluxes, etc., and
	returns the results in a structure

syntax
	chstr=chummarizer(counts,wave,effar=effar,wvlar=wvlar,$
	lsffwhm=lsffwhm,type=type,hawastr=hawastr,kkcont=kkcont,$
	ctline=ctline,wscale=wscale,wcont=wcont,lpos=lpos,lerrpos=lerrpos,$
	lflx=lflx,lerrflx=lerrflx,lwdt=lwdt,lerrwdt=lerrwdt,$
	verbose=verbose,maxkern=maxkern,clev=clev,maxiter=maxiter)

parameters
	counts	[INPUT; required] counts spectrum
	wave	[INPUT; required] wavelength grid for the spectrum
		* if size matches that of COUNTS, taken to be mid-bin values
		* if size exceeds COUNTS by 1, taken to be grid boundaries
		* if size is double that of COUNTS, taken to be two
		  concatenated arrays of lower and upper boundaries of grid
		* it is assumed that WAVE is on a regular grid, i.e., that
		  WAVE[1:*]-WAVE is constant

keywords
	effar	[INPUT] effective area [cm^2]
		* if set, the counts are converted to flux prior to
		  summarizing
	wvlar	[INPUT] wavelengths at which effective area is defined
		* if not set, assumed to be WAVE
		* size MUST match EFFAR, else both are ignored
		** currently, both EFFAR and WVLAR are ignored
	lsffwhm	[I/O] passed w/o check to HAWALINER()
	type	[INPUT] string denoting which model function to use
		in fitting the detected lines (see LIBMODEL)
		* default: 'beta=2.5' (like Chandra grating LSFs)
	hawastr	[OUTPUT] output from HAWALINER()
	kkcont	[OUTPUT] output from HAWALINER()
	ctline	[OUTPUT] output from HAWALINER()
	wcont	[OUTPUT] output from HAWALINER()
	wscale	[I/O] pass defined wavelet scales to HAWALINER()
	lpos	[OUTPUT] output from HAWALINER()
	lerrpos	[OUTPUT] output from HAWALINER()
	lflx	[OUTPUT] output from HAWALINER()
	lerrflx	[OUTPUT] output from HAWALINER()
	lwdt	[OUTPUT] output from HAWALINER()
	lerrwdt	[OUTPUT] output from HAWALINER()
	verbose	[INPUT] controls chatter
	_extra	[INPUT ONLY] pass defined keywords to subroutines
		* HAWALINER: MAXKERN, CLEV, MAXITER

restrictions
	backgrounds are ignored
	apply only to MEG
	no error bars yet

subroutines
	HAWALINER()
	HIPD_INTERVAL()
	MID2BOUND()
	GETLOCMAX()

history
	vinay kashyap (May07)
	multiple bug corrections (VK; Jun07)
	modified calling sequence to HAWALINER, changed behavior of
	  how counts are collected (VK; Jul08)

(See /data/fubar/SCAR/pro/specific/chummarizer.pro)


CH_GET_FILE

[Previous Routine] [Next Routine] [List of Routines]
 PROJECT     : CHIANTI

       CHIANTI is an Atomic Database Package for Spectroscopic Diagnostics of
       Astrophysical Plasmas. It is a collaborative project involving the Naval
       Research Laboratory (USA), the University of Florence (Italy), the
       University of Cambridge and the Rutherford Appleton Laboratory (UK). 

                   
 NAME        : CH_GET_FILE
     		          
 PURPOSE     : to select a file from either a selected directory or the working
               directory, having an extension.

               
 EXPLANATION : a file in  either a selected directory or the working
               directory, having an extension can be selected using a
               widget. Note that both directory and extension have to be
               supplied. If no file is found, an empty string is returned.                   ; 		

 USE         : IDL> name = ch_get_file( '~/', '.pro',  tit=' Select a procedure ')


 EXAMPLES    : dir= concat_dir(!xuvtop),'dem') 
		dem_name=ch_get_file(path=dir,filter='*.dem',title='Select DEM File')
		
    
 INPUTS      : directory, extension 
		
               
 OPT. INPUTS : 

               
 OUTPUTS     : the file name
	
 OPT. OUTPUTS:
		

 KEYWORDS    : title


 CALLS       : findfile, break_file
		
 COMMON      : co
 		
 RESTRICTIONS:  both directory and extension have to be
               supplied. 

               
 SIDE EFFECTS: 
               
 CATEGORY    : 
               
 PREV. HIST. : extracted from CDS/CHIANTI routines.


      
 WRITTEN     : 

       Giulio Del Zanna (GDZ), 
	DAMTP  (University of Cambridge, UK) 

 MODIFIED    : Version 1, GDZ 10-Oct-2000
               V.2, GDZ, corrected a typo at the end of the file.
               V.3, GDZ,  generalized directory concatenation to work for
                   Unix, Windows  and VMS. 

               V. 4, 19-July-2002, GDZ

                Added the option to select files also with the standard IDL
                dialaog_pickfile, and changed a few things...

               V.5, 2-Aug-02, GDZ 
                 reduced the size of the widget.

               V.6, 12-Aug-02, GDZ
                 corrected for a bug in the directory output.

               V.7, 3-Nov-03  GDZ
                 Fixed a bug when using Windows, the returned path was not
                 correct. 

 VERSION     :  7,  3-Nov-03


(See /data/fubar/SCAR/pro/external/ch_get_file.pro)


CLEANSPEC

[Previous Routine] [Next Routine] [List of Routines]
function	cleanspec
	return a "clean" spectrum, one with the best estimates of the
	source count without explicitly subtracting the background but
	rather by marginalizing over the background model intensities,
	as in van Dyk, D.A., Connors, A., Kashyap, V.L., & Siemiginowska,
	A., 2001, ApJ 548, 224.

syntax
	srcct=cleanspec(spec,bspec,bounds,bkgscl,srcscl=srcscl,srcest=srcest,$
	bkgest=bkgest,/getave,clev=clev,verbose=verbose, nsgrid=nsgrid,$
	srcmax=srcmax,srcmin=srcmin,jmax=jmax,/double,k=k,eps=eps)

parameters
	spec	[INPUT; required] array of counts in the source region
	bspec	[INPUT; required] array of counts in the background region
		* if size is smaller than SPEC, gets filled out with the
		  value of the last element of the array
	bounds	[OUTPUT] array of size [2,N(SPEC)] containing the lower [0,*]
		and upper [1,*] bounds on the cleaned source count, at a
		level defined by CLEV
	bkgscl	[INPUT] the area (or exptime) in which BSPEC were collected
		* if not given, assumed to be same as SRCSCL
		* if size is smaller than SPEC, fills out with last element

keywords
	srcscl	[INPUT] area (or exptime) in which SPEC were collected
		* default is 1.0
		* if size is smaller than SPEC, fills out with last element
	srcest	[INPUT] a priori information about the source strength --
		this value is used to define ALPHA_S (=SRCEST+1) in the
		gamma prior and BETA_S (1 if SRCEST is non-zero, 0 otherwise)
		* if illegal (i.e., < 0), then defaults to the
		  non-informative prior of ALPHA_S=1,BETA_S=0
	bkgest	[INPUT] a priori information about the background strength --
		this is used to define ALPHA_B (=BKGEST+1)
		* used iff BSPEC is 0 or -ve
		* default value is <BSPEC> or <SPEC>*BKGSCL/SRCSCL,
		  if the former is zero
	getave	[INPUT] if set, returns the mean value computed from
		the posterior probability distribution rather than
		the mode.  beware that this will be off by 1 from
		what one may normally expect from gaussian intuition.
	clev	[INPUT] level at which to determine the bounds on the
		source intensities
		* default is 0.68
		* if < 0, abs value is used
		* if > 1 and < 100, then assumed to be given as a percentage
		* if > 100, then 1-1/CLEV is used as the true value
	verbose	[INPUT] controls chatter
	_extra	[INPUT ONLY] pass defined keywords to subroutines
		-- POST_SRCGAMMA: NSGRID,SRCMAX,SRCMIN
		-- QROMB: JMAX,DOUBLE,K,EPS

subroutines
	POST_SRCGAMMA
	PROB_GAMMADIST
	KILROY

history
	vinay kashyap (Aug01)

(See /data/fubar/SCAR/pro/cleanspec.pro)


COLBEHR

[Previous Routine] [Next Routine] [List of Routines]
function	colbehr
	computes hardness ratios based on 3-band data by invoking
	BEHR (Bayesian Estimate of Hardness Ratios) twice, and
	returns the inputs as well as the following quantities
	and their credible ranges in a structure:
	  {S, M, H, lS=log10(S), lM=log10(M), lH=log10(H),
	  SpM=S+M, MpH=M+H, SpH=S+H, T=S+M+H,
	  SmM=S-M, MmH=M-H, SmH=S-H,
	  R1=S/M, R2=M/H, R3=S/H,
	  C1=C_SM, C2=C_MH, C3=C_SH,
	  HR1=(S-M)/(S+M), HR2=(M-H)/(M+H), HR3=(S-H)/(S+H),
	  HRA=(S-M)/(S+M+H), HRB=(M-H)/(S+M+H), HRC=(S-H)/(S+M+H)}

	Warning: Because of the necessity of combining two separate
	runs of BEHR, only the MCMC option is used.  Thus, if the
	length of the chain is small, the computed values may be
	subject to computational instability.

	Warning: BEHR assumes that the passbands in question
	do not overlap, and that the counts input to the program
	are statistically independent.  It is up to the users to
	ensure the validity of this assumption.  No checks are
	made to verify it.

	Reference:
	"Bayesian Estimation of Hardness Ratios: Modeling and Computations",
	  Park, T., Kashyap, V.L., Siemiginowska, A., van Dyk, D., Zezas, A.,
	  Heinke, C., and Wargelin, B., 2006, ApJ, 652, 610
	http://hea-www.harvard.edu/AstroStat/BEHR/

syntax
	behr3=colbehr(Ssrc,Msrc,Hsrc,Sbkg=Sbkg,Mbkg=Mbkg,Hbkg=Hbkg,$
	Sarea=Sarea,Marea=Marea,Harea=Harea,$
	Seff=Seff,Meff=Meff,Heff=Heff,$
	Sidx=Sidx,Midx=Midx,Hidx=Hidx,$
	Sscl=Sscl,Mscl=Mscl,Hscl=Hscl,$
	Stable=Stable,Mtable=Mtable,Htable=Htable,$
	/post,level=level,nsim=nsim,nburnin=nburnin,hpd=hpd,$
	outputf=outputf,BEHRdir=BEHRdir, verbose=verbose)

parameters
	Ssrc	[INPUT; required] counts in source region in the soft (S) band
	Msrc	[INPUT; required] counts in source region in the medium (M) band
	Hsrc	[INPUT; required] counts in source region in the hard (H) band
		* can be arrays; if so, the array with the most elements
		  determines the size of the output and the shortfalls in the
		  others, if any, are made up by replicating the first elements

keywords
	Sbkg	[INPUT] counts in background region in the S band
	Mbkg	[INPUT] counts in background region in the M band
	Hbkg	[INPUT] counts in background region in the H band
		* if not given, assumed to be 0
		* if size smaller than Xsrc, first element gets replicated
	Sarea	[INPUT] background scaling factor in the S band
	Marea	[INPUT] background scaling factor in the M band
	Harea	[INPUT] background scaling factor in the H band
		* (background region area)/(source region area)
		* if not given, assumed to be 1
		* can also include differences in exposure time into
		  the ratio, in the same manner as geometric area
		* if size smaller than Xsrc, first element gets replicated
	Seff	[INPUT] effective area in S band
	Meff	[INPUT] effective area in M band
	Heff	[INPUT] effective area in H band
		* if none are set, all are assumed to be 1,
		  else if one is set, all are assumed to be equal to that one,
		  else if two are set and unequal, third is assumed to be 1
		* can also be the effective area relative to some
		  special point on the detector (e.g., aimpoint)
		  or even some specific detector (e.g., ACIS-I v/s ACIS-S)
		* if size smaller than Xsrc, first element gets replicated
	Sidx	[INPUT] index of prior on S (range = 0+)
	Midx	[INPUT] index of prior on M (range = 0+)
	Hidx	[INPUT] index of prior on H (range = 0+)
		* if none are set, all are assumed to be 0.5,
		  else if one is set, all are assumed to be equal to that one
		  else if two are set and are unequal, third is assumed to be 0.5
		* if size smaller than Xsrc, first element gets replicated
		* similar to AGAMMA of PPD_SRC()
	Sscl	[INPUT] scaling index of prior on Ssrc
	Mscl	[INPUT] scaling index of prior on Msrc
	Hscl	[INPUT] scaling index of prior on Hsrc
		* if none are set, all are assumed to be 0
		  else if one is set, all are assumed to be equal to that one
		  else if two are set and are unequal, third is assumed to be 0
		* if size smaller than Xsrc, first element gets replicated
		* similar to BGAMMA of PPD_SRC()
	Stable	[INPUT] filename containing a tabulated prior for Ssrc
	Mtable	[INPUT] filename containing a tabulated prior for Msrc
	Htable	[INPUT] filename containing a tabulated prior for Hsrc
		* the table prior must be an ascii file with the following format:
		  line 1: number of entries, say NLIN
		  line 2: labels for the columns, ignored
		  lines 3..NLIN+2: two whitespace separated columns of numbers,
	            with each row containing the source intensity and the posterior
	            density, in that order
		* the default filenames are "./tblprior_{soft|med|hard}.txt"
		* the default filenames are used iff Stable, Mtable, and Htable are set
		  but are not found
		* WARNING: if regex is used in the filename specification, only the
		  first file from the list will be used.  furthermore, if specified,
		  the table priors are applied to _all_ SSRC, MSRC, and HSRC
	post	[INPUT] if set, suggests the values of (Sidx,Sscl), (Midx,Mscl),
		and (Hidx,Hscl) going forward, i.e., what you should set the
		priors to in your next calculation for the same source -- the
		suggested values are stored in the output structure
	level	[INPUT] percentage confidence level at which to report error
		(default = 68)
	details	[INPUT] compute various ratios (true/false)?
		(default = true)
	nsim	[INPUT] number of draws if algo=gibbs (default=10000)
	nburnin	[INPUT] number of burn-in draws if algo=gibbs
		(default=5000 or NSIM/2, whichever is smaller)
	outputF	[INPUT] root of filename in which to place output
		(default = 'none')
		* output will be placed in the files OUTPUTF.txt and OUTPUTF_draws.txt
		* NOTE: if OUTPUTF='none', then MC draws will be in BEHR_draws.txt
	BEHRdir	[INPUT] full path to directory where BEHR executable resides
		(default = '/data/fubar/kashyap/AstroStat/BEHR')
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to prevent crashing the program

requirements
	uses subroutines HIPD_INTERVAL() and MODALPOINT()
	BEHR executable must be installed in BEHRDIR
	BEHR should be executable under the shell via SPAWN
	BEHR output assumed to be compatible with 12-19-2005 version

side-effects
	potentially creates numerous ascii files in $cwd or `basedir OUTPUTF`

history
	vinay kashyap (Mar07; based on behr_hug.pro)
	bug correction with NaNs not being caught in some cases
	  (VK; Mar07)
	added keywords Stable,Mtable,Htable (VK; Feb08)

etymology
	getting color-color diagrams using BEHR
	(that's my story and I'm sticking to it)

(See /data/fubar/SCAR/pro/stat/colbehr.pro)


CONT_CIE

[Previous Routine] [Next Routine] [List of Routines]
FUNCTION	cont_cie
	returns continuum emissivities (NLOGT,NBIN) using CIE (subset
	of SPEX) [1e-23 ergs cm^3/s/A]

	WARNING: The continuum emissivities returned here differ from the
	PoA philosophy of line emissivities in that abundances and ion
	balance are *included*!

SYNTAX
	emis=cont_cie(elem,pres,logT,wvl,reH,wmn=wmn,wmx=wmx,nbin=nbin,$
	n_e=n_e,abund=abund,ciedir=ciedir,eqfile=eqfile,$
	cieinp=cieinp,ciespec=ciespec,chidir=chidir)

PARAMETERS
	elem	[INPUT; required] name of element e.g., "He", "C", etc.
		* may specify ionic state (e.g., 'Fe13'), but will be ignored
		* only the elements that CIE can handle will be included
		  in the final calculation.  As of Dec97, these were
		  	C,N,O,Ne,Na,Mg,Al,Si,S,Ar,Ca,Fe,Ni
		  in addition to H and He, which are ALWAYS included
		* if invalid, ALL of the above will be included
	pres	[INPUT; default: 1e15 cm^-3 K] electron pressure at which
		to compute intensities
	logT	[INPUT/OUTPUT] log(Temperature[K]) at which to compute the
		intensities.  if not given, then LOGT=4.0+FINDGEN(81)*0.05
		* best results if evenly spaced in log(T)
	wvl	[OUTPUT] all the bin-beginning values and the final
		bin ending value in the spectrum [Ang]
	reH	[OUTPUT] n_e/n_H for each LOGT

KEYWORDS
	wmn	[INPUT; default=1] minimum in wavelength range [Ang]
		* absolute minimum is 0.1 ***hardcoded***
	wmx	[INPUT; default=180] maximum in wavelenth range [Ang]
	nbin	[INPUT; default=1000] number of bins in the spectrum
		* if -ve, then binning is logarithmic
	n_e	[INPUT] electron density [/cm^3]
		* OVERRIDES values determined using PRES and LOGT
	abund	[INPUT] abundances (default is from Anders & Grevesse)
	ciedir	[INPUT] directory containing the CIE executable
		* default = /data/fubar/SCAR/CIE
	eqfile	[INPUT] pathname, relative to CHIDIR, of file containing
		ionization equilibrium values
		* default: ioneq/arnaud_rothenflug.ioneq
	cieinp	[INPUT; default='/tmp/cie_inp'] command file name
	ciespec	[INPUT; default='tmp.spec'] file containing output spectrum

	_extra	[INPUT ONLY] use to pass defined keywords to NENH
		* CHIDIR

description
	for each temperature, computes the emissivity using CIEDIR/cie
	and returns a density "insensitive" value

a note on the units:
	in SPEX, the output is power [1e44 ph/s/keV], for an EM of 1e64 /m^3
	in CIE, the output is "emissivity" [ph/m^3/s/keV] (later converted
	  to [ph/m^3/s/Ang]).  the question is, where does the "/m^3" come
	  from in CIE, and how do we get to [ergs cm^3/s/A]?
	answer: there is an extra multiplication by nH^2 [(cm^-3)^2] and the
	  EM is 1e50 /cm^3, and the constant in front is 3e-9, not 3e-1.
	CIE/(n_e*n_H) :: [ph/m^3/s/keV]/[cm^-6]->[ph/m^3/s/keV]*[cm^6]
		->[1e-12 ph m^3/s/keV]
	correcting for the constant in front :: [1e-20 ph m^3/s/keV]
	EM*CORR*CIE/(n_e*n_H) :: [1e-20 ph m^3/s/keV]*[1e44 m^-3]
		->[1e24 ph/s/keV]
	correct for SPEX's default EM :: [1e24 ph/s/keV]*[1e64/1e44]
		->[1e44 ph/s/keV] -> voila!

	so, take CIE, divide by 1e6 [(cm/m)^3], divide by n_e*n_H [(cm^-3)^2],
	multiply by energy of photon at this wavelength,
	multiply by [1e23] (to make numbers large),
	to end up with [1e-23 ergs cm^3/s/(whatever)]

restrictions
	* requires CIE to have been compiled and accessible
	* requires ln -s CIEDIR/*.dat $cwd/.
	* works on UNIX.  only.
	* uses CHIANTI compilation of ion balance
	* requires subroutines
	  -- GETABUND [SETABUND]
	  -- SYMB2ZION [LAT2ARAB]
	  -- NENH [RD_IONEQ [READ_IONEQ (a CHIANTI routine)]
	  -- KILROY

history
	vinay kashyap (Dec97)
	minimum abundance now always > 0 (due to CIE bug); added keywords
	  CIEINP and CIESPEC (VK; Jan98)

(See /data/fubar/SCAR/pro/mkemis/cont_cie.pro)


CONVERTNAME

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

 PROJECT:  CHIANTI

 PROJECT:  CHIANTI

       CHIANTI is an atomic database package for the calculation of
       continuum and emission line spectra from astrophysical plasmas. It is a 
       collaborative project involving the Naval Research Laboratory
       (Washington DC, USA), the Arcetri Observatory (Firenze, Italy), and the
       Cambridge University (United Kingdom).

 NAME:
	convertname

 PURPOSE:
	Ion names as character strings are converted into
	numerical values (note c_2 is C II or C^+1
	in spectroscopic or atomic notation)

 CATEGORY:
	
	naming utility

 CALLING SEQUENCE:

       CONVERTNAME,Name,Iz,Ion


 INPUTS:
	Name:   such as 'c_2'


 OUTPUTS:

	Iz:  nuclear charge Z  (6 for 'c_2', the equivalent of C II)
       Ion:  ionization stage:  (2 for 'c_2')

 OPTIONAL OUTPUTS

       DIELECTRONIC   Set to 1 if NAME has a 'd' appended to it 
                      (indicating dielectronic recombination data) else 
                      set to 0

 EXAMPLE:

                     > convertname,'c_2',iz,ion
                     > print,iz,ion
                     > 6,2

                     > convertname,'o_6d',iz,ion
                     > print,iz,ion
                     > 8,6

 MODIFICATION HISTORY:
 	Written by:	Ken Dere
	March 1996:     Version 2.0
       October 1999:   Version 3.  by kpd

       Ver.4, 11-Dec-01, Peter Young
           Revised routine, removing ch_repstr call.
           Added DIELECTRONIC optional output.

(See /data/fubar/SCAR/pro/external/convertname.pro)


CONVERT_TO_TYPE

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

 PURPOSE:

       Converts its input argument to a specified data type.

 AUTHOR:

       FANNING SOFTWARE CONSULTING
       David Fanning, Ph.D.
       1645 Sheely Drive
       Fort Collins, CO 80526 USA
       Phone: 970-221-0438
       E-mail: davidf@dfanning.com
       Coyote's Guide to IDL Programming: http://www.dfanning.com

 CATEGORY:

       Utilities

 CALLING SEQUENCE:

       result = Convert_To_Type(input, type)

 INPUT_PARAMETERS:

       input:          The input data to be converted.
       type:           The data type. Accepts values as given by Size(var, /TNAME) or Size(var, /TYPE).

 OUTPUT_PARAMETERS:

      result:          The input data is converted to specified data type.

 KEYWORDS:

     None.

 RESTRICTIONS:

     Data types STRUCT, POINTER, and OBJREF are not allowed.

 MODIFICATION HISTORY:

     Written by David W. Fanning, 19 February 2006.

(See /data/fubar/SCAR/pro/external/convert_to_type.pro)


CONV_RMF

[Previous Routine] [Next Routine] [List of Routines]
procedure	conv_rmf
	convolves input energy spectrum with the response matrix

	unlike the combination of RDRESP and FOLD_RESP, this one goes
	easy on memory at the expense of speed.

syntax
	conv_rmf,nrg,flx,chan,spec,rmf,effar=effar,nrgar=nrgar,$
	rmfstr=rmfstr,fchcol=fchcol,/shift1,verbose=verbose

parameters
	nrg	[INPUT; required] mid-bin values at which input FLX is
		defined.
		* usually [keV], depends on RMF file
		* if size = N(FLX)+1, assumed to be bin-boundaries
	flx	[INPUT; required] fluxes in [ph/bin/(s/cm^2/sr/...)]
	chan	[OUTPUT; required] bin boundary values at which output SPEC
		is defined
		* same units as NRG
	spec	[OUTPUT; required] output, convolved spectrum
	rmf	[INPUT; required] name of OGIP-compliant FITS file containing
		the response matrix
		* may also be a structure, such as the output of RD_OGIP_RMF()

keywords
	effar	[INPUT] effective areas [cm^2]
	nrgar	[INPUT] energies at which EFFAR are defined
		* same units as NRG
		* sizes of EFFAR and NRGAR must match
		* range of NRGAR must overlap NRG
		* if EFFAR and NRGAR are legal, FLX is multiplied by
		  EFFAR (over intersection of NRGAR and NRG; zeroed
		  elsewhere) before convolving with response matrix
		* of course, this multiplication makes sense only if
		  units on FLX are [ph/bin/cm^2/...]
	rmfstr	[OUTPUT] structure containing info of response matrix,
		the output of RD_OGIP_RMF()
	verbose	[INPUT] controls chatter
	_extra	[INPUT ONLY] pass defined keywords to subroutines:
		RD_OGIP_RMF: FCHCOL, SHIFT1
		REBINW : SLOWOK

restrictions
	requires IDLAstro library
	requires RD_OGIP_RMF()
	requires REBINW()
	requires BINERSP()

history
	vinay kashyap (Apr99)
	added keyword SHIFT1 (VK; JanMMI)
	bug: incorrect usage of WVLAR instead of NRGAR in effar block
	  (Erica R; Aug01)
	deleted keyword SHIFT1, cleaned up and speeded up (VK; Nov2001)
	bug: when spectrum size < RMF size and RMF has multiple groups,
	  was using only the first group (VK; Nov'02)
	bug: was crashing when NRG was outside the bounds of the RMF
	  in cases where the RMF was at a higher resolution (LL/VK; Apr'03)
	added keyword VERBOSE (VK; MarMMV)
	bug: when input spectrum energy range was smaller than RMF range,
	  was assuming RMF was at higher resolution even if it wasn't
	  (VK; Aug'07)
	bug: wasn't checking for frequency beating between input spectrum
	  grid and input RMF grid in above case; now if it does, and calls
	  REBINW() and forces input spectrum to the right grid (VK; Aug'07)
	bug: EFFAR multiplication was being ignored when input spectrum had
	  to be rebinned to match RMF grid (VK; Oct'07)

(See /data/fubar/SCAR/pro/conv_rmf.pro)


CURVEFIT

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

 PURPOSE:
       Non-linear least squares fit to a function of an arbitrary 
       number of parameters.  The function may be any non-linear 
       function.  If available, partial derivatives can be calculated by 
       the user function, else this routine will estimate partial derivatives
       with a forward difference approximation.

 CATEGORY:
       E2 - Curve and Surface Fitting.

 CALLING SEQUENCE:
       Result = CURVE_FIT(X, Y, Weights, A, SIGMA, FUNCTION_NAME = name, $
                         ITMAX=ITMAX, ITER=ITER, TOL=TOL, /NODERIVATIVE)

 INPUTS:
       X:  A row vector of independent variables.  This routine does
           not manipulate or use values in X, it simply passes X
           to the user-written function.

       Y:  A row vector containing the dependent variable.

  Weights:  A row vector of weights, the same length as Y.
            For no weighting,
                 Weights(i) = 1.0.
            For instrumental (Gaussian) weighting,
                 Weights(i)=1.0/sigma(i)^2
            For statistical (Poisson)  weighting,
                 Weights(i) = 1.0/y(i), etc.

       A:  A vector, with as many elements as the number of terms, that 
           contains the initial estimate for each parameter.  IF A is double-
           precision, calculations are performed in double precision, 
           otherwise they are performed in single precision. Fitted parameters
           are returned in A.

 KEYWORDS:
       FUNCTION_NAME:  The name of the function (actually, a procedure) to 
       fit.  IF omitted, "FUNCT" is used. The procedure must be written as
       described under RESTRICTIONS, below.

       ITMAX:  Maximum number of iterations. Default = 20.
       ITER:   The actual number of iterations which were performed
       TOL:    The convergence tolerance. The routine returns when the
               relative decrease in chi-squared is less than TOL in an 
               interation. Default = 1.e-3.
       CHI2:   The value of chi-squared on exit (obselete)
     
       CHISQ:   The value of reduced chi-squared on exit
       NODERIVATIVE:   IF this keyword is set THEN the user procedure will not
               be requested to provide partial derivatives. The partial
               derivatives will be estimated in CURVEFIT using forward
               differences. IF analytical derivatives are available they
               should always be used.

 OUTPUTS:
       Returns a vector of calculated values.
       A:  A vector of parameters containing fit.

 OPTIONAL OUTPUT PARAMETERS:
       Sigma:  A vector of standard deviations for the parameters in A.

 COMMON BLOCKS:
       NONE.

 SIDE EFFECTS:
       None.

 RESTRICTIONS:
       The function to be fit must be defined and called FUNCT,
       unless the FUNCTION_NAME keyword is supplied.  This function,
       (actually written as a procedure) must accept values of
       X (the independent variable), and A (the fitted function's
       parameter values), and return F (the function's value at
       X), and PDER (a 2D array of partial derivatives).
       For an example, see FUNCT in the IDL User's Libaray.
       A call to FUNCT is entered as:
       FUNCT, X, A, F, PDER
 where:
       X = Variable passed into CURVEFIT.  It is the job of the user-written
           function to interpret this variable.
       A = Vector of NTERMS function parameters, input.
       F = Vector of NPOINT values of function, y(i) = funct(x), output.
       PDER = Array, (NPOINT, NTERMS), of partial derivatives of funct.
               PDER(I,J) = DErivative of function at ith point with
               respect to jth parameter.  Optional output parameter.
               PDER should not be calculated IF the parameter is not
               supplied in call. IF the /NODERIVATIVE keyword is set in the
               call to CURVEFIT THEN the user routine will never need to
               calculate PDER.

 PROCEDURE:
       Copied from "CURFIT", least squares fit to a non-linear
       function, pages 237-239, Bevington, Data Reduction and Error
       Analysis for the Physical Sciences.  This is adapted from:
       Marquardt, "An Algorithm for Least-Squares Estimation of Nonlinear
       Parameters", J. Soc. Ind. Appl. Math., Vol 11, no. 2, pp. 431-441,
       June, 1963.

       "This method is the Gradient-expansion algorithm which
       combines the best features of the gradient search with
       the method of linearizing the fitting function."

       Iterations are performed until the chi square changes by
       only TOL or until ITMAX iterations have been performed.

       The initial guess of the parameter values should be
       as close to the actual values as possible or the solution
       may not converge.

 EXAMPLE:  Fit a function of the form f(x) = a * exp(b*x) + c to
           sample pairs contained in x and y.
           In this example, a=a(0), b=a(1) and c=a(2).
           The partials are easily computed symbolicaly:
           df/da = exp(b*x), df/db = a * x * exp(b*x), and df/dc = 1.0

           Here is the user-written procedure to return F(x) and
           the partials, given x:

       pro gfunct, x, a, f, pder      ; Function + partials
         bx = exp(a(1) * x)
         f= a(0) * bx + a(2)         ;Evaluate the function
         IF N_PARAMS() ge 4 THEN $   ;Return partials?
         pder= [[bx], [a(0) * x * bx], [replicate(1.0, N_ELEMENTS(f))]]
       end

         x=findgen(10)                  ;Define indep & dep variables.
         y=[12.0, 11.0,10.2,9.4,8.7,8.1,7.5,6.9,6.5,6.1]
         Weights=1.0/y            ;Weights
         a=[10.0,-0.1,2.0]        ;Initial guess
         yfit=curvefit(x,y,Weights,a,sigma,function_name='gfunct')
         print, 'Function parameters: ', a
         print, yfit
       end

 MODIFICATION HISTORY:
       Written, DMS, RSI, September, 1982.
       Does not iterate IF the first guess is good.  DMS, Oct, 1990.
       Added CALL_PROCEDURE to make the function's name a parameter.
              (Nov 1990)
       12/14/92 - modified to reflect the changes in the 1991
            edition of Bevington (eq. II-27) (jiy-suggested by CreaSo)
       Mark Rivers, U of Chicago, Feb. 12, 1995
           - Added following keywords: ITMAX, ITER, TOL, CHI2, NODERIVATIVE
             These make the routine much more generally useful.
           - Removed Oct. 1990 modification so the routine does one iteration
             even IF first guess is good. Required to get meaningful output
             for errors. 
           - Added forward difference derivative calculations required for 
             NODERIVATIVE keyword.
           - Fixed a bug: PDER was passed to user's procedure on first call, 
             but was not defined. Thus, user's procedure might not calculate
             it, but the result was THEN used.

      Steve Penton, RSI, June 1996.
            - Changed SIGMAA to SIGMA to be consistant with other fitting 
              routines.
            - Changed CHI2 to CHISQ to be consistant with other fitting 
              routines.
            - Changed W to Weights to be consistant with other fitting 
              routines.
            _ Updated docs regarding weighing.

	Vinay Kashyap, CfA, Dec 1998
	     - Changed name to CURVE_FIT.
	     - Added keyword _EXTRA=E to calling sequence and to all
	       calls to CALL_PROCEDURE.
           

(See /data/fubar/SCAR/pro/external/curve_fit.pro)


CUT_ID

[Previous Routine] [Next Routine] [List of Routines]
function	cut_id
	add or delete IDs to an existing ID structure

syntax
	newid=cut_id(idstr,idx,delet=delet,addon=addon,verbose=verbose,$
	/incieq,dbdir=dbdir,sep=sep,pres=pres,logP=logP,n_e=n_e,$
	chifil=chifil,chidir=chidir,eqfile=eqfile)

warning
	will not keep track of relative fluxes or their errors properly,
	though the total flux will be conserved.

parameters
	idstr	[INPUT; required] an ID structure (see LINEID.PRO) containing
		line identifications of spectral features
	idx	[INPUT; required] a zero-based index of the feature
		being (re)edited
		* must be a scalar
		* nothing happens if IDX is outside the legal range defined
		  by IDSTR

keywords
	delet	[INPUT] set to a zero-based index to IDSTR.(IDX+1)
		* if float, assumed to refer to IDSTR.(IDX+1).WVL
		* if string, assumed to be in same format as understood by
		  RD_LIST: "Z ION <sep> WAVE <sep> SOURCE <sep> DESCRIPTION"
		  (RD_LIST will in fact be called in order to decipher it)
		* may be an array
	addon	[INPUT] string describing the line to be added as an ID
		to IDSTR.(IDX+1)
		* must be in same format as that understood by RD_LIST:
		  "Z ION <sep> WAVE <sep> SOURCE <sep> DESCRIPTION"
		* may be an array
	eps	[INPUT] a small number
		* default is 1e-5
	verbose	[INPUT] controls chatter
	_extra	[INPUT ONLY] pass defined keywords to
		RD_LIST: INCIEQ,DBDIR,SEP,PRES,LOGP,N_E,CHIFIL,CHIDIR,EQFILE
		LINEFLX: DEM,ABUND,NOPH,EFFAR,WVLAR

restrictions
	requires subroutines:
	  RD_LIST, RD_LINE, FOLD_IONEQ, READ_IONEQ, RD_IONEQ, LINEFLX,
	  GETABUND, WHEE, SYMB2ZION, LAT2ARAB, CAT_LN
	requires IDL 5.3+ (because of use of STRSPLIT, STRJOIN, STRCMP)

history
	vinay kashyap (JanMMI)

(See /data/fubar/SCAR/pro/cut_id.pro)


DARSHANA

[Previous Routine] [Next Routine] [List of Routines]
procedure	darshana
	display 1D curve with annotation

	"darshana" is the verb form of "vision", the Joan kind.
	pronounced "the-r-shun-ah"

syntax
	darshana,x,y,ststr,wid=wid,pid=pid,xsize=xsize,ysize=ysize,$
	colmax=colmax,stretch=stretch, PLOT_KEYWORDS

parameters
	x	[INPUT; required] points where the curve is defined
	y	[INPUT; required] the curve Y[X] (usually a spectrum)
		* size of Y must match that of X
	ststr	[INPUT; required] the state structure containing all
		the necessary information on what labels to put where.
		* see description in KALPANA.PRO

keywords
	wid	[INPUT] window ID for plots (ignored if device is not X)
	pid	[INPUT] if set, plots only the PIDth plot
	xsize	[INPUT] window size (goes with WID)
	ysize	[INPUT] window size (goes with WID)
	colmax	[INPUT] maximum available color (!D.N_COLORS, we need
		this hack to handle postscript plots)
	stretch	[INPUT] set to float number to stretch all y-positions
		by constant amount
		* default is 1
		* 0, etc. are ignored
	_extra	[INPUT ONLY] pass defined keywords to PLOT
		(anything except the stuff provided for in STSTR.WINDOW,
		TITLE,[XY]TITLE,[XY]STYLE,[XY]LOG,CHARSIZE,XRANGE,YRANGE)

side-effects
	makes plots

history
	vinay kashyap (SepMIM)
	added _EXTRA to PLOT (VK; AugMM)

(See /data/fubar/SCAR/pro/darshana.pro)


DATA_CHK

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

   Purpose: checks input data for type, ndimension, etc
	     (uses IDL size function results)

   Keyword Parameters:
      type -   if set, return idl data type (0,1,2..8) from size function
      ndimen - if set, return number dimensions (size(0))
      nimages - if set, return #images (1->2D, NI->3D, else 0)
      xsize - if set, return X size (size(data))(1)
      nx    - synonym for xsize
      ysize - if set, return Y size (size(data))(2)
      ny    - synonym for ysize
      orr    - if set, return value is OR of all boolean flags (def=AND)
      string/struct/undefined - if set, return true if type matches 
      scalar, vector - if set, true if data of specified variety
            
   Calling Examples:
      if (data_chk(p1,/type) eq data_chk(p2,/type)) then...
      case data_chk(data,/type) of...
      if data_chk(data,/string,/scalar) then ...
      if data_chk(data,/string,/struct,/undef,/orr)
      case data_chk(maybe_cube,/nimages) of...

   History:
      27-Apr-1993 (SLF)
      21-Mar-1994 (SLF) documentation header
      10-oct-1996 (SLF) add SCALAR (synonym for the historical mispell SCALER)
       2-oct-1997 (SLF) add NIMAGES
      15-nov-1997 (SLF) add XSIZE and YSIZE keyword and function

   Restrictions:
      some keywords are mutually exclusive - for self-documenting code 
      and reduction of code duplicataion 

(See /data/fubar/SCAR/pro/external/data_chk.pro)


DEMACS

[Previous Routine] [Next Routine] [List of Routines]
function	demacs
	a DEM editor that allows interactively "tweaking" a specified DEM

syntax
	dem=demacs(logt,dem0=dem0,logt0=logt0,norm=norm,slope=slope,$
	group=group,igroup=igroup, PLOT_KEYWORDS)

parameters
	logt	[INPUT; required] log10(Temperature [K]) at which DEM
		is to be determined

keywords
	dem0	[INPUT] initial DEM (just for guidance).
		* if size does not match LOGT0, gets stretched to suit.
		* overrides SLOPE, but not NORM
		* if max(DEM0)<100, assumed to be in log form -- i.e.,
		  plots are in "linear" form and +vity is not enforced.
	logt0	[INPUT] logT at which DEM0 are defined.  if not given,
		assumed to be LOGT.
	norm	[INPUT] if set, first element of initial DEM is set to NORM
	slope	[INPUT; default=1] if given, generates initial
		DEM=NORM*T0^(SLOPE)
		* if DEM0 is specified, SLOPE is ignored
	group	[OUTPUT] long-int array of same size as LOGT containing
		grouping information
	igroup	[OUTPUT] array of same size as GROUP, containing index
		of "representative element" of each group
	_extra	[INPUT] allows passing defined keywords (e.g., YRANGE)
		to PLOT.

restrictions
	requires X-windows, display, and mouse capability.

history
	vinay kashyap (Feb97)
	corrected log behavior, added _extra to PLOT (VK; Apr97)
	cleaned up log behavior, added keystrokes *,/,v,^,z (VK; Aug98)
	button press status now stored in !MOUSE, not !ERR (VK; Apr09)

(See /data/fubar/SCAR/pro/demacs.pro)


DESCALE_ALL

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

      This routine descales all types of spline fits into upsilons or 
      rates, i.e., it does both electron upsilons and proton rates, 
      and both 5-point and 10-point splines. In addition it can 
      simultaneously descale several temperatures at once.

 INPUTS

      TEMP     Temperature(s), K.

      SPLSTR   Structure output by read_splups.

      INDEX    Index of structure.

 OUTPUTS

      UPS      Upsilon value(s) at temperature(s) TEMP.

 EXAMPLES

      read_splups,splupsfile,splstr
      descale_all,[1.e6,2.e6],splstr,5,ups
      print,ups

 HISTORY

      Ver.1, 15-Mar-01, Peter Young
               adapted from Ken Dere's descale_ups.pro.

      Ver.2, 12-Nov-01, Peter Young
               added type 6 transitions (for protons)

(See /data/fubar/SCAR/pro/external/descale_all.pro)


DESCALE_UPS_VK

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

 PROJECT:  CHIANTI

       CHIANTI is an atomic database package for the calculation of
       continuum and emission line spectra from astrophysical plasmas. It is a 
       collaborative project involving the Naval Research Laboratory
       (Washington DC, USA), the Arcetri Observatory (Firenze, Italy), and the
       Cambridge University (United Kingdom).


 NAME:
	DESCALE_UPS_VK
	(used to be) DESCALE_UPS

 PURPOSE:

	convert from Burgess-Tully scaling spline fits to Upsilons

 CATEGORY:

	science.

 CALLING SEQUENCE:

       DESCALE_UPS,Index,Jndex,xt,upsilion, T_TYPE,C_UPS,SPLUPS

 INPUTS:

	Index:	index of lower energy level (lowest level is 1)
	Jndex:	index of upper energy level (lowest level is 1)
	xt:  scaled temperature

	T_TYPE: 2 dimensional array contain values of the transition type
	C_UPS: 2 dimensional array containing values of the Burgess and Tully
		scaling parameter c
	SPLUPS: spline fits to the scaled Upsilons

 OPTIONAL INPUTS:

	None:
	
 KEYWORD PARAMETERS:

	None:	

 OUTPUTS:

	Upsilon:  the Maxwellian averaged collision strength



 COMMON BLOCKS:

	NONE:

	;common elvlc,l1a,term,conf,ss,ll,jj,ecm,eryd,ecmth,erydth,eref
       ;common wgfa, wvl,gf,a_value
       ;common upsilon,t_type,c_ups,splups


 PROCEDURE:

	see Burgess and Tully, 1992, Astron and Astrophys, 254, 436.

 EXAMPLE:

             ;
 MODIFICATION HISTORY:
 	Written by:	Ken Dere
	March 1996:     Version 2.0
       December 1998:  Include transition type 5   (kpd)

	September 2000: Add parameters T_TYPE,C_UPS,SPLUPS and comment out
		all common blocks (Vinay Kashyap)
	THIS ROUTINE IS OBSOLETE FOR CHIANTIv4+ (VK; Jun02)

(See /data/fubar/SCAR/pro/external/descale_ups_vk.pro)


DETECT_LIMIT

[Previous Routine] [Next Routine] [List of Routines]
function	detect_limit
	compute and return the counts upper limit for
	detection of a source at a given significance,
	given the background counts.

description
	compute the cumulative significance of obtaining a specified
	number of counts given the background, and assume that a source
	would be considered detected if the counts were to exceed the
	NSIG threshold.

	see Pease, Drake, & Kashyap (2006, ApJ 636, 426) for full description.
	briefly, computes the probability that as many as D counts can be
	observed for a given background b, p(=<D|b), and thence the probability
	that a given number of counts can be obtained in an observation simply
	due to the background.  The number of counts required for a detection
	at a specified probability is the upper limit.  Note also that this
	goes only halfway towards a full upper limit (see Kashyap et al., 2008,
	AAS-HEAD, 2008.03.03) in that this produces an upper limit in counts
	space and not in intrinsic flux space.

syntax
	ul=detect_limit(bkg,nsig,asrc=asrc,abkg=abkg,bgalt=bgalt,abgalt=abgalt,$
	nsim=nsim,ulsig=ulsig,ulsim=ulsim,/gaussy,nxbin=nxbin,verbose=verbose)

parameters
	bkg	[INPUT; required] counts in the background
	nsig	[INPUT] the Gaussian-equivalent sigma at which
		to compute upper limit to detection
		* if not given, assumed to be 3

keywords
	asrc	[INPUT; default=1] area in which source counts are collected
	abkg	[INPUT; default=1] area in which background counts are collected
	bgalt	[INPUT; default=0] alternative set of background
		contamination, say from a different area of the instrument,
		or from a model, or from an extended source, etc.
		* may be an array
		* NOTE: the _same_ BGALT is appended to _all_ elements of BKG
	abgalt	[INPUT; default=asrc] area in which BGALT is "collected"
		* size must match BGALT
		* if size < size(BGALT), first element is assumed to be
		  the default
	nsim	[INPUT; default=0] number of Monte Carlo simulations to run
		to account for error in background
		* setting this results in computing the upper limit for
		  a number of realizations of BKG; the resulting 1-sigma
		  range in the value of computed upper limits is reported
		  in ULSIG, and a conservative upper limit based on
		  combining all of the simulations is returned in ULSIM[*,0]
	ulsig	[OUTPUT] the 1-sigma error on the upper limit, estimated
		by bootstrapping BKG
	ulsim	[OUTPUT] a 2D array of size (NBKG,NSIM+1) which contains
		all the simulated limits
		* ULSIM[*,0] is identical to the primary output if NSIM=0
		* for NSIM>0, ULSIM[*,0] is the conservative limit that
		  is derived from the coadded probability distributions
		  that take into account the variations in the background
	gaussy	[INPUT] if set, computes the limit corresponding to the
		significance matching the location of the NSIG-sigma
		*intercept* of a Gaussian, rather than matching the total
		area under the curve.
	nxbin	[INPUT] number of bins to use in the integration
		* the integration is carrid out over a range of
		  0..5*E(bg) or 20, whichever is greater.
		  by default, the number of bins is set by the step size,
		  which is set to 1 count,
		  -- unless E(bg) < 1, in which case a bin width of 0.05
		  is used by default
		* changing NXBIN does not change the range, but only
		  changes the bin size.
		* a hard lower limit of 20 is set -- cannot use a bin
		  width larger than 1 count
	verbose	[INPUT] controls chatter

subroutines
	LNPOISSON()
	KILROY

history
	vinay kashyap (Apr2004)
	added keyword ULSIG; changed name from PUPLIM to DETECT_LIMIT
	  (VK; May2004)
	added keyword NXBIN (VK; Sep2004)
	added keywords BGALT and ABGALT (VK; Dec2004)
	modified output behavior of ULSIM[*,0]; now BGALT can be 0
	  (VK; Mar2005)
	fixed bug for when NXBIN is set; made the numerical precision
	  problem at high NSIG explicit by making the code return -1 as
	  the UL (VK; Mar2009)

(See /data/fubar/SCAR/pro/stat/detect_limit.pro)


DID2EMIS2EM

[Previous Routine] [Next Routine] [List of Routines]
procedure	did2emis2em
	for a specified line, read in emissivities at various densities,
	compute fluxes, and invert to get emission measure estimates at
	each density.

syntax
	did2emis2em,idstr,edens,fluxes=fluxes,/deblend,DEM=DEM,logT=logT,$
	ldir=ldir,NH=NH,EMs=EMs,FXs=FXs,xtitle=xtit,ytitle=ytit,title=tit,$
	verbose=v,dWVL=dWVL,eps=eps,/incieq,mapping=mapping,chifil=chifil,$
	chidir=chidir,eqfile=eqfile,abund=abund,/noph,effar=effar,wvlar=wvlar,$
	/kev,tol=tol,fH2=fH2,He1=He1,HeII=HeII,/Fano,/wam,/bam,/mam,/Zbeda,$
	/Ibeda,Wbeda=Wbeda,/Lbeku,wform=wform,wstyle=wstyle,ziform=ziform,$
	/nuthin,/noday,/notime,/nouser,/nopack,stacol=stacol,stasiz=stasiz,$
	stathk=stathk,charsize=charsize,align=align

parameters
	idstr	[INPUT; required] structure containing ID information
		(see LINEID for description)
	edens	[I/O] array of electron densities [cm^-3]
		* default is [1e8,1e14]
		* if not specified, insufficiently specified, or otherwise
		  meaningless, uses default and overwrites input

keywords
	fluxes	[I/O] observed fluxes
		* if size does not match the number of components
		  or the number of IDs, will instead use IDSTR.(#).FLUX
		  and overwrite the input
		* see UPDATID() for details
	deblend	[INPUT] if _not_ set (which is the default), squishes multiple
		IDs of a single feature into one single flux and calculates
		only a "composite" ID.  on the other hand, if set, leaves
		the multiple IDs alone.
	DEM	[INPUT] differential emission measure to use in computing
		the fluxes
		* default is to use 1e12 [cm^-5] at each specified LOGT
	logT	[INPUT] temperatures at which DEM is defined
		* if not specified, set to 6.5, unless DEM has more elements,
		  in which case is interpolated into the 4..8 range
	ldir	[INPUT] string array of database directories to use to
		search for the emissivities
		* default is '$CHIANTI'
		* if size does not match either number of IDSTR components
		  or IDs, only the first element is used
	NH	[INPUT] H column density [cm^-2]
	EMs	[OUTPUT] array of emission measures EMS[EDEN,WVL] that
		are plotted.
		* at any given point, EMS = \int DEM[LOGT]*dLOGT,
		  unless DEM has one or two elements only, in which
		  case EMS = SUM(DEM)
		* what this implies is that the input DEM is scaled
		  at each density to match the observed flux at each
		  wavelength and this scaled DEM is represented in the
		  plot by the summed measure.  This ensures that all
		  wavelengths considered are compared over the same
		  temperature range, and the ambiguity regarding the
		  temperature of peak emissivity, etc. has been removed.
	FXs	[OUTPUT] the predicted fluxes FXS[EDEN,WVL] which are used
		to scale the EMs above.
	xtitle	[INPUT] passed to PLOT
	ytitle	[INPUT] passed to PLOT
	title	[INPUT] passed to PLOT
	verbose	[INPUT] controls chatter
	_extra	[INPUT] pass defined keyword values to subroutines:
		ID2EMIS2ID: DWVL
		RD_LIST: EPS, INCIEQ, MAPPING
		FOLD_IONEQ: CHIFIL, EQFILE
		RD_IONEQ: CHIDIR
		SQUISHEM: ABUND
		LINEFLX: ABUND, NOPH, EFFAR, WVLAR, KEV
		ARRAYEQ: TOL
		ISMTAU: fH2, He1, HeII, FANO, WAM, BAM, MAM
		IDLABEL: ZBEDA, IBEDA, WBEDA, LBEKU, WFORM, WSTYLE, ZIFORM
		STAMPLE: NUTHIN,NODAY,NOTIME,NOUSER,NOPACK,STACOL,STASIZ,STATHK
		XYOUTS: CHARSIZE,ALIGN
	n_e	[IGNORE] here only to trap boxing gloves

restrictions
	requires IDL5.3+ because of use of STRMATCH, etc.
	requires subroutines
	  BAMABS
	  CAT_LN
	  FOLD_IONEQ
	  GETABUND
	  ID2EMIS2ID
	  IDLABEL
	  INICON
	  ISMTAU
	  LAT2ARAB
	  LINEFLX
	  RDABUND
	  RD_IONEQ
	  RD_LINE
	  RD_LIST
	  READ_IONEQ
	  SQUISHEM
	  SYMB2ZION
	  SYZE
	  UPDATID
	  WHEE
	  ZION2SYMB

side-effects
	generates a plot which erases any plot that exists beforehand

history
	vinay kashyap (JanMMI; based on DID2EM)
	improved color-scale setting for 24-bit consoles (VK; FebMMI)

(See /data/fubar/SCAR/pro/did2emis2em.pro)


DISCRIMINATEMP

[Previous Routine] [Next Routine] [List of Routines]
function	discriminatemp
	an implementation of Mark Weber's scheme for determining
	the temperature discrimination ability of a given set of
	emissivity functions.  the output is a square matrix
	of the same size as the temperature grid, showing the value
	of a statistic that can be used to infer whether two
	corresponding temperatures can be distinguished.

	the technique is simple -- compute fluxes at two temperatures
	for the same emission measure, and for an assumed uncertainty,
	ask whether the two sets of fluxes differ in a statistically
	significant manner.  if they do, the two temperatures are
	distinguishable, and not if they do not.

syntax
	dtemp=disriminatemp(emis,ferr,EM0=EM0,outflx=outflx,$
	wvl=wvl,Z=Z,logT=logT,abund=abund,normark=normark,$
	verbose=verbose,$
	/noph,effar=effar,wvlar=wvlar,/ikev,metals=metals,fipbias=fipbias)

parameters
	emis	[INPUT; required] array of emissivities
		* EMIS is a 2D array with size (LOGT, WVL)
		* the units are assumed to be [1e-23 ergs cm^3/s]
		  for anything else (e.g., for solar work), put the
		  difference into EM0 and be sure to set the keyword
		  NOPH=1, because it gets pushed into LINEFLX()
	ferr	[INPUT] the assumed uncertainties on the lines
		* if not given, taken to be 0.1 of the computed
		  fluxes for all lines
		* if scalar, then
		    if >0 and <1, taken to be that fraction of the
		    computed fluxes for all lines
		    if >1 and <100, taken to be that percentage of
		    the computed fluxes for all lines
		    if >100, the reciprocal is taken to be the
		    fraction of the computed fluxes for all lines
		    if <0, the abs value is taken to be a constant
		    absolute uncertainty for all lines
		* if vector, each individual value is used as given,
		  with the same condition on each as for the scalar
		  case
		* e.g., if there are 4 lines, and FERR=[-10,0.3,50],
		  after the 4 fluxes are computed, the corresponding
		  errors are set to [10.,0.3*F[1],0.5*F[2],0.1*F[3]]
		* the best way to set reasonable errors is to run
		  this program once, extract the computed fluxes
		  using keyword OUTFLX, figure out the appropriate
		  errors, and then feed it back into another run

keywords
	EM0	[INPUT] the emission measure to use
		* default is 1d14 cm^-5, fwiw
	outflx	[OUTPUT] the fluxes calculated for each line for each
		temperature, is an array of size (LOGT,WVL), same as EMIS
	wvl	[INPUT] line wavelengths for which EMIS is given
		* used only if keyword NOPH is _not_ set (i.e.,
		  in the conversion of [erg/...] to [ph/...])
		  and if size matches the 2nd dimension of EMIS
	Z	[INPUT] atomic numbers of elements contributing
		to EMIS
		* used only if size matches 2nd dimension of EMIS,
		  and is used to multiply EMIS with the appropriate
		  abundance
		* if not given, assumed to be 1 (i.e., H), which
		  is essentially a way to ignore ABUND
	logT	[INPUT] log_10(Temperature [K]) at which EMIS are given
		* unused
	abund	[I/O] element abundances
		* if size smaller than 30, calls GETABUND() and resets
		  to use Anders & Grevesse
	normark	[INPUT] a normalization factor, usually set to the
		maximum number of filters or lines that can be used,
		and whose squared reciprocal divided into the output --
		Mark Weber uses this to "normalize" the results across
		different filter choices
		* hard minimum value is 1, also the default
		* if this is set, the diagonal elements of the output,
		  which are identically zero, are reset to the mean of
		  the nearest neighbors
		* if vector, only the first element is used and all the
		  extra elements are ignored
	verbose	[INPUT] controls chatter

	_extra	[INPUT ONLY] pass defined variables to subroutines
		LINEFLX : /NOPH, /IKEV, EFFAR, WVLAR
		GETABUND : METALS, FIPBIAS

description
	Weber et al., 2008, SPD?

history
	vinay kashyap (2009mar)

(See /data/fubar/SCAR/pro/discriminatemp.pro)


DORREN

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

 computes spot modulated stellar light curve using Dorren(1987)

syntax 
      curve =  x, A, f, pder,ldstr=ldstr,ldspt=ldspt,rdns=rdns,$
      photT=photT,spotT=spotT,wvl=wvl
 
parameters 
       x   [INPUT;required] absissca points at which to compute spot
           model. These are angular displacements with respect to the 
           initial spot longitude specified in A, in units of degrees. 
       A   [INPUT;required] spot parameters for dorrens model in
                            radians where: 
                            a(0) = stellar inclination to LOS
                            a(1) = spot latitude 
                            a(2) = spot size 
                            a(3) = initial spot longitude 
       pder[OUTPUT]         partial derivative with respect to each 
                            parameter in A 
keywords 
       ldstr [INPUT] limb-darkening coefficient for star 
                          default = 0.32 Van Hamme(1994) 
       ldspt [INPUT] limb-darkening coefficient for spot (umbra) 
       rdns  [INPUT] set this parameter if spot parameters and absissca are input 
                     in radians rather than degrees
       photT [INPUT] photospheric temperature in degrees Kelvin
       spotT [INPUT] spot temperature in degrees Kelvin 
       wvl   [INPUT] wavelength in nanometers
subroutines 
       MOD
       
history
       liwei lin (Sep 03) better documentation/functionality than
                          mod.pro. switch to modular
                 (Jul 06) removed loop over longitudes and add pder
                 (Aug 06) BUGFIX: note that T should be defined as: 
                           Pi - ATAN((-SIN(h(tmp)))*(TAN(b1(tmp)))) when B1>=Pi/2           
                           ATAN((SIN(h(tmp)))*(TAN(b1(tmp)))) when B1<Pi/2 
                          to avoid dicontinuities. This differs from Dorren (1987)
                          formalism only in the '=' sign placement 

(See /data/fubar/SCAR/pro/timing/dorren.pro)


DOVE_CICLO

[Previous Routine] [Next Routine] [List of Routines]
function	dove_ciclo
	this function acts as a wrapper to all the morphological
	operations that are used to extract pixels that define a loop
	from an image of the solar corona

	the general workflow is:
	- [CONVOL] - enhance contrast by subtracting background
	- [MORFO_ROTTANGOLI] open with rectangular structure element
	- [MORPH_CLOSE] close with small square kernel
	- [CONVOL] enhance contrast again by subtracting background
	- [MORFO_SOGLIA] threshold to selectively enhance structures
	- [MORPH_CLOSE] close the image again
	- [MORFO_SEGMENTO] group contiguous pixels into region blobs
	  and throw out regions deemed too small
	- [ROI_SELEZIONI] interactively select some blobs for further study
	- [MORFO_SCHELETRO] create a skeleton for these blobs
	- [MORFO_POTARE] prune the skeleton to make a cleaner image
	- [] extract the pixels that form the pruned skeleton and
	  convert them to heliographic coordinates

	keywords control whether any of the calls to the subroutines
	should be skipped or repeated.  keywords also set up the input
	parameters to the subroutines.

syntax
	oimg=dove_ciclo(inpimg,$
	/xbgdat,icell=icell,$
	/xrect,xsize=xsize,ysize=ysize,angle=angle,gray=gray,/readd,/reuse,$
	/xrclose,$
	/xbgsub,jcell=jcell,$
	/xthresh,thrthr=thrthr,nsigma=nsigma,mimg=mimg,gamma=gamma,$
		centrale=centrale,bitlev=bitlev,/zeromin,$
	/xtclose,$
	/xblob,blbthr=blbthr,areas=areas,$
		subidx=subidx,/hardcut,deepimg=deepimg,$
	/xroi,pixroi=pixroi,roithr=roithr,jitter=jitter,/hadrian,$
	/xskel,skthr=skthr,rmin=rmin,$
	/xprune,minpix=minpix,$
	outx=outx,outy=outy,sunrad=sunrad,pixsiz=pixsiz,$
	offsetx=offsetx,offsety=offsety,suncenx=suncenx,sunceny=sunceny,$
	loopsav=loopsav, verbose=verbose)

parameters
	inpimg	[INPUT; required] image of the corona

keywords	For keywords with names beginning with "X", when set,
		the corresponding call to the subroutine is skipped.
		But if that keyword is set to a negative number -N,
		the subroutine is called N times in sequence (unless
		otherwise noted below).

	xbgdat	[INPUT] if set, skips initial background subtraction
	icell	[INPUT; default=1] defines the size of the cell to subtract
		background - the "source" is measured in a square of size
		2*ICELL+1 and the "background" in a surrounding layer of 1pix
	xrect	[INPUT] if set, skips morphological open with rectangular
		structure element
	xsize	[INPUT; default=1] width of the structure element
	ysize	[INPUT; default=10] height of the structure element
	angle	[INPUT; default=findgen(36)*5] angle of tilt of the rectangle
		defined by (XSIZE,YSIZE) in [degrees]
	xrclose	[INPUT] if set, skips morphological close apres open
	xbgsub	[INPUT] if set, skips background subtraction of modified image
	jcell	[INPUT; default=ICELL] defines size of cell to subtract
		background
	xthresh	[INPUT] if set, skips image thresholding
	thrthr	[OUTPUT] value used if histogram-threshold is applied
	nsigma	[INPUT] if given, sets the threshold at mean+NSIGMA*stddev
		* default is 1
		* if mean+NSIGMA*stddev < 0, this is not applied
	mimg	[OUTPUT] the median threshold image, constructed if
		CENTRALE is set
	xtclose	[INPUT] if set, skips morphological close apres thresholding
	xblob	[INPUT] if set, skips grouping the image into distinct regions
		* if set to -ve number, gets automatically unset
	areas	[OUTPUT] number of pixels in each labeled region
	arclev	[INPUT; default=0.68] fraction of the area of the largest
		blob as the threshold below which to discard blobs
	deepimg	[OUTPUT] an image that depicts the depth at which a
		particular pixel was added to a blob
	blbthr	[INPUT; default=0] threshold value at which to convert
		grouped image to bitmap
	xroi	[INPUT] if set, skips selecting a subset of regions
		* if set to -ve number, gets automatically unset
	pixroi	[INPUT] if set, assumed to be a set of pixels around
		which to pick out the region of interest non-interactively
	roithr	[INPUT; default=0] threshold value at which to ignore pixels
	xskel	[INPUT] if set, skips making skeletons of regions
		* if set to -ve number, gets automatically unset
	rmin	[INPUT; default=1] radius of circle that acts as
		structure element
	skthr	[INPUT; default=0] threshold to filter region
	xprune	[INPUT] if set, skips pruning skeletons
		* if set to -ve number, gets automatically unset
	minpix	[INPUT; default=4] number of pixels above which a given
		branch must be kept while pruning
	outx	[OUTPUT] the x-pixel indices of the pruned points
	outy	[OUTPUT] the y-pixel indices of the pruned points
		* if SUNRAD is set, then floating point values defining
		  the locations in heliospheric coordinates are returned
	sunrad	[INPUT] radius of the Sun as seen from the spacecraft,
		in [arcsec]
		* if this is set, then OUTX and OUTY are transformed
		  to heliospheric coordinate system
		* if set to 1, assumed to be (RSun/AU)*(180/!pi)*3600
	pixsiz	[INPUT; default=0.5] pixel size, in [arcsec]
	offsetx	[INPUT; default=0] offset to be applied to OUTX
		to bring them in line with SUNCENX
	offsety	[INPUT; default=0] offset to be applied to OUTY
		to bring them in line with SUNCENY
	suncenx	[INPUT; default=0] the X coordinate distance of the
		center of INPIMG from Sun center in [arcsec]
	sunceny	[INPUT; default=0] the Y coordinate distance of the
		center of INPIMG from Sun center in [arcsec]
	verbose	[INPUT] controls chatter
	loopsav	[INPUT] if set to a filename, saves all the
		intermediate arrays in the named IDL save file
	_extra	[INPUT ONLY] pass defined keywords to subroutines
		MORFO_ROTTANGOLI: GRAY, READD, REUSE
		MORFO_SOGLIA: GAMMA, CENTRALE, BITLEV, ZEROMIN
		MORFO_SEGMENTO: SUBIDX, HARDCUT
		ROI_SELEZIONI: JITTER, HADRIAN

subroutines
	MORFO_ROTTANGOLI
	MORFO_SOGLIA [GMASCL,ERROR_MESSAGE,PATH_SEP,SCALE_VECTOR,CONVERT_TO_TYPE,FPUFIX]
	MORFO_SEGMENTO
	ROI_SELEZIONI
	MORFO_SCHELETRO
	MORFO_POTARE
	INICON
	KILROY

history
	vinay kashyap (May2007)

(See /data/fubar/SCAR/pro/solar/dove_ciclo.pro)


DRAKOPY

[Previous Routine] [Next Routine] [List of Routines]
procedure	drakopy
	set up the environment to make plots per individual preferences

syntax
	drakopy,milieu,/HELP,/UNDO,MAGNIFY=MAGNIFY,VERBOSE=VERBOSE

parameters
	milieu	[INPUT] string specifying what sort of environment to set to.
		accepted values are:
		-- 'jeremy'
		-- 'olivia'
		-- 'jjd' (jeremy old preferences)
		-- 'drake' (jeremy older preferences)
		-- 'vinay' (different depending device at call time)
		-- 'poster'
		-- 'original'

keywords
	help	[INPUT] if set, prints out a somewhat verbose help
	undo	[INPUT] if set, restores original state
	verbose	[INPUT] controls chatter level
	magnify	[INPUT] scale all the variables by this factor
	_extra	[JUNK] here only to prevent crashing the program

commons
	drakopy	{old_P, old_X, old_Y, old_Z}

description
	sets the !P, !X, !Y, and !Z variables to special and specific values.
	stores the old values in a common block for later access.

example
	set_plot,'ps' & device,file='/tmp/test_drakopy.ps'
	  plot,findgen(10),title='MILIEU=Original'
	  drakopy,'jeremy' & plot,findgen(10),title='MILIEU=Jeremy'
	  drakopy,'olivia' & plot,findgen(10),title='MILIEU=Olivia'
	  drakopy,'original' & plot,findgen(10),title='MILIEU=Original'
	  drakopy,/undo & plot,findgen(10),title='MILIEU=previous (Olivia)'
	device,/close & set_plot,'x'

history
	vinay kashyap (SepMM)
	added option "drake" (VK; Aug01)
	added option "jjd"; added keyword MAGNIFY (VK; Feb02)
	added option "vinay" (VK; May03)
	added option "poster" (VK; Jul03)
	told the code that "poster" is a valid option (VK; Sep03)

(See /data/fubar/SCAR/pro/misc/drakopy.pro)


DRAT

[Previous Routine] [Next Routine] [List of Routines]
function	drat
	return the ratio of fluxes in one line relative to another line
	for a variety of densities

syntax
	frat=drat(line1,line2,edens,DEM,logT,fx1=fx1,fx2=fx2,$
	mapping=mapping,chifil=chifil,chidir=chidir,eqfile=eqfile,$
	abund=abund,/noph,effar=effar,wvlar=wvlar,NH=NH,fH2=fH2,$
	He1=He1,HeII=HeII,/Fano,dbdir=dbdir,sep=sep,prefix=prefix)

parameters
	line1	[INPUT; required] string describing the line/wavelength-range
		that defines the numerator
	line2	[INPUT; required] string describing the line/wavelength-range
		that defines the denominator
		* LINE1 and LINE2 must be in the format used by RD_LIST, i.e.,
		  	Z ION <sep> WAVE <sep> DBDIR <sep> DESCRIPTION
		  and WAVE = "WVL"/"WVL +- dW"/"WMIN,WMAX"/"WMIN-WMAX"
	edens	[INPUT; required] electron densities at which to compute
		the flux ratios
	DEM	[INPUT; required] differential emission measure to use in
		computing the fluxes
	logT	[INPUT; required] temperatures at which DEM is defined
		* size must match that of DEM

keywords
	fx1	[OUTPUT] the fluxes due to line 1 at each EDENS
	fx2	[OUTPUT] the fluxes due to line 2 at each EDENS
	_extra	[INPUT ONLY] pass defined keywords to subroutines
		RD_LIST: MAPPING,DBDIR,SEP,PREFIX
		FOLD_IONEQ: CHIFIL,EQFILE
		RD_IONEQ: CHIDIR
		LINEFLX: ABUND,NOPH,EFFAR,WVLAR
		ISMTAU: NH,fH2,He1,HeII,FANO,BAM
		BAMABS: ABUND

subroutines
	RD_LIST
	RD_LINE
	FOLD_IONEQ
	LINEFLX
	ISMTAU
	BAMABS
	CAT_LN

history
	vinay kashyap (MarMM)

(See /data/fubar/SCAR/pro/drat.pro)


DUMMYID

[Previous Routine] [Next Routine] [List of Routines]
function  dummyid
	Convert a RD_LINE() style emissivity structure into a dummy
	ID structure such as that generated by LINEID()

syntax
	idstr=dummyid(linstr,DEM=DEM,/temp,abund=abund,/noph,$
	nhne=nhne,effar=effar,wvlar=wvlar,/ikeV,/noabund)

parameters 
	linstr	[INPUT; required] RD_LINE() or RD_LIST() style line
		emissivity structure

keywords
	_extra	[INPUT ONLY] use this to pass defined keywords to subroutines
		LINEFLX: DEM,ABUND,EFFAR,WVLAR,NOABUND,NHNE,NOPH,TEMP,IKEV
              
subroutines 
	LINEFLX() 
history 
	liwei lin (Feb06)  lift parameter check from cat_ln() 
	cleaned up a bit (VK; Feb06)

(See /data/fubar/SCAR/pro/dummyid.pro)


EG_DEM_FLX2EM

[Previous Routine] [Next Routine] [List of Routines]
SERTS_DEM_FLX2EM.PRO

program to call DEM_FLX2EM for SERTS data
				-vinay kashyap

(See /data/fubar/SCAR/pro/esempio/eg_dem_flx2em.pro)


EG_FIDGIT

[Previous Routine] [Next Routine] [List of Routines]
EG_FIDGIT.PRO

example program for calling FIDGIT
							vinay kashyap

(See /data/fubar/SCAR/pro/esempio/eg_fidgit.pro)


EG_FITLINES

[Previous Routine] [Next Routine] [List of Routines]
EG_FITLINES
	example program to exercize FITLINES.PRO

usage:
	.run fitlines_event fitlines eg_fitlines

vinay kashyap

(See /data/fubar/SCAR/pro/esempio/eg_fitlines.pro)


EG_FIT_LEVMAR

[Previous Routine] [Next Routine] [List of Routines]
EG_FIT_LEVMAR.PRO
	program to road test FIT_LEVMAR

usage:
	.run adjustie lmcoeff levmarq fit_levmar eg_fit_levmar

vinay k

(See /data/fubar/SCAR/pro/esempio/eg_fit_levmar.pro)


EG_FLUX_TO_EM

[Previous Routine] [Next Routine] [List of Routines]
EG_FLUX_TO_EM.PRO
	example calling program for FLUX_TO_EM.

	start from a set of ID'd lines whose fluxes have
	been measured, and make EMs appropriate for the
	given IDs.

	1. read in ID structure from $SCARDIR/pro/esempio/eg_flux_to_em.sav
	2. extract the line emissivities for each ID'd feature
	   (and sum them up if multiply ID'd)
	3. extract the fluxes too
	4. call FLUX_TO_EM
	5. make plots showing the output

vinay kashyap (MMJul)

(See /data/fubar/SCAR/pro/esempio/eg_flux_to_em.pro)


EG_FLX2EM

[Previous Routine] [Next Routine] [List of Routines]
EG_FLX2EM.PRO

example program to call FLX2EM
				-vinay kashyap

(See /data/fubar/SCAR/pro/esempio/eg_flx2em.pro)


EG_HAARLINE

[Previous Routine] [Next Routine] [List of Routines]
script	eg_haarline
	a script to demonstrate the use of the wavelet based
	line detection program HAARLINE

usage
	pha2fil='/data/snafu/kashyap/Capella/o1248_pha2.fits'
	pharow=1
	.run eg_haarline

vinay kashyap (Dec'02)

(See /data/fubar/SCAR/pro/esempio/eg_haarline.pro)


EG_IDSTR

[Previous Routine] [Next Routine] [List of Routines]
EG_IDSTR.PRO
	an example program that extracts information out of an ID structure

	requires an input ID structure in the variable IN_IDSTR
	extracts all the ID'd wavelengths, atomic numbers, ionic states,
	and places them in arrays named OUT_<var>
	look in OUT_IDX for a pointer to the original component

	TBD: need to be cleverer about labels and notes.

subroutines
	ZION2SYMB

vinay kashyap (AugMM)

(See /data/fubar/SCAR/pro/esempio/eg_idstr.pro)


EG_LINEID

[Previous Routine] [Next Routine] [List of Routines]
EG_LINEID.PRO

example program to call LINEID
				-vinay kashyap

(See /data/fubar/SCAR/pro/esempio/eg_lineid.pro)


EG_LINESPEC

[Previous Routine] [Next Routine] [List of Routines]
EG_LINESPEC.PRO

example program for calling LINESPEC
							vinay kashyap

(See /data/fubar/SCAR/pro/esempio/eg_linespec.pro)


EG_LINESPEC_EM

[Previous Routine] [Next Routine] [List of Routines]
EG_LINESPEC_EM.PRO

example program for calling LINESPEC_EM
							vinay kashyap

(See /data/fubar/SCAR/pro/esempio/eg_linespec_em.pro)


EG_LOOPYLOT

[Previous Routine] [Next Routine] [List of Routines]
eg_loopylot
	make plots of T and EM distributions using the output
	of MCMC_DEM() for when the keyword LOOPY is set

	the standard routine used to munge the output of MCMC_DEM(),
	MCMC_PLOT, is not of much use when the LOOPY option is used.
	this example routine shows which variables are of interest
	and how they can be manipulated to get useful numbers out
	of the output

usage
	mcmcsav='mcmc.save'
	;set PSROOT to make hardcopy plots
	;set NSMIN to avoid checking SIMPRB
	.run eg_loopylot

	NOTE:  SIMPRB are the probabilities at each point of the chain.
	If a trend of any sort is discernible at the beginning parts,
	do not include that part of the chain.  If there is a trend in
	the later parts, do not use this chain: it hasn't converged.

history
	vinay k (jun2005)
	now force contour axes arrays to match size of contour array
	  (VK; apr2006)

(See /data/fubar/SCAR/pro/esempio/eg_loopylot.pro)


EG_LSD_SHOW

[Previous Routine] [Next Routine] [List of Routines]
EG_LSD_SHOW.PRO

	example program to find density sensitive lines in given wavelength
	range with LSD.PRO and display it with SHOW_LINE.PRO

vinay kashyap

(See /data/fubar/SCAR/pro/esempio/eg_lsd_show.pro)


EG_MCMC_CHAIN

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

example program to call MCMC_CHAIN

vinay kashyap (Aug2008)

(See /data/fubar/SCAR/pro/esempio/eg_mcmc_chain.pro)


EG_MCMC_DEM

[Previous Routine] [Next Routine] [List of Routines]
EG_MCMC_DEM
	create an arbitrary set of line fluxes from an arbitrary DEM
	and see if we can get back the DEM

(See /data/fubar/SCAR/pro/esempio/eg_mcmc_dem.pro)


EG_MERGE_LINE

[Previous Routine] [Next Routine] [List of Routines]
EG_MERGE_LINE.PRO

example program to call MERGE_LINE
				-vinay kashyap

(See /data/fubar/SCAR/pro/esempio/eg_merge_line.pro)


EG_POTAVE

[Previous Routine] [Next Routine] [List of Routines]
EG_POTAVE.PRO
	example program to call POTAVE

vinay kashyap (Jun97)

(See /data/fubar/SCAR/pro/esempio/eg_potave.pro)


EG_RAM_SPEC

[Previous Routine] [Next Routine] [List of Routines]
eg_ram_spec.pro
	make a spectrum in the 2-200 AA region (for RAM, which is
	supposed to have a calorimeter as a detector) with a resolution
	of 2 eV

usage
	ldbdir='$CHIANTI' & verbose=5 & abref='grevesse et al'
	edens=1e9 & NH=1e10 & betap=2.5
	outfil='/tmp/ram_spec.save'
	.run eg_ram_spec

vinay kashyap (28may02; Ed Deluca wanted it)

(See /data/fubar/SCAR/pro/esempio/eg_ram_spec.pro)


EG_RD_LIST

[Previous Routine] [Next Routine] [List of Routines]
EG_RD_LIST.PRO
	example program to exercise RD_LIST.PRO and CAT_LN.PRO

vinay k

(See /data/fubar/SCAR/pro/esempio/eg_rd_list.pro)


EG_STARFLUX

[Previous Routine] [Next Routine] [List of Routines]
EG_STARFLUX.PRO
	example program to call STARFLUX

vinay kashyap (1999May)

(See /data/fubar/SCAR/pro/esempio/eg_starflux.pro)


EG_TRACESPEC

[Previous Routine] [Next Routine] [List of Routines]
EG_TRACESPEC.PRO

example program for calling LINESPEC for TRACE data
							vinay kashyap

(See /data/fubar/SCAR/pro/esempio/eg_tracespec.pro)


EQT_INTERVAL

[Previous Routine] [Next Routine] [List of Routines]
function	eqt_interval
	computes and returns the double-sided equal-tail interval
	[lower_bound,upper_bound] at a specified confidence level.
	interval includes the central mass of the probability
	distribution unless explicitly required otherwise.

syntax
	hpd=eqt_interval(f,x,/fsample,clev=clev,pdfnorm=pdfnorm,$
	xaround=xaround,verbose=verbose)

parameters
	f	[INPUT; required] the array for which the confidence interval
		must be computed
		* assumed to be a density function unless FSAMPLE is set
	x	[INPUT; optional] abscissae values
		* if not given, and F is a density function, then taken
		  to be the array indices
		* ignored if FSAMPLE is set
		* if N(X).GT.1 but N(X).NE.N(F), X is ignored and
		  FSAMPLE is set automatically

keywords
	fsample	[INPUT] if set, assumes that F is a set of samples from a
		density function, as opposed to being the density function
		itself
	clev	[INPUT] confidence level at which to compute the intervals
		* default is 0.68
		* if < 0, abs(CLEV) is used
		* if > 1 and < 100, then assumed to be given as a percentage
		* if > 100, then 1-1/CLEV is used
	pdfnorm	[INPUT] if set, forces F to integrate to abs(PDFNORM)
		* if explicitly set to 0, does not normalize F at all
		* if not set, normalizes to 1
		* ignored if FSAMPLE is set
		* WARNING: do not use this keyword unless you know
		  what you are doing
	xaround	[INPUT] by default, the central part of the distribution
		is used, i.e., an equal area is left out on both ends.  if
		this keyword is defined, a fraction CLEV/2 of the area is
		used on either side of XAROUND.
		* if F is a sample, XAROUND must be in the same units as F
		* you can return single-sided intervals by setting XAROUND
		  to min(X) or max(X) (min/max of F if sample)
		* if not set, XAROUND is set to the median
	verbose	[INPUT] controls chatter
	_extra	[INPUT ONLY] pass defined keywords to subroutines

example
	for i=1,20 do print,eqt_interval(randomn(seed,10000L)*i,/fsample)

history
	vinay kashyap (Apr2006)

(See /data/fubar/SCAR/pro/stat/eqt_interval.pro)


ERORS

[Previous Routine] [Next Routine] [List of Routines]
procedure	erors
	compute asymmetric error bars on fit parameters by projecting the
	chi-sq surface onto each parameter axis.  what this means is that
	for each non-frozen parameter, step through a range of values of
	the parameter, finding the best-fit chi-square calculated by fitting
	the rest of the parameters, and report that range where the chi-square
	increases by a set amount from the minimum.

	this program tries to be a wee bit clever by starting from the
	best-fit value and then stumbling about on either side until
	the chi-sq goes above the mark; the length of the strides change
	according to the projected location of said mark.

syntax
	erors,x,y,a,erru,errl,ysig=ysig,freeze=freeze,dchi=dchi,$
	  dchi=dchi,algo=algo,maxstep=maxstep,verbose=verbose,$
	  erra=erra,yfunc=yfunc,$
	  itmax=itmax,chithr=chithr,/dumb, jumpup=jumpup,jumpdn=jumpdn,$
	  svdthr=svdthr,funcs=funcs, function_name=function_name,$
	  type=type, missing=missing,/fwhm,/norm,betap=betap, /poisson

parameters
	x	[INPUT; required] data points
	y	[INPUT; required] Y(X)
		* sizes of X and Y must match
	a	[I/O; required] parameters for user-supplied function
		* on input, these are assumed to be initial guesses
		* on output, these contain the best-fit values
	erru	[OUTPUT; required] upper limits of confidence range interval
	errl	[OUTPUT] lower limits of confidence range interval
		* if ERRL is not specified on input, ERRU will contain the
		  average value of the upper and lower >>deviations<<.

keywords
	ysig	[INPUT] standard deviations on Y
		* default=sqrt(abs(Y)+0.75)+1
		* if single element, then sig(Y[*])=YSIG(0)
		* if -ve, taken to be the fractional error
	freeze	[INPUT] freeze numbered parameters (index starts from 0!)
	dchi	[INPUT] how big a change in chi-square to look for?
		* default is 2.7 (corresponding to 90% CL)
	algo	[INPUT] fitting algorithm
		* only the following are implemented:
		-- LevMarq+SVD (default; calls FIT_LEVMAR)
		-- IDL-Curvefit (calls CURVE_FIT)
	maxstep	[INPUT] maximum number of steps to take before giving up
		on actually finding the bounds
		* default is 100
	verbose	[INPUT] verbosity level
	erra	[OUTPUT] formal "curvature" errors on the best-fit parameters
	yfunc	[OUTPUT] best-fit Y(X;A)
	_extra	[INPUT] pass defined variables to subroutines:-
		FIT_LEVMAR: ITMAX, CHITHR, DUMB
		ADJUSTIE: TIES, VNAME
		LEVMARQ: JUMPUP, JUMPDN, SVDTHR
		LMCOEFF: FUNCS, POISSON
		CURVE_FIT: FUNCTION_NAME
		note:-	FUNCS and FUNCTION_NAME refer to name of
			user-defined function that takes as input X
			and A, and returns YMODEL(X;A), and the
			partial derivatives of the model function
			wrt A.  Any function that was written to work
			with CURVEFIT or GHRS' WFIT will do.
			The default for FIT_LEVMAR is X3MODEL.
		MK_3MODEL: TYPE
		MK_GAUSS: MISSING, FWHM, NORM
		MK_LORENTZ: BETAP, MISSING, NORM

history
	vinay kashyap (MM.I) (yes, I _do_ know how to spell "error")
	added call to ADJUSTIE to handle constraints on ERRU,ERRL (VK; FebMM)
	what if adjusted ERRA becomes 0? (VK; MarMM)
	allowed halting with either "q" or "x" (VK; SepMM)
	force extra iteration after "r"; increased wait time (VK; JanMMI)
	added confirmation check for too many thawed params (VK; FebMMI)
	interpol was crashing because it was getting only 1 element
	  arrays; now correctly updates all parameters if better fit is found
	  (VK; Aug01)
	made various bug fixes that was causing program to go bonkers for
	  some special cases, such as small fluxes (VK; Apr02)
	added hooks into MPFIT (Liwei Lin/VK; Oct02)
	bug correction re VERBOSE (LL; Apr03)
	bug correction, first step was failing sometimes when input A were
	  integers (VK; Mar08)

(See /data/fubar/SCAR/pro/erors.pro)


ERROR_MESSAGE

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

 PURPOSE:

    The purpose of this function  is to have a device-independent
    error messaging function. The error message is reported
    to the user by using DIALOG_MESSAGE if widgets are
    supported and MESSAGE otherwise.

    In general, the ERROR_MESSAGE function is not called directly.
    Rather, it is used in a CATCH error handler. Errors are thrown
    to ERROR_MESSAGE with the MESSAGE command. A typical CATCH error
    handler is shown below.

       Catch, theError
       IF theError NE 0 THEN BEGIN
          Catch, /Cancel
          ok = Error_Message()
          RETURN
       ENDIF

    Error messages would get into the ERROR_MESSAGE function by
    throwing an error with the MESSAGE command, like this:

       IF test NE 1 THEN Message, 'The test failed.'

 AUTHOR:

   FANNING SOFTWARE CONSULTING
   David Fanning, Ph.D.
   1645 Sheely Drive
   Fort Collins, CO 80526 USA
   Phone: 970-221-0438
   E-mail: davidf@dfanning.com
   Coyote's Guide to IDL Programming: http://www.dfanning.com/

 CATEGORY:

    Utility.

 CALLING SEQUENCE:

    ok = Error_Message(the_Error_Message)

 INPUTS:

    the_Error_Message: This is a string argument containing the error
       message you want reported. If undefined, this variable is set
       to the string in the !Error_State.Msg system variable.

 KEYWORDS:

    ERROR: Set this keyword to cause Dialog_Message to use the ERROR
       reporting dialog. Note that a bug in IDL causes the ERROR dialog
       to be used whether this keyword is set to 0 or 1!

    INFORMATIONAL: Set this keyword to cause Dialog_Message to use the
       INFORMATION dialog instead of the WARNING dialog. Note that a bug
       in IDL causes the ERROR dialog to be used if this keyword is set to 0!

    TITLE: Set this keyword to the title of the DIALOG_MESSAGE window. By
       default the keyword is set to 'System Error' unless !ERROR_STATE.NAME
       equals "IDL_M_USER_ERR", in which case it is set to "Trapped Error'.

    TRACEBACK: Setting this keyword results in an error traceback
       being printed to standard output with the PRINT command. Set to
       1 (ON) by default. Use TRACEBACK=0 to turn this functionality off.

 OUTPUTS:

    Currently the only output from the function is the string "OK".

 RESTRICTIONS:

    The WARNING Dialog_Message dialog is used by default.

 EXAMPLE:

    To handle an undefined variable error:

    IF N_Elements(variable) EQ 0 THEN $
       ok = Error_Message('Variable is undefined')

 MODIFICATION HISTORY:

    Written by: David W. Fanning, 27 April 1999.
    Added the calling routine's name in the message and NoName keyword. 31 Jan 2000. DWF.
    Added _Extra keyword. 10 February 2000. DWF.
    Forgot to add _Extra everywhere. Fixed for MAIN errors. 8 AUG 2000. DWF.
    Adding call routine's name to Traceback Report. 8 AUG 2000. DWF.
    Added ERROR, INFORMATIONAL, and TITLE keywords. 19 SEP 2002. DWF.
    Removed the requirement that you use the NONAME keyword with the MESSAGE
      command when generating user-trapped errors. 19 SEP 2002. DWF.
    Added distinctions between trapped errors (errors generated with the
      MESSAGE command) and IDL system errors. Note that if you call ERROR_MESSAGE
      directly, then the state of the !ERROR_STATE.NAME variable is set
      to the *last* error generated. It is better to access ERROR_MESSAGE
      indirectly in a Catch error handler from the MESSAGE command. 19 SEP 2002. DWF.
    Change on 19 SEP 2002 to eliminate NONAME requirement did not apply to object methods.
      Fixed program to also handle messages from object methods. 30 JULY 2003. DWF.
    Removed obsolete STR_SEP and replaced with STRSPLIT. 27 Oct 2004. DWF.
    Made a traceback the default case without setting TRACEBACK keyword. 19 Nov 2004. DWF.

(See /data/fubar/SCAR/pro/external/error_message.pro)


EUVE_DS

[Previous Routine] [Next Routine] [List of Routines]
procedure	EUVE_DS
	reads in effective area curves for the Extreme Ultra-Violet
	Explorer's Deep Survey instrument

usage
	euve_ds,area,wvl,ardb=ardb,/help

parameters
	area	[OUTPUT] effective areas [cm^2]
	wvl	[OUTPUT] wavelengths at which area is defined [Ang]

keywords
	ardb	[INPUT] analysis reference data base directory,
		in which to look for instrument calibration data
		[default: /data/fubar/SCAR/ardb/]
	help	[INPUT] if set, prints usage and exits
	_extra	[JUNK] here only to prevent crashing the program

commons
	euve_ds	{dsea, ds}

restrictions
	* will crash if ARDB is incorrectly set or if ds_ea_quad1.FITS file
	  is not present in ARDB
	* requires IDLASTRO library
	* requires SETSYSVAL

history
	vinay kashyap (Jul97)
	changed CALDIR default (VK; Nov98)
	added keyword HELP (VK; MayMM)
	changed CALDIR to ARDB (VK; DecMM)
	now stores in common regardless, and takes ARDB default from !ARDB
	  added call to SETSYSVAL (VK; Sep01)

(See /data/fubar/SCAR/pro/specific/euve_ds.pro)


EUVE_LW

[Previous Routine] [Next Routine] [List of Routines]
procedure	EUVE_LW
	reads in effective area curves for the Extreme Ultra-Violet
	Explorer's Long-Wavlength spectrometer

usage
	euve_lw,area,wvl,order=order,ardb=ardb,/help

parameters
	area	[OUTPUT] effective areas [cm^2]
	wvl	[OUTPUT] wavelengths at which area is defined [Ang]

keywords
	order	[I/O] if input is not a vector, then returns only the
		effective area for the specified order in AREA(WVL).
		otherwise, on output is an array specifying the
		spectrographic order at which each element in
		AREA(WVL) is defined.
		* if not specified, assumes ORDER=1
	ardb	[INPUT] analysis reference data base directory,
		in which to look for instrument calibration data
		[default: /data/fubar/SCAR/ardb/]
	_extra	[JUNK] here only to prevent crashing the program

commons
       euve_lw	{lwea, lw, lword}

restrictions
	* will crash if ARDB is incorrectly set or if lw_ea.FITS file
	  is not present in ARDB
	* requires IDLASTRO library
	* requires SETSYSVAL

history
	vinay kashyap (Jan97)
	changed CALDIR default (VK; Nov98)
	added keyword HELP (VK; MayMM)
	changed CALDIR to ARDB (VK; DecMM)
	now stores in common regardless, and takes ARDB default from !ARDB;
	  added call to SETSYSVAL (VK; Sep01)

(See /data/fubar/SCAR/pro/specific/euve_lw.pro)


EUVE_MW

[Previous Routine] [Next Routine] [List of Routines]
procedure	EUVE_MW
	reads in effective area curves for the Extreme Ultra-Violet
	Explorer's Medium-Wavlength spectrometer

usage
	euve_mw,area,wvl,order=order,ardb=ardb,/help

parameters
	area	[OUTPUT] effective areas [cm^2]
	wvl	[OUTPUT] wavelengths at which area is defined [Ang]

keywords
	order	[I/O] if input is not a vector, then returns only the
		effective area for the specified order in AREA(WVL).
		otherwise, on output is an array specifying the
		spectrographic order at which each element in
		AREA(WVL) is defined.
		* if not specified, assumes ORDER=1
	ardb	[INPUT] analysis reference data base directory,
		in which to look for instrument calibration data
		[default: /data/fubar/SCAR/ardb/]
	help	[INPUT] if set, prints usage and exits
	_extra	[JUNK] here only to prevent crashing the program

commons
       euve_mw	{mwea, mw, mword}

restrictions
	* will crash if ARDB is incorrectly set or if mw_ea.FITS file
	  is not present in ARDB
	* requires IDLASTRO library
	* requires SETSYSVAL

history
	vinay kashyap (Jan97)
	changed CALDIR default (VK; Nov98)
	added keyword HELP (VK; MayMM)
	changed CALDIR to ARDB (VK; DecMM)
	now stores in common regardless, and takes ARDB default from !ARDB;
	  added call to SETSYSVAL (VK; Sep01)

(See /data/fubar/SCAR/pro/specific/euve_mw.pro)


EUVE_SW

[Previous Routine] [Next Routine] [List of Routines]
procedure	EUVE_SW
	reads in effective area curves for the Extreme Ultra-Violet
	Explorer's Short-Wavlength spectrometer

usage
	euve_sw,area,wvl,order=order,ardb=ardb,/help

parameters
	area	[OUTPUT] effective areas [cm^2]
	wvl	[OUTPUT] wavelengths at which area is defined [Ang]

keywords
	order	[I/O] if input is not a vector, then returns only the
		effective area for the specified order in AREA(WVL).
		otherwise, on output is an array specifying the
		spectrographic order at which each element in
		AREA(WVL) is defined.
		* if not specified, assumes ORDER=1
	ardb	[INPUT] analysis reference data base directory,
		in which to look for instrument calibration data
		[default: /data/fubar/SCAR/ardb/]
	help	[INPUT] if set, prints usage and exits
	_extra	[JUNK] here only to prevent crashing the program

commons
	euve_sw	{swea, sw, sword}

restrictions
	* will crash if ARDB is incorrectly set or if sw_ea.FITS file
	  is not present in ARDB
	* requires IDLASTRO library
	* requires SETSYSVAL

history
	vinay kashyap (Jan97)
	changed CALDIR default (VK; Nov98)
	added keyword HELP (VK; MayMM)
	changed CALDIR to ARDB (VK; DecMM)
	now stores in common regardless, and takes ARDB default from !ARDB;
	  added call to SETSYSVAL (VK; Sep01)

(See /data/fubar/SCAR/pro/specific/euve_sw.pro)


EXAPED

[Previous Routine] [Next Routine] [List of Routines]
procedure	exaped
	EX APED AD IDL
	extract line and/or continuum emissivity data from an APED file

syntax
	exaped,filroot,emis,tlog,wvl,edens,Z,ion,desig,econf,jon,src,$
	/llist,/coco,/tlist,/noerg,/okeV,atomdb=atomdb,verbose=verbose

parameters
	filroot	[INPUT; required] APED fits file root
		* if this includes a ".fits", the suffix is assumed
		  to be already included and nothing extra is added.
		* the suffix '_linelist.fits' is automatically applied,
		  so don't specify that part.
		  (this is inflexible at this point because we only
		  support reading in this file.  sometime later on
		  the other APED format will also be supported.)
		* looks for ".gz" automatically if the filename
		  specified without it does not exist
	emis	[OUTPUT; required] emissivity array, of the format
		(NTLOG,NWVL,NEDENS)
		* APED units are [ph cm^3/s], which will be converted
		  into [1e-23 ergs cm^3/s] unless the NOERG keyword
		  is set
	tlog	[OUTPUT; required] log10(Temperature [K]) grid on
		which EMIS are placed
	wvl	[OUTPUT; required] wavelength array
		* units are in [Ang] unless the OKEV keyword is set,
		  in which case output in [keV]
	edens	[OUTPUT; required] electron densities at which
		EMIS have been calculated
	Z	[OUTPUT; required] atomic numbers of species producing
		the given line
	ion	[OUTPUT; required] ionic state of species corresponding
		to the line
	desig	[OUTPUT] (2,NWVL) string array of lower and upper level
		designation
		* currently, just the lower and upper levels
	econf	[OUTPUT] (2,NWVL) string array of electron configuration
		of lower and upper levels of the transition in question
		* not implemented yet
	jon	[OUTPUT] the ionic state that matters to the ion balance
		* not implemented yet
	src	[OUTPUT] numeric code specifiying that this is an APED
		output, set to 3

keywords
	llist	[INPUT] if set, reads from FILROOT_linelist.fits
		* currently this is the only option supported
	coco	[INPUT] if set, reads from FILROOT_coco.fits
		* NOT YET IMPLEMENTED
	tlist	[INPUT] if set, reads from FILROOT_line.fits
		* NOT YET IMPLEMENTED
	noerg	[INPUT] if set, EMIS will be output in same units as
		in the APED files, i.e., [ph cm^3/s]
	okeV	[INPUT] if set, WVL will be converted from [Ang] to [keV]
	atomdb	[INPUT] directory containing input file
		* default is !ATOMDB
		* hardcoded default is /data/atomdb/
		* prepended to FILROOT only if FILROOT does not begin with
		  a '/' (UNIX), ':' (MacOS), '\' (Windows), or '[' (VMS?)
	logT	[INPUT] if defined as an array, then interpolates/extrapolates
		EMIS(NTLOG,NWVL) to a new grid EMIS(NLOGT,NWVL) prior to
		output.  TLOG will be overwritten by LOGT.
	verbose	[INPUT] controls chatter
	_extra	[JUNK] ignore -- here only to prevent crashing the program

subroutines
	SETSYSVAL
	ARRAYEQ
	REBINX

description
	The ATOMDB file format is described in
		http://cxc.harvard.edu/atomdb/features_formats.html
	In this case, the line list (grouped by line) file is read, and
	in particular, only the block EMISSIVITY is read.

history
	vinay kashyap (Jul02)
	bug correction when multiple densities are included (VK; Mar03)

(See /data/fubar/SCAR/pro/mkemis/exaped.pro)


EXIST

[Previous Routine] [Next Routine] [List of Routines]
 Project     :	SDAC

 Name        :	EXIST

 Purpose     :	To See if variable Exists

 Explanation :	So obvious, that explaining it will take more
               lines than the code.

 Use         :	A=EXIST(VAR)

 Inputs      :	VAR = variable name

 Opt. Inputs : None.

 Outputs     :	1/0 if variable exists or not

 Opt. Outputs:	None.

 Keywords    :	None.

 Calls       :	None.

 Common      :	None.

 Restrictions:	None.

 Side effects:	None.

 Category    :	Useful stuff

 Prev. Hist. :	None.

 Written     :	Dominic Zarro (ARC)

 Version     :	Version 1.0, 18 September 1993

(See /data/fubar/SCAR/pro/external/exist.pro)


FIDGIT

[Previous Routine] [Next Routine] [List of Routines]
procedure	fidgit
	digitally (i.e., using Darwin-given fingers) fit a DEM
	to a given spectrum

syntax
	fidgit,x,y,lstr,cstr,ysigma=ysigma,dem=dem,logt=logt,abund=abund,$
	abfrac=abfrac,ldbdir=ldbdir,cdbdir=cdbdir,ceroot=ceroot,lsf=lsf,$
	wdem=wdem,wspc=wspc,verbose=verbose,$
	pres=pres,logP=logP,n_e=n_e,desig=desig,econf=econf,/allah,$
	chidir=chidir,chifil=chifil,chidir=chidir,eqfile=eqfile,$
	effar=effar,wvlar=wvlar

parameters
	x	[INPUT; required] wavelengths or channels of observed
		spectrum
		* if channels, must specify an RMF via the keyword LSF
		  that matches the binning of the spectrum
		  BEWARE: no checks are performed to verify that the
		  supplied RMF is consistent with the input data
	y	[INPUT; required] spectrum
	lstr	[I/O; required] line emissivity structure of the sort read in
		by RD_LINE()
		* if not given on input, will call RD_LINE() and generate it
	cstr	[I/O; required] continuum emissivity structure of the sort
		read in by RD_CONT()
		* if not given on input, will call RD_LINE() and generate it

keywords
	ysigma	[INPUT] errors on Y; default is 1+SQRT(0.75+ABS(Y))
	dem	[I/O] DEM to start out with, will contain the final
		result on output
	logt	[I/O] log(T [K]) at which DEM are defined.  ignored on
		input if it doesn't match the size of DEM
	abund	[INPUT] abundances
		* if not set, assumed to be from Anders & Grevesse 1989
	abfrac	[I/O] multiplicative factor by which to modify ABUND
		* if scalar, assumed to be metallicity
		* if vector, must match size of ABUND, else gets reset to 1
		* default is 1
	ldbdir	[INPUT] path to line emissivity database to read in if LSTR
		is not given
		* default is '$CHIANTI'
		* uses !LDBDIR if set
	cdbdir	[INPUT] path to continuum emissivity database to read in if
		CSTR is not given
		* default is '$CONT'
		* uses !CDBDIR if set
	ceroot	[INPUT] prefix for continuum emissivity files
		* default is 'cie'
		* uses !CEROOT if set
	lsf	[INPUT] line spread function
		* if scalar, the width of the line in bins used as a
		  halfwidth for boxcar smoothing
		* if vector, assumed to be the kernel with which to smooth
		* if RMF structure (of the type read in from RD_OGIP_RMF())
		  then convolves the theoretical spectrum with this RMF
	wdem	[INPUT] window number to display DEM in
	wspc	[INPUT] window number to display spectrum in
	verbose	[INPUT] controls chatter
		* uses !VERBOSE if set
	_extra	[INPUT] allows specifying defined keywords to subroutines
		called by this program
		* RD_LINE: PRES, LOGP, N_E, DESIG, ECONF, ALLAH
		* RD_CONT: PRES, LOGP, N_E
		* FOLD_IONEQ: CHIFIL, VERBOSE
		* RD_IONEQ: CHIDIR, EQFILE
		* LINEFLX: EFFAR, WVLAR

restrictions
	* requires subroutines
	  -- DEMACS
	  -- WHEE
	  -- RD_LINE [FOLD_IONEQ, RD_IONEQ, READ_IONEQ]
	  -- RD_CONT
	  -- LINEFLX
	  -- CONV_RMF
	  -- INICON

history
	vinay kashyap (Feb97)
	modified ion balance calcs (VK; 99May)
	completely rewritten (VK; Aug04)

(See /data/fubar/SCAR/pro/fidgit.pro)


FILEPERMIT

[Previous Routine] [Next Routine] [List of Routines]
procedure	filepermit
	a wrapper for find.  removes (or adds) group and world rwx
	permissions as appropriate (i.e., duplicates u permissions)
	to all files in the hierarchy

syntax
	filepermit,dir,plus=plus,world=world,group=group,exclude=exclude,$
	opts=opts,/dironly,/nouser,verbose=verbose

parameters
	dir	[INPUT; required] topmost level of directory structure
		* if array of directories, runs the same commands on each

keywords
	plus	[INPUT] if set, _adds_ group rwx permissions to all files
		as appropriate
		* the default is to _remove_ group rwx permission
	world	[INPUT] if set, _adds_ world rwx permissions to all file
		as appropriate
		* the default is to _remove_ setting of world permissions
	group	[INPUT] if set to a scalar string, changes group name
		to the specified GROUP
	exclude	[INPUT] if set to a scalar string, excludes the given
		file pattern from the searches
		* wildcards must be escaped with a "\"
	opts	[INPUT] if set to a scalar string, assumes that what is
		given are extra options to FIND and tacks them on just
		prior to the -type command
		* unless you know exactly what you are doing, avoid
		  -user, -perm, -exec, -type
		* example:
		  to avoid traversing links, include OPTS='! -type l'
		  to echo each file found to STDOUT, use OPTS='-ls'
		  to check only files modified within the past week,
		  	use OPTS='-mtime -7'
	dironly	[INPUT] if set, operates on directories only
	nouser	[INPUT] if set, does not include "-user WHOAMI" in call
	verbose	[INPUT] controls chatter

	_extra	[JUNK] here only to prevent crashing the program

description
	spawns the following instances of find:
		find DIR \
		-user WHOAMI \
		[ OPTS ] \
		\( ! -name EXCLUDE \)  \
		[ -type d ] \
		-perm -u+[rwx] \
		-exec chmod g[-+][rwx],o[-+][rwx] {} \; \
		-exec chgrp GROUP {} \;

restrictions
	works only on UNIX
	cannot EXCLUDE directories -- must use
	  /NOUSER,OPTS='\( -name DIR_TO_EXCLUDE -prune -o -print \)'
	or something of that sort

history
	vinay kashyap (MMIVfeb; yes, a shell or perl script would
	have been more appropriate, but I found it easier to handle
	the flexibility better in IDL)

(See /data/fubar/SCAR/pro/misc/filepermit.pro)


FILE_EXIST

[Previous Routine] [Next Routine] [List of Routines]
   Name: file_exist

   Purpose: returns true(1) if any files match pattern=file
	     false(0) if no files found

   Input Parameters:
      file - file, pathname or file filter to check

   Optional Keyword Parameters
      direct - set if want full check (slower) - use if might be an
		empty directory you are looking for

   History: written by slf, 11/30/91
	4-Sep-92 (MDM) - Modified to handle an array of input files
      23-sep-93 (slf) - make sure null file returns false
			 (findfile count=1! when null requested)
      17-Mar-94 (SLF) - use file_stat(/exist) for non wild card cases
      April Fools'94 (DMZ) -- added check for :: in file name
                              (file_stat doesn't work across DECNET)
      31-May-94 (DMZ)      -- added check for VMS directory name input
                              (file_stat doesn't seem to work on VMS
                               dir names like '[ys.atest.soft]')
      16-Aug-94 (DMZ)      -- added another VMS patch to handle
                              case when user enters  a VMS subdirectory name
                              without a file name.
      6-Aug-97 (Zarro/GSFC) -- added check for nonstring input
      30-may-99 (rdb)      -- stop use of file_stat with WINDOWS
                              cause access violation - for wildcard search
      8-Jan-1999 - S.L.Freeland - put in IDL version check since 5.3/IRIX
                   (at least) not backwardly compatible (must use findfile)
     10-Jan-1999 - S.L.Freeland - extended 8-jan mod to all UNIX 5.3
     15-Feb-2000 - S.L.Freeland - removed 5.3 changes (moved fix to file_stat)

(See /data/fubar/SCAR/pro/external/file_exist.pro)


FILE_STAT

[Previous Routine] [Next Routine] [List of Routines]
 Project     :	SOHO - SSW

 Name        :	FILE_STAT()

 Purpose     :	Vector version of FSTAT

 Category    :	Utility, Operating_system

 Explanation :	Vector version of FSTAT

 Syntax      :	Result = FILE_STAT( FILES )

 Examples    :	

 Inputs      :	FILES	= List of files to check.

 Opt. Inputs :	None.

 Outputs     :	None.

 Opt. Outputs:	None.

 Keywords    :	EXIST	= If set, then the returned values are whether the
			  files exist or not.  This is the default behavior.
		SIZE	= If set, then the returned values are the sizes of the
			  files.

 Calls       :	DATA_CHK

 Common      :	None.

 Restrictions:	None.

 Side effects:	None.

 Prev. Hist. :	11-Mar-1994 (SLF) Wanted faster file_exist function

 History     :	Version 1, 11-Mar-1994, S. Freeland
               Version 1.1 05-Jun-1998, J. Newmark changed loop to long
               Version 1.2 15-Feb-2000, S.L.Freeland - work around RSI
                 Version 5.3 non-backwardly compatible change....
               Version 1.3 10-Mar-2000, S.L.Freeland - fix 5.3 /SIZE bug
  
 Contact     :	SFREELAND
 Restrictions:
   file size returned for directories under +5.3 is not valid

(See /data/fubar/SCAR/pro/external/file_stat.pro)


FINDEX

[Previous Routine] [Next Routine] [List of Routines]
 ROUTINE:  findex

 PURPOSE:  Compute "floating point index" into a table using binary
           search.  The resulting output may be used with INTERPOLATE.

 USEAGE:   result = findex(u,v)

 INPUT:    
   u       a monitically increasing or decreasing 1-D grid
   v       a scalor, or array of values

 OUTPUT:
   result  Floating point index. Integer part of RESULT(i) gives
           the index into to U such that V(i) is between
           U(RESULT(i)) and U(RESULT(i)+1).  The fractional part
           is the weighting factor

                          V(i)-U(RESULT(i))
                          ---------------------
                     U(RESULT(i)+1)-U(RESULT(i))


 DISCUSSION: 
           This routine is used to expedite one dimensional
           interpolation on irregular 1-d grids.  Using this routine
           with INTERPOLATE is much faster then IDL's INTERPOL
           procedure because it uses a binary instead of linear
           search algorithm.  The speedup is even more dramatic when
           the same independent variable (V) and grid (U) are used
           for several dependent variable interpolations.

  
 EXAMPLE:  

; In this example I found the FINDEX + INTERPOLATE combination
; to be about 60 times faster then INTERPOL.

  u=randomu(iseed,200000) & u=u(sort(u))
  v=randomu(iseed,10)     & v=v(sort(v))
  y=randomu(iseed,200000) & y=y(sort(y))

  t=systime(1) & y1=interpolate(y,findex(u,v)) & print,systime(1)-t
  t=systime(1) & y2=interpol(y,u,v)            & print,systime(1)-t
  print,f='(3(a,10f7.4/))','findex:   ',y1,'interpol: ',y2,'diff:     ',y1-y2

 AUTHOR:   Paul Ricchiazzi                        21 Feb 97
           Institute for Computational Earth System Science
           University of California, Santa Barbara
           paul@icess.ucsb.edu

 REVISIONS:

(See /data/fubar/SCAR/pro/external/findex.pro)


FINDSCALE

[Previous Routine] [Next Routine] [List of Routines]
function	findscale
	returns the lengthscale in pixels at each point on the given curve

syntax
	ls=findscale(curve,dim,/crunch,/half,pick=pick,choice=choice,eps=eps)

parameters
	curve	[INPUT; required] regularly gridded array of function
		values to be used to compute the length scales
		* if scalar, returns 0
		* if 2D,
		  -- use DIM to specify primary dimension
		  -- compute lengthscales separately along each projection
		* if >2D, convert to 1D
	dim	[INPUT; default=1] primary dimension in case of 2D array
		(e.g., if CURVE=CURVE(NX,NY), DIM=2 returns SCALE=SCALE(NY))

keywords
	crunch	[INPUT] if set, and CURVE is 2D, collapses the array along
		the secondary dimension to generate 1D curve
	half	[INPUT] if set, returns the half-scale
	pick	[INPUT; default=0] if 2D, specifies how to combine the
		scales computed at the different cuts
		0: pick the smallest scale
		1: pick the largest scale
		2: get the average
	choice	[INPUT; default=0] what algorithm to use to find the scale?
		0: MexicanHat wavelet
		1: use inverse of 1st derivative
		2: radius of curvature
		3: stepped toggle
	eps	[INPUT; default=1e-7] small number
	_extra	[JUNK] ignore.  here only to prevent crashing program.

subroutines
	WVLT_SCALE [ROOFN]

history
	vinay kashyap (Apr97)
	added CHOICE option 3 (VK; Feb03)

(See /data/fubar/SCAR/pro/findscale.pro)


FITLINES

[Previous Routine] [Next Routine] [List of Routines]
function	fitlines
	widget-based procedure to fit Gaussians and Lorentzians (or
	combinations, or other 3-parameter functions) to lines in a
	spectrum and determine line fluxes.  returns a structure of
	the form
	  {POS,PERRP,PERRM,PERRC,$
	   FLX,FERRP,FERRM,FERRC,$
	   WDT,WERRP,WERRM,WERRC,$
	   THAW,TYPE,TIES,EPITHET,CONLEVX,CONLEV,CONSIGX,CONSIG,COMMENT}
	All these are also available as output individually as keywords.
	See keyword descriptions for what the variables mean.

syntax
	fxstr=fitlines(x,y,ysig=ysig,funcs=funcs,/intens,dchi=dchi,$
	pos=pos,perrp=perrp,perrm=perrm,perrc=perrc,$
	flx=flx,ferrp=ferrp,ferrm=ferrm,ferrc=ferrc,$
	wdt=wdt,werrp=werrp,werrm=werrm,werrc=werrc,$
	thaw=thaw,type=type,epithet=epithet,ties=ties,$
	conlev=conlev,consig=consig,comment=comment,$
	histerix=histerix,$
	/dumb,verbose=verbose,xsize=xsize,ysize=ysize,$
	wid=wid,dynrng=dynrng,/posve,/negve,itmax=itmax,chithr=chithr,$
	jumpup=jumpup,jumpdn=jumpdn,svdthr=svdthr,missing=missing,$
	/noday,/notime,/nouser,/nopack,stacol=stacol,stacol=stacol,$
	stathk=stathk,/nuthin)

parameters
	x	[INPUT; required] absissa, e.g., wavelength or energy
	y	[INPUT; required] count spectrum Y(X)
		* size of Y must match that of X

keywords
	ysig	[INPUT] errors on Y
		* default is sqrt(abs(Y)+0.75)+1.
	funcs	[INPUT] name of user defined function (actually a procedure)
		that takes as input X and A (the model parameters), and returns
		Y(X;A) and the partial derivatives dY/dA
		* default is set to X3MODEL
		* NOTE: if MPFIT is chosen as the optimization algorithm,
		  then "_f" is automatically appended to the name.  This
		  is because MPFIT requires a _function_, not a procedure.
		  The program corresponding to X3MODEL is X3MODEL_F() and
		  that corresponding to LIBMODEL is LIBMODEL_F()
	intens	[INPUT] if set, Y(X) is assumed to be intensity, i.e.,
		(counts|ergs|.../bin_unit/...)
		* default is to take Y(X) to be (counts|ergs|.../bin/...)
		* passed straight to FITLINES_EVENT
		* WARNING: this has >not< been road-tested!
	dchi	[INPUT] delta-chisq threshold for projection errors
		* default is 1.0
		* may be changed within FITLINES_EVENT, but those changes
		  will not be propagated back.
	pos	[I/O] best-fit line positions
		* length of vector shows number of components
	perrp	[I/O] 1-sided error on POS (POS+PERRP is upper bound)
	perrm	[I/O] 1-sided error on POS (POS-PERRM is lower bound)
	perrc	[I/O] DCHI threshold used in computing PERR?
	flx	[I/O] best-fit fluxes in the lines
	ferrp	[I/O] 1-sided error on FLX (FLX+FERRP is upper bound)
	ferrm	[I/O] 1-sided error on FLX (FLX-FERRM is lower bound)
	ferrc	[I/O] DCHI threshold used in computing FERR?
	wdt	[I/O] best-fit widths (sigma, core-radius, etc.) of the lines
	werrp	[I/O] 1-sided error on WDT (WDT+WERRP is upper bound)
	werrm	[I/O] 1-sided error on WDT (WDT-WERRM is lower bound)
	werrc	[I/O] DCHI threshold used in computing WERR?
		* on input, FLX, WDT, and ?ERR? are forced to match the length
		  of POS: excess elements are thrown away, and insufficient
		  lengths are made up by padding with first elements, 1s, etc.
		* on output ?ERRM are identical to ?ERRP >unless< the
		  projected errors have been calculated using ERORS, in
		  which case the values may be different
		* on output, places where ?ERRC contain 0's are those where
		  the computed errors are 1-sigma formal curvature errors
	thaw	[I/O] integer array signaling frozen (0) or thawed parameter (1)
		* refers to sequences of {POS,WDT,FLX} for each component in
		  a 3-parameter model (cf. X3MODEL) -- whatever goes for the
		  appropriate user-defined function.
		* length must match 3*length(POS)
		* default is to freeze defined input, thaw all new additions
	type	[I/O] type of model ('gauss', 'lorentz', etc.)
		* default is 'gauss'
	epithet	[I/O] label for each component
		* labels, obtained, for example, with IDLABEL
		* Merriam-Webster> a characterizing word or phrase accompanying
		  or occurring in place of the name of a person or thing
	ties	[I/O] any ties between parameters?
	conlev	[I/O] the continuum that was taken out of the spectrum
		* CONLEV must match the size of X and Y else ignored
	consig	[I/O] error on CONLEV
		* default for CONSIG is sqrt(abs(CONLEV)+0.75)+1.
		* NOTE: CONLEV and CONSIG are compressed using SPLAC in
		  the output that gets returned via the structure.  That
		  structure therefore also has appropriate abscissae
		  CONLEVX and CONSIGX.
	comment	[OUTPUT] descriptive string
	histerix	[OUTPUT] a structure containing the state at each step
			of the fitting process
			* if explicitly set to 0, will not contain any output
			* passed w/o comment to FITLINES_EVENT
       oldstr  [INPUT] old fitlines structure from which to start with 
	_extra	[INPUT ONLY] use this to pass defined keywords to subroutines
		PICKRANGE: XSIZE, YSIZE, WID, DYNRNG
		LINEREM: POSve, NEGve
		FIT_LEVMAR: ITMAX, CHITHR, DUMB
		LEVMARQ: JUMPUP, JUMPDN, SVDTHR
		MK_3MODEL: MISSING
		MK_SLANT: ANGLE, BETAP
		ERORS: VERBOSE
		STAMPLE: NUTHIN, NODAY, NOTIME, NOUSER, NOPACK, STACOL,
			 STASIZ, STATHK

subroutines
	FITLINES_EVENT
	FMTSTUFF
	PICKRANGE
	FUNCS
	(X3MODEL/LIBMODEL/MPFITFUN)
	(MK_3MODEL, MK_GAUSS, MK_LORENTZ, MK_SLANT, MK_ROGAUSS, MK_POWLAM, MK_POLY1D)
	LINEREM
	SETCONT
	ERORS
	FIT_LEVMAR
	ADJUSTIE
	LEVMARQ
	LMCOEFF
	CURVE_FIT
	SPLAC
	WHICH
	KILROY
	WHEE
	STAMPLE
	PEASECOLR
	IS_KEYWORD_SET

known bugs
	cannot handle spectra with varying bin sizes
	INTENS has not been tested
	SPLAC keywords are not gracefully handled
	help is available only in UNIX

history
	vinay kashyap (Oct98)
	added renormalization option (VK; Nov98)
	added keywords INTENS,DCHI,PERRL,WERRL,FERRL,PERRC,WERRC,FERRC;
	  changed output structure format (VK; FebMM)
	changed keywords PERR,WERR,FERR to PERRU,WERRU,FERRU; also the
	  corresponding output structure fields (VK; MarMM)
	changed ?ERRU to ?ERRP and ?ERRL to ?ERRM to avoid confusion
	  with ERR[U,L] of ERORS (VK; MarMM)
	moved QUIT to end of row, far from FIT; added ability to save
	  to disk; changed ?ERR[M,C] to be I/O; added TIES to output
	  structure (VK; JulMM)
	added labeling capability via keyword EPITHET; reorganized
	  to combine 6th and 7th rows (VK; AugMM)
	changed location of doc file to ardb ; allowed call to STAMPLE
	  (VK; DecMM)
	changed default of ?ERRC to 0.0 (VK; JanMMI)
	per Antonio Maggio's suggestion, removed keyword MULTIPLE from
	  call to WIDGET_LIST (VK; FebMMI)
	changed suffix of help file from ".doc" to ".hlp" (VK; FebMMI)
	added code to make it easier to switch between color tables
	  (VK; Oct02)
	added monte-carlo errors as option (LL; Aug03) 
	added keyword HISTERIX (VK; Feb04)
       added keyword OLDSTR (LL; Jul05) 
	updated for IDL5.6 keyword_set([0]) behavior change for vectors
	  (VK; 20Mar2006)

(See /data/fubar/SCAR/pro/fitlines.pro)


FITLINES_EVENT

[Previous Routine] [Next Routine] [List of Routines]
procedure	fitlines_event
	widget event handler subroutine for FITLINES.  see that routine
	for a description of variables, etc.  only rudimentary consistency
	checks are carried out here.  uses subroutine FMTSTUFF, which is
	included in this file.

syntax
	fitlines_event,x,y,pos,wdt,flx,perr,werr,ferr,thaw,type,ties,epithet,$
	conlev,consig,chisq,funcs,sigy,widg, perrm=perrm,werrm=werrm,$
	ferrm=ferrm,perrc=perrc,werrc=werrc,ferrc=ferrc,/intens,rmfstr=rmfstr,$
	histerix=histerix

subroutines
	FMTSTUFF
	PICKRANGE
	FUNCS
	(X3MODEL/LIBMODEL)
	(MK_3MODEL, MK_GAUSS, MK_LORENTZ, MK_SLANT, MK_ROGAUSS, MK_POWLAM, MK_POLY1D)
	LINEREM
	SETCONT
	ERORS
	FIT_LEVMAR , CURVE_FIT , MPFITFUN
	ADJUSTIE
	LEVMARQ
	LMCOEFF
	STAMPLE
	KILROY
	WHEE
	PEASECOLR
	IS_KEYWORD_SET

history
	vinay kashyap (Oct98)
	added renormalization option (VK; Nov98)
	various bug fixes and reorganizations (VK; Dec98)
	now allows fitting a single parameter (VK; Aug99)
	enhancements to include call to ERORS, setting YRANGEs,
	  INTENSity units, etc. (VK; FebMM)
	avoid repeat calls to CW_BGROUP, saving tremendous headaches;
	  bug correction CONTINUUM->AdjustNorm (VK; MarMM)
	bug correction -- undefined STYPE for new component; rudimentary
	  changing parameter labels (VK; JunMM)
	moved QUIT to end of row, far away from FIT; added DUMP to disk
	  (VK; JulMM)
	added error-bar plotting capability via VIEW->SetDefaults;
	  pass x,y-range to setcont; added labeling capability via
	  keyword EPITHET; merged 6th and 7th rows; bug correction
	  with xcont in adjust norm (VK; AugMM)
	changed location of help file to ardb; added calls to STAMPLE
	  (VK; DecMM)
	bug fixes: invisible error output, adding model deleted existing
	  projected errors, streamlined saves (VK; JanMMI)
	per Antonio Maggio's suggestion, removed keyword MULTIPLE from
	  call to WIDGET_LIST; improved color-scale setting for 24-bit
	  consoles; replaced call to WHICH by call to ROUTINE_INFO
	  (VK; FebMMI)
	various extra info messages (VK; AprMMI)
	changed y to z on lines 1012 and 1285, because.. y was
	  inappropriate for some reason? (VK; Jun01)
	was crashing due to missing ZSIG in cont_acpt (VK; Aug01)
	bug was not passing predefined CONLEV to SETCONT (piecewise) (VK; Apr02)
	handle color tables in 24-bit displays (VK; Jun02)
	bug correction -- if all ties were deleted, then TIES was turning into
	  and integer array (VK; Jul02)
	made changes to plotting so that hardcopy won't come out with annoying
	  blank sheets (VK; Sep02)
	changed default colors to be compatible with PEASECOLOR (VK);
	  added hooks into MPFIT (Liwei Lin/VK; Oct02)
	tied the left column of parameter values to changes in the main parameter
	  list window on the right (VK; Apr03)
	added monte-carlo errors as option and added keyword RMFSTR (LL; Aug03)
	added keyword HISTERIX (VK; Jul03)
	bug correction: algo_type undefined unless fit is run first (LL; Aug04)
	updated for IDL5.6 keyword_set([0]) behavior change for vectors
	  (VK; 20Mar2006)
	modified some widget instructions to be slightly clearer (VK; Aug06)

*********************************************************************

subroutine	fmtstuff
	takes in the model as described, and returns it properly formatted
	for display in the widget.  parameters are named as before.  only
	minimal consistency checks are carried out.
usage
	fmtstuff,pos,wdt,flx,thaw,type,epithet,perr,werr,ferr,$
	  perrm=perrm,werrm=werrm,ferrm=ferrm,$
	  perrc=perrc,werrc=werrc,ferrc=ferrc,$
	  plist=plist,list=list,$
	  tiep=tiep,tiew=tiew,tief=tief,ties=ties,delcmp=delcmp

keywords
	plist 	[OUTPUT] appropriately formatted model parameter list
	list	[OUTPUT] denoting frozen/thawed components
	tiep	[I/O] ties specially setting the range on positions
	tiew	[I/O] ties specially setting the range on widths
	tief	[I/O] ties specially setting the range on fluxes
	ties	[I/O] rest of ties
	delcmp	[ACTION] if set to component number, deletes component DELCOMP
		and all TIES that contain references to parameters in that
		component
	_extra	[INPUT] pass defined keywords to STAMPLE (NODAY,NOTIME,
		NOUSER,NOPACK,STACOL)

(See /data/fubar/SCAR/pro/fitlines_event.pro)


FITLINES_UNDUMP

[Previous Routine] [Next Routine] [List of Routines]
script	fitlines_undump
	restores the variables saved to disk from FITLINES_EVENT
	and calls FITLINES again.

warning
	this will restore all saved variables from within FITLINES_EVENT.
	all of your existing variables with the same names will be
	overwritten.  best to always start from a clean environment.

	save files written in IDL 5.4 are incompatible with earlier versions,
	but can be restored under certain circumstances using the CMSVLIB
	package of Craig Markwardt
	(http://cow.physics.wisc.edu/~craigm/idl/idl.html)
	This program has a "restore" command right at the start that
	may fail, but if the variables have already been loaded in,
	just type .SKIP and .CON, and bob's your uncle.

usage
	fitsavfil='fitlines.save'
	.run fitlines_undump

input
	FITSAVFIL	name of IDL save file containing the variables
			dumped from within the FITLINES GUI

output
	FITSTR	structure containing the fit parameters

history
	vinay kashyap (MMJul)
	cosmetic surgery (VK; DecMM)
	included keyword HISTERIX (VK; FebMMIV)

(See /data/fubar/SCAR/pro/scrypt/fitlines_undump.pro)


FIT_LEVMAR

[Previous Routine] [Next Routine] [List of Routines]
procedure	fit_levmar
	uses the Levenberg-Marquardt method to find best-fit parameters

syntax
	fit_levmar,x,y,a,yfunc,freeze=freeze,erra=erra,chisq=chisq,$
	itmax=itmax,chithr=chithr,/dumb,ties=ties,vname=vname,$
	jumpup=jumpup,jumpdn=jumpdn,svdthr=svdthr,funcs=funcs,sig=sig,$
	/poisson

parameters
	x	[INPUT; required] data points
	y	[INPUT; required] Y(X)
		* sizes of X and Y must match
	a	[I/O; required] parameters for user-supplied function
		* on input, these are the initial guesses
		* on output, these contain the best-fit values
	yfunc	[OUTPUT] best-fit Y(X;A)

keywords
	freeze	[INPUT] freeze numbered parameters (starting from 0!)
	erra	[OUTPUT] formal errors on the best-fit parameters
	chisq	[OUTPUT] the chi-sq statistic denoting degree of agreement
		between model and data
	itmax	[INPUT; default=100] maximum number of iterations
	chithr	[INPUT; default=0.1] stopping rule: ignore changes in CHISQ
		smaller than this amount
	dumb	[INPUT] if set, skips the part where the user can readjust
		the parameter values in case the fit has gone bad.
	tiptoe	[INPUT] if set, forces small steps on A
	verbose	[INPUT] controls chatter
	_extra	[INPUT] use this to pass defined variables to subroutines:-
		ADJUSTIE: TIES, VNAME
		LEVMARQ: JUMPUP, JUMPDN, SVDTHR
		LMCOEFF: FUNCS, SIG
		(note: FUNCS is actually the name of a _procedure_ --
		CURVEFIT is to blame for the confusion)

subroutines
	ADJUSTIE
	LEVMARQ
	    LMCOEFF
	    SVDC
	    SVSOL

history
	vinay kashyap (Oct98)
	added parameter YFUNC (VK; Dec98)
	bug fix: crashing if freeze not set (VK; 99Aug)
	now returns correct chisq if all params are frozen (VK; JanMM)
	also adjust ERRA for ties (VK; FebMM)
	what if adjusted ERRA becomes 0? (VK; MarMM)
	added keywords TIPTOE and VERBOSE, changed behavior if
	  dead end to now tiptoe around point (VK; Nov04)

(See /data/fubar/SCAR/pro/fit_levmar.pro)


FLUXCURVE

[Previous Routine] [Next Routine] [List of Routines]
procedure	fluxcurve
	compute a fluxed light curve from low-spectral-resolution
	events data

syntax
	fluxcurve,time,chan,charf,chnrg,fluxlc,tgrid,flxerr,$
	ctlc=ctlc,/adapbin,tmin=tmin,tmax=tmax,tbin=tbin,$
	tstart=tstart,tstop=tstop,/shift1,verbose=verbose,$
	/slowok,snrthr=snrthr

parameters
	time	[INPUT; required] photon arrival times
	chan	[INPUT; required] the PI or PHA values of each photon
	charf	[INPUT; required] the average effective area in each channel
	chnrg	[INPUT; required] the average photon energy in each channel
	fluxlc	[OUTPUT; required] the fluxed light curve, in [ergs/s/cm^2]
	tgrid	[OUTPUT; required] the bin boundaries over which the light
		curve is computed
	flxerr	[OUTPUT; optional] the standard errors on the fluxed light
		curve, computed as stddev(fluxes)/nphotons in each bin

keywords
	ctlc	[OUTPUT] the counts light curve, in [ct/s]
	adapbin	[INPUT] if set, rebins adaptively to ensure a
		minimum number of counts in each bin, by pushing
		the counts histogram through SMOOTHIE
		* assumes errors to be sqrt(CTLC*TBIN)
		* for each group, the fluxes from the individual
		  bins are averaged
	tmin	[INPUT] the minimum time value to consider
		* default: min(TIME) < min(TSTART)
	tmax	[INPUT] the maximum time value to consider
		* default: max(TIME) > max(TSTOP)
	tbin	[INPUT] the bin size
		* default: TMAX-TMIN
	tstart	[INPUT] array of start times of GTI's
	tstop	[INPUT] array of stop times of GTI's
	shift1	[INPUT] if set, assumes that the channel numbers
		start from 1, not from 0
		* see the FIRSTCHAN field in the response matrix
		  structure read in via RD_OGIP_RMF()
	verbose	[INPUT] controls chatter
	_extra	[INPUT ONLY] pass defined keywords to subroutines
		SMOOTHIE : SNRTHR
		REBINW : SLOWOK

subroutines
	TI_COVER
	REBINW
	FINDEX
	SMOOTHIE

history
	vinay kashyap (MMVI.IX)

(See /data/fubar/SCAR/pro/timing/fluxcurve.pro)


FLUX_TO_EM

[Previous Routine] [Next Routine] [List of Routines]
function	flux_to_em
	return emission measures (-1 where undeterminable) at various
	temperatures consistent with given line fluxes and line emissivities.

	for each temperature, assume a delta-function emission measure,
	compute line fluxes seen through some instrument, account for
	interstellar absorption, and scale to match the observed flux.

syntax
	em=flux_to_em(emis,flux=flux,logT=logT,wvl=wvl,Z=Z,NH=NH,$
	defEM=defEM,noph=noph,thresh=thresh, abund=abund,/temp,/ikev,$
	effar=effar,wvlar=wvlar,fh2=fh2,he1=he1,heII=heII,/fano)

parameters
	emis	[INPUT; required] 2D array of line emissivities, EMIS(LOGT,WVL)
		* if 1-D, assumed to be EMIS(LOGT)

keywords
	flux	[INPUT] observed fluxes
		* if not given, assumed to be 1 [(ph|erg)/s/cm^2]
		* size is forced to match 2nd dimension of EMIS
		  if <, filled with 1s
		  if >, extra elements are ignored
		* NOTE: the author realizes that there may be multiple IDs
		  for the single observed line, and directs the inquirer
		  to the function ID_TO_EMIS, which returns the appropriately
		  concatenated emissivity table.
	logT	[INPUT] log_10(Temperature [K]) at which EMIS is defined
		* if not given, assumed to go from 4 to 8 in even steps
		* interpolated if size does not match 1st dimension of EMIS
	wvl	[INPUT] wavelengths at which EMIS is defined
		* if not given or if size does not match 2nd dimension of EMIS,
		  (a) interstellar absorption correction is not made
		  (b) all fluxes >gotta be< [ergs/s/cm^2]
	Z	[INPUT] atomic numbers
		* if not given, assumed to be 1s (i.e., H. i.e., no
		  abundance corrections are made)
		* size is forced to match 2nd dimension of EMIS
		  if <, filled with 1s
		  if >, extra elements are ignored
	NH	[INPUT] H column density [cm^-2]
		* ignored if WVL is incorrect
	defEM	[INPUT; default=1e14] default EM to use prior to scaling [cm^-5]
	noph	[INPUT] if set, FLUX is assumed to be in [ergs/s/cm^2], and
		no attempts are made to convert things to [ph/...]
		* forcibly set if WVL is incorrect
	thresh	[INPUT; default=1e-2] dynamic range in output curves,
		relative to maximum in each curve
	_extra	[INPUT ONLY] use this to pass defined keywords to subroutines
		LINEFLX [ABUND,TEMP,IKEV,EFFAR,WVLAR]
		ISMTAU [FH2,HE1,HEII,FANO]

restrictions
	* EFFAR and WVLAR must be correctly defined, or else the output
	  will be garbage
	* requires subroutines
	  LINEFLX
	      WHEE
	  ISMTAU

history
	vinay kashyap (Oct98)
	bug correction re 0 EMIS (VK; Nov98)
	bug correction re 0 NH (VK; AugMM)

(See /data/fubar/SCAR/pro/flux_to_em.pro)


FOLD_ARIA

[Previous Routine] [Next Routine] [List of Routines]
function	fold_aria
	returns spectrum with effective area folded in

syntax
	aspec=fold_aria(x,spec,arstr=arstr,effar=effar,wvlar=wvlar,$
	/lines,/unfold,/perbin)

parameters
	x	[INPUT; required] wavelengths at which spectrum is given
	spec	[INPUT] spectrum, SPEC[X]
		* size must match that of WVL, unless
		* if scalar, expanded out to match size of X, or
		* if missing, assumed to be unity

keywords
	arstr	[INPUT] structure containing effective areas and wavelengths
		* see ARIA.PRO for definition and construction
		* if not given, or is not a structure, looks to EFFAR and WVLAR
	effar	[INPUT] if ARSTR is not defined, take effective areas from
		this keyword
		* if missing or undefined, assumed to be unity
	wvlar	[INPUT] wavelengths at which EFFAR is defined
		* size MUST match that of EFFAR
	lines	[INPUT] if set, assumes that SPEC[X] are individual lines
		and not a spectrum.
	unfold	[INPUT] if set, *divides* the input spectrum by the
		effective area
		* WARNING: where the area is zero, the output is set to NaN
	perbin	[INPUT] if set, assumes that units of SPEC are [.../bin]
	_extra	[JUNK] here only to prevent crashing the program

restrictions
	* requires IDL5+
	* requires subroutines
	  -- ARIA
	  -- REBINW
	* X, ARSTR.WVL, and WVLAR must all have the same units
	* if grating orders > 1 are present in ARSTR
	  -- X must be a wavelength scale
	  -- if LINES and/or UNFOLD are set, output will be garbage

history
	vinay kashyap (JunMM)

(See /data/fubar/SCAR/pro/fold_aria.pro)


FOLD_IONEQ

[Previous Routine] [Next Routine] [List of Routines]
function	fold_ioneq
	folds in ionization equilibrium fractions of the various ions
	of a given element with line emissivities (which include only
	level population info; see RD_LINE()).  returns
	emis(T;Z,ion)*ioneq(T;Z,ion)

syntax
	lflx=fold_ioneq(emis,Z,ion,logt=logt,tmax=tmax,trng=trng,$
	level=level,userarr=userarr,chifil=chifil,chidir=chidir,$
	eqfile=eqfile,verbose=v)

parameters
	emis	[INPUT; required] 1- or 2-D array of line emissivities as
		a function of temperature
		* if 2D, assumed to be EMIS(Temperature,Wavelength)
		* if 1D, assumed to be EMIS(Temperature), unless the
		  number of elements matches that of Z
	Z	[INPUT; required] atomic number(s) corresponding to
		each wavelength
		* if size does not match the 2nd dimension of EMIS, then
		  if >, ignore extra elements
		  if <, but >0, use available ones, and use Z[0] for rest
	ion	[INPUT; default: Z+1] ionic state(s) corresponding to
		each wavelength
		* if size does not match the 2nd dimension of EMIS, then
		  if >, ignore extra elements
		  if <, but >0, use available ones, and use ION[0] for rest
		* NOTE: this is the ionic state >>that matters<<, i.e.,
		  the ionic state of the species that populates the
		  upper level.  See keyword JON of RD_LINE, which is
		  what is needed here.

keywords
	logt	[INPUT] 1D array of log10(temperature [K]) at which EMIS
		is given. (default: findgen(81)*0.05+4)
		* if size does not match that of EMIS, use default
	level	[INPUT; default: 0.5] level at which to determine the
		temperature range on line flux (in other words, default
		will be to return the FWHM)
		* if <1, TRNG=LOGT(where(FLUX>LEVEL*MAX(FLUX))
		* if >=1, TRNG=LOGT(where(FLUX>(LEVEL/100.)*MAX(FLUX))
		* if <=0 or >=100, set to 0.5
	tmax	[OUTPUT] log10(temperature) at which contribution is maximum
	trng	[OUTPUT] range in LOGT (LEVEL of MAX)
		-- TRNG(0,*) is lower bound, TRNG(1,*) is upper bound
	userarr	[INPUT] an array of ionization fractions in the same
		format as is returned by RD_IONEQ(), and has the size
		[n(T),max(Z)+1,n(Z)]
		* if this is given and is legit (i.e., matches the
		  supplied EMIS and LOGT), then EQFILE and CHIFIL are
		  ignored
	eqfile	[I/O] file from which to read in ion-balance data
		* default is to read in the CHIANTI file, !IONEQF
		* hard-coded default is
		  ioneq/mazzotta_etal.ioneq
		* if not given, but CHIFIL is given, uses that.
	chifil	[I/O] if set, reads in from CHIANTI-type database; must be
		set to the name of the file containing the ionization
		equilibrium info (i.e., CHIDIR/CHIFIL)
		* may be overridden with EQFILE
		* default is ioneq/mazzotta_etal.ioneq
		* currently, set automatically if not given.  
	verbose	[INPUT] higher the number, greater the chatter
	_extra	[INPUT] use to transmit defined keywords to called functions
		* RD_IONEQ [CHIDIR]

subroutines
	-- WHEE
	-- SETSYSVAL
	-- RD_IONEQ [READ_IONEQ (%)]
	(%) CHIANTI subroutine, used as is

history
	vinay kashyap (Dec96)
	removed call to KILROY and added call to WHEE, hacked default
	  use of READ_IONEQ until more options become available; corrected
	  bug that was reading in ionstate-1 rather than ionstate; added
	  code to handle Z=0 (VK; Feb97)
	bug: if Z is scalar take em all to be same element (VK; Apr97)
	added keyword VERBOSE (VK; MarMM)
	streamlined meanings of EQFILE, CHIFIL (VK; DecMM)
	changed default for EQFILE; now pass VERBOSE to RD_IONEQ; added
	  call to SETSYSVAL (VK; Jul01)
	allowed EQFILE to be "none" (VK; Feb04)
	changed default behavior of Z and ION when sizes don't match EMIS;
	  now uses first element of input if given (VK; Nov04)
	bug correction, ION is offset by 1 from array index (LL/VK; Dec04)
	added keyword USERARR, slightly modified behavior when EMIS
	  was input as 1D (VK; Aug08)

(See /data/fubar/SCAR/pro/fold_ioneq.pro)


FOLD_RESP

[Previous Routine] [Next Routine] [List of Routines]
function	fold_resp
	returns the PH spectrum as observed with an instrument defined
	by the specified response

syntax
	ph=fold_resp(resp,iE,flx,/binE,fchcol=fchcol,/shift1)

parameters
	resp	[INPUT; required] either of:
		A: 2D array (N_NRG,N_PH) describing the response to a photon
		B: name of OGIP-compliant FITS file containing the response
	iE	[INPUT; required] either of:
		A': bin indices of energy array corresponding to rows of the
		    response matrix
		B': energy of photons which must be binned according to
		    the response matrix resolution
	flx	[INPUT] flux at given iE -- a weighting function
		* if scalar or 1-element vector, essentially acts as
		  "normalization"

keywords
	binE	[INPUT] if set, *and* RSP is a filename, IE is assumed to
		be actual energies and is binned appropriately.
	_extra	[INPUT ONLY] pass defined keywords to subroutines:
		RD_OGIP_RMF: FCHCOL, SHIFT1

restrictions
	* requires subroutines RD_OGIP_RMF, RDRESP, BINERSP,
	  and the IDLASTRO library

history
	vinay kashyap (Jul97)
	corrected bug with bad binning in NRG, now handles large RESP
	  (VK; Mar99)

(See /data/fubar/SCAR/pro/fold_resp.pro)


FPUFIX

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

 PURPOSE:

       This is a utility routine to examine a variable and fix problems
       that will create floating point underflow errors.

 AUTHOR:

       FANNING SOFTWARE CONSULTING
       David Fanning, Ph.D.
       1645 Sheely Drive
       Fort Collins, CO 80526 USA
       Phone: 970-221-0438
       E-mail: davidf@dfanning.com
       Coyote's Guide to IDL Programming: http://www.dfanning.com

 CATEGORY:

       Utilities

 CALLING SEQUENCE:

       fixedData = FPUFIX(data)

 ARGUMENTS:

       data :         A numerical variable to be checked for values that will cause
                      floating point underflow errors. Suspect values are set to 0.

 KEYWORDS:

       None.

 RETURN VALUE:

       fixedData:    The output is the same as the input, except that any values that
                     will cause subsequent floating point underflow errors are set to 0.

 COMMON BLOCKS:
       None.

 EXAMPLES:

       data = FPTFIX(data)

 RESTRICTIONS:

     None.

 MODIFICATION HISTORY:

       Written by David W. Fanning, from Mati Meron's example FPU_FIX. Mati's
          program is more robust that this (ftp://cars3.uchicago.edu/midl/),
          but this serves my needs and doesn't require other programs from
          Mati's library.  24 February 2006.

(See /data/fubar/SCAR/pro/external/fpufix.pro)


FREEBOUND_CH

[Previous Routine] [Next Routine] [List of Routines]
 PROJECT:  CHIANTI

      CHIANTI is an Atomic Database Package for Spectroscopic Diagnostics of
      Astrophysical Plasmas. It is a collaborative project involving the Naval
      Research Laboratory (USA), the University of Florence (Italy), the
      University of Cambridge and the Rutherford Appleton Laboratory (UK). 

 NAME

      FREEBOUND_CH

 EXPLANATION

      Calculates the free-bound (radiative recombination) continuum.

 INPUTS

      TEMP    Temperature in K (can be an array).

      WVL     Wavelength in angstroms (can be an array).

 OUTPUTS

      INT     Free-bound continuum intensity in units of 
              10^-40 erg cm^3/s/sr/Angstrom per unit emission measure 
              ( integral(N_H N_e dh) in cm^-5) if a DEM is not defined. 

              If DEM values are defined, it is assumed that they are given
              as N_H N_e dh/dT.  The units are 10^-40 erg/cm^2/s/srAngstrom 

              If T is given as a 1-D array, then the output will be a 
              2-D array, with one element for each temperature and 
              wavelength (but also see SUMT).

 OPTIONAL INPUTS

      DEM_INT The intensity array is multiplied by a DEM number for 
              each temperature. DEM_INT needs to be of the same size 
              as TEMPERATURE. It is needed for the synthetic spectrum 
              routines.

      IZ     Only calculate continuum for the element with atomic 
             number IZ

      ION    (To be used in conjunction with IZ.) Calculated continuum 
             for a single ion (IZ, ION).

 KEYWORDS

      NO_SETUP If the procedure setup_elements has already been called 
               then the keyword /nosetup should be set to avoid 
               repeating this step

      MIN_ABUND If set, calculates the continuum only from those 
                elements which have an abundance greater than 
                min_abund.  Can speed up the calculations.  For 
                example:
                   abundance (H)  = 1.
                   abundance (He) = 0.085
                   abundance (C)  = 3.3e-4
                   abundance (Si) = 3.3e-5
                   abundance (Fe) = 3.9e-5

      PHOTONS  The output spectrum is given in photon units rather 
               than ergs.

      SUMT     When a set of temperatures is given to FREEBOUND_CH, the 
               default is to output INTENSITY as an array of size 
               (nwvl x nT). With this keyword set, a summation over 
               the temperatures is performed.

      VERBOSE  Output information from FREEBOUND_CH.

 COMMON BLOCKS

      ELEMENTS

 CALLS

      FREEBOUND_ION, SETUP_ELEMENTS, READ_KLGFB, GET_IEQ

 HISTORY

      Ver.1, 24-Jul-2002, Peter Young

      Ver.2, 26-Jul-2002, Peter Young
           revised call to freebound_ion; corrected ion fraction problem
      Ver.PoA, 18-Feb-2005, LiWei Lin 
          Commented common block out and 
          Added _extra keyword
          Rename routine freebound_ch
           

(See /data/fubar/SCAR/pro/external/freebound_ch.pro)


FREEBOUND_ION

[Previous Routine] [Next Routine] [List of Routines]
 PROJECT:  CHIANTI

      CHIANTI is an Atomic Database Package for Spectroscopic Diagnostics of
      Astrophysical Plasmas. It is a collaborative project involving the Naval
      Research Laboratory (USA), the University of Florence (Italy), the
      University of Cambridge and the Rutherford Appleton Laboratory (UK). 

 NAME

      FREEBOUND

 EXPLANATION

      Calculates the free-bound (radiative recombination) continuum 
      from a single ion. Note that the output does not contain the ion 
      fraction, element abundance or differential emission measure term.

 INPUTS

      TEMP    Temperature in K (can be an array).

      WVL     Wavelength in angstroms (can be an array).

      IZ      Atomic number of ion (e.g., 26 = Fe)

      ION     Spectroscopic number of ion (e.g., 13 = XIII)

 OUTPUTS

      INT     Free-bound continuum intensity. Needs to be multiplied by 
              element abundance, ion fraction and DEM to obtain the final 
              continuum intensity.

 OPTIONAL INPUTS

      IP      The ionization potential of the ion.

      VDATA   An array containing the Verner & Yakovlev data array.

      PE      An array containing the PE data from READ_FBLVL

      KLGFB   An array containing the KLGFB data from READ_FBLVL

      [Note: the above 3 inputs are used when calling freebound_ion from 
       freebound]

 KEYWORDS

      NOVERNER  If set, then the Verner & Yakovlev cross-sections will 
                not be used.

 COMMON BLOCKS

      None.

 CALLS

      READ_FBLVL, ZION2FILENAME, VERNER_XS, KARZAS_XS, CONCAT_DIR,
      READ_IP, READ_KLGFB, FILE_EXIST

 PROGRAMMING NOTES

      The way I treat the exponential function in the expression for the 
      emissivity may seem strange, but it saves a bit of time in the 
      calculation. Basically calculating exp(E-IP+E_i/T) for each level 
      was time consuming so I split it into exp(E-IP/T)*exp(E_i/T). The 
      first term comes out of the for loop, while the second term is the 
      exponential of a vector rather than an array. This made a ~30% 
      time-saving for freebound.

 HISTORY

      Ver.1, 24-Jul-2002, Peter Young

      Ver.2, 26-Jul-2002, Peter Young
          Added /noverner keyword.

      Ver.3, 30-Jul-2002, Peter Young
          Speeded up routine by modifying treatment of exponential.

(See /data/fubar/SCAR/pro/external/freebound_ion.pro)


FREEFREE_CH

[Previous Routine] [Next Routine] [List of Routines]
 PROJECT     :  CHIANTI

       CHIANTI is an Atomic Database Package for Spectroscopic Diagnostics of
       Astrophysical Plasmas. It is a collaborative project involving the Naval
       Research Laboratory (USA), the University of Florence (Italy), the
       University of Cambridge and the Rutherford Appleton Laboratory (UK). 

 NAME

     FREEFREE

 EXPLANATION

     This routine computes the free-free continuum (bremsstrahlung) 
     using the fitting formulae of Itoh et al. (ApJS 128, 125, 2000) 
     and Sutherland (MNRAS 300, 321, 1998).

     The Itoh et al. data are valid for smaller ranges for temperature 
     and wavelength than Sutherland and so for points outside of their 
     ranges we use the data of Sutherland.

 INPUTS

    TEMP    Temperature (in K).

    WVL     Wavelengths in angstroms. Can be a scalar or vector.

 OUTPUTS

    INT     Free-free continuum intensity in units of 
            10^-40 erg cm^3/s/sr/Angstrom  per unit emission measure 
            [ integral(N_H N_e dh) in cm^-5 ] if a DEM is not defined. 

            If DEM values are defined, it is assumed that they are given
            as N_H N_e dh/dT.  The units are 10^-40 erg/cm^2/s/sr/Angstrom. 

            If T is given as a 1-D array, then the output will be a 2-D array,
            with one element for each temperature and wavelength 
            (but also see SUMT).

 OPTIONAL INPUTS

    DEM_INT An array of same length as TEMP which contains the 
            differential emission measure values at each temperature. 
            The emissivity at each temperature is multiplied by the 
            DEM value and the d(logT) value.

    MIN_ABUND This keyword allows the specification of a minimum abundance, 
              such that any elements with an abundance (relative to 
              hydrogen) less than MIN_ABUND will not be included in the 
              calculation. E.g., MIN_ABUND=1e-5.

 KEYWORDS

    NO_SETUP By default the routine asks the user which ion balance 
             and abundance files to use via pop-up widgets. If 
             /no_setup is used then this data is taken from the common 
             block.

    SUMT     The default is to output the intensity array as an array 
             of size (nwvl x nT). Setting this keyword performs a sum 
             over the temperatures to yield a vector of same size as 
             the input wavelengths, thus producing the complete 
             free-free spectrum.

    PHOTONS  Gives output emissivity in photon units rather than ergs.

 CALLS

    SUTHERLAND_CH, ITOH_CH

 COMMON BLOCKS

    ELEMENTS

 PROGRAMMING NOTES

    The Itoh fitting formula is only valid for (6.0 LE logT LE 8.5). 
    For temperatures below this, we thus switch to the Sutherland 
    fitting formula. There is very little (<1%) between the two at 
    logT=6.

    Itoh also has a constraint on the quantity u=hc/kTl (l=wavelength), 
    such that (-4 LE log u LE 1.0). The upper limit corresponds to the 
    continuum being cut-off prematurely at low wavelengths. E.g., for 
    T=10^6 the cutoff is at 14.39 angstroms. For these low wavelengths 
    we also use the Sutherland data to complete the continuum. Note that 
    the continuum at these wavelengths is very weak

 MODIFICATION HISTORY

    Ver.1, 5-Dec-2001, Peter Young
         Completely revised to call the separate itoh.pro and 
         sutherland.pro routines.

    V. 2, 21-May-2002,  Giulio Del Zanna (GDZ),
          Corrected the description of the  units.
          Added verbose keyword and a printout.

    V. 3, 22-May-2002,  Peter Young (PRY)
          Added MIN_ABUND optional input.
          Changed ioneq_t to ioneq_logt (GDZ).

    V.PoA, 18-Feb-2005, LiWei Lin 
          Commented common block out and 
          Added _extra keyword
          Rename routine freefree_ch
          Edit calls to sutherland and itoh to sutherland_ch and itoh_ch

(See /data/fubar/SCAR/pro/external/freefree_ch.pro)


GENERATIO

[Previous Routine] [Next Routine] [List of Routines]
procedure	generatio
	a generalized mechanism to compute flux ratios and errors
	from given input fluxes and a well-defined definition of
	how the ratios are constructed

	all of the input fluxes are assumed to be independent
	of each other and uncorrelated

syntax
	generatio,fx,rcode,rx,fxerr=fxerr,rxerr=rxerr,verbose=v,$
	dfx_mul=dfx_mul,dfx_add=dfx_add

parameters
	fx	[INPUT; required] input fluxes
	rcode	[INPUT] string array describing which of the
		input fluxes must be considered only as ratios
		* basic format is: "sP#[,sP#[,...]]" where
		  -- "#" is an integer flag describing the ratio being
		     constructed
		  -- "P" is a positional descriptor and can take on
		     values N (for numerator) or D (for denominator)
		  -- "s" stands for the sign with which the flux
		     goes into the ratio "+" or "-"
		* e.g., to construct a simple ratio FX[2]/FX[1],
		  RCODE=['','+D1','+N1']
		* e.g., to construct two hardness ratios
			FX[3]/FX[1] and
			(FX[3]-FX[1])/(FX[3]+FX[1]),
		  RCODE=['','+D1,-N2,+D2','','+N1,+N2,+D2']
		* if size is incompatible with FX, then no action
		  is taken.
	rx	[OUTPUT] array of ratios constructed using FX and RCODE

keywords
	fxerr	[INPUT] 1-sigma errors on FX
		* size must match that of FX.  otherwise,
		  -- if single-element, assumed to represent
		     -- a fractional error if >0 and <1
		     -- a percentage error if >1 and <100
		     -- an abs(constant) error if >100 or <0
		  -- ignored otherwise
	rxerr	[OUTPUT] 1-sigma errors on RX, computed only if FXERR
		is given and is legal
	verbose	[INPUT] controls chatter
	dfx_mul	[INPUT] multiplicative factor by which to jiggle FX
		while computing partial derivatives to propagate
		errors (default is 0.05)
	dfx_add	[INPUT] additive factor by which to jiggle FX
		while computing partial derivatives to propagate
		errors (default is 0.05)
	_extra	[JUNK] here only to avoid crashing the program

example
	;this makes the ratios FX[0]/FX[1] and (FX[1]-FX[0])/(FX[1]+FX[0])
	fx=[10.,5.] & fxerr=0.1 & rcode=['+N1,-N2,+D2','+D1,+N2,+D2']
	generatio,fx,rcode,rx,fxerr=fxerr,rxerr=rxerr
	for i=0,n_elements(rx)-1 do print,rx[i],' +- ',rxerr[i]

	Warning: The numeral suffix in the ratio specification is
	only as a placeholder to determine uniqueness and does _not_
	translate to the index in the output.  For example, try:
	fx=[1.,2.,1.,3.,1.,4.,1.,5.,1.,6.]
	rcode=['+D1','+N1','+D2','+N2','+N3','+D3','+N4','+D4','+D5','+N5']
	generatio,fx,rcode,rx,verbose=100
	print,rcode & print,rx
	generatio,fx,reverse(rcode),rx_reverse,verbose=100
	print,reverse(rcode) & print,rx_reverse

subroutines
	IS_KEYWORD_SET

history
	vinay kashyap (Nov'02)
	cosmetic changes (VK; Dec'02)
	won't spit out error messages if RCODE is 'X', though the FX
	  corresponding to that is ignored (VK; Apr'03)
	added warning about ratio sequence -- it's a feature, not a bug;
	  corrected bug in case of sequence number exceeding 9 (VK; Dec'03)
	now lets specifying just numerator or just denominator (VK,LL; Jun'04)
	updated for IDL5.6 keyword_set([0]) behavior change for vectors
	  (VK; 20Mar2006)

(See /data/fubar/SCAR/pro/misc/generatio.pro)


GETABUND

[Previous Routine] [Next Routine] [List of Routines]
function	getabund
		returns elemental abundances in an array

syntax
	abund=getabund(hint,elem=elem,source=source,norm=norm,$
	metals=metals,fipbias=fipbias,abunde=abunde)

parameters
	hint	[INPUT] some hint as to what output is required.  examples:
		'help' -- prints out usage
		'anders', 'anders & grevesse', etc. -- Anders & Grevesse (1989)
		'meyer', 'coronal', etc. -- Meyer (1985)
		'allen', 'cosmic' -- Allen (1973)
		'ross', 'aller', 'ross & aller', etc. -- Ross & Aller (1976)
		'grevesse', 'grevesse et al.', etc. -- Grevesse et al (1992)
			modifications to Anders & Grevesse (1989)
		'feldman', etc. -- Feldman et al (1992)
		'waljeski', etc. -- Waljeski et al. (1994)
		'murphy', 'chromospheric', etc. -- Murphy (1985) chromospheric
		'grevesse & anders' -- Grevesse & Anders (1991)
		'grevesse & sauval' -- Grevesse & Sauval (1998) "standard
			abundances"
		'young', 'photo' -- photospheric abundances from Young et
			al. (1997)
		'fludra', 'schmelz' -- Fludra & Schmelz (1999) "hybrid coronal"
		'asplund' -- Asplund, Grevesse, & Sauval (2005) 3D hydro
			model of solar atmosphere to constrain convection
		'path/file', etc. -- if string contains a "/" in it, then
			read from disk file which contains one entry per
			line, with atomic symbol first, and abundance next

keywords
	elem	[INPUT] element -- if given, return abundances for only
		the specified element
		* if string, converts to atomic number using SYMB2ZION
		* if byte, integer, or float, assumed to be atomic number
		* may be an array
	source	[INPUT] another way to say "hint"
		1: Anders & Grevesse (1989)
		2: Meyer (1985)
		3: Allen (1973)
		4: Ross & Aller (1976)
		5: Grevesse et al. (1992)
		6: Feldman et al. (1992)
		7: Waljeski et al. (1994)
		8: Murphy (1985)
		9: Grevesse & Anders (1991)
		10: Grevesse & Sauval (1998)
		11: Young et al. (1997)
		12: Fludra & Schmelz (1999)
		13: Asplund, Grevesse, & Sauval (2005)
		* overrides HINT iff HINT is not understood
	norm	[INPUT] normalization
		* use this to set output format
		  NORM=1: output will be n(Z)/n(H) (this is the default)
		  NORM>1: output will be NORM(0)+log10(n(Z)/n(H))
		  	(e.g., NORM=12 is the standard log form)
		  0<NORM<1: output will be NORM(0)*n(Z)/n(H)
		  	(this can be useful when ELEM is set)
		  -1<=NORM<0: output will be n(Z)/DEFAULT_n(Z)
		  	(if you want to compare different abundance tables)
		  NORM<-1: output will be log10(n(Z)/DEFAULT_n(Z))
		  	(I have no idea why anyone would use this)
	metals	[INPUT] metallicity.  if set, modifies the abundances of
		all elements past He by the appropriate amount
		* if not set, makes no changes
		* assumed to be in log10 form if
		  -- abs(NORM) > 1, or
		  -- < 0
		* assumed to be multiplicative factor otherwise
		* NOTE: for example, if norm=12 then metals=0 means
		  Solar abundances, while if norm=1 then metals=0
		  means complete metal depletion!
	fipbias	[INPUT] if set to a non-zero scalar, multiplies the
		abundances of low-FIP elements by this factor.  be
		careful not to use it for abundance lists that already
		include the FIP effect.
		* if not set, or set to 0, does nothing.
	abunde	[OUTPUT] errors on abundances
	
	_extra	[INPUT] junk -- here only to prevent program from crashing

subroutines
	RDABUND
	SYZE
	SYMB2ZION

history
	vinay kashyap (Dec96)
	avoid analyzing HINT if SOURCE is set (VK; Jan97)
	added 'angr' and tightened 'Anders&Grevesse' v/s 'Grevesse' (VK; Jul97)
	added option of reading from disk file (VK; Jun98)
	added Murphy (1985) data, and allowed ELEM to be array (VK; Jul98)
	corrected bug associated with non-array ELEMs (VK; Sep98)
	added keyword METALS, deleted keywords ALTER, FORM, removed call to
	  SETABUND, added call to RDABUND (VK; Dec98)
	added Grevesse & Anders (1991), Grevesse & Sauval (1998), Young et
	  al (1998) (VK; Apr99)
	added keyword FIPBIAS (VK; Jul01)
	added Fludra & Schmelz (1999); now HINT overrides SOURCE and program
	  warns if there is a conflict (VK; Jun02)
	corrected Meyer abundances for O and Na (VK; Apr04)
	corrected Fludra & Schmelz abundances (VK; Jun04)
	added Asplund, Grevesse, & Sauval abundances; added keyword ABUNDE
	  (VK; Apr05)
	B was off by 2 orders of magnitude (thx Marc Audard; VK Jul06)

(See /data/fubar/SCAR/pro/getabund.pro)


GETDISTDT

[Previous Routine] [Next Routine] [List of Routines]
function	getdistdt
	compute a theoretical distribution of arrival time differences
	for a supplied light curve

description
	the Poisson probability of finding k events in the interval dt,
	for rate R,
		p(k|R,dt) = (R*dt)^k * exp(-R*dt) / Gamma(k+1)

	when we consider a list of photon arrival times, the time differences
	between each photon constitute the case where exactly one event is
	observed in that duration.  these time differences must therefore be
	distributed as
		p(1|R,dt) = (R*dt) * exp(-R*dt)

	If R is varying, R=R(t_i), the instantaneous rate at any given time is
	iid Poisson, so the overall distribution is the sum of the distributions
	at each time,
		Sum_i p(1|R_i,dt)

	this routine takes count rates assumed to be binned at constant bin
	sizes, computes a distribution for each of the rates, adds them up,
	and returns the result.

syntax
	hdt=getdistdt(lc,ldt,ldtmin=ldtmin,ldtmax=ldtmax,ldtbin=ldtbin,$
	/nolog,verbose=verbose)

parameters
	lc	[INPUT; required] the light curve for which the differences
		in photon arrival times needs to be computed
		* must be given in count rates [counts/sec]
		* negative values will be silently ignored
	ldt	[OUTPUT] the log10(deltaT) grid over which the output
		is calculated
		* output will be a grid of plain deltaT if NOLOG is set
		* note that this will have one more element than the output
		  histogram, will have all bin beginnings and endings

keywords
	ldtmin	[INPUT] the minimum time difference to consider
		* default is -5
		* if NOLOG is set, assumed to be not in log10,
		  and default is changed to 0.
	ldtmax	[INPUT] the maximum time difference to consider
		* default is 2
		* if NOLOG is set, assumed to be not in log10,
		  and default is changed to 1e3.
	ldtbin	[INPUT] the bin size for the output LDT grid
		* default is 0.01
		* if NOLOG is set, assumed to be not in log10,
		  and default is changed to 1.
	nolog	[INPUT] if set, computes the arrival time differences
		in regular sec, not in log10.
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to prevent crashing the program


history
	vinay kashyap (Nov2009)

(See /data/fubar/SCAR/pro/timing/getdistdt.pro)


GETLOCMAX

[Previous Routine] [Next Routine] [List of Routines]
function	getlocmax
	returns the position indices where y(x) is a local maximum

syntax
	ilm=getlocmax(x,y,width=width,sigmay=sigmay,nsigma=nsigma,/flattop)

parameters
	x	[INPUT; required] abscissae where input function is defined
	y	[INPUT] input function.  if not given, X is taken to be Y
		and array position indices are taken to be X

keywords
	width	[INPUT; default: 1] window in which to search for local
		maxima -- window width = 2*abs(WIDTH)+1 or 3, whichever
		is greater.
	sigmay	[INPUT; default: 1+sqrt(abs(Y)+0.75)] error at each point
		* if scalar and NSIGMA is not defined, then SIGMAY->NSIGMA
	nsigma	[INPUT; default: 1] multiple of SIGMA to consider as a
		threshold filter
		* to use var(y) as a constant value of SIGMAY, do
		  ilm=getlocmax(x,y,sigmay=sqrt((moment(y))(1)),/nsigma)
	flattop	[INPUT] if set, allows for the finding of points which
		all have the same peak value within the window width,
		in contrast to the default method that only finds those
		points that are indubitably the local maximum within the
		window
		* be warned that this will catch everything in a flat Y(X)
		  use it carefully
	_extra	[INPUT] junk -- here only to keep routine from crashing

history
	vinay kashyap (Dec96)
	corrected bug with 1-, 2-, or 3-element inputs (VK; Nov98)
	changed keyword SIGMA to SIGMAY (VK; Apr03)
	corrected bug with input x not sorted in ascending order
	  (VK; Feb04)
	added keyword FLATTOP to allow finding of flat peaks (VK; Apr07)

(See /data/fubar/SCAR/pro/misc/getlocmax.pro)


GET_CHANDRA_PSFSIZE

[Previous Routine] [Next Routine] [List of Routines]
function	get_chandra_psfsize
	read in Diab's table that lists the PSF sizes and return
	the radius [arcsec] that encloses a specified fraction
	of the PSF

syntax
	psfradii=get_chandra_psfsize(theta,phi,energy=energy,eefrac=eefrac,$
	eeftbl=eeftbl,idx_eef=idx_eef,idx_nrg=idx_nrg,idx_phi=idx_phi,$
	verbose=verbose)

parameters
	theta	[INPUT; required] off-axis angles in [arcmin]
	phi	[INPUT; optional] azimuthal angles in [degree]
		* if phi is not given, assumed to be 0
		* if N(PHI)=1, all PHI are taken to be PHI[0]
		* if N(PHI).ne.N(THETA), only PHI[0] is used

keywords
	energy	[INPUT; default=1.5 keV] energy at which to determine
		PSF size
	eefrac	[INPUT; default=0.9] fraction of PSF enclosed
		* note that in case of both ENERGY and EEFRAC,
		  there is no interpolation -- entries closest
		  to specified value will be chosen.  (users can
		  always carry out the interpolations post facto)
		* if <0, ABS(EEFRAC) is assumed
		  if >1 and <100, assumed to be percentage
		  if >100, then 1-1/EEFRAC is used
	eeftbl	[INPUT; '/data/L3/fap/ecf/hrmaD1996-12-20hrci_ecf_N0002.fits.gz']
		full path name to Diab Jerius' compilation of
		enclosed energy fractions
	idx_eef	[OUTPUT] index of EE fraction column used
	idx_nrg	[OUTPUT] index of energy column used
	idx_phi	[OUTPUT] index of PHI column used
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to prevent crashing the program

history
	vinay kashyap (Apr2006)

(See /data/fubar/SCAR/pro/specific/get_chandra_psfsize.pro)


GET_IEQ

[Previous Routine] [Next Routine] [List of Routines]
 PROJECT:  CHIANTI

      CHIANTI is an Atomic Database Package for Spectroscopic Diagnostics of
      Astrophysical Plasmas. It is a collaborative project involving the Naval
      Research Laboratory (USA), the University of Florence (Italy), the
      University of Cambridge and the Rutherford Appleton Laboratory (UK). 

 NAME

      GET_IEQ()

 EXPLANATION

      For a specified ion (IZ, ION) and set of temperatures (TEMP) this 
      routine takes the ion fraction values tabulated in one of the CHIANTI 
      .IONEQ files, interpolates and extracts the values of the ion 
      fraction at the input temperatures.

 INPUTS

      TEMP   The temperature(s) at which the ion fractions are required.

      IZ     The atomic number of the element (e.g., 26 = iron).

      ION    The spectroscopic number of the ion (e.g., 13 = XIII).

 OPTIONAL INPUTS

      IONEQ_LOGT  The temperature output from the READ_IONEQ routine.

      IONEQ_FRAC  The ion fractions from the READ_IONEQ routine.

 OUTPUT

      A vector of same length as the input TEMP containing the ion 
      fractions at these temperatures.

 CALLS

      READ_IONEQ

 HISTORY

      Ver.1, 24-Jul-2002, Peter Young

(See /data/fubar/SCAR/pro/external/get_ieq.pro)


GET_IONLIST

[Previous Routine] [Next Routine] [List of Routines]
function	get_ionlist
	return a list of all the ions for a particular element that
	CHIANTI has data for

syntax
	all_ions=get_ionlist(Z,dielec=dielec,chidir=chianti_topdir)

parameters
	z	[INPUT; required] atomic number
		* must be a scalar integer!

keywords
	chidir	[INPUT] path to CHIANTI top directory
		[default: /data/fubar/SCAR/CHIANTI/dbase]
	dielec	[OUTPUT] integer array of same size as output, specifying
		whether given ion refers to dielectronic recombination
		lines (1) or not (0)
	_extra	[JUNK] here only to prevent crashing program

requires subroutines
	SYMB2ZION
	IS_KEYWORD_SET

history
	vinay kashyap (Nov96; based on CHIANTI's SYNTHETIC.PRO)
	added keyword DIELEC, modified to include CHIANTIv3 dielectronic
	  recombination directories (VK; OctMM)
	handle trailing whitespace in masterlist.ions (VK; Jun02)
	updated for IDL5.6 keyword_set([0]) behavior change for vectors
	  (VK; 20Mar2006)

(See /data/fubar/SCAR/pro/mkemis/get_ionlist.pro)


GET_PIMMS_FILE

[Previous Routine] [Next Routine] [List of Routines]
function	get_pimms_file
	returns a string containing the name of the file containing the
	effective areas for the given instrument.

usage
	filnam=get_pimms_file(mission,instr,config,special=special,pdir=pdir)

parameters
	mission	[INPUT; required] e.g., 'ROSAT', 'AXAF', etc.
	instr	[INPUT] instrument (e.g., 'PSPC', 'ACIS', etc.)
	config	[INPUT] instrument configuration (e.g., 'OPEN', 'BI', etc.)

keywords
	special	[INPUT] any special requests
		* e.g., if MISSION='rosat', INSTR='pspc', and CONFIG='R4'
		and SPECIAL='R7', the output will be 'rosat_pspc_r4tor7.area'
	pdir	[INPUT; default='/soft/ciao/config/pimms/data/'] directory
		containing the PIMMS data files

history
	vinay kashyap (Mar98)
	changed PDIR default from /soft/prop_cli/config/pimms/data to
	  /soft/pimms/data (VK; Feb03)
	changed PDIR default from /soft/pimms/data to
	  /soft/ciao/config/pimms/data/ (VK; Mar06)

(See /data/fubar/SCAR/pro/specific/get_pimms_file.pro)


GMASCL

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

 PURPOSE:

       This is a utility routine to perform basic gray-level pixel
       transformations of images. I think of it as BYTSCL on steroids.
       It is similar to IMADJUST in _Digital Image Processing with MATLAB_
       by Gonzales, Wood, and Eddins.

 AUTHOR:

       FANNING SOFTWARE CONSULTING
       David Fanning, Ph.D.
       1645 Sheely Drive
       Fort Collins, CO 80526 USA
       Phone: 970-221-0438
       E-mail: davidf@dfanning.com
       Coyote's Guide to IDL Programming: http://www.dfanning.com

 CATEGORY:

       Utilities

 CALLING SEQUENCE:

       scaledImage = GMASCL(image)

 ARGUMENTS:

       image:         The image to be scaled. Written for 2D images, but arrays
                      of any size are treated alike.

 KEYWORDS:

       GAMMA:         The exponent in a power-law transformation (image^gamma). A gamma
                      value of 1 results in a linear distribution of values between
                      OMIN and OMAX. Gamma values less than 1 compress the
                      lower range of values and extend the upper range. Gamma values
                      greater than 1 compress the upper range of values and extend the
                      lower range. The gamma value is constrained to be greater than 1.0e-6.

       MAX:           Any value in the input image greater than this value is
                      set to this value before scaling.

       MIN:           Any value in the input image less than this value is
                      set to this value before scaling.

       NEGATIVE:      If set, the "negative" of the result is returned.

       OMAX:          The output image is scaled between OMIN and OMAX. The
                      default value is 255.

       OMIN:          The output image is scaled between OMIN and OMAX. The
                      default value is 0.
 RETURN VALUE:

       scaledImage:   The output, scaled into the range OMIN to OMAX. A byte array.

 COMMON BLOCKS:
       None.

 EXAMPLES:

       LoadCT, 0                                            ; Gray-scale colors.
       image = LoadData(11)                                 ; Load image.
       TV, GmaScl(image, Min=30, Max=100)                   ; Similar to BytScl.
       TV, GmaScl(image, /Negative)                         ; Produce negative image.
       power = Shift(ALog(Abs(FFT(image,-1))), 124, 124)    ; Create power spectrum.
       TV, GmaScl(power, Gamma=2.5)                         ; View power specturm with gamma correction.
       TV, GmaScl(power, Gamma=2.5, /Negative)              ; Reverse power spectrum.

 RESTRICTIONS:

     Requires SCALE_VECTOR from the Coyote Library:

        http://www.dfanning.com/programs/scale_vector.pro

 MODIFICATION HISTORY:

       Written by:  David W. Fanning, 17 February 2006.

(See /data/fubar/SCAR/pro/external/gmascl.pro)


GMODEL

[Previous Routine] [Next Routine] [List of Routines]
procedure	gmodel
		procedure written to be compatible with IDL's CURVEFIT
		GHRS-IDL's WFIT, etc.  computes F(X;A) and partial
		derivatives as needed.

syntax
	gmodel,x,a,f,pder

parameters	x	[INPUT; required] points at which to generate models
		a	[INPUT; required] array of parameter values
		f	[OUTPUT; required] output f=f(x;a)
		pder	[OUTPUT; optional] partial derivatives for each
			parameter

requires
	MK_3MODEL.PRO
	MK_GAUSS.PRO

history
	vinay kashyap (Nov96)

(See /data/fubar/SCAR/pro/gmodel.pro)


GRATFLX

[Previous Routine] [Next Routine] [List of Routines]
function	gratflx
	computes observed flux from spectral lines using LINEFLX
	and returns fluxes and wavelengths in a structure of structures.
	this is essentially a wrapper routine for LINEFLX to handle
	the case of multiple effective areas (as in different grating
	orders)

syntax
	ostr=gratflx(areas,line,logT,wvl,Z,wout=wout,fout=fout,$
	DEM=DEM,abund=abund,/ikev,/noph,/temp)

parameters
	areas	[INPUT; required] structure of structures containing
		effective area information in the form:
		  effective areas:	AREAS.(#).(0)	[cm^2]
		  wavelengths:		AREAS.(#).(1)	[Ang]
		  order:		AREAS.(#).(2)	[integer; default=1]
		  comment:		AREAS.(#).(3)	[string; default='']

	(the following are passed without comment to LINEFLX)

	line	[INPUT; required] array of line cooling emissivities
		in units of 1e-23 erg cm^3/s
		* if 2D array, LINE==LINE(logT,WVL)
		* WARNING: will return garbage if given 1D array LINE(WVL)
		  use a for-loop to handle such a case
		* WARNING: will get converted to 1-element vector if input
		  as scalar
	logT	[INPUT; required] array of log10(Temperature [K]) at
		which emissivities are given.
		* array size MUST match that of LINE
	wvl	[INPUT; required] wavelength(s) [Angstrom] of lines at
		which LINE is given
		* array size MUST match LINE
	Z	[INPUT] atomic number of element that generates each WVL
		* if Z has less elements than WVL, Z is ignored
		* if Z is to be ignored, all lines are assumed to be from
		  same element, and abundance values are ignored

keywords
	wout	[OUTPUT] all the "translated" wavelengths
	fout	[OUTPUT] all the fluxes
	_extra	[INPUT] use this to pass defined keywords to subroutines
		LINEFLX -- DEM, ABUND, IKEV, NOPH, TEMP

history
	vinay kashyap (Oct98)
	added keywords WOUT, FOUT; ability to handle "bad" AREAS (VK;Nov98)

(See /data/fubar/SCAR/pro/gratflx.pro)


HAARLINE

[Previous Routine] [Next Routine] [List of Routines]
function	haarline
	return the best guesses for the locations of lines in a
	1D spectrum, in units of the position index, using Haar
	wavelet transforms (hence the name)

	gets the filtered transform at multiple scales, and starting
	from the smallest scale, determines line locations by averaging
	over contiguous regions weighted by the wavelet transform.
	at succeedingly larger scales, the value of the computed line
	location is updated if the max of the transform is greater
	than before, and ignored if (a) if it is not, and (b) if the
	support of the line at this scale contains more than one line
	at smaller scales.

syntax
	xpos=haarline(y,scales,xerr=xerr,thrct=thrct,sclout=sclout,$
	sclmin=sclmin,sclmax=sclmax,ysig=ysig,thrsig=thrsig,$
	thrloc=thrloc,verbose=verbose,hy=hy,wy=wy)

parameters
	y	[INPUT; required] 
	scales	[I/O] if given on input as an integer array, computes
		the Haar transforms at these scales.
		* if illegal in any way, is calculated using SCLMIN and SCLMAX

keywords
	xerr	[OUTPUT] the 1-sigma errors on the line locations, also
		in units of array indices
	thrct	[INPUT; default=10] minimum signal in the reconstructed
		function before calling it a line
	sclout	[OUTPUT] the scale at which the line is detected
	sclmin	[INPUT; default=4, hardcoded minimum=1] lowest scale in
		wavelet transform
	sclmax	[INPUT; default=32, hardcoded maximum=N(Y)/6] highest scale
		in wavelet transform
		* scales go from SCLMIN to SCLMAX in powers of 2
		* if SCLMIN and SCLMAX are not integers, the ceiling is used
		* if SCLMIN and SCLMAX are not powers of 2, the nearest
		  power of 2 smaller than them are used
	verbose	[INPUT] controls chatter
	wy	[OUTPUT] the wavelet correlation coefficients, output of HAARTRAN()
	hy	[OUTPUT] the filtered coefficients, output of HAARTRAN()
	_extra	[INPUT ONLY] pass defined keywords to subroutine HAARTRAN():
		-- YSIG 	default is Poisson for counts, 0 otherwise
		-- THRSIG 	default is 1.0
		-- THRLOC 	set by default, explicitly set to 0 if unwanted

subroutines
	HAARTRAN
	KILROY
	IS_KEYWORD_SET

history
	vinay kashyap (Dec'02)
	updated for IDL5.6 keyword_set([0]) behavior change for vectors
	  (VK; 20Mar2006)

(See /data/fubar/SCAR/pro/haarline.pro)


HAARTRAN

[Previous Routine] [Next Routine] [List of Routines]
function	haartran
	Run the input 1D array through a sequence of Haar wavelets,
	and return the filtered wavelet transform coefficients.

	convolves Y with Haar wavelet at different scales; at each
	scale, a threshold is applied, either a global one based on
	the histogram of the wavelet coefficients or a local one based
	on the propagated error or a local one based on the local
	background and the probability of fluctuations; the filtered
	coefficients are returned in a 2D array, the first row of
	which contains the "reconstructed/denoised" Y.

	a Haar wavelet is simply a boxcar with a moat.

syntax
	hy=haartran(y,scales,ss,ysig=ysig,thrsig=thrsig,/thrloc,$
	thrpoi=thrpoi,wy=wy,verbose=v)

parameters
	y	[INPUT; required] the input 1D function, assumed to
		be on a regular grid
	scales	[INPUT] scales at which to construct the Haar wavelets
		* must be integer
		* if not specified, then taken to be integers going in
		  powers of 2 from 1..(N(Y)/6)
		  (6 because the kernel width is actually 3*scale, and
		  you want to go only so far as to fill half of Y, it
		  would be useless beyond that)
		* if array, taken to be the actual wavelet scales given
		  in bin or pixel units
		* if scalar, taken to be the _number_ of scales to be
		  considered, 1..2^(SCALES)
		* in all cases, maximum scale size must be < N(Y)/6
		  (scales higher than that are simply ignored)
	ss	[OUTPUT] the scales at which the wavelet is applied

keywords
	ysig	[INPUT] error on Y
		* if not given, and Y are integers and max(Y)>1, then assumed
		  to be sqrt(abs(Y)+0.75)+1, else 0
		* if given and is a scalar, then
		  -- if <0, the abs value is assumed to be a constant error
		  -- if >0 and <1, assumed to be a constant fractional error
		  -- if >1 and <100, assumed to be a constant percentage error
		  -- if >100, assumed to be a constant additive error
		* if an array and size does not match N(Y), then ignored
		* used only if THRLOC is set
	thrsig	[INPUT; default=1] threshold sigma to use for filtering
		* if THRLOC is set, then filter out all wavelet coefficients
		  with values < THRSIG*local_error
		* if THRLOC is not set (default), filter out all wavelet
		  coefficients with values<(mean_of_dist+THRSIG*stddev_of_dist)
		* note that this does _not_ imply a probablity of false
		  detection or anything of that ilk.  this is just a number,
		  use it as such.
	thrloc	[INPUT] if set, filters wavelet coefficients based on a
		locally computed error
	thrpoi	[INPUT] if set, first estimates a local background at each
		bin at the given scale, and then sets the local threshold
		such that at most THRPOI bins are found to be false lines
		over the range of Y (i.e., sets a probability threshold
		locally at THRPOI/N(Y))
		* if set, overrides THRLOC and ignores THRSIG
	wy	[OUTPUT] _all_ the computed coefficients, without any filtering,
		for those that may wish to apply a more rigorous filtering,
		as a 2D array of size (N(SCALES),N(Y))
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to avoid crashing the program

subroutines
	KILROY

history
	vinay kashyap (Dec'02)

(See /data/fubar/SCAR/pro/haartran.pro)


HASTOGRAM

[Previous Routine] [Next Routine] [List of Routines]
function	hastogram
	returns a frequency histogram over a specified grid,
	calculated in a fast and clever way.  really.
	works in haste, without waste.

	works best when the grid is sparsely populated.
	if there are more items than bins, use IDL's
	built-in HISTOGRAM() function instead.

syntax
	f=hastogram(list,x,wts=wts,verbose=verbose)

parameters
	list	[INPUT; required] list of numbers to bin
	x	[I/O] the required binning scheme
		* if not set, assumes a linear grid of size 100 from
		  min(LIST) to max(LIST)
		* if scalar or 1-element vector, assumes this to be the
		  number of bins
		  * if -ve, log grid, else linear
		* if vector with more than 1 element, assumes it to be
		  the bin boundaries.
		* WARNING: if input as scalar, will overwrite with the
		  adopted grip on output

keywords
	wts	[INPUT] if given, appropriately weights each element of LIST
		* default is unity
		* if size does not match size(LIST), will be appropriately
		  interpolated
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to prevent crashing the program

description
	the problem is the following: if the number of bins is large,
	accumulating a frequency histogram by linear search takes too
	long, esp. in IDL if one uses for-loops.
	so, first create a monster array containing both the list elements
	and the grid values.  then sort this array.  this results in an
	array where the list elements are all nicely placed within the
	correct bins.  now, if we've been keeping track of the positions
	of the list elements, it's an easy job to count up the number in
	each bin of the grid.  to do the latter, we first create a new
	array made up of -1s in positions of list elements and position
	indices for grid values and reorder according to the above sort.
	then, replace each -1 by the nearest non-(-1) from the left.  now
	each list element is assigned the correct bin number.  voila!

restrictions
	X must be sorted in increasing order.
	(no longer, as of Jun02)

subroutines
	KILROY

history
	vinay kashyap (Jan98)
	added kludge to speed up in case max(X) < max(LIST) (VK; Sep98)
	added quit in case X is not sorted in ascending order (VK; JanMMI)
	added keyword VERBOSE, and removed restriction on order of X
	  (VK; Jun02)
	changed ints to longs (VK; Aug08)

(See /data/fubar/SCAR/pro/misc/hastogram.pro)


HAWALINER

[Previous Routine] [Next Routine] [List of Routines]
function	hawaliner
	returns the wavelengths at which spectral lines are found
	to be located in the high-resolution counts spectrum

syntax
	linewvl=hawaliner(counts,wave,wrange=wrange,lsffwhm=lsffwhm,$
	maxkern=maxkern,clev=clev,maxiter=maxiter,/fullerr,verbose=verbose,$
	hawastr=hawastr,kkcont=kkcont,ctline=ctline,wscale=wscale,$
	wcont=wcont,ewcont=ewcont,lpos=lpos,lerrpos=lerrpos,$
	lflx=lflx,lerrflx=lerrflx,$
	lwdt=lwdt,lerrwdt=lerrwdt,type=type)

parameters
	counts	[INPUT; required] counts spectrum
		* this routine was developed for integer counts spectra, but
		  currently no explicit assumption of Poisson distributions
		  is made, and it _ought_ to work for spectral intensities
		  in any units -- but no guarantees!
	wave	[INPUT; required] wavelength grid for the spectrum
		* if size matches that of COUNTS, taken to be mid-bin values
		* if size exceeds COUNTS by 1, taken to be grid boundaries
		* if size is double that of COUNTS, taken to be two
		  concatenated arrays of lower and upper boundaries of grid
		* it is assumed that WAVE is on a regular grid, i.e., that
		  WAVE[1:*]-WAVE is constant

keywords
	wrange	[INPUT] range of wavelengths to consider in the analysis
		* if not given, or is not a 2D array, a range that includes
		  99% of the total counts that includes the peak of the
		  spectrum is used
	lsffwhm	[I/O] fwhm of the spectral lines, in same units as WAVE
		* forced to be greater than the FWHM of the strongest line
		  in the spectrum
		* if given, ignores all kernels that are smaller than this
		* it is assumed that LSFFWHM does not vary significantly
		  across the spectrum
		* if undefined, then the program will calculate it internally
		  (by finding the highest point in the spectrum and walking
		  down the slopes) and this calculated will be returned on
		  output
		* TO REITERATE: if defined on input, will be unchanged on output
	maxkern	[INPUT] maximum kernel size to use, in bins
		* by default, we start with a kernel of size 3 and increase
		  the scale such that the central +ve part of the next scale
		  is as large as the full extent of the previous scale
		* if not given, set to a size corresponding to 30*LSFFWHM
	clev	[INPUT] the confidence level at which to filter the
		correlation coefficients
		* default is 0.95
		* if < 0, abs(CLEV) is used
		* if > 1 and < 100, then assumed to be given as a percentage
		* if > 100, then 1-1/CLEV is used
	maxiter	[INPUT] maximum number of iterations
		* default is 10
		* hardcoded minimum is 2
	fullerr	[INPUT] if set, calls MCERROR to derive better error bars
		* WARNING: this can slow the program to a crawl
	hawastr	[OUTPUT] a structure that contains all sorts of useful arrays:
		{filtered WAVE, filtered COUNTS, wavelength range,
		scales, LSF width, estimated continuum, filtered continuum,
		line pos, line pos error, line flux, line flux error,
		line width, line width error}
	kkcont	[OUTPUT] the continuua calculated at each scale
		* this is an array of size [WVL,SCALES], where WVL
		  is a filtered version of WAVE (see HAWASTR.X)
	ctline	[OUTPUT] the line "spectrum" devoid of continuum
		* on same grid as WAVE
	wcont	[OUTPUT] the continuum "spectrum" devoid of lines
		* on same grid as WAVE
	ewcont	[OUTPUT] error on WCONT
		* on same grid as WAVE
		* note that the errors on each bin are highly correlated
		  with those at adjacent bins and should not be assumed to
		  be independent
	wscale	[INPUT] the kernel sizes to be used in the calculation
		* the actual width of the wavelets will be 3*WSCALE
		* if not given, will be calculated as
		  2*LSFFWHM/dWAVE*[1,3,...,NBIN/3]/3
	lpos	[OUTPUT] the positions of the detected lines
		* (same as primary output)
	lerrpos	[OUTPUT] errors on LPOS
	lflx	[OUTPUT] the fluxes of the detected lines
	lerrflx	[OUTPUT] errors on LFLX
	lwdt	[OUTPUT] the widths of the detected lines
	lerrwdt	[OUTPUT] errors on LWDT
	verbose	[INPUT] controls chatter
	_extra	[INPUT ONLY] pass defined keywords to subroutines
		FIT_LEVMAR : TYPE

description
	carries out a wavelet-like analysis, by computing the correlations
	of the counts spectrum with Haar-like wavelets, and identifies bins
	that are likely to have lines, finds the nearest local maximum
	in the data corresponding to each identified line, and computes
	their mean location

subroutines
	HIPD_INTERVAL()
	MID2BOUND()
	GETLOCMAX()
	FIT_LEVMAR
	MCERROR
	ADJUSTIE()
	LEVMARQ
	LMCOEFF
	LNPOISSON()

history
	Vinay Kashyap (Apr2007)
	added call to MCERROR, included SIGY in call to FIT_LEVMAR,
	  changed CTCONT to KKCONT, added keyword EWCONT (VK; Jun2007)
	various tweaks and bug fixes, changed behavior of WSCALE
	  and LSFFWHM (VK; Jul2008)

about the name
	It is a Haar-like Wavelet-based line finding program, so works
	for the purpose of taking up a unique spot in namespace.  Well,
	unique at least until the Indians decide to make a luxury airliner.

(See /data/fubar/SCAR/pro/hawaliner.pro)


HINODE_XRT_EMIS

[Previous Routine] [Next Routine] [List of Routines]
function	hinode_xrt_emis
	compute and return the combined emissivities of Hinode/XRT
	filters in an array of form [Ntemp,Nfilt] in units of
	[1d-23 ergs cm^5/s] for each pixel

syntax
	xrtemis=hinode_xrt_emis(filter,tgrid,ldbdir=ldbdir,$
	cdbdir=cdbdir,ioneqf=ioneqf,abund=abund,cieroot=cieroot,$
	n_e=n_e,NH=NH,xrteff=xrteff,lstr=lstr,cstr=cstr,$
	/toel,/toph,/toDN,EM0=EM0,pixsize=pixsize,verbose=verbose,$
	chidir=chidir,fH2=fH2,He1=He1,HeII=HeII)

parameters
	filter	[INPUT; required] scalar or array of filter names
		* for Hinode/XRT, acceptable filter names are
		  Al-mesh, Al-poly, C-poly, Ti-poly, Be-thin,
		  Be-med, Al-med, Al-thick, Be-thick,
		  Al-poly/Al-mesh, Al-poly/Ti-poly, Al-poly/Al-thick,
		  Al-poly/Be-thick, C-poly/Ti-poly
		* set to 'all' to get everything
	tgrid	[I/O] the log(T[K]) grid over which the output
		is to be defined
		* if not specified on input, will be set to be
		  the same as that in the emissivity tables,
		  the PoA default, findgen(81)*0.05+4

keywords
	ldbdir	[INPUT; '$CHIANTI'] line emissivity database directory
	cdbdir	[INPUT; '$CONT'] continuum emissivity database directory
	ioneqf	[INPUT; 'ioneq/mazzotta_etal.ioneq'] location of the
		ion fraction tables
	abund	[INPUT; getabund('Grevesse et al')] abundances
	cieroot	[INPUT; 'cie'] root name for the files in $CONT
	n_e	[INPUT; 1e9] electron number density in the plasma
	NH	[INPUT; 0] H column density to apply
	xrteff	[I/O] the XRT effective areas; input can be any of the
		following:-
		- a structure that contains the following fields --
		  {TYPE, CHANNEL_NAME, WAVE, EFF_AREA, LENGTH}
		  which can be generated using the SSW routine
		  xrteff = MAKE_XRT_WAVE_RESP(contam_time=contam_time)
		- the name of a save file that contains the previously
		  generated structure, named either XRTEFF or EFF
		- a flag that indicates that this must be calculated
		  in situ by calling MAKE_XRT_WAVE_RESP() (requires SSW)
		  - this can be accomplished by setting /XRTEFF, but
		    that will prevent it from being returned up.  instead,
		    it is better to do something like
		    xrteff=1 & xrtemis=hinode_xrt_emis(...,xrteff=xrteff,...)
		* on output, will always contain the structure that
		  was read in or calculated
	lstr	[OUTPUT] line emissivities structure, as read in
		from RD_LINE()
	cstr	[OUTPUT] continuum emissivities structure, as read in
		from RD_CONT()
	toel	[INPUT; default=0] if set, returns the output in units
		of [el cm^5/s]
	toph	[INPUT; default=0] if set, returns the output in units
		of [ph cm^5/s]
	toDN	[INPUT; default=0] if set, returns the output in units
		of [DN cm^5/pix]
		* NOTE: TODN overrides TOPH overrides TOEL
	EM0	[INPUT; default=1] if set, multiples the output by
		this value to derive [ph/s] or [ph/cm^2/s] depending
		on whether the input has units [cm^-3] or [cm^-5]
	pixsize	[INPUT; default=1.0024 arcsec] the size of a pixel on
		the detector
	xrtl	[OUTPUT] the response due solely to lines
	xrtc	[OUTPUT] the response due solely to continuum
		* both XRTL and XRTC are identical in size and units
		  to the primary output, XRTEMIS
	verbose	[INPUT; default=0] controls chatter
	_extra	[INPUT ONLY] pass defined keywords to subroutines
		FOLD_IONEQ : CHIDIR
		ISMTAU : FH2, HE1, HEII
		MAKE_XRT_WAVE_RESP : INDEX, CONTAM_THICK, CONTAM_TIME

history
	vinay kashyap (Jun2007)
	added keywords TOEL, PIXSIZE, XRTL, XRTC (VK; Mar2008)
	changed call from CALC_XRT_EFFAREA() to MAKE_XRT_WAVE_RESP() (VK; Apr2009)
	bugfix: FILTER was failing to match to XRTEFF.NAME when specified
	  (VK; Nov2009)

(See /data/fubar/SCAR/pro/solar/hinode_xrt_emis.pro)


HIPD_INTERVAL

[Previous Routine] [Next Routine] [List of Routines]
function	hipd_interval
	computes and returns the interval [lower_bound,upper_bound] at a
	specified confidence level that includes the highest probability
	densities.  by definition, this is the shortest possible interval.

syntax
	hpd=hipd_interval(f,x,/fsample,clev=clev,pdfnorm=pdfnorm,$
	fmode=fmode,verbose=verbose)

parameters
	f	[INPUT; required] the array for which the confidence interval
		must be computed
		* assumed to be a density function unless FSAMPLE is set
	x	[INPUT; optional] abscissae values
		* if not given, and F is a density function, then taken
		  to be the array indices
		* ignored if FSAMPLE is set
		* if N(X).GT.1 but N(X).NE.N(F), X is ignored and
		  FSAMPLE is set automatically

keywords
	fsample	[INPUT] if set, assumes that F is a set of samples from a
		density function, as opposed to being the density function
		itself
	clev	[INPUT] confidence level at which to compute the intervals
		* default is 0.68
		* if < 0, abs(CLEV) is used
		* if > 1 and < 100, then assumed to be given as a percentage
		* if > 100, then 1-1/CLEV is used
	pdfnorm	[INPUT] if set, forces F to integrate to abs(PDFNORM)
		* if explicitly set to 0, does not normalize F at all
		* if not set, normalizes to 1
		* ignored if FSAMPLE is set
		* WARNING: do not use this keyword unless you know
		  what you are doing
	fmode	[OUTPUT] the mode of the distribution
	verbose	[INPUT] controls chatter
	_extra	[INPUT ONLY] pass defined keywords to subroutines
		MODALPOINT: EPS

subroutines
	MODALPOINT

description
	* if density function, find the cumulative integral around the
	  mode and interpolate at CLEV to derive the HPD interval
	* if array of sample values, find all intervals corresponding to
	  CLEV that contain the mode and pick the smallest of the lot.
	  this is a method devised by Vinay K and Taeyoung Park during
	  the course of developing BEHR.
	* works well only for unimodal distributions, but that's better
	  than nothing.

example
	for i=1,20 do print,hipd_interval(randomn(seed,10000L)*i,/fsample)

history
	vinay kashyap (Mar2006)
	bug correction with FSAMPLE cdf (VK; Apr2006)
	added keyword FMODE (VK; Nov2006)
	bug correction with F(X) case (VK; Apr2007)

(See /data/fubar/SCAR/pro/stat/hipd_interval.pro)


HIPD_INTERVAL2

[Previous Routine] [Next Routine] [List of Routines]
function	hipd_interval
	computes and returns the interval [lower_bound,upper_bound] at a
	specified confidence level that includes the highest probability
	densities.  by definition, this is the shortest possible interval.

syntax
	hpd=hipd_interval(f,x,/fsample,clev=clev,pdfnorm=pdfnorm,$
	verbose=verbose)

parameters
	f	[INPUT; required] the array for which the confidence interval
		must be computed
		* assumed to be a density function unless FSAMPLE is set
	x	[INPUT; optional] abscissae values
		* if not given, and F is a density function, then taken
		  to be the array indices
		* ignored if FSAMPLE is set
		* if N(X).GT.1 but N(X).NE.N(F), X is ignored and
		  FSAMPLE is set automatically

keywords
	fsample	[INPUT] if set, assumes that F is a set of samples from a
		density function, as opposed to being the density function
		itself
	clev	[INPUT] confidence level at which to compute the intervals
		* default is 0.68
		* if < 0, abs(CLEV) is used
		* if > 1 and < 100, then assumed to be given as a percentage
		* if > 100, then 1-1/CLEV is used
	pdfnorm	[INPUT] if set, forces F to integrate to abs(PDFNORM)
		* if explicitly set to 0, does not normalize F at all
		* if not set, normalizes to 1
		* ignored if FSAMPLE is set
		* WARNING: do not use this keyword unless you know
		  what you are doing
	fmode	[OUTPUT] the mode of the distribution
	verbose	[INPUT] controls chatter
	_extra	[INPUT ONLY] pass defined keywords to subroutines
		MODALPOINT: EPS

subroutines
	MODALPOINT

description
	* if density function, find the cumulative integral around the
	  mode and interpolate at CLEV to derive the HPD interval
	* if array of sample values, find all intervals corresponding to
	  CLEV that contain the mode and pick the smallest of the lot.
	  this is a method devised by Vinay K and Taeyoung Park during
	  the course of developing BEHR.
	* works well only for unimodal distributions, but that's better
	  than nothing.

example
	for i=1,20 do print,hipd_interval(randomn(seed,10000L)*i,/fsample)

history
	vinay kashyap (Mar2006)
	bug correction with FSAMPLE cdf (VK; Apr2006)
	added keyword FMODE (VK; Nov2006)
	bug correction with F(X) case (VK; Apr2007)

(See /data/fubar/SCAR/pro/stat/hipd_interval2.pro)


HIRES2LOWRES

[Previous Routine] [Next Routine] [List of Routines]
 procedure     hires2lowres
         given filenames containing HETG HEG and MEG PHA data,
         calculated ARFs, and ACIS ARFs and RMFs, predict what would
         be observed with ACIS-S or ACIS-I (without gratings) 

 syntax
         make_lowres,hphafile,mphafile,hgarffile,mgarffile,$
         hhetgwvl,hhetgcts,mhetgwvl,mhetgcts,hetgwvl,hhetgflx,$
         hhetgflxerr,mhetgflx,mhetgflxerr,tothetgflx,tothetgflxerr,$
         aciswvl,aciscts,aciserr,hphahdr,mphahdr,hgarfhdr,mgarfhdr,$
         acisarffile,acisrmffile,debug=debug

 parameters
         hphafile     [INPUT; required] PHA type I spectral file
                      containing the HEG HETG spectrum for a given
                      order
         mphafile     [INPUT; required] PHA type I spectral file
                      containing the MEG HETG spectrum for a given
                      order
         hgarffile    [INPUT; required] Gratings ARF corresponding to
                      the HEG PHA file
         mgarffile    [INPUT; required] Gratings ARF corresponding to
                      the MEG PHA file
         hhetgwvl     [OUTPUT; required] The midpoints of the HEG
                      wavelength bins
                      * units are Angstroms
         hhetgcts     [OUTPUT; required] The background-subtracted
                      counts spectrum extracted from the HEG PHA file
                      * units are [cts/s/AA]
         mhetgwvl     [OUTPUT; required] The midpoints of the MEG
                      wavelength bins
                      * units are Angstroms
         mhetgcts     [OUTPUT; required] The background-subtracted
                      counts spectrum extracted from the MEG PHA file
                      * units are [cts/s/AA]
         hetgwvl      [OUTPUT; required] The midpoints of the common
                      HEG, MEG, and HEG+MEG flux spectrum's
                      wavelength grid 
                      * grid extends ~0-30 AA at HEG resolution
         hhetgflx     [OUTPUT; required] Adaptively-smoothed,
                      background-subtracted HEG flux spectrum
                      * units are [ph/s/cm^2/AA]
         hhetgflxerr  [OUTPUT; required] The error on the HEG flux
                      spectrum
         mhetgflx     [OUTPUT; required] Adaptively-smoothed,
                      background-subtracted MEG flux spectrum
                      * units are [ph/s/cm^2/AA]
         mhetgflxerr  [OUTPUT; required] The error on the MEG flux
                      spectrum
         tothetgflx   [OUTPUT; required] Adaptively-smoothed,
                      background-subtracted coadded HEG+MEG flux
                      spectrum
                      * units are [ph/s/cm^2/AA]
         tothetgflxerr [OUTPUT; required] The error on the coadded
                      HEG+MEG flux spectrum
         aciswvl      [OUTPUT; required] The midpoints of the
                      predicted ACIS spectrum's wavelength grid
         aciscts      [OUTPUT; required] The predicted ACIS spectrum
                      * units are [cts/s/AA]
         aciserr      [OUTPUT; required] The error on the predicted
                      ACIS spectrum
         hphahdr      [OUTPUT; required] The header of the HEG PHA
                      file
         mphahdr      [OUTPUT; required] The header of the MEG PHA
                      file
         hgarfhdr     [OUTPUT; required] The header of the HEG gARF
                      file
         mgarfhdr     [OUTPUT; required] The header of the MEG gARF
                      file
         acisarffile  [INPUT; required] The ACIS ARF
         acisrmffile  [INPUT; required] The ACIS RMF

 keywords
         debug        [INPUT] controls debugging chatter

 restrictions
         requires conv_rmf, smoothie, and rebinw from PINTofALE,
         available at http://hea-www.harvard.edu/PINTofALE/

 history
         Owen Westbrook, Peter Mendygral, and John Slavin (Mar07)

(See /data/fubar/SCAR/pro/esempio/hires2lowres.pro)


HRCS_GEOM

[Previous Routine] [Next Routine] [List of Routines]
function	hrcs_geom
	incorporates the HRC-S/LETG geometry and converts to/from
	dispersion coordinate/dispersion angle

	given source location and position on detector in mm, returns
	the appropriate wavelength, and vice versa.

syntax
	y=hrcs_geom(x,offaxis=offaxis,rowd=rowd,Sdelta=Sdelta,$
	tilt1=tilt1,tilt2=tilt2,tilt3=tilt3,w1=w1,w3=w3,wl=wl,wr=wr,$
	e12=e12,e21=e21,e23=e23,e32=e32, order=order,dper=dper,$
	/ang2mm, gaps=gaps)

parameters
	x	[INPUT; required] dispersion coordinate
		(or wavelength if ANG2MM is set)

keywords
	offaxis	[INPUT; 0 arcmin] offset of 0th order source
		relative to nominal
	rowd	[INPUT; 8637 mm] diameter of Rowland circle
	Sdelta	[INPUT; 0.1 mm] offset of plate S2 from best
		focus at nominal position
	tilt1	[INPUT; 178.5679 deg] tilt of plate S1
	tilt2	[INPUT; 0.0 deg] tilt of plate S2
	tilt3	[INPUT; 1.2202 deg] tilt of plate S3
	w1	[INPUT; 103 mm] length of plate S1
	w3	[INPUT; 103 mm] length of plate S3
	wl	[INPUT; 48 mm] length of plate S1 left of nominal 0th order
	wr	[INPUT; 55 mm] length of plate S1 right of nominal 0th order
	e12	[INPUT; 0 mm] from edge of S1 to intersection of plane of S2
	e21	[INPUT; 0 mm] from edge of S2 to intersection of plane of S1
	e23	[INPUT; 0 mm] from edge of S2 to intersection of plane of S3
	e32	[INPUT; 0 mm] from edge of S3 to intersection of plane of S2
	order	[INPUT; 1] in order to convert from angle to angstrom for
		higher orders
	dper	[INPUT; 9912.5 Ang] grating period
	ang2mm	[INPUT; 0] if set, assumes that X are in wavelengths in
		[Ang] and converts to [mm]
	gaps	[OUTPUT] wavelengths corresponding to the edges of the plates
		in the order [lS1,rS1, lS2,rS2, lS3,rS3]
	_extra	[JUNK] here only to prevent crashing the program

description
	file://localhost/data/toad1/kashyap/Olivia/hrcs_geom_fig.ps
	file://localhost/data/toad1/kashyap/Olivia/hrcs_geom_dvi.ps

history
	vinay kashyap (JunMM)
	ROWD changed (VK; FebMMI)

(See /data/fubar/SCAR/pro/specific/hrcs_geom.pro)


HRCS_PROCESS_EVT

[Previous Routine] [Next Routine] [List of Routines]
procedure	hrcs_process_evt
	process HRC-S amplifier data to produce positions

syntax
	hrcs_process_evt,chip_id,au1,au2,au3,av1,av2,av3,amp_sf,crsu,crsv,$
	pha,statbit, ampscl,fineu,finev,fracu,fracv,u,v,au3cor=au3cor,av3cor=av3cor,$
	rawu=rawu,rawv=rawv,xdet=xdet,ydet=ydet,Hfilt=Hfilt,HXfilt=HXfilt,$
	caldb=caldb,degaps=degaps,degapf=degapf,tringf=tringf,$
	dampcor=dampcor,ampgain_s=ampgain_s,ampratio_s=ampratio_s,$
	pha_rng_min=pha_rng_min,pha_rng_mid=pha_rng_mid,pha_rng_max=pha_rng_max,$
	hevt=hevt,rangelev=rangelev,$
	pha_1to2=pha_1to2,pha_2to3=pha_2to3,w_1to2=w_1to2,w_2to3=w_2to3,$
	va=va,vb=vb,vc=vc,vd=vd,vbeta=vbeta,vgamma=vgamma,vthr=vthr,$
	ua=ua,ub=ub,uc=uc,ud=ud,ubeta=ubeta,ugamma=ugamma,uthr=uthr,$
	vBh=vBh,vHh=vHh,vAh=vAh,vdHh=vdHh,$
	uBh=uBh,uHh=uHh,uAh=uAh,udHh=udHh,$
	verbose=verbose

parameters
	chip_id	[INPUT; required] on which plate did the count register?
	au1	[INPUT; required] U tap signal from amplifier 1
	au2	[INPUT; required] U tap signal from amplifier 2
	au3	[INPUT; required] U tap signal from amplifier 3
	av1	[INPUT; required] V tap signal from amplifier 1
	av2	[INPUT; required] V tap signal from amplifier 2
	av3	[INPUT; required] V tap signal from amplifier 3
	amp_sf	[INPUT; required] amplifier scale
	crsu	[INPUT; required] U tap (coarse position)
	crsv	[INPUT; required] V tap (coarse position)
	pha	[INPUT; required] event pulse height amplitudes
	statbit	[INPUT; required] status bits
	ampscl	[OUTPUT] rescaled AMP_SF, according to PHA range
	fineu	[OUTPUT] U fine position based on AU1,AU2,AU3
	finev	[OUTPUT] V fine position based on AU1,AU2,AU3
	fracu	[OUTPUT] fraction of center-tap events in U
	fracv	[OUTPUT] fraction of center-tap events in V
	u	[OUTPUT] degapped U position
	v	[OUTPUT] degapped V position

keywords
	au3cor	[OUTPUT] tap ringing corrected AU3
	av3cor	[OUTPUT] tap ringing corrected AV3
	rawu	[OUTPUT] V converted to raw detector coordinates
	rawv	[OUTPUT] U converted to raw detector coordinates
	xdet	[OUTPUT] RAWV converted to detector X coordinates *** NOT IMPLEMENTED ***
	ydet	[OUTPUT] RAWU converted to detector Y coordinates *** NOT IMPLEMENTED ***
	Hfilt	[OUTPUT] indices of all photons that pass the H-test
	HXfilt	[OUTPUT] indices of all photons that fail the H-test
	caldb	[INPUT] the location of the Chandra CALDB
		* if not set, assumed to be /soft/ciao/CALDB/
	degapf	[INPUT] CALDB file containing the degap coefficients
		* if not set (and DEGAPS is not set), read from file
		$CALDB/data/chandra/hrc/bcf/degap/hrcsD1999-07-22gapN0002.fits
		* if string, read from specified file
		* ignored if DEGAPS is well-defined
	degaps	[I/O] the degap coefficients in a structure of the
		format defined by the file DEGAPF
		* if not set, read in from DEGAPF
		* if set and passes rudimentary format checks, ignores
		  DEGAPF and uses these values
		* if set and does not pass rudimentary format checks,
		  will be overwritten by the contents of DEGAPF
		* if set to 0, will NOT remove gaps
	tringf	[INPUT] CALDB file containing the tap ringing coefficients
		* must be pathname relative to CALDB, e.g.,
		  '/data/chandra/hrc/bcf/tapring/hrcsD1999-07-22tapringN0001.fits'
		* if not defined, then looks at keywords
		    VA,VB,VC,VD,VBETA,VGAMMA,VTHR,VOFF,
		    UA,UB,UC,UD,UBETA,UGAMMA,UTHR,UOFF
		  for the values, which btw default to the values in
		  $CALDB/data/chandra/hrc/bcf/tapring/hrcsD1999-07-22tapringN0001.fits
	dampcor	[INPUT] if set, dynamically determines the PHA range
		over which the SUMAMPS scale changes
	hevt	[INPUT] the header from the EVT1 file, to be used to
		determine the value of RANGELEV
		* see http://cxc.harvard.edu/ciao/threads/hrc_ampsf/
		* if RANGELEV or DATE-OBS is present, overrides keyword input
	ampgain_s,ampratio_s,pha_rng_min,pha_rng_mid,pha_rng_max,rangelev,pha_1to2,pha_2to3,w_1to2,w_2to3
		[INPUT] AMP_SF scale correction parameters
	va,vb,vc,vd,vbeta,vgamma,vthr	[INPUT] tap-ringing coefficients
	ua,ub,uc,ud,ubeta,ugamma,uthr	[INPUT] tap-ringing coefficients
	vBh,vHh,vAh,vdHh	[INPUT] H-test coefficients
	uBh,uHh,uAh,udHh	[INPUT] H-test coefficients
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to avoid crashing the program

history
	vinay kashyap (Apr02)
	added keyword HEVT,RANGELEV (VK; Aug03)
	added keywords TRINGF,UOFF,VOFF, and changed algorithm on which
	  events to apply tap ringing correction (VK; Sep03)

(See /data/fubar/SCAR/pro/specific/hrcs_process_evt.pro)


HRC_DTF_FILTER

[Previous Routine] [Next Routine] [List of Routines]
function	hrc_dtf_filter
	computes the average dead-time correction factor
	for a new set of good time intervals obtained after
	filtering the existing DTF file

syntax
	dtcor=hrc_dtf_filter(dtffil,tstart,tstop,gtibeg=gtibeg,gtiend=gtiend,$
	dtfthr=dtfthr,gtifil=gtifil,verbose=verbose,$
	leap=leap,fitsref=fitsref,exten=exten,fitshdr=fitshdr,form=form,page=page)

parameters
	dtffil	[INPUT; required] full path name to the dtf file
	tstart	[OUTPUT] the new start times of the GTIs
	tstop	[OUTPUT] the new stop times of the GTIs

keywords
	gtibeg	[INPUT] beginning times for any GTI that should also
		be included
	gtiend	[INPUT] ending times for GTIs corresponding to GTIBEG
		* GTIBEG and GTIEND may be arrays
		* the sizes of GTIBEG and GTIEND must match or else
		  both are ignored
	dtfthr	[INPUT] the threshold dead-time correction factor
		below which to ignore time bins
		* default=0.99
	gtifil	[INPUT] full path name of the output file that will
		contain the list of TSTART and TSTOP -- this can be
		used as a filter in dmcopy to do the actual filtering
		* if not set or the name contains "none", will not
		  be written out
		* if set to number, assumes that the file should be
		  named 'hrc_dtf_filter_gti_GTIFIL.txt'
		* if name ends in .fit, .fits, .ft, or .mt then
		  writes out a FITS file, otherwise an ASCII file
	verbose	[INPUT] controls chatter
	_extra	[INPUT ONLY] pass defined keywords to subroutines
		TI_CLEAN: LEAP
		TI_WRITE: FITSREF, EXTEN, FITSHDR, FORM, PAGE

subroutines
	mrdfits
	ti_clean
	ti_write
	ti_and
	ti_filter

history
	vinay kashyap (Sep2006)

(See /data/fubar/SCAR/pro/specific/hrc_dtf_filter.pro)


HYDROGENIC

[Previous Routine] [Next Routine] [List of Routines]
function	hydrogenic
	return the theoretical line sequence for the hydrogenic
	series for a given principal quantum number of the 1-electron
	configuration of a given element.

	warning: this routine does not take into account fine structure
	corrections due to the velocity dependence of electron mass,
	electron spin, and the Lamb shift due to radiation fields.

syntax
	Hwvl=hydrogenic(Z,N,nmax=nmax,elimit=elimit,/okeV,$
	/lyman,/balmer,/paschen,/brackett,/pfund,/humphreys)

parameters
	Z	[INPUT; required] the atomic number of the element
		for which the hydrogenic sequence is to be calculated
		* may also be a symbol
	N	[INPUT] the principal quantum number that defines the
		series.  if not given, assumed to be 1
		* if given, overrides the keywords below

keywords
	nmax	[INPUT] number of lines to include in the output
		* default is NMAX=10
	elimit	[OUTPUT] the series limit, in the same units as
		the primary output
	okeV	[INPUT] if set, returns the line energies in [keV]
		* default is to return [Ang]
	lyman	[INPUT] if set and N is not given, assumes N=1
	balmer	[INPUT] if set and N is not given, assumes N=2
	paschen	[INPUT] if set and N is not given, assumes N=3
	brackett	[INPUT] if set and N is not given, assumes N=4
	pfund	[INPUT] if set and N is not given, assumes N=5
	humphreys	[INPUT] if set and N is not given, assumes N=6
		* if more than one of the above keywords are specified, then
		  the one that corresponds to the smallest N is adopted.

subroutines
	INICON

history
	vinay kashyap (Jun02)

(See /data/fubar/SCAR/pro/misc/hydrogenic.pro)


ID2EMIS2ID

[Previous Routine] [Next Routine] [List of Routines]
function	id2emis2id
	takes an ID structure, strips it into component parts,
	reads in new emissivities, and puts them back in.

syntax
	newidstr=id2emis2id(idstr,ldbdir,dWVL=dWVL,verbose=verbose,$
	eps=eps,/incieq,mapping=mapping,pres=pres,logP=logP,n_e=n_e,$
	chifil=chifil,chidir=chidir,eqfile=eqfile)

warning
	new emissivities will not necessarily reflect the fluxes
	as distributed among the components.  also, if the database
	is changed, there is no reason to believe a priori that
	the correct lines are really read back in.  we strongly
	recommend using a high (say 10) verbosity level.

parameters
	idstr	[INPUT; required] ID structure, see LINEID for description
	ldbdir	[INPUT] directory in which to look for line database
		* default is "$CHIANTI"
		* if array size matches the number of features, is
		  distributed among components appropriately; if size
		  matches that of total number of lines, maps one-to-one
		  onto line list; if size is incompatible with IDSTR,
		  then uses only what is in the first element.

keywords
	dWVL	[INPUT] slack in wavelength search in which to find the
		matching line (this comes in handy when databases are
		being changed around)
		* default is 0.005
	verbose	[INPUT] controls chatter
	_extra	[INPUT ONLY] pass defined keywords to
		RD_LIST: EPS,INCIEQ,MAPPING,PRES,LOGP,N_E,CHIFIL,CHIDIR,EQFILE

restrictions
	requires subroutines:
	  RD_LIST, RD_LINE, FOLD_IONEQ, RD_IONEQ, READ_IONEQ,
	  SYMB2ZION, ZION2SYMB, LAT2ARAB, CAT_LN, LINEFLX,
	  INICON, WHEE, GETABUND, RDABUND, SYZE
	requires IDL 5.3+

history
	vinay kashyap (AugMM)
	catch if correct emissivities not found; added keywords
	  VERBOSE, DWVL; allowed LDBDIR to be array (VK; JanMMI)

(See /data/fubar/SCAR/pro/id2emis2id.pro)


IDLABEL

[Previous Routine] [Next Routine] [List of Routines]
function	idlabel
	return a string array containg a nicely formatted set of labels,
	appropriate for each of the IDs in an ID structure.

syntax
	label=idlabel(idstr,idx,/Zbeda,/Ibeda,/Wbeda,/Lbeku,$
	wform=wform,wstyle=wstyle,sep=sep,intex=intex, ziform=ziform)

parameters
	idstr	[INPUT; required] the ID structure containing the features
		with attached IDs. (see LINEID for description)
	idx	[OUTPUT] an integer array pointing out which label belongs
		to which feature.  this is of use in case of multiple IDs.
		* begins from 0, not 1

keywords
	Zbeda	[INPUT] if set, does not include the atomic symbol in label
	Ibeda	[INPUT] if set, does not include the ionic state in label
	Wbeda	[INPUT] if set, does not include the line wavelength in label
	Lbeku	[INPUT] if set, includes a description of the transition,
		in the form of the level-designation and electronic
		configuration (if available) in label
	wform	[INPUT] wavelength format, relevant if Wbeda=0
		* default: 'f7.2'
		  if WSTYLE = 1, unadorned WFORM
		  if WSTYLE = 2, automatically prepends $\lambda$:
			'"!4k!3 ",'+WFORM
		  if WSTYLE = 4, automatically appends \AA:
			WFORM+',"'+string(byte(197))+'"'
		  if WSTYLE = 8, automatically appends keV: WFORM+'," keV"'
	wstyle	[INPUT] bit-style flag shortcut to various WFORMs
		* see above for effect on WFORM
		* if -ve, uses the wavelength of the ID'd feature, not
		  the wavelength of the ID itself
	sep	[INPUT] separator between "Z Ion", wvl, and description
		* default is "<tab>", unless INTEX is set, in which case
		  the default is " & "
	intex	[INPUT] if set, encloses the description (see LBEKU) within
		"$...$"
	_extra	[INPUT] pass defined keywords to subroutines
		ZION2SYMB: ZIFORM

restrictions
	requires input to be in format generated by LINEID, CAT_ID, etc.
	requires subroutines
		ZION2SYMB [INICON]

examples
	l=idlabel(idstr,idx,wform='f5.1')
	l=idlabel(idstr,/Wbeda)
	l=idlabel(idstr,wstyle=4)
	l=idlabel(idstr,wstyle=6)
history
	vinay kashyap (AugMM)
	added keywords SEP,INTEX; implemented LBEKU (VK; JanMMI)
	back-compatibility: STRMID must have 3 args (VK; FebMMI/A.Maggio)
	bug fix: IDNAM[2] is ID1, not ID2 (VK; MayMMVI/L.Lin)

(See /data/fubar/SCAR/pro/idlabel.pro)


IDL_RELEASE

[Previous Routine] [Next Routine] [List of Routines]
 Project     : SOHO - CDS     
                   
 Name        : IDL_RELEASE
               
 Purpose     : check if IDL release version within specified range
               
 Category    : system
               
 Explanation : 
               
 Syntax      : IDL> a=idl_release(lower=lower,upper=upper)
    
 Examples    :

 Inputs      : None
               
 Opt. Inputs : 
               
 Outputs     : 1/0 if IDL version is within specified range

 Opt. Outputs: None
               
 Keywords    : LOWER = lower version to check
               UPPER = upper version to check
               INCLUSIVE = make check inclusive
               VERS = IDL version

 Common      : None
               
 Restrictions: None
               
 Side effects: None.
               
 History     : Version 1,  27-Feb-1997,  D M Zarro.  Written

 Contact     : DZARRO@SOLAR.STANFORD.EDU

(See /data/fubar/SCAR/pro/external/idl_release.pro)


ID_TO_FITPAR

[Previous Routine] [Next Routine] [List of Routines]
procedure	id_to_fitpar
	given the ID structure resulting from LINEID, figures out
	initial fitting parameters for use in, e.g., FITLINES, FIT_LEVMAR,
	etc.

syntax
	id_to_fitpar,idstr,pars,ties,thaw,pos=pos,wdt=wdt,flx=flx,$
	lsfwdt=lsfwdt,shackle=shackle,leeway=leeway,perr=perr,werr=werr,$
	ferr=ferr

parameters
	idstr	[INPUT; required] ID structure containing the observed
		wavelengths and appropriate matches
	pars	[OUTPUT] initial values of all the parameters set up in
		a single array for consumption by, e.g., FIT_LEVMAR or
		X3MODEL.
	ties	[OUTPUT] constraints on the parameters
	thaw	[OUTPUT] integer array of same size as PARS, signaling
		frozen (0) or thawed (1) parameter
		* all parameters that are SHACKLEd are frozen

keywords
	pos	[OUTPUT] initial-guess positions of all lines
	wdt	[OUTPUT] initial-guess widths of all lines
	flx	[OUTPUT] initial-guess fluxes of all lines
       epithet [OUTPUT] species label (e.g. 'OVII' or 'FeXIX') string array
	lsfwdt	[INPUT] width of the instrument's line spread function, and
		the minimum value of WDT
		* if not defined, assumed to be same as PERR
		  (on the theory that your position determination is uncertain
		  on the same order as the LSF width)
	shackle	[INPUT] specify how to handle multiple ID components:-
		"position" => line centers are fixed relative to location
		  of line of maximum strength
		"width" => freeze all WDT at maximum determined value OR
		  value of WERR if given
		"flux" => relative strengths of fluxes are held fixed
		* if array, only the first element is considered
		* if integer (as in /shackle), all 3 of above are set
		* any two (or all 3) may be specified simply as "flux & pos",
		  "width and flux", "position,width,flux", etc.
		* all affected parameters are frozen
	leeway	[INPUT] specify how to handle multiple ID components:-
		"position" => relative locations of line centers are held
		  to within a narrow range of position of line of maximum
		  strength, defined by PERR
		"width" => all WDT are constrained to be > minimum determined
		  width, and < maximum determined width, and this range may
		  be further expanded by WERR
		"flux" => relative strengths of fluxes are held to within
		  a narrow range defined by FERR
		* obviously, SHACKLE takes precedence if both are set
		* if array, only the first element is used
		* if integer (e.g., /leeway), all of above are set
		* unlike SHACKLE, all affected parameters are kept THAWed.
	perr	[INPUT; default=1.0] slippage allowed in POS
		* setting this is crucial in case the IDs include lines
		  from higher orders or unknown IDs, because this will
		  tell the program that deviations larger than PERR from
		  the location of the observed line are suspect.
		* if LSFWDT is not set, PERR constitutes a >lower limit< to WDT
	werr	[INPUT] allowed excess variation in range of WDT
		* default is 0.5*PERR[0]
		* subtracted from min and added to max if LEEWAY requires it
	ferr	[INPUT; default=0.1] allowed fractional error in FLX
		* has an effect only if LEEWAY is set
		* NOTE: for PERR,WERR,FERR, if size does not match that of
		  POS,WDT,FLX respectively OR the number of components in
		  IDSTR, only the first element is used
       numer   [INPUT; default = 0] if set, ties specified via leeway, perr,
                 werr, and ferr will be specified numerically rather than 
                 symbolically
       nozero  [INPUT; default = 0] if set, then fluxes are constained to 
                 be positive. if set negative, then fluxes are constrained 
                 to be negative 
	_extra	[JUNK] here only to prevent crashing the program

history
	vinay kashyap (Nov98)
	added keyword LSFWDT (VK; Mar99)
	changed call to INITSTUFF to INICON (VK; 99May)
       added EPITHET keyword (LL; Feb04) 
       added NUMER keyword (LL; Jul05) 
       BUGFIX: for multiplet component leeway width specification (LL; Jul 05) 
       had used lower bound for position instead of width 
       added NOZERO keyword (LL; Jul05) 
	BUGFIX: for multiplet component leeway position specification
	  was written with the wrong sign (VK; May06)

(See /data/fubar/SCAR/pro/id_to_fitpar.pro)


INICON

[Previous Routine] [Next Routine] [List of Routines]
procedure	inicon
	return atomic symbols, names, ionization potentials, fundamental
	and other fun constants, atomic weights, roman numerals

syntax
	inicon,atom=atom,aname=aname,amu=amu,fip=fip,fundae=fundae,$
	roman=roman,/help

parameters	NONE

keywords
	atom	[OUTPUT] atomic symbols
	aname	[OUTPUT] names of elements
	amu	[OUTPUT] structure containing atomic weights in AMU (1H=1)
		* AMU.(Z) is an array, with first element the atomic weight
		  for terrestrial composition, then the AMUs of the isotopes
		  in order of abundance (i.e., most abundant is 2nd element,
		  second most abundant is 3rd element, etc. -- but not
		  completely implemented)
	fip	[OUTPUT] first ionization potentials [eV]
		* set to -1 if not known
	fundae	[OUTPUT] structure containing some useful physical and
		astronomical constants
		* just do help,fundae,/str -- should be obvious
	roman	[OUTPUT] roman numerals, upto max(ATOM)+1
		* beware that CHIANTI has a function named ROMAN()
		  which returns numerals that are offset by 1 compared
		  to this variable.

		NOTE: in IDL versions prior to 5, the keywords must be
		pre-defined if output is desired

requires
	CREATE_STRUCT

history
	modified from INITSTUFF (VK; 99May)
	bug correction -- ROMAN wasn't working (VK; 99Jul)
	added Jupiter (VK; MIM.XI)
	added keV-to-Ang (VK; MMII.I)
	added planetary data (VK; MMII.IX)
	changed AMU tag names from symbol to full names (VK; MMII.X)
	corrected AMU value (JD; IMVIM.I)
	added JouleV, ergeV, and arcsr (VK; IMVIM.V)
	corrected Bode's Law and extended to 12 "planets" (VK; MMV.VII)
	changed Planets field to "Classical Planets", moved Pluto to
	  separate Plutoid field (VK; MMVIII.VII)

(See /data/fubar/SCAR/pro/misc/inicon.pro)


INITALE

[Previous Routine] [Next Routine] [List of Routines]
script	initale
	extremely flexible initialization script for the Package for
	Interactive Analysis of Line Emission (PINTofALE); defines some
	useful variables as system variables.  Examples and scripts in
	the standard distribution use these variables.

	NOTE: Strictly speaking, none of these system variables are
	_necessary_ in order to use basic PINTofALE functionality.
	However, they set up the default values for some commonly
	used keywords and usually must be explicitly included in
	calls to PINTofALE routines.  Most scripts and documentation
	examples do use these directly, and some routines set their
	default values at run-time if the system variables are defined.
	An additional use of this script is that it sets up the !PATH
	to include PINTofALE, CHIANTI, and IDL-Astro if they are not
	already included.

syntax
	.run initale
	(or)
	.run /full/path/initale

system variables and hardcoded default values
	!PoA	 current version number
	!TOPDIR	 the top-level PINTofALE directory
		 * first checks for environment variables
			PINTofALE, PoA, SCARDIR, and SCAR
		   in that order.  if none of them exist, then uses
		   value deduced from the location of _this_ script.
	!LDBDIR	 [!TOPDIR+'emissivity/chianti'] directory of line emissivities
	!CDBDIR	 [!TOPDIR+'emissivity/cont'] directory of continuum emissivities
	!CHIDIR	 [!TOPDIR+'CHIANTI'] path to CHIANTI installation
		 NOTE: !TOPDIR is added to initial values of above 3 ONLY IF:
		 -- !TOPDIR is not already contained in them
		 -- the first character is not a "$"
		 -- the first character is not a "/"
		 -- for CHIANTIv4+, path name must include the "dbase" part
	!ATOMDB  [!TOPDIR+'atomdb/'] directory of local installation of ATOMDB
	!APECDIR where the IDL tools of APED are
		 * first checks for environment variable APEC_DIR, and if
		   that is missing, looks in succession in
		   -- !ATOMDB+'apec_v11_idl/'
		   -- !TOPDIR+'apec_v11_idl/'
		   -- !TOPDIR+'atomdb/apec_v11_idl/'
	!ARDB	 [!TOPDIR+'ardb/'] the Analysis Reference DataBase directory,
		 contains sundry useful documents
	!CEROOT	 ['cie'] root prefix for continuum emissivity files
	!IONEQF	 ['ioneq/mazzotta_etal.ioneq'] path name relative to
		   !CHIDIR of the ion-balance file to be used
	!ABREF	 ['grevesse et al.'] abundance reference
	!CALDB	 ['/data/caldb/'] directory containing instrument
		    calibration data products
	!METALS	 [0.0] [Fe/H] relative to !ABREF
	!ABUND	 abundances of elements H..Zn corresponding to !ABREF and
		 !METALS
	!GASPR	 [1e15 cm^-3 K] gas pressure
	!LOGPR	 [15] log10(gas pressure) -- if set, overrides !GASPR
	!EDENS	 [1e10 cm^-3] electron density -- if set, overrides use of
		   !GASPR and !LOGPR
	!LOGT	 [findgen(81)*0.05+4] the default temperature grid
	!DEM	 [dblarr(81)+1d12] a sample DEM(!LOGT)
	!NH	 [1e18 cm^-2] H column density
	!FH2	 [0.26] fraction of molecular H2 relative to HI
	!HE1	 [1e17 cm^-2] He I column
	!HEII	 [1e16 cm^-2] He II column
	!WMIN	 [1.239854 Ang] minimum wavelength
	!WMAX	 [3000.0 Ang] maximum wavelength
	!VERBOSE [5] verbosity -- controls chatter
	!ATOM	 atomic symbols
	!AMU	 atomic weights
	!FUNDAE	 a whole bunch of fundamental constants
	!FIP	 firt ionization potentials [eV]
	!ROMAN	 roman numerals, upto max(!ATOM)+1
	!AA	 ['!3'+string(byte(197))+'!X'] the symbol for Angstrom
	!ANGSTROM	An array of Angstrom symbols, should work for
			every conceivable font choice.

control variables
	factory	 determines whether to reset all the system variables to
		 the "factory default" or not.  set this variable to 0 or 1 
		 prior to running the script.
		 * if explicitly set to 0, then only initializes those
		   variables which have not been defined yet
		 * if PARFIL is defined, automatically gets unset
		 * if set, or is not defined, then overwrites all variables
		   with hardcoded defaults
		 -- one may want to use FACTORY=0 when some of the variables
		    have been set (e.g, !TOPDIR) during the session without
		    an initial call to this script, or when a limited number
		    of the variables are being reset via a parameter file.
		 -- upon execution, if FACTORY is not set, it will be set to 0
	parfil	 if set to a named parameter file that contains new definitions
		 of the defined system variables.  They must be placed one on
		 each line, and must be fully legal IDL statements.
		* if not set, will automatically look in
		  !ARDB+'initale.par'
		* DO NOT try to define the following in PARFIL:
		   !ABUND, !ATOM, !AMU, !FUNDAE, !FIP, !ROMAN, !PoA
	yCHIANTI if set then checks to see whether the CHIANTI distribution is
		 available for use and includes it if it is not.
	yATOMDB  if set then checks to see whether the ATOMDB IDL routines
		 are accesible and adds them if they are

calls subroutines
	GETABUND
	INICON
	PEASECOLR

restrictions
	subroutine WHICH works only in UNIX, but it is used only if none
	  of the environment variables PINTofALE, PoA, SCARDIR, or SCAR
	  are set.
	Unlike normal IDL variables, system variables, once defined,
	  cannot change their size, though their values may be changed.
	  Thus, care must be taken to match the expected sizes of the
	  following variables to the hardcoded defaults if they are to
	  be redefined within PARFIL:
	  !ABUND, !LOGT, !DEM, !ATOM, !AMU, !FUNDAE, !FIP, !ROMAN

history
	Vinay Kashyap(OctMM)
	set FACTORY to 0 if undefined; changed !ABREF default; added !ARDB;
	  !TOPDIR now automagic (VK; DecMM)
	added !PoA, !CALDB, !LOGT, !DEM, and !AA (VK; JanMMI)
	fixed bug with !TOPDIR becoming an array if none of the env vars
	  were defined; change prompt for large !VERBOSE (VK FebMMI/Dan Dewey)
	changed call to WHICH to WHEREIS (VK; Dec2001)
	commented out call to WHEREIS by using the output of HELP, and now
	  adds !TOPDIR/pro to !PATH if it doesn't exist; also check for
	  other packages such as IDL-ASTRO and CHIANTI; more robust to
	  OS filename dependencies for v5.3+ due to extensive use of
	  FILEPATH function; added !ATOMDB, !APECDIR, and yATOMDB
	  (VK; Jun2002)
	added call to PEASECOLR (VK; Jul02)
	some people have IDL-ASTRO installed under 'astrolib' (VK; Aug02)
	added !ANGSTROM; made !AA robust to font choices (VK; Dec'02)
	suppose environment variable is defined, but incorrectly?  i.e.,
	  what if $PINTofALE, $SCARDIR, etc. do not exist? (VK; May'03)
	if IDL_DIR is not defined, assumes that IDL library is in anything
	  that has '...idl/lib' (VK; Jul'03)
	corrected case where if env variable defining TOPDIR had a trailing
	  "/", would miss matching it in !PATH and not reset the order of
	  directories (VK; MarMMIV)
	made a few of the system variables read-only (VK; May04)
	made windows compatible, by and large (VK; Apr05)
	forced IDL-Astro to move ahead of Chianti's astron directory
	  in !PATH (VK; FebMMVII)
	removed early call to strsplit() and forced restoration of
	  correctly compiled versions of STRSPLIT, UNIQ, and STR_2_ARR
	  (VK; JunMMVII)
	bugfix: wasn't setting TOPDIR correctly when it had to be determined
	  from the location of this file (VK; OctMMIX)

(See /data/fubar/SCAR/pro/scrypt/initale.pro)


IONABS

[Previous Routine] [Next Routine] [List of Routines]
function	ionabs
       returns the photoelectric absorption cross-sections for a given
	photon energy for specified chemical composition, and ion fractions.
	Uses ground state photoionisation cross-sections computed using the
	fortran code of Verner, D.A., Ferland, G.J., Korista, K.T., & Yakovlev,
	D.G., 1996, ApJ, 465, 487 and is supplemented with the O cross-sctions
	from Garcia et al., 2005,ApJ,??,?? 

syntax
	sigabs=ionabs(w,abund=abund,ionfrac=ionfrac,vfkydir=vfkydir,/ikeV,$
	nconsec=nconsec,DEM=DEM,logt=logt,verbose=verbose,noHeH=noHeH,$
	icrstr=icrstr,chidir=chidir,eqfile=eqfile)

parameters
	w	[INPUT; required] photon energy values at which to compute
		the absorption cross-section
		* default units are [Ang], unless IKEV is set, when they are
		  assumed to be [keV]

keywords
	abund	[INPUT] abundances relative to H=1
		* default is to use Grevesse & Sauval
	ionfrac	[I/O] the ion fraction for all elements
		* must be a 2D array of size (NZ,NION), where
		  NION=NZ+1 and usually NZ=30
		* note that in normal cases, total(IONFRAC,2)
		  is an array of 1s.
		* if not given, assumed to be all neutral, IONFRAC[*,0]=1
		  - unless DEM is given, see below
		* if non-zero scalar, assumed to be all neutral
		  - DEM is ignored
		* if given as an array of size NZ, each element
		  is assumed to have a total of that fraction,
		  and all the ions have the same fraction
		  - this is clearly an artificial case, to be used mainly
		    for debugging and the like
		  - DEM is studiously ignored
		* if given as a 1D array of size not matching NZ,
		  is ignored with a warning and the default is used
		  - unless DEM is given, see below
		* if given as a 2D array of size not matching (NZ,NZ+1),
		  program quits with an error
		  - unless DEM is given, see below
		* if DEM (see below) is given, is read in as a 3D array
		  of size (NT,NZ+1,NZ1) from the database (using the PINTofALE
		  function RD_IONEQ(), which calls the CHIANTI procedure
		  READ_IONEQ), weights the fractions according to the DEM
		  and is converted into a 2D array of size (NZ,NZ+1)
	vfkydir	[INPUT] where to find the save files that contain the
		cross-sections calculated for each ionization state
		* default is '$ARDB'
		* NOTE: the cross-sections are not read in if the keyword
		  ICRSTR is properly defined
	ikeV	[INPUT] if set, assumes that W are in units of keV
	nconsec	[INPUT] number of grid points that define the cross-sections
		that must fall within one bin of the user defined grid before
		the switch from averaging to interpolating occurs
		* default=1
	DEM	[INPUT] the Differential Emission Measure that will be
		used to weight the different temperatures to compute the
		ionization fraction
		* looked at only if IONFRAC is not supplied as input
		* size must match LOGT, otherwise ignored
	logT	[INPUT] the temperature grid over which DEM is defined
		* size must match DEM, otherwise DEM is ignored
	noHeH	[INPUT] if set to any number other than 1 or 2, excludes
		H and He from the cross-sections
		* if set to 1, only excludes H
		* if set to 2, only excludes He
	icrstr	[I/O] the cross-sections calculated for each ionization
		state, stored in a structure of structures of the form
		ICRSTR.(Z) = {EVSPLAC, CROSSI}
		* if given on input, will use these numbers
		* if the structure does not contain enough tags, or if
		  any one of the substructures does not contain enough
		  tags, will be read in using the data in VFKYDIR
	verbose	[INPUT] controls chatter
	_extra	[INPUT ONLY] pass defined variables to subroutines
		-- RD_IONEQ : CHIDIR, EQFILE

subroutines
	GETABUND()
	RD_IONEQ()
	READ_IONEQ
	INICON

history
       written as IONTAU by Jeremy Drake (Apr07)
       further shoehorned into PoA format by Vinay Kashyap (Apr07)
	bug fixes and corrections and changed behavior of IONFRAC
	  (VK; May09)

(See /data/fubar/SCAR/pro/ionabs.pro)


ISMTAU

[Previous Routine] [Next Routine] [List of Routines]
function	ismtau
	returns the optical depth for a given photon energy at specified
	column density.  i.e., the $\tau$ of $e^{-\tau}$.

	ingredients:
	* in the EUV regime, cannibalizes ISMEUV.PRO for
	  -- HI photoionization (Spitzer 19??, "Physical Processes in the
	     Interstellar Medium", p105), between 0.03 keV (413.3A) and 911.75A
	  -- HeII photoionization (ibid), between 0.03 keV (413.3A) and 911.75A
	  -- HeI with auto-ionization resonances (Marr & West 1976;
	     Oza 1986, Phys.Rev.A 33 824; Fernley et al. 1987, J.Phys.B 20,
	     6457; Rumph, Bowyer, & Vennes 1994, AJ 107, 2108) below 503.97A
	  -- NOTE: these are extended down to 43.657 AA when the X-ray
	     calculations are not being done.
	* in the X-ray regime (0.03 - 10 keV), either
	  -- Morrison & McCammon (1983, ApJ 270, 119) polynomial fit between
	     0.03 keV and 10 keV, or
	  -- Balucinska-Church & McCammon (1992, ApJ 400, 699) cross-sections,
	     which allows abundance variations, or
	  -- Wilms, Allen, & McCray (2000, ApJ, in press) calculations
	     that use cross-sections from Verner & Yakovlev (1995, A&AS,
	     109, 125), which also allows abundance variations
	  -- Verner, Ferland, Korista, & Yakovlev (1996, ApJ, 465, 487)
	     ground state photoionisation cross-sections that allows for
	     abundance variations (down to 911.75 Ang)
	* in the hard X-ray regime and beyond (>10 keV),
	  -- Tanaka & Bleeker (1977, ???) power-law extended past 10 keV
	* Molecular H (Cruddace et al. 1977, ApJ 187, 497; Kashyap et
	  al. 1992, ApJ 391, 684) between 12.3985A (1 keV) to 911.75A

	to extract only the cross-sections, set NH=1
	to obtain transmission factors, use exp(-ismtau(...))

syntax
	tau=ismtau(w,NH=NH,fH2=fH2,He1=He1,HeII=HeII,Fano=Fano,/ikev,$
	/vion,/wam,/bam,/mam, abund=abund,noHeH=noHeH,verbose=verbose,$
	tauH1=tauH1,tauH2=tauH2,tauHeII=tauHeII,tauHe1=tauHe1,tauX=tauX,tauTB=tauTB,$
	icrstr=icrstr,ionfrac=ionfrac,vfkydir=vfkydir,nconsec=nconsec,$
	DEM=DEM,logT=logT,chidir=chidir,eqfile=eqfile)

parameters
	w	[INPUT; required] photon energy values at which to compute
		the optical depth.
		* default units are [Ang], unless IKEV is set, when they are
		  assumed to be [keV]

keywords
	NH	[INPUT; default=1] atomic H I column density [cm^-2]
		* note that when NH=1, the function essentially returns
		  the absorption cross-section in units of [cm^2]
	fH2	[INPUT; default=0.] N(H2)/N(HI)
		* the default value comes from the asymptotic value of
		  N(H2)/N(HI) computed with the 3 component model (cold
		  HI, warm HI, H2) of Bloemen, J.B.G.M. (1987, ApJ 322, 694)
		* originally was set to a default of 0.26 (the Galactic average)
		  but has now been changed to 0. explicitly set it to a float
		  number to include H2 cross-sections
		* if NoHeH is set to exclude H, fH2 is assumed to be 0
	He1	[INPUT; default=0.1*NH] neutral He column density [cm^-2]
	HeII	[INPUT; default=0.1*He1] ionized He column density [cm^-2]
		* if NoHeH is set to exclude He, both HeI and HeII cross-sections
		  will be excluded regardless of what the keywords He1 and
		  HeII are set to
	Fano	[INPUT] if set, the 4 strongest auto-ionizing resonances
		of He I are included; the shape of these resonances are
		given by a Fano profile (cf. Rumph, Bowyer, & Vennes 1994,
		AJ 107, 2108).
		* input wavelength grid between 190 A and 210 A should be
		  ~0.01 A for this to be useful
	ikev	[INPUT] if set, assumes that W are in units of keV
	vion	[INPUT] if set, uses Verner et al. (1996) cross-sections
		* calls IONABS()
	wam	[INPUT] if set, uses Wilms, Allen, & McCray cross-sections
		* NOT IMPLEMENTED YET -- if set, defaults to Balucinska-Church
		  & McCammon.
	bam	[INPUT] if set, uses Balucinska-Church and McCammon updates
		to Morrison & McCammon cross-sections in 30 eV - 10 keV range
		* calls BAMABS()
	mam	[INPUT] if set, uses Morrison and McCammon photoionization
		cross-sections in the 30 eV - 10 keV range
		* This is the default
		* VION takes precedence over
		  WAM takes precedence over
		  BAM takes precedence over MAM.
		* if MAM is explicitly set to 0 and none of VION, BAM, or WAM are
		  set, then the original ISMEUV code is used from 43 AA longwards
	noHeH	[INPUT] passed on unchanged to BAMABS() and IONABS()
		if set to any number other than 1 or 2, excludes H and He
		cross-sections in BAMABS (and ensures that even if fH2 and
		He1 are not zero, they are properly excluded within ISMTAU)
		* if set to 1, excludes only H
		* if set to 2, excludes only He
		* NOTE: if set, will supersede fH2, He1 and HeII keyword
		  values in that H, H2, He1, He2 are all appropriately
		  excluded
	tauH1	[OUTPUT] optical depth due to H
	tauH2	[OUTPUT] optical depth due to molecular H2
	tauHe2	[OUTPUT] optical depth due to HeII
	tauHe1	[OUTPUT] optical depth due to HeI
	tauX	[OUTPUT] optical depth in EUV and X-ray regime (0.03-10 keV)
	tauTB	[OUTPUT] optical depth in hard X-ray regime (>10 keV)
	icrstr	[I/O] passed without comment to IONABS()
	_extra	[INPUT ONLY] pass defined variables to subroutines
		BAMABS: ABUND,VERBOSE
		IONABS: ABUND,IONFRAC,VFKYDIR,NCONSEC,DEM,LOGT,CHIDIR,EQFILE

history
	written by Vinay Kashyap (Feb97), based on
	  ISMEUV.PRO (W.Landsman [Oct94], via ISM.C@cea-ftp.cea.berkeley.edu
	  (Pat Jelinsky, Todd Rumph, et al.)) and ISMABS.PRO (VK; Dec91)
	changed default on HeII from 0 to 0.1*He1 (VK; Jan MM)
	changed default on NH from 1e20 to 1.0 (VK; MarMM)
	changed keyword KEV to IKEV; also for some reason H and He
	  photoionization from ISMEUV had been cut off at the C edge,
	  now corrected; added keywords WAM, BAM, and MAM, and call to BAMABS
	  (VK; OctMM)
	bug correction: BAM was not filtering on energy; allowed setting
	  MAM=0 to recover original ISMEUV calc (VK; Jun03)
	follow-up bug correction (VK; Jul03)
	added keyword NOHEH to streamline behavior of handling H and He
	  cross-sections with BAMABS (thanks Christian Schneider; VK Feb07)
	added keywords TAUH1,TAUH2,TAUHE2,TAUHE1,TAUX,TAUTB, VION,ICRSTR,;
	  changed all array index notation from old "()" to new "[]";
	  **WARNING** changed behavior of FH2 -- new default is 0, not 0.26
	  added call to IONABS();
	  (VK; May09)

(See /data/fubar/SCAR/pro/ismtau.pro)


IS_DIR

[Previous Routine] [Next Routine] [List of Routines]
 Project     : HESSI
                  
 Name        : IS_DIR
               
 Purpose     : platform/OS independent check if input name is a 
               valid directory.
                             
 Category    : system utility
               
 Explanation : uses 'cd' and 'catch'
               
 Syntax      : IDL> a=is_dir(name)

 Inputs      : NAME = directory name to check
               
 Outputs     : 1/0 if success/failure
               
 Keywords    : OUT = full name of directory
             : COUNT = # of valid directories
             
 Restrictions: Needs IDL version .ge. 4. Probably works in Windows
               
 Side effects: None
               
 History     : Written, 6-June-1999, Zarro (SM&A/GSFC)
               Modified, 2-Dec-1999, Zarro - add check for NFS /tmp_mnt
               Modified, 3-Jan-2002, Zarro - added check for input
                directory as environment variable
                  

 Contact     : dzarro@solar.stanford.edu

(See /data/fubar/SCAR/pro/external/is_dir.pro)


IS_KEYWORD_SET

[Previous Routine] [Next Routine] [List of Routines]
function	is_keyword_set
	a wrapper to KEYWORD_SET(), in order to produce the
	same behavior with vector [0] as with IDL 5.6 and prior

parameters
	key	[INPUT] the keyword to test for

keywords
	none	isn't this ironic?

description
	prior to IDL 5.6, keyword_set(0) returned false and
	keyword_set([0]) returned true.  this behavior changed
	in IDL 5.6 to match the documentation of keyword_set,
	so that both 0 and [0] now return false.  it is far too
	difficult to change the code logic of all the programs
	written with old IDLs, so better to have a wrapper
	that duplicates the same behavior instead.

history
	Vinay Kashyap (Mar2006)

(See /data/fubar/SCAR/pro/misc/is_keyword_set.pro)


ITOH_CH

[Previous Routine] [Next Routine] [List of Routines]
 PROJECT:  CHIANTI

       CHIANTI is an Atomic Database Package for Spectroscopic Diagnostics of
       Astrophysical Plasmas. It is a collaborative project involving the Naval
       Research Laboratory (USA), the University of Florence (Italy), the
       University of Cambridge and the Rutherford Appleton Laboratory (UK). 

 NAME

    ITOH_CH

 EXPLANATION

    Calculates the relativistic free-free continuum using the fitting 
    formula of Itoh et al. (ApJS 128, 125, 2000).

 INPUTS

    TEMP    Temperature (in K).

    WVL     Wavelengths in angstroms. Can be a scalar or vector.

 OUTPUTS

    INT     Free-free continuum emissivity in units of 
            10^-40 erg cm^3 / s / sr / Angstrom per unit emission 
            measure [ integral(N_e N_H dh) in cm^-5 ]. If T is given as 
            a 1-D array, then RAD will be output as a 2-D array, 
            with one element for each temperature and wavelength 
            (but also see SUMT).

 OPTIONAL INPUTS

    DEM_INT An array of same length as TEMP which contains the 
            differential emission measure values at each temperature. 
            The emissivity at each temperature is multiplied by the 
            DEM value and the d(logT) value.

    MIN_ABUND This keyword allows the specification of a minimum abundance, 
              such that any elements with an abundance (relative to 
              hydrogen) less than MIN_ABUND will not be included in the 
              calculation. E.g., MIN_ABUND=1e-5.

 KEYWORDS

    NO_SETUP By default the routine asks the user which ion balance 
             and abundance files to use via pop-up widgets. If 
             /no_setup is used then this data is taken from the common 
             block.

    SUMT     The default is to output the intensity array as an array 
             of size (nwvl x nT). Setting this keyword performs a sum 
             over the temperatures to yield a vector of same size as 
             the input wavelengths, thus producing the complete 
             free-free spectrum.

    PHOTONS  Gives output emissivity in photon units rather than ergs.

 CALLS

    Chianti:  SETUP_ELEMENTS

 PROGRAMMING NOTES

    In the Itoh et al. paper they state that their fitting formula is 
    valid for ion charges (Z_j) of 1-28. The data-file they provide 
    actually goes up to Z_j=30, and so you will see that the loop over 
    z (see below) goes up to 30.

    There is no restriction on the elements for which the fitting 
    formula is valid, and so all elements are allowed to be included 
    (subject to their abundances being non-zero).

 HISTORY

    Ver.1, 3-Dec-2001, Peter Young

    Ver.2, 22-May-2002, Peter Young
            Added MIN_ABUND optional input.

    Ver.3, 28-May-2002, Peter Young
            Corrected way in which DEM is handled.
    ver.PoA 18-Feb-2005, LiWei Lin 
            Commented out common block 
            Added abund, ioneq, ioneq_logt keywords
            Replaced variable ioneq_t with ieq_logt, _extra             
            Renamed routine itoh_ch

(See /data/fubar/SCAR/pro/external/itoh_ch.pro)


KABOOM

[Previous Routine] [Next Routine] [List of Routines]
procedure	kaboom
	produces BOOMs and BANGs
	(to be used only to indicate catastrophic failure, OK?  don't overdo it)

syntax
	kaboom,boom,bang=bang,/beep,/flash,/help

parameters
	boom	[INPUT; default='KABOOM!!'] could be 'BIFF'.  or 'POW'.  could
		even be an array

keywords
	bang	[INPUT; default=42] number of "KABOOM"s to produce
	beep	[INPUT] if set, also produces beeps
	flash	[INPUT] if set, flashes the window
	help	[INPUT] prints usage and quits
	_extra	[JUNK] here only to prevent crashing the program

usage examples
	kaboom,boom,bang=bang,/beep,/flash,/help
	kaboom,'?',bang=100,/beep,/flash

side-effects
	makes an almighty mess of the plot window; may also make noises

history
	vinay kashyap (rewritten from memory of 1993 program)
	added keywords FLASH, HELP, and _EXTRA (VK; Nov98)
	improved color-scale setting for 24-bit consoles (VK; FebMMI)
	added a brief pause (VK; Apr04)

(See /data/fubar/SCAR/pro/misc/kaboom.pro)


KALPANA

[Previous Routine] [Next Routine] [List of Routines]
procedure	kalpana
	widget-based procedure to make an annotated plot, e.g., of a spectrum.

	"kalpana" means "imagination".  or "delirium", if you prefer.
	pronounced "cull-pun-ah"

syntax
	kalpana,x,y,ststr,idstr,oststr=oststr,wshow=wshow,wwork=wwork

parameters
	x	[INPUT; required] points where the curve is defined
	y	[INPUT; required] the curve Y[X] (usually a spectrum)
		* size of Y must match that of X
	ststr	[I/O; required] the state structure containing all
		the necessary information on what labels to put where.
		* see >>description<< below
	idstr	[INPUT] the output of LINEID, containing the wavelengths,
		IDs, labels, etc. of identified features in the spectrum.
		* if given, STSTR is suitably modified.

keywords
	oststr	[OUTPUT] returns the original STSTR, in case modifications
		are not acceptable
	wshow	[INPUT] display final result in this window number (def: 1)
	wwork	[INPUT] display working plot in this window number (def: 0)
	_extra	[INPUT] pass defined keywords to subroutines

description
	The state structure contains the following substructures
	WINDOW:
		MULTI: !P.MULTI
		TITLE: overall title
		SUBTITLE: array of subtitles for each plot if >1,
			the subtitle for one if one.
		XTITLE: string array of xtitles, for each of the plots
		YTITLE: string array of ytitles
		XSTYLE: integer aarray of xstyles
		YSTYLE: integer array of ystyles
		XLOG: integer array for x-axis in log style (1) or linear (0)
		YLOG: integer array for y-axis in log style (1) or linear (0)
		CHARS: character size for labels
		XMIN: array of minimum values of XRANGE
		XMAX: array of minimum values of XRANGE
		YMIN: array of minimum values of YRANGE
		YMAX: array of minimum values of YRANGE
	LOC:
		X: x-values to which the labels apply
		Y: y-values to which the labels apply
		GROUP: index in X from which to take attributes.
		  e.g., if STSTR.LOC.GROUP(I+1)=J+1, then STSTR.LI.(ALIGN,
		  ORIENT,SIZE,THICK,LABCOLOR,LINCOLOR,ARRANGE,UNDERLINE,
		  SIDELINE) are taken from STSTR.LJ
	L1..N:	one structure for each of LOC, containing
		POS: [x,y] at which label is to be written
		LABEL: the label text (could be a string array)
		XPATH: array of intermediate x-positions of line connecting
			POS to LOC
		YPATH: as XPATH, for intermediate y-positions
		ALIGN: the alignment of the label wrt POS (LEFT/RIGHT/UP/DOWN)
		ORIENT: the orientation of the label text
		SIZE: size of characters in LABEL
		THICK: thickness of line in PATH
		LABCOLOR: a number from 1..255
		LINCOLOR: a number from 1..255
		ARRANGE: if multiple fields in LABEL, arrange them in
			a ROW or a COLUMN
		UNDERLINE: underline (+ve), overline (-ve), no line (0)
			with values >1 indicating extent of pincer tip
		SIDELINE: same as UNDERLINE, but sideways

restrictions
	requires graphics capability
	subroutines:
		KALPANA_EVENT [PICKLABL, MOVELABL]
		DARSHANA
		MUDRA
		STR_2_ARR
	hardcopies are not working, needs a few more features to be
	  really useful, and still somewhat klunky.

history
	vinay kashyap (SepMIM)

(See /data/fubar/SCAR/pro/kalpana.pro)


KALPANA_EVENT

[Previous Routine] [Next Routine] [List of Routines]
procedure	kalpana_event
	widget event handler subroutine for KALPANA.  see that routine
	for a description of variables, etc.  only rudimentary consistency
	checks are carried out here.
	uses subroutines PICKLABL and MOVELABL, which are included in
	this file.
syntax
	kalpana_event,x,y,ststr,widg,oststr=oststr,wshow=wshow,wwork=wwork,$
		outroot=outroot
parameters
	X,Y,STSTR,WIDG	[INPUT; required]
keywords
	OSTSTR,WSHOW,WWORK	[INPUT]
	OUTROOT	[INPUT] filename root for output

procedure	PICKLABL
	interactively select label indices
usage
	picklabl,x,y,xloc,xlab,ylab,ilab
parameters
	X	[INPUT] as in KALPANA
	Y	[INPUT] as in KALPANA
	XLOC	[INPUT] STSTR.LOC.X
	XLAB	[INPUT] STSTR.L#.POS(0)
	YLAB	[INPUT] STSTR.L#.POS(1)
	ILAB	[OUTPUT] the "#"-1 in STSTR.L#

procedure	MOVELABL
	interactively move label locations and connecting lines
usage
	movelabl,x,y,ststr,pnum,lnum,coarse=coarse,dcor=dcor,springy=springy
parameters
	X	[INPUT] as in KALPANA
	Y	[INPUT] as in KALPANA
	STSTR	[I/O] as in KALPANA
	PNUM	[INPUT] plot window
	LNUM	[I/O] selected label -- can be changed via keyboard control
keywords
	COARSE	[INPUT] if set, forces intermediate points to line up
	DCOR	[INPUT; default=0.1] "fineness" of the coarseness
	SPRINGY	[I/O] if set, keeps XPATH/YPATH relative positions as is
		if end positions are changed
		* if <0, then moves whole system bodily

subroutines
	PICKLABL
	MOVELABL

history
	vinay kashyap (SepMIM)
	handle color tables in 24-bit displays (VK; Jun02)
	changed call from STR2ARR to STR_2_ARR (VK; Apr05)
	button press status now stored in !MOUSE, not !ERR (VK; Apr09)

(See /data/fubar/SCAR/pro/kalpana_event.pro)


KARZAS_XS

[Previous Routine] [Next Routine] [List of Routines]
 PROJECT:  CHIANTI

      CHIANTI is an Atomic Database Package for Spectroscopic Diagnostics of
      Astrophysical Plasmas. It is a collaborative project involving the Naval
      Research Laboratory (USA), the University of Florence (Italy), the
      University of Cambridge and the Rutherford Appleton Laboratory (UK). 

 NAME

    KARZAS_XS()

 EXPLANATION

    Outputs the photoionization cross-section at the wavelengths WVL for 
    ionization of an N,L electron with ionization energy IONIZ_EN, 
    calculated using the Karzas & Latter (ApJS 6, 167, 1961) formulation. 
    The bound-free gaunt factor is derived from the tables of Karzas & 
    Latter.

 INPUTS

    WVL    Wavelengths (in angstroms) for which cross-sections are 
           required (1-D array).

    N      Principal quantum number of the electron being removed in the 
           ionization.

    L      The orbital angular momentum of the electron being removed in the 
           ionization.

    IONIZ_EN  The ionization energy (in cm^-1) of the electron being 
              removed.

 OPTIONAL INPUTS

    PE      Allows the PE array from READ_KLGFB to be directly input to 
            KARZAS_XS thus avoiding the need to read the K&L data 
            repeatedly for many ions. Requires KLGFB to also be input.

    KLGFB   Allows the KLGFB array from READ_KLGFB to be directly input to 
            KARZAS_XS thus avoiding the need to read the K&L data 
            repeatedly for many ions. Requires PE to also be input.

 OUTPUT

    The photoionization cross-section for the ionization of the outer 
    electron in units of mega-barns (Mb = 10^-18 cm^2) at the input 
    wavelengths. E.g., for Fe XIII (ground configuration 
    1s2.2s2.2p6.3s2.3p2) it is the cross-section for the removal of the 
    3p electron.

 CALLS

    READ_KLGFB

 HISTORY

    Ver.1, 24-Jul-2002, Peter Young

(See /data/fubar/SCAR/pro/external/karzas_xs.pro)


KILROY

[Previous Routine] [Next Routine] [List of Routines]
procedure	kilroy
	"kilroy was here"
	writes a little something to the screen every time it is called

syntax
	kilroy,here,ndot=ndot,dot=dot,say=say

parameters
	here	[I/O; optional] if given, is included in the output and
		is increased by 1 upon output.
		* cannot be a string
			
keywords
	ndot	[INPUT] number of dots to write out (default is 1)
	dot	[INPUT] symbol to use (default is ".")
	say	[INPUT] an extra word or whatever to print out
	_extra	[JUNK] here only to avoid crashing the program

history
	vinay kashyap (Aug 1996)

(See /data/fubar/SCAR/pro/misc/kilroy.pro)


LAT2ARAB

[Previous Routine] [Next Routine] [List of Routines]
function 	lat2arab
		return arabic (decimal) equivalent of a latin numeral

syntax
	arabic=lat2arab(latin)

parameters
	latin	[INPUT; required] the latin numeral

keywords	NONE

restrictions
	* spaces, "."s, and anything that is not part of the
	  roman numeral system (I V X L C D M) is ignored.
	* there is no reverse function, to go from arabic
	  to latin, because that is not a unique transformation.
	  e.g., 1995 could be either MDCCCCLXXXXV (the BBC way),
	  or MVM, or all steps in between.
	* guaranteed to work only in simple cases.
	  DON'T push the envelope!
	* CAVEATVSVATOR

history
	vinay kashyap (Nov95)

(See /data/fubar/SCAR/pro/misc/lat2arab.pro)


LEGALVAR

[Previous Routine] [Next Routine] [List of Routines]
function	legalvar
	returns 1 or 0 depending on whether VAR is a legal IDL variable
	or not.  simply calls EXECUTE.  need to put this inside a subroutine
	to protect possible existing variables of same name in main routine.

syntax
	l=legalvar(vars,verbose=verbose)

parameters
	var	[INPUT; required] string of candidate variable names
		* if array, output will also be an array of 1s and 0s

keywords
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to prevent crashing the program

history
	vinay kashyap (MM.I)
	bug fix if input is scalar (VK; MM.X)
	added keyword verbose (VK; IMVIM.VIII)

(See /data/fubar/SCAR/pro/misc/legalvar.pro)


LEVMARQ

[Previous Routine] [Next Routine] [List of Routines]
procedure	levmarq
	Levenberg-Marquardt method, attempting to reduce the value chi^2 of a
	fit between a set of data points Y(X) with individual std.dev.s SIG,
	and a nonlinear function dependent of A parameters.  The input array
	IFIT indicates by non-zero entries those components of A that should
	be fitted for, and by 0 entries those components that should be held
	fixed at their input values.  The program returns current best-fit
	values for the parameters A and the value of CHISQ.  The arrays
	COVAR and ALPHA are used as working space during most iterations.
	Supply a routine FUNCS(x,a,yfit,dYdA) that evaluates the fitting
	function YFIT, and its derivatives dY/dA wrt fitting parameters A@X.
	On the first call, provide an initial guess for parameters A, and
	set ALAMDA < 0 for initialization.  If a step succeeds, CHISQ becomes
	smaller and ALAMDA decreases by a factor 10.  If a step fails, ALAMDA
	grows by a factor 3.  Call this routine repeatedly until convergence
	is achieved.  Then, make one final call with ALAMDA=0, so that COVAR
	returns the covariance matrix, and ALPHA the curvature matrix.  Those
	parameters held fixed will return zero covariances.

syntax
	levmarq,x,y,a,chisq,funcs=funcs,sig=sig,ifit=ifit,alamda=alamda,$
	jumpup=jumpup,jumpdn=jumpdn,ochisq=ochisq,alpha=alpha,covar=covar,$
	bvec=bvec,svdthr=svdthr,trial=trial,yfunc=yfunc,/tiptoe,$
	funcs=funcs,sig=sig,ties=ties, FUNCS_KEYWORDS

parameters
	x	[INPUT; required]
	y	[INPUT; required] size must match that of X
	a	[INPUT; required]
	chisq	[OUTPUT; required] the chi-sq statistic denoting degree of
		agreement between model and data

keywords
	ifit	[INPUT] integer array of same size as A, with 0's indicating
		frozen parameters and 1's indicating thawed parameters
		* if IFIT does not match A for any reason, all parameters
		  are assumed to be thawed
	jumpup	[INPUT; default=3] factor by which to increase ALAMDA if
		current trial fails
	jumpdn	[INPUT; default=0.1] factor by which to decrease ALAMDA if
		current trial succeeds
	alamda	[I/O] if not defined on input or is -ve, initializes the
		procedure.
	ochisq	[OUTPUT] the old value of the chi^2
	alpha	[OUTPUT] if ALAMDA=0, the curvature matrix
	covar	[OUTPUT] if ALAMDA=0, the covariance matrix
	bvec	[OUTPUT] the BETA fitting-vector
	svdthr	[INPUT; default=1e-6] threshold for singular values of
		diagonal SVD matrix
	trial	[OUTPUT] current trial values of the parameters
	yfunc	[OUTPUT] best-fit Y(X;A)
	tiptoe	[INPUT] if set, forces small steps on A
	verbose	[INPUT] controls chatter
	_extra	[INPUT] pass defined keywords to subroutines
		LMCOEFF: FUNCS, SIG
		ADJUSTIE: TIES
		FUNCS: whatever is needed

subroutines
	LMCOEFF
	SVDC
	SVSOL
	ADJUSTIE

history
	(C) Copr. 1986-92 Numerical Recipes Software =$j!]Y'1,).
	translated from MRQMIN.F to IDL by Vinay Kashyap (Oct98)
	changes: (i) matrix solution method from Gauss-Jordan elimination
	  to Singular-Value Decomposition; (ii) if trial fails, ALAMDA
	  increased by x{JUMPUP=3} instead of x10 and if trial succeeds,
	  decreased by x{JUMPDN=0.1} to avoid obvious oscillations;
	  (iii) call to COVSRT avoided; (iv) call to ADJUSTIE included;
	  (v) no resetting chisq within procedure (VK; Oct98)
	added keyword YFUNC (VK; Dec98)
	allowed "inversion" of 1-element "matrices" bypassing
	  SVDC and SVSOL (VK; Aug99)
	now returns correct chisq if all params are frozen (VK; JanMM)
	added keyword VERBOSE (VK; Nov04)

(See /data/fubar/SCAR/pro/levmarq.pro)


LIBMODEL

[Previous Routine] [Next Routine] [List of Routines]
procedure	libmodel
	computes F(X;A) and dF/dA for a library of model functions.
	procedure written to be compatible with FIT_LEVMAR, and also
	with IDL's CURVEFIT, GHRS-IDL's WFIT, etc.

syntax
	libmodel,x,a,f,pder,anew,type=type,verbose=verbose,$
	missing=missing,/norm,/fwhm,betap=betap,angle=angle,vrot=vrot,$
	Xo=Xo,pbreak=pbreak,NH=NH,wvlar=wvlar,effar=effar,exptime=exptime,$
	dellam=dellam,X0=X0,angrise=angrise,angfall=angfall,ybase=ybase,$
	yoff=yoff

parameters
	x	[INPUT; required] points at which to generate models
	a	[INPUT; required] array of parameter values
		* should match the number expected from TYPE.
		* no checks are made to verify that the user is not shooting
		  hirself in the foot.
	f	[OUTPUT; required] output f=f(x;a)
	pder	[OUTPUT; optional] partial derivatives for each parameter
	anew	[OUTPUT; optional] return a new set of A in which the
		normalization parameters have all been adjusted to account
		for the supplied RENORM

keywords
	type	[INPUT; required] string array denoting the model functions
		to be called.
		* this should rightly be a parameter, because it is
		  a very necessary part of the program.  however, most
		  fitting functions do not allow that degree of flexibility
		  and so we are forced to use this hack.
		* some models may be multiplicative (e.g., 'absorb'), and
		  their location in the TYPE array matters.  a multiplicative
		  model multiplies the model that is defined after it.  so
		  to apply the same absorption model to a powerlaw and a
		  gaussian, set
		    TYPE=['absorb','power','absorb','gauss']
		  and then use TIES=['a6=a1'],FREEZE=[6] to make sure the same 
		  absorption is applied to both components
	betap	[I/O] keyword passed w/o checking to MK_LORENTZ and MK_SLANT
	angle	[I/O] keyword passed w/o checking to MK_SLANT
	vrot	[I/O] keyword passed w/o checking to MK_ROGAUSS
	x0	[I/O] keyword passed w/o checking to MK_POWLAM,MK_BKNPOWER
	pbreak	[I/O] keyword passed w/o checking to MK_POWLAM,MK_BKNPOWER
	phase	[I/O] keyword passed w/o checking to MK_SINUSOID
	angrise	[I/O] keyword passed w/o checking to MK_LCECLIPSE
	angfall	[I/O] keyword passed w/o checking to MK_LCECLIPSE
	ybase	[I/O] keyword passed w/o checking to MK_LCECLIPSE
	yoff	[I/O] keyword passed w/o checking to MK_LCECLIPSE
	verbose	[INPUT; default=0] controls chatter
	renorm	[INPUT; default=1] renormalize the output by multiplying
		by this factor
		* the adjusted normalizations for each component that
		  correspond to this renormalization are returned in ANEW

	_extra	[INPUT] pass defined keywords to subroutines
		MK_GAUSS: MISSING, FWHM, NORM
		MK_LORENTZ: BETAP, MISSING, NORM
		MK_SLANT: ANGLE, BETAP, MISSING, NORM
		MK_ROGAUSS: VROT, FWHM, NORM, MISSING
		MK_POWLAM: XO,PBREAK,NH,WVLAR,EFFAR,EXPTIME,DELLAM
		MK_BKNPOWER: XO,NOBREAK,VERBOSE
		MK_POLY1D: X0
		MK_SINUSOID: PHASE, MISSING
		MK_LCECLIPSE: ANGRISE, ANGFALL, YBASE, YOFF
		MK_ABSORB: FH2,HE1,HEII,FANO,IKEV,WAM,BAM,MAM,NOHEH,ABUND
		MK_EFOLD: VERBOSE
		MK_BBANG: VERBOSE
		MK_BBKEV: VERBOSE
		MK_RECIPROCALPOW: VERBOSE
		MK_SPLINE1D: XLOC,USEINIT,TENSION,VERBOSe

subroutines
	MK_GAUSS
	MK_LORENTZ
	MK_SLANT
	MK_ROGAUSS
	MK_POWLAM
	MK_BKNPOWER
	MK_POLY1D
	MK_LCECLIPSE
	MK_ABSORB
	MK_EFOLD
	MK_BBANG
	MK_BBKEV
	MK_RECIPROCALPOW

history
	vinay kashyap (Aug01; based on X3MODEL and MK_3MODEL)
	added call to MK_SINUSOID (VK; Sep04)
	added call to MK_LCECLIPSE, allowed return of extra parameters
	  via keywords (VK; May07)
	added call to MK_BKNPOWER via "pow" and "pe"; added MK_ABSORB
	  via "absorb"; allowed for multiplicative as well as additive
	  models (VK; Jul08)
	added call to MK_EFOLD via "ef", "efold", and "exp" and to
	  MK_BBANG and MK_BBKEV via "bbang" and "bbkev" (VK; Aug08)
	added call to MK_RECIPROCALPOW via "reci/pow" and MK_SPLINE1D
	  via "spline=KNOTS"; added parameter ANEW and keyword RENORM
	  (VK; Sep08)

(See /data/fubar/SCAR/pro/libmodel.pro)


LIBMODEL_F

[Previous Routine] [Next Routine] [List of Routines]
procedure	libmodel_f
	function written to be compatible with MPFIT, and is
	identical in all respects to LIBMODEL, except that this
	is a function and not a procedure.
	returns F(X;A) and computes dF/dA for a library of model functions.

syntax
	f=libmodel_f(x,a,pder,type=type,verbose=verbose,$
	missing=missing,/norm,/fwhm,betap=betap,angle=angle,vrot=vrot,$
	Xo=Xo,pbreak=pbreak,NH=NH,wvlar=wvlar,effar=effar,exptime=exptime,$
	dellam=dellam,X0=X0)

parameters
	x	[INPUT; required] points at which to generate models
	a	[INPUT; required] array of parameter values
		* should match the number expected from TYPE.
		* no checks are made to verify that the user is not shooting
		  hirself in the foot.
	pder	[OUTPUT; optional] partial derivatives for each parameter

keywords
	type	[INPUT; required] string array denoting the model functions
		to be called.
		* this should rightly be a parameter, because it is
		  a very necessary part of the program.  however, most
		  fitting functions do not allow that degree of flexibility
		  and so we are forced to use this hack.
	verbose	[INPUT; default=0] controls chatter

	_extra	[INPUT] pass defined keywords to subroutines
		MK_GAUSS: MISSING, FWHM, NORM
		MK_LORENTZ: BETAP, MISSING, NORM
		MK_SLANT: ANGLE, BETAP, MISSING, NORM
		MK_ROGAUSS: VROT, FWHM, NORM, MISSING
		MK_POWLAM: XO,PBREAK,NH,WVLAR,EFFAR,EXPTIME,DELLAM
		MK_POLY1D: X0

subroutines
	MK_GAUSS
	MK_LORENTZ
	MK_SLANT
	MK_ROGAUSS
	MK_POWLAM
	MK_POLY1D

history
	vinay kashyap (Oct02; converted from LIBMODEL)

(See /data/fubar/SCAR/pro/libmodel_f.pro)


LICOSPEC

[Previous Routine] [Next Routine] [List of Routines]
procedure	licospec
	compute the contributions of line and continuum
	emissivities over a specified wavelength grid.

syntax
	licospec,wgrid,lspec,cspec,at_logT,lrf=lrf,lstr=lstr,cstr=cstr,$
	lemis=lemis,cemis=cemis,abund=abund,lcthr=lcthr,constr=constr,$
	ldbdir=ldbdir,cdbdir=cdbdir,ceroot=ceroot,verbose=verbose,$
	pres=pres,logP=logP,n_e=n_e,chifil=chifil,chidir=chidir,$
	eqfile=eqfile,logT=logT,DEM=DEM,effar=effar,wvlar=wvlar,$
	type=type,/norm,/fwhm,betap=betap,angle=angle,vrot=vrot

parameters
	wgrid	[INPUT; required] wavelength bin boundaries over
		which to compute line and continuum contributions
		* must be in same units as the wavelengths stored
		  in LDBDIR, i.e., Angstroms
	lspec	[OUTPUT; required] line emission at each wavelength bin
	cspec	[OUTPUT; required] continuum emission at each wavelength bin
		* note that these are essentially spectra, and include
		  the effects of specified abundance, DEM, and any input
	 	  RMFs, LRFs, or effective areas.
	at_logT	[INPUT] if set to a scalar, assumes a delta-function
		emission measure to compute the appropriate fluxes;
		the default is to assume a DEM that covers the range
		4..8 in logT (but note that any arbitrary DEM can be
		defined using keywords LOGT and DEM).
		* NOT TESTED

keywords
	lrf	[INPUT] if scalar, the width of the line response function
		NOTE: the function used to define the LRF can be set
		using the keyword TYPE (e.g., TYPE='gauss', TYPE='beta=2.5')
		* if float, the width in the same units as WGRID
		* if integer, the width in number of bins
		* if RMF structure (e.g., output of RD_OGIP_RMF()), use
		  it to convolve the output and place in channels defined
		  by WGRID indices (i.e., if LRF is defined as an RMF,
		  it _must_ match the wavelength grid)
	lstr	[I/O] line emissivity structure out of RD_LINE()*FOLD_IONEQ()
		* if defined on input, RD_LINE() and FOLD_IONEQ() will not
		  be called unless bounds of WGRID spill out, in which case
		  the user will be asked what to do
		* unlike LEMIS below, abundances are _not_ included
		  (unless in case of APED)
	cstr	[I/O] continuum emissivity structure out of RD_CONT() --
		* if defined on input, RD_CONT() will not be called unless
		  bounds of WGRID spill out, in which case the user will be
		  asked what to do
	ldbdir	[INPUT; '$CHIANTI'] line emissivity database directory
	cdbdir	[INPUT; '$CONT'] continuum emissivity database directory
	ceroot	[INPUT; 'cie'] prefix of files containing the continuum
		emissivities
	abund	[INPUT] element abundances to use while computing the
		continuum emissivities, the line and continuum fluxes,
		combining line emissivities into wavelenth bins, etc.
		* if not defined, calls GETABUND(!ABREF)
		* if !ABREF is not defined, adopts Grevesse et al.
	lemis	[OUTPUT] line emissivities recast to be on the input
		wavelength grid, i.e., an array of size N(LOGT)xN(WGRID)
		and with units [1e-23 ergs cm^3/s]
		* the output line emissivities _include_ the specified
		  ion balances and abundances
	cemis	[OUTPUT] continuum emissivities recast to be on the input
		wavelength grid, i.e., an array of size N(LOGT)xN(WGRID)
		and with units [1e-23 ergs cm^3/s]
		* NOTE: the /Ang usually present in continuum emissivities
		  is missing here
	lcthr	[INPUT] if set, combines the continuum emissivity from all
		the bins with LSPEC/CSPEC less than LCTHR and returns it
		in CONSTR
		* if negative, then combines all bins with CSPEC < LCTHR
	constr	[OUTPUT] continuum emissivity structure with the emissivities
		marginalized over wavelength
       allah   [INPUT] if set, no bounds of WGRID are not checked against 
               LSTR and the structure is used as is 
	verbose	[INPUT] controls chatter
	_extra	[INPUT ONLY] pass defined keywords to subroutines
		RD_LINE: PRES, LOGP, N_E
		FOLD_IONEQ: CHIFIL, CHIDIR, EQFILE
		RD_CONT: PRES, LOGP, N_E, ABUND
		LINEFLX: LOGT, DEM, ABUND, EFFAR, WVLAR
		LIBMODEL: TYPE, NORM, FWHM, BETAP, ANGLE, VROT

example
	;	make a wavelength grid
	wgrid=findgen(2001)*0.001+18. & lrf=0.02 & type='beta=2.5'
	;	call LICOSPEC
	licospec,wgrid,lspec,cspec,verbose=10,lstr=lstr,cstr=cstr,$
	lcthr=0.1,constr=constr,lemis=lemis,cemis=cemis,n_e=1e10,$
	lrf=lrf,type=type
	;	plot line to continuum flux ratio
	plot,wgrid,lspec/cspec,/ylog,$
	xtitle='wavelength [Ang]',ytitle='line-to-continuum'
	;	plot line and continuum integrated emissivities
	tmpl=dblarr(81) & for i=0,80 do tmpl[i]=total(lemis[i,*])
	tmpc=dblarr(81) & for i=0,80 do tmpc[i]=total(cemis[i,*])
	plot,lstr.LOGT,tmpl,/yl & oplot,cstr.LOGT,tmpc,thick=3,line=2
	;	integrated emissivities over a sub range
	oo=where(lspec/cspec lt 0.1)
	tmpl=dblarr(81) & for i=0,80 do tmpl[i]=total(lemis[i,oo])
	tmpc=dblarr(81) & for i=0,80 do tmpc[i]=total(cemis[i,oo])
	plot,lstr.LOGT,tmpl,/yl & oplot,cstr.LOGT,tmpc,thick=3,line=2

subroutines
	CONV_RMF [RD_OGIP_RMF]
	FOLD_IONEQ [RD_IONEQ [READ_IONEQ], WHEE]
	GETABUND
	HASTOGRAM [KILROY]
	LIBMODEL [MK_GAUSS, MK_LORENTZ, MK_ROGAUSS [MK_GAUSS], MK_SLANT]
	LINEFLX [GETABUND, WHEE]
	MID2BOUND
	RD_CONT [SETSYSVAL [LEGALVAR], SYMB2ZION [LAT2ARAB]]
	RD_LINE [INICON, SETSYSVAL [LEGALVAR], SYMB2ZION [LAT2ARAB]]
	REBINW [FINDEX]
	SETSYSVAL [LEGALVAR]
	IS_KEYWORD_SET

history
	vinay kashyap (Dec2003)
	added keywords LEMIS,CEMIS,LCTHR,CONSTR,ABUND,LDBDIR,CDBDIR,CEROOT;
	  corrected bug with CSTR.CONT_INT being degraded in repeated calls;
	  now -asks- if input wavelength range has changed and LSTR/CSTR do
	  not span this range (VK; Jan2004)
	cleaned up behavior of CSTR.CONT_INT for compatibility with RD_CONT();
	  now output LEMIS and CEMIS add up in photon space (VK; Apr2004)
       added ALLAH keyword to facilitate use of ZRESP keyword in
         SOLAR_TRESP() (LL; Sep2005) 
	updated for IDL5.6 keyword_set([0]) behavior change for vectors
	  (VK; 20Mar2006)

(See /data/fubar/SCAR/pro/licospec.pro)


LIKELI

[Previous Routine] [Next Routine] [List of Routines]
function	likeli
	returns p(D|M), the likelihood of observing the data for the
	given model.

	the default action is to return exp(-chi^2/2)

syntax
	prob=likeli(data,model,derror,dsigma=dsigma,ulim=ulim,$
	/binom,/chi2,/rchi,/cash,/castor,softlim=softlim)

parameters
	data	[INPUT; required] observed data
	model	[INPUT; required] predicted model or model parameters
	derror	[INPUT] errors on DATA
		* if specified, overrides keyword DSIGMA

keywords
	dsigma	[INPUT] errors on DATA
		* if not specified, taken to be 1+sqrt(abs(DATA)+0.75)
		* used only if DERROR is not present
	ulim	[INPUT] long-integer array specifying which elements of
		DATA are upper limits (1: UL, 0: not)
		* applies only to CHI2 and RCHI
	cash	[INPUT] if set, returns the Cash (19??, ApJ 228, 939) statistic
	castor	[INPUT] if set, returns the Castor correction to Cash
	binom	[INPUT] if set, likelihood is computed as
		    MODEL(0)^(d1)*(1.-MODEL(0))^(d0)
		where
		    d1=total(DATA(where(DATA ge BINOM))) and
		    d0=total(DATA(where(DATA lt BINOM)))
	chi2	[INPUT; default] if set, returns -alog(p(D|M))
	rchi	[INPUT] if set, returns alog(p(D|M))/n_elements(D)
		* priority: CASH supercedes CASTOR supercedes
		  BINOM supercedes CHI2 supercedes RCHI
	softlim	[INPUT] if set, then likelihood is unaffected when
		model values are below data values, and drops as a
		Gaussian centered on SOFTLIM*DSIGMA with error DSIGMA
		otherwise
		* if not set, upper limits are taken to be hard
		  limits, i.e., likelihood drops to 0 if model
		  values exceed data values
	_extra	[INPUT] junk -- here only to avoid crashing the program

history
	vinay kashyap (Mar 97)
	added keywords CASH and CASTOR (VK; Jul98)
	changed keyword name SIGMA to DSIGMA (VK; MMaug)
	had forgotten to actually include CASH and CASTOR in call (VK; May02)
	added parameter DERROR as a dupe for DSIGMA (VK; Jun05)
	BUGFIX to not crash if all DATA are upper limits (VK; Sep05)
	added keyword SOFTLIM (VK; May06)
	bug correction re SOFTLIM model estimate (VK; Jul07)
	corrected output to be same as all the others when /BINOM,/CHI2
	  is set or when /RCHI is set but not /CHI2 (VK; Apr08)
	fixed a lower bound of 1e-30 for model intensities for CASH per
	  discussion with Jan-Uwe (VK; Aug08)

(See /data/fubar/SCAR/pro/stat/likeli.pro)


LINEFLX

[Previous Routine] [Next Routine] [List of Routines]
function	lineflx
	computes observeable counts [ct/s] or flux [ergs/s] from spectral
	line for specified DEM by simple trapezoidal integration over
	temperatures.
	if effective area is not specified, output will be [ph/s/cm^2]
	or [ergs/s/cm^2]

	input line emissivities are in [1e-23 ergs cm^3/s].  these include
	ionization balance, but not (necessarily) abundances.  the line
	emissivities are multiplied by the differential emission measure
	and element abundance to get fluxes, then divided by the line energy
	to get photon fluxes, and multiplied by the supplied effective areas
	to get count rates.  no effort is made to determine line profiles
	or to include spectral responses (beyond the effective areas).

syntax
	fx=lineflx(line,logT,wvl,Z,DEM=DEM,/temp,abund=abund,/noph,$
	nhne=nhne,effar=effar,wvlar=wvlar,/ikev,/noabund)

parameters
	line	[INPUT; required] array of line cooling emissivities
		in units of 1e-23 erg cm^3/s
		* if 2D array, LINE==LINE(logT,WVL)

		* WARNING: will return garbage if given 1D array LINE(WVL)
		  (or even 2D array LINE(1,WVL))
		  use a for-loop to handle such a case

		* WARNING: will get converted to 1-element vector if input
		  as scalar
	logT	[INPUT; required] array of log10(Temperature [K]) at
		which emissivities are given.
		* array size MUST match that of LINE
		* if not regularly gridded, remember to set REGRID!
	wvl	[INPUT; required] wavelength(s) [Angstrom] of lines at
		which LINE is given
		* array size MUST match LINE
	Z	[INPUT] atomic number of element that generates each WVL
		* if Z has less elements than WVL, Z is ignored
		* if Z is to be ignored, all lines are assumed to be from
		  same element, and abundance values are ignored

keywords
	DEM	[INPUT] Differential Emission Measure at each T [cm^-5/logK]
		* default is a constant=1e14!!
		* if array size does not match that of LOGT, then DEM is
		  assumed to cover the same range and is linear interpolated
		* if defined at only 1 temperature, assumed to be EM [cm^-5]
	temp	[INPUT] if set, assumes that logT is actually in T [K], and
		that DEM is given in units of [cm^-5/K]
		* ignored if logT is defined at only one bin
	abund	[INPUT] abundances relative to H (abund(0)=1)
		* abund(Z-1) contains the abundance for element Z
		* if array size is smaller than the largest present Z,
		  the last element is replicated to fill the gap
		* default: Anders & Grevesse (1989)
	noph	[INPUT] if set, does not do the conversion to [ph] from [ergs]
	nhne	[INPUT] the ratio of N(H)/n_e needed to complete the
		intensity calculation
		* if not set, assumes 0.83, which is the limiting value
		  for high-temperature plasma with approximately cosmic
		  abundances
		* if array and size does not match LOGT, then uses only
		  the first element
		* if Z is not defined, then it is **IGNORED**
		* see discussion in the documentation of POPSOL()
	effar	[INPUT] effective area [cm^2]
		* if not set, assumed to be 1 cm^2
	wvlar	[INPUT] wavelengths at which effective area is defined.
		* if not set, assumed to be WVL
		* array size MUST match that of EFFAR
	ikev	[INPUT] if set, assumes that WVL and WVLAR are in [keV],
		NOT [Angstrom]
	noabund	[INPUT] if set, ABUND values are ignored in the calculations,
		same as though they (or Z) had been set to 1
	regrid	[INPUT] if set, assumes that LOGT is irregularly sampled
		and regrids it (and LINE) to a regular grid
		* NOT IMPLEMENTED YET
	_extra	[INPUT] junk -- here only to prevent crashing the program

subroutines
	GETABUND
	WHEE

usage examples
	* f=lineflx(rd_line(logP=20,wvl=w,logT=T,/allah),T,w,dem=10.D^(5*t))
	* fl=rd_line(wr=16.776,wvl=w,logT=T,/allah) & t=10.^(t)
	  f=lineflx(fl,T,w,dem=10.D^(5*alog10(t)),/temp)

history
	vinay kashyap (Nov96)
	added keywords EFFAR and WVLAR (VK; Jan96)
	added call to WHEE, removed call to KILROY,
	  ensured DEM stretches to fit logT, added case of EM masquerading
	  as DEM, removed the [/sr] from the output (VK; Feb97)
	changed integration style; restructured to ignore effective area
	  if not supplied; added keyword REGRID (VK; Apr97)
	corrected ln v/s log10 bug (VK; Jun97)
	added keyword NOPH; bug correction -- dlogT should in in base 10
	  (VK; Jan98)
	changed keyword KEV to IKEV (VK; DecMM)
	EFFAR and WVLAR ignored if set to 0 (VK; JanMMI)
	added keyword NHNE (VK; Jun02)
	added keyword NOABUND (VK; Apr03)
	changed bad input check from LINE(0)=-1 to total(LINE)=-N(LINE)
	  (VK; Feb06)
	changed back integration style to simple from trapezoidal (VK; Mar06)
	changed check for whether WVL are given (VK; Jun07)

(See /data/fubar/SCAR/pro/lineflx.pro)


LINEID

[Previous Routine] [Next Routine] [List of Routines]
function	lineid
	allows identification of spectral features and returns ID
	information in a structure (see structure variable IDHLP
	for complete description of fields)

syntax
	id=lineid(lamda,spec,elem,wrng=wrng,wshift=wshift,locmax=locmax,$
	best=best,topX=topX,batch=batch,stor=stor,oldid=oldid,omatch=omatch,$
	markw=markw,feature=feature,verbose=verbose,$
	n_e=n_e,logP=logP,pres=pres,dbdir=dbdir,/allah,chifil=chifil,$
	eqfile=eqfile,chidir=chidir,dem=dem,abund=abund,effar=effar,$
	wvlar=wvlar,sigmay=sigmay,xsize=xsize,ysize=ysize,wid=wid,$
	dynrng=dynrng,markp=markp,marks=marks,marko=marko,$
	/nuthin,/noday,/notime,/nouser,/nopack,stacol=stacol,stasiz=stasiz,$
	stathk=stathk)

parameters
	lamda	[INPUT; required] wavelength(s) at which spectrum is defined
		* interactive if LAMDA is a multi-element array, batch mode
		  otherwise (also see keyword BATCH)
	spec	[INPUT; optional] the spectrum
		* default is 10+random
		* if SPEC is a character string or array, taken to be ELEM
		* if LAMDA and SPEC do not match in size, taken to be atomic
		  numbers
	elem	[INPUT; optional] confine matches to this particular element
		* overrides anything inferred "via" SPEC

keywords
	wrng	[INPUT] interval in which to search for matches
		* default is WRNG=0.01
		* if scalar and between 0 and 1, look for matches in the range
		  	[W-W*WRNG,W+W*WRNG]
		* if scalar and > 1, or scalar and < 0, abs(WRNG) is assumed
		  to be the actual step size and is used as is, i.e.,
		  	W+abs(WRNG)*[-1,1]
		* if 1-element vector, then range is W+abs(WRNG(0))*[-1,1]
		* if multi-element vector, then [W-WRNG[0],W+WRNG[1]]
		* NOTE: in interactive mode the range may be altered, but
		  the >behavior< of the range is set by the initial values.
		* also note that WRNG is not changed on output.
	wshift	[INPUT] amount by which to shift the wavelength scale
		* WRNG will be reset to WRNG+WSHIFT
	locmax	[INPUT] if set, finds matches at all local maxima
		* search window width (2*abs(LOCMAX)+1)>3
	best	[INPUT] if set, returns "best" match -- the strongest
		possible nearest line
		* obviously, there is weighting involved
		* BEST.GE.0: pick largest of Flx[w]/(w-w0)^BEST
		* otherwise: return the nearest match(es)
	topX	[I/O; default: 20] returns at most TOPX matches
		* MUST be scalar
		* in interactive mode, presents only TOPX for matching choice
		* if 0 < TOPX < 1, uses this as a >threshold<, selecting only
		  those lines whose theoretical predicted fluxes are this
		  fraction or higher than the maximum flux in the set.
		* if TOPX < 0, the integer value is used as the upper limit
		  to number of matches, and the fractional value is used as
		  the threshold.
		* may get altered within LINEID_MENU
		* examples:
		  TOPX = 0 brings up 20 matches
		  TOPX = 10 brings up 10 matches
		  TOPX = 0.6 brings up all lines with fluxes > 0.6 of max
		  TOPX = -40.01 brings up 40 lines with fluxes > 1% of max
	batch	[INPUT] if set, operates in batch mode (i.e., no widget-based
		selections)
		* batch mode is also forced if:-
		  o N_ELEMENTS(LAMDA)=1
		  o LOCMAX is set
		  o TOPX is set to 1
		  o !D.NAME is not 'X'
	stor	[I/O] if present in call, will store the output of RD_LINE and
		FOLD_IONEQ as a structure.  if a structure, then MUST be of
		the form {LINE_INT,LOGT,WVL,Z,ION,DESIG,CONFIG}, because
		then RD_LINE and FOLD_IONEQ will be bypassed!
		* use with caution!!
	oldid	[INPUT] if set and is in the same format as the output of
		LINEID, starts off from this point.  i.e., things can be
		added or modified from here on.
	omatch	[INPUT] if OLDID is given *and* OMATCH is set, forces each
		wavelength selection to match the nearest matched wavelength
		in OMATCH.
		* if OMATCH < 0, won't verify, but will force a match if
		  new location is within abs(OMATCH), and will force a new
		  match otherwise
		* if OMATCH > 0, will ask
	markw	[INPUT] if set, places marks on the plot at these wavelengths
	feature	[INPUT] labels for MARKW
		* passed with minimal modification to PICKRANGE
	verbose	[INPUT] controls chatter
	wrange	[IGNORED] keyword for RD_LINE, will be trapped and ignored.
	temp	[IGNORED] keyword for LINEFLX, will be trapped and ignored.
	_extra	[INPUT ONLY] pass predefined input keywords to subroutines:
		pres	(RD_LINE) pressure [cm^-3 K]
		logP	(RD_LINE) log10(pressure [cm^-3 K])
		n_e	(RD_LINE) electron density [cm^-3]
		dbdir	(RD_LINE) line emissivity database
		allah	(RD_LINE) which elements to choose
		chifil	(FOLD_IONEQ) set to read CHIANTI ion balance files
		eqfile	(FOLD_IONEQ) name of ion balance file
		chidir	(RD_IONEQ) location of CHIANTI installation
		DEM	(LINEFLX) Differential Emission Measure distribution
		abund	(LINEFLX) abundances
		effar	(LINEFLX) effective area [cm^2]
		wvlar	(LINEFLX) wavelength grid for EFFAR
		sigmaY	(PICKRANGE) error-bars on SPEC
		xsize	(PICKRANGE) window size
		ysize	(PICKRANGE) window size
		wid	(PICKRANGE) window ID
		dynrng	(PICKRANGE) dynamic range in log scale
		markp	(PICKRANGE) PSYM for (FEATURE,MARKW)
		marks	(PICKRANGE) SYMSIZE for (FEATURE,MARKW)
		marko	(PICKRANGE) ORIENTATION for (FEATURE,MARKW)
		oxr	(PICKRANGE) final output XRANGE
		oyr	(PICKRANGE) final output YRANGE
		nuthin	(STAMPLE) don't stamp the plots
		noday	(STAMPLE) don't stamp the plots with day
		notime	(STAMPLE) don't stamp the plots with time
		nouser	(STAMPLE) don't stamp the plots with username
		nopack	(STAMPLE) don't stamp the plots with package name
		stacol	(STAMPLE) stamp color
		stasiz	(STAMPLE) stamp size
		stathk	(STAMPLE) stamp thickness

description
	read in database of line cooling intensities and for each observed
	wavelength which requires a match, find the set of matches.  if
	interactive, allow selection of multiple matches.  once done,
	reorganize into structure of
	{WVL: observed wavelength;
	  {corresponding
	    WVL: matched wavelengths,
	    Z: atomic numbers,
	    ION: ionic states,
	    LABL: e-configurations or whatever is available,
	    FLUX: theoretical fluxes for all new or modified matches
	    	(fluxes in OLDID are not touched unless ID is changed),
	    FLUXERR: errors on FLUX (set to zero),
	    LOGT: temperatures at which emissivities are defined
	    EMIS: line emissivities for all IDs (ion-balance included)
	    NOTES: scribbles about this ID, for human eyes only
	  }
	}

restrictions
	requires IDL v5 or greater
	interactive selections require X-windows
	requires subroutines
	    RD_LINE [KILROY, SYMB2ZION [LAT2ARAB]]
	    FOLD_IONEQ [WHEE, GETLOCMAX, RD_IONEQ [READ_IONEQ]]
	    LINEFLX [WHEE]
	    GETLOCMAX
	    PICKRANGE
	    LINEID_MENU [CAT_ID]
	    CREATE_STRUCT
	    KABOOM
	    INICON
	    STR_2_ARR

usage examples
	* lid=lineid(12.3985/7.83,['Fe','Ni'],wr=0.1*[1,1],topX=50)
	* stor=1 & lid=lineid(x,y,wr=[1],/allah,logP=20,stor=stor)
	  lid=lineid(x,y,wr=[1],/allah,logP=20,stor=stor)
	* lid=lineid(x,y,'Fe',logP=20,econf=0)

history
	vinay kashyap (Dec96)
	bug corrections: ion balance in STOR, format sizes in menu input;
	  added ID history info to PICKRANGE and menu; added keyword OLDID
	  (VK; Feb97)
	added keyword OMATCH; allowed expeditious return when no matches
	  found (VK; Jun98)
	modified behavior of STOR to eliminate excess variables (VK; Oct98)
	added LOGT and EMIS (EMIS includes ion balance) to the output; bug
	  correction re STOR not being specified; corrected bug with
	  BEST actually returning the worst; added keywords BATCH, MARKW,
	  FEATURE; added calls to KABOOM, INITSTUFF, STR2ARR; TOPX now acts
	  as threshold too; added support for multiple grating orders
	  (VK; Nov98)
	changed behavior of WRANGE; added renormalization of fluxes; bug fix
	  older matches not echoing in menu window; added field FLUXERR to
	  ID structure (VK; Dec98)
	added field NOTES to ID structure (VK; Mar99)
	modified ion balance calcs (VK; 99May)
	changed call to INITSTUFF to INICON (VK; 99May)
	changed to full IDL5+ compatibility ("()"->"[]"); stor does not
	  have to be defined on input, just be present in the call; added
	  dummy keywords WRANGE and TEMP (VK; AugMM)
	added keyword VERBOSE, and now doesn't default to random if NX eq NY+1
	  (i.e., bin boundaries are given rather than mid-bin values: VK; Nov01)
	changed call to STR_2_ARR from STR2ARR (VK; AprMMV)

(See /data/fubar/SCAR/pro/lineid.pro)


LINEID_MENU

[Previous Routine] [Next Routine] [List of Routines]
function	lineid_menu
	function to select matches to wavelengths and return position
	indices of selected matches.

syntax
	oo=lineid_menu(menu,w0,w,f,wshift,topX,wrange,cord,code,scratch,$
	wvls=wvls,idwvls=idwvls,gwvl=gwvl,renorm=renorm)

parameters
	menu	[INPUT] list of items to choose from; string array
	w0	[INPUT] wavelength that needs match
	w	[INPUT] wvls of matched lines (must be of same size as MENU)
	f	[INPUT] fluxes of all matched lines (same size as MENU)
	wshift	[I/O] wavelength shift
	topX	[I/O] maximum number of matches
	wrange	[I/O] interval in which to search for matches
	cord	[I/O] comma-separated list of grating orders
	code	[OUTPUT] 0: NEXT WAVELENGTH
			 1: QUIT LINEID
			 2: REPEAT FOR NEW PARAMETERS
	scratch	[OUTPUT] human readable notation

keywords
	wvls	[INPUT] wavelengths which are previously identified
	idwvls	[INPUT] structure describing IDs 
	gwvl	[INPUT] grating-order corrected wavelengths
	renorm	[INPUT] renormalization factor

restrictions
	* widget based
	* dedicated subroutine to LINEID (written simply to avoid
	  making LINEID too large to comprehend)
	* no error checking is done.  it is assumed that this function
	  is called from LINEID, and naught else.
	* requires subroutines
	  -- CAT_ID
	  -- CREATE_STRUCT

warning
	* here be hippogrif
	* don't even <<think>> about understanding this program

history
	author of this hack prefers anonymity, thank you very much (Dec96)
	some cosmetic surgery, added button STATUS and call to CAT_ID (Feb97)
	corrected bug with reordering (Jul98)
	added CORD, GWVL, changed TOP field from /LONG to /FLOAT (Nov98)
	changed behavior of UNDO LAST; renamed NEXT as HELP; renamed DONE
	  as NEXT; added keyword RENORM and entry field PARS_NORM; changed
	  MBAR_NEXT to MBAR_HELP (Dec98)
	added output SCRATCH (Mar99)
	bug correction re SCRATCH (FebMM)

(See /data/fubar/SCAR/pro/lineid_menu.pro)


LINEREM

[Previous Routine] [Next Routine] [List of Routines]
function	linerem
	remove lines from input spectrum and return the "cleaned" spectrum

syntax
	cleanspec=linerem(lamda,spec,sig=sig,cell=cell,nsigma=nsigma,$
	bkgval=bkgval,bkgerr=bkgerr,/quiet,/posve,/negve)

parameters
	lamda	[INPUT; required] wavelengths at which spectrum
		is defined.
	spec	[INPUT; optional] the spectrum.
		NOTE: if not given, LAMDA is taken to be SPEC and
		the array indices are taken to be LAMDA

keywords
	sig	[INPUT] error at each point; if not given, the
		errors are taken to be 1+sqrt(abs(SPEC)+0.75).
	nsigma	[INPUT; default: 4] multiple of SIG to consider
		as a threshold for detection of features
	cell	[INPUT] 1D filter to use in computing the background
		* default is [1,1,0,0,0,1,1]
		* if scalar, then [IC+1,ICC,IC+1], where
		  IC=intarr(2*CELL), ICC=intarr(2*CELL+1)
	bkgval	[OUTPUT] final background values at each bin
		NOTE: This is essentially a smoothed version of
		the cleaned spectrum!
	bkgerr	[OUTPUT] error estimates on BKGVAL
	quiet	[INPUT] if set, doesn't show, doesn't tell
	posve	[INPUT] if set, removes only +ve deviations
	negve	[INPUT] if set, removes only -ve deviations
	_extra	[JUNK] here only to prevent crashes

description
	1. make sure that the spectrum is defined on a regular grid.
	   (if not, rebin [NOT IMPLEMENTED!])
	2. convolve the spectrum with background cell to determine
	   local background.
	3. also propagate errors (assume gaussian; if poisson, use
	   gaussian approximation)
	4. compare local value with local background
	5. flag those bins which are significantly different from local
	   background (use +-NSIGMA*SIG as a threshold value)
	6. reset the flagged bin values to local background values
	7. repeat 2-6 until no new bins are flagged

history
	vinay kashyap (Oct96)
	changed keyword SIGMA to SIG (VK; Jun98)
	CELL was being altered if input as scalar -- corrected; altered
	  behavior of output when no deviations are found (VK; Oct98)
	now if QUIET>1, won't ask to quit if many bins are found (VK; 99Aug)
	changed POS and NEG to POSVE and NEGVE (VK; MMJul)

(See /data/fubar/SCAR/pro/linerem.pro)


LINESPEC

[Previous Routine] [Next Routine] [List of Routines]
function	linespec
	returns a spectrum of atomic lines.  output will be in units
	of [erg,ph]/s/cm^2/[keV,Ang]
	
	if IKEV is set, WMIN,WMAX,WW must be input in [keV] and the
	output will have units .../keV

	if NOPH is set, output will have units of erg/...

	if EFFAR and WVLAR are not set, output will have units of .../cm^2

syntax
	spec=linespec(atom,wmin=wmin,wmax=wmax,nbin=nbin,/wlog,ww=ww,/ikev,$
	fstr=fstr,pres=pres,logP=logP,n_e=n_e,desig=desig,econf=econf,$
	/allah,dbdir=dbdir,dem=dem,abund=abund,effar=effar,wvlar=wvlar,$
	/noph,chifil=chifil,chidir=chidir,eqfile=eqfile,verbose=verbose)

parameters
	atom	[INPUT; default: all] element(s) whose line intensities are
		to be read.
		* can specify ionic state (e.g., 'FeXX')
		* may be an array (e.g., ['He', 'c 5', 'N V', 's_8'])

keywords
	wmin	[I/O] minimum value of wavelength range
		* default is 1.23985A (10 keV)
		* overwritten if WW is set
	wmax	[I/O] maximum value of wavelength range
		* default is 900A
		* overwritten if WW is set
	nbin	[I/O] number of bins in spectrum
		* default is 100
		* overwritten if WW is set
	wlog	[I/O] if set, binning will be logarithmic
	ww	[I/O] if set as an array on input, assumed to be the
		bin boundaries --
		* NBIN will be reset to n_elements(WW)-1 on output
		* WMIN will be reset to min([WW(0),WW(nbin)]) on output
		* WMAX will be reset to max([WW(0),WW(nbin)]) on output
	ikev	[INPUT] if set, WMIN,WMAX,WW are all assumed to be in keV
		* it is also caught at this stage and is not passed down to
		  LINEFLX
	fstr	[I/O] if defined on input, will return all the spectral
		lines info LINE_INT,LOGT,WVL,Z,ION,DESIG,ECONF in that order
		in a structure.
		* ion balance is included in LINE_INT, but abundances
		  are not.
		* if defined as a structure on input, RD_LINE and FOLD_IONEQ
		  will not be called, so use with caution!
	_extra	[INPUT] allows specifying defined keywords to subroutines
		called by this program
		* RD_LINE: PRES,LOGP,N_E,DESIG,ECONF,ALLAH,DBDIR,VERBOSE
		* FOLD_IONEQ: CHIFIL,VERBOSE
		* RD_IONEQ: CHIDIR,EQFILE
		* LINEFLX: DEM,ABUND,EFFAR,WVLAR,NOPH

subroutines
	RD_LINE [KILROY, SYMB2ZION [LAT2ARAB]]
	FOLD_IONEQ [WHEE, GETLOCMAX, RD_IONEQ [READ_IONEQ (CHIANTI)]]
	LINEFLX [WHEE]
	HASTOGRAM [KILROY]

history
	vinay kashyap (Jan97)
	included ion balance into FSTR (VK;Feb97)
	bug -- crashes when FSTR not specified (VK;Mar97)
	speeded up spectrum accumulation by adding call to HASTOGRAM (VK;Jan98)
	modified ion balance calcs (VK; 99May)
	changed keyword KEV to IKEV; DESIG and ECONF must be explicitly set
	  to 0 to avoid reading them in in RD_LINE; streamlined IKEV behavior
	  (VK; JanMMI)

(See /data/fubar/SCAR/pro/linespec.pro)


LINESPEC_EM

[Previous Routine] [Next Routine] [List of Routines]
function	linespec_em
	returns a spectrum of atomic lines for a 1-T EM.  output will be in
	units of [erg,ph]/s/cm^2/[keV,Ang]
	
	if IKEV is set, WMIN,WMAX,WW must be input in [keV] and the
	output will have units .../keV

	if NOPH is set, output will have units of erg/...

	if EFFAR and WVLAR are not set, output will have units of .../cm^2

syntax
	spec=linespec_em(atom,wmin=wmin,wmax=wmax,nbin=nbin,/wlog,ww=ww,/ikev,$
	tlog=tlog,EM=EM,fstr=fstr,pres=pres,logP=logP,n_e=n_e,desig=desig,$
	econf=econf,/allah,dbdir=dbdir,abund=abund,effar=effar,wvlar=wvlar,
	/noph,chifil=chifil,chidir=chidir,eqfile=eqfile,verbose=verbose)

parameters
	atom	[INPUT; default: all] element(s) whose line intensities are
		to be read.
		* can specify ionic state (e.g., 'FeXX')
		* may be an array (e.g., ['He', 'c 5', 'N V', 's_8'])

keywords
	wmin	[I/O] minimum value of wavelength range
		* default on input is 1.23985A (10 keV)
	wmax	[I/O] maximum value of wavelength range
		* default on input is 900A
	nbin	[I/O] number of bins in spectrum
		* default on input is 100
	wlog	[I/O] if set, binning will be logarithmic
	ww	[I/O] if set as an array on input, assumed to be the
		bin boundaries --
		* NBIN will be set to n_elements(WW)-1 on output
		* WMIN will be set to min([WW(0),WW(nbin)]) on output
		* WMAX will be set to max([WW(0),WW(nbin)]) on output
	ikev	[INPUT] if set, WMIN,WMAX,WW are all assumed to be in keV
		* it is also caught at this stage and is not passed down to
		  LINEFLX
	fstr	[I/O] if defined on input, will return all the spectral
		lines info LINE_INT,LOGT,WVL,Z,ION,DESIG,ECONF in that order
		in a structure.
		* ion balance is included in LINE_INT, but abundances
		  are not.
		* if defined as a structure on input, RD_LINE and FOLD_IONEQ
		  will not be called, so use with caution!
	tlog	[INPUT] log10(T [K]) at which EM is defined
	EM	[INPUT] Emission Measure [cm^-5; if not, output units
		must be suitably mangled]
	_extra	[INPUT] allows specifying defined keywords to subroutines
		called by this program
		* RD_LINE: PRES, LOGP, N_E, DESIG, ECONF, ALLAH, DBDIR
		* FOLD_IONEQ: CHIFIL
		* RD_IONEQ: CHIDIR, EQFILE
		* LINEFLX: DEM, ABUND, EFFAR, WVLAR, NOPH

subroutines
	RD_LINE [KILROY, SYMB2ZION [LAT2ARAB]]
	FOLD_IONEQ [WHEE, GETLOCMAX, RD_IONEQ [READ_IONEQ (CHIANTI)]]
	LINEFLX [WHEE]
	HASTOGRAM [KILROY]

history
	vinay kashyap (Apr97; modified from LINESPEC.PRO)
	speeded up spectrum accumulation by adding call to HASTOGRAM;
	  speeded up cycling thru lines by modifying DEM (VK;Jan98)
	modified ion balance calcs (VK; 99May)
	changed keyword KEV to IKEV; DESIG and ECONF must be explicitly set
	  to 0 to avoid reading them in in RD_LINE; streamlined IKEV behavior
	  (VK; JanMMI)

(See /data/fubar/SCAR/pro/linespec_em.pro)


LINE_CHIANTI

[Previous Routine] [Next Routine] [List of Routines]
FUNCTION	line_chianti
	returns a 2D array containing line cooling emissivities at a set of
	temperatures for all available spectral lines (in a CHIANTI style
	database [http://wwwsolar.nrl.navy.mil/chianti.html]) for the
	specified element at the specified pressure or density
	[1e-23 erg cm^3 s^-1] (NTEMP,NANG)
	NOTE: Ion Balance is NOT included!!!

SYNTAX
	fx=line_chianti(elem,pres,logT,ang,trans,kev=kev,ikey=ikey,jkey=jkey,$
	econf=econf,wmn=wmn,wmx=wmx,n_e=n_e,istate=istate,/tex,chidir=chidir)

PARAMETERS
	elem	[INPUT; required] name of element e.g., "He", "C", etc.
		* may specify ionic state (e.g., 'Fe XXII')
		* if an array, only the first element is looked at
	pres	[INPUT; default: 1e15 cm^-3 K] pressure at which to compute
		level populations
	temp	[INPUT/OUTPUT] log(Temperature[K]) at which to compute the
		line fluxes.  if not given, then TEMP=4.0+FINDGEN(81)*0.05
		* best results if evenly spaced in log(T)
	ang	[OUTPUT] all the wavelengths [Angstrom]
	trans	[OUTPUT] 2D array of transitions --
		trans[0,*] lower levels; trans[1,*] upper levels

KEYWORDS
	kev	[OUTPUT] all the line energies (same as ANG, but in [keV])
	ikey	[OUTPUT] ionic state of element producing the line at ANG
	jkey	[OUTPUT] ionic state that matters to ion balance
	econf	[OUTPUT] 2D string array of e-configurations --
		econf[0,*] lower levels; econf[1,*] upper levels
	wmn	[INPUT; default: 0 Angstrom] minimum value of wavelength
		to include in output
	wmx	[INPUT; default: 900 Angstrom] maximum value of wavelength
		to include in output
	n_e	[INPUT] electron density [/cm^3]
		* OVERRIDES values determined using PRES and TEMP
	istate	[INPUT; default: ALL; overridden by ELEM] limit calculations
		to specified ionic states (1=neutral, 2=singly ionized, etc.;
		can be an array)

	_extra	[INPUT ONLY] used to specify
		* /TEX -- TRANS in TeX format (1) or not (0)
		* CHIDIR -- path name to the CHIANTI installation

RESTRICTIONS
	* uses the CHIANTI database
	* requires subroutines:
	  -- GET_IONLIST
	  -- SYMB2ZION [LAT2ARAB]
	  -- RD_CHIANTI [READ_WGFA2(%), READ_ELVLC(%), READ_SPLUPS(%), READ_IP(%)]
	  -- POPSOL [DESCALE_UPS(%), NENH]
	  -- TRANSLABEL
	  -- KILROY
	  -- IS_KEYWORD_SET
	  (%): CHIANTI subroutine, used as is

HISTORY
	vinay kashyap (Nov96)
	removed ion balance, changed input keyword CONF to output ECONF,
	  changed mult. factor from 1e30 to 1e23 (VK; Dec96)
	added level excitation check (VK; Jun97)
	corrected bug with TEMP specification; forced ELEM to be scalar
	  (VK; Nov98)
	changed call from POPLEV to POPSOL (VK; SepMM)
	added keyword JKEY; corrected calls to modifications of GET_IONLIST,
	  RD_CHIANTI, and POPSOL to account for dielectronic recombination
	  lines; converted syntax to IDL5 (VK; OctMM)
	bug correction: CHIDIR was not being passed on;	caught and
	  filtered -ve population levels (VK; DecMM)
	bug correction: transition labels were being filtered on wavelength
	  twice, once within TRANSLABEL and once here.  now forced the range
	  in TRANSLABEL to be ignored (VK; Jun01)
	bug correction: was failing if ELEM contained ION info (VK; May02)
	modified call to POPSOL, per CHIANTI 4.2 changes (VK; Apr04)
	updated for IDL5.6 keyword_set([0]) behavior change for vectors
	  (VK; 20Mar2006)

(See /data/fubar/SCAR/pro/mkemis/line_chianti.pro)


LINE_SPEX

[Previous Routine] [Next Routine] [List of Routines]
procedure	line_spex
	IDL procedure that completes the task begun by line_spex.f
	i.e., it converts the line emissivity info contained in
	the files in the current directory and reorganizes it in
	a form that may be read in with RD_LINE.PRO

syntax
	line_spex,z=z,outdir=outdir

parameters	NONE

keywords
	Z	[INPUT; default: ALL] element, ionic state (e.g.:'He','Fe XII')
	outdir	[INPUT; default: emisspex] directory tree under which to
		store the output files

side-effects
	deposits (possibly large) files in OUTDIR
	* ATOM_wvl	wavelengths of all the transitions
	* ATOM_tem	temperatures
	* ATOM_##.#	line intensities I(tem,wvl)@logP
	* ATOM_ion	ionic states corresponding to wvl
	* ATOM_jon	ionic states that actually *determine* intensities
	* ATOM_src	source of line information
			1: SPEX
	* ATOM_lvl	description of each transition
	* ATOM_ecn	blank array, for consistency with CHIANTI (and
			hopefully future implementation)

history
	vinay kashyap (Jan97)
	changed N_PRES from 11 to 8 (VK; Jun97)
	added call to INITSTUFF, added ATOM_jon as output, etc (VK; May99)

(See /data/fubar/SCAR/pro/mkemis/line_spex.pro)


LINE_SPEXD

[Previous Routine] [Next Routine] [List of Routines]
procedure	line_spexD
	IDL procedure that completes the task begun by line_spexD.f
	i.e., it converts the line emissivity info contained in
	the files in the current directory and reorganizes it in
	a form that may be read in with RD_LINE.PRO

syntax
	line_spexD,z=z,outdir=outdir

parameters	NONE

keywords
	Z	[INPUT; default: ALL] element, ionic state (e.g.:'He','Fe XII')
	outdir	[INPUT; default: emisspexD] directory tree under which to
		store the output files

side-effects
	deposits (possibly large) files in OUTDIR
	* ATOM_wvl	wavelengths of all the transitions
	* ATOM_tem	temperatures
	* ATOM_##.#	line intensities I(tem,wvl)@log(n_e)
	* ATOM_ion	ionic states corresponding to wvl
	* ATOM_jon	ionic states that actually *determine* intensities
	* ATOM_src	source of line information
			1: SPEX
	* ATOM_lvl	description of each transition
	* ATOM_ecn	blank array, for consistency with CHIANTI (and
			hopefully future implementation)

history
	vinay kashyap (based on line_spex.pro; Jun97)
	changed densities to go from 8..15 in steps of 1 dex instead of
	  7.7..14 (change done to match with CHIANTI) (VK; Dec98)
	added call to INITSTUFF, added ATOM_jon as output, etc (VK; May99)

(See /data/fubar/SCAR/pro/mkemis/line_spexD.pro)


LMCOEFF

[Previous Routine] [Next Routine] [List of Routines]
procedure	lmcoeff
	used by LEVMARQ (formerly MRQMIN.F) to evaluate the linearized
	fitting matrix ALPHA and vector BVEC (BETA in Numerical Recipes)
	and calculate chi^2

syntax
	lmcoeff,x,y,a,funcs=funcs,sig=sig,ifit=ifit,alpha=alpha,bvec=bvec,$
	chisq=chisq,yfunc=yfunc,poisson=poisson

parameters
	x	[INPUT; required] data points
	y	[INPUT; required] Y(X)
		* sizes of X and Y must match
	a	[INPUT; required] parameters for user-supplied procedure

keywords
	funcs	[INPUT] name of user-defined procedure that takes as input X
		and A, and returns YMODEL(X;A), and the partial derivatives
		of the model function wrt A.  Any procedure that was written
		to work with CURVEFIT or GHRS' WFIT will do.
		* default is set to X3MODEL
		* why is it a procedure and not a function?
		  well, ask the person who wrote CURVEFIT.
	sig	[INPUT; default=sqrt(abs(Y)+0.75)+1] standard deviations on Y
	ifit	[INPUT] integer array of same size as A, with 0's indicating
		frozen parameters and 1's indicating thawed parameters
		* if IFIT does not match A for any reason, all parameters
		are assumed to be thawed
	alpha	[OUTPUT] fitting matrix
	bvec	[OUTPUT] fitting vector
	chisq	[OUTPUT] chi^2, or ln(p(D|M)) if POISSON is set
	yfunc	[OUTPUT] Y(X;A) -- function values
	poisson	[INPUT] if set, returns the log of the poisson likelihood,
		p(D|M) instead of the chi-sq
		* do _not_ use this keyword for background-subtracted data!!
	_extra	[JUNK] here only to prevent crashing the program

subroutines
	LNPOISSON

history
	(C) Copr. 1986-92 Numerical Recipes Software =$j!]Y'1,).
	translated from MRQCOF.F to IDL by Vinay Kashyap (Oct98)
	now returns correct chisq if all params are frozen (VK; JanMM)
	added keyword POISSON and call to LNPOISSON (VK; Aug01)

(See /data/fubar/SCAR/pro/lmcoeff.pro)


LNPOISSON

[Previous Routine] [Next Routine] [List of Routines]
function	lnpoisson
	returns the natural log of the poisson likelihood of observing
	the specified counts given the model source intensity,
		p(D|M) = M^D * exp(-M) / D!

syntax
	lnp=lnpoisson(d,m,/chilike,verbose=verbose)

parameters
	d	[INPUT; required] data counts
	m	[INPUT; required] model intensity
		* output will be array of size [N(D),N(M)]
		  unless CHILIKE is set, in which case output will be N(M)
		  (beware that IDL automatically compresses trailing
		  dimensions if any of them are equal to 1)

keywords
	chilike	[INPUT] if set, returns -2*SUM_{D}(ln(p(D|M)))
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to avoid crashing the program

history
	vinay kashyap (Aug01)
	bug correction: m^d was not translated correctly (VK; Mar02)

(See /data/fubar/SCAR/pro/stat/lnpoisson.pro)


LNVANDYK

[Previous Routine] [Next Routine] [List of Routines]
function	lnvandyk
	return the natural log of the joint posterior probability
	distribution of the source and background built up using
	the Poisson likelihood and Gamma-distribution priors for
	the source and background,
	  p(s,b|Y,I) = exp(-b*(betaB+1)+s*(betaS+1)) * 
		       (b+s)^(Y) * b^(alfaB-1) * s^(alfaS-1) /
		       (Y! * Gamma(alfaB) * Gamma(alfaS))
	where Y are the observed counts, s,b are the model source and
	background intensities, and alfaB,alfaS,betaB,betaS are the
	hyperparameters of the gamma-distribution priors p(s|I) and
	p(b|I) (see eqn 5 of van Dyk et al., 2001, ApJ 548, 224).
	alfaB is generally set to the number of observed background
	counts + 1, betaB is the ratio of the background area (or
	exposure time) to the source area (or exposure time), and
	alfaA and betaA are set based on prior knowledge (if any)
	of the source intensity.

syntax
	lnp=lnvandyk(s,b,Y,alfaS=alfaS,betaS=betaS,alfaB=alfaB,betaB=betaB,$
	Ybkg=Ybkg,asrc=asrc,abkg=abkg,/chilike,verbose=verbose)

parameters
	s	[INPUT; required] model source intensity
	b	[INPUT; required] model background intensity
	Y	[INPUT; required] observed counts
		* output will be array of size [N(Y),N(S),N(B)]
		  (beware that IDL automatically compresses trailing
		  dimensions if any of them are equal to 1)

keywords
	alfaS	[INPUT; default=1] alpha parameter for source prior
	betaS	[INPUT; default=0] beta parameter for source prior
	alfaB	[INPUT; default=1] alpha parameter for background prior
		* if YBKG is set, this is ignored completely
	betaB	[INPUT; default=1] beta parameter for background prior
		* if ASRC and ABKG are set, this is ignored completely
	Ybkg	[INPUT; default=0] observed background counts
		* if given, ALFAB is taken to be YBKG+1
		* if even one element is specified, overrides ALFAB entirely
	asrc	[INPUT; default=1] area (or exposure time) over which
		source (and some background) counts are collected
	abkg	[INPUT; default=1] area (or exposure time) over which
		background counts are collected
		* if ASRC _or_ ABKG is given, overrides BETAB entirely
		  (unless, of course, they are 0 or less, in which case
		  they are ignored)

		* size of all of the above keywords are expanded or pruned
		  to match that of Y.  i.e., there is freedom to specify
		  a separate prior for each data point, but not for each
		  model grid point.

	chilike	[INPUT] if set, returns -2*SUM_{Y} (ln(p(s,b|Y)))
	verbose	[INPUT] controls chatter

	_extra	[JUNK] here only to prevent crashing the program

common blocks

history
	vinay kashyap (Aug01)

(See /data/fubar/SCAR/pro/stat/lnvandyk.pro)


LOCMAX

[Previous Routine] [Next Routine] [List of Routines]
function	locmax
		returns the local maxima of a 1D array

syntax
	fmax=locmax(f,sigma=sigma,thresh=thresh,width=width,prob=prob,$
		/poisson,nubin=nubin,fmin=fmin,fmax=fmax)

parameters 	f	[INPUT; required] input array

keywords	sigma	[INPUT] errors on F (ignored if POISSON is set)
			* ignored if POISSON is set AND F(*).GE.0
			* default is sqrt(abs(F)+0.75)+1
		thresh	[INPUT; default: 0.5] threshold probability below
			which to ignore a calculation
		width	[INPUT; default: 1] compare value in bin to values
			on either side averaged over WIDTH bins
			* NOTE: WIDTH is the *half*width
		poisson	[INPUT] if set, assumes a poisson error distribution
			* automatically UNSET if min(F) < 0
		prob	[OUTPUT] returns the computed probabilities

	the following are not to be changed unless the user understands
	what's going on!

		nubin	[INPUT; default: 100] size of uniform grid to
			superpose on F
		fmin	[INPUT] minimum value for integration.
			default is 0.2*min(F) or if min(F)<0 then 5*min(F)
		fmax	[INPUT] maximum value for integration.
			default is 5*max(F) or if max(F)<0 then 0.2*max(F)

description
	at each point, compute the probability that given value is a
	local maximum.
	  p = \int dF p(f|f[i],s[i])*p(f[i-1]<f|s[i-1])*p(f[i+1]<f|s[i+1])
	find all the peaks in the distribution of probabilities that
	lie above a given threshold.  the positions of these peaks are
	identified with positions of local maxima.

requires
	LOCMAX_CDF (included in file)
	IGAMMA (not in old IDLs)
	ERRORF (not in old IDLs?)

history
	vinay kashyap (Oct96)

(See /data/fubar/SCAR/pro/misc/locmax.pro)


LOCUS_ELLIPSE

[Previous Routine] [Next Routine] [List of Routines]
procedure	locus_ellipse
	make a curve describing the locus of an ellipse 

syntax
	locus_ellipse,xout,yout,xcen=xcen,ycen=ycen,amajor=amajor,$
	aminor=aminor,theta=theta,npt=npt,verbose=verbose

parameters
	xout	[OUTPUT; required] x-coordinates of the locus
	yout	[OUTPUT; required] y-coordinates of the locus

keywords
	xcen	[INPUT; default=0] x-coordinate of the center
	ycen	[INPUT; default=0] y-coordinate of the center
	amajor	[INPUT; default=1] length of the semi-major axis
	aminor	[INPUT; default=1] length of the semi-minor axis
		* if AMINOR is not defined, it is set to AMAJOR
		  to make a circle
		* if AMINOR>AMAJOR, no harm done, program will
		  run regardless of mathematical purity
	theta	[INPUT; default=0 degrees] anticlockwise angle made
		by AMAJOR with x-axis
	npt	[INPUT; default=101] number of points along the locus,
		spaced equally along THETA
		* note that the first and the last points are identical
		  unless NPT < 0, in which case abs(NPT) points are
		  returned without the overlap
	verbose	[INPUT; default=0] controls chatter
	
	_extra	[JUNK] here only to prevent crashing the program

history
	vinay kashyap (Mar2008)

(See /data/fubar/SCAR/pro/misc/locus_ellipse.pro)


LOGIT

[Previous Routine] [Next Routine] [List of Routines]
function	logit
	compute and return the logit function.

	LOGIT() maps a variable in the [0,1] range to the
	real number line [-\infty,+\infty] by applying the
	transformation ln(x/(1-x)).
	conversely, UNLOGIT() maps the real number line to
	[0,1] by applying the transformation e^y/(1+e^y).

syntax
	lx=logit(x,sigx,sigl=sigl)

parameters
	x	[INPUT; required] a variable in the range [0,1]
		* can be an array
		* value is set to NaN in output if input falls
		  outside valid range
	sigx	[INPUT] standard error on X
		* if <0 and >-1, then ABS(SIGX) is taken to be the
		  fractional error
		* if <-1 and >-100, then ABS(SIGX) is taken to be
		  the percentage error
		* if <-100, then 1/ABS(SIGX) is taken to be the
		  fractional error

keywords
	sigl	[OUTPUT] standard error on LOGIT(X)
		* note that SIGL = SIGX/(X*(1-X))
	_extra	[JUNK] here only to prevent crashing the program

history
	vinay kashyap (3may04; based on conversation with Xiao-li Meng)

(See /data/fubar/SCAR/pro/stat/logit.pro)


LOOPEM

[Previous Routine] [Next Routine] [List of Routines]
function	loopem
	convert a set of integrated emission measures to a differential
	emission measure distribution assuming a hydrostatic-loop type
	distribution and return computed DEM

	DEM(T) is generally n^2*dX/dlnT, and
	EM(T) == \int_0^T dlnT' DEM(T') = \int_0^T dT' DEM(T')/T'
	In particular, DEM is parameterized as DEM(T)=a*T^b
	So for a given EM(T), we obtain
		EM(T)=(a/b)*(Tmax^(b)-Tmin^(b)), Tmin=0, b>0
	with Tmin=0 for b>0

syntax
	dem=loopem(logTmax,EM,logT=logT,sloop=sloop,verbose=verbose)

parameters
	logTmax	[INPUT; required] loop top temperature(s) in log10(deg K)
	EM	[INPUT] if given, normalize the output DEM to give a
		total Emission Measure equal to this.
		* size must match that of logTmax -- if fewer, fills out
		  with 1st element; if more, ignored

keywords
	logT	[INPUT] temperature grid over which output DEM is returned
		* default is 4..8 in steps of 0.05
	sloop	[INPUT] slope of DEM in log(DEM)-log(T) space
		* default is 1.5
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to prevent crashing the program

history
	vinay kashyap (Nov01)
	changed NORM calc to allow for large values of SLOOP (VK; Feb05)

(See /data/fubar/SCAR/pro/loopem.pro)


LOSRAD

[Previous Routine] [Next Routine] [List of Routines]
script	losrad
	compute radiative loss function

syntax
	.run losrad

warning
	all internal program variables have names that begin as "v_" or "jnk_"
	if you have any preexisiting variables with these names, they will be
	overwritten.

inputs
	!LDBDIR	 line emissivity database
	!CDBDIR	 continuum emissivity database directory
	!CEROOT	 continuum emissivity database root
	!IONEQF	 ion-balance file
	!EDENS	 electron density
	!ABUND	 abundances
	!VERBOSE controls chatter
	V_WMIN	 [1.0 Ang] minimum wavelength to consider
	V_WMAX	 [3000.0 Ang] maximum wavelength to consider

outputs
	V_LLOGT	 temperatures at which radiative loss is computed
	V_LOSS	 radiative loss function P(T)
	V_LLOS	 loss function due to lines
	V_CLOS	 loss function due to continuum processes
	V_LLOSE	 loss function due to excitation transitions only
	V_LLOSR	 loss function due to radiative transitions only
	V_LLOSI	 loss function due to inner-shell ioniszation transitions only

how to use
	1. initialize the PINTofALE environment using INITALE
	2. the parameters that will be set with INITALE are:
	   --	ATOMIC: !LDBDIR, !IONEQF, !CDBDIR, !CEROOT, !CHIDIR
	   --	STELLAR: !EDENS, !ABUND, !NH, !FH2, !HE1, !HEII
	   verify that they are initialized to the right values
	3. set the wavelength range of interest
		V_WMIN = 1.0
		V_WMAX = 3000.
	4. run this script

history
	vinay kashyap (May99; modified from radloss.pro)
	major cosmetic overhaul (VK; DecMM)
	minor cosmetic changes (VK; Jul01)
	changed default WMAX to 3000 AA (VK; Sep01)
	plot now handles the 24-bit color case (VK; Apr03)
	updated for IDL5.6 keyword_set([0]) behavior change for vectors
	  (VK; 20Mar2006)
	allowed for APED emissivities (VK; 6Aug2009)

(See /data/fubar/SCAR/pro/esempio/losrad.pro)


LSD

[Previous Routine] [Next Routine] [List of Routines]
function	lsd
	returns list of density sensitive lines in given wavelength range

syntax
	ld=lsd(wrange,fluxes,wvls,elem=elem,edens=edens,DEM=DEM,tlog=tlog,$
	dbdir=dbdir,ceiling=ceiling,flor=flor,ratmax=ratmax,flxmax=flxmax,$
	outZ=outZ,outIon=outIon,outIDX=outIDX, tol=tol,chifil=chifil,$
	chidir=chidir,eqfile=eqfile,/temp,abund=abund,/noph,effar=effar,$
	wvlar=wvlar,/ikev)

parameters
	wrange	[INPUT; required] wavelength range in which to search for
		density sensitive lines
		* if only one element is given, set the range to be 10% of
		  it on either side
		* if the single element is a string, apply RD_LIST rules
		  to decipher it ("WVL +- dW", "WMIN,WMAX", "WMIN-WMAX"
		  are all allowed)
	fluxes	[OUTPUT] 2D array of predicted fluxes for lines that are
		found to be density sensitive, FLUXES(EDENS,WVLS)
	wvls	[OUTPUT] array of wavelengths of lines that are found to
		be density sensitive

keywords
	elem	[INPUT] if set, confine attention to just those elements and
		ionic species specified.
		* default is to look at all available lines
	edens	[I/O] array of electron densities [cm^-3] at which to
		check for density sensitivity.
		* default is [1e8,1e14]
		* if not specified, insufficiently specified, or otherwise
		  meaningless, uses default
	DEM	[INPUT] input array of differential emission measures [cm^-5]
		* default is to use 1e12 [cm^-5] at specified TLOG
	tlog	[INPUT] log(temperatures) at which DEM is defined
		* if not specified, set to 6.0, unless DEM has more steps,
		  in which case interpolated to the 4..8 range
	dbdir	[INPUT] line database directory to use to search for the
		density sensitive lines
		* default is $CHIANTI
	ceiling	[INPUT] maximum relative variation the fluxes of a given
		line must have before it is accepted as density sensitive
		* default is 2
		* if 0 < CEILING < 1, it is assumed that the *reciprocal*
		  of CEILING is given (e.g., CEILING=0.5 is translated to 2)
		* if CEILING < 0, assumed to be percentages (e.g., CEILING=-1
		  is translated to 1/0.01 == x100)
	flor	[INPUT] if set, ignores any line which has a peak flux
		a factor FLOR below the flux of the strongest of the
		lines filtered through CEILING.
		* default is 0
		* if FLOR > 1, assumed that the reciprocal of FLOR is given,
		  i.e., FLOR=100 translates to 0.01
		* if FLOR < 0, taken to be the absolute flux threshold, in
		  whatever units it is being calculated in
		* NOTE on difference between CEILING and FLOR:-
		  CEILING works on ratios, and FLOR works on the intensities
	ratmax	[OUTPUT] the maximum deviations found for each of the
		density-sensitive lines found
	flxmax	[OUTPUT] the peak fluxes for each of the density sensitive
		line found
	outZ	[OUTPUT] atomic numbers
	outIon	[OUTPUT] atomic numbers
	outIDX	[OUTPUT] indices which passed the test
		* be careful in how you use this.  a common mistake is to
		  assume that it matches with whatever line emissivity
		  database that has been read in.  that might very well be
		  true, but is definitely not guaranteed.
		
	_extra	[INPUT] use this to pass defined keywords to subroutines:-
		FOLD_IONEQ: CHIFIL
		RD_IONEQ: CHIDIR, EQFILE
		LINEFLX: TEMP, ABUND, NOPH, EFFAR, WVLAR, IKEV
		ARRAYEQ: TOL

example usage
	ls=lsd('10-120',dbdir='$CHIANTI',edens=[1e9,1e12],ceiling=2,ratmax=rmx)
	for i=0,n_elements(ls)-1 do print,ls(i),1./rmx(i),i
	;
	eden=10.^(findgen(6)+8)
	ls=lsd('113.35?0.1',flx,elem='Fe20',dbdir='$CHIANTI',edens=eden)
	plot,eden,flx

subroutines
	MK_DEM
	RD_LINE
	FOLD_IONEQ
	    RD_IONEQ
	        READ_IONEQ (CHIANTI subroutine)
	LINEFLX
	ARRAYEQ
	KABOOM
	INICON
	IS_KEYWORD_SET

history
	vinay kashyap (Nov98)
	changed default EDENS to [1e8,1e14]; added keywords DEM,TLOG,OUTZ,
	  OUTION; added call to MK_DEM; changed keyword FLOOR to FLOR; changed
	  behavior of FLOR<0 (VK; Dec98)
	modified ion balance calcs (VK; 99May)
	changed call to INITSTUFF to INICON (VK; 99May)
	added keyword outIDX (VK; JanMMI)
	updated for IDL5.6 keyword_set([0]) behavior change for vectors
	  (VK; 20Mar2006)

(See /data/fubar/SCAR/pro/lsd.pro)


MAKE_LOWRES

[Previous Routine] [Next Routine] [List of Routines]
 procedure     make_lowres
         wrapper script to run hires2lowres and put the simulated
         ACIS spectral data into a ASCII tables and fits files

 syntax
         make_lowres,hphafile,mphafile,hgarffile,mgarffile,$
         hhetgwvl,hhetgcts,mhetgwvl,mhetgcts,hetgwvl,hhetgflx,$
         hhetgflxerr,mhetgflx,mhetgflxerr,tothetgflx,tothetgflxerr,$
         aciswvl,aciscts,aciserr,hphahdr,mphahdr,hgarfhdr,mgarfhdr,$
         acisarffile,acisrmffile,debug=debug,txtfile=txtfile,$
         fitsfile=fitsfile,flxfits=flxfits,flxtxt=flxtxt

 parameters
         hphafile     [INPUT; required] PHA type I spectral file
                      containing the HEG HETG spectrum for a given
                      order
         mphafile     [INPUT; required] PHA type I spectral file
                      containing the MEG HETG spectrum for a given
                      order
         hgarffile    [INPUT; required] Gratings ARF corresponding to
                      the HEG PHA file
         mgarffile    [INPUT; required] Gratings ARF corresponding to
                      the MEG PHA file
         hhetgwvl     [OUTPUT; required] The midpoints of the HEG
                      wavelength bins
                      * units are Angstroms
         hhetgcts     [OUTPUT; required] The background-subtracted
                      counts spectrum extracted from the HEG PHA file
                      * units are [cts/s/AA]
         mhetgwvl     [OUTPUT; required] The midpoints of the MEG
                      wavelength bins
                      * units are Angstroms
         mhetgcts     [OUTPUT; required] The background-subtracted
                      counts spectrum extracted from the MEG PHA file
                      * units are [cts/s/AA]
         hetgwvl      [OUTPUT; required] The midpoints of the common
                      HEG, MEG, and HEG+MEG flux spectrum's
                      wavelength grid 
                      * grid extends ~0-30 AA at HEG resolution
         hhetgflx     [OUTPUT; required] Adaptively-smoothed,
                      background-subtracted HEG flux spectrum
                      * units are [ph/s/cm^2/AA]
         hhetgflxerr  [OUTPUT; required] The error on the HEG flux
                      spectrum
         mhetgflx     [OUTPUT; required] Adaptively-smoothed,
                      background-subtracted MEG flux spectrum
                      * units are [ph/s/cm^2/AA]
         mhetgflxerr  [OUTPUT; required] The error on the MEG flux
                      spectrum
         tothetgflx   [OUTPUT; required] Adaptively-smoothed,
                      background-subtracted coadded HEG+MEG flux
                      spectrum
                      * units are [ph/s/cm^2/AA]
         tothetgflxerr [OUTPUT; required] The error on the coadded
                      HEG+MEG flux spectrum
         aciswvl      [OUTPUT; required] The midpoints of the
                      predicted ACIS spectrum's wavelength grid
         aciscts      [OUTPUT; required] The predicted ACIS spectrum
                      * units are [cts/s/AA]
         aciserr      [OUTPUT; required] The error on the predicted
                      ACIS spectrum
         hphahdr      [OUTPUT; required] The header of the HEG PHA
                      file
         mphahdr      [OUTPUT; required] The header of the MEG PHA
                      file
         hgarfhdr     [OUTPUT; required] The header of the HEG gARF
                      file
         mgarfhdr     [OUTPUT; required] The header of the MEG gARF
                      file
         acisarffile  [INPUT; required] The ACIS ARF
         acisrmffile  [INPUT; required] The ACIS RMF

 keywords
         debug        [INPUT] controls debugging chatter
         txtfile      [INPUT; required] Output text file for the HETG
                      and predicted ACIS spectra
         fitsfile     [INPUT; required] Output FITS file for the HETG
                      and predicted ACIS spectra
         flxfits      [INPUT; required] Output FITS file for the HEG,
                      MEG, and combined HEG+MEG flux spectra
         flxtxt       [INPUT; required] Output text file for the HEG,
                      MEG, and combined HEG+MEG flux spectra

 restrictions
         requires conv_rmf, smoothie, and rebinw from PINTofALE,
         available at http://hea-www.harvard.edu/PINTofALE/

 history
         Owen Westbrook, Peter Mendygral, and John Slavin (Mar07)

(See /data/fubar/SCAR/pro/esempio/make_lowres.pro)


MAKE_SPEC

[Previous Routine] [Next Routine] [List of Routines]
MAKE_SPEC.PRO
	take the line and continuum emissivities and generate a
	theoretical spectrum over the specified wavelength grid

restrictions
	output wavelength grid must be defined in WGRID
	line database must be in structure LINSTR
	continuum database must be in structure CONSTR

subroutines
	LINEFLX
	    GETABUND
	        SETABUND
	    WHEE
	ISMTAU
	HASTOGRAM
	REBINW

vinay kashyap (Dec98)

(See /data/fubar/SCAR/pro/scrypt/make_spec.pro)


MAKE_SPECTRUM

[Previous Routine] [Next Routine] [List of Routines]
script 	make_spectrum
	compute a spectrum using line and continuum emissivities

warning
	all program variables have names that begin as "v_" or "jnk_"
	if you have any preexisiting variables with these names, they
	will be overwritten.

inputs
	ATOMIC:
	  line emissivities and wavelengths
	  continuum emissivities and wavelength grid
	  (subsumed in database directory names)
	  ion fractions
	STELLAR:
	  coronal electron density
	  coronal abundances
	  Differential Emission Measure
	  distance
	  Galactic coordinates (or absorption column density)
	OBSERVATIONAL:
	  instrument effective area
	  synthetic spectrum wavelength grid
	  photon redistribution matrix
	  exposure time

outputs
	v_linint	line intensities @ source
		(@ wavelengths v_lwvl; from species v_Z,v_ion)
	v_conint	continuum intensities @ source
		(@ wavelength grid v_cww)
	v_linflx	theoretical line fluxes @ earth
		(using ISM transmission factors v_ltrans)
	v_conflx	theoretical continuum fluxes @ earth
		(using ISM transmission factors v_ctrans)
	v_linspc	theoretical line spectrum @ earth
	v_conspc	theoretical continuum spectrum @ earth
	v_flxspc	predicted spectrum through telescope
	v_wvls  	mid-bin values of predicted spectrum wavelength grid
	v_ctspc 	predicted count spectrum for detector
	v_chan  	energy channels for count spectrum

how to use
	1. initialize the PINTofALE environment using INITALE
	2. the parameters that will be set with INITALE are:
	   --	ATOMIC: !LDBDIR, !IONEQF, !CDBDIR, !CEROOT, !CHIDIR
	   --	STELLAR: !EDENS, !ABUND, !NH, !FH2, !HE1, !HEII
	   verify that they are initialized to the right values
	3. define DEM as a function of LOGT (use DEMACS() or MK_DEM())
	   --	place in variables v_LOGT [K] and v_DEM [cm^-3]
	4. define distance in [pc]
	   --	place in variable v_DIST
	5. read in the instrument effective area
	   --	place in variables v_EFFAR [cm^2] and v_WVLAR [Ang]
	6. read in (or define) the synthetic spectrum wavelength grid
	   --	place in variable v_WGRID [Ang]
	   (must be _bin boundaries_)
	7. define the exposure time [ks]
	   --	place in variable v_EXPTIME
	8. define the name of the OGIP-style RMF
	   --	place in variable v_RMF
	   (set to 'NONE' if, e.g., grating spectrum is being analyzed)
	9. run this script

history
	vinay kashyap (OctMM)

(See /data/fubar/SCAR/pro/scrypt/make_spectrum.pro)


MARFRMF

[Previous Routine] [Next Routine] [List of Routines]
function	marfrmf
	returns the instrument response matrix computed as the product of
	the redistribution matrix with the ancillary response.

syntax
	rsp=marfrmf(arffil,rmffil,ostr,effar=effar,/noext,/nofull,$
	fchcol=fchcol,/shift1)

parameters
	arffil	[INPUT; required] OGIP-compliant Ancillary Response File
		* appends a ".arf" if missing (overridden by NOEXT)
	rmffil	[INPUT; required] OGIP-compliant Redistribution Matrix File
		* appends a ".rmf" if missing (overridden by NOEXT)
	ostr	[OUTPUT] structure containing the axes information for the
		response matrix -- see RD_OGIP_RMF()

keywords
	effar	[OUTPUT] returns the effective area as a function of ELO
	noext	[INPUT] normally, if an extension is missing from ARFFIL
		or RMFFIL, the program will append the appropriate extension.
		if this keyword is set, no such action will occur.
	nofull	[INPUT] if set, bypasses RDRESP() and the accompanying
		computation of the full response matrix (i.e., with the OGIP
		compression removed).  this is useful for those cases where
		the uncompressed matrix is too large for memory.
		* if this is set, the output will be simply the same as
		  OSTR.MATRIX, which is the compressed version of the
		  effective area weighted redistribution matrix
	_extra	[INPUT] pass defined keywords to subroutines
		RD_OGIP_RMF: FCHCOL, SHIFT1

restrictions
	* requires subroutines RD_OGIP_RMF, RDRESP and RDARF
	* requires IDLASTRO library of routines

history
	vinay kashyap (Jul97)
	allowed for keyword SHIFT1 (VK; JanMMI)
	added keyword NOFULL; now multiplication also works on OSTR.MATRIX
	  (VK; Nov2001)
	changed output in case of /NOFULL from 1.0 to OSTR.MATRIX (VK; Oct2008)

(See /data/fubar/SCAR/pro/marfrmf.pro)


MCERROR

[Previous Routine] [Next Routine] [List of Routines]
procedure	mcerror
	procedure that estimates confidence bounds for model fits by
	fitting to different monte-carlo realizations of the data and
	estimating the bounds from the distribution of the resulting
	parameter values.

	generates NN number of synthetic data sets by randomly varying
	each data point within its estimated error. fits these NN
	synthetic data  sets to generate parameter sets a(1),a(2),..a(NN),
	so that we can estimate distribution of a(x)-a(best).  Uses this
	as a basis for confidence bound estimation.  Finds smallest possible
	bounds giving required confidence (as opposed to 'counting' up
	and down from best fit by required fraction)
            
syntax
	mcerror,x,y,a,erru,errl,ysig=ysig,freeze=freeze,mcfuncs=mpfuncs,$
	algo=algo,verbose=verbose, erra=erra,yfunc=yfunc,mciter=mciter,$
	itmax,chitr=chitr,mcconf=mcconf,/dumb, jumpup=jumpup,jumpdn=jumpdn,$
	=svdthr,funcs=funcs, function_name=function_name,$
	ype, missing=missing,/fwhm,/norm,betap=betap, /poisson

parameters
	x	[INPUT; required] data points
	y	[INPUT; required] Y(X)
		* sizes of X and Y must match
	a	[I/O; required] parameters for user-supplied function
		* on input, these are assumed to be initial guesses
		* on output, these contain the best-fit values
	erru	[OUTPUT; required] upper limits of confidence range interval
	errl	[OUTPUT] lower limits of confidence range interval
		* if ERRL is not specified on input, ERRU will contain the
		  average value of the upper and lower >>deviations<<.

keywords
	ysig	[INPUT] standard deviations on Y
		* default=sqrt(abs(Y)+0.75)+1
		* if single element, then sig(Y[*])=YSIG(0)
		* if -ve, taken to be the fractional error
       mciter  [INPUT] number of additional iterations for each parameter:
               total iterations = (mciter x number of parameters) > 2xmciter+1                               
               default: mciter=30
       mcconf  [INPUT] (two-sided) confidence for bound estimation,
                       default: mpfunc =0.68
       mcsims  [OUTPUT] 2 dimensional array MCSIMS==MCSIMS(free,sims)
               where free are the number of thawed paramters and sims 
               is the number of simulations. contains all simulations 
               on output 
       mpfunc  [INPUT] contains name of input function to fit
                       REQUIRED WHEN USING MPFIT
	freeze	[INPUT] freeze numbered parameters (index starts from 0!)
	algo	[INPUT] fitting algorithm
		* only the following are implemented:
		-- LevMarq+SVD 
		-- IDL-Curvefit 
               -- Mardkwardt's MPFIT
	verbose	[INPUT] verbosity level
	erra	[OUTPUT] formal "curvature" errors on the best-fit parameters
	yfunc	[OUTPUT] best-fit Y(X;A)
	_extra	[INPUT] pass defined variables to subroutines:-
		FIT_LEVMAR: ITMAX, CHITHR, DUMB
		ADJUSTIE: TIES, VNAME
		LEVMARQ: JUMPUP, JUMPDN, SVDTHR
		LMCOEFF: FUNCS, POISSON
		CURVE_FIT: FUNCTION_NAME
		note:-	FUNCS, FUNCTION_NAME, and MPFUNC refer to name
			of user-defined function that takes as input X
			and A, and returns YMODEL(X;A), and the partial
			derivatives of the model function wrt A.  Any
			function that was written to work with CURVEFIT
			or GHRS' WFIT will do.
			The default for FIT_LEVMAR is X3MODEL.
		MK_3MODEL: TYPE
		MK_GAUSS: MISSING, FWHM, NORM
		MK_LORENTZ: BETAP, MISSING, NORM

history
	Liwei Lin (Apr03) idenentical to ERORS.pro in input/output/parameter checks
	  added keyword MPFUNC for compatability with MPFIT            
	  added keyword MCCONF so user can toggle confidence required
                 BUG FIX, mcerror not mcerors LL/SC JUL03
                 BUG FIX, yfunc was being recursivly overwritten in
                          synthetic loop LL/SC JUL03
	  added forward_function (VK; Jul03)
	some cosmetic changes (VK; Feb04)
         added MCSIMS (LL; Mar04) 
       BUG FIX algo keyword incorrectly processed (LL ; Sep05)

(See /data/fubar/SCAR/pro/mcerror.pro)


MCMCM

[Previous Routine] [Next Routine] [List of Routines]
function	mcmcm
	carries out a Metropolis check on the test params
	and either accepts (1) or rejects (0) the new set
	based on the associated probabilities

	the basic Metropolis criterion can be summarized thus
	(see e.g., Kashyap & Drake 1998, ApJ, 503, 450):
	if the new set of parameters are more likely, then
	always accept them.  otherwise, accept it with a probability
	p(TESTPRB,PRB), which ensures that the solution does not
	get stuck in local minima.

syntax
	test=mcmcm(prb,testprb,testtyp=testtyp,seed=seed)

parameters
	prb	[INPUT; required] probability for current parameter set
	testprb	[INPUT; required] probability for test parameter set
		* NOTE: PRB and TESTPRB may be arrays (whose sizes
		  _must_ match), in which case the output will be an
		  integer array of the same size containing 0's and 1's
		  as appropriate for each PRB,TESTPRB pair.

keywords
	testtyp	[I/O] by default, the ratio min(1,TESTPRB/PRB) is used
		as the acceptance function.   set this keyword to
		-- 'HELP' to print out available options
		-- 'CHILRT' to use min(1,exp(-TESTPRB)/exp(-PRB))
		* will be reset to 'DEFAULT' if 'HELP' is input
	seed	[I/O] seed for random number generator RANDOMU()

	_extra	[JUNK] here only to avoid crashing the program

history
	vinay kashyap (Jun2005)

(See /data/fubar/SCAR/pro/stat/mcmcm.pro)


MCMC_ABUND

[Previous Routine] [Next Routine] [List of Routines]
function    mcmc_abund 
        
        An abundance-independent DEM-reconstruction can be achieved 
        by running a Monte Carlo Markov-Chain DEM reconstruction
        mcmc_dem() on a set of He-like to H-like flux ratios. 

        A DEM realized in this fashion together with the observed 
        line fluxes give implied abundances. This function returns 
        fractional abundnaces relative to solar 'grevesse & sauval'
        (not logarithmic values) given a set of MCMC realized DEMS 
        (mcmc_dem ouput), fluxes, and line details. 
 
parameters 
        simdem [INPUT;required]  an array of size
		(NT,NSIM+1), with last column containing the best-fit
	 logt   [INPUT] log_10(Temperature [K]) at which DEMS are given
        wvl	[INPUT; required] wavelengths [Ang] 
	 flx	[INPUT; required] flux [ph/s] at each WVL ([ph/s/cm^2]
        fsigma [INPUT; required] errors for flx
	 emis	[INPUT; required] line emissivities [1e-23 ergs cm^3/s]
		* EMIS==EMIS(LOGT,WVL)
        z      [INPUT; required] atomic numbers of the elements
               generating the	lines at WVL.
        asig   [OUTPUT] error in the weighted mean abundance
        zout   [OUTPUT] atomic numbers corresponding to output abundances
keywords
        abund  [INPUT] set  of abundances. see GETABUND(). Output 
               will be relative to this set. Default is Grevesse &
               Sauval (1998)
        abweight [INPUT] if a different weighting is required to compute 
               abundances then specify abweight as an array of weights of 
               the same size as flx (e.g. one can use fsigma) 
        elogt  [INPUT] log_10(Temperature[K]) at which EMIS are
                       defined if different from logt 
        nosol  [INPUT] if set, then output abundances will not be
                       relative to solar 
        olog   [INPUT] if set, outputs abundances and asig will be
               logarithmic values.         
        crctn_factor [INPUT] if set, correctin factor is applied to
                     theoretical fluxes before calculation of abundnaces
        _extra [INPUT ONLY] use this to pass defined keywords to subroutines
           
subroutines
        MC_EROR (/home/llin/mc_eror.pro) not PoA standard yet 
        LINEFLX 
history 
        Liwei Lin 5/03 
           ADDED keyword log for logarithmic output (LL 7/03) 
           BUG FIX elogt is actually taken into account when set (LL/WB 8/03)
        LL/CA 9/03 BUGFIX Costanza points out error calculation bug
           which gives overestimation in errors 
       BUG FIX elogt handler (call to rebinx) should have logt
           not dlogt as input (LL/WB 9/03) 
        LL 01/04 
           ADDED keyword crctn_factor for use with mixie
        LL 01/04 
           H abundance cannot be updated 
        LL/SC 2/04 
           BUGFIX HISTOGRAM will give a one element array if given 
           just one atomic number to bin up.
        LL ADDED _extra keyword to lineflx 
        LL 5/05 Change the asig determination to only include the errors 
           as determined from the DEMs.THIS SHOULD HAVE BEEN FIXED 9/03 AS 
           stated above. (do not include the error in the 
           fluxes a second time). 
           ADDED keyword abweight 
        LL 6/05 ADDED keyword abund
           BUGFIX previous error calculation would fail for highly
           assymetric cases
        LL/DG 6/05 BUGFIX crash when MC_EROR returns two-element 
           arrays 

(See /data/fubar/SCAR/pro/mcmc_abund.pro)


MCMC_BURN

[Previous Routine] [Next Routine] [List of Routines]
procedure	mcmc_burn
	burns in the parameters in a Markov-Chain Monte Carlo sequence

syntax
	mcmc_burn,x,y,ain,rngpar,aout,siga,nburn=nburn,rhat=rhat,qhat=qhat,$
	qfrac=qfrac,rthresh=rthresh,qthresh=qthresh,$
	sigy=sigy,funcs=funcs,fnprob=fnprob,thaw=thaw,/singly,$
	sampar=sampar,sclpar=sclpar,seed=seed,testtyp=testtyp,ties=ties,$
	FUNCS;	type=type,/fwhm,/norm,betap=betap,vrot=vrot,angle=angle,$
		phase=phase,group=group,delp=delp,missing=missing,$
	FNPROB;	ulim=ulim,/chi2,/binom,/cash,/castor

parameters
	x	[INPUT; required] data points
	y	[INPUT; required] Y(X)
		* sizes of X and Y _must_ match
	ain	[INPUT; required] initial values of the parameters of
		the model to fit to Y(X)
		* parameters should be 1-D array
		* if 2-D, the size of the 2nd dimension describes the
		  number of chains that are concurrently running
	rngpar	[INPUT; required] the allowed range for each parameter
		as a 2-D array of size (N(PAR),2)
		* if 1-D array, range assumed to be symmetrical
		  -- additive if +ve
		  -- abs value multiplicative if -ve
		* if size does not match, assumed to be uniformly (-100)
	aout	[OUTPUT; required] values of the parameters at conclusion
		of burn-in phase -- will be same size as AIN
	siga	[OUTPUT; required] the width of the allowed deviation
		to generate new parameter values from old values.  this
		is usually the standard deviation of the samples, unless
		abs(kurtosis)>0.2, in which case SIGA is set to -ve of
		the maximum possible deviation.

keywords
	nburn	[INPUT] maximum number of steps to go through
		* default is 100
	rhat	[OUTPUT] ratio of rms(inter-chain) to rms(intra-chain)
		for each parameter -- the chains have converged if
		RHAT drops to ~ 1
		* will be set to 0 if there is only one chain
	qhat	[OUTPUT] a measure of the stability of the persistent
		distribution of the parameters, which indicates the
		convergence of a given chain.  this is simply the
		ratio of the product of an older frequency distribution
		of a parameter with a newer one, normalized by number
		of samples, and averaged over all the parameters.
		* will return a value for each chain
		* the chain will have converged if QHAT goes up to ~ 1
	qfrac	[INPUT] the fractions of the parameter chain to be used
		to define the "older" and "newer" frequency distributions
		in the calculation of QHAT.
		* must be composed of numbers >0 and <1, and must
		  sum to <1
		 -- if .le.0 or .ge.1, or is not set, is set to 0.25
		* should be 2-element vector describing the fractional
		  lengths of the chains to consider: QFRAC[0] is for the
		  "new" distribution and runs backwards from newest, and
		  QFRAC[1] is for the "old" distribution, and runs backwards
		  from the end of "old"
		  -- if QFRAC[0]+QFRAC[1] > 1, then QFRAC[1] is set to
		     1-QFRAC[0]
	rthresh	[INPUT] the threshold value of RHAT below which it can be
		assumed that the chains have converged
		* default is 1.5
	qthresh	[INPUT] the threshold value of QHAT above which it can be
		assumed that the chain has converged
		* default is 0.95
		* notes:
		  -- generally, both RTHRESH and QTHRESH must be satisfied,
		     and the latter for all chains, for burning to stop
		     before NBURN is reached
		  -- if the number of chains is 1, RTHRESH is ignored
	nbatch	[INPUT] caught and discarded, because it will be set to 1
		in call to MCMC_STEP
	aburn	[OUTPUT] all the parameters looked at in each step
		* is of size {NPAR,NCHAIN,NBURN}
	_extra	[INPUT ONLY] pass defined keywords to subroutines:
		sigy	[MCMC_STEP]
		funcs	[MCMC_STEP]
		fnprob	[MCMC_STEP]
		thaw	[MCMC_STEP]
		singly	[MCMC_STEP]
		sampar	[MCMC_STEP]
		sclpar	[MCMC_STEP]
		seed	[MCMC_STEP]
		testtyp	[MCMCM]
		ties	[ADJUSTIE]
		*	[FUNCS]
		*	[FNPROB]

subroutines
	ADJUSTIE
	ARITHTOGRAM()
	LOGIT()
	MCMC_STEP()
	MCMCM()
	UNLOGIT()
	-FUNCS-
	-FNPROB()-

history
	vinay kashyap (Jun05)

(See /data/fubar/SCAR/pro/stat/mcmc_burn.pro)


MCMC_CHAIN

[Previous Routine] [Next Routine] [List of Routines]
function	mcmc_chain
	a simple MCMC chain that generates new parameter values
	and adds them on to a chain, and returns the chains in
	a structure of the form
	{PROB: likelihood, PAR1: parameter 1, ..., PARn: parameter N}
	where each parameter is stored in a structure of the form
	{TRACE,MEAN,MEDIAN,MODE,MIN,MAX,STDDEV,HIP68,CLEV68,CLEV90}
	This is based on the XSPEC "chain" command, which carries
	out a Metropolis-Hastings chain using the best-fit values
	and the covariance matrix sigmas as Gaussian proposal
	distributions.

syntax
	parstr=mcmc_chain(x,y,parval,parsig,parinit=parinit,parrng=parrng,$
	ulim=ulim,/useMH,ysig=ysig,freeze=freeze,funcs=funcs,$
	type=type,ydc=ydc,arfil=arfil,areff=areff,rmfil=rmfil,ties=ties,xfilter=xfilter,$
	/perbin,nsim=nsim,nburn=nburn,onepar=onepar,verbose=verbose,$
	bgx=bgx,bgy=bgy,bparval=bparval,bparsig=bparsig,bparini=bparini,$
	bparrng=bparrng,bysig=bysig,bkgscal=bkgscal,bfreeze=bfreeze,$
	btype=btype,$
	mcmc_trace=mcmc_trace,mcmc_prb=mcmc_prb,$
	mcmc_flux=mcmc_flux,mcmc_counts=mcmc_counts,$
	mcmc_btrace=mcmc_btrace,mcmc_bprb=mcmc_bprb,$
	mcmc_bflux=mcmc_bflux,mcmc_bcounts=mcmc_bcounts,$
	solnup=solnup,solndn=solndn,solnpr=solnpr,solnsimul=solnsimul,$
	denspr=denspr,densxpr=densxpr,$
	bsolnup=bsolnup,bsolndn=bsolndn,bsolnpr=bsolnpr,bsolnsimul=bsolnsimul,$
	bdenspr=bdenspr,bdensxpr=bdensxpr,$
	...)

parameters
	x	[INPUT; required] the abscissa array defining the data
		* if an RMF is given, then this _must_ be in channels
	y	[INPUT; required] the data array
		* size of X and Y must match
		* counts preferred
	parval	[INPUT; required] array of starting parameter values
		* if USEMH is set, these are assumed to be the
		  best-fit values
	parsig	[INPUT; required] stddev of the Gaussian distribution to
		use as the proposal distribution.  typically, use values
		determined with the covariance matrix, inflated by 2-10x
		as needed.
		* use of functions other than Gaussians is possible,
		  but not yet implemented
		* size must match that of PARVAL, and all elements
		  must be +ve.  if not,
		  - if scalar, assumed to be the same error on all PARVAL:
		    	if 0<PARSIG<1, then set to PARSIG*PARVAL
		    	if 1<PARSIG<100, then set to (PARSIG/100)*PARVAL
		    	if PARSIG>100, then set to PARSIG
		    	if PARSIG<0, then set to abs(PARSIG)
		  - if vector, then each element controls the width of
		    the distribution for that parameter.  if any of the
		    elements are -ve, then the absolute value is treated
		    as the fractional error on that parameter, same as
		    the scalar case above.

keywords
	parinit	[INPUT] use these to set the starting values of the
		chain.  if given and has the right size, will always
		override PARVAL.  useful when USEMH is set.
	parrng	[INPUT] 2-D array of size [2,N(PARVAL)] to set the
		limits on how far the chain can range.  points that
		fall outside the range will be forced on to the boundary.
		* if not given, then no bounds are set
		* set individual elements to !VALUES.F_NAN to selectively
		  toggle the bounds
		* if scalar, then the same fractional range is applied to
		  all the parameters, e.g., setting "parrng=10" causes the
		  range for all parameters to go from PARVAL/10 to PARVAL*10
		  - PARRNG=1 is the same as PARRNG=1e5
		  - if -ve, then PARVAL+-abs(PARRNG) is used as the range
		* if 2-element vector, it is the same as the scalar, except
		  that the range can be asymmetrical, with the 1st element
		  defining the lower range and the 2nd element defining the
		  upper range.
	ulim	[INPUT] array of indices specifying which of the input Y
		are upper limits (1: UL, 0: not).
		* An upper limit is treated differently in the calculation of the
		  likelihood: any parameter value that predicts a model value less
		  than Y will have no effect on the computed likelihood, but if it
		  predicts a model value greater than Y, the likelihood becomes 0
		  (or the chi^2 blows up)
	useMH	[INPUT] if set, uses a Metropolis-Hastings scheme, with
		a proposal distribution centered at PARVAL and with
		width PARSIG.
		* if not set, uses a Metropolis scheme, with a proposal
		  distribution that is centered on the current parameter
		  value and with width PARSIG
	ysig	[INPUT] the error on Y
		* default is to use sqrt(abs(Y)+0.75)+1, corresponding
		  Gehrels' approximation
	freeze	[INPUT] array of indices of parameters that must be frozen
		(note: indexing begins from zero!)
	funcs	[INPUT] name of user-defined procedure that takes as
		input X and A, and returns YMODEL(X;A).  Any procedure
		that was written to work with CURVEFIT or GHRS' WFIT or
		Craig Marwardt's MPFIT will do
		* default is set to LIBMODEL
		* why is it a procedure and not a function?
		  well, ask the person who wrote CURVEFIT.
	type	[INPUT] string array of models to pass down to LIBMODEL
	ydc	[INPUT] an array given as an offset to Y(X)
		* if scalar, assumed to be a constant offset at all X
		* if vector, size must match that of Y, else is ignored
	arfil	[INPUT] ancillary response file
	areff	[INPUT] an array of effective areas may be input in lieu
		of ARFIL, on the same grid as X
		* ignored if size does not match X or if ARFIL is given
	rmfil	[INPUT] response matrix file
	ties	[INPUT] constraints on parameters, passed w/o comment to ADJUSTIE
	xfilter	[INPUT] array of X indices to use as a filter
		* if not set, the entire array is used
	perbin	[INPUT] if set, computes the model in units of /bin instead
		of /unit (e.g., /Ang, /keV, etc.)
	nsim	[INPUT] number of simulations to keep after burn-in
		* default is 1000L
	nburn	[INPUT] minimum number of simulations to use for burn-in
		* default is 0.1*NSIM
		* some rudimentary checks are made to see whether burn-in
		  has succeeded, and if it hasn't, then burn-in will
		  continue.  these simulations are not saved.
		  *** NOT YET IMPLEMENTED ***
		* to override the fuzziness of the burn-in, set NBURN to
		  a negative number, e.g., -100, and then the burn-in phase
		  will end regardless after abs(NBURN) iterations.
	onepar	[INPUT] if set, kicks one parameter at a time
		* the default is to get new deviates for all the
		  thawed parameters at once
		* If input as an integer vector, this can also be used to
		  vary bunches of parameters at once.  the first element
		  contains the number of bunches defined, NBUNCH.  The
		  succeeding elements contain, in sequence, the number of
		  parameters in a given bunch, and their indices.  e.g.,
		  in the case of a DEM with 81 temperature bins and 30
		  abundance bins where each set is varied separate bunches,
		  set this to
		  	[2, 81, lindgen(81), 30, lindgen(30)+81]
		  Parameters not included in this list are varied one by
		  one after all those listed here are dealt with.
	verbose	[INPUT] controls chatter

	bgx	[INPUT] the abscissa array to define the background
		* if not given, but BGY is given, assumed to be same as X
	bgy	[INPUT] the background array
		* if not given, it is assumed that there is no background
		* size must match BGX
		* counts preferred
		* WARNING: separate ARFs/RMFs for background are not
		  yet implemented
	bparval	[INPUT] like PARVAL, for the background model
		* if not given, but BGY is given, then the background
		  is not fit, but rather the source model is fit to
		  background-subtracted data
		* SOMEDAY: convert to using background marginalization
	bparsig	[INPUT] like PARSIG, for the background model
		* ignored if BPARVAL is not defined
		* size must match that of BPARVAL
		* if not given, but BPARVAL is given, then the background
		  model is frozen at BPARVAL (or BPARINI, if given)
	bparini	[INPUT] like PARINIT, for the background model
		* ignored if BPARVAL is not defined
		* size must match that of BPARVAL
		* if given, overrides BPARVAL
	bparrng	[INPUT] like PARRNG, for the background model
		* ignored if BPARVAL is not defined
	bysig	[INPUT] the error on BGY
		* default is to use sqrt(abs(BGY)+0.75)+1, corresponding
		  Gehrels' approximation
	bkgscal	[INPUT] the background scaling factor for normalization
		corrections, is the ratio of the geometric area of the
		background to source, but could also include exposure
		times, effective area, etc.
		* correction applied post RMF convolution
		* if vector, must match the size of BGX
	bfreeze	[INPUT] array of indices of background parameters that
		must be frozen
		* note: indexing starts with 0
	btype	[INPUT] string array of background models to pass down
		to LIBMODEL
	bties	[INPUT] constraints on bakground model parameters, passed
		w/o comment to ADJUSTIE
	barfil	[INPUT] ARFIL for background data (NOT IMPLEMENTED)
	brmfil	[INPUT] RMFIL for background data (NOT IMPLEMENTED)
	mcmc_trace	[OUTPUT] trace of source parameters
	mcmc_btrace	[OUTPUT] trace of background parameters
	mcmc_flux	[OUTPUT] trace of source model fluxes
	mcmc_bflux	[OUTPUT] trace of background model fluxes
	mcmc_counts	[OUTPUT] trace of source model counts
	mcmc_bcounts	[OUTPUT] trace of background model counts
	mcmc_prb	[OUTPUT] trace of samples from source posterior pdf
	mcmc_bprb	[OUTPUT] trace of samples from background posterior pdf
	solnup	[INPUT] a previously obtained set of MCMC solutions that
		serve as an upper limit to the current calculation
		* should be an array of size [N(PARVAL),N(SIMULATIONS)]
	solndn	[INPUT] as SOLNUP, but as a lower limit to the current calc
		* should be an array of size [N(PARVAL),N(SIMULATIONS)]
	solnpr	[INPUT] a previously obtained set of MCMC solutions that
		can be used as a direct prior for the current calculation
		* should be an array of size [N(PARVAL),N(SIMULATIONS)]
	solnsimul	[INPUT] a previously obtained set of MCMC solutions
			that are incorporated into the current MCMC simultaneously
			(not implemented)
			* should be an array of size [N(PARVAL),N(SIMULATIONS)]
	denspr	[INPUT] a formal probability density to act as a prior on the
			parameters (not implemented)
	densxpr	[INPUT] the absissa grid for DENSPR (not implemented)
	bsolnup	[INPUT] as SOLNUP, for the background parameters (not implemented)
		* should be an array of size [N(BPARVAL),N(SIMULATIONS)]
	bsolndn	[INPUT] as SOLNDN, for the background parameters (not implemented)
		* should be an array of size [N(BPARVAL),N(SIMULATIONS)]
	bsolnpr	[INPUT] as SOLNPR, for the background parameters (not implemented)
		* should be an array of size [N(BPARVAL),N(SIMULATIONS)]
	bsolnsimul	[INPUT] as SOLNSIMUL, for the background parameters
			(not impelmented)
			* should be an array of size [N(BPARVAL),N(SIMULATIONS)]
	bdenspr	[INPUT] as DENSPR, for the background parameters (not implemented)
	bdensxpr	[INPUT] as DENSXPR, for the background parameters
			(not implemented)
	_extra	[INPUT ONLY] pass defined keywords to subroutines
		LIBMODEL: NORM,FWHM,etc.
		ADJUSTIE: VNAME
		LIKELI: SOFTLIM,CASH,CASTOR,BINOM

subroutines
	RDARF()
	RD_OGIP_RMF()
	BINERSP()
	ADJUSTIE
	KILROY

history
	vinay kashyap (Apr2008)
	various updates, bug fixes, and enhancements (VK; Sep2008)
	changed behavior of vector PARSIG and BPARSIG to match scalar, so now
	  -ve inputs are treated as absolute sigma; bugfix when chain was
	getting stuck, the proposal was turning into a delta fn (VK; Oct2009)

(See /data/fubar/SCAR/pro/mcmc_chain.pro)


MCMC_DEM

[Previous Routine] [Next Routine] [List of Routines]
function	mcmc_dem
	performs Markov-Chain Monte-Carlo using a Metropolis algorithm
	on a set of supplied line fluxes and returns an estimate of the
	DEM that generates observed fluxes.

syntax
	dem=mcmc_dem(wavelengths,fluxes,emissivities,Z=Z,logt=logt,$
	diffem=initial_DEM,abund=abundances,fsigma=flux_errors,$
	onlyrat=onlyrat,sysdev=sysdev,sysgrp=sysgrp,$
	sampenv=sampenv,storpar=storpar,storidx=storidx,$
	bestpar=bestpar,$
	simprb=simprb,simdem=simdem,simabn=simabn,simflx=simflx,simprd=simprd,$
	ulim=upper_limit_flag,softlim=softlim,demrng=DEMrange,abrng=abrng,$
	smoot=smooth,loopy=loopy,/spliny,verbose=verbose, xdem=DEM_bins,xab=ABUND_bins,$
	nsim=nsim,nbatch=nbatch,/steps,weight=weight,/gauss,type=type,/boxcar,$
	nburn=nburn,/nosrch,savfil=savfil,bound=bound,demerr=demerr,$
	aberr=aberr,/temp,/noph,effar=effar,wvlar=wvlar,/ikev,/regrid,$
	mproxy=mproxy,mplet=mplet)

parameters
	wvl	[INPUT; required] wavelengths [Ang] at which fluxes are
		observed
		* NOTE: these are used only if the keyword NOPH is _not_ set,
		  i.e., when the input is to be converted from [erg/...] to
		  [ph/...].  In cases when the EMIS is precomputed with the
		  effective area and abundances (e.g., for filter data from
		  solar observatories), this is a dummy variable.
	flx	[INPUT; required] flux [ph/s] at each WVL ([ph/s/cm^2]
		if EFFAR and WVLAR are not passed to LINEFLX)
	emis	[INPUT; required] line emissivities [1e-23 ergs cm^3/s]
		* EMIS==EMIS(LOGT,WVL)
		* DEM is computed at all temperatures that EMIS are defined.
		* NOTE: the units are assumed to be [1e-23 ergs cm^3/s],
		  but of course the code doesn't care what they are exactly.
		  So it is perfectly possible to have them in units of, e.g.,
		  [DN cm^5 s^-1 pix^-1] if one so chooses (see SOLAR_TRESP.PRO)

keywords
	Z	[INPUT] atomic numbers of the elements generating the
		lines at WVL.
		* if not given, assumed to be Fe
		* if EMIS are precalculated including abundances, then
		  set this to *1* (to mimic H)
	logt	[INPUT] log_10(Temperature [K]) at which EMIS are given
		* if not supplied, assumed to go from 4 to 8
		* if there is a size mismatch, logT will get stretched/shrunk
		  to cover EMIS
	diffem	[INPUT] initial guess for DEM(LOGT); default is 1e14 [cm^-5]
	abund	[I/O] abundances.  default is to use Anders & Grevesse (see
		GETABUND)
		* if ABRNG is non-trivial, will be allowed to vary and on
		  exit will contain the MAP estimates of the abundances.
		* minimum is hardcoded at 1e-20
	fsigma	[INPUT] error on FLX; if not given, taken to be
		1+sqrt(abs(FLX)+0.75)
	ulim	[INPUT] long-integer array specifying which of the fluxes
		are upper limits (1: UL, 0: not)
	onlyrat	[INPUT] string array describing which of the input fluxes
		must be considered only as ratios
		* each element of ONLYRAT corresponds to the fate of the
		  corresponding element of FLX
		* basic format is: "sP#[,sP#[,...]]" where
		  -- "#" is an integer flag describing the ratio being
		     constructed
		  -- "P" is a positional descriptor and can take on
		     values N (for numerator) or D (for denominator)
		  -- "s" stands for the sign with which the flux
		     goes into the ratio "+" or "-"
		* e.g., to construct a simple ratio FLUXES[2]/FLUXES[1],
		  ONLYRAT=['','+D1','+N1']
		* e.g., to construct two hardness ratios
			FLUXES[3]/FLUXES[1] and
			(FLUXES[3]-FLUXES[1])/(FLUXES[3]+FLUXES[1]),
		  ONLYRAT=['','+D1,-N2,+D2','','+N1,+N2,+D2']
	sysdev	[INPUT] systematic deviations in the underlying atomic
		physics data, multiplies the emissivity for a given line
		by a random number in each iteration to mimic systematic
		uncertainty in EMIS
		* it is assumed that these modifications are small -- if
		  you do use this option, please check the output traces
		  to make sure that the chain is stable
		* should be an array of the same size as FLX, and each
		  number defines the range over which EMIS[*,WVL] varies,
		  10.^(randomn(seed)*SYSDEV[i])*EMIS[*,i]
		* if size is smaller than FLX, the missing elements are
		  set to 0, i.e., no modifications are made
	sysgrp	[INPUT] group different rows in EMIS to vary the same way
		in each iteration, is simply an array of 1-based grouping
		indices
		* e.g., if N(WVL)=6, and SYSGR=[0,1,2,1,0,2], then rows
		  1 and 3 are modified in conjunction (i.e., if #1 is
		  changed by a factor 10^(r*SYSDEV[1]), then #3 is changed
		  by a factor 10^(r*SYSDEV[3]), where r is the same for both),
		  2 and 5 are modified in conjunction, but 0 and 4 are
		  _not_ tied together and are independently varied
		* if SYSDEV is not defined, SYSGRP is ignored
		* size must match that of FLX, but if smaller, the missing
		  elements are set to -1, i.e., are all tied together
		  - so if SYSGRP is not defined at all, all the rows are
		    tied together, and only SYSDEV[0] is used
	demrng	[INPUT] array containing the allowed range of variation
		in DEM: DEMRNG(i,0) < DEM(i) < DEMRNG(i,1)
 		* if not supplied, DEMRNG(*,0)=DEM/1e5 & DEMRNG(*,1)=DEM*1e5
		* if DEMRNG(k,0)=DEMRNG(k,1), this component is frozen
	abrng	[INPUT] as DEMRNG, for ABUND.
		* if not supplied, ABRNG(*,0)=ABUND(*)=ABRNG(*,1)
	xdem	[INPUT] bin boundaries for accumulating the realized DEMs
		* if scalar or 1-element vector, taken to be bin-width in log10
		* if not specified, runs from min(DEMRNG) to max(DEMRNG)
		  in steps of 0.1 in log10
	xab	[INPUT] bin boundaries for accumulating the realized ABUNDs
		* if scalar or 1-element vector, taken to be bin-width
		* if not specified, runs from min(ABRNG) to max(ABRNG) in
		  steps of 0.1 in log10
	xnsig	[INPUT; default=3] force a minimum search range of
			XNSIG*sigma_determined_internally
	nsim	[INPUT; default: 100; min=10] # of batches
	nbatch	[INPUT; default: 10; min=5] # simulations per batch
	nburn	[INPUT; default=NSIM/10] max # of simulations to run
		before assuming that solution has stabilized
		* note that this is a maximum -- if burn-in is achieved
		  earlier, the algorithm will move on to standard MCMC
	nosrch	[INPUT] if set, does *not* carry out a (crude) grid search
		for a best guess initial starting point.
		* if set to a IDL savefile name, restores the best guess
		  from said file
	savfil	[INPUT] if set, saves all variables to an IDL save file
		prior to exit
		* if not a string, or is an array, saves to 'mcmc.sav'
	bound	[INPUT; default=0.9] confidence interval of interest
		* minimum=0.1
	hwhm	[INPUT] if set, returns the upper and lower Half-Widths
		at Half-Maxmimum in DEMERR and ABERR.
	demerr	[OUTPUT] confidence bounds on MAP estimates of DEM
		* DEMERR(*,0) are lower bounds, DEMERR(*,1) are upper bounds
	aberr	[OUTPUT] confidence bounds on MAP estimates of ABUND
		* ABERR(*,0) are lower bounds, ABERR(*,1) are upper bounds
	smoot	[INPUT] if set, multiplies the local length scale determined
		using FINDSCALE by SMOOT.
	smooscl	[INPUT] if set, bypasses FINDSCALE and uses the scales input
		via this keyword as the local length scales
		* _must_ be in units of [bins], not delta_T, dlogT, or whatever
		* if vector and size matches LOGT, then uses the input values
		  as the [bins] over which to smooth
		* otherwise assumes constant smoothing scale corresponding to
		  first element
	loopy	[INPUT] if set, "smooths" by converting to T^3/2, loop-like DEM
		* use keyword SLOOP to change the index
		* set to a number >1 to limit the maximum number of
		  temperature components
	spliny	[INPUT] if set, "smooths" by making a spline interpolation
	sampenv	[INPUT] envelope from which to sample the temperature bins.
		this is a way to avoid T bins which may have no data and thus
		work more efficiently to explore just that part of the parameter
		space that is interesting.
		* if not given, or is not understandable, assumed to be the
		  simple envelope of all the emissivities in EMIS
		* if set to:
		  'ONLYRAT' - then the envelope is computed taking
		  	into account the ratios
		  'INCABUND' - then use emissivities weighted by the abundance
		  'FLAT' - then make no distinction between different T bins
		  'INCALLT' - then force a look at all T bins at a 1% level
		  'STEPPED' - then zero everywhere EMIS does not cover the
		  	T range, and at least 25% of maximum where it does
		  'COVER' - then zero everywhere EMIS does not cover the
		  	T range, and constant where it does
		* NOTE: multiple SAMPENV settings may be specified, and
		  they will be applied in the above sequence -- whether the
		  sequence makes sense or not is up to the user to determine
		* if set to a numerical array the same size as LOGT, then
		  simply use that array as the envelope
		* NOTE: recommend using 'COVER' or 'STEPPED' for EMIS
		  derived from broad-band filters such as for solar data
	storpar	[OUTPUT] parameters from the MCMC chain
	storidx	[OUTPUT] index of the parameters stored in STORPAR
	bestpar	[OUTPUT] best values of the parameters as found in the chain
	simprb	[OUTPUT] the metric at the end of each batch, an array of size
		(NSIM+1), with last element containing the value for the best-fit
	simdem	[OUTPUT] the DEM at the end of each batch, an array of size
		(NT,NSIM+1), with last column containing the best-fit
	simabn	[OUTPUT] same as SIMDEM, but for abundances
	simflx	[OUTPUT] same as SIMDEM, but for the fluxes with each [DEM,ABUND]
	simprd	[OUTPUT] same as SIMFLX, but for the ratios, only if ONLYRAT is used
       mixsstr [I/O]  Set to turn on line deblending via MIXIE().  
                Line (and/or conitnuum) structure of
                RD_LIST() format containing info (wvl,emis,z) on 
                lines (and/or continuum) for which possible contaminants will be identified 
                and for which correction factors  will be
                calculated. Assumes that ion equilibria are
                included. (see RD_LIST() keyword INCIEQ). 
       mixlstr [I/O] Line (and/or conitnuum) structure of
                RD_LIST() format containing info (wvl,emis,z) on 
                lines (and/or continuum) for which possible contaminants will be identified 
                and for which correction factors  will be
                calculated. Assumes that ion equilibria are
                included. (see RD_LIST() keyword INCIEQ)
                set to turn on line deblending via MIXIE().  
	verbose	[INPUT] explicitly set to 0 to avoid making plots
		* THINK TWICE before doing this!!
	_extra	[INPUT] pass defined keywords to subroutines
               ties    [ADJUSTIE] tie abundance parameters 
		temp	[LINEFLX] assume input LOGT are actually T [K]
		noph	[LINEFLX] compute fluxes in [ergs/s/...] not [ph/s/...]
		effar	[LINEFLX] effective area in [cm^2]
		wvlar	[LINEFLX] wavelengths at which EFFAR are defined [Ang]
		nhne	[LINEFLX] ratio of N(H)/n_e, assumed to be 0.83
		softlim	[LIKELI] allow for upper limits to be softly defined
		steps	[VARSMOOTH] assume stepped averaging from smoothing scale
		weight	[VARSMOOTH] allow weighting of adjacent points in boxcar smooth
		type	[VARSMOOTH] functional form to smooth with, see X3MODEL/LIBMODEL
		boxcar	[VARSMOOTH] controls smoothing behavior at endpoints
		betap	[MK_LORENTZ/MK_SLANT] index of beta-profile
		angle	[MK_SLANT] angle of tilt
		fwhm	[MK_GAUSS/MK_LORENTZ/MK_ROGAUSS] return FWHM rather than
			sigma or core width
		sloop	[LOOPEM] slope of loop DEM
		dfx_mul	[GENERATIO] multiplicative delta_Fx to compute partials
		dfx_add	[GENERATIO] additive delta_Fx to compute partials
		choice	[FINDSCALE] flag to choose algo to find the scales
		pick	[FINDSCALE] flag on hoe to collapse scales from 2D to 1D
		crunch	[FINDSCALE] collapse 2D to 1D prior to finding scales
		half	[FINDSCALE] return half-scale
		eps	[FINDSCALE] a small number
               mproxy  [MIXIE]  see MIXIE() 
               mplet   [MIXIE]  see MIXIE()
               
restrictions
	requires subroutines
	-- KILROY
	-- GETABUND
	-- MCMC_DEM_ONLY [LINEFLX, LIKELI, MK_DEM, VARSMOOTH, LOOPEM]
	-- LINEFLX [GETABUND, WHEE]
	-- LIKELI [SOFTLIM]
	-- FINDSCALE [WVLT_SCALE [ROOFN]]
	-- MK_DEM
	-- LOOPEM
	-- VARSMOOTH
	-- GENERATIO
       -- ADJUSTIE

history
	vinay kashyap (Apr 97)
	added keyword SMOOT (VK; May97)
	added keyword LOOPY and replaced call to VARSMOOTH by call to
	  MK_DEM (VK; Nov01)
	added keyword ONLYRAT and call to GENERATIO (VK; Nov'02)
	numerous bug fixes (VK/LL; Dec'02)
	ratio stuff was not being passed on to MCMC_DEM_ONLY; now stores
	  simulated DEMs, ABUNDs, fluxes, and ratios (VK/LL; Jan'03)
	added keywords SAMPENV,STORPAR,STORIDX,SIMPRB,SIMDEM,SIMABN,
	  SIMFLX,SIMPRD,NBURN (VK; Feb'03)
	added keyword SMOOSCL (VK; May'03)
	added keyword SPLINY (VK; Jun'03)
	added _extra to call to PRED_FLX (VK; Jul'03)
       bugfix sampenv ONLYRAT keyword handler included (VK/LL:Dec'03)
       bugfix sampenv was ignored if input as array (LL: Dec'03)
       bugfix nemt is undefined in logt keyword handler(LL:Dec'03)
       added BRNSTR in call to MCMC_DEM_ONLY() to enable deblending
         via MIXIE() (LL:Jan'04)
       bugfix abndupdt, a MIXIE keyword  now set by default and 
         turned off if abrng keyword is set (LL:Mar'04) 
	added keyword XNSIG (VK; Jun'04)
	bug fix: compute DEMs for /LOOPY and /SPLINY on correct T grid
	  (VK; Jan05)
	allow limiting number of T components for LOOPY (VK; Mar05)
       added call to adjustie and MIXLSTR keyword (LL; Jun05) 
	added LCOMP to call to MK_DEM, check to make sure FSIGMA
	  are all +ve definite, and a warning if ABUND[0] is not 1,
	  force single T deviate per iteration for LOOPY (VK; Jun05)
	bug correction: if no update found in a batch, was still
	  storing DEM from that batch; now corrected (VK; Jul05)
	added options COVER and STEPPED for SAMPENV (VK; Jan06)
	include extra kick at NPAR+1 to unfreeze parameters in case
	  of LOOPY getting stuck; also bug correction for NPAR+1
	  selections in regular case if some T bins are frozen
	  (VK; Apr06)
	added keyword VERBOSE (VK; Jun07)
	added keyword BESTPAR (VK; Nov08)
	added keywords SYSDEV and SYSGRP (VK; Apr09)

(See /data/fubar/SCAR/pro/mcmc_dem.pro)


MCMC_DEM_ONLY

[Previous Routine] [Next Routine] [List of Routines]
procedure	mcmc_dem_only
	dedicated subroutine to MCMC_DEM, written only to make MCMC_DEM
	more readable.  this part decodes the parameters, calls LINEFLX
	to get predicted fluxes and LIKELI to get the likelihood.

syntax
	mcmc_dem_only,pars,fobs,fsigma,ulim,line,logT,wvl,Z,scale,ff,prb,$
	dem,abnd,loopy=loopy,/spliny,nrats=nrats,onlyrat=onlyrat,obsdat=obsdat,$
	obssig=obssig,idxflx=idxflx,prddat=prddat, _extra=e

parameters
	pars	[I/O] parameters {DEM(T),ABUND}, ABUND can be updated
	              via MIXIE() 
	fobs	[INPUT] observed fluxes
	fsigma	[INPUT] errors on FOBS
	ulim	[INPUT] integer array specifying upper limits (1: UL, 0: not)
	line	[INPUT] emissivities of lines identified with FOBS
	logT	[INPUT] temperatures at which LINE is defined
	wvl	[INPUT] wavelengths at which fluxes are observed
	Z	[INPUT] atomic numbers of each id'd line
	scale	[INPUT] smoothing scale
	ff	[OUTPUT] predicted fluxes
	prb	[OUTPUT] likeihood (could be chi^2)
	dem	[OUTPUT] DEM
	abnd	[OUTPUT] abundances

keywords
	loopy	[INPUT] if set, "smoothing" by converting to T^3/2 DEM
	spliny	[INPUT] if set, "smooth" by using spline interpolation
	onlyrat	[INPUT]
	obsdat	[INPUT]
	obssig	[INPUT]
	idxflx	[INPUT]
	nrats	[INPUT]
	verbose	[INPUT]
	_extra	[INPUT] pass defined keywords to LINEFLX (TEMP, EFFAR,
		WVLAR, KEV, REGRID), LIKELI (SOFTLIM, CHI2, RCHI, BINOM),
		VARSMOOTH (STEPS, WEIGHT, TYPE), LOOPEM (SLOOP), or
               ADJUSTIE (TIES) 

restrictions
	no error checking is done because it is assumed that this is
	called from and only from MCMC_DEM

history
	vinay kashyap (May97)
	changed SIGMA to FSIGMA; added DEM and ABND to parameter list
	  (VK; AugMM)
	added keyword LOOPY, and switched out VARSMOOTH for MK_DEM
	  (VK; Nov01)
	added keywords ONLYRAT,OBSDAT,OBSSIG,IDXFLX,NRATS and call to
	  GENERATIO (VK; Dec'02)
	numerous bug fixes (liwei lin/VK; Dec'02)
	added keyword PRDDAT (VK; Jan'03)
	added keyword SPLINY (VK; Jun'03)
       added keywords BRNSTR,MIXLSTR,MIXSSTR,BRNSTR,XFRAC, as well as 
         abundance updating via parameter  PARS. PARS now
         contains updated abundances from MIXIE() on
         output if MIXIE() keyword ABNDUPDT is set (LL; Jan'04) 
	bug fix: compute DEMs for /LOOPY and /SPLINY on correct T grid (VK; Jan05)
	allow limiting number of T components for LOOPY (VK; Mar05)
       added call to ADJUSTIE to tie ABUND values (LL; Jun05)  
	added keyword VERBOSE (VK; Jun07)

(See /data/fubar/SCAR/pro/mcmc_dem_only.pro)


MCMC_DEM_POST

[Previous Routine] [Next Routine] [List of Routines]
function	mcmc_dem_post
	returns the best-fit values and the error ranges for the
	various parameters in a structure of the form:
	{LOGT, NUEFF, MINCHISQ, BOUND,$
	DEM_BEST,DEM_MODE,DEM_HPD,DEM_EQT,DEM_MEDIAN,DEM_RNG,DEM_ENV,DEM_FRAC,$
	AB_BEST,AB_MODE,AB_HPD,AB_EQT,AB_MEDIAN,AB_RNG,AB_ENV}

syntax
	mcmcstr=mcmc_dem_post(savfil,clev=clev,verbose=verbose)

parameters
	savfil	[INPUT; required] full pathnmae to the save file
		that is written out by MCMC_DEM()

keywords
	clev	[INPUT] set this to override the confidence level at
		which to determine the bounds on the parameters
		* default is to use EBOUND in SAVFIL
		* if < 0, abs value is used
		* if > 1 and < 100, then assumed to be given as a percentage
		* if > 100, then 1-1/CLEV is used as the true value
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to prevent crashing the program

output description
	LOGT:	the temperature grid
	NUEFF:	the effective degrees of freedom for adopted smoothing
	MINCHISQ:	the minimum chisq achieved
	BOUND:	the confidence level at which to compute errors
	*_BEST: best-fit parameter value
	*_MODE: mode of parameter
	*_MEDIAN:	median of parameter
	*_HPD: highest probability-density range at confidence BOUND
	*_EQT: equal-tail range at confidence BOUND
	*_RNG: half-tail range at confidence BOUND measured from best-fit
	*_ENV:	envelope range of best BOUND fraction (by chisq)
	DEM_FRAC:	number of hits at each temperature bin
	HELP:	a description of the output

subroutines
	MODALPOINT
	HIPD_INTERVAL
	EQT_INTERVAL

history
	vinay kashyap (Apr2006)
	bug fix: simprb was being compared to chisqcvf rather than half that
	  (LL; May2006)

(See /data/fubar/SCAR/pro/mcmc_dem_post.pro)


MCMC_DEVIATE

[Previous Routine] [Next Routine] [List of Routines]
function	mcmc_deviate
	returns a set of parameters as a deviation from the current set

	ideally, this function should be called from MCMC_STEP().
	unfortunately, while that improves readability, it helps
	with neither speed nor efficiency of computation.  e.g.,
	when the parameters are sampled from SAMPAR, using this
	function will result in a lot of wasted samples of the
	parameters, and when each parameter is updated singly, a
	lot of wasted tests.  so, while I will try to keep this
	as up to date as possible, MCMC_STEP() will retain all the
	functionality present here, and will likely be the program
	of choice for the foreseeable future.

syntax
	testpar=mcmc_deviate(par,sigpar,rngpar=rngpar,thaw=thaw,sampar=sampar,$
	sclpar=sclpar,seed=seed)

parameters
	par	[INPUT; required] parameters of the model to fit to Y(X)
		* parameters should be 1-D array
		* if 2-D, the size of the 2nd dimension describes the
		  number of chains that are concurrently running
	sigpar	[INPUT; required] this is used to determine how to get
		a new set of parameters with PAR as the starting point
		* if size is identical to the first dimension of PAR, then
		  +ve ==> assumed to be the stddev of Gaussian centered on PAR
		  -ve ==> abs value assumed to be maximum deviation from PAR

keywords
	rngpar	[INPUT] the allowed range for each parameter as a 2-D
		array of size (N(PAR),2)
		* overrides output of SIGPAR
		* if 1-D array, range assumed to be symmetrical
		  -- additive if +ve
		  -- abs value multiplicative if -ve
		* ignored if size doesn't match
		* WARNING: RNGPAR[.,0] must be less than RNGPAR[.,1]
		  in the interests of speed, this is _not_ checked for
	thaw	[INPUT] array indicating which parameters are frozen (0) and
		which are thawed (1)
		* size _must_ match number of parameters, else all
		  parameters are assumed thawed
		* overrides SIGPAR and RNGPAR
	sampar	[INPUT] used to determine how to pick the parameters
		to vary within the program:
		-- if not set, then parameters are picked in sequence
		-- if set to scalar, then parameters are picked randomly
		-- if set to array of same size as PAR, assumed to be
		   a sampling distribution for the parameters
	sclpar	[INPUT] a flag that describes how PAR should be scaled
		prior to taking a deviate
		1 == alog(PAR) scaling ;	-1 == exp(PAR) scaling
		10 == alog10(PAR) scaling ;	-10 == 10^PAR scaling
		100 == LOGIT() scaling ;	-100 == UNLOGIT() scaling
		2 == sqrt(PAR) scaling ;	-2 == PAR^2 scaling
		0, or other == no scaling
		* NOTE: no checks are made to ensure that values are
		  defined post-transformation -- it is the responsibility
		  of the user to ensure that the scaling makes sense
		* if scalar, the same scaling is applied to all the parameters
		* if vector, size must match the number of parameters, or
		  else this is ignored
	seed	[I/O] seed for random number generator
	_extra	[JUNK] here only to prevent crashing the program

subroutines
	LOGIT()
	UNLOGIT()

history
	vinay kashyap (Jun2005)

(See /data/fubar/SCAR/pro/stat/mcmc_deviate.pro)


MCMC_OUT

[Previous Routine] [Next Routine] [List of Routines]
MCMC_OUT
	program to read in the output of MCMC_DEM for further
	manipulation.

vinay kashyap (Mar97)
	numerous bug fixes (VK/LL; Dec'02)

(See /data/fubar/SCAR/pro/mcmc_out.pro)


MCMC_PLOT

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

       This procedure plots Monte Carlo Markov-Chain DEM
       reconstruction results. One sigma uncertanties are 
       shown as a grey scale (or otherwise specified) with a gradient
       determined by how the N simulated DEMs (which  ordain the one sigma
       confidence intervals) are distributed about the best-fit DEM. 
       Alternatively, the gradient may be determined by the p(D|M) of 
       each DEM.
 
       NOTE: ALL REQUIRED INPUTS ARE STANDARD MCMC_DEM() OUTPUTS

parameters
       logt    [INPUT; required] array which determines the mid-bin values 
               of the temperature grid on which DEM is defined
       simdem  [INPUT; required] two dimensional array [NT, NSIM+1]
               simulated arrays, the last of which is the best fit. 
       demerr  [INPUT; required] confidence bounds on MAP estimates of DEM
		* DEMERR(*,0) are lower bounds, DEMERR(*,1) are upper bounds
       simprb  [INPUT; required] the p(D|M) of each DEM            
       schme   [INPUT; optional] string designating plotting strategy. Can be:

                   'ERRBAR'      - Just plot error bars using DEMERR (default)
                   'DIFFERENCE'  - Colors are determined by
                                   difference of each DEM simulation
                                   bin value from the best fit DEM
                                   values. Colors are polyfilled
                                   between simulated values within
                                   each  logT bin. 
                   'INDEX'       - Colors are determined by the order in which
                                   they appear (starting from the best
                                   DEM outwards). Colors are polyfilled
                                   between simulated values within each
                                   logT bin. 
                   'SPLINE INDEX'- Colors are determined by the order in which
                                   they appear (starting from the best
                                   DEM outwards). Colors are polyfilled
                                   between simulated values within each
                                   logT bin. Spline interpolated
                                   curves are plotted in lieu of
                                   histogram style bins
                   'PROB'        - Colors are determined by the p(D|M)
                                   of each DEM. Values are oploted
                                   with thick bars between simulated
                                   values within each  logT bin.
                   'SPLINE'      - Simulated DEMS are spline
                                   interpolated and colors determined
                                   by the p(D|M) associated with
                                   each. Each spline is oploted onto
                                   a best-fit dem plot. 
                   'NICE'        - For each temperature bin, a median simulation
                                   value is calculated. The median values will be
                                   plotted (dotted line) together with the DEM
                                   simulation (solid line) that best fits them.
                                   Uncertainty will be displayed by plotting the MIN and
                                   MAX simulation values for each
                                   bin. (dashed lines) Use the SLECT and CLEV
                                   keywords to limit which simulations to include.
                   'NICE DIFFERENCE' - A combination of DIFFERENCE and NICE
                                   Colors are determined by
                                   difference of each DEM simulation
                                   bin value from the best fit DEM
                                   simulation to the median value as
                                   described in the 'NICE'
                                   definition.  Colors are polyfilled
                                   between simulated values within
                                   each  logT bin. 
                   'NICE INDEX'    - A combination of DIFFERENCE and NICE 
                                   Colors are determined by the order in 
                                   which they appear (starting from the 
                                   best fit simulation to the median value 
                                   as described in the 'NICE' definition. 
                                   Colors are plyfilled between simulated
                                   values within each logT value.                                 
                   'SUPPORT'       - Just plot upper and lower bounds of the 
                                   support in each bin given the set of 
                                   selected DEMs (see SLECT keyword) 

       storidx [INPUT ; optional]  from MCMC_DEM(), contains the indices of 
                                   of all the sampled parameters stored in
                                   STORPAR. If a temperature bin has not been 
                                   adequately sampled ( default threshold is
                                   nsim*0.10 ), then the bin is not
                                   plotted. Only bins at the ends of the Log
                                   T range are thrown out. (see SAMPCT keyword)
 
keywords
       slect    [INPUT]  choose which DEMS to include default=[2] 
            
                   1:ALL     -Include all simulations
                   2:CHI^2   -Limit simulations to best 50% p(D|M) DEMS
                              (default = 50, use CLEV keyword to toggle)
                   3:Errors  -Limit simulations to values in each bin that
                              lie  within the specified confidence bounds (demerr)
       clev     [INPUT]  To be used in conjunction with slect=2,
                         determines what percentage by which to limit
                         sims in p(D|M) 
       col_rng  [INPUT]  index range in the color table to cover. 
                         gradient will taper
                         off from 0 (darkest) to 
                         col_rng (brightest). (maximum is 255)
       col_tabl [INPUT]  color table on which to base the gradient       
       col_shft [INPUT]  number of color indices by which to shift
                         brighter(or darker if black background), col_rng will
                         be adjusted accordingly
       ps_fil   [I/O]    name of ps file to output. If not specified 
                         plot will be sent to current device
       demslope [I/O]    if set, linear fits are made to the simulated DEMs 
                         in a temperature range specefied by keyword SLOPEDT 
                         and DEMSLOPE will return the mean slope. The
                         distribution of slopes will be plotted
       slopesig [OUTPUT] if set, returns standard deviation slopes of
                            linear fits 
       slopedt  [INPUT]  temperature range specified in Log(T[K]) within which
                         to make linear fits to DEM 
                             * if 2-element array, then SLOPEDT =
                               [min(SLOPEDT),max(SLOPEDT)] 
                             * if 1-element array, then SLOPEDT = 
                               [SLOPEDT, logt(max(bestdem)))] or 
                               [SLOPEDT, logt(min(bestdem))]
                               if logt(max(bestdem)) eq SLOPEDT 
                             * if not set, then SLOPEDT = [min(logt),
                               logt(max(bestdem))] or [SLOPEDT,
                               logt(min(bestdem))] if logt(max(bestdem)) eq SLOPEDT
       sampct   [INPUT]  when STORIDX is input, set this to threshold for T
                         bin to be included. Expressed as percent of nsim. (default = 10) 
       goodt    [OUPUT]  if STORIDX is input, GOODT will containt the log T
                         range used to plot 
       tbuff    [INPUT]  if STORIDX is set, TBUFF can be set to the number of
                         bins to add on either side of the temperature range 
                         determined with STORIDX
       monochrom[INPUT] set this to a value between 0 and 255 to make 
                        all the plots in this color. 
restrictions
       The SPLINE and SPLINE INDEX plotting schemes may not be used with slect = 3
       NOT tested yet with positional parameters e.g. !P.POSITION

subroutines 
       mid2bound
       peasecolr
       stample
history
    
    (LL 6/03) 
    ADDED 'Nice' and 'Nice Difference' option for schme parameter (LL 2/04)
    ADDED call to STAMPLE (LL 2/04)
    ADDED call to PEASECOLR to restore settings after loadct (LL 2/04)
    ADDED recognition of weather plot background is black or white
          and and adjustment to col_shft accordingly (LL 2/04) 
    FIXED SPLINE INDEX schme so that it actually polyfills and doesn't just
          oplot i.e. no more 'speckled' look. Also added a NOERASE
          plot statement to prevent polyfills from hiding tickmarks (LL 2/04) 
    FIXED color schemes so that the background color recognition
          scheme would work with both psuedo color and true color (LL 2/04)
    REMOVED PEASECOLR because IDL dynamically updates the x windows
          display whith the current color table (LL 2/04) 
    BUGFIX variables CUPBND and CLOBND should be of size nT not nkpt (LL 3/04)
          if this affected you the routine would have crashed. 
    ADDED 'NICE INDEX' scheme. (LL 10/04) 
    CHANGED 'PROB' color schme so best-fit is plotted brightest for
        'x' and darkest for 'ps', order in which bars plotted matters! (LL 9/05)
    BUGFIX now compatible with multiple plots per page via !p.multi (LL 10/05)
    ADDED 'SUPPORT' scheme and keywords MONOCHROM and OUTMED (LL 11/05) 
    CHANGED col_tabl behavior, only loads col_tabl when set, so default is 
           now whatever is currently loaded and not B/W Linear (LL 11/05)
    ADDED keywords DEMSLOPE, SLOPSIG, SLOPEDT and parameter STORIDX (LL 1/06)
    CHANGED behavior of output to be not in color if COL_TABL is 0 (VK 8/07)

(See /data/fubar/SCAR/pro/mcmc_plot.pro)


MCMC_STEP

[Previous Routine] [Next Routine] [List of Routines]
function	mcmc_step
	returns an updated set of parameters in Markov-Chain Monte Carlo step

syntax
	newpar=mcmc_step(x,y,par,sigpar,sigy=sigy,funcs=funcs,fnprob=fnprob,$
	nbatch=nbatch,rngpar=rngpar,thaw=thaw,/singly,sampar=sampar,$
	sclpar=sclpar,seed=seed,testtyp=testtyp,ties=ties,$
	FUNCS;	type=type,/fwhm,/norm,betap=betap,vrot=vrot,angle=angle,$
		phase=phase,group=group,delp=delp,missing=missing,$
	FNPROB;	ulim=ulim,/chi2,/binom,/cash,/castor)

parameters
	x	[INPUT; required] data points
	y	[INPUT; required] Y(X)
		* sizes of X and Y _must_ match
	par	[INPUT; required] parameters of the model to fit to Y(X)
		* parameters should be 1-D array
		* if 2-D, the size of the 2nd dimension describes the
		  number of chains that are concurrently running
	sigpar	[INPUT; required] this is used to determine how to get
		a new set of parameters with PAR as the starting point
		* if size is identical to the first dimension of PAR, then
		  +ve ==> assumed to be the stddev of Gaussian centered on PAR
		  -ve ==> abs value assumed to be maximum deviation from PAR

keywords
	sigy	[INPUT] error on Y
		* by default, assumed to be Gehrel's approximation,
		  1+sqrt(abs(Y)+0.75)
		* if single element, assumed to be
		  -- fractional error on Y if +ve
		  -- abs value is absolute error if -ve
		* if size does not match Y, default is used
	funcs	[INPUT] name of user defined function (actually a procedure,
		but this name is used for compatibility with IDL's curvefit)
		that takes as input X and A (the model parameters), and
		returns Y(X;A) (the model)
		* should be callable from the command line independently as
		  FUNCS, X, PAR, YMODEL
		* default is set to X3MODEL, which accepts keywords
		  TYPE=TYPE,/FWHM,/NORM,BETAP=BETAP,VROT=VROT,ANGLE=ANGLE,$
		  PHASE=PHASE,GROUP=GROUP,DELP=DELP,MISSING=MISSING
	fnprob	[INPUT] name of user defined function that computes the
		probability of model parameters
		* must be a function that takes as input parameters
		  data,model,errors and return probability, as follows:
		  PROB = FNPROB( Y, MODEL, SIGY )
		* default is LIKELI(), which accepts keywords
		  ULIM=ULIM,/CHI2,/BINOM,/CASH,/CASTOR
		* note: if using /CHI2, remember to also set TESTTYP='CHILRT'
	nbatch	[INPUT; default=10] the number of new parameter sets to try 
		before exiting the program.  only the last set is returned
		as output and the rest are discarded.
	rngpar	[INPUT] the allowed range for each parameter as a 2-D
		array of size (N(PAR),2)
		* overrides output of SIGPAR
		* if 1-D array, range assumed to be symmetrical
		  -- additive if +ve
		  -- abs value multiplicative if -ve
		* ignored if size doesn't match
		* WARNING: RNGPAR[.,0] must be less than RNGPAR[.,1]
		  in the interests of speed, this is _not_ checked for
	thaw	[INPUT] array indicating which parameters are frozen (0) and
		which are thawed (1)
		* size _must_ match number of parameters, else all
		  parameters are assumed thawed
		* overrides SIGPAR and RNGPAR
	singly	[INPUT] if set, does the Metropolis-Hastings check
		for each parameter individually, before going on to
		the next parameter
	sampar	[INPUT] used to determine how to pick the parameters
		to vary within the program:
		-- if not set, then parameters are picked in sequence
		-- if set to scalar, then parameters are picked randomly
		-- if set to array of same size as PAR, assumed to be
		   a sampling distribution for the parameters
	sclpar	[INPUT] a flag that describes how PAR should be scaled
		prior to taking a deviate
		1 == alog(PAR) scaling ;	-1 == exp(PAR) scaling
		10 == alog10(PAR) scaling ;	-10 == 10^PAR scaling
		100 == LOGIT() scaling ;	-100 == UNLOGIT() scaling
		2 == sqrt(PAR) scaling ;	-2 == PAR^2 scaling
		0, or other == no scaling
		* NOTE: no checks are made to ensure that values are
		  defined post-transformation -- it is the responsibility
		  of the user to ensure that the scaling makes sense
		* if scalar, the same scaling is applied to all the parameters
		* if vector, size must match the number of parameters, or
		  else this is ignored
	seed	[I/O] seed for random number generator
	_extra	[INPUT ONLY] pass defined keywords to subroutines:
		testtyp	[MCMCM]
		ties	[ADJUSTIE]
		*	[FUNCS]
		*	[FNPROB]

restrictions
	requires user-defined procedure FUNCS and function FNPROB()
	(see keyword descriptions above)

subroutines
	ADJUSTIE
	LOGIT()
	MCMCM()
	UNLOGIT()
	-FUNCS-
	-FNPROB()-

history
	vinay kashyap (Jun2005)

(See /data/fubar/SCAR/pro/stat/mcmc_step.pro)


MC_EROR

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

          simple procedure that calculates confidence bounds 
          about a given parameter value g given a certain number 
          of monte carlo simulations contained in array sims. 
          assumes the simulations are distributed normally about 
          the 'candidate' parameters.

          by default,set to find smallest possible bounds. can also
          be set to find confidence bounds by counting  upward 
          and downwards by required fraction.        

syntax
           mc_eror, g, sims, erru, errl, confidence=confidence 

parameters

         g     [input, required] parameter about which to estimate bounds
         sims  [input, required] array of monte carlo simulated g's 
                                 minimum 10 simulations [though this 
                                 seems a ridiculous number]
         bndu  [output]          upper confidence bound
         bndl  [output]          lower confidence bound 
 
keywords 
 
         confidence [default = 0.68269] confidence limit at which bounds
                                    are desired. 
         alas                    find confidence bounds by counting  upward 
                                 and downwards by required
                                 fraction. may also be set 
                                 to find smallest possible bounds.               

history 
         LL Jan03  

(See /data/fubar/SCAR/pro/mc_eror.pro)


MERGE_LINE

[Previous Routine] [Next Routine] [List of Routines]
procedure	merge_line
	merges the spectral line information available in RD_LINE
	readable format in two directories

	there is no problem if none of the lines are common to the
	two databases; the databases are simply concatenated.  if
	there are common lines, then the following rules apply to
	I. recognizing that two spectral lines are identical
	*  first of all, the atomic number and ionic state of the 
	   two lines in question must be identical.  if they are, and
	   o if the wavelengths of the two lines are identical within a
	     user specified precision then they are considered "strong"
	     candidates for a match;
	   o if the lines differ by greater than the stated precision, but
	     "not by much" (controlled by another user specified keyword),
	     the lines are "weak" candidates for a match.
	*  the temperature response of the candidate lines, in particular
	   the temperatures of maximum response and the intensity of a line
	   summed over all temperatures are then compared.
	   o if the temperature maxima are within a user specified fraction
	     of each other AND the intensities summed over all temperature
	     bins are within a factor 4,
	     x "strong" candidates are accepted as identical
	     x "weak" candidates are "provisionally" accepted as identical
	   o if the temperature maxima are beyond the specified fraction AND
	     the summed intensities are beyond a factor 4,
	     x "strong" candidates are "provisionally" accepted as identical
	     x "weak" candidates are considered distinct lines
	*  for "provisionally" accepted matches, all the relevant data
	   are displayed and the user is given a choice of accepting or
	   rejecting the match.  the default action is to reject the
	   match unless the total line intensities summed over temperature
	   (where both profiles lie above a threshold=1e-10*max) are within
	   a user specified fraction.
	II. what to do with a matched set of spectral lines
	*  the final database should not contain duplicates, so the
	   information from one of the matched lines must be discarded.
	   this is done arbitrarily by assuming that the first directory
	   named in the parameter list contains the better information.
	*  it may turn out that many lines from DIR2 match many lines
	   from DIR1.  in that case, only the first of the best candidates
	   are accepted.

syntax
	merge_line,dir1,dir2,outdir,atom=atom,logP=logP,n_e=n_e,$
	prec=prec,doubt=doubt,tdex=tdex,frat=frat,mish=mish,mash=mash,$
	omatch=omatch,/batch,wrange=wrange,/allah

restrictions
	* assumes that the temperature gridding of the two datasets are
	  identical, and does *no corrections* (quits on inconsistency)
	* requires subroutines
	  -- KILROY
	  -- RD_LINE [SYMB2ZION [LAT2ARAB]]
	  -- CREATE_STRUCT

side-effects
	* if plotting device is X, then displays the temperature profile
	  of all lines that are "weak" candidates.
	* if OUTDIR is set, writes (possibly large) files to disk.

parameters
	dir1	[INPUT; required] directory which contains the database files
	dir2	[INPUT; required] directory which contains the database files
	outdir	[INPUT] output directory to hold merged files -- if not
		specified, will not write anything to disk.

keywords
	atom	[INPUT; default: ALL] confine attention to specified atom
		* passed w/o comment to RD_LINE
		* from a practical viewpoint, always set this keyword!
	logP	[INPUT; default: 15] log10(Pressure [cm^-3 K])
	n_e	[INPUT] electron density [cm^-3].  if set,
		* overrides LOGP
		* appends a "D" to DIR1, DIR2, and OUTDIR
	prec	[INPUT; default: 0.01] expected precision of the database
		wavelength information; lines whose wavelengths lie within
		PREC of each other are considered identical if they pass
		all the other tests.
	doubt	[INPUT; default: 1] room for doubt; creates a fuzzy
		boundary for PREC -- any lines with wavelengths that
		differ by > PREC but < (1+DOUBT)*PREC are also considered
		identical (if they pass other tests)
	tdex	[INPUT; default: 0.5] same as PREC, but for the temperatures
		of maximum response.
	frat	[INPUT; default: 3] fraction within which the summed
		intensities of candidate lines must be for "tendency to
		accept as match" (see description above)
	batch	[INPUT] if set, all default actions are performed w/o
		user input -- i.e., runs in batch mode.
	mish	[I/O] index matching DIR1 to DIR2
	mash	[I/O] position indices of extra lines in DIR2
		* MISH and MASH may get OVERWRITTEN during the program
		* if they are properly defined, then the matching
		  algorithm is skipped.
		* they must <<both>> be correctly defined or else they
		  are ignored (and worse, overwritten!)
		* use them to avoid redoing the matching (especially all
		  those "weak" candidates -- see below)
		* the quality of the match is uniformly set to 1 ("weak")
		  unless OMATCH is correctly defined at input, in which
		  case OMATCH.Q is left as is.
		* don't even <<think>> of trying to define these arrays
		  from scratch.  to use, first do
		  IDL> merge_line,dir1,dir2,mish=mish,mash=mash,logp=lp1 ...
		  at which time they get initialized, and may be used
		  over and over,
		  IDL> merge_line,dir1,dir2,mish=mish,mash=mash,logp=lp2 ...
	omatch	[OUTPUT] structure that contains all the matched wavelengths
		and corresponding fluxes
	_extra	[INPUT] used to pass defined keywords to RD_LINE
		(WRANGE, ALLAH, VERBOSE; no point in setting PRES!)

history
	vinay kashyap (Jan97)
	added keyword N_E (VK; Jun97)
	removed unwanted 'DD's going into RD_LINE (VK; Jul97)

(See /data/fubar/SCAR/pro/merge_line.pro)


MID2BOUND

[Previous Routine] [Next Routine] [List of Routines]
function	mid2bound
	given mid-bin values, make an intelligent determination of
	the bin boundaries and return said boundaries.  given input
	array of N elements, returns array of N+1 elements.

	(actually, it's not all that intelligent.  uses spline interpolation)

syntax
	dm=mid2bound(m,/halfit,eps=eps,verbose=verbose)

parameters
	m	[INPUT; required] the mid-bin values from which to
		expand out

keywords
	halfit	[INPUT] if set, does the simpleminded thing, i.e.,
		puts the bin half-way between 2 points, and extrapolates
		by repeating previous bins
	eps	[INPUT] a small number, default is 1e-6
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to prevent crashing the program

history
	vinay kashyap (OctMM)
	added keyword HALFIT (VK; Jul01)
	default EPS had not been defined (VK; Jan05)

(See /data/fubar/SCAR/pro/misc/mid2bound.pro)


MIXIE

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

      MIXIE() computes correction factors for line blends given a set of
      intersting lines (LSTR) and a set of contaminants (SSTR). 
      LSTR and SSTR should both be RD_LIST() style structures, which 
      contain necessary line information (emissivity, wvl, z, etc.) 
 
      MIXIE()  will identify which lines in SSTR are possible contaminants
      for each line in LSTR.  SSTR lines must meet two criteria to be
      included in the correction fraction computation of each LSTR line: 

      1) The SSTR line lies within 2*NSIG*LWDT on either side of the LSTR line 
      2) The total contribution of the line is  greather than a 
         user-defined threshold: LTHR * INTENSITY OF LINE (LTHR is 
         keyword input while intensity of the interesting line is
         computed internally.)
 
      Correction factors are estimated by computing complimentary 
      error functions with an IDL native routine ERRORF() for each 
      contaminant (i.e. gaussian  profiles are assumed). If an
      OGIP-compliant rmf is fed via the RMFSTR keyword, the rmf 
      will be used to estimate correction factors rather than
      ERRORF() <<RMFSTR NOT IMPLEMENTED YET>>.
      The correction factor is defined as follows: 
 
        CORRECTION FACTOR = INT / (INT + total contributions from blends)
        where INT = intensity of interesting line

      If set, the MIXSTR keyword can return a structure containing the
      identification, emissivities, and wavelengths of each contaminant
      line, together with LSTR and SSTR indices which match contaminated line 
      to contaminant (VICTIM and CULPRIT respectively). Also to be contained in
      the structure are the fractional contributions CONTAMFRAC and intensity of
      of the contaminant CONTAMINT (i.e. the total contribution of the contaminant is
      CONTAMINT*CONTAMFRAC). The fields in the output structure will be the
      the following (see KEYWORDS for individual descriptions):

      {CONTAMFRAC,CONTAMINT,VICTIM,CULPRIT,WVL,IDTAG}

 
syntax 
      x=mixie(lstr,sstr,lwdt=lwdt,nsig=nsig,lthr=lthr,rmfstr=rmfstr,mixstr=mixstr,$
           contamfrac=contamfrac,victim=victim,culprit=culprit,contamint=contamint,$
           idtag=idtag,vint=vint,mproxy=mproxy,mplet=mplet,_extra=e)

parameters
      lstr   [INPUT;required] Line (and/or conitnuum) structure of
                      RD_LIST() format containing info (wvl,emis,z) on 
                      lines (and/or continuum) for which possible contaminants will be identified 
                      and for which correction factors  will be
                      calculated. Assumes that ion equilibria are
                      included. (see RD_LIST() keyword INCIEQ)
      sstr   [I/O]    Line structure of RD_LIST() format 
                      containing user specified line contaminant suspect
                      info (wvl, emis, z).  Assumes that ion equilibria are
                      included. (see RD_LIST() keyword INCIEQ). If SSTR is
                      ommitted or undefined on input, the emissivity database will
                      read with RD_LIST() in the neccessary wavelength range
                      and including all species to create a list of  suspects.
                      If undefined on input, will contain RD_LIST() structure
                      on output.                
                     
keywords 
      lwdt   [INPUT]  Std. deviation to be used as an estimate for 
                      line broadening. Only contamination candidate profiles (sstr) 
                      within 2*lwdt*nsig of the line in question will
                      be considered. May be single value or an array
                      with values for each element in LSTR. (must
                      match number of lines+continuum specified in LSTR)
                      default = 0.2 pixels
      nsig   [INPUT]  number of standard deviations from line of interest that
                      defines wavelength range within which to consider contamination.
                      If not set, the default is determined by LTHR.  
                      May be single value or an array of values for
                      each element in lstr. If array, must match the
                      number of lines+continuum specified in LSTR.
                      
                      So the range within which to consider
                      contamination for each line is defined as: 

                         WRANGE = [LSTR.WVL(x)-LWDT*NSIG,LSTR.WVL(x)+LWDT*NSIG]                     

                      or if LWDT and NSIG are arrays: 

                         WRANGE = [LSTR.WVL(x)-LWDT(x)*NSIG(x),LSTR.WVL(x)+LWDT(x)*NSIG(x)]
 
                      NOTE: To handle continuum measurements, 
                      choose an NSIG which adequatly covers your
                      continuum measurement wavelength range.        
         
            
      lthr   [INPUT]  fraction of intensity of the line of interest to
                      use as cut-off intensity value for contaminant
                      candidate fractional flux  contributions. default = 1e-4  
                      i.e. cutoff = (intnsity of line of interest)/100
      rmfstr [INPUT]  <<NOT IMPLEMENTED YET>> structure containing OGIP compliant RMF. see
                      RD_OGIP_RMF(). If set, contamination will be
                      estimated by analyzing RMF instead of using ERRORF()
      mixstr [OUTPUT] Structure containing detailed information for
                      each pair of blends. The structure fields are
                      the following: 

                      {CONTAMFRAC,CONTAMINT,VINT,VICTIM,CULPRIT,WVL,IDTAG}

                      Each field can also be returned individually:

      contamfrac [OUTPUT] array containting contribution fractions for
                      each culpable line
      contamint [OUTPUT] the contaminant line intensities         
      vint [OUTPUT] the victim line intensities 
      victim [OUTPUT] lstr index of intersting line being contaminated 
      culprit[OUTPUT] sstr index of indices of contaminant lines
      idtag  [OUTPUT] string containing derscription of each culprit.
                      the description is as follows:

                      SPECIES, WVL, DATABASE, DESCRIPTION
                      
                      SPECIES gives atomic symbol and ionic
                      state. WVL gives Wavelength. DATABASE gives 
                      the name of the DATABASE used. And DESCRIPTION 
                      gives the level designations and electron
                      configurations of the transition. e.g.
 
                      MgXII 8.41920 $CHIANTI (1s) 2S_1/2 (2p) 2P_3/2 
                      OVIII 18.9726 $CHIANTI (1s) 2S_1/2 (2p) 2P_1/2 

      vidtag [OUPUT]  string containing description of each victim
                      and of same format as idtag 
      mproxy [INPUT] If a correction factor is needed for  a
                       multiplet measured using a single profile,
                       then MPROXY will specify the
                       multiplet components on input, and contain
                       the multiplet correction factor on output.
 
                       One component of the multiplet is to stand
                       proxy for the group, and must be specified in 
                       LSTR. 
                       
                         MPROXY is defined  as follows: 
                     
                         mproxy = strarr(2,N) or 
                         mproxy = intarr(2,N)
                      
                         N is the number of component-proxy
                         relationships. Each component-proxy
                         relationship  is expressed as a two
                         element string array. The first element should
                         contain the LSTR index of the proxy. The
                         second element should contain either the LSTR index of the
                         component if it is included in LSTR, or a
                         string description of the component in IDTAG format. 
                         One may optionally leave out:

                            o the DESCRIPTION field (e.g. just use SPECIES, WVL,DATABASE). 
                            o the DATABASE and WVL fields (e.g. just use
                              SPECIES, DATABASE)
 
                       On output, one correction factor will be given 
                       for each multiplet. The index of this
                       correction factor in the output correction
                       factor array is determined by the position of
                       the proxy in LSTR. (See examples below)
                                                 
      mplet  [INPUT] If blending between one or
                       more multiplet components is already accounted
                       for (e.g. a multiplet is modelled with
                       serveral profiles)  then MPLET can
                       specify which multiplet component to leave 
                       out of the correction factor calculation of 
                       another component. 
 
                         MPLET is defined as follows: 
 
                         mplet = strarr(2,N)
                         mplet = intarr(2,N)
          
                         N is the number of component-component 
                         relationships. Each component-component 
                         relationship is expressed as a two element 
                         string array. The first element should
                         contain  the LSTR index of the component 
                         whose correction factor is needed. 
                         The second element should contain either the
                         LSTR index of the component to leave out, or
                         a string description of the component to
                         leave out in IDTAG format. 
                         One may optionally leave out:

                            o the DESCRIPTION field (e.g. just use SPECIES, WVL,DATABASE). 
                            o the DATABASE or WVL fields (e.g. just use
                              SPECIES, DATABASE)

                      Correction factors will not be calculated for 
                      lines specified to be left out of another
                      lines' correction factor calculation. See
                      examples below.
      brnstr [I/O]    if mixie is to be run multiple times
                      (e.g. using MCMC_DEM() ) the brnstr keyword can 
                      be set so that MIXIE() creates a sturcture
                      containing internally calculated and recycle-able information, to be fed
                      to subsequent MIXIE() calls. The structure is
                      of the form: 

                      {FRACS,NDX,INTNDX,NSS,NNSS,PRXBSE,MULTSTR} 

                      where: 

                      FRACS   = float array contribution fractions of all non-exempt lines
                      NDX     = long array  sstr index of each of thes lines 
                      INTNDX  = float array ndx and fracs index intervals corresponding to each victim
                      NSS     = float array lstr index of each victim  
                      NNSS    = long array  number of actual victims i.e. n_elements(nss) 
                      PRXBSE  = long array  lstr index of the proxy in each proxy relation. 
                      MULTSTR = STRUCT      rd_line structure of proxee in each relation 

                      When fed as input, BRNSTR allows MIXIE to avoid
                      explicit contribution factor calculations for
                      each suspect and cumbersome MPROXY and
                      MPLET sting parsing. 
      DEM    [INPUT]  differential emission measure  at each T [cm^-5/logK]
                      * default is a constant=1e14!!
                      * if defined, DLOGT must also be specified
                      * if LSTR and SSTR emissivity temperature grids do not
                        match  DLOGT then they are rebinned and
                        resampled so that they do 
      DLOGT  [INPUT   logarithmic temperature grid at which DEM is defined
                      * default is 4.0 to 8.0 in steps of 0.05
      ABUND  [I/O]  abudnanaces relative to H abund(0) = 1
      	               * abund(Z-1) contains the abundance for element Z
                      * default: Grevesse & Sauval(1998)
      ABNDUPDT [INPUT] If set, then abundnaces will be updated on
                      output. Abundances are calculated after taking 
                      into account the correction factors 
      OBSFLX [INPUT]  Obseved fluxes used to calculate abundnaces,
                      must match the number of correction factors
                      calculated                         
      OFSIG  [INPUT]  errors for OBSFLX
      MULTIPLET [INPUT] temporary, same as MPLET
      MULTPLET [INPUT]  temporary, same as MPLET 
      MULTPROXY [INPUT] temporary, same as MPROXY
      MULTIPROXY[INPUT] temporary, same as MPROXY
      verbose[INPUT]  set verbosity 
      _extra [INPUT]  pass defined keywords to
	               LINEFLX (DEM, ABUND, EFFAR, WVLAR, TEMP, NOPH, IKEV, REGRID)
                      RD_LIST (DBDIR,LOGP,PRES,N_E,EQFILE)
      
subroutines
      LINEFLX
      RD_LIST
      INICON
      CAT_LN
      REBINX
      MCMC_ABUND
      MCMC_EROR 
      IS_KEYWORD_SET

restrictoins
      Is is suggested that LSTR and SSTR be read from a common
      database to avoid accidentally identifying a line as 'self blending' 
      MIXIE() will NOT compute correct correction factors for DR lines. 

usage examples

      * !LDBDIR = '$CHIANTI'
        Ne9   = rd_list('Ne9|[13.44,13.45]',/incieq,sep='|')
        cand  = rd_list('ALL|[12.44,15.45]',/incieq,sep='|')
        factor = mixie(Ne9,Cand,lwdt=0.008,nsig=5,lthr=0.02,contamfrac=contamfrac,victim=victim,$
                      culprit=culprit,contamint=contamint,idtag=idtag, mixst=mixstr)
        for j = 0,n_elements(culprit)-1 do print,mixstr.idtag(j), mixstr.contamint(j)* mixstr.contamfrac(j)

      * !LDBDIR = '$CHIANTI'
        Ne9    = rd_list('Ne9|[13.44,13.45]',/incieq,sep='|')
        factor = mixie(Ne9,lwdt=0.008,nsig=5,lthr=0.02,contamfrac=contamfrac,victim=victim,$
                 culprit=culprit,contamint=contamint,idtag=idtag, mixst=mixstr)
        for j = 0,n_elements(culprit)-1 do print,mixstr.idtag(j), mixstr.contamint(j)* mixstr.contamfrac(j)

      * !LDBDIR = '$CHIANTI'
        T_components  = [6.6,6.9,7.4]           ; log(T[K]) components in the EM
        EM_components = [3.05,3.05,3.55]*1d11   ; Emission Measure [cm^-3]
        !DEM=mk_dem('delta', logT = !LOGT, pardem=T_components, indem=EM_components)
        Ne9   = rd_list('Ne9|[13.44,13.45]',/incieq,sep='|')
        factor = mixie(Ne9,lwdt=0.008,nsig=5,lthr=0.02,contamfrac=contamfrac,victim=victim,$
                      culprit=culprit,contamint=contamint,idtag=idtag, mixst=mixstr,DEM=!DEM, DLOGT=!LOGT)
        for j = 0,n_elements(culprit)-1 do print,mixstr.idtag(j),mixstr.contamint(j)* mixstr.contamfrac(j)
 
      * !LDBDIR = '$CHIANTI' 
        N7  = rd_list('N7|[24.77,24.79]',/incieq,sep='|'); this list specifies a triplet
        mproxy = [ [2,1], [2,0] ]  ; We use one triplet component as proxy       
        factor = mixie(N7,lwdt=0.008,nsig=5,lthr=0.008,contamfrac=contamfrac,victim=victim,$
                 culprit=culprit,contamint=contamint,idtag=idtag,mproxy=mproxy,$
                 mixstr=mixstr)

      * !LDBDIR = '$CHIANTI' 
        N7 = rd_list('N7|[24.7846,24.7847]',/incieq,sep='|'); this list contains one N7 triplet component 
        ; use MPROXY to specify N7 triplet components the one component are to stand proxy for
        mproxy = [['0','NVII 24.7793 $CHIANTI (1s) 2S_1/2 (2p) 2P_3/2'], $ 
                  ['0','NVII 24.7844 $CHIANTI (1s) 2S_1/2 (2s) 2S_1/2']]  
        factor = mixie(N7,njk,lwdt=0.008,nsig=5,lthr=0.008,contamfrac=contamfrac,victim=victim,$
                       culprit=culprit,contamint=contamint,idtag=idtag,$
                       mixst=mixstr,mproxy=mproxy )

      * !LDBDIR = '$CHIANTI' 
        N7 = rd_list('NVII|24.7847|$CHIANTI|(1s) 2S_1/2 (2p) 2P_1/2',sep='|',/incieq)
        ; use MPROXY to specify multiplet components the N7 at 24.7847 is to stand proxy for
        mproxy = [['0','NVII 24.7793 $CHIANTI (1s) 2S_1/2 (2p) 2P_3/2'], $ 
                  ['0','NVII 24.7844 $CHIANTI (1s) 2S_1/2 (2s) 2S_1/2']]  
        factor = mixie(N7,j,lwdt=0.008,nsig=5,lthr=0.008,contamfrac=contamfrac,victim=victim,$
                       culprit=culprit,contamint=contamint,idtag=idtag,$
                       mixst=mixstr,mproxy=mproxy)
                 
history
                INTENDED as an improvement on bland() (LL:Jul'03)
                NEW documentation new default nsig 
                  output now correction factor and not mixstr (LL:Aug'03)
                BUG FIX: 1/SQRT(2) factor needed for arguement of ERRORF so
                  lwdt is actually standard deviation
                now prints message when no blends are found
                now robust to theoretical lines (designated by
                negative wavelengths)                      
                BUG FIX correction factor calculations for multiple
                victim list was incorrect (LL/DG:Sep'03) 
                ADDED keyword COMPOSITE to handle doublets (LL:Sep'03) 
                REPLACED keyword COMPOSITE with MUTLPROXY which now handles
                  multiplets. ADDED related keyword MULTIPLET. (LL:Oct'03)
                ADDED correction for 'over correction' i.e. a CULPRIT now
                  cannot 'overdistribute' its flux when contaminating
                  several VICTIMS at once. (LL:Oct'03)  
                CHANGED LTHR and NSIG so that they can handle arrays
                  so correction factors for continuum measurements
                  are possible (LL:Oct'03) 
                CHANGED default RD_LIST() call so that makes
                  intelligent efficient wrange decision (LL:Oct'03) 
                ADDED BRNSTR keyword so that doesn't bog down
                  MCMC_DEM(). ALSO included explicit intensity
                  calculations so to avoid being slowed by LINEFLX(). (LL:Oct'03) 
                ADD ABNDUPDT keyword to toggle ABUND updating on
                  output (LL:Jan'04) 
                CHANGED location of ABUNDANCE calculation so that it
                  abundances get updated after contamination
                  correction. ADDED keyword OFSIG (LL:Jan'04) 
                CHANGED MULTIPLET KEYWORD to MPLET and MULTPROXY to
                  MPROXY (LL/DG:Jan'04) 
		 changed default of LTHR to 1e-4 (VK;Jan'04)
                ADDED new MPLET and MPROXY format (LL:Feb'04) 
                BUG FIX over correction mechanism (i.e. considering
                  situations of one culprit and two victims) was not
                  working properly, leading to correction factors >
                  1. (LL/DG:Feb'04) 
                BUG FIX total(contamfrac) gt 1 changed to
                  n_elements(culprit) gt 1  (LL:Feb'04) 
                BUG FIX keywords idtag and mixstr were failing 
                  because need to handle with keyword_set()  not
                  arg_present() (LL:Mar'04) 
                VARIOUS BUG FIXES 
                  sstr enteed as dummy argument = crash 
                  mixstr and idtag fix (LL:Mar'05)  
		 replaced direct reference to !LOGT with calls to
		   defsysv and setsysval (VK; Apr'05)
                BUG FIX if sstr is one component only it was 
                  ignored. (LL:Apr'05) 
	updated for IDL5.6 keyword_set([0]) behavior change for vectors
	  (VK; 20Mar2006)

(See /data/fubar/SCAR/pro/mixie.pro)


MKACISGARF

[Previous Routine] [Next Routine] [List of Routines]
function	mkacisgarf
	returns effective area as a function of wavelength for specified
	CXC grating and order on the ACIS-S

syntax
	arf=mkacisgarf(offset,wgrid,order=order,arm=arm,caldb=caldb,$
	hrmaea=hrmaea,acisqe=acisqe,greff=greff,contam=contam,$
	tstart=tstart,verbose=verbose)

parameters
	offset	[INPUT; required] offset of source position from the
		nominal aim point on S3 [arcmin]
		* +ve is towards the center of S3
		* someday, after I figure out how to do it, I'll change
		  the required inputs to (SRC_X,SRC_Y), and possibly ROLL.
		  meanwhile, this parameter goes straight to ACISS_GAPS.
	wgrid	[OUTPUT] wavelengths at which effective area is computed

keywords
	order	[INPUT] diffraction order.  if not set, assumes +ve 1st order.
	arm	[INPUT] string specifying which grating arm to be used.
		* 'MEG', 'HEG', or 'LEG', in decreasing precedence
		* if illegal or undecipherable, NONE is assumed
		* Note that MEG intercepts rays from the two outer HRMA shells
		  (1 and 3, denoted 1100) and the HEG intercepts rays from the
		  two inner shells (4 and 6, denoted 0011)
	caldb	[INPUT] root $CALDB directory
		* default: /soft/ciao/CALDB/
		* assumes that the following tree exists:
		- CALDBhrma=CALDB/data/chandra/default
		- CALDBacis=CALDB/data/chandra/acis/
		- CALDBhetg=CALDB/data/chandra/default/greff/
		- CALDBletg=CALDB/data/chandra/default/greff/
	hrmaea	[INPUT] full path name of file containing HRMA effective areas
		* must be a FITS file with extensions AXAF_EFFEA1..5, one
		  for each mirror shell (viz. header keyword SHELL), and
		  each extension having the columns
		  	ENERG_LO,ENERG_HI,EFFAREA
		* if not specified, assumed to be
			CALDBhrma/effarea/hrmaD1996-12-20axeffaN0008.fits
	acisqe	[INPUT] full path name of file containing ACIS QEs
		* must be a FITS file with an extension for each chip
		  (AXAF_QE1..10), and each extension having columns
		  	ENERGY,QE
		  (latter assumed to be product of detector QE and
		  optical blocking filter)
		* if not specified, assumed to be
			CALDBacis/qe/acisD1997-04-17qeN0006.fits
	greff	[INPUT] full path name of file containing grating efficiencies
		* must be a FITS file with an extension (AXAF_GREFF1..4),
		  for each mirror shell (viz., header keyword SHELL), and
		  each extension having the columns
		  	ENERGY, EFF[--..-1,0,+1,..++]
		* if not specified, assumed to be
		  ARM='LEG':	CALDBletg/letgD1996-11-01greffpr001N0005.fits
		  else: 	CALDBhetg/hetgD1996-11-01greffpr001N0006.fits
	contam	[INPUT] full path name of file containing ACIS contamination
		coefficients
		* must be FITS file with 3 extensions, one each for C-K, O-K, and F-K
		  edges, with columns
		  	FEATURE,N_ENERGY,ENERGY,ALPHA,N_TIME,TIME,BETA
		* if not specified, assumed to be
		  	CALDBacis/contam/acisD1997-04-17contamN0006.fits
		* NOTE: this file does not exist in caldb yet, so for the
		  nonce, the CONTAM file is ignored unless explicitly specified
		* NOTE: the contamination is a multiplicative factor to the ARF,
		  exp(SUM{-alpha(E)*beta}), where beta is a time dependent factor
	tstart	[INPUT] the time of observation to be used to determine BETA for
		contamination corrections, in units of spacecraft time in [s]
		since launch.
		* if not specified, the latest time encoded in CONTAM is assumed
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to prevent crashing the program

restrictions
	does not handle the 0th order
	does not handle ACIS-I CCDs being used as the spectroscopic array

subroutines
	ACISS_GAPS

history
	modified from ACISGARF (VK; MMIVjan)
	updated default files (VK; MMVIIsep)

(See /data/fubar/SCAR/pro/specific/mkacisgarf.pro)


MKHRCIARF

[Previous Routine] [Next Routine] [List of Routines]
function	mkhrciarf
	returns effective area as a function of wavelength for specified
	CXC grating and order on the HRC-I

syntax
	arf=mkhrciarf(wgrid,order=order,arm=arm,caldb=caldb,$
	hrmaea=hrmaea,qefil=qefil,greff=greff,verbose=verbose)

parameters
	wgrid	[OUTPUT] wavelengths at which effective area is computed

keywords
	order	[INPUT] diffraction order.  if not set, assumes +ve 1st order.
	arm	[INPUT] string specifying which grating arm to be used.
		* 'NONE', 'MEG', 'HEG', or 'LEG', in decreasing precedence
		* if illegal or undecipherable, NONE is assumed
		* Note that MEG intercepts rays from the two outer HRMA shells
		  (1 and 3, denoted 1100) and the HEG intercepts rays from the
		  two inner shells (4 and 6, denoted 0011)
	caldb	[INPUT] root $CALDB directory
		* default: /soft/ciao/CALDB/
		* assumes that the following tree exists:
		- CALDBhrma=CALDB/data/chandra/default/
		- CALDBhrc=CALDB/data/chandra/hrc/
		- CALDBhetg=CALDB/data/chandra/default/greff/
		- CALDBletg=CALDB/data/chandra/default/greff/
	hrmaea	[INPUT] full path name of file containing HRMA effective areas
		* must be a FITS file with extensions AXAF_EFFEA1..5, one
		  for each mirror shell (viz. header keyword SHELL), and
		  each extension having the columns
		  	ENERG_LO,ENERG_HI,EFFAREA
		* if not specified, assumed to be
			CALDBhrma/axeffa/hrmaD1996-12-20axeffaN0008.fits
	qefil	[INPUT] full path name of file containing HRC-I QEs
		* must be a FITS file with an extension for each chip
		  (AXAF_QE1..4; but currently only AXAF_QE1), and each
		  extension having columns ENERGY,QE
		  (latter assumed to be product of detector QE and
		  optical blocking filter)
		* if not specified, assumed to be
			CALDBhrc/qe/hrciD1999-07-22qeN0007.fits
	greff	[INPUT] full path name of file containing grating efficiencies
		* must be a FITS file with an extension (AXAF_GREFF1..4),
		  for each mirror shell (viz., header keyword SHELL), and
		  each extension having the columns
		  	ENERGY, EFF[--..-1,0,+1,..++]
		* if not specified, assumed to be
		  ARM='NONE':	ignored
		  ARM='LEG':	CALDBletg/letgD1996-11-01greffpr001N0005.fits
		  else: 	CALDBhetg/hetgD1996-11-01greffpr001N0006.fits
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to prevent crashing the program

restrictions

history
	modified from MKACISGARF (VK; MMVjan)
	brought defaults up to date (VK; MMIXnov)

(See /data/fubar/SCAR/pro/specific/mkhrciarf.pro)


MK_3MODEL

[Previous Routine] [Next Routine] [List of Routines]
function	mk_3model
	generate and return a compound model using the supplied
	parameters of components made up of 3-parameter functions

syntax
	model=mk_3model(x,p,w,h,pder,group=group,delp=delp,type=type,/asis,$
	/allcomp,/fwhm,/normflx,missing=missing,betap=betap,vrot=vrot)

parameters
	x	[INPUT; required] points where model is computed
	p	[INPUT; required] positions of components
	w	[INPUT; required] widths of components
	h	[INPUT; required] heights of components
	pder	[OUTPUT] contains 2D array (NX,3*NPAR) of partial derivatives
		of each component wrt parameters

keywords
	group	[INPUT] grouping index of gaussians
	delp	[INPUT] offsets from first position value in group
		NOTE: GROUP and DELP are ignored if ASIS is set
		NOTE: if GROUP and DELP are not given, ASIS is set
	type	[INPUT; default='G*aussian'] what type of curve to generate
		for the model.  other possibilities are
			L*orentzian
			B*eta-profile (set "Beta=<value>")
			SL*ant (set "slant=<angle>,<beta>")
			R*otation-convolved Gaussian (set "rot=<velocity>")
			P*ower-law (set "pw=<break>" or "pe=<break>")
			I*dentity
			U*ser_defined (not yet implemented), etc.
			SI*nusoid (set "sin=<phase>")
		* if not defined, uses "Gauss"
		* if insufficiently defined, uses last defined as default
		  for the rest
	asis	[INPUT] the default action is to verify that the p are
		consistent with GROUP and DELP and to correct as necessary.
		if ASIS is set, this is not done.
	allcomp	[INPUT] if set, returns the sum of components and also each
		component in a separate column of a 2D array of size
		(N_ELEMENTS(P)+1,N_ELEMENTS(X))
	_extra	[INPUT] pass defined variables to subroutine:-
		MK_GAUSS: MISSING, FWHM, NORMFLX
		MK_LORENTZ: BETAP, MISSING, NORMFLX
		MK_SLANT: ANGLE, BETAP, MISSING, NORMFLX
		MK_ROGAUSS: VROT, MISSING, FWHM, NORMFLX
		MK_IDENT: GIGO
		MK_SINUSOID: PHASE, MISSING

usage summary
	* call as a function
	* returns composite model by adding up components
	* input component parameters as sequence of arrays of
	  positions, widths, and heights
	* input grouping info by 2 additional arrays
	* specify type of model with keyword TYPE
	* partial derivatives are computed only if ALL 5 parameters are
	  supplied in call
	* example TYPEs:
	  'Gauss', 'gaussian', 'gau', 'g'
	  'Lorentz', 'lorentz', 'lorentzian', 'lor', 'l'
	  'beta=1.8', 'BETA=2.4', 'B=2', 'b 1.8', 'b:1.8', 'b	1.8'
	  'slant=45,1.8','SLANT=89,2.4', 's=10','s=,2', 's:3,2'
	  'rotational velocity=1e-4', 'rot=30', 'r:30e5', 'R 1e-4'
	  'pe=1', 'pw=12.3985', 'pw@12.4'
	  'sin', 'sin=90'
			
subroutines
	MK_GAUSS
	MK_LORENTZ
	MK_SLANT
	MK_ROGAUSS
	MK_POWLAM
	MK_SINUSOID
	KILROY

history
	vinay kashyap (Oct96)
	added parameter to return partial derivatives (VK; Nov96)
	added _EXTRA, added call to MK_LORENTZ (VK; Oct98)
	allowed setting BETAP for MK_LORENTZ via TYPE definition (VK; Dec98)
	added MK_SLANT calls (VK; MarMM)
	added MK_ROGAUSS, MK_POWLAM calls (VK; JunMM)
	changed name from MK_MODEL to MK_3MODEL (VK; Aug01)
	converted array notation to IDL 5; added MK_IDENT (VK; Apr02)
	changed keyword NORM to NORMFLX (VK; Oct02)
	added call to MK_SINUSOID (VK; Sep04)

(See /data/fubar/SCAR/pro/mk_3model.pro)


MK_ABSORB

[Previous Routine] [Next Routine] [List of Routines]
function	mk_absorb
	returns a multiplicative transmission factor for ISM absorption

syntax
	ismcorr=mk_absorb(x,NH,pder, fH2=fH2,He1=He1,HeII=HeII,/Fano,/ikev,$
	/wam,/bam,/mam,/noHeH,abund=abund,verbose=verbose)

parameters
	x	[INPUT array; required] where the function must be computed
	NH	[INPUT; default: 1e18] H column
	pder	[OUTPUT; optional] partial derivatives of model wrt parameter
		at each X; calculated only if 3 parameters are supplied in call.

keywords
	_extra	[INPUT ONLY] pass defined keywords to subroutines
		ISMTAU: FH2, HE1, HEII, FANO, IKEV, WAM, BAM, MAM, NOHEH, ABUND

description
	wrapper to ISMTAU

subroutines
	ISMTAU

history
	vinay kashyap (Jul08)

(See /data/fubar/SCAR/pro/mk_absorb.pro)


MK_BBANG

[Previous Routine] [Next Routine] [List of Routines]
function	mk_bbang
	returns the Planck function B(lam) [ph/s/cm^2/Ang] as a
	function of lam [Ang] at a given temperature T.

	In general,
	B(nu)d(nu) = (R/d)^2*(2*pi/c^2) * d(nu)*nu^2/(exp(h*nu/kT)-1)
	for lam=c/nu,
	B(lam)d(lam) = (R/d)^2 * (2*pi*c) * d(lam) * (1/lam^4)/(exp(hc/lam/k/T)-1)
		== A * (lam^-4/(exp(hc/lam/k/T)-1)) * d(lam)

syntax
	b=mk_bbang(x,norm,temperature,pder,verbose=verbose)

parameters
	x	[INPUT array; required] where B(X) must be computed
	norm	[INPUT; required] normalization for B(X)
	temp	[INPUT; required] temperature in [K]
	pder	[OUTPUT; optional] partial derivatives of model wrt parameters
		at each X; calculated only if 4 parameters are supplied in call.

keywords
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to prevent crashing

usage summary
	* call as a function

subroutines
	NONE

history
	vinay kashyap (Aug08; based loosely on 1993 blackbody.pro)

(See /data/fubar/SCAR/pro/mk_bbang.pro)


MK_BBKEV

[Previous Routine] [Next Routine] [List of Routines]
function	mk_bbkev
	returns the Planck function B(E) [ph/s/cm^2/keV] as a
	function of E [keV] at a given temperature T.

	In general,
	B(nu)d(nu) = (R/d)^2*(2*pi/c^2) * d(nu)*nu^2/(exp(h*nu/kT)-1)
	for E=h*nu,
	B(E)dE	= (R/d)^2 * (2*pi/c^2/h^3) * dE*E^2/(exp(E/kT)-1)
		== A * (E^2/(exp(E/kT)-1)) * dE

syntax
	b=mk_bbkev(x,norm,temp,pder,verbose=verbose)

parameters
	x	[INPUT array; required] where B(X) must be computed
	norm	[INPUT; required] normalization for B(X)
	temp	[INPUT; required] temperature in [K]
	pder	[OUTPUT; optional] partial derivatives of model wrt parameters
		at each X; calculated only if 4 parameters are supplied in call.

keywords
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to prevent crashing

usage summary
	* call as a function

subroutines
	NONE

history
	vinay kashyap (Aug08; based loosely on 1993 blackbody.pro)

(See /data/fubar/SCAR/pro/mk_bbkev.pro)


MK_BKNPOWER

[Previous Routine] [Next Routine] [List of Routines]
function	mk_bknpower
	returns a broken Power-law function,
	  p(X)	= NORM*(X/Xo)^gamma1 {X.le.PBREAK}
		= NORM*(PBREAK/Xo)^(gamma1-gamma2)*(X/Xo)^gamma2 {X.ge.PBREAK}

syntax
	p=mk_bknpower(x,norm,gamma1,gamma2,pbreak,pder,Xo=Xo,/nobreak,verbose=verbose)

parameters
	X	[INPUT; required] where p(X) must be computed
	norm	[INPUT; required] normalization
	gamma1	[INPUT; required] power-law index 1 (valid for 0<X<PBREAK)
	gamma2	[INPUT; necessary] power-law index 2 (valid for X>PBREAK)
	pbreak	[INPUT; necessary] break point
		* GAMMA2 and PBREAK are ignored if NOBREAK is set
	pder	[OUTPUT; optional] partial derivatives of model wrt parameters
		at each X; calculated only if 6 parameters are supplied in call.
		* array of size [N(X),4], with columns containing the partial
		  derivatives wrt NORM, GAMMA1, GAMMA2, and PBREAK respectively
		* to have it return PDER as [N(X),2] for a non-broken power-law
		  distribution, set NOBREAK (must have GAMMA2 and PBREAK in the
		  call, but they will be ignored)

keywords
	Xo	[INPUT] X-value at which which normalization is defined
		* default is 1.0
	nobreak	[INPUT] if set, ignores GAMMA2 and PBREAK, essentially assuming
		that PBREAK=$\infty$
	verbose	[INPUT] controls chatter
	_extra	[JUNK] here only to prevent crashing the program

example
	x=(findgen(100)+1)/10. & p=mk_bknpower(x,1.,-1,-3,1.5) & plot,x,p,/xl,/yl
	p2=mk_bknpower(x,1.,-1,-3,1.5,/nobreak) & oplot,x,p2,line=2,thick=2

history
	Vinay Kashyap (Apr2008)

(See /data/fubar/SCAR/pro/mk_bknpower.pro)


MK_CONT_CIE

[Previous Routine] [Next Routine] [List of Routines]
MK_CONT_CIE.PRO
	IDL program to call WRT_CONT_CIE repeatedly for various densities
	to generate a database of continuum emission

vinay kashyap (Dec97, based on MK_LCOOL_CHIANTI.PRO)

(See /data/fubar/SCAR/pro/scrypt/mk_cont_cie.pro)


MK_CONT_CIE50

[Previous Routine] [Next Routine] [List of Routines]
MK_CONT_CIE50.PRO
	IDL program to call WRT_CONT_CIE repeatedly for various densities
	to generate a database of continuum emission

vinay kashyap (Dec97, based on MK_LCOOL_CHIANTI.PRO)

(See /data/fubar/SCAR/pro/scrypt/mk_cont_cie50.pro)


MK_DEM

[Previous Routine] [Next Routine] [List of Routines]
function	mk_dem
	returns DEM(T) [cm^-5]

syntax
	DEM=mk_dem(type,logT=logT,indem=indem,pardem=pardem,$
	sloop=sloop,xcur=xcur,ycur=ycur,loopy=loopy,lcomp=lcomp,$
	weight=weight,/gauss,verbose=verbose)

description
	this provides a way to generate DEMs quickly by various means.
	TYPE, a string variable, decides what sort of method to use to
	generate the DEM.  TYPE can be
		'help'
		'constant'	PARDEM = value
		'chebyshev'	PARDEM = coefficients
		'cursor'	PARDEM = max range in DEM
		'interpolate'	PARDEM = original logT
		'loop'   	PARDEM = original logT
		'rebin' 	PARDEM = rebinning scales
		'spline'	PARDEM = logT location of points
		'varsmooth'	PARDEM = smoothing scales
		'delta'		PARDEM = logT locations of EM components
	if a particular method requires an input DEM (e.g., 'interpolate'),
	feed that in via the keyword parameter INDEM.
	any parameters that the method requires go in via PARDEM (e.g., for
	'interpolate', PARDEM would be the temperature grid at which INDEM
	is defined).

parameters
	type	[INPUT; required] specifies what type of DEM.
		* if 'help', prints out available options

keywords
	logT	[INPUT; default=findgen(81)*0.05+4] log10(T [K]) at which
		to return DEM(T)
	pardem	[INPUT] parameters to be used to figure out the DEM.
		strictly case dependent.
	indem	[INPUT] for those cases that require an input/initial DEM
	xcur	[I/O] cursor X locations for the "cursor" option
	ycur	[I/O] cursor Y locations for the "cursor" option
	loopy	[INPUT] set to the maximum number of loop components
		that should be used for LOOP type DEMs
		* the top LOOPY EM values are kept as is, and the rest are
		  discarded
		* LCOMP lists the components that _must_ be kept
	lcomp	[INPUT] scalar or vector which contains the indices of
		the parameters that must be used to compute loops
		  -- if LCOMP exceeds LOOPY, only the largest of the
		     specified components that are within quota are kept
		  -- if LCOMP is less than LOOPY, the remaining slots are
		     filled in by the largest of the remaining components
	_extra	[INPUT ONLY] allows setting defined keywords to subroutines
		-- VARSMOOTH (WEIGHT, GAUSS, STEPS)
		-- LOOPEM (SLOOP, VERBOSE)

subroutines
	CHEBYSHEV, VARSMOOTH, LOOPEM

history
	vlk (Jun98)
	added option to interpolate (VK; Dec98)
	added option for variable scale rebin (VK; 1999)
	added option to interactively specify DEM (VK; MMJul)
	rebin option now works (VK; AugMM)
	added keywords XCUR and YCUR (VK; JanMMI)
	converted array notation to IDL 5 (VK; Apr02)
	added 'delta' option (VK; Mar03)
	now correctly converts EM to DEM for 'delta' (VK; Jun03)
	added keyword LOOPY; allows limiting the number of T components
	  for LOOP (VK; Mar05)
	added keyword LCOMP (VK; Jun05)
	button press status now stored in !MOUSE, not !ERR (VK; Apr09)

(See /data/fubar/SCAR/pro/mk_dem.pro)


MK_EFOLD

[Previous Routine] [Next Routine] [List of Routines]
function	mk_efold
	returns an exponential, NORM*exp(-x*SCALE)+YOFF

syntax
	f=mk_efold(x,norm,scale,yoff,pder,verbose=verbose)

parameters
	x	[INPUT array; required] where F(X) must be computed
	norm	[INPUT; required] normalization for exponential
	scale	[INPUT; required] reciprocal of e-folding decay scale
	yoff	[INPUT; required] offset from Y=0
		* NORM,SCALE,YOFF must be scalars or single-element
		  vectors -- extra elements, if present, are silently
		  ignored
	pder	[OUTPUT; optional] partial derivatives of model wrt parameters
		at each X; calculated only if supplied in the calling sequence.

keywords
	verbose	[INPUT; default=0] controls chatter
	_extra	[JUNK] here only to prevent crashing

example
	x=findgen(100) & plot,x,mk_efold(x,100.,0.05,20.)

subroutines
	NONE

history
	vinay kashyap (Aug08)

(See /data/fubar/SCAR/pro/mk_efold.pro)


MK_GAUSS

[Previous Routine] [Next Routine] [List of Routines]
function	mk_gauss
	returns a gaussian G(X)

syntax
	g=mk_gauss(x,mean,sig,peak,pder,