This page was created by the IDL library routine
make_html_help. For more information on
this routine, refer to the IDL Online Help Navigator
or type:
? make_html_help
at the IDL command line prompt.
Last modified: Mon Feb 20 19:35:16 2006.
NAME:
acssip_ad2xy
PURPOSE:
Read new ACS _flt.fits header to invert distortion matrix and
find distorted x & y positions given tangent RA/Dec in arcseconds
relative to the center pixel (CRPIX1,2). Will only work with headers
that have A_p_q, B_p_q keywords (after Aug 2004),
and are only found in extensions 1 (CCD #2) and 4 (CCD #1).
CALLING SEQUENCE:
acssip_xy2ad, ra, dec, hdr, xd, yd
INPUT:
ra : right ascension in arcseconds in the tangent plane from
the pixel desginated by (CRPIX1-1, CRPIX2-1)
dec : declination in arcseconds
hdr : ACS header, designed for WFC, from HDU #1 or #4 in _flt files
OUTPUT:
xd : distorted pixel column in native CCD frame
yd : distorted pixel row in native CCD frame
SUBROUTINES CALLED:
sxpar()
COMMENTS:
Based on the reference of "The SIP Convention for Representing
Distortion in FITS Image Headers"
by Shupe et al. 2005.
BUGS:
Doesn't do the tangent-plane projection correctly; i.e., this
assumes that tan(theta)=theta.
REVISION HISTORY
Implemented by S. Burles during the lost year of 05.
(See pro/astrom/acssip_ad2xy.pro)
NAME:
acssip_invert
COMMENTS:
Based on the reference of "The SIP Convention for Representing
Distortion in FITS Image Headers", by Shupe et al. 2005.
Iterates the distortion correction to invert the distortion pixel map
EXAMPLE:
adxy, hdr, ra, dec, xl, yl
acssip_invert, xl, yl, hdr, x, y
REVISION HISTORY:
Implemented by S. Burles during the lost year of 05.
(See pro/astrom/acssip_invert.pro)
NAME:
acssip_xy2ad
PURPOSE:
Read new ACS _flt.fits header to convert pixel locations into
RA/Dec pairs relative to CRPIX1,2. Will only work with headers
that have A_p_q, B_p_q keywords (after Aug 2004), and are only found
in extensions 1 (CCD #2) and 4 (CCD #1)
CALLING SEQUENCE:
acssip_xy2ad, pix_col, pix_row, hdr, ra, dec
INPUT:
pix_col : any dimension array containing pixel column positions
pix_row : any dimension array containing pixel row positions
hdr : ACS header, designed for WFC, from HDU #1 or #4 in _flt files
OUTPUT:
ra : right ascension in arcseconds in the tangent plane from
the pixel desginated by (CRPIX1-1, CRPIX2-1)
dec : declination in arcseconds
SUBROUTINES CALLED:
sxpar()
COMMENTS:
Based on the reference of "The SIP Convention for Representing
Distortion in FITS Image Headers"
by Shupe et al. 2005.
BUGS:
Doesn't do the tangent-plane projection correctly; i.e., this
assumes that tan(theta)=theta.
REVISION HISTORY
Implemented by S. Burles during the lost year of 05.
(See pro/astrom/acssip_xy2ad.pro)
NAME:
adjust_error
PURPOSE:
given data points, uncertainties, and mean value, determines
what extra uncertainty yields chi^2/dof=1?
CALLING SEQUENCE
adjustment = adjust_error( x, xerr, mean=mean, dof=dof)
INPUTS:
x - [N] array of measurements
xerr - [N] array of estimated measurement uncertainties
OPTIONAL INPUTS:
mean - mean value if known [default is computed from x, xerr]
dof - degrees of freedom, defaults to N; value (even the
default) is reduced by 1 if mean is not input
tol - tolerance in adjustment in chi^2 units [default is
0.01*sqrt(dof)]
maxiter - maximum number of binary search iterations
OUTPUT:
adjustment - minimum uncertainty to add to each xerr (in
quadrature) to yield chi^2 <= dof
OPTIONAL OUTPUTS:
niter - number of iterations executed
chisq - chi^2 corresponding to adjustment
METHOD:
dunno
REVISION HISTORY:
Blanton & Hogg 2003-07-15 written, tested a bit
(See pro/math/adjust_error.pro)
NAME:
alm2healpix
PURPOSE:
Compute healpix map from spherical harmonic transform (Alm)
CALLING SEQUENCE:
map = alm2healpix(nside, alm, lmax=lmax)
INPUTS:
nside - healpix nside (number of pixels is 12*nside^2)
alm - dcomplex array of Alm coefficients (Alm[l, m])
Of course this is zero for l<m
KEYWORDS:
lmax - maximum l to compute (Default determined by alm array size)
OUTPUTS:
map - healpix map
OPTIONAL OUTPUTS:
RESTRICTIONS:
EXAMPLES:
COMMENTS:
Something is a little funny (part in 1 million) at the poles
REVISION HISTORY:
2003-Mar-14 Written by Douglas Finkbeiner, Princeton
2003-Nov-12 Can do many maps at once, sped up - DPF & NP
(See pro/healpix/alm2healpix.pro)
NAME: angdidis PURPOSE: Compute angular diameter distancea (for c/H_0=1). CALLING SEQUENCE: D= angdidis(z,OmegaM,OmegaL, weq=weq) INPUTS: z - redshift or vector of redshifts OmegaM - Omega-matter at z=0 OmegaL - Omega-Lambda at z=0 OPTIONAL INPUTS: weq - Equation of state (Default=-1) KEYWORDS OUTPUTS: angular diameter distance in units of the Hubble length c/H_0 COMMENTS: BUGS: May not work for pathological parts of the OmegaM-OmegaL plane. EXAMPLES: PROCEDURES CALLED: propmotdis() REVISION HISTORY: 25-Jun-2000 Written by Hogg (IAS) 2004-Sep-8, Added equation of state for OmegaL, Padmanabhan (Princeton)
(See pro/cosmography/angdidis.pro)
NAME:
angles_to_xyz
PURPOSE:
Convert spherical coordinates (r,phi,theta) into Cartesion coordinates
(x,y,z). The angles must be in the following ranges:
0 <= phi < 360
0 <= theta <= 180
where theta=0 corresponds to the N pole, and theta=180 is the S pole.
If you want to convert from RA and DEC, pass the following
arguments (in degrees): RA, 90-DEC
REVISION HISTORY:
2005-09-10 tweaked - Hogg (NYU)
(See pro/coord/angles_to_xyz.pro)
NAME:
ASINH
PURPOSE:
Return the inverse hyperbolic sine of the argument
EXPLANATION:
The inverse hyperbolic sine is used for the calculation of asinh
magnitudes, see Lupton et al. (1999, AJ, 118, 1406)
CALLING SEQUENCE
result = asinh( x)
INPUTS:
X - hyperbolic sine, numeric scalar or vector (not complex)
OUTPUT:
result - inverse hyperbolic sine, same number of elements as X
double precision if X is double, otherwise floating pt.
METHOD:
Expression given in Numerical Recipes, Press et al. (1992), eq. 5.6.7
Note that asinh(-x) = -asinh(x) and that asinh(0) = 0. and that
if y = asinh(x) then x = sinh(y).
REVISION HISTORY:
Written W. Landsman February, 2001
Bug fixed for multiple elements M Blanton Mar 2002
(See pro/math/asinh2.pro)
NAME:
astrom_engine
PURPOSE:
Compute astrometric solution for a list of stars & catalogue stars
CALLING SEQUENCE:
gsa_out = astrom_engine( xpos, ypos, catlon, catlat, gsa_in, $
[ search_rad=, search_scale=, search_angle=, $
poserr=, nmatch=, catind=, obsind=, /radial, /verbose ] )
INPUTS:
xpos - X positions in CCD coordinates
ypos - Y positions in CCD coordinates
catlon - Catalog star longitudes in the same coordinate system as GSA_IN
catlat - Catalog star latitutes in the same coordinate system as GSA_IN
gsa_in - Input GSSS structure with initial guess for astrometric
solution
radial - (Not used.)
OPTIONAL INPUTS:
search_rad - Unused ???
search_scale - Unused ???
search_angle - If set, then search for rotations offset by +/-SEARCH_ANGLE
relative to the input astrometric guess.
poserr - Maximum position error in CCD coordinates; default to 1.
No stars will be matched at distances further than this.
verbose - If set, then be verbose.
OUTPUTS:
gsa_out - Output GSSS structure with astrometric solution;
return 0 if astrometry failed
OPTIONAL OUTPUTS:
nmatch - Number of matched objects with the input catalog.
catind - Indices of CATLON,CATLAT for matched objects.
obsind - Indices of XPOS,YPOS for matched objects.
COMMENTS:
We assume that we know the scale and rotation well enough, then solve
for the X,Y offsets by correlating with catalog stars.
BUGS:
The match distances are **hard-wired** to 6 arcsec on the first iteration,
and 3 arcsec on the 2nd iteration???
PROCEDURES CALLED:
angle_from_pairs()
astrom_tweak
gsssadxy
gsssxyad
offset_from_pairs
REVISION HISTORY:
10-Jun-2002 Written by D. Schlegel & D. Finkbeiner, Princeton.
(See pro/astrom/astrom_engine.pro)
NAME:
astrom_tweak
PURPOSE:
Tweak astrometric solution, given a good initial guess
CALLING SEQUENCE:
gsa_out = astrom_tweak( gsa_in, catra, catdec, imx, imy, $
[ dtheta=, errflag=, nmatch=, catind=, obsind=, /verbose ] )
INPUTS:
gsa_in - Initial guess for astrometric solution (struct)
cat - Structure (with fields .ra, .dec) of catalogue positions
im - Structure (with fields .x, .y) of image star positions
OPTIONAL KEYWORDS:
dtheta - Match distance between catalog and image stars;
default to 5 arcsec
verbose - If set, then print sizes of offsets
OUTPUTS:
gsa_out - returned guess for astrometric solution (struct);
0 if solution failed
OUTPUT OUTPUTS:
errflag - Set to 1 if fatal error occurs, 0 otherwise
nmatch - Number of matched stars
catind - Indices of CATLON,CATLAT for matched objects.
obsind - Indices of XPOS,YPOS for matched objects.
COMMENTS:
Uses preliminary solution given in astr structure to match image
and catalogue stars within maxsep pixels of each other. These
are then used by astrom_warp to determine a new solution, returned
in astr.
BUGS:
The terms AMDX[4],AMDY[4] in the GSSS structure should actually *not*
be fit for since they are higher-order, but this was the easiest
way to implement this code???
PROCEDURES CALLED:
djs_angle_match()
gsssadxy
gsssxyad
REVISION HISTORY:
02-Feb-2003 Written by D. Schlegel and D. Hogg, APO
(See pro/astrom/astrom_tweak.pro)
NAME:
ATV
PURPOSE:
Interactive display of 2-D images.
CATEGORY:
Image display.
CALLING SEQUENCE:
atv [,array_name OR fits_file] [,min = min_value] [,max=max_value]
[,/linear] [,/log] [,/histeq] [,/block]
[,/align] [,/stretch] [,header = header]
REQUIRED INPUTS:
None. If atv is run with no inputs, the window widgets
are realized and images can subsequently be passed to atv
from the command line or from the pull-down file menu.
OPTIONAL INPUTS:
array_name: a 2-D data array to display
OR
fits_file: a fits file name, enclosed in single quotes
KEYWORDS:
min: minimum data value to be mapped to the color table
max: maximum data value to be mapped to the color table
linear: use linear stretch
log: use log stretch
histeq: use histogram equalization
block: block IDL command line until ATV terminates
align: align image with previously displayed image
stretch: keep same min and max as previous image
header: FITS image header (string array) for use with data array
OUTPUTS:
None.
COMMON BLOCKS:
atv_state: contains variables describing the display state
atv_images: contains the internal copies of the display image
atv_color: contains colormap vectors
atv_pdata: contains plot and text annotation information
RESTRICTIONS:
Requires IDL version 5.1 or greater.
Requires Craig Markwardt's cmps_form.pro routine.
Requires the GSFC IDL astronomy user's library routines.
Some features may not work under all operating systems.
SIDE EFFECTS:
Modifies the color table.
EXAMPLE:
To start atv running, just enter the command 'atv' at the idl
prompt, either with or without an array name or fits file name
as an input. Only one atv window will be created at a time,
so if one already exists and another image is passed to atv
from the idl command line, the new image will be displayed in
the pre-existing atv window.
MODIFICATION HISTORY:
Written by Aaron J. Barth, with contributions by
Douglas Finkbeiner, Michael Liu, David Schlegel, and
Wesley Colley. First released 17 December 1998.
This version is 1.4, last modified 23 June 2003.
For the most current version, revision history, instructions,
list of known bugs, and further information, go to:
http://www.astro.caltech.edu/~barth/atv
Hacked up by Finkbeiner 5 December 2003 to support healpix.
;-
(See pro/plot/atv.pro)
NAME:
atv_healcart_ind
PURPOSE:
Generate and cache healcart pixel index array and header for atv
CALLING SEQUENCE:
ind = atv_healcart_ind(image, nest=, header=)
INPUTS:
image - healpix array
KEYWORDS:
nest - indicate nested ordering
OUTPUTS:
ind - index array
OPTIONAL OUTPUTS:
header - mock FITS header for nonstandard HCT projection
COMMENTS:
Used by atv.
IDLUTILS version of wcsxy2sph.pro recognizes this projection, even
though it is NOT STANDARD FITS!
REVISION HISTORY:
2003-May-10 Written by Douglas Finkbeiner, Princeton
(See pro/healpix/atv_healcart_ind.pro)
NAME: atv_joe_writeps PURPOSE: Write a PostScript file of the current ATV display w/out using a widget CALLING SEQUENCE: atv_joe_writeps, filename, [ _EXTRA ] INPUTS: filename - Name of PostScript file OPTIONAL INPUTS: aspect - retain aspect ratio in .ps file _EXTRA - Optional keywords for DEVICE OUTPUT: OPTIONAL OUTPUTS: COMMENTS: This routine allows one to send the current contents of the ATV window to a PostScript file without using a widget. This makes it convenient for using ATV in a batch mode to make plots (though the ATV window will still pop up on your terminal). Note that there are a number of defaults set in the call to DEVICE that can be over-written in the call to this routine. EXAMPLES: BUGS: PROCEDURES CALLED: REVISION HISTORY: 08-May-2003 Written by J. Hennawi and D. Schlegel, Princeton
(See pro/plot/atv_joe_writeps.pro)
NAME:
balkan_plot
PURPOSE:
plot balkans of a set of polygons
CALLING SEQUENCE:
balkan_plot, poly [, /over , /noplot, balkans=, weight=, $
poly=, shading=, verts= ]
INPUTS:
poly - [np] mangle polygon structures
OPTIONAL KEYWORDS:
/over - overplot previously existing plot
/noplot - don't actually plot
OPTIONAL OUTPUTS:
poly - [np] polygons guessed from the input
balkans - [nb] balkanized polygons
weight - [nb] weight to add in each balkanized polygon
shading - [nb] shading values based on exposure time
verts - [nb] structure containing vertices
.NVERTS - number of vertices
.RA - pointer to array of RA values
.DEC - pointer to array of DEC values
COMMENTS:
If you want better control over how things get plotted, call with
the /noplot option and have it return the "verts" and "shading"
outputs (or you can set the shading yourself based on the
"weight" output). Then you can do something like the following
inside your plotting routine:
loadct, 0
for i=0L, n_elements(verts)-1L do $
if(allverts[i].nverts gt 0) then $
polyfill, *verts[i].ra, *verts[i].dec, color=shading[i], $
noclip=0
REVISION HISTORY:
2005-Jul-07 as exposure_plot for FITS files MRB (NYU)
2005-Dec-07 rewritten for more generality MRB (NYU)
(See pro/mangle/balkan_plot.pro)
NAME: beatdrive PURPOSE: test a new disk partition by writing it full of data and verifying CALLING SEQUENCE: beatdrive, path, fits=fits, size=size INPUTS: path - path to beat on (will make with mkdir -p) KEYWORDS: fits - set to write with writefits instead of writeu size - multiply SDSS image size (5574656 bytes) by this factor OUTPUTS: lots of files! RESTRICTIONS: EXAMPLES: beatdrive, '/scr1/test' COMMENTS: data file size is 5574656 Bytes = 5444 kB = 5.3164 MB = 0.00519180 GB REVISION HISTORY: BOT Written by Douglas Finkbeiner, Princeton 10-Dec-2005 checked into idlutils/pro/misc
(See pro/misc/beatdrive.pro)
NAME: beatdrive_check PURPOSE: test a new disk partition by reading output of beatdrive.pro CALLING SEQUENCE: beatdrive_check, path, fits=fits, nocompare=nocompare INPUTS: path - path given to beatdrive.pro KEYWORDS: fits - set to read with readfits [not implemented] nocompare - turn off comparisons for speed. EXAMPLES: beatdrive_check, '/scr1/test' COMMENTS: data file size is 5574656 Bytes = 5444 kB = 5.3164 MB = 0.00519180 GB REVISION HISTORY: BOT Written by Douglas Finkbeiner, Princeton 10-Dec-2005 checked into idlutils/pro/misc
(See pro/misc/beatdrive_check.pro)
NAME:
bh_rdfort
PURPOSE:
Read 4*E(B-V) for Burstein & Heiles reddening maps.
Read values directly from Michael Strauss' Fortran data files.
This program returns identical results as from Michael Strauss'
program, but does not allow the interpolation option.
Regions with no data return values of -14, -99 or -396. Valid
data is always > -0.22.
CALLING SEQUENCE:
value = bh_rdfort( [ gall, galb, infile=infile, outfile=outfile, $
bhpath=bhpath ] )
INPUTS:
OPTIONAL INPUTS:
gall: Galactic longitude(s) in degrees
galb: Galactic latitude(s) in degrees
infile: If set, then read LCOORD and BCOORD from this file
outfile: If set, then write results to this file
bhpath: Path name for BH data files
OUTPUTS:
value: 4*E(B-V) from Burstein & Heiles reddening maps
PROCEDURES CALLED:
readcol
REVISION HISTORY:
Written by D. Schlegel, 2 Oct 1997, Durham
(See pro/dust/bh_rdfort.pro)
NAME:
blanton_oned_meanplot
PURPOSE:
plot sliding mean of one quantity vs one other
COMMENTS:
INPUTS:
x - data values
z - quantity to average
OPTIONAL INPUTS:
weight - weighting for data points; default unity
xrange - x range; default to the number > minnum area
dxbin - size of boxes in x-dir; default to a function of
first and second moments
levels - contour levels; default to a function of image range
minnum - minimum number of points in a sliding box to plot;
default 100
KEYWORDS:
BUGS:
REVISION HISTORY:
2003-01-08 written - Hogg
(See pro/plot/blanton_oned_meanplot.pro)
NAME:
blanton_weighted_mean_surface
PURPOSE:
make an image of the weighted mean for a 2-d set of measurements
CALLING SEQUENCE:
images = weighted_mean_surface(x,y,weight,quantity,xbin,ybin,dx,dy)
INPUTS:
x,y - [N] values of measurements
quantity - [N] measurements themselves
weight - [N] weights for measurements
xbin,ybin - [nx],[ny] vectors of coordinates of image pixel centers
dx,dy - size of sliding box in which means are taken
OPTIONAL INPUTS:
boot_seed - if set, use as seed for a bootstrap resampling trial
OUTPUTS:
images - [nx,ny,4] output images of number of contributing
points (image 0), total weight used (image 1), total
square weight used (image 2), and weighted mean (image 3)
COMMENTS:
BUGS:
REVISION HISTORY:
2003-01-11 written - Hogg
(See pro/plot/blanton_weighted_mean_line.pro)
NAME:
bspline_action
PURPOSE:
1) Construct banded bspline matrix, with dimensions [ndata, bandwidth]
CALLING SEQUENCE:
action = bspline_action( x, sset, x2=x2, lower=lower, upper=upper)
INPUTS:
x - independent variable
sset - Structure to be returned with all fit parameters
RETURNS:
action - b-spline action matrix
OPTIONAL KEYWORDS:
x2 - Orthogonal dependent variable for 2d fits
OPTIONAL OUTPUTS:
lower - A list of pixel positions, each corresponding to the first
occurence of position greater than breakpoint indx
upper - Same as lower, but denotes the upper pixel positions
COMMENTS:
Does not yet support the slatec function to directly return
derivatives of the b-spline (ideriv).
EXAMPLES:
PROCEDURES CALLED:
REVISION HISTORY:
11-Sep-2000 Written by Scott Burles, FNAL
3-Jul-2001 Fundamental array organization bug fixed, S. Burles
(See pro/bspline/bspline_action.pro)
NAME:
bspline_bkpts
PURPOSE:
Choose bkpts for b-spline given different constraints
CALLING SEQUENCE:
fullbkpt = bspline_bkpts(x, nord=, bkpt=, $
bkspace=, nbkpts=, everyn=, /silent)
INPUTS:
bkpt - Breakpoint vector returned by efc
nord - Order for spline fit
RETURNS:
fullbkpt - The fullbkpt vector required by evaluations with bvalu
OPTIONAL KEYWORDS:
bkspace - Spacing of breakpoints in units of x
everyn - Spacing of breakpoints in good pixels
nbkpts - Number of breakpoints to span x range
minimum is 2 (the endpoints)
silent - Do not produce non-critical messages
OPTIONAL OUTPUTS:
bkpt - breakpoints without padding
COMMENTS:
If both bkspace and nbkpts are passed, bkspace is used.
EXAMPLES:
PROCEDURES CALLED:
none
REVISION HISTORY:
10-Mar-2000 Written by Scott Burles, FNAL
(See pro/bspline/bspline_bkpts.pro)
NAME:
bspline_fit
PURPOSE:
Calculate a B-spline in the least-squares sense
based on two variables: x which is sorted and spans a large range
where bkpts are required
and y which can be described with a low order
polynomial
CALLING SEQUENCE:
error_code = bspline_fit(x, y, invvar, sset, $
fullbkpt=, nord=, x2=, npoly=, yfit=)
INPUTS:
x - Independent variable
y - Dependent variable
invvar - Inverse variance of Y
sset - Structure to be returned with all fit parameters
(if not set, then it is created)
OPTIONAL KEYWORDS:
fullbkpt - Pass fullbkpt to seed structure; if not set, then
this is generated with CREATE_BSPLINESET()
nord - Order of b-splines; default to 4 (cubic)
x2 - Orthogonal dependent variable
npoly - Order of x2 polynomial fit; default to the value in the
SSET structure, or to 1.
OUTPUTS:
error_code - Non-negative numbers indicate ill-conditioned bkpts
0 is good
-1 is dropped breakpoints, try again
-2 is failure, should abort
sset - Structure with all fit parameters
OPTIONAL OUTPUTS:
yfit - Evaluation of b-spline at X (and X2)
COMMENTS:
This code replaces efcmn and efc2d calls in the slatec library.
BUGS:
Do we need to sort X for this routine???
EXAMPLES:
PROCEDURES CALLED:
bspline_action()
bspline_maskpoints()
bspline_valu()
cholesky_band()
cholesky_solve()
create_bsplineset()
REVISION HISTORY:
20-Aug-2000 Written by Scott Burles, FNAL
(See pro/bspline/bspline_fit.pro)
NAME:
bspline_iterfit
PURPOSE:
Calculate a B-spline in the least squares sense with rejection
CALLING SEQUENCE:
sset = bspline_iterfit( )
INPUTS:
xdata - Data x values
ydata - Data y values
OPTIONAL KEYWORDS:
invvar - Inverse variance of y; if not set, then set to be
consistent with the standard deviation. This only matters
if rejection is being done.
nord - Order for spline fit; default to 4.
x2 - 2nd dependent variable for 2-D spline fitting.
npoly - Polynomial order to fit over 2nd variable (X2); default to 2.
xmin - Normalization minimum for X2; default to MIN(XDATA).
xmax - Normalization maximum for X2; default to MAX(XDATA).
oldset - If set, then use values of FULLBKPT, NORD, XMIN, XMAX, NPOLY
from this structure.
funcname - If OLDSET is not specified and this is a 2-D B-spline,
then the function for the second variable may be passed.
The default is 'legendre' in the call to CREATE_BSPLINESET().
maxiter - Maximum number of rejection iterations; default to 10;
set to 0 to disable rejection.
upper - Upper rejection threshhold; default to 5 sigma.
lower - Lower rejection threshhold; default to 5 sigma.
requiren - force at at least (requiren) data points between each set of bkpts.
_EXTRA - Keywords for BSPLINE_BKPTS(), BSPLINE_FIT and/or DJS_REJECT().
OUTPUTS:
sset - Structure describing spline fit.
Return 0 if too few good (INVVAR NE 0) points are passed.
OPTIONAL OUTPUTS:
outmask - Output mask, set =1 for good points, =0 for bad points.
fullbkpt - If OLDSET is not specified, then the break points are
chosen with a call to BSPLINE_BKPTS() which can be returned
with this keyword.
yfit - B-spline fit evaluated at each data point.
COMMENTS:
Data points can be masked either by setting their weights to zero
(INVVAR[]=0), or by using INMASK and setting bad elements to zero.
INMASK is passed to DJS_REJECT().
If OLDSET is used, then the output structure SSET will be a structure
with the same name as OLDSET. This will allow the two structures to
be concatented, i.e.
> junk = [oldset, sset]
Although I'm not sure how to treat data points which fall outside
minmax(bkpt), now I will set them equal to minmax with invvar = 0
EXAMPLES:
Construct a random function, and fit a B-spline to it without
any rejection:
IDL> x = findgen(1000)
IDL> y = smooth(randomu(1234,1000),10)
IDL> sset = bspline_iterfit(x,y,nord=3,maxiter=0,bkspace=10)
IDL> yfit = bspline_valu(x,sset)
PROCEDURES CALLED:
bspline_bkpts()
bspline_fit()
create_bsplineset()
djs_reject()
REVISION HISTORY:
05-Sep-2000 Written by D. Schlegel & S. Burles
(See pro/bspline/bspline_iterfit.pro)
NAME:
bspline_maskpoints
PURPOSE:
Perform simple logic of which breakpoints to mask
CALLING SEQUENCE:
error_code = bspline_maskpoints(sset, errb, npoly)
INPUTS:
sset - Bspline structure
errb - Errors returned from cholesky routines
npoly - Polynomial norder of 2d fit (default 1)
RETURNS:
error_code = -1: Breakpoints have been dropped, try again
-2: Solution not possible, abort
OUTPUTS:
OPTIONAL KEYWORDS:
OPTIONAL OUTPUTS:
COMMENTS:
EXAMPLES:
PROCEDURES CALLED:
REVISION HISTORY:
12-Oct-2000 Written by Scott Burles, FNAL
(See pro/bspline/bspline_maskpoints.pro)
NAME:
bspline_radial
PURPOSE:
Calculate the action matrix for a Radial B-spline with PSF convolution
CALLING SEQUENCE:
sset = bspline_psf_action( )
INPUTS:
r - independent radial coordinate
theta - independent angular coordinate (in radians)
data - Data values
OPTIONAL KEYWORDS:
invvar - Inverse variance of data; if not set, then all data points
have weight of 1.0
ntheta - Vector of multipole identifiers
Each entry will correspond to an independent angular mode
Negative elements represent sin(abs(ntheta)*theta)
Positive elements represent cos(ntheta*theta)
Default is [0,-2,2]
rbkpt - This is analogous to bkpt keyword in bspline_iterfit
This sets the breakpoint positions in the radial dimension
and does not include the boundary breakpoints.
One can choose to use bkspace or everyn to also set rbkpt.
_EXTRA - Keywords for BSPLINE_BKPTS() and/or DJS_REJECT().
OUTPUTS:
sset - Structure describing spline fit.
Return 0 if too few good (INVVAR NE 0) points are passed.
OPTIONAL OUTPUTS:
outmask - Output mask, set =1 for good points, =0 for bad points.
yfit - B-spline fit evaluated at each data point.
COMMENTS:
The calling is analogous to bspline_iterfit, so hopefully you're
familiar with the 1d bsplines. This fits a function in polar coordinates,
and r, theta, and data must be supplied. The number of free parameters
is given by (Nbkpt + Nord - 1) * N_multipole.
Nbkpt = n_elements(bkpt)
Nord = the order of the bspline (default is 4)
N_multipole = n_elements(ntheta)
See Bolton et al. 2005 for an official description of radial bsplines
EXAMPLES:
PROCEDURES CALLED:
bspline_bkpts()
bspline_workit()
bspline_action()
create_bsplineset()
djs_reject()
REVISION HISTORY:
16-Aug-2005 Written by S. Burles & A. Bolton, MIT
(See pro/bspline/bspline_psf_action.pro)
NAME:
bspline_radial
PURPOSE:
Calculate a Radial B-spline in the least squares sense with rejection
CALLING SEQUENCE:
sset = bspline_radial( )
INPUTS:
r - independent radial coordinate
theta - independent angular coordinate (in radians)
data - Data values
OPTIONAL KEYWORDS:
invvar - Inverse variance of data; if not set, then all data points
have weight of 1.0
ntheta - Vector of multipole identifiers
Each entry will correspond to an independent angular mode
Negative elements represent sin(abs(ntheta)*theta)
Positive elements represent cos(ntheta*theta)
Default is [0,-2,2]
rbkpt - This is analogous to bkpt keyword in bspline_iterfit
This sets the breakpoint positions in the radial dimension
and does not include the boundary breakpoints.
One can choose to use bkspace or everyn to also set rbkpt.
_EXTRA - Keywords for BSPLINE_BKPTS() and/or DJS_REJECT().
OUTPUTS:
sset - Structure describing spline fit.
Return 0 if too few good (INVVAR NE 0) points are passed.
OPTIONAL OUTPUTS:
outmask - Output mask, set =1 for good points, =0 for bad points.
yfit - B-spline fit evaluated at each data point.
COMMENTS:
The calling is analogous to bspline_iterfit, so hopefully you're
familiar with the 1d bsplines. This fits a function in polar coordinates,
and r, theta, and data must be supplied. The number of free parameters
is given by (Nbkpt + Nord - 1) * N_multipole.
Nbkpt = n_elements(bkpt)
Nord = the order of the bspline (default is 4)
N_multipole = n_elements(ntheta)
See Bolton et al. 2005 for an official description of radial bsplines
EXAMPLES:
PROCEDURES CALLED:
bspline_bkpts()
bspline_workit()
bspline_action()
create_bsplineset()
djs_reject()
REVISION HISTORY:
22-Feb-2005 Written by S. Burles & A. Bolton, MIT
(See pro/bspline/bspline_radial.pro)
NAME:
bspline_radial_valu
PURPOSE:
1) Evaluate a radial bspline set (see bspline_radial) at the 2-d
positions specified by the r and theta arrays
CALLING SEQUENCE:
radial_fit = bspline_radial_valu( r, theta, sset, [mode = ] )
INPUTS:
x - independent variable
sset - Structure to be returned with all fit parameters
RETURNS:
radial_fit - Evaluated b-spline fit
OPTIONAL KEYWORDS:
mode - return just a single mode of the bspline fit,
must be GE 0 and LT n_elements(sset.ntheta)
Default is to return the sum of all modes
OPTIONAL OUTPUTS:
COMMENTS:
EXAMPLES:
PROCEDURES CALLED:
REVISION HISTORY:
22-Feb-2005 Written by Scott Burles & Adam Bolton, MIT
(See pro/bspline/bspline_radial_valu.pro)
NAME:
bspline_valu
PURPOSE:
1) Evaluate a bspline set (see create_bsplineset) at specified
x and x2 arrays
CALLING SEQUENCE:
yfit = bspline_valu( x, sset, x2=x2, action=action, upper=upper,
lower=lower, mask=mask)
INPUTS:
x - independent variable
sset - Structure to be returned with all fit parameters
RETURNS:
yfit - Evaluated b-spline fit
OPTIONAL KEYWORDS:
x2 - Orthogonal dependent variable for 2d fits
action - This keyword is overwritten with b-spline action matrix
lower,upper- Internal keywords used by action, maybe should replace
action with a structure including lower and upper
OPTIONAL OUTPUTS:
mask - a mask array of good (1's) bspline evalutions
COMMENTS:
the mask attempts to show regions where the bspline was ill-defined
and breakpoints had been dropped.
EXAMPLES:
PROCEDURES CALLED:
REVISION HISTORY:
11-Sep-2000 Written by Scott Burles, FNAL
(See pro/bspline/bspline_valu.pro)
NAME:
bvalu2d
PURPOSE:
Evaluate a bspline fit over 2 dependent variables
CALLING SEQUENCE:
z = bvalu2d(x, y, bkpt, coeff, ideriv=ideriv)
INPUTS:
x - vector of x positions to evaluate
y - vector of y positions to evaluate
bkpt - Breakpoint vector returned by efc
coeff - B-spline coefficients calculated by efc
2d in this case [npoly, nbkpt-nord]
OPTIONAL KEYWORDS:
ideriv - Derivative to evaluate at x (default 0)
OUTPUTS:
z - Evaluations corresponding to x positions
OPTIONAL OUTPUTS:
COMMENTS:
EXAMPLES:
PROCEDURES CALLED:
slatec_bvalu
REVISION HISTORY:
13-Mar-2000 Written by Scott Burles, FNAL
(See pro/slatec/bvalu2d.pro)
NAME: cap_distance PURPOSE: Return distance from coordinates to a cap, in degrees. CALLING SEQUENCE: cap_distance INPUTS: OPTIONAL INPUTS: OUTPUT: OPTIONAL OUTPUTS: COMMENTS: The sign is positive if in the cap, and negative if outside EXAMPLES: BUGS: PROCEDURES CALLED: angles_to_x() REVISION HISTORY: 19-Jun-2003 Written by David Schlegel, Princeton.
(See pro/mangle/cap_distance.pro)
NAME:
catfits
PURPOSE:
Read and concatenate a bunch of binary FITS tables
CALLING SEQUENCE:
struc = catfits(flist)
INPUTS:
filst - string array of FITS filenames to read and concatenate
for each column of data to be read. Allowed letters are
OUTPUTS:
struc - IDL structure
REVISION HISTORY:
Written 2001-Nov-28 D. Finkbeiner
(See pro/misc/catfits.pro)
NAME:
ccm_fitrv.pro
PURPOSE:
Does a simple fit to R_V and normalization
CALLING SEQUENCE:
R_V = ccm_fitrv(wave, redfac, [weight=, norm=norm, chi2=chi2])
INPUTS:
wave : Wavelength [Ang] at which A is measured
redfac : Measured A
weight : Weight coefficients (by band)
OUTPUTS:
R_V : Measured R_V
OPTIONAL OUTPUTS:
norm : The measured normalization
chi2 : Returned chi2 (unit weights assumed if none passed)
COMMENTS:
The chi2 is measured by func_ccm_fitrv.pro. See that function
for weights etc.
The reddening curve is computed by ccm_unred.pro
REVISION HISTORY:
2003-Sep-10 Written by D. Finkbeiner & N.Padmanabhan, Princeton
(See pro/dust/ccm_fitrv.pro)
NAME:
circle_cap
PURPOSE:
Return a circular cap centered on a certain set of coordinates.
CALLING SEQUENCE:
cap=circle_cap(radius, [ra=, dec=, xyz= ])
INPUTS:
radius - proper radius of cap, in degrees
ra, dec - coordinates of center
OR
xyz - xyz value of center (should be unit vector)
COMMENTS:
Use for the cap of a mangle polygon defining a circle.
ra,dec inputs will override xyz inputs
REVISION HISTORY:
01-Oct-2002 Written by MRB (NYU)
(See pro/mangle/circle_cap.pro)
NAME:
CMPS_FORM
PURPOSE:
This function puts up a form the user can configure a PostScript
device driver. The function result (if the user selects either the
ACCEPT or CREATE FILE buttons) can be sent directly to the DEVICE
procedure by means of its _Extra keyword. User's predefined
configurations may be retrieved from a common block.
AUTHOR:
*********** CM 01 Feb 2000 VERSION *************
Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
craigm@lheamail.gsfc.nasa.gov
Based almost entirely on, but a totally revamped version of, CMPS_FORM by
FANNING SOFTWARE CONSULTING (David Fanning Ph.D.) http://www.dfanning.com
MAJOR TOPICS:
Device Drivers, Hardcopy Output, PostScript Output
PROCEDURE:
This is a pop-up form widget. It is a modal or blocking widget.
Keywords appropriate for the PostScript DEVICE command are returned.
Use your LEFT mouse button to move the "Plot Window" around the page.
Use your RIGHT mouse button to draw your own "Plot Window" on the page.
HELP:
formInfo = CMPS_FORM(/Help)
CALLING SEQUENCE:
formInfo = CMPS_FORM(xoffset, yoffset, Cancel=cancelButton)
OPTIONAL INPUTS:
XOFFSET -- Optional xoffset of the top-level base of cmps_form. Default is
to try to center the form on the display.
YOFFSET -- Optional yoffset of the top-level base of cmps_form. Default is
to try to center the form on the display.
INPUT KEYWORD PARAMETERS:
BITS_PER_PIXEL -- The initial configuration of the bits per pixel button.
BLOCKING -- Set this keyword to make this a blocking widget under IDL 5.0.
(All widget programs block under IDL 4.0.)
COLOR -- The initial configuration of the color switch.
DEFAULTS -- A stucture variable of the same type and structure as the
RETURN VALUE of cmps_form. It will set initial conditions. This makes
it possible to start cmps_form up again with the same values it had the
last time it was called. For example:
mysetup = cmps_form()
newsetup = cmps_form(Defaults=mysetup)
ENCAPSULATED -- The initial configuration of the encapsulated switch.
FILENAME -- The initial filename to be used on the form.
HELP -- Prints a helpful message in the output log.
INCHES -- The initial configuration of the inches/cm switch.
INITIALIZE -- If this keyword is set, the program immediately returns the
"localdefaults" structure. This gives you the means to configue the
PostScript device without interrupting the user.
SELECT -- used only when INITIALIZE is set. Set SELECT to a
string which identifies the predefined configuration to
be returned by cmps_form when INITIALIZE is set. This is
a convenient way to select a predefined config
non-interactively.
LANDSCAPE -- The initial configuration of the landscape/portrait switch.
LOCALDEFAULTS -- A structure like the DEFAULTS structure. If specified,
then it is added as a predefined configuration entry called "Local".
See below for a further discussion of predefined configurations.
PREDEFINED -- An alternate way to specify predefined
configurations. Pass an array of structures to
populate the "predefined" dropbox in the
dialog. This array, if specified, overrides the the
common block technique.
XOFFSET -- The initial XOffSet of the PostScript window.
YOFFSET -- The initial YOffSet of the PostScript window.
XSIZE -- The initial XSize of the PostScript window.
YSIZE -- The initial YSize of the PostScript window.
ASPECT -- The aspect ratio of the window (Y/X). This keyword can
substitute for one of XSIZE or YSIZE.
PRESERVE_ASPECT -- Set this keyword if you want to hold the
aspect ratio constant.
PAPERSIZE -- If set, allows user to specify the size of the paper
media to be printed on, as a scalar string. NOTE:
this specification cannot be passed to DEVICE, but
can be selected for completeness's sake. Default is
'Letter'.
MARGINSIZE -- Size of the margins on all sides. Default is 0.25 inches.
When MARGINSIZE is non-zero, a graphic cannot directly
abut the edge of the page. This is normally a good thing,
since there is often a non-printable region which borders
the page.
DEFAULTPAPER -- Default paper size to use, when it is unspecified
in a predefined, "local", or "default"
configuration. This value also overrides any
configuration from common blocks. European users
will probably set this to 'A4'.
PARENT -- if this widget is invoked by another widget program,
then this keyword parameter must be set to the top level
widget which is to serve as the group leader. Failure
to do so will result in unexpected behavior. IDL 4
programs do not need to pass this parameter. Default:
NONE.
OUTPUT KEYWORD PARAMETERS
CANCEL -- This is an OUTPUT keyword. It is used to check if the user
selected the "Cancel" button on the form. Check this variable rather
than the return value of the function, since the return value is designed
to be sent directly to the DEVICE procedure. The varible is set to 1 if
the user selected the "Cancel" button. Otherwise, it is set to 0.
CREATE -- This output keyword can be used to determine if the user
selected the 'Create File' button rather than the 'Accept' button.
The value is 1 if selected, and 0 otherwise.
PAPERSIZE -- If set to a named variable, any newly selected paper
size is returned in that variable.
XPAGESIZE -- Size of paper in "X" dimension, in units given by
the returned config structure.
YPAGESIZE -- Size of paper in "Y" dimension, in units given by
the returned config structure.
PAGEBOX -- specifies the page rectangle relative to the plot
window, in normalized units. A 4-vector of the form
[XLL, YLL, XUR, YUR] is returned, giving the positions
of the lower left (LL) and upper right (UR) corners of
the page with respect to the plot window. Thus, the
following command:
PLOT, x, y, position=PAGEBOX
will construct a graphic whose plot region exactly
fills the page (with no margin around the edges).
Naturally, the page is usually larger than the
graphics window, so the normalized coordinates will
usually fall outside the range [0,1].
However, the bounding box constructed by the
Postscript driver includes only the graphics window.
Anything drawn outside of it may be clipped or
discarded.
RETURN VALUE:
formInfo = { cmps_form_INFO, $
xsize:0.0, $ ; The x size of the plot
xoff:0.0, $ ; The x offset of the plot
ysize:0.0, $ ; The y size of the plot
yoff:0.0 $ ; The y offset of the plot
filename:'', $ ; The name of the output file
inches:0 $ ; Inches or centimeters?
color:0, $ ; Color on or off?
bits_per_pixel:0, $ ; How many bits per image pixel?
encapsulated:0,$ ; Encapsulated or regular PostScript?
isolatin1:0,$ ; Encoded with ISOLATIN1?
landscape:0 } ; Landscape or portrait mode?
USAGE:
The calling procedure for this function in a widget program will
look something like this:
info.ps_config = cmps_form(/Initialize)
formInfo = cmps_form(Cancel=canceled, Create=create, $
Defaults=info.ps_config)
IF NOT canceled THEN BEGIN
IF create THEN BEGIN
thisDevice = !D.Name
Set_Plot, "PS"
Device, _Extra=formInfo
Enter Your Graphics Commands Here!
Device, /Close
Set_Plot, thisDevice
info.ps_config = formInfo
ENDIF ELSE
info.ps_config = formInfo
ENDIF
MAJOR FUNCTIONS and PROCEDURES:
None. Designed to work originally in conjunction with XWindow, a
resizable graphics window. [ NOTE: this modified version of
cmps_form, by Craig Markwardt, is incompatible with the original
version of XWINDOW. ]
MODIFICATION HISTORY:
Based on cmps_form of : David Fanning, RSI, March 1995.
Major rewrite by: Craig Markwardt, October 1997.
- Drawing and updating of form and sample box are now modular
- Option of storing more than one predefined postscript configuration
- Selection of paper size by name
- Access to predfined configurations through (optional) common
block
Several additions, CM, April 1998 VERSION CM2.0
- better integration of paper sizes throughout program.
Predefined configurations now also know about paper.
- allow passing predefined configurations instead of using
common block
- addition of ISOLATIN selection, and streamlining of dialog
appearance
Fixed bug in INITIALIZE w.r.t. paper sizes, CM, Nov 1998
Added SELECT keyword, CM, 09 Dec 1998
Added Parent keyword to allow modal widgets in IDL 5, 19 Jan 1999
Added "Choose" button for filename selection, 19 Sep 1999
Added ability to program different button names, 19 Sep 1999
Added ASPECT and PRESERVE_ASPECT, based on work by Aaron Barth, 18
Oct 1999
Removed NOCOMMON documentation and logic, 19 Oct 1999, CM
Added aspect to cmps_form_numevents (per Aaron Barth), 18 Oct 1999
Corrected small bug under Initialize keyword (inches), 18 Oct 1999
Made call to *_pscoord more consistent, 18 Oct 1999
Added XPAGESIZE, YPAGESIZE and PAGEBOX keywords, 19 Oct 1999
Small cosmetic cleanup, CM, 01 Feb 2000
COMMON BLOCKS:
The user may store frequently used or helpful configurations in a
common block, and cmps_form() will attempt to access them. This
provides a way for the user to have persistent, named,
configurations.
NOTE: this format has changed since the last version. You may
have to quit your IDL session for the changes to take effect
properly. If you have place a predefined configuration in your
startup file, you should review the new format.
COMMON CMPS_FORM_CONFIGS, cmps_form_DEFAULT_PAPERSIZE, $
cmps_form_STDCONFIGS
cmps_form_DEFAULT_PAPERSIZE - a string designating the default
paper size, when none is given.
The predefined configurations
offerred by this program will
respect the default value. (See
also the DEFAULTPAPER keyword.)
cmps_form_STDCONFIGS - An array of cmps_form_CONFIG structures,
each containing information about one
predefined configuration, such as its
name and size of paper. Each "config"
element is a cmps_form_INFO structure,
which contains the actual postscript
configuration.
See the IDL source code cmps_form_LOAD_CONFIGS for an example of how
to make a list of configurations. One possibility would be to
declare and populate the common block from within the user's
start-up script, allowing the same configurations to appear in
every session.
cmps_form() takes its initial list of configurations from this
common block if it exists. A default list is provided ala the
procedure cmps_form_LOAD_CONFIGS. Any modifications that take place
during the cmps_form() widget session are not transferred back to
the common block upon return. It might be useful to be able to do
this, through some form of 'save' procedure.
Also, if the PREDEFINED keyword is used, then the common block is
not consulted.
(See pro/plot/cmps_form.pro)
NAME:
cmp_fits_files
PURPOSE:
Compare the contents of two FITS files.
CALLING SEQUENCE:
cmp_fits_files, filename1, filename2, [ /verbose ]
INPUTS:
filename1 - First FITS file
filename2 - Second FITS file
OPTIONAL INPUTS:
verbose - If set, then report extensions that are the same, as
well as reporting any differences
OUTPUTS:
OPTIONAL OUTPUTS:
COMMENTS:
All HDUs are compared, both images and structures.
Report a warning if the variable type is different, for example if
one file contains a structure and the other an image, or if one
contains an integer image and the other a floating-point image.
For images, report a warning if the number of array elements disagree,
or if any values disagree.
For structures, report a warning if the number of structure tags disagree,
or if any values disagree.
EXAMPLES:
BUGS:
PROCEDURES CALLED:
mrdfits()
splog
REVISION HISTORY:
06-Nov-2003 Written by David Schlegel, Princeton.
(See pro/fits/cmp_fits_files.pro)
NAME:
comdis
PURPOSE:
Compute comoving line-of-sight distances (for c/H_0=1).
CALLING SEQUENCE:
D= comdis(z,OmegaM,OmegaL, weq=weq)
INPUTS:
z - redshift or vector of redshifts
OmegaM - Omega-matter at z=0
OmegaL - Omega-Lambda at z=0
OPTIONAL INPUTS:
weq - Equation of state (default=-1)
KEYWORDS
OUTPUTS:
comoving line-of-sight distance in units of the Hubble length c/H_0
COMMENTS:
BUGS:
The integrator is crude, slow and repetetive.
May not work for pathological parts of the OmegaM-OmegaL plane.
EXAMPLES:
PROCEDURES CALLED:
dcomdisdz()
REVISION HISTORY:
25-Jun-2000 Written by Hogg (IAS)
2004-Sep-06 Added support for different equations of state,
Padmanabhan (Princeton)
(See pro/cosmography/comdis.pro)
NAME:
comdis2
PURPOSE:
Compute comoving line-of-sight distances (for c/H_0=1).
CALLING SEQUENCE:
D= comdis2(z,OmegaM,OmegaL,cdtable=cdtable,zmaxtable=zmaxtable)
INPUTS:
z - redshift or vector of redshifts
OmegaM - Omega-matter at z=0
OmegaL - Omega-Lambda at z=0
OPTIONAL INPUTS:
cdtable - returns the lookup table calculated, so you can reuse
zmaxtable - set max z value of lookup table
KEYWORDS
OUTPUTS:
comoving line-of-sight distance in units of the Hubble length c/H_0
COMMENTS:
Call as:
dC = comdis2(z,OmegaM,OmegaL,cdtable=cdtable)
if you call it multiple times, so it does not remake the the
lookup table.
BUGS:
The integrator is crude, slow and repetitive.
May not work for pathological parts of the OmegaM-OmegaL plane.
Relies on interpolate() working
EXAMPLES:
PROCEDURES CALLED:
dcomdisdz()
REVISION HISTORY:
2000-Jun-25 Written by Hogg (IAS)
2002-Feb-20 Look-up table to increase speed; Blanton (NYU)
(See pro/cosmography/comdis2.pro)
NAME: construct_cap PURPOSE: Create the structure for a cap CALLING SEQUENCE: poly=construct_cap() INPUTS: OPTIONAL INPUTS: OUTPUTS: OPTIONAL INPUT/OUTPUTS: COMMENTS: EXAMPLES: BUGS: PROCEDURES CALLED: REVISION HISTORY: 01-Oct-2002 Written by MRB (NYU)
(See pro/mangle/construct_cap.pro)
NAME: construct_polygon PURPOSE: Create the structure for a polygon. This has the number of caps stored, a bitmask indicating whether to use each cap, the weight, and the area CALLING SEQUENCE: poly=construct_polygon() INPUTS: OPTIONAL INPUTS: OUTPUTS: OPTIONAL INPUT/OUTPUTS: COMMENTS: EXAMPLES: BUGS: Number of caps limited to 32 PROCEDURES CALLED: REVISION HISTORY: 01-Oct-2002 Written by MRB (NYU)
(See pro/mangle/construct_polygon.pro)
NAME: construct_vertex PURPOSE: Create the structure for a vertex. CALLING SEQUENCE: vertex=construct_vertex([maxnvertices= ]) INPUTS: OPTIONAL INPUTS: maxnvertices - the maximum number of vertices allowed for any vertex OUTPUTS: OPTIONAL INPUT/OUTPUTS: COMMENTS: EXAMPLES: BUGS: Number of caps limited to 32 PROCEDURES CALLED: REVISION HISTORY: 01-Oct-2002 Written by MRB (NYU)
(See pro/mangle/construct_vertex.pro)
NAME: copy_caps PURPOSE: copy information about caps from one polygon to another CALLING SEQUENCE: copy_caps, poly1, poly2 INPUTS: OPTIONAL INPUTS: OUTPUTS: OPTIONAL INPUT/OUTPUTS: COMMENTS: blows away old pointers EXAMPLES: BUGS: Number of caps limited to 32 PROCEDURES CALLED: REVISION HISTORY: 01-Oct-2002 Written by MRB (NYU)
(See pro/mangle/copy_caps.pro)
NAME:
count_freelun
PURPOSE:
Count the number of logical file pointers (LUNs) that are available
CALLING SEQUENCE:
num = count_freelun()
INPUTS:
OPTIONAL INPUTS:
OUTPUTS:
num - Number of logical file pointers (LUNs) that can be allocated
with GET_LUN before triggering an error
OPTIONAL OUTPUTS:
COMMENTS:
EXAMPLES:
BUGS:
DATA FILES:
PROCEDURES CALLED:
REVISION HISTORY:
02-Mar-2004 Written by D. Schlegel, Princeton
(See pro/misc/count_freelun.pro)
NAME: cpbackup PURPOSE: Copy a file to a backup file name. CALLING SEQUENCE: cpbackup, filename INPUTS: filename - File to copy if it exists. OUTPUTS: COMMENTS: Make a backup copy of the specified file by appending ".1", ".2", etc. The first unused number is used as an appendix. EXAMPLES: BUGS: This is only written to work with a Unix file system, since it spawns the Unix "cp" command. PROCEDURES CALLED: REVISION HISTORY: 11-Mar-2000 Written by D. Schlegel, Princeton
(See pro/misc/cpbackup.pro)
NAME:
crossprod
PURPOSE:
compute cross product of two vectors or arrays of vectors
CALLING SEQUENCE:
C=crossprod(A,B)
INPUTS:
A, B - either [3] or [Nvec,3]
OUTPUT:
C - either [3] or [Nvec,3]
COMMENTS:
If A and B are BOTH row vectors, return a row vector.
Otherwise, return [Nvec,3]
REVISION HISTORY:
2003-May-13 Written by Finkbeiner & Schlegel, Princeton
(See pro/coord/crossprod.pro)
NAME: current_mjd PURPOSE: Transform systime() to current MJD. CALLING SEQUENCE: mjd= current_mjd() INPUTS: OPTIONAL KEYWORDS: OUTPUTS: OPTIONAL OUTPUTS: COMMENTS: Your clock better be right when you ask for UT! EXAMPLES: BUGS: Relies on IDL 5.4 feature /utc for systime(). PROCEDURES CALLED: REVISION HISTORY: 2001-Feb-07 written by Hogg, NYU
(See pro/coord/current_mjd.pro)
NAME:
dcomdisdz
PURPOSE:
Compute differential comoving line-of-sight distances (for c/H_0=1).
CALLING SEQUENCE:
dDdz= dcomdisdz(z,OmegaM,OmegaL, weq=weq)
INPUTS:
z - redshift or vector of redshifts
OmegaM - Omega-matter at z=0
OmegaL - Omega-Lambda at z=0
OPTIONAL INPUTS:
weq - Eq. of state (Default =-1)
KEYWORDS
OUTPUTS:
differential comoving distance DD/dz in units of the Hubble length c/H_0
COMMENTS:
BUGS:
May not work for pathological parts of the OmegaM-OmegaL plane.
EXAMPLES:
PROCEDURES CALLED:
REVISION HISTORY:
25-Jun-2000 Written by Hogg (IAS)
2004-Sep-06 Added support for different equations of state,
Padmanabhan (Princeton)
(See pro/cosmography/dcomdisdz.pro)
NAME: dcomvoldz PURPOSE: Compute differential comoving volume element dV_c/dz per unit solid angle. CALLING SEQUENCE: dVdz= dcomvoldz(z,OmegaM,OmegaL) INPUTS: z - redshift or vector of redshifts OmegaM - Omega-matter at z=0 OmegaL - Omega-Lambda at z=0 OPTIONAL INPUTS: KEYWORDS OUTPUTS: Comoving volume per steradian in units of the Hubble volume (c/H_0)^3 COMMENTS: Formulae from Carrol, Press & Turner, 1992, Kolb & Turner, 1990, and my own calculation. BUGS: May not work for pathological parts of the OmegaM-OmegaL plane. EXAMPLES: PROCEDURES CALLED: dpropmotdisdz propmotdis REVISION HISTORY: 2001-Mar-12 Written by Hogg (NYU)
(See pro/cosmography/dcomvoldz.pro)
NAME:
dec2hms
PURPOSE:
convert decimal number to HH:MM:SS (base sixty)
CALLING SEQUENCE:
result = dec2hms(angle_in, double=double)
INPUTS:
angle_in - angle [hours for RA, degrees for declination]
KEYWORDS:
double - double precision math
OUTPUTS:
result - string containing HH:MM:SS or DD:MM:SS
EXAMPLES:
ra_string = dec2hms(ra_degree/15)
dec_string = dec2hms(dec_degree)
COMMENTS:
This function does not convert from hours to degrees!
Pass type double, or suffer 0.003 arcsec error
There is some tom-foolery to prevent roundoff problems
(like 1 -> '00 59 60.0') but if you aren't using /double
you have no right to expect high precision anyway.
REVISION HISTORY:
Written by Douglas Finkbeiner in ancient times
2000-Nov-29 - double keyword added - DPF
2005-Sep-16 - call self recursively for array - DPF
(See pro/coord/dec2hms.pro)
NAME: destruct_polygon PURPOSE: Destroy the structure for a polygon. CALLING SEQUENCE: destruct_polygon, poly INPUTS: poly - polygon to destroy OPTIONAL INPUTS: OUTPUTS: OPTIONAL INPUT/OUTPUTS: COMMENTS: EXAMPLES: BUGS: PROCEDURES CALLED: REVISION HISTORY: 01-Oct-2002 Written by MRB (NYU)
(See pro/mangle/destruct_polygon.pro)
NAME: dfpsclose PURPOSE: Finkbeiner's routine to close a PostScript file previously opened with DFPSOPEN, and revert to sending plots to the X-display. CALLING SEQUENCE: dfpsclose INPUTS: OPTIONAL INPUTS: OUTPUTS: OPTIONAL OUTPUTS: COMMENTS: EXAMPLES: PROCEDURES CALLED: REVISION HISTORY: The-Beginning-of-Time Written by Doug Finkbeiner, Berkeley. 05-Sep-1999 Modified and commented by David Schlegel, Princeton. 06-Aug-2001 Check if X device is set already - DPF, Princeton
(See pro/plot/dfpsclose.pro)
NAME:
dfpsplot
PURPOSE:
Finkbeiner's routine to open a PostScript file for plotting commands.
Close with DFPSCLOSE.
CALLING SEQUENCE:
dfpsplot, filename, [/square, /landscape, ysize=ysize, $
/encap, /color, _EXTRA=KeywordsForDevice ]
INPUTS:
filename - File name to open
OPTIONAL INPUTS:
square - Make the plotting area square.
landscape - Use landscape paper; default is to use portrait.
ysize - For portrait mode, the YSIZE can be changed from its
default of 8-inches. For landscape mode, the value
of YSIZE is ignored.
encap - Force non-encapsulated file unless this keyword is set.
color - Force non-color file unless this keyword is set.
OUTPUT:
OPTIONAL OUTPUTS:
COMMENTS:
EXAMPLES:
PROCEDURES CALLED:
REVISION HISTORY:
The-Beginning-of-Time Written by Doug Finkbeiner, Berkeley.
05-Sep-1999 Modified and commented by David Schlegel, Princeton.
(See pro/plot/dfpsplot.pro)
NAME:
dierfc
PURPOSE:
Inverse of the Complementary Error Function "erfc^{-1}(x)"
CALLING SEQUENCE:
result = dierfc( input )
INPUTS:
input - Arbitrary array of values from 0 to 2.
(positive values returned for inputs between 0 and 1)
exact 0 return NaN,
OUTPUTS:
result - The output array of type double, with range from
-infinity to +infinity.
OPTIONAL OUTPUTS:
COMMENTS:
The results outside of -20 < results < +20 may lack desired accuracy
EXAMPLES:
inverse = dierfc([0.0,0.0027,0.0456,1.0d,1.6827,1.9])
sigma = -sqrt(2.0) * inverse*sqrt(2.0)
print, sigma, format='(6f10.4)'
-Infinity -3.0000 -1.9991 0.0000 1.0000 1.6449
COPYRIGHT:
Copyright(C) 1996 Takuya OOURA (email: ooura@mmm.t.u-tokyo.ac.jp).
You may use, copy, modify this code for any purpose and
without fee. You may distribute this ORIGINAL package.
REVISION HISTORY:
11-Jun-2002 Adapted by S. Burles, MIT
(See pro/math/dierfc.pro)
NAME: DISPLAY PURPOSE: This procedure will display an image with the TV command that fills the plotting window. It handles scale, annotations, X and PostScript devices, aspect ratios, logarithmic scaling, and interpolation. Masked values and values below <MIN> are mapped to !P.BACKGROUND. Values above <MAX> are mapped to !P.COLOR. CATEGORY: Image display. CALLING SEQUENCE: DISPLAY, Image, XS, YS INPUTS: Image: Two-dimensional array to be displayed. OPTIONAL INPUTS: XS: Vector of x-axis values. The length must equal the number of rows in <Image> YS: Vector of y-axis values. The length must equal the number of columns in <Image> KEYWORD PARAMETERS: TITLE= Set this keyword to a string containing the title annotation to be used by PLOT. XTITLE= Set this keyword to a string containing the x-axis annotation to be used by PLOT. YTITLE= Set this keyword to a string containing the y-axis annotation to be used by PLOT. SUBTITLE= Set this keyword to a string containing the subtitle annotation to be used by PLOT. ASPECT= Set this keyword to the aspect ratio (width/height) of the pixels. /ASPECT is the same as ASPECT=1 and produces square pixels. /INTERPOLATE: Set this switch to enable bilinear interpolation for pixels in the expanded image. See /PS_FINE for information on using this switch on a PostScript device. MASKVALUE= Set this keyword to the value that pixels with bad data or no data have been flagged with. These will be mapped to 0B. MIN= The minimum value of <Image> to be considered. If MIN is not provided, <Image> is searched for its minimum value. All values less than MIN are set to !P.BACKGROUND in the Result. MAX= The maximum value of <Image> to be considered. If MAX is not provided, <Image> is searched for its maximum value. All values greater than MAX are set to !P.COLOR in the Result. BOT= The minimum value of the scaled result. If TOP is not specified, 0B is used. TOP= The maximum value of the scaled result. If TOP is not specified, 255B is used. LEVELS= Set this keyword to a vector of data value boundaries between which all elements of <Image> have the same scaled byte value. e.g. LEVELS=[0,1,2,5] maps all values below 0 and above 5 to 0B, map values between 0 and 1 to 1B, map values between 1 and 2 to 128B, and map values between 2 and 5 to 255B. This does not plot contours. /LOG: Set this switch to cause a logarithmic mapping. This is overridden by the LEVELS keyword. PS_FINE= Set to the approximate number of elements along an axis to use in interpolating on a PostScript device. Interpolation to the full indexable range of a PostScript device would be unwise. This is only useful with /INTERPOLATE and will increase the size of the PostScript file. The default size is 256 if PS_FINE= is not set or <=0, 512 if 1 < PS_FINE= < 512, and take from the keyword if PS_FINE > 512. /NOERASE: Set the switch to prevent output device from being erased before the image, scales, and annotations are displayed. /NO_EXPAND: Set this switch to prevent the image from being expanded to fill the plotting window. Scaling to byte type is still performed. SIDE EFFECTS: TV display is altered. SUBORDINATE ROUTINES: IMGSCL() IMGEXP() RESTRICTIONS: This routine may work for other devices, but it has only been tested on 'X' and 'PS'. PROCEDURE: Straight forward. :-) EXAMPLE: LoadCT, 3 image = SHIFT(DIST(20, 20), 10, 10) scale = FINDGEN(20) - 10.0 DISPLAY, image, scale, scale, /INTERPOLATE, TITLE='!6Smooth Slope', $ /ASPECT ;Use CONTOUR with /OVERPLOT to overlay contours. CONTOUR, image, scale, scale, LEVELS=1.0+FINDGEN(4)*2.0, /OVERPLOT DISPLAY ;prints out a "Usage:" line MODIFICATION HISTORY: Written by: Fen Tamanaha, July 10, 1993. Release 3.1 July 13, 1993 Fen: (3.2) Fixed /No_Expand July 16, 1993 Fen: (3.3) Really fixed /No_Expand
(See pro/plot/display.pro)
NAME:
djs_angle_group
PURPOSE:
Group objects using their coordinates on the sphere.
Any coordinates within dtheta of one another are put in the same group.
Note that if there is a string of successive objects on the sky, each
separated by less than dtheta, then all of these objects are assigned
to the same group. This is incorrect in the sense that the first and
last objects in the string may have a large separation; however, this
is the only unambigious answer to the problem.
CALLING SEQUENCE:
ngroup = djs_angle_group( ra, dec, dtheta, $
[gstart=gstart, gcount=gcount, gindx=gindx, units=units] )
INPUTS:
ra: RA of point(s) in radians/degrees/hours
dec: DEC of point(s) in radians/degrees
dtheta: Maximum angular distance for points to be considered matches
OPTIONAL INPUTS:
units: Set to
degrees - All angles in degrees
hrdeg - RA angles in hours, DEC angles and output in degrees
radians - All angles in radians
Default to "degrees".
OUTPUTS:
ngroup: Total number of groups. If no matches are found, then this
equals the number of objects.
OPTIONAL OUTPUTS:
gstart: Vector of length "ngroup" with the starting index of each group.
gcount: Vector of length "ngroup" with the number of objects in each
group.
gindx: Indices of objects in each group. The i-th group will have
its object indices stored in gindx(gstart:gstart+gcount-1).
PROCEDURES CALLED:
INTERNAL SUPPORT PROCEDURES:
djs_search_around
REVISION HISTORY:
29-May-1997 Written by D. Schlegel, Durham
24-Feb-1999 Converted to IDL 5 (DJS).
(See pro/coord/djs_angle_group.pro)
NAME:
djs_angle_match
PURPOSE:
Given two lists of coordinates on a sphere, find matches within an
angular distance. For each entry in list A, find all the entries
in list B that lie within an angular distance dtheta.
Optionally output up to mmax of these matches per entry, giving
the index number of the matches in mindx, and the angular distance
in mdist.
If the lists A and B are different, then the total number of pairs
is given by total(mcount).
If the lists A and B are the same, then the total number of unique
pairs is given by (total(mcount) - N_elements(raA)) / 2.
This function loops over the objects in each list (sort of), so it's
not very fast.
CALLING SEQUENCE:
ntot = djs_angle_match( raA, decA, [raB, decB,] dtheta=dtheta, $
[ mcount=mcount, mindx=mindx, mdist=mdist, mmax=mmax, units=units ]
INPUTS:
raA: RA of first point(s) in radians/degrees/hours
decA: DEC of first point(s) in radians/degrees
dtheta: Maximum angular distance for points to be considered matches
OPTIONAL INPUTS:
raB: RA of second point(s) in radians/degrees/hours
decB: DEC of second point(s) in radians/degrees
mmax: Maximum number of matches per point. Default to 1.
units: Set to
degrees - All angles in degrees
hrdeg - RA angles in hours, DEC angles and output in degrees
radians - All angles in radians
Default to "degrees".
OUTPUTS:
ntot: Total number of points A with one or more matches in B
OPTIONAL OUTPUTS:
mcount: For each A, number of matches in B. Vector of length A.
mindx: For each A, indices of matches in B, sorted by their distance.
If mmax > 1, this array is of dimensions (mmax, A).
For each A, only the values (0:mcount-1,A) are relevant.
If mmax = 1, then the return value is a vector.
Any unused array elements are set to -1.
mdist: For each A, distance to matches in B, sorted by their distance.
If mmax > 1, this array is of dimensions (mmax, A).
For each A, only the values (0:mcount-1,A) are relevant.
If mmax = 1, then the return value is a vector.
Any unused array elements are set to -1.
COMMENTS:
By specifying only one set of coordinates (raA, decA), matches are found
within that list, but avoiding duplicate matches (i.e., matching 1 to 2
and then 2 to 1) and avoiding matching an object with itself (i.e.,
matching 1 to 1). If you wish to include self-matches and duplicates,
then call with raB=raA and decB=decA.
PROCEDURES CALLED:
djs_diff_angle()
INTERNAL PROCEDURES:
djs_angle_1match()
djs_angle_2match()
REVISION HISTORY:
27-May-1997 Written by David Schlegel, Durham
24-Feb-1999 Converted to IDL 5 (DJS)
05-Mar-1999 Made the internal routines for more efficient matching
within the same coordinate list without duplicates, e.g.
by only specifying raA, decA and not raB, decB.
(See pro/coord/djs_angle_match.pro)
NAME:
djs_angle_nmatch
PURPOSE:
Given two lists of coordinates on a sphere, find matches within an
angular distance. For each entry in list B, return the number of
matches in list A that lie within an angular distance dtheta.
This function loops through list A, so it is very slow if that list is long.
The angle dtheta can be the same for each object in A, or may be set
to a vector of length A.
A list of indices where B has a match in A is where(nmatch GT 0).
CALLING SEQUENCE:
nmatch = djs_angle_nmatch( raA, decA, raB, decB, dtheta, $
[ units=units ]
INPUTS:
raA: RA of first point(s) in radians/degrees/hours
decA: DEC of first point(s) in radians/degrees
raB: RA of second point(s) in radians/degrees/hours
decB: DEC of second point(s) in radians/degrees
dtheta: Maximum angular distance for points to be considered matches
OPTIONAL INPUTS:
units: Set to
degrees - All angles in degrees
hrdeg - RA angles in hours, DEC angles and output in degrees
radians - All angles in radians
Default to "degrees".
OUTPUTS:
nmatch: For each B, number of matches with A
PROCEDURES CALLED:
djs_diff_angle()
REVISION HISTORY:
18-Jul-1997 Written by David Schlegel, Durham
Modified from djs_angle_match().
24-Feb-1999 Converted to IDL 5 (DJS)
(See pro/coord/djs_angle_nmatch.pro)
NAME: djs_angpos PURPOSE: Put an angle into the range [0, 360). CALLING SEQUENCE: result = djs_angpos(xval) INPUTS: xval OUTPUTS: result PROCEDURES CALLED: REVISION HISTORY: Written D. Schlegel, 17 June 1996, Durham
(See pro/coord/djs_angpos.pro)
NAME: djs_angsgn PURPOSE: Put an angle into the range [-180, 180). CALLING SEQUENCE: result = djs_angsgn(xval) INPUTS: xval OUTPUTS: result PROCEDURES CALLED: REVISION HISTORY: Written D. Schlegel, 17 June 1996, Durham
(See pro/coord/djs_angsgn.pro)
NAME: djs_arrow PURPOSE: Modified version of ARROW to allow a string for the color(s) CALLING SEQUENCE: djs_arrow INPUT: OUTPUTS: PROCEDURES CALLED: REVISION HISTORY: Written by D. Schlegel, 11 Dec 1998, Princeton
(See pro/plot/djs_arrow.pro)
NAME:
djs_avsigclip
PURPOSE:
Average multiple images with sigma-rejection.
CALLING SEQUENCE:
result = djs_avsigclip( array, [ dimension, sigrej=, maxiter=, $
inmask=, outmask= ] )
INPUTS:
array - N-dimensional array
OPTIONAL INPUTS:
dimension - The dimension over which to collapse the data. If ommitted,
assume that the last dimension is the one to collapse.
sigrej - Sigma for rejection; default to 3.0.
maxiter - Maximum number of sigma rejection iterations. One iteration
does no sigma rejection; default to 10 iterations.
inmask - Input mask, setting =0 for good elements
OUTPUTS:
result - The output array.
outmask - Output mask, setting =0 for good elements, =1 for bad.
Any pixels masked in INMASK are also masked in OUTMASK.
OPTIONAL OUTPUTS:
COMMENTS:
The DIMENSION input is analogous to that used by the IDL built-in
function TOTAL.
EXAMPLES:
Create a data cube of 10 random-valued 100x200 images. At each pixel in
the image, compute the average of the 10 values, but rejecting 3-sigma
outliers:
> array = randomu(123,100,200,10)
> ave = djs_avsigclip(array, sigrej=3)
If all points are masked in any given vector or array, a mean and
dispersion are computed for all the points. Is this the behaviour we want?
If you want to replace those values with zeros instead, look at OUTMASK:
> array = randomu(123,100,200)
> inmask = bytarr(100,200)
> inmask[*,8] = 1 ; mask all of row #8
> ave = djs_avsigclip(array, 1, inmask=inmask, outmask=outmask)
> ibad = where( total(1-outmask, 1) EQ 0)
> if (ibad[0] NE -1) then ave[ibad] = 0 ; zero-out bad rows
BUGS:
PROCEDURES CALLED:
Dynamic link to arravsigclip.c
REVISION HISTORY:
07-Jul-1999 Written by David Schlegel, Princeton.
(See pro/math/djs_avsigclip.pro)
NAME: djs_axis PURPOSE: Modified version of AXIS CALLING SEQUENCE: djs_axis INPUT: OUTPUTS: PROCEDURES CALLED: TeXtoIDL() REVISION HISTORY: Written by D. Schlegel, 21 Jan 1998, Durham
(See pro/plot/djs_axis.pro)
NAME:
djs_batch
PURPOSE:
Batch processing script for running jobs locally or across a network.
CALLING SEQUENCE:
djs_batch, topdir, [localfile], [outfile], protocol, remotehost, $
remotedir, command, [ priority=, selecthost=, wtime= ]
INPUTS:
topdir - Local top-level directory for input and output files.
Also use this directory for remote hosts where REMOTEDIR
is not specified.
localfile - Array of pointers to input files on local machine [NPROGRAM].
This input is optional.
outfile - Array of pointers to output files created on remote machine
and copied to local machine upon completion [NPROGRAM]
This input is optional.
protocol - List of protocols for remote hosts. Valid values are:
'ssh', 'ssh1', 'ssh2', 'rsh', or ''. One must set to
no protocol ('') if the remote host name is 'localhost'.
Otherwise, one must always set a protocol.
remotehost - List of remote hosts [NHOST]
remotedir - List of remote directories; scalar or [NHOST]
command - Command to execute to begin a job; scalar or [NPROGAM]
OPTIONAL KEYWORDS:
priority - Priority for each job, where the jobs with the largest
value are done first [NPROGRAM]
selecthost - If set, then assign each job to only a host that matches
the selected host per job [NPROGRAM]
wtime - Sleep time between checking status of all jobs; default to
600 seconds.
OUTPUTS:
COMMENTS:
The file names will support wildcards. For example, if you want to
return all files from the directory REMOTEDIR/abc on the remote machine,
then set OUTFILE = 'abc/*'.
EXAMPLES:
BUGS:
PROCEDURES CALLED:
INTERNAL SUPPORT ROUTINES:
batch_spawn
count_freelun()
create_program_list()
create_host_list()
batch_if_done()
batch_assign_job
batch_finish_job
REVISION HISTORY:
17-Oct-2000 Written by D. Schlegel, Princeton
(See pro/misc/djs_batch.pro)
NAME: djs_ceil PURPOSE: Return smallest integer not less than xvalue. This is identical to the C library function "ceil()". CALLING SEQUENCE: result = djs_ceil(xvalue) INPUTS: xvalue OUTPUTS: result PROCEDURES CALLED: REVISION HISTORY: Written D. Schlegel, 27 November 1996, Durham
(See pro/math/djs_ceil.pro)
NAME: djs_contourpts PURPOSE: Make a contour plot from point data, drawing contours only where the point density is high. CALLING SEQUENCE: djs_contourpts INPUT: xpt: ypt: OPTIONAL KEYWORDS: bin1: bin2: overplot: If set, then use current plot limits and overplot. nlevels: levels: loglevels: If set, then select NLEVEL (or 6) log-spaced levels nopoints: If set, then do not plot any point data (only contours). psym: Keyword for plotting point data; default to 3 color: Keyword for plotting point data OUTPUTS: OPTIONAL OUTPUTS: level0: Lowest contour level ilow: Indices for points outside the lowest contour level. PROCEDURES CALLED: djs_icolor() djs_oplot REVISION HISTORY: Written by D. Schlegel, 9 Dec 1998, Princeton
(See pro/plot/djs_contourpts.pro)
NAME:
djs_correlate
PURPOSE:
Compute a cross-correlation function using weights (or masks).
CALLING SEQUENCE:
result = djs_correlate( x, y, [ lags, xweight=, yweight= ] )
INPUTS:
x - Vector
y - Vector, which may have a different number of elements from X
OPTIONAL INPUTS:
lags - A scalar or integer vector specifying the lags at which
to compute the cross-correlation; default to one lag at 0.
xweight - Vector of weights for X; default to 1 for all points
yweight - Vector of weights for Y; default to 1 for all points
OUTPUTS:
result - The output vector, with one result per LAG value.
OPTIONAL OUTPUTS:
COMMENTS:
This routine is similar to the IDL routine C_CORRELATE(), but with a
few notable differences. The X and Y vectors do not wrap when they are
shifted, but rather only overlapping elements are compared at each lag.
Because of this, X and Y do not have to have the same number of dimensions.
A weight (or mask) can be assigned to each element of X,Y using the
XWEIGHT,YWEIGHT keywords. These weights can effectively be used to
mask out regions of each vector by setting the weight to 1 for good
pixels and 0 for bad ones.
Each pixel of both X and Y are effectively weighted by XWEIGHT*YWEIGHT
appropriately shifted before the multiplication.
EXAMPLES:
BUGS:
The C routine only supports type FLOAT.
PROCEDURES CALLED:
Dynamic link to ccorrelate.c
REVISION HISTORY:
07-Jul-2000 Written by David Schlegel, Princeton.
(See pro/math/djs_correlate.pro)
NAME:
djs_diff_angle
PURPOSE:
Compute the angular distance between two points on a sphere.
CALLING SEQUENCE:
adist = djs_diff_angle( ra, dec, ra0, dec0, [ units=units ] )
INPUTS:
ra1: RA of first point(s) in radians/degrees/hours
dec1: DEC of first point(s) in radians/degrees
ra2: RA of second point(s) in radians/degrees/hours
dec2: DEC of second point(s) in radians/degrees
OPTIONAL INPUTS:
units: Set to
degrees - All angles in degrees
hrdeg - RA angles in hours, DEC angles and output in degrees
radians - All angles in radians
Default to "degrees".
OUTPUTS:
adist: Angular distance(s) in radians if UNITS is set to 'radians',
or in degrees otherwise
COMMENTS:
Note that either (ra1,dec1) or (rap,decp) must be scalars or 1-element
arrays, or all must be arrays of the same length.
PROCEDURES CALLED:
REVISION HISTORY:
14-May-1997 Written by D. Schlegel, Durham
(See pro/coord/djs_diff_angle.pro)
NAME: djs_floor PURPOSE: Return largest integer not greater than xvalue. This is identical to the C library function "floor()". CALLING SEQUENCE: result = djs_floor(xvalue) INPUTS: xvalue OUTPUTS: result PROCEDURES CALLED: REVISION HISTORY: Written D. Schlegel, 27 November 1996, Durham
(See pro/math/djs_floor.pro)
NAME:
djs_hex2bin
PURPOSE:
Convert hexadecimal number(s) to binary numbers.
CALLING SEQUENCE:
binval = djs_hex2bin(hexval, [ndigit=ndigit])
INPUTS:
hexval: String or array of strings containing hexadecimal number(s)
OPTIONAL INPUTS:
ndigit: Number of binary digits in output; if not supplied, then the
minimum number of digits are used
OUTPUTS:
intval: Byte array(s) of binary values, dimensioned intval(ndigit,nnum)
EXAMPLE:
PRINT, DJS_HEX_TO_BINARY( '1a' )
IDL prints the result
0 1 0 1 1
One can truncate to only the 4 least significan digits by setting NDIGIT:
PRINT, DJS_HEX_TO_BINARY( '1a', NDIGIT=4 )
IDL prints the result
0 1 0 1
PRINT, DJS_HEX_TO_BINARY( ['1a', '2b', '3'] )
IDL prints the result
0 1 0 1 1 0
1 1 0 1 0 1
1 1 0 0 0 0
PROCEDURES CALLED:
djs_hex2int()
djs_int2bin()
REVISION HISTORY:
Written D. Schlegel, 30 June 1997, Durham
(See pro/math/djs_hex2bin.pro)
NAME:
djs_hex2int
PURPOSE:
Convert hexadecimal number(s) to long integer(s).
CALLING SEQUENCE:
intval = djs_hex2int(hexval)
INPUTS:
hexval: String or array of strings containing hexadecimal number(s)
OUTPUTS:
intval: Long integer or array or long integers
EXAMPLE:
PRINT, DJS_HEX_TO_INT( '1a' )
IDL prints the result
26
PRINT, DJS_HEX_TO_INT( ['1a', '2b', '3'] )
IDL prints the result
26 43 3
PROCEDURES CALLED:
REVISION HISTORY:
Written D. Schlegel, 30 June 1997, Durham
(See pro/math/djs_hex2int.pro)
NAME: djs_icolor PURPOSE: Internal routine for converting a color name to an index. CALLING SEQUENCE: icolor = djs_icolor(color) INPUT: color: OUTPUTS: icolor PROCEDURES CALLED: REVISION HISTORY: Written by D. Schlegel, 27 September 1997, Durham
(See pro/plot/djs_icolor.pro)
NAME:
djs_int2bin
PURPOSE:
Convert integer number(s) to binary numbers.
CALLING SEQUENCE:
binval = djs_int2bin(val, [ndigit=ndigit])
INPUTS:
val: Integer number(s)
OPTIONAL INPUTS:
ndigit: Number of binary digits in output; if not supplied, then the
minimum number of digits are used
OUTPUTS:
binval: Byte array(s) of binary values
PROCEDURES CALLED:
djs_floor()
REVISION HISTORY:
Written D. Schlegel, 30 June 1997, Durham
31-Jul-1998 DJS - Subscripts modified to IDL 5 convention.
03-Aug-1999 DJS - Modified to work with signed integers by
first converting to unsigned integers.
(See pro/math/djs_int2bin.pro)
NAME:
djs_iterstat
PURPOSE:
Compute the mean, median and/or sigma of data with iterative sigma clipping.
CALLING SEQUENCE:
djs_iterstat, image, [sigrej=, maxiter=, mean=, median=, sigma=, mask=]
INPUTS:
image: Input data
OPTIONAL INPUTS:
sigrej: Sigma for rejection; default to 3.0
maxiter: Maximum number of sigma rejection iterations; default to 10
OUTPUTS:
OPTIONAL OUTPUTS:
mean: Computed mean
median: Computed median
sigma: Computed sigma
mask: Mask set to 1 for good points, and 0 for rejected points
PROCEDURES CALLED:
COMMENTS:
This routine is based upon Mark Dickinson's IRAF (!) script ITERSTAT.
It iteratively rejects outliers as determined by SIGREJ. It stops
when one of the following conditions is met:
(1) The maximum number of iterations, as set by MAXITER, is reached.
(2) No new pixels are rejected, as compared to the previous iteration.
(3) At least 2 pixels remain from which to compute statistics. If not,
then the returned values are based upon the previous iteration.
BUGS:
REVISION HISTORY:
16-Jun-1999 Written by David Schlegel, Princeton
11-Sep-2000 Speeded up by Hogg and Eisenstein
18-Sep-2000 Note change in MASK values to =1 for good (unrejected) points.
(See pro/math/djs_iterstat.pro)
NAME:
djs_laxisgen
PURPOSE:
Return a longword integer array with the specified dimensions.
Each element of the array is set equal to its index number along
the dimension IAXIS.
CALLING SEQUENCE:
result = djs_laxisgen( dimens, [ iaxis=iaxis ] )
INPUT:
dimens: Vector of the dimensions for the result.
Only up to 3 dimensions can be specified.
iaxis: Axis number to use for indexing RESULT. The first dimension
is axis number 0, the second 1, etc. Default to 0.
OUTPUTS:
result: Output array
PROCEDURES CALLED:
REVISION HISTORY:
Written by D. Schlegel, 7 Oct 1997, Durham
Modified 12 May 1998 to pass one vector with all dimensions.
(See pro/misc/djs_laxisgen.pro)
NAME:
djs_laxisnum
PURPOSE:
Return a longword integer array with the specified dimensions.
Each element of the array is set equal to its index number in
the specified axis.
CALLING SEQUENCE:
result = djs_laxisnum( dimens, [ iaxis= ] )
INPUT:
dimens: Vector of the dimensions for the result.
Only up to 3 dimensions can be specified.
iaxis: Axis number to use for indexing RESULT. The first dimension
is axis number 0, the second 1, etc. Default to 0.
OUTPUTS:
result: Output array
PROCEDURES CALLED:
REVISION HISTORY:
15-Jun-2001 Written by D. Schlegel, Princeton
(See pro/misc/djs_laxisnum.pro)
NAME:
djs_locate_file()
PURPOSE:
Locate full file name (including path) of a file, searching IDL paths
CALLING SEQUENCE:
fullname = djs_locate_file( filename )
INPUT:
filename: File name to find somewhere in path, including any extensions
OUTPUTS:
fullname: File name of first located file (including full path),
or '' if no matches found
PROCEDURES CALLED:
os_family()
REVISION HISTORY:
Written by D. Schlegel, 27 May 1997, Durham
Modified version of GETPRO in Goddard library.
(See pro/misc/djs_locate_file.pro)
NAME:
djs_lockfile
PURPOSE:
Test if a file is already "locked", and lock it if not.
CALLING SEQUENCE:
res = djs_lockfile( filename, [ lun=, append= ] )
INPUT:
filename: File name
OPTIONAL INPUTS:
lun: If this argument exists, then open FILENAME for read/write
access and return the pointer (LUN number) for that file.
Do this only if we are able to lock the file.
append: If set, then append to any file that already exists if
opening the file using LUN. Ignored if the LUN argument
is not present.
OUTPUTS:
res: Return 0 if file already locked, or 1 if not in which case
we would have just locked it.
COMMENTS:
For Unix systems running IDL 5.4 or later, we use the SPAWN command
to create a symbolic link from FILENAME.lock -> FILENAME. This can
be done atomically, such that it is impossible for two processes
to build that same link at once.
For other operating systems or ealier versions of IDL (which do
not allow SPAWN to return an error), we use a lock file which
has a single byte written to it to indicate that FILENAME should
be locked (as determined by any subsequent calls to this routine).
For all OS-es, unlock files with DJS_UNLOCKFILE.
BUGS:
PROCEDURES CALLED:
REVISION HISTORY:
30-Apr-2000 Written by D. Schlegel, APO
(See pro/misc/djs_lockfile.pro)
NAME:
djs_maskinterp
PURPOSE:
Interpolate over masked pixels in a vector, image or 3-D array.
CALLING SEQUENCE:
ynew = djs_maskinterp( yval, mask, [ xval, iaxis=, /const ] )
INPUTS:
yval - Y values; 1-, 2-, or 3-dimensional
mask - Mask values correspoding to YVAL; interpolate over all pixels
where MASK is not 0
OPTIONAL INPUTS:
xval - X (abscissa) values corresponding to YVAL; otherwise a
regular grid is assumed
iaxis - Axis along which to interpolate if YVAL has more than one
dimension; required keyword in that case; dimensions are
0-indexed, so the X axis is IAXIS=0
const - The default is to linearly interpolate beyond the endpoints
of good data. Setting this keyword instead copied the
first (last) good points for the data beyond the first (last)
good points.
OUTPUTS:
ynew - Y values after linearly interpolating over masked pixels
COMMENTS:
The IDL function INTERPOL is used for linear interpolation.
If no good points exist in a vector, then that vector is returned
unchanged.
EXAMPLES:
Create a sin-wave function, and interpolate across points at the beginning
and in the middle of this function:
xval=findgen(100)/10
yval=sin(xval)
splot,xval,yval
mask=bytarr(100)
mask[0:10]=1
mask[40:60]=1
ynew = djs_maskinterp(yval, mask, xval)
plot,xval,yval
oplot,xval,ynew,ps=2
BUGS:
This routine only supports 1-D, 2-D, and 3-D arrays.
PROCEDURES CALLED:
INTERNAL SUPPORT ROUTINS:
djs_maskinterp1()
REVISION HISTORY:
27-Jan-2000 Written by David Schlegel, Princeton.
(See pro/image/djs_maskinterp.pro)
NAME: djs_mean PURPOSE: Return the mean value of an array. CALLING SEQUENCE: result = djs_mean(array) INPUTS: array - Array of numbers OUTPUTS: result - Computed mean PROCEDURES CALLED: COMMENTS: This function is faster than the IDL function MEAN(), and will not crash when passed a 1-element array. REVISION HISTORY: 06-Oct-1997 Written by David Schlegel, Durham.
(See pro/math/djs_mean.pro)
NAME:
djs_median
PURPOSE:
Return the median of an image either with a filtering box or by collapsing
the image along one of its dimensions.
CALLING SEQUENCE:
result = djs_median( array, [ dimension, width=, boundary= ] )
INPUTS:
array - N-dimensional array
OPTIONAL INPUTS:
dimension - The dimension over which to compute the median, starting
at one. If this argument is not set, the median of all array
elements (or all elements within the median window described
by WIDTH) are medianed.
width - Width of median window; scalar value.
It is invalid to specify both DIMENSION and WIDTH.
boundary - Boundary condition:
'none': Do not median filter within WIDTH/2 pixels of
the edge; this is the default for both this
routine and MEDIAN().
'nearest': Use the value of the nearest boundary pixel.
NOT IMPLEMENTED
'reflect': Reflect pixel values around the boundary.
'wrap': Wrap pixel values around the boundary.
NOT IMPLEMENTED
These boundary conditions only take effect if WIDTH is set,
and if ARRAY is either 1-dimensional or 2-dimensional.
OUTPUTS:
result - The output array. If neither DIMENSION nor WIDTH are set,
then RESULT is a scalar. If DIMENSION is not set and WIDTH
is set, then RESULT has the same dimensions as ARRAY.
If DIMENSION is set and WIDTH is not
OPTIONAL OUTPUTS:
COMMENTS:
The DIMENSION input is analogous to that used by the IDL built-in
function TOTAL.
I should like to add the functionality of having WIDTH be an N-dimensional
smoothing box. For example, one should be able to median a 2-D image
with a 3x5 filtering box.
EXAMPLES:
Create a 2-D image and compute the median of the entire image:
> array = findgen(100,200)
> print, djs_median(array)
Create a data cube of 3 random-valued 100x200 images. At each pixel in
the image, compute the median of the 3:
> array = randomu(123,100,200,3)
> medarr = djs_median(array,3)
Create a random-valued 2-D image and median-filter with a 9x9 filtering box:
> array = randomu(123,100,200)
> medarr = djs_median(array,9)
BUGS:
The C routine only supports type FLOAT.
PROCEDURES CALLED:
Dynamic link to arrmedian.c
REVISION HISTORY:
06-Jul-1999 Written by David Schlegel, Princeton.
(See pro/math/djs_median.pro)
NAME:
djs_modfits
PURPOSE:
Wrapper for MODFITS that allows the header to increase in size,
and that works with g-zipped files.
CALLING SEQUENCE:
djs_modfits, filename, data, [hdr, exten_no=, /delete_data]
INPUTS:
filename - FITS file name; if the name ends in the suffix ".gz",
then the file is g-unzipped first, modified, then re-g-zipped.
data - New data array or structure for extension EXTEN_NO;
if this is undefined or zero, then don't modify the data.
OPTIONAL INPUTS:
hdr - New FITS header for extension EXTEN_NO
exten_no - FITS extension number to modify; default to 0.
delete_data - If set, then delete this data. Note that this cannot
be accomplished by setting DATA=0, since that simply says
to not change the data array/structure (to be consistent
with the functionality of MODFITS).
OUTPUTS:
OPTIONAL OUTPUTS:
COMMENTS:
EXAMPLES:
BUGS:
PROCEDURES CALLED:
modfits
mrdfits()
mwrfits
readfits()
writefits
INTERNAL PROCEDURES:
bitsperpixel()
REVISION HISTORY:
17-May-2000 Written by David Schlegel, Princeton.
(See pro/fits/djs_modfits.pro)
NAME:
djs_mosaic_rgb
PURPOSE:
Make color (RGB) images from 3 FITS files, and overplot text and points
CALLING SEQUENCE:
djs_mosaic_rgb, prefix
INPUTS:
prefix - start of filenames
OPTIONAL KEYWORDS:
resizefactor - factor by which to scale the JPG relative to the
fits files; default 0.5
stretch - factor by which to multiply the default RGB
scales; default 1.0
rotation - integer to pass to IDL rotate command; default 0
xtext - X position for text [NTEXT]
ytext - Y position for text [NTEXT]
text - Text [NTEXT]
colortext - Colors for text; dimensioned either [3] or [3,NTEXT],
where [255,0,0] is red, [0,255,0] is green, etc.
xplot - X position for points [NPOINTS]
yplot - Y position for points [NPOINTS]
colorplot - Colors for points; dimensioned either [3] or [3,NPOINTS],
where [255,0,0] is red, [0,255,0] is green, etc.
_EXTRA - Keywords to pass to XYOUTS and PLOT, such as
CHARSIZE, PSYM, etc
COMMENTS:
Stretch is constant in f_lambda
EXAMPLES:
djs_mosaic_rgb, 'marla-001'
BUGS:
Memory issues with asinh etc.
The current implementation is very slow if COLORTEXT or COLORPLOT
are 2-dimensional arrays.
REVISION HISTORY:
2003-11-24 written - Hogg
2004-01-03 Modified (generalized) by D. Schlegel, Princeton
(See pro/rgbcolor/djs_mosaic_rgb.pro)
NAME:
djs_neff
PURPOSE:
Return the neff statistic (effective number of pixels)
neff = [ SUM(image) ]^2 / SUM(image^2)
CALLING SEQUENCE:
neff = djs_neff(image, [sigimg, nerr=nerr] )
INPUTS:
image: An image of any number of dimensions
OPTIONAL INPUTS:
sigimg: Image of errors for computing nerr
OUTPUTS:
neff: Return value of neff
OPTIONAL OUTPUTS:
nerr: Error in neff, if sigimg is specified
PROCEDURES CALLED:
COMMENTS:
If computing this statistic for an object on an image, the background
(sky) level should first be removed. However, the image need not be
renormalized. For an object of constant surface brightness, Neff equals
the number of pixels subtended by the object. For a Gaussian profile
that is well-sampled, Neff = 4 * pi * sigma^2.
REVISION HISTORY:
10-Sep-1998 Written by D Schlegel, Princeton
(See pro/djsphot/djs_neff.pro)
NAME: djs_oplot PURPOSE: Modified version of OPLOT. CALLING SEQUENCE: djs_oplot, [x,] y INPUT: x: y: OUTPUTS: COMMENTS: Allows COLOR, PSYM, and SYMSIZE to be vectors. Also allows COLOR to be string descriptions of eight possible colors. If string descriptors are used, then load a basic 8-color color table. PROCEDURES CALLED: djs_icolor() REVISION HISTORY: Written by D. Schlegel, 27 September 1997, Durham
(See pro/plot/djs_oplot.pro)
NAME:
djs_oploterr
PURPOSE:
Modified version of OPLOTERR and DJS_OPLOT.
Allows COLOR, PSYM, and SYMSIZE to be vectors.
Also allows COLOR to be string descriptions of eight possible colors.
If string descriptors are used, then load a basic 8-color color table.
CALLING SEQUENCE:
djs_oploterr, [x,] y, xerr=xerr, yerr=yerr, xlog=xlog, ylog=ylog, $
cap=cap, xlen=xlen, ylen=ylen, $
color=color, psym=psym, symsize=symsize
INPUT:
x:
y:
OPTIONAL INPUTS:
xerr: Error in X; or -1 for upper limit arrow, -2 for lower limit arrow
yerr: Error in Y; or -1 for upper limit arrow, -2 for lower limit arrow
xlog: If set, take the logarithm of X and its error
ylog: If set, take the logarithm of Y and its error
cap: If set, place caps on error bars
xlen: Length of upper/lower limit bars in X; default to 6% of plot range
ylen: Length of upper/lower limit bars in Y; default to 6% of plot range
OUTPUTS:
PROCEDURES CALLED:
REVISION HISTORY:
Written by D. Schlegel, 5 February 1998, Durham
(See pro/plot/djs_oploterr.pro)
NAME:
djs_phot
PURPOSE:
Driver for aperture photometry with the option of re-centering and
sky-subtraction.
CALLING SEQUENCE:
flux = djs_phot( xcen, ycen, objrad, skyrad, image, [invvar, $
calg=, cbox=, cmaxiter=, cmaxshift=, $
fwhm=, fixfw=, ceps=, $
salg=, srejalg=, smaxiter=, $
lorej=, hirej=, $
flerr=, skyval=, skyrms=, skyerr=, peakval=, /quick, /exact ] )
INPUTS:
xcen: X center(s)
ycen: Y center(s)
objrad: Radius for aperture on object, or a vector of such radii.
skyrad: A 2-element array with two radii to define an annulus,
or a scalar to define a circular aperture, or undefined
for no sky calculation
image: FITS data array, as read from readfits().
OPTIONAL INPUTS:
invvar: Inverse variance image, for computing the errors FLERR
----------- FOR CENTERING ALGORITHM
calg: Centering algorithm. Choose from iweight, gauss1, gauss2, none.
iweight = intensity-weighted center, computed independently
in both X and Y
gauss1 = gaussian fit, including a constant term, computed
independently in both X and Y
gauss2 = not implemented
none = no centering
Default to iweight.
cbox: Centering box width. Default to 7.
cmaxiter: Maximum number of iterations for centering algorithm.
Default to 10.
cmaxshift: Maximum center shift. If this shift is exceeded in either
X or Y, then return the center position passed in XCEN,YCEN.
A value of 0 imposes no maximum shift. Default to 3.
fwhm: FWHM for gauss1 or gauss2 centering algorithms. If this is
a scalar, then the same value is used for both X and Y.
If this is a vector, then the first two elements are used
for X and Y respectively.
fixfw: If set and nonzero, then fix the FWHM for gauss1 or gauss2 fits.
ceps: Stop iterating when relative shifts in both X and Y are less
than this value. Default to 0.
----------- FOR SKY FITTING ALGORITHM
salg: Sky fitting algorithm. Choose from mean, median, mode, none.
Default to "mean" if SKYRAD is set, or "none" otherwise.
srejalg: Rejection algorithm. Choose from none, sigclip, pclip.
sigclip = sigma clipping; reject outliers that are
more than lorej*sigma below skyval or hirej*sigma
above skyval
pclip = percentile clipping; reject the lowest lorej
fraction and the highest hirej fraction of points
none = no rejection
Default to sigclip
smaxiter: Maximum number of srejalg iterations. Default to 10.
lorej: If srejalg="sigclip", then the number of standard deviations
below skyval to clip (default to 3.0).
If srejalg="pclip", then fraction of low pixels to clip
(default to 0.05).
hirej: If srejalg="sigclip", then the number of standard deviations
above skyval to clip (default to 3.0).
If srejalg="pclip", then fraction of high pixels to clip
(default to 0.05).
KEYWORDS:
exact Use slow photo-based photfrac algorithm (Not thoroughly tested)
Requires image to be centered such that xcen and ycen
are integer values. If set, does not recalculate
center.
quick Use faster photfrac algorithm (Not thoroughly tested)
OUTPUTS:
flux: Total flux within each circular aperture defined by objrad,
minus the sky contribution within each aperture [NOBJ,NRAD].
xcen: Re-centered X position (modified).
ycen: Re-centered X position (modified).
OPTIONAL OUTPUTS:
flerr: Flux error from the sky background uncertainty within
the object aperture(s) [NOBJ,NRAD]
skyval: Sky value in counts per unit area [NOBJ].
skyrms: RMS of sky pixels about skyval, again in counts per unit area.
This assumes that each unit area is independent. The RMS
is computed for only the values that remain after all the
rejection iterations [NOBJ].
skyerr: The error in skyval assuming that each pixel is independent.
This is skyrms divided by the square root of the number of
pixels [NOBJ].
peakval: Peak pixel value (before sky-subtraction)
COMMENTS:
Sub-pixel sampling of the circular apertures is handled exactly.
If /exact keyword is set, input xcen, ycen must be integers or
the code bombs. See exact_photfrac.pro for more details, but
basically exact_photfrac is much simpler to implement if the
object is already centered, which doesn't cost you precision.
For similar reasons, if /exact is set, djs_phot will not try to
recentroid your object.
PROCEDURES CALLED:
djs_photcen
djs_photfrac
djs_photsky()
REVISION HISTORY:
28-Nov-1996 Written by D. Schlegel, Durham.
01-Jun-2000 Major revisions: change XYCEN to XCEN,YCEN; remove use
of FITS headers; make IDL 5 compliant (DJS).
02-Nov-2000 objrad, skyrad recast as floats (D. Finkbeiner)
If they are ints, 1% errors may arise.
(See pro/djsphot/djs_phot.pro)
NAME:
djs_photcen
PURPOSE:
Recenter an object position.
CALLING SEQUENCE:
djs_photcen, xcen, ycen, image, $
[ calg=, cbox=, cmaxiter=, cmaxshift=, fwhm=, /fixfw, ceps=, qmaxshift= ]
INPUTS:
xcen: X center(s)
ycen: Y center(s)
image: 2-dimensional image
OPTIONAL INPUTS:
calg: Centering algorithm. Choose from iweight, gauss1, gauss2, none.
iweight = intensity-weighted center, computed independently
in both X and Y
gauss1 = gaussian fit, including a constant term, computed
independently in both X and Y
gauss2 = 2D gaussian fit, including a constant term
none = no centering
Default to iweight.
cbox: Centering box width. Default to 7.
cmaxiter: Maximum number of iterations for centering algorithm.
Default to 10.
cmaxshift: Maximum center shift. If this shift is exceeded in either
X or Y, then return the center position passed in XCEN, YCEN.
A value of 0 imposes no maximum shift. Default to 3.
fwhm: FWHM for gauss1 or gauss2 centering algorithms. If this is
a scalar, then the same value is used for both X and Y.
If this is a vector, then the first two elements are used
for X and Y respectively.
fixfw: If set and nonzero, then fix the FWHM for gauss1 or gauss2 fits.
ceps: Stop iterating when relative shifts in both X and Y are less
than this value. Default to 0.
OUTPUTS:
xcen: Re-centered X position (modified).
ycen: Re-centered X position (modified).
OPTIONAL OUTPUS:
qmaxshift: Return 1 if maximum shift was reached in either X or Y.
Return 0 otherwise.
PROCEDURES CALLED:
curvefit()
djs_ceil()
djs_floor()
gauss2dfit()
REVISION HISTORY:
01-Dec-1996 Written by D. Schlegel, Durham.
10-Aug-1998 Added option for calg='gauss2' (DJS).
01-Jun-2000 Major revisions: change XYCEN to XCEN,YCEN; remove use
of FITS headers; make IDL 5 complient (DJS).
(See pro/djsphot/djs_photcen.pro)
NAME:
djs_photfrac
PURPOSE:
Create a list of pixel numbers and their fractional contribution to
an annular region.
CALLING SEQUENCE:
djs_photfrac, xcen, ycen, Rvec, xdimen=, ydimen=, $
[ xPixNum=, yPixNum=, pixnum=, fracs=, fillfrac= ]
INPUTS:
xcen: X center(s)
ycen: Y center(s)
Rvec: Either a 2-element array with two radii to define an annulus,
or a scalar to define a circular aperature.
OPTIONAL INPUTS:
xdimen: Number of X pixels.
ydimen: Number of Y pixels.
OUTPUTS:
pixnum: Pixel number, 0-indexed, for referencing array using one index.
xPixNum: Pixel number in X, 0-indexed.
yPixNum: Pixel number in Y, 0-indexed.
fracs: Return value of covering fraction of the annulus
over the pixel number.
fillfrac: Ratio of returned pixel areas to the annulus area;
this ratio should equal 1.0 if the aperature falls completely
within the image boundaries
COMMENTS:
The total counts within this region is given by
totcounts = total( pData(pixnum) * fracs )
The area within this region is given by
area = total(fracs)
The average counts is given by
totcounts = total( pData(pixnum) * fracs ) / total(fracs)
To test for bad pixels, e.g. values greater than vmax, within
the aperature,
if (where(pData(pixnum) GT vmax) EQ -1) then <no bad values> $
else <bad values exist>
If no pixels within the given annulus are found, then return pixnum=-1.
BUGS:
- can wrap around on edge of you use PixNum. XPixNum,YPixNum do
not exhibit this problem
PROCEDURES CALLED:
djs_ceil()
djs_floor()
REVISION HISTORY:
Written D. Schlegel, 27 November 1996, Durham
Bug identified - 2 Nov 2000, D. Finkbeiner
(See pro/djsphot/djs_photfrac.pro)
NAME:
djs_photsky
PURPOSE:
Compute the sky value within an annulus.
At present, fractional pixels are not treated properly; this is because
we need a sort routine that carries index numbers, such as NR indexx().
CALLING SEQUENCE:
skyval = djs_photsky( xcen, ycen, skyrad, image, $
[ salg=, srejalg=, smaxiter=, $
lorej=, hirej=, skyrms=, skyerr= ] )
INPUTS:
xcen: X center(s)
ycen: Y center(s)
skyrad: A 2-element array with two radii to define an annulus,
or a scalar to define a circular aperature, or undefined or 0
for no sky calculation
image: FITS data array, as read from readfits().
OPTIONAL INPUTS:
salg: Sky fitting algorithm. Choose from mean, median, mode, none.
Default to "mean" if SKYRAD is set, or "none" otherwise.
srejalg: Rejection algorithm. Choose from none, sigclip, pclip.
sigclip = sigma clipping; reject outliers that are
more than lorej*sigma below skyval or hirej*sigma
above skyval
pclip = percentile clipping; reject the lowest lorej
fraction and the highest hirej fraction of points
none = no rejection
Default to sigclip
smaxiter: Maximum number of srejalg iterations. Default to 10.
lorej: If srejalg="sigclip", then the number of standard deviations
below skyval to clip (default to 3.0).
If srejalg="pclip", then fraction of low pixels to clip
(default to 0.05).
hirej: If srejalg="sigclip", then the number of standard deviations
above skyval to clip (default to 3.0).
If srejalg="pclip", then fraction of high pixels to clip
(default to 0.05).
quick: Set to use quick_photfrac (much faster)
exact: Set to use exact_photfrac (slower)
OUTPUTS:
skyval: Sky value in counts per pixel.
skyrms: RMS of sky pixels about skyval, again in counts per pixel.
This assumes that each pixel is independent. The RMS
is computed for only the values that remain after all the
rejection iterations.
skyerr: The error in skyval assuming that each pixel is independent.
This is skyrms divided by the square root of the number of
pixels.
PROCEDURES CALLED:
djs_photfrac
REVISION HISTORY:
28-Nov-1996 Written by D. Schlegel, Durham.
01-Jun-2000 Major revisions: change XYCEN to XCEN,YCEN; remove use
of FITS headers; make IDL 5 complient (DJS).
(See pro/djsphot/djs_photsky.pro)
DJS_PLANCK returns the spectral radiance of a blackbody.
DESCRIPTION:
IDL function to return the spectral radiance of a blackbody,
i.e. the Planck curve, in units of either MJy/steradian (I_nu)
or watts/cm^2/steradian (nu_I_nu).
The blackbody temperature and either frequency (in icm or GHz)
or wavelength (in microns) are inputs to the function. The
routine also optionally returns the derivative with respect to
temperature, in units of MJy/sr/K or W/cm^2/sr/K.
CALLING SEQUENCE:
RESULT = DJS_PLANCK (temperature, nu_or_lambda [,dBdT] $
[,UNITS=units], [/MJY], [/WCM2])
ARGUMENTS (I = input, O = output, [] = optional):
RESULT O flt [arr] Spectral radiance at each wavelength.
Units: W/cm^2/sr/K if /WCM2 specified
MJy/sr if /MJY specfied
TEMPERATURE I flt Temperature of blackbody, in K.
NU_OR_LAMBDA I flt Frequency or wavelength at which to
calculate spectrum. Units are as
specified with UNITS keyword.
dBdT [O] flt [arr] Derivative of Planck with respect to
temperature.
UNITS [I] str 'Microns', 'icm', or 'GHz' to
identify units of NU_OR_LAMBDA. Only
first character is required. If
left out, default is 'microns'.
/MJY I key Sets output units to MJy/sr
/WCM2 I key Sets output units to W/cm^2/sr
WARNINGS:
1. One of /MJY or /WCM2 MUST be specified.
2. Routine gives incorrect results for T < 1 microKelvin and
wavelengths shortward of 1.e-10 microns. (So sue me).
EXAMPLE:
To produce a 35 K spectrum in MJy/sr at 2, 4, 6, 8, 10 microns:
wavelength = 2. + 2.*findgen(5)
temp = 35.
blackbody = djs_planck(temp, wavelength, units='micron', /mjy)
One could also get back the derivative by including it in the
call:
blackbody = djs_planck(temp, wavelength, deriv, units='m', /mjy)
#
COMMON BLOCKS:
None
PROCEDURE (AND OTHER PROGRAMMING NOTES):
Identifies units using the UNITS keyword, then converts the
supplied independent variable into microns to evaluate the
Planck function. Uses Rayleigh-Jeans and Wien approximations
for the low- and high-frequency end, respectively. Reference:
Allen, Astrophysical Quantities, for the Planck formula.
PERTINENT ALGORITHMS, LIBRARY CALLS, ETC.:
None
MODIFICATION HISTORY:
Written by Rich Isaacman, General Sciences Corp. 17 April 1991
Revised by RBI 27 Jan 1992 to use updated fundamental constants
(SPR 9449)
Revised by RBI 29 Jan 1992 to calculate derivatives only when
necessary
Revised by RBI 3 Feb 1992 to redimension output to a scalar if only
a single wavelength is supplied (SPR 9459)
Revised by RBI 6 Mar 92 to return either MJy/sr or (!) W/cm^2/sr
Revised by RBI 1 Jun 92 to fix single-wavelength failure when no
derivative is requested (SPR 9738), and to use MESSAGE.
RBI corrected error in derivative calculation SPR 9817 (17 Jul 92)
RBI corrected error in Wien and RJ tails SPR 10392 (24 Dec 92)
but didn't get it quite right (Piper/Kryszak, 28-Dec-92)
Revised by David Schlegel 10-Mar-1999 to allow calling with temperature
and/or wavelength as a vector; converted to IDL-5; renamed from
PLANCK() to DJS_PLANCK(). Note that this code was copied from
the COBE analysis software.
SPR 9616
.TITLE
Routine DJS_PLANCK
(See pro/dust/djs_planck.pro)
NAME: djs_plot PURPOSE: Modified version of PLOT CALLING SEQUENCE: djs_plot, [x,] y INPUT: x: y: OUTPUTS: COMMENTS: Pass COLOR, PSYM, and SYMSIZE to djs_oplot. PROCEDURES CALLED: djs_oplot TeXtoIDL() REVISION HISTORY: Written by D. Schlegel, 27 September 1997, Durham
(See pro/plot/djs_plot.pro)
NAME: djs_plotlimitbox PURPOSE: Plot a box that bounds the given limits in X and Y. CALLING SEQUENCE: djs_plotlimitbox, xrange, yrange INPUT: xrange: Range in X yrange: Range in Y OUTPUTS: PROCEDURES CALLED: djs_oplot REVISION HISTORY: Written by D. Schlegel, 11 Dec 1998, Princeton
(See pro/plot/djs_plotlimitbox.pro)
NAME: djs_posmod PURPOSE: Return the non-negative modulus x % y, in the range [0,y). CALLING SEQUENCE: result = djs_posmod(x, y) INPUTS: xvalue OUTPUTS: result PROCEDURES CALLED: REVISION HISTORY: Written D. Schlegel, 15 May 1997, Durham
(See pro/math/djs_posmod.pro)
NAME:
DJS_READCOL
PURPOSE:
Read a free-format ASCII data file with columns of data into IDL
variables. Lines of data not meeting the specified format (e.g.
comments) are ignored. Columns may be separated by commas or spaces.
Use READFMT to read a fixed-format ASCII file. Use RDFLOAT for
much faster I/O (but less flexibility).
CALLING SEQUENCE:
DJS_READCOL, name, v1, [ v2, v3, v4, v5, ... v25 ,
FORMAT = , /DEBUG , /SILENT , SKIPLINE = , NUMLINE = ]
INPUTS:
NAME - Name of ASCII data file, scalar string. In VMS, an extension of
.DAT is assumed, if not supplied.
OPTIONAL INPUT KEYWORDS:
FORMAT - scalar string containing a letter specifying an IDL type
for each column of data to be read. Allowed letters are
A - string data, B - byte, D - double precision, F- floating
point, I - integer, L - longword, and X - skip a column.
Columns without a specified format are assumed to be floating
point. Examples of valid values of FMT are
'A,B,I' ;First column to read as 6 character string, then
1 column of byte data, 1 column integer data
'L,L,L,L' ;Four columns will be read as longword arrays.
' ' ;All columns are floating point
If a FORMAT keyword string is not supplied, then all columns are
assumed to be floating point.
SILENT - Normally, READCOL will display each line that it skips over.
If SILENT is set and non-zero then these messages will be
suppressed.
DEBUG - If this keyword is non-zero, then additional information is
printed as READCOL attempts to read and interpret the file.
SKIPLINE - Scalar specifying number of lines to skip at the top of file
before reading. Default is to start at the first line.
NUMLINE - Scalar specifying number of lines in the file to read.
Default is to read the entire file
OUTPUTS:
V1,V2,V3,...V15 - IDL vectors to contain columns of data.
Up to 25 columns may be read. The type of the output vectors
are as specified by FORMAT.
EXAMPLES:
Each row in a file POSITION.DAT contains a star name and 6 columns
of data giving an RA and Dec in sexigesimal format. Read into IDL
variables. (NOTE: The star names must not contain internal spaces.)
IDL> FMT = 'A,I,I,F,I,I,F'
IDL> READCOL,'POSITION',F=FMT,name,hr,min,sec,deg,dmin,dsec
The HR,MIN,DEG, and DMIN variables will be integer vectors.
Alternatively, all except the first column could be specified as
floating point.
IDL> READCOL,'POSITION',F='A',name,hr,min,sec,deg,dmin,dsec
To read just the variables HR,MIN,SEC
IDL> READCOL,'POSITION',F='X,I,I,F',HR,MIN,SEC
RESTRICTIONS:
This procedure is designed for generality and not for speed.
If a large ASCII file is to be read repeatedly, it may be worth
writing a specialized reader.
Columns to be read as strings must not contain spaces or commas,
since these are interpreted as column delimiters. Use READFMT
to read such files.
Numeric values are converted to specified format. For example,
the value 0.13 read with an 'I' format will be converted to 0.
PROCEDURES CALLED
GETTOK(), NUMLINES(), REPCHR(), STRNUMBER(), ZPARCHECK
REVISION HISTORY:
Written W. Landsman November, 1988
Modified J. Bloch June, 1991
(Fixed problem with over allocation of logical units.)
Added SKIPLINE and NUMLINE keywords W. Landsman March 92
Read a maximum of 25 cols. Joan Isensee, Hughes STX Corp., 15-SEP-93.
Call NUMLINES() function W. Lansdman Feb. 1996
(See pro/misc/djs_readcol.pro)
NAME:
djs_readilines()
PURPOSE:
Read selected lines of an ASCII file as one character string for each line.
If NHEAD is specified and greater than zero, then that number
of lines is read in first as header strings in HEAD.
CALLING SEQUENCE:
Data = djs_readilines( infile, indx=indx, [ nhead=nhead, Head=Head ] )
INPUT:
infile: Input file name
OPTIONAL INPUT:
nhead: Number of lines in header
indx: Line numbers to read (0-indexed); if not set, then
default to reading all data lines in their current order.
The indices start with 0 for the first data line.
OUTPUTS:
Data: Array of strings, one for each data line
OPTIONAL OUTPUTS:
Head: Array of strings, one for each header line
PROCEDURES CALLED:
REVISION HISTORY:
Written by D. Schlegel, 29 May 1997, Durham
(See pro/misc/djs_readilines.pro)
NAME: djs_readlines() PURPOSE: Read an ASCII file as one character string for each line. If NHEAD is specified and greater than zero, then that number of lines is read in first as header strings in HEAD. CALLING SEQUENCE: Data = djs_readlines( infile, [ nhead=nhead, Head=Head ] ) INPUT: infile: Input file name OPTIONAL INPUT: nhead: Number of lines in header OUTPUTS: Data: Array of strings, one for each data line OPTIONAL OUTPUTS: Head: Array of strings, one for each header line PROCEDURES CALLED: REVISION HISTORY: Written by D. Schlegel, 29 May 1997, Durham
(See pro/misc/djs_readlines.pro)
NAME: djs_readmany PURPOSE: Read many FITS 2-D images into a data cube. CALLING SEQUENCE: cube = djs_readmany( files, [hdr=] ) INPUTS: files: FITS file names (array of strings) OUTPUTS: cube: Data cube with dimensions [NAXIS1, NAXIS2, nfile] OPTIONAL OUTPUTS: hdr: Header for first image COMMENTS: Additional keywords are passed to the function READFITS(). At present, the output image is always typed FLOAT. PROCEDURES CALLED: readfits() REVISION HISTORY: 07-Jul-1999 Written by David Schlegel, Princeton.
(See pro/fits/djs_readmany.pro)
NAME:
djs_reject
PURPOSE:
Routine to reject points when doing an iterative fit to data.
CALLING SEQUENCE:
qdone = djs_reject(ydata, ymodel, outmask=, [ inmask=, $
sigma=, invvar=, upper=, lower=, maxdev=, $
maxrej=, groupsize=, groupdim=, grow=, /sticky ] )
INPUTS:
ydata - Data values
ymodel - Fit values
REQUIRED KEYWORDS:
outmask - Output mask, usually from previous calls to DJS_REJECT(),
set =1 for good points, =0 for bad points.
If /STICKY is set, then bad pixels accumulate in this mask
between calls. Otherwise, this mask is only used to determine
if the rejection iterations are complete (e.g., to set QDONE).
This keyword is required to be present, though need not be set.
OPTIONAL KEYWORDS:
inmask - Input mask, set =1 for good points, =0 for bad points;
bad points always have OUTMASK=0 also.
sigma - Errors in YDATA, used to reject based upon UPPER and LOWER.
invvar - Inverse variance in YDATA, used to reject based upon UPPER
and LOWER; cannot specify both SIGMA and INVVAR.
upper - Reject points with YDATA > YMODEL + UPPER * SIGMA.
lower - Reject points with YDATA < YMODEL - LOWER * SIGMA.
maxdev - Reject points with abs(YDATA - YMODEL) > MAXDEV.
maxrej - Maximum number of points to reject this iteration. If /STICKY
is set, then this number of points can be rejected per
iteration. If either GROUPDIM or GROUPSIZE is a vector,
then this quantity should be as well.
groupdim - Dimension along which to group the data; set to 1 to group
along the 1st dimension, 2 for the 2nd dimension, etc.
If YDATA has dimensions [100,200], then setting GROUPDIM=2
is equivalent to grouping the data with GROUPSIZE=100.
In either case, there are 200 groups, specified by [*,i].
groupsize - If this and MAXREJ are set, then reject a maximum of MAXREJ
points per group of GROUPSIZE points. If GROUPDIM is also
set, then this specifies sub-groups within that.
groupbadpix- Overrides the other groupsizes: This associates each
consectuive string of bad pixels as a group. And maxrej
is applied to each group of bad pixels.
***Unlikely to Work with Multi-Dimension Data***
sticky - If set, then points rejected in OUTMASK are kept rejected.
Otherwise, if a fit (YMODEL) changes between iterations,
points can alternate from being rejected to not rejected.
grow - Also nearest neighbors of rejected points (default 0)
OUTPUTS:
qdone - Set to 0 if YMODEL is not set (usually the first call to
this routine), or if the points marked as rejected in OUTMASK
changes; set to 1 when the same points are rejected as from
a previous call.
OPTIONAL OUTPUTS:
COMMENTS:
If neither SIGMA nor INVVAR are set, then a scalar value of SIGMA is
determined from the data points, excluding those points masked either
with INMASK or OUTMASK.
If the number of points rejected is limited with MAXREJ, then only the
worst points are rejected. The worst points are those with the largest
deviation in terms of sigma (if UPPER or LOWER are set), or the largest
number of multiples of MAXDEV from YMODEL (if MAXDEV is set).
For example, if this is a 2-D array with GROUPDIM=1, then loop over each
column of the data. If GROUPDIM=2, then loop over each row.
Note that UPPER, LOWER and MAXDEV can all be set.
EXAMPLES:
Construct an array of random numbers. Reject high outliers, rejecting
at most 1 point per iteration, for a maximum of 3 iterations:
ydata = randomn(123,1000)
ymodel = 0 * ydata
sigma = 0 * ydata + 1
outmask = 0
maxiter = 3
for iiter=0, maxiter do $
if djs_reject(ydata, ymodel, outmask=outmask, upper=3, $
maxrej=1, /sticky) then iiter = maxiter
Usually, one would want to re-fit YMODEL between rejection iterations.
The following does a weighted cubic fit to the data, but rejecting all
points that deviate by more than 2-sigma from the fit.
xdata = findgen(1000)
ydata = randomn(123,1000)
sigma = 0 * ydata + 1
iiter = 0
maxiter = 10
outmask = 0 * ydata + 1 ; Begin with all points good
while (NOT keyword_set(qdone) AND iiter LE maxiter) do begin
qdone = djs_reject(ydata, ymodel, outmask=outmask, upper=2, lower=2)
res = polyfitw(xdata, ydata, outmask/sigma^2, 2, ymodel)
iiter = iiter + 1
endwhile
BUGS:
Check case of no good points, or only 1 point with a value of 0
(which might confuse keyword_set()). ???
PROCEDURES CALLED:
djs_laxisnum()
REVISION HISTORY:
30-Aug-2000 Written by D. Schlegel, Princeton
11-Dec-2001 Slight changes to groupsize algorithm and add grow
(See pro/math/djs_reject.pro)
NAME:
djs_rgb_make
PURPOSE:
Creates JPEG from three images or FITS files
CALLING SEQUENCE:
djs_rgb_make, rimage, gimage, bimage, [ name=, origin=, scales=, $
nonlinearity=, satvalue=, rebinfactor=, overlay=, quality= ]
INPUTS:
rimage,gimage,bimage - Input 2-dimensional images or names of FITS files;
the dimensions of all images must agree
OPTIONAL KEYWORDS:
name - Name of the output JPEG file; default to 'test.jpg'
origin - Subtract these zero-point values from the input images
before any other scalings; default to [0,0,0]
scales - Multiplicative scaling for each image; default to [1,1,1]
nonlinearity- Nonlinearity constant, =0 for linear, =Inf for logarithmic;
default to 3
satvalue - Saturation value (before applying rescaling with SCALES, but
after applying ORIGIN) for which we should group pixels
into saturated "objects"; default to 100;
set to zero to disable
rebinfactor - Integer by which to rebin pixels in the x and y
directions; eg, a rebinfactor of 2 halves the number
of pixels in each direction and quarters the total
number of pixels in the image
overlay - Optional overlay image, which must be dimensionsed as
[NX/REBINFACTOR,NY/REBINFACTOR,3]
quality - Quality for WRITE_JPEG; default to 75 per cent
OUTPUTS:
COMMENTS:
This routine is based upon Nick Wherry's code NW_RGB_MAKE.
The main difference is that saturated pixels are grouped into
contiguous "objects", which are then assigned a color based upon
the sum of all the pixels in that object.
The nonlinearity function applied is
RIMAGE = RIMAGE * asinh(b*r)/(b*r)
GIMAGE = GIMAGE * asinh(b*r)/(b*r)
BIMAGE = BIMAGE * asinh(b*r)/(b*r)
where "b" is the input NONLINEARITY parameter and we define at each pixel
r = (RIMAGE + GIMAGE + BIMAGE)
Note that there are two types of saturation. The first is that objects
can be considered saturated if they exceed SATVALUE in any of the input
images. For such objects, contiguous saturated pixels are combined into
one "object" with the mean color of all included pixels.
The second type of saturation is of the RGB image. This saturation is
dealt with at the pixel level, and each pixel rescaled in all three images
such that the brightest color hits the JPEG limit (of 255), but the
colors (ratios between the RGB images) are preserved.
EXAMPLES:
BUGS:
REVISION HISTORY:
10-May-2004 - Written by D. Schlegel, Princeton;
based upon Nick Wherry's code NW_RGB_MAKE
(See pro/rgbcolor/djs_rgb_make.pro)
NAME:
djs_selectlines
PURPOSE:
Select the line numbers specified by INDX of a file, and print either
to the standard output or to another file.
This is not yet optimized for very large files, as it will read in
all of the requested lines (though not all the lines) into memory first.
CALLING SEQUENCE:
djs_selectlines, infile, [ indx=indx, nhead=nhead, outfile=outfile ]
INPUTS:
infile: Input file name
OPTIONAL INPUTS:
indx: Array of line numbers to select (0-indexed); default to all.
The indices start with 0 for the first data line.
nhead: Number of lines in header
outfile: Output file name; if not set then print to terminal
OUTPUTS:
PROCEDURES CALLED:
djs_readilines()
REVISION HISTORY:
Written by D. Schlegel, 25 September 1997, Durham
(See pro/misc/djs_selectlines.pro)
NAME:
djs_sfit
PURPOSE:
Surface-fitting code to tabulated data (optionally with errors).
CALLING SEQUENCE:
acoeff = djs_sfit( fval, xval, yval, degreex, degreey, $
[ sqivar=, yfit= ] )
INPUTS:
fval - Function values at XVAL,YVAL.
xval - X coordinate values
yval - Y coordinate values
degreex - Degree of polynomial fit in X; 1 for linear, 2 for quadratic
degreey - Degree of polynomial fit in Y; 1 for linear, 2 for quadratic
OPTIONAL INPUTS:
sqivar - Inverse sigma, which are the weights
OUTPUTS:
acoeff - Fit coefficients as [DEGREEX+1,DEGREEY+1] array
OPTIONAL OUTPUTS:
yfit - Fit values
COMMENTS:
EXAMPLES:
Create a random 2-dimensional field with a gradient in the X direction,
and fit to a quadratic function in both X and Y:
IDL> xval = dindgen(100) # replicate(1,100) / 100.
IDL> yval = replicate(1,100) # dindgen(100) / 100.
IDL> image = smooth(randomu(1234,100,100),11,/edge) + 0.2*xval^2
IDL> acoeff = djs_sfit(image,xval,yval,2,2,yfit=yfit)
Display the original image, and then the residual between that
image and the fit:
IDL> atv, image
IDL> atv, image - yfit
BUGS:
PROCEDURES CALLED:
INTERNAL SUPPORT ROUTINS:
REVISION HISTORY:
25-Oct-2002 Written by David Schlegel, Princeton.
(See pro/image/djs_sfit.pro)
NAME:
djs_unlockfile
PURPOSE:
Unlock a file if locked with DJS_LOCKFILE().
CALLING SEQUENCE:
djs_unlockfile, filename, [lun= ]
INPUT:
filename: File name
OPTIONAL INPUTS:
lun: If this argument exists, then close the file associated
with this LUN number. This is useful if FILENAME has
been opened with DJS_LOCKFILE().
OUTPUTS:
COMMENTS:
We use a lock file, which is either a symbolic link or a file with
a single byte written to it, to indicate that FILENAME has been
locked by DJS_LOCKFILE(). This routine deletes that file.
BUGS:
PROCEDURES CALLED:
REVISION HISTORY:
30-Apr-2000 Written by D. Schlegel, APO
(See pro/misc/djs_unlockfile.pro)
NAME: djs_xyouts PURPOSE: Modified version of XYOUTS CALLING SEQUENCE: djs_xyouts INPUT: OUTPUTS: COMMENTS: Allows COLOR, and CHARSIZE to be vectors. Also allows COLOR to be string descriptions of eight possible colors. If string descriptors are used, then load a basic 8-color color table. PROCEDURES CALLED: djs_icolor() TeXtoIDL() REVISION HISTORY: 16-Apr-2000 Written by D. Schlegel, Princeton
(See pro/plot/djs_xyouts.pro)
NAME: dlookbackdz PURPOSE: Compute differential lookback time dt/dz (for c/H_0=1). CALLING SEQUENCE: dtdz= dlookbackdz(z,OmegaM,OmegaL) INPUTS: z - redshift or vector of redshifts OmegaM - Omega-matter at z=0 OmegaL - Omega-Lambda at z=0 OPTIONAL INPUTS: KEYWORDS OUTPUTS: differential lookback time per unit redshift, units of the Hubble time 1/H_0 COMMENTS: BUGS: May not work for pathological parts of the OmegaM-OmegaL plane. EXAMPLES: PROCEDURES CALLED: REVISION HISTORY: 2001-May-12 Written by Hogg (NYU)
(See pro/cosmography/dlookbackdz.pro)
NAME:
dotproduct_sphere
PURPOSE:
Compute the cosign of the angle between two unit vectors on the
sphere. This formula is from Jackson, pg 101. (Or see my notes
of 6 Dec 92). The angles must be in the following ranges:
0 <= phi < 360
0 <= theta <= 180
where theta=0 corresponds to the N pole, and theta=180 is the S pole.
If you want the dot product between RA and DEC coordinates,
pass the following arguments (in radians):
RA1, DEC1+90, RA2, DEC2+90
CALLING SEQUENCE:
dotproduct_sphere( phi1, theta1, phi2, theta2, [/degrees, /hrdeg] )
INPUTS:
phi1: RA of first point(s) in radians
theta1: DEC of first point(s) in radians
phi2: RA of second point(s) in radians
theta2: DEC of second point(s) in radians
OPTIONAL INPUTS:
degrees: If set, then all angles are in degrees
hrdeg: If se, then RA angles in hours and DEC angles in degrees
OUTPUTS:
cosgamma: Cosine of the angle between the two positions
(See pro/coord/dotproduct_sphere.pro)
NAME: dpf_nest2ring PURPOSE: Convert healpix nested pixel number to ring pixel number CALLING SEQUENCE: dpf_nest2ring, nside, ipnest, ipring INPUTS: nside - healpix nside ipnest - nested pixel number OUTPUTS: ipring - ring pixel number EXAMPLES: COMMENTS: Usage is same as Hivon's nest2ring, only this is 4 times as fast. REVISION HISTORY: 2003-Dec-04 Written by Douglas Finkbeiner, Princeton
(See pro/healpix/dpf_nest2ring.pro)
NAME:
dpf_pix2ang_nest
PURPOSE:
Compute coordinates for HEALPix pixel numbers, nested order
CALLING SEQUENCE:
dpf_pix2ang_nest, nside, ipix, theta, phi, double=double
INPUTS:
nside - healpix nside
ipix - pixel numbers
OUTPUTS:
theta - angle from north pole [radians]
phi - longitude angle [radians]
EXAMPLES:
COMMENTS:
Calling syntax is same as pix2ang_nest and agrees to machine
precision.
This routine has somewhat better performance when called for the
full sky than pix2ang_nest.
REVISION HISTORY:
2004-Jun-08 Written by Douglas Finkbeiner, Princeton
(See pro/healpix/dpf_pix2ang_nest.pro)
NAME:
dpf_pix2ang_ring
PURPOSE:
Compute coordinates for HEALPix pixel numbers
CALLING SEQUENCE:
dpf_pix2ang_ring, nside, ipix, theta, phi, double=double
INPUTS:
nside - healpix nside
ipix - pixel numbers
OUTPUTS:
theta - angle from north pole [radians]
phi - longitude angle [radians]
EXAMPLES:
COMMENTS:
Calling syntax is same as pix2ang_ring and agrees to machine
precision.
This routine has somewhat better performance when called for the
full sky than pix2ang_ring.
REVISION HISTORY:
2003-Dec-06 Written by Douglas Finkbeiner, Princeton
(See pro/healpix/dpf_pix2ang_ring.pro)
NAME: dpropdisdz PURPOSE: Compute differential proper line-of-sight distances (for c/H_0=1). CALLING SEQUENCE: dDdz= dpropdisdz(z,OmegaM,OmegaL) INPUTS: z - redshift or vector of redshifts OmegaM - Omega-matter at z=0 OmegaL - Omega-Lambda at z=0 OPTIONAL INPUTS: KEYWORDS OUTPUTS: differential proper distance DD/dz in units of the Hubble length c/H_0 COMMENTS: BUGS: May not work for pathological parts of the OmegaM-OmegaL plane. EXAMPLES: PROCEDURES CALLED: dcomdisdz() REVISION HISTORY: 25-Jun-2000 Written by Hogg (IAS)
(See pro/cosmography/dpropdisdz.pro)
NAME: dpropmotdisdz PURPOSE: Compute differential proper motion distance dD/dz for c=H_0=1. CALLING SEQUENCE: dDdz= dpropmotdisdz(z,OmegaM,OmegaL) INPUTS: z - redshift or vector of redshifts OmegaM - Omega-matter at z=0 OmegaL - Omega-Lambda at z=0 OPTIONAL INPUTS: KEYWORDS OUTPUTS: differential proper motion distance in units of the Hubble length c/H_0 COMMENTS: BUGS: May not work for pathological parts of the OmegaM-OmegaL plane. EXAMPLES: PROCEDURES CALLED: propmotdis REVISION HISTORY: 2001-Mar-12 Written by Hogg (NYU)
(See pro/cosmography/dpropmotdisdz.pro)
NAME:
dustplot
PURPOSE:
Make a PostScript plot of the dust maps in a rectalinear projection.
CALLING SEQUENCE:
dustplot
INPUTS:
OPTIONAL INPUTS:
latrange: Latitude range; default to [-30,30]
lonrange: Longitude range; default to [-30,30]
rangestr: 3-element string with plot limits and units;
default to ['0.0', '1.0', 'A(B)']
Valid entries for RANGESTR[2] are:
A(B)
A(I)
E(B-V)
I100
T
csys: Coordinate system:
'gal': Galactic coordinates (default)
'equ1950': Equatorial coordinates, epoch 1995
'equ2000': Equatorial coordinates, epoch 2000
'ecl': Ecliptic coordinates
tspace: Tick spacing for grid overlay; default to 5 deg
pixpdeg: Pixels per degree; default to 500 pixels across the image
filename: Output file name; default to "test.ps"
encap: If set, then produce encapsulated PostScript
ctnum: Color table number; default to 23 (Purple-Red + Stripes)
invert: Invert color map
colorbar: Plot color bar on bottom of page
nonames: If set, then disable the title string on the top,
and our names on the bottom
OUTPUTS:
PROCEDURES CALLED:
adstring()
djs_laxisgen()
dust_getval()
euler
jprecess
REVISION HISTORY:
Written D. Schlegel, 18 June 1999, Princeton
(See pro/dust/dustplot.pro)
NAME:
dust_getmap
PURPOSE:
Reproject dust map to projection described by a FITS header
CALLING SEQUENCE:
image=dust_getmap(hdr, mapname, ipath=, bhpath=)
INPUTS:
hdr - FITS astrometric header. Must be parsed properly by extast
mapname - one of the following (case insensitive)
BH : Burstein-Heiles 4*E(B-V)
I100: 100-micron map in MJy/Sr
X : X-map, temperature-correction factor
T : Temperature map in degrees Kelvin for n=2 emissivity
IX : Temperature-corrected 100-micron map in MJy/Sr
Ebv : E(B-V) in magnitudes
mask: 8-bit mask
OPTIONAL INPUTS:
ipath - path for dust maps; default is $DUST_DIR/maps
bhpath - path name for BH maps
OUTPUTS:
image - reprojected dust/IRAS/whatever image
EXAMPLES:
To read in an halpha map, then generate a dust map in the same
projection:
halpha = readfits('Halpha.fits', hdr)
dust = dust_getmap(hdr, 'Ebv')
COMMENTS:
Params ipath and bhpath are passed to dust_getval.
Keywords /noloop and /interp are always set.
The other keywords of dust_getval have no meaning in this
context.
REVISION HISTORY:
2003-Jan-30 Written by Douglas Finkbeiner, Princeton
2003-Feb-07 Precess headers if necessary
(See pro/dust/dust_getmap.pro)
NAME:
dust_getval
PURPOSE:
Read values from BH files or our dust maps.
CALLING SEQUENCE:
value = dust_getval( [ gall, galb, infile=infile, skipline=skipline, $
outfile=outfile, map=map, interp=interp, noloop=noloop, verbose=verbose, $
ipath=ipath, bhpath=bhpath ] )
INPUTS:
OPTIONAL INPUTS:
gall: Galactic longitude(s) in degrees
galb: Galactic latitude(s) in degrees
map: Set to one of the following (default is 'Ebv'):
BH : Burstein-Heiles 4*E(B-V)
I100: 100-micron map in MJy/Sr
X : X-map, temperature-correction factor
T : Temperature map in degrees Kelvin for n=2 emissivity
IX : Temperature-corrected 100-micron map in MJy/Sr
Ebv : E(B-V) in magnitudes
mask: 8-bit mask
infile: If set, then read GALL and GALB from this file
skipline: Number of lines to skip at the top of the input file
outfile: If set, then write results to this file
interp: Set this flag to return a linearly interpolated value
from the 4 nearest pixels.
This is disabled if map='mask'.
noloop: Set this flag to read all values at once without a FOR loop.
This is a faster option for reading a large number of values,
but requires reading an entire FITS image into memory.
(Actually, the smallest possible sub-image is read.)
verbose: Set this flag for verbose output, printing pixel coordinates
and map values. Setting NOLOOP disables this option.
ipath: Path name for dust maps; default to path set by the
environment variable $DUST_DIR/maps, or to the current
directory.
bhpath: Path name for BH maps
OUTPUTS:
value: Value(s) from Lambert-projection maps.
COMMENTS:
These data are based upon the following paper:
"Maps of Dust IR Emission for Use in Estimation of Reddening
and CMBR Foregrounds", Schlegel, D., Finkbeiner, D., & Davis, M.,
ApJ, 1998, 500, 525.
Either the coordinates GALL and GALB must be set, or these coordinates
must exist in the file INFILE. Output is written to the variable VALUE
and/or the file OUTFILE.
EXAMPLES:
Read the reddening value E(B-V) at Galactic (l,b)=(12,+34.5),
interpolating from the nearest 4 pixels, and return result in VALUE.
> value = dust_getval(12, 34.5, /interp)
Read the temperature map at positions listed in the file 'dave.in',
interpolating from the nearest 4 pixels, and output to file 'dave.out'.
The path name for the temperature maps is '/u/schlegel/'.
> value = dust_getval(map='T', ipath='/u/schlegel/', /interp, $
infile='dave.in', outfile='dave.out')
DATA FILES FOR SFD MAPS:
SFD_dust_4096_ngp.fits
SFD_dust_4096_sgp.fits
SFD_i100_4096_ngp.fits
SFD_i100_4096_sgp.fits
SFD_mask_4096_ngp.fits
SFD_mask_4096_sgp.fits
SFD_temp_ngp.fits
SFD_temp_sgp.fits
SFD_xmap_ngp.fits
SFD_xmap_sgp.fits
DATA FILES FOR BH MAPS:
hinorth.dat
hisouth.dat
rednorth.dat
redsouth.dat
PROCEDURES CALLED:
bh_rdfort()
djs_int2bin()
readcol
wcs_getval()
REVISION HISTORY:
25-Sep-1997 Written by David Schlegel, Durham
19-Jan-1998 DJS - Modified for general release.
30-Mar-1998 DJS - Modified to read SGP mask file for b<0, since it was
incorrectly reading the NGP mask.
19-May-1998 DJS - Subscripts modified to IDL 5 convention.
30-Jul-1998 DJS - Added default file path names for any users at Princeton
or at Berkeley.
18-Mar-1999 DJS - Allow call with GALL=0 or GALB=0.
31-Mar-1999 DJS - Modified to use wcs_getval() instead of lambert_getval()
(See pro/dust/dust_getval.pro)
NAME:
dust_intfilter
PURPOSE:
Integrate the extinction curve over a given source function + filter curve.
CALLING SEQUENCE:
avec = dust_intfilter( ixval, ffilename=, sfilename=, [ atmfilename=, $
rv=, anorm=, dlam=, zsource=, /debug ] )
INPUTS:
ixval - Temperature-corrected 100-micron flux (IX) from SFD maps,
in MJy/sr (scalar or vector).
REQUIRED KEYWORDS:
ffilename - ASCII file with wavelengths in Ang (1st column) and throughput
(2nd column) for the filter response curve.
sfilename - ASCII file with wavelengths in Ang (1st column) and flux in
f_lambda (2nd column) for the source function. Note that
since we assume f_lambda (flux/Ang), we multiply this
by one power of the wavelength to convert to a flux in
photon number per Angstrom.
OPTIONAL KEYWORDS:
atmfilename- ASCII file with wavelengths in Ang (1st column) and magnitudes
of atmospheric extinction (2nd column). If specified,
then the filter response is multiplied by 10^(-ATM/2.5).
rv - Extinction curve parameter R_V; default to 3.1.
anorm - Normalization factor for multiplying IX to obtain
extinction at 1 micron; default to SFD normalization
of (1.319)*(0.0184) mag/(MJy/sr).
dlam - Spacing of numeric integration in Angstroms; default
to 1 Ang.
zsource - Redshift of source; default to 0.
debug - If set, then make debugging plots with SPLOT.
OUTPUTS:
avec - Extinction in magnitudes (same dimensions as IXVAL).
COMMENTS:
The Galactic extinction curve is that from O'Donnell (1994)
and Cardelli, Clayton & Mathis (1989).
The integrations (and optional debugging plots) are limited to
the wavelength range within which the filter curve is positive-valued.
The filter curve, source function, and atmospheric extinction curve
are cached between calls. If the same file is specified on a
subsequent call, then those cached values are used.
PROCEDURES CALLED:
ext_odonnell()
numlines()
readcol
DATA FILES:
REVISION HISTORY:
01-Dec-2002 Written by D. Schlegel, Princeton
(See pro/dust/dust_intfilter.pro)
NAME:
dust_sdssfilter
PURPOSE:
Integrate the extinction curve over a selection of source fuctions and
the SDSS filters.
CALLING SEQUENCE:
aval = dust_sdssfilter( ixval, [ source=, zsource=, rv=, anorm=, dlam=, /debug ] )
INPUTS:
ixval - Temperature-corrected 100-micron flux (IX) from SFD maps,
in MJy/sr [NDATA].
OPTIONAL INPUTS:
source - Source function. Options are:
'Fstar': Hot F-star model from Kurucz at T_eff=7000K
'Galaxy': SDSS mean galaxy spectrum
'QSO': SDSS mean QSO spectrum
Default to 'Galaxy'.
zsource - Redshift of source; default to 0.
rv - Extinction curve parameter R_V; default to 3.1.
anorm - Normalization factor for multiplying IX to obtain
extinction at 1 micron; default to SFD normalization
of (1.319)*(0.0184) mag/(MJy/sr).
dlam - Spacing of numeric integration in Angstroms; default
to 1 Ang.
debug - If set, then make debugging plots with SPLOT.
old - If set, then use the original SDSS filters curves
used for the SFD paper.
OUTPUTS:
avec - Extinction in magnitudes [5,NDATA].
COMMENTS:
EXAMPLES:
Given a set of Galactic coordinates L,B, evaluate the SFD-predicted
extinction in the 5 SDSS filters for a source with the spectrum of an F star:
IDL> aval = dust_sdssfilter(dust_getval(l, b, map='IX', /interp), source='Fstar')
Compare the predicted extinction at a given dust value of IX=10. for two
different values of R_V (5.5 vs. 3.1):
IDL> print, dust_sdssfilter(10., rv=5.5) / dust_sdssfilter(10.)
PROCEDURES CALLED:
dust_intfilter()
mrdfits()
sxpar()
DATA FILES:
$IDLUTILS_DIR/data/filters/kurucz_fstar.dat
$IDLUTILS_DIR/data/filters/kpno_atmos.dat
$IDLUTILS_DIR/data/filters/sdss_1994_u_noatm.dat
$IDLUTILS_DIR/data/filters/sdss_1994_g_noatm.dat
$IDLUTILS_DIR/data/filters/sdss_1994_r_noatm.dat
$IDLUTILS_DIR/data/filters/sdss_1994_i_noatm.dat
$IDLUTILS_DIR/data/filters/sdss_1994_z_noatm.dat
$IDLUTILS_DIR/data/filters/sdss_jun2001_u_atm.dat
$IDLUTILS_DIR/data/filters/sdss_jun2001_g_atm.dat
$IDLUTILS_DIR/data/filters/sdss_jun2001_r_atm.dat
$IDLUTILS_DIR/data/filters/sdss_jun2001_i_atm.dat
$IDLUTILS_DIR/data/filters/sdss_jun2001_z_atm.dat
$IDLUTILS_DIR/data/filters/sdss_meangalaxy_52223.dat
DATA FILES:
REVISION HISTORY:
01-Dec-2002 Written by D. Schlegel, Princeton
(See pro/dust/dust_sdssfilter.pro)
NAME:
efc2d
PURPOSE:
Calculate a B-spline in the least-squares sense
based on two variables: x which is sorted and spans a large range
where bkpts are required
and y which can be described with a low order
polynomial
CALLING SEQUENCE:
coeff = efc2d(x, y, z, invsig, npoly, nbkptord, fullbkpt)
INPUTS:
x - data x values
y - data y values
z - data z values
invsig - inverse error array of y
npoly - Order of polynomial (as a function of y)
nbkptord - Order of b-splines (4 is cubic)
fullbkpt - Breakpoint vector returned by efc
RETURNS:
coeff - B-spline coefficients calculated by efc
OUTPUTS:
OPTIONAL KEYWORDS:
OPTIONAL OUTPUTS:
COMMENTS:
This IDL proc is an extension of efcmn
EXAMPLES:
x = findgen(100)
y = randomu(200, 100, /normal)
zmodel = 10.0*sin(x/10.0) + y
z = zmodel + randomu(100,100,/normal)
invsig = fltarr(100) + 1.0
fullbkpt = [-3.0,-2.0,-1.0,findgen(11)*10.0,101.0,102.0,103.0]
npoly = 2L
nbkptord = 4L
coeff = efc2d(x, y, z, invsig, npoly, nbkptord, fullbkpt)
zfit = bvalu2d(x, y, fullbkpt, coeff)
PROCEDURES CALLED:
efc_idl in src/slatec/idlwrapper.c
which wraps to efc.o in libslatecidl.so
REVISION HISTORY:
10-Mar-2000 Written by Scott Burles, FNAL
(See pro/slatec/efc2d.pro)
NAME:
efcmn
PURPOSE:
Calculate a B-spline in the least-squares sense
CALLING SEQUENCE:
coeff = efcmn(x, y, invsig, nord, fullbkpt)
INPUTS:
x - data x values
y - data y values
invsig - inverse error array of y
nord - Order of b-splines (default 4: cubic)
fullbkpt - Breakpoint vector returned by efc
RETURNS:
coeff - B-spline coefficients calculated by efc
OUTPUTS:
OPTIONAL KEYWORDS:
OPTIONAL OUTPUTS:
COMMENTS:
This IDL proc mimics efc.f
EXAMPLES:
x = findgen(100)
y = randomu(100,100)
invsig = fltarr(100) + 1.0
fullbkpt = [-3.0,-2.0,-1.0,findgen(12)*10.0,101.0,102.0,103.0]
nord = 4L
coeff = efcmn(x, y, invsig, nord, fullbkpt)
xfit = findgen(10)*10.0
yfit = slatec_bvalu(xfit, fullbkpt, coeff)
PROCEDURES CALLED:
efc_idl in src/slatec/idlwrapper.c
which wraps to efc.o in libslatecidl.so
REVISION HISTORY:
10-Mar-2000 Written by Scott Burles, FNAL
(See pro/slatec/efcmn.pro)
NAME:
embed_stamp
PURPOSE:
Add to one image the parts which are overlapped by a second image
CALLING SEQUENCE:
embed_stamp,full_image,stamp_image,xlo,ylo
INPUTS:
full_image - [full_nx, full_ny] image to add to
stamp_image - [stamp_nx, stamp_ny] image to add by
xlo, ylo - position in full_image of lower left corner of lower left
pixel of stamp
OUTPUTS:
full_image - resulting image
REVISION HISTORY:
2003-01-20 Written - Blanton
(See pro/image/embed_stamp.pro)
NAME:
em_pca
PURPOSE: (one line)
Perform E-M PCA to get first k principal components
DESCRIPTION:
Uses Sam Roweis' Expectation Maximization version of PCA to
efficiently find the first k principal components for a
distribution in p (>k) dimensions. The procedure guesses an
initial set of eigenvectors (stored the in [p,k] dimensional
matrix "eigenvec") and applies the following iteration to the
[p,N] dimensional "data":
hidden= ( eigenvec^T . eigenvec )^{-1} . eigenvec^T . data
eigenvec= data . hidden^T . (hidden . hidden^T)^{-1}
From:
Neural Information Processing Systems 10 (NIPS'97) pp.626-632
available at:
http://www.cs.toronto.edu/~roweis/papers/empca.ps.gz
CATEGORY:
Mathematical
CALLING SEQUENCE:
em_pca, data, k, eigenvec, hidden [, tol=, maxiter=, niter=, /verbose]
INPUTS:
data - [p,N] data to be PCAed
k - number of eigenvectors desired (<p)
OPTIONAL INPUT PARAMETERS:
tol - tolerance of convergence (default 0.)
maxiter - maximum number of iterations (default 20)
KEYWORD PARAMETERS:
/verbose - verbose output
/nofix - don't do the final real PCA
OUTPUTS:
eigenvec - [p,k] matrix of k leading eigenvectors
hidden - [k] matrix of "hidden" variables (the lower dimensional
representation of the data)
OPTIONAL OUTPUTS:
niter - number of iterations used
COMMON BLOCKS:
SIDE EFFECTS:
BUGS:
Somewhat untested.
RESTRICTIONS:
Does not implement Sam's Sensible-PCA procedure
PROCEDURE:
MODIFICATION HISTORY:
2003-01-26 - Written by Michael Blanton (NYU)
(See pro/math/em_pca.pro)
NAME:
em_pca_sparse_matrix
PURPOSE: (one line)
Perform E-M PCA to get first k principal components of large sparse matrix
DESCRIPTION:
Uses Sam Roweis's algorithm (described in em_pca.pro in detail)
but takes an initial sparse matrix rather than a data set as
input. (in the lle_sm format)
CATEGORY:
Mathematical
CALLING SEQUENCE:
em_pca_sparse_matrix, matrix, k, eigenvec, hidden [, tol=, $
maxiter=, niter=, /verbose]
INPUTS:
matrix - sparse matrix to be PCAd
k - number of eigenvectors desired (<p)
OPTIONAL INPUT PARAMETERS:
tol - tolerance of convergence (default 0.)
maxiter - maximum number of iterations (default 20)
KEYWORD PARAMETERS:
/verbose - verbose output
/nofix - don't do the final real PCA
OUTPUTS:
eigenvec - [p,k] matrix of k leading eigenvectors
OPTIONAL OUTPUTS:
niter - number of iterations used
COMMON BLOCKS:
SIDE EFFECTS:
BUGS:
not completed yet
RESTRICTIONS:
Does not implement Sam's Sensible-PCA procedure
PROCEDURE:
MODIFICATION HISTORY:
2003-01-26 - Written by Michael Blanton (NYU)
(See pro/math/em_pca_sparse_matrix.pro)
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(/Traceback, /Error)
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', /Traceback)
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.
(See pro/psconfig/error_message.pro)
NAME: etalambda_to_radec PURPOSE: convert from eta, lambda (SDSS survey coordinates) to RA, Dec CALLING SEQUENCE: etalambda_to_radec, eta,lambda,ra,dec INPUTS: eta SDSS survey coordinate eta (deg) lambda SDSS survey coordinate lambda (deg) OPTIONAL OUTPUTS: ra RA (deg), J2000 dec Dec (deg), J2000 BUGS: Location of the survey center is hard-wired, not read from astrotools. REVISION HISTORY: 2001-Jul-21 written by Hogg (NYU) 2002-Oct-04 modified by Blanton (NYU)
(See pro/coord/etalambda_to_radec.pro)
NAME: eta_to_stripe PURPOSE: find the stripe which an eta value is in; hardwired to what astrotools v5_6 does; except it uses lambda to deal with southern stripes CALLING SEQUENCE: etalambda_to_stripe, eta, stripe INPUTS: eta value of eta (survey lat) in deg lambda value of lambda (survey long) in deg OUTPUTS: stripe Survey Stripe # BUGS: Location of the survey center is hard-wired, not read from astrotools. REVISION HISTORY: 2002-Feb-20 written by Blanton (NYU)
(See pro/coord/eta_to_stripe.pro)
NAME:
EULER_2000
PURPOSE:
Transform between Galactic, celestial, and ecliptic coordinates.
EXPLANATION:
Use the procedure ASTRO to use this routine interactively
CALLING SEQUENCE:
EULER_2000, AI, BI, AO, BO, [ SELECT, /FK4 ]
INPUTS:
AI - Input Longitude in DEGREES, scalar or vector. If only two
parameters are supplied, then AI and BI will be modified to
contain the output longitude and latitude.
BI - Input Latitude in DEGREES
OPTIONAL INPUT:
SELECT - Integer (1-6) specifying type of coordinate transformation.
SELECT From To | SELECT From To
1 RA-Dec (2000) Galactic | 4 Ecliptic RA-Dec
2 Galactic RA-DEC | 5 Ecliptic Galactic
3 RA-Dec Ecliptic | 6 Galactic Ecliptic
If omitted, program will prompt for the value of SELECT
Celestial coordinates (RA, Dec) should be given in equinox J2000
unless the /FK4 keyword is set.
OUTPUTS:
AO - Output Longitude in DEGREES
BO - Output Latitude in DEGREES
INPUT KEYWORD:
/FK4 - If this keyword is set and non-zero, then input and output
celestial and ecliptic coordinates should be given in equinox
B1950.
NOTES:
EULER was changed in December 1998 to use J2000 coordinates as the
default, ** and may be incompatible with earlier versions***.
REVISION HISTORY:
Written W. Landsman, February 1987
Adapted from Fortran by Daryl Yentis NRL
Converted to IDL V5.0 W. Landsman September 1997
Made J2000 the default, added /FK4 keyword W. Landsman December 1998
Renamed to euler_2000.pro by D. Finkbeiner 15 Apr 1999
-------------------
Memory managment improved 16 April 1999 - D. Finkbeiner.
- now makes heavy use of "temporary" function to deallocate
arrays
- arguments of atan() are now floats, since atan is the
limiting factor on memory usage, and numerical precision is
not such a big deal for atan.
- These changes reduce memory usage by 58%, but cause
differences of up to .03 arcsec relative to the standard
version of euler. If you are interested in higher
precision than this, DO NOT USE THIS ROUTINE!
-------------------
(See pro/coord/euler_2000_fast.pro)
NAME:
exact_photfrac
PURPOSE:
Create list of contribution of pixels to circular or annular aperture
CALLING SEQUENCE:
exact_photfrac, xcen, ycen, radius [, fracs=, xdimen=, ydimen=, ]
pixnum=, xpixnum=, ypixnum= ]
INPUTS:
xcen - X center(s) (LONG)
ycen - Y center(s) (LONG)
radius - radius of aperture (if 2-element array, inner and outer
radii of annulus)
OPTIONAL INPUTS:
xdimen - number of pixels upon a side to output [default - radius+1]
ydimen - number of pixels upon a side to output [default - radius+1]
safefactor - we set strictly to zero all pixels outside
max(radius)*safefactor [default 1.2]
OUTPUTS:
fracs- contribution of each pixel to image
pixnum - Pixel number, 0-indexed, for referencing array using one index.
xPixNum - Pixel number in X, 0-indexed.
yPixNum - Pixel number in Y, 0-indexed.
COMMENTS:
Uses Robert Lupton's Aperture Photometry scheme to measure seeing-
and pixel-convolved aperture photometry in band-limited images.
xcen and ycen MUST be integers. This simplifies the caching
of the weights considerably. Note that for band-limited images
(the only kind that this code works for) you can always sshift
the image to get the center of the object at the center of a
pixel (ie. an integer pixel number).
BUGS:
PROCEDURES CALLED:
REVISION HISTORY:
Started - 22-Aug-2003 M. Blanton (NYU)
(See pro/image/exact_photfrac.pro)
NAME:
extract_profmean
PURPOSE:
Extract a photoesque radial profile
CALLING SEQUENCE
extract_profmean, image, center, profmean, proferr $
[,profradius=profradius] [,invvar=invvar]
INPUTS:
image - [nx,ny] image
center - [2] center of extraction (LONG)
OPTIONAL INPUTS:
invvar - [nx,ny] inverse variance image; default to unity
profradius - [nrad] defining profile, in pixels; default to PHOTO aps
KEYWORDS:
OUTPUTS:
nprof - number of "good" profmean values (based on image
size alone)
profmean - [nrad] annular fluxes
profmean_ivar - [nrad] uncertainties
qstokes - if present, calculates Stokes Q parameter in each circle
(not within annuli)
ustokes - if present, calculates Stokes U parameter in each circle
(not within annuli)
OPTIONAL INPUT/OUTPUTS:
cache - cache storing photfracs for re-use
COMMENTS:
Image must be centered on the center pixel.
DEPENDENCIES:
idlutils
BUGS:
REVISION HISTORY:
2002-09-04 Written - Blanton
2002-09-12 Modified to use djsphot - Hogg
(See pro/image/extract_profmean.pro)
NAME: ext_ccm PURPOSE: Return extinction curve from CCM (1989), defined in the wavelength range [1250,33333] Angstroms. CALLING SEQUENCE: Alam = ext_ccm( lambda, [ Rv ] ) INPUTS: lambda: Wavelength(s) in Angstroms OPTIONAL INPUTS: Rv: Value of R_V; default to 3.1 OUTPUTS: Alam: Return value A(lambda)/A(V) COMMENTS: Reference is Cardelli, J.A., Clayton, G.C., & Mathis, J.S. 1989, ApJ, 345, 245-256. PROCEDURES CALLED: REVISION HISTORY: Written D. Schlegel, 8 September 1997, Durham
(See pro/dust/ext_ccm.pro)
NAME: ext_odonnell PURPOSE: Return extinction curve from Odonnell (1994), defined in the wavelength range [3030,9091] Angstroms. Outside this range, use CCM (1989). CALLING SEQUENCE: Alam = ext_odonnell( lambda, [ Rv ] ) INPUTS: lambda: Wavelength(s) in Angstroms OPTIONAL INPUTS: Rv: Value of R_V (scalar); default to 3.1 OUTPUTS: Alam: Return value A(lambda)/A(V) COMMENTS: Reference is O'Donnell, J. E. 1994, ApJ, 422, 158-163. PROCEDURES CALLED: ext_ccm() REVISION HISTORY: Written D. Schlegel, 8 September 1997, Durham
(See pro/dust/ext_odonnell.pro)
NAME: ex_max PURPOSE: expectation-maximization iterative multi-gaussian fit to data INPUTS: weight [N] array of data-point weights point [d,N] array of data points - N vectors of dimension d amp [M] array of gaussian amplitudes mean [d,M] array of gaussian mean vectors var [d,d,M] array of gaussian variance matrices OPTIONAL INPUTS: maxiterate maximum number of iterations; default to 1000 qa name for QA plot PostScript file label [d] array of QA plot axis labels; default 'x_i' OUTPUTS: amp updated amplitudes mean updated means var updated variances OPTIONAL OUTPUTS: entropy final entropy, relative to one-gaussian case probability [N,M] array of probabilities of point i in gaussian j exponent [N,M] array of exponents for point i in gaussian j BUGS: Hogg is pretty sure that the "probability" calculation in the middle of the iteration is WRONG -- see in-code comments. Entropy calculation could be wrong; see in-code comments. Stopping condition is hard-wired. DEPENDENCIES: idlutils REVISION HISTORY: 2001-Aug-06 written by Blanton and Hogg (NYU) 2001-Oct-02 added data-point weights - Hogg
(See pro/math/ex_max.pro)
NAME:
ex_max_plot
PURPOSE:
plot ex_max outputs or other N-dimensional data sets
INPUTS:
weight [N] array of data-point weights
point [d,N] array of data points - N vectors of dimension d
amp [M] array of gaussian amplitudes
mean [d,M] array of gaussian mean vectors
var [d,d,M] array of gaussian variance matrices
psfilename name for PostScript file; if no filename is given, then the
plots will simply be sent to the currently active device
OPTIONAL INPUTS:
nsig number of sigma for half-width of each plot; default 5
label [d] array of axis labels; default 'x_i'
contlevel confidence levels for contouring; defaults in source code
range [2,d] array of plotting ranges
textlabel [q] vector of text labels
textpos [d,q] array of text label positions
box [2,d] array of coordinates for d-dimensional box
xdims,ydims indices of data dimensions to use on each x and y axis
npix_x,npix_y number of pixels in x and y dimensions of each panel
sqrt sqrt stretch on image
log logarithmic stretch on image
axis_char_scale size of characters on labels
overpoints [d,P] set of points to overplot a red box on each panel
model_npix_factor for gaussians, use this factor to scale down pixel size
panellabels label string for each panel (size of xdims, ydims arrays)
quantfrac vector of fractions at which to plot quantiles on conditional
panels
default_font font command to send to set font for plotting
pthick thickness of plot lines
yrangefudge fudge range on histograms (default 1.)
KEYWORDS:
nomodel don't show model fits as greyscales or histograms
nodata don't show data as greyscales or histograms
noellipse don't show ellipses on 2-d plots
bw show ellipses in b/w
conditional plot the conditional distribution of y on x
nogreyscale don't plot the greyscale
OUTPUTS:
OPTIONAL OUTPUTS:
quantile output array of quantile positions; read the source code
quantneff the effective number of data points contributing to the medians
twodimages set of all of the 2-dimensional projections
(doesn't save the gaussian model unless
model_npix_factor==1)
BUGS:
Greyscales need work?
DEPENDENCIES:
REVISION HISTORY:
2001-10-22 written - Hogg
2002-03-22 many added features - Blanton
(See pro/plot/ex_max_plot.pro)
NAME: ex_max_probability PURPOSE: Return probabilities given ex_max results INPUTS: point [d,N] array of data points - N vectors of dimension d amp [M] array of gaussian amplitudes mean [d,M] array of gaussian mean vectors var [d,d,M] array of gaussian variance matrices OPTIONAL INPUTS: OUTPUTS: OPTIONAL OUTPUTS: probability [N,M] array of probabilities of point i in gaussian j BUGS: should be called by ex_max for consistency (would involve including entropy calc here) DEPENDENCIES: idlutils REVISION HISTORY: 2002-Nov-20 Blaton
(See pro/math/ex_max_probability.pro)
NAME: fac_flux2temp PURPOSE: Compute factor to convert from flux/sr to brightness temp CALLING SEQUENCE: fac_flux2temp, nu_ghz INPUTS: nu_ghz - frequency in GHz OUTPUTS: <value> - conversion factor (micro-K) / (MJy/sr) PROCEDURES CALLED: fac_temp2flux() COMMENTS: see fac_temp2flux.pro We call fac_temp2flux so that these routines are the inverse of each other by construction. REVISION HISTORY: Written by D. Finkbeiner, 10 March, 1999 - Berkeley
(See pro/dust/fac_flux2temp.pro)
NAME: fac_temp2flux PURPOSE: Compute factor to convert from brightness temp to flux/sr CALLING SEQUENCE: fac_temp2flux, nu INPUTS: nu_ghz - frequency in GHz OUTPUTS: <value> - conversion factor (MJy/sr) / (micro-K) PROCEDURES CALLED: <none> COMMENTS: REVISION HISTORY: Written by D. Finkbeiner, 10 March, 1999 - Berkeley Modified 16 March, 1999 to handle integer nu_ghz argument - DPF
(See pro/dust/fac_temp2flux.pro)
NAME:
FASTCONV
PURPOSE:
Perform a convolution faster by binning both the image and
kernel down by a factor of BINFACTOR.
CALLING SEQUENCE:
Fastcon, image, kernel, binfactor
INPUTS:
image - input array to be convolved
kernel - array to convolve image with - e.g. a Gaussian
binfactor - factor to bin down by (must divide both image and
kernel dimensions)
OUTPUTS:
REVISION HISTORY:
Written D. Finkbeiner, 3 Sept 96
2 May 1997 Add nodisplay keyword
3 May 1997 Add edge_wrap keyword
30 March 1998 Allow non-square arrays (introduced bug)
24 April 1998 Bug found - failed to divide by binfactor before
rebinning. Bug fixed.
29 June 1998 Add disc keyword to allow disc smoothing (DPF)
(See pro/image/fastconv.pro)
NAME:
FCHEBYSHEV
PURPOSE:
Compute the first M terms in a CHEBYSHEV polynomial expansion.
EXPLANATION:
Meant to be used as a supplied function to SVDFIT.
CALLING SEQUENCE:
result = FCHEBYSHEV( X, M )
INPUTS:
X - the value of the independent variable, scalar or vector
M - number of term of the CHEBYSHEV expansion to compute, integer scalar
OUTPUTS:
result - (N,M) array, where N is the number of elements in X and M
is the order. Contains the value of each CHEBYSHEV term for
each value of X
EXAMPLE:
(1) If x = 2.88 and M = 3 then
IDL> print, fchebyshev(x,3) ==> [1.00, 2.88, 15.5888]
(2) Find the coefficients to an M term Chebyshev polynomial that gives
the best least-squares fit to a dataset (x,y)
IDL> coeff = SVDFIT( x,y,M,func='fchebyshev')
METHOD:
REVISION HISTORY:
04-Aug-1999 Written by Scott Burles by hacking FLEGENDRE code
by Landsman in the Goddard libraries.
(See pro/trace/fchebyshev.pro)
NAME:
FCHEBYSHEV_SPLIT
PURPOSE:
Compute the first M terms in a CHEBYSHEV polynomial expansion,
but modified to allow a split in the baseline at X=0.
EXPLANATION:
Meant to be used as a supplied function to SVDFIT.
CALLING SEQUENCE:
result = FCHEBYSHEV_SPLIT( X, M )
INPUTS:
X - the value of the independent variable, scalar or vector
M - number of term of the CHEBYSHEV expansion to compute, integer scalar
The first two elements describe the constant value which is
different on each side of X=0.
OUTPUTS:
result - (N,M) array, where N is the number of elements in X and M
is the order. Contains the value of each CHEBYSHEV term for
each value of X
EXAMPLE:
(1) If x = 2.88 and M = 3 then
IDL> print, fchebyshev_split(x,3) ==> [1.00, 1.00, 2.88]
(2) Find the coefficients to an M term Chebyshev polynomial that gives
the best least-squares fit to a dataset (x,y)
IDL> coeff = SVDFIT( x,y,M,func='fchebyshev_split')
METHOD:
REVISION HISTORY:
04-Aug-1999 Written by Scott Burles by hacking FLEGENDRE code
by Landsman in the Goddard libraries.
(See pro/trace/fchebyshev_split.pro)
NAME:
fileandpath
PURPOSE:
Split a file name into the path and the file name.
CALLING SEQUENCE:
filename = fileandpath(fullname, [path= ])
INPUTS:
fullname - File name(s) which may include disk and/or directory
specifications.
OUTPUT:
filename - File name(s) without any disk or directory specifications.
OPTIONAL OUTPUT:
path - Disk and directory specification(s).
COMMENTS:
This routine is meant to absorb any operating system dependencies.
EXAMPLES:
For Unix:
IDL> print, fileandpath('data/all/one.dat', path=path)
one.dat
IDL> print, path
data/all
BUGS:
PROCEDURES CALLED:
fdecomp
REVISION HISTORY:
30-May-2000 Written by David Schlegel, Princeton.
(See pro/misc/fileandpath.pro)
NAME:
fill_bspline
PURPOSE:
Calculate a B-spline in the least-squares sense
based on two variables: x which is sorted and spans a large range
where bkpts are required
and y which can be described with a low order
polynomial
CALLING SEQUENCE:
coeff = fill_bspline(x, y, z, invsig, npoly, nbkptord, fullbkpt)
INPUTS:
x - data x values
y - data y values
z - data z values
invsig - inverse error array of y
npoly - Order of polynomial (as a function of y)
nbkptord - Order of b-splines (4 is cubic)
fullbkpt - Breakpoint vector returned by efc
RETURNS:
coeff - B-spline coefficients calculated by efc
OUTPUTS:
OPTIONAL KEYWORDS:
OPTIONAL OUTPUTS:
COMMENTS:
please sort x for this routine? This might not be necessary
replacement for efcmn and efc2d which calls slatec library
EXAMPLES:
PROCEDURES CALLED:
efc_idl in src/slatec/idlwrapper.c
which wraps to efc.o in libslatecidl.so
REVISION HISTORY:
20-Aug-2000 Written by Scott Burles, FNAL
(See pro/bspline/fill_bspline.pro)
NAME:
findbkpt
PURPOSE:
Choose bkpts for b-spline given different constraints
CALLING SEQUENCE:
fullbkpt = findbkpt(x, good, bkpt, nord, bkspace=bkspace, nbkpts=nbkpts, $
everyn=everyn, silent=silent)
INPUTS:
bkpt - Breakpoint vector returned by efc
RETURNS:
fullbkpt - The fullbkpt vector required by evaluations with bvalu
OPTIONAL KEYWORDS:
bkspace - Spacing of breakpoints in units of x
everyn - Spacing of breakpoints in good pixels
nbkpts - Number of breakpoints to span x range
minimum is 2 (the endpoints)
silent - Do not produce non-critical messages
OPTIONAL OUTPUTS:
bkpt - breakpoints without padding
COMMENTS:
If both bkspace and nbkpts are passed, bkspace is used.
EXAMPLES:
PROCEDURES CALLED:
none
REVISION HISTORY:
10-Mar-2000 Written by Scott Burles, FNAL
(See pro/slatec/findbkpt.pro)
NAME:
findopfile
PURPOSE:
Find the op file corresponding to a specified MJD.
CALLING SEQUENCE:
filename = findopfile( expres, mjd, [ indir, /abort_notfound, /silent ] )
INPUTS:
expres - Op file names to match which may include any wildcards
other other expressions valid for the function FINDFILE().
mjd - Number (MJD) for matching corresponding op file.
OPTIONAL INPUT:
indir - Input directory
abort_notfound - If set and no files are found to match the expression,
then abort with the MESSAGE command; otherwise return ''.
silent - If set, then don't output any text.
OUTPUTS:
filename - Matched file name without path information
OPTIONAL OUTPUTS:
COMMENTS:
The MJD for the op file is determined from the file name itself
by looking at whatever number is immediately after the first '-'.
For example, the file 'opBC-52000.par' is interpreted as having
MJD=52000.
The matching op file is the one with the same MJD as that requested,
or the last one preceding the requested MJD. If the requested MJD
precedes any for the existing op files, then return the op file
with the lowest MJD. For example, if we have two opBC files
'opBC-50000.par' and 'opBC-52000.par', then the first is returned
for all MJDs up to 51999, and the latter used for MJD=52000 and later.
EXAMPLES:
Find the opBC file in the directory $IDLSPEC2D_DIR/examples
that is appropriate for data taken on MJD=52000:
IDL> indir = getenv('IDLSPEC2D_DIR')+'/examples'
IDL> filename = findopfile('opBC*.par', 52000, indir)
BUGS:
PROCEDURES CALLED:
djs_filepath()
fileandpath()
splog
INTERNAL SUPPORT ROUTINES:
DATA FILES:
REVISION HISTORY:
27-Feb-2002 Written by Scott Burles & David Schlegel.
Broken out from an internal function of SDSSPROC.
(See pro/sdss/findopfile.pro)
NAME:
find_sb
PURPOSE:
Find objects in a 2-d image with a gaussian filter
CALLING SEQUENCE
find_sb, sub, wt, x=x, y=y, flux=flux, $
[sigma=, hpix=, hmin=]
INPUTS:
sub - skysubtracted image
wt - inverse variance weight (0 or 1 for CR mask is OK)
OPTIONAL INPUTS:
sigma - sigma of gaussian filter in pixels (1.0 is default)
hpix - half-pixel width of convolution filter (2 is default)
hmin - minimum flux threshold
curvr - the maximum allowed log ratio of curvature along the
major/minor axes (basically checking for roundness).
default is 2.
KEYWORDS:
OUTPUTS:
x - column pixel positions of flux peak (sorted be decreasing flux)
y - row pixel position "
flux - gaussian filtered flux estimate
pa_degrees - a guess at the PA of the object from the x-axis
ab - a guess at the minor/major axis ratio
COMMENTS:
DEPENDENCIES:
idlutils
BUGS:
No checks on neighboring peaks
Not tested yet with real inverse variance weighting
Not sure that I have PA calculated correctly
REVISION HISTORY:
2005-11-30 Written - Burles
(See pro/image/find_sb.pro)
NAME:
first_coverage
PURPOSE:
Read the FIRST survey coverage maps.
CALLING SEQUENCE:
skyrms = first_coverage(ra, dec)
OPTIONAL INPUTS:
ra: Right ascensions [J2000 deg]
dec: Declinations [J2000 deg]
OUTPUTS:
skyrms: Returned RMS noise in mJy/beam
COMMENTS:
These images give the RMS in mJy/beam tabulated on a ~3 arcmin grid
in RA and DEC. However, the WCS headers in these FITS files are invalid.
BUGS:
The coordinates in these FITS headers have been interpreted to be
for the *center* of each pixel, though there is no documentation as
to whether this is the correct interpretation.
DATA FILES:
The following data files can be copied from:
http://sundog.stsci.edu/first/catalogs/
and should be put in a directory pointed to by the environment
variable $FIRST_DIR:
$FIRST_DIR/coverage-north-3arcmin-03apr11.fits
$FIRST_DIR/coverage-south-3arcmin-01oct15.fits
PROCEDURES CALLED:
headfits()
mrdfits()
REVISION HISTORY:
Written D. Schlegel, 18 July 2003, Princeton
31 July 2003 - /silent keyword added to read - DPF
(See pro/first/first_coverage.pro)
NAME:
first_read
PURPOSE:
Read the FIRST catalog (and generate IDL save sets)
CALLING SEQUENCE:
bigdat = first_read( [ racen, deccen, radius, node=, incl=, hwidth=, $
columns= ] )
OPTIONAL INPUTS:
racen: Central RA for selecting a region of stars [J2000 deg]
deccen: Central DEC for selecting a region of stars [J2000 deg]
radius: Radius for selecting a region of stars [deg]
node: Node of great circle for selecting a stripe of stars [deg]
incl: Inclination of great circle for selecting a stripe [deg]
hwidth: Half-width of great circle for selecting a stripe [deg]
columns: Select only these columns from the data files.
Must include 'FIRST_RA' and 'FIRST_DEC' if a circular or
great circle region is selected.
OUTPUTS:
bigdat: Returned structure containing data
COMMENTS:
To trim to objects within a circle, RACEN, DECCEN and RADIUS must
all be set.
To trim to objects along a great circle, NODE, INCL and HWIDTH must
all be set.
The equinox of the returned data is always J2000.
BUGS:
DATA FILES:
The following data files can be copied from:
http://sundog.stsci.edu/first/catalogs/
and should be put in a directory pointed to by the environment
variable $FIRST_DIR:
$FIRST_DIR/catalog_03apr11.bin
This file must be uncompressed.
INTERNAL SUPPORT ROUTINES:
first_convert()
first_testwrite()
first_readascii()
first_rdindex
first_readfits()
first_readfile()
PROCEDURES CALLED:
djs_diff_angle()
mrdfits()
mwrfits
radec_to_munu
splog
REVISION HISTORY:
Written D. Schlegel, 18 July 2003, Princeton
(See pro/first/first_read.pro)
NAME: fits_purge_nans PURPOSE: Purge invalid (NaN) values from FITS headers CALLING SEQUENCE: fits_purge_nans, hdr, [ /verbose ] INPUTS: hdr - FITS header OPTIONAL INPUTS: verbose - If set, then report which keywords are being disposed OUTPUTS: hdr - (Modified) OPTIONAL OUTPUTS: COMMENTS: This procedure removes header keywords that are not strings, but are returned by SXPAR() as NaN-valued (as determined by the FINITE() function). This procedure was written to deal with raw SDSS headers that sometimes contain header lines like 'ALT = NaN', where the NaN is not contained in quotes. EXAMPLES: BUGS: PROCEDURES CALLED: splog sxpar REVISION HISTORY: 14-Jul-2004 Written by David Schlegel, Princeton.
(See pro/fits/fits_purge_nans.pro)
NAME:
fits_wait
PURPOSE:
Wait for a FITS file to be fully written to disk.
CALLING SEQUENCE:
qdone = fits_wait(filename, [deltat=, tmax=, _EXTRA=KeywordsForFitsRead ])
INPUTS:
filename - FITS file name.
OPTIONAL INPUTS:
deltat - Time to wait between attempts to check file; default to 10 sec.
tmax - Maximum time to check file; default to 300 sec.
_EXTRA - Keywords to pass to FITS_READ, such as /HEADER_ONLY or EXTEN=.
OUTPUTS:
qdone - Return 0 if the file was never read as a valid FITS file;
return 1 if it was.
OPTIONAL OUTPUTS:
COMMENTS:
The purpose of this routine is to be able to test when a FITS file
has been fully written to disk. This is useful for real-time processes
that must check this. The Goddard routine FITS_READ is used to
determine when a file is fully written.
EXAMPLES:
BUGS:
PROCEDURES CALLED:
fits_read
REVISION HISTORY:
02-Oct-2000 Written by David Schlegel, Princeton.
(See pro/fits/fits_wait.pro)
NAME:
floatcompress
PURPOSE:
Make floating-point data more compressible by trimming binary digits.
The routine keeps the ndig most signifcant binary digits.
If keyword nsig is passed, the algorithm rounds to the nearest
power of two less than nsig*sigma, where sigma is evaluated from
the passed array (with 5 sigma outlier rejection).
CALLING SEQUENCE:
out = floatcompress(data, ndig=ndig, nsig=nsig)
INPUTS:
data - input data (type float or double)
WARNING: input data array is nuked to save memory
on large arrays.
OPTIONAL KEYWORDS:
ndig - number of binary significant digits to keep
nsig - number of sigma at which to round data
OUTPUTS:
out - output data array with ndig significant binary digits
kept and the rest zeroed.
COMMENTS:
This function does not compress the data in an array, but fills
unnecessary digits of the IEEE floating point representation with
zeros. This makes the data more compressible by standard
compression routines such as compress or gzip.
The default is to retain 10 binary digits instead of the usual 23
bits (or 52 bits for double precision), introducing a fractional
error strictly less than 1/1024). This is adequate for most
astronomical images, and results in images that compress a factor
of 2-4 with gzip.
EXAMPLES:
image = readfits('map.fits') ; read in FITS image
outimage = floatcompress(image,ndig=8) ; keep 8 binary digits
writefits,'mapsmall.fits',outimage ; write image
Then from the UNIX shell
> gzip -8 mapsmall.fits
(level 8 gzip is slower but more effective than average this is
good for files that will be zipped once and unzipped many times)
PERFORMANCE:
On the typical maps of the ISM, gzip -8 compression factor is
~2.1. Mileage may vary. For some images, a factor of 4-5 is possible.
BUGS:
None known, but it is possible that there are floating point
values that are corrupted due to round off errors. Results should
be double-checked.
PROCEDURES CALLED:
REVISION HISTORY:
05-Jul-2000 Written by Doug Finkbeiner (UC Berkeley)
16-Sep-2000 Put in current format and commented -DPF
22-Sep-2000 Added nsig keyword
22-Jun-2002 Deals with Infs and NaNs - DPF
(See pro/misc/floatcompress.pro)
NAME:
frac_profmean
PURPOSE:
Get the radius of a certain light fraction, given the total light radius
CALLING SEQUENCE
radfrac= frac_profmean(frac, nprof, profmean, radtot $
[,profradius=profradius] )
INPUTS:
frac - fraction desired
nprof - number of annuli to trust
profmean - [nrad,ncent] annular fluxes
radtot - total light radius
OPTIONAL INPUTS:
profradius - [nrad] defining profile, in pixels; default to PHOTO aps
KEYWORDS:
OUTPUTS:
radfrac - radius containing frac fraction of the light in radtot
COMMENTS:
DEPENDENCIES:
idlutils
BUGS:
no indication of whether fit is sensible
REVISION HISTORY:
2003-09-15 Written - Blanton
(See pro/image/frac_profmean.pro)
NAME:
FSC_DROPLIST
PURPOSE:
The purpose of this compound widget is to provide an alternative
to the DROPLIST widget offered in the IDL distribution. What has
always annoyed me about a droplist is that you can't get the current
"value" of a droplist easily. This compound widget makes this and
other tasks much easier.
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:
General programming.
CALLING SEQUENCE:
droplistObj = FSC_Droplist(parent, Title='Animals: ", Value=['Dog'. 'Cat', 'Coyote'], Index=2)
The return value of the FSC_Droplist (droplistObj in this example) is
an object reference. Interaction with the droplist will occur through
object methods.
INPUT PARAMETERS:
parent -- The parent widget ID of the compound widget. Required.
INPUT KEYWORDS:
Any keyword that is appropriate for the Widget_Droplist function can be used.
In addition, these keywords are explicitly defined.
EVENT_FUNC -- Set this keyword to the name of an Event Handler Function.
EVENT_PRO -- Set this keyword to the name of an Event Handler Procedure.
FORMAT -- A format specifier for the "format" of the values in the droplist.
INDEX -- The index number of the current selection.
SPACES -- A two-element array that indicates the number of blank spaces to be added
to the the beginning and end of the formatted values. If a single number
is provided, this number of blank spaces is added to both the beginning
and the end of the value.
TITLE -- The title of the droplist widget.
UNAME -- The user name of the droplist widget. (Only available in IDL 5.2 and higher.)
UVALUE -- The normal "user value" of the droplist.
VALUE -- An array of the droplist "selections". May be any data type.
COMMON BLOCKS:
None.
DEPENDENCIES:
Requires ERROR_MESSAGE from the Coyote Library..
EVENT STRUCTURE:
An event is returned each time the droplist value is changed. The event structure
is defined like this:
event = { FSC_DROPLIST_EVENT, $ ; The name of the event structure.
ID: 0L, $ ; The ID of the compound widget's top-level base.
TOP: 0L, $ ; The widget ID of the top-level base of the hierarchy.
HANDLER: 0L, $ ; The event handler ID. Filled out by IDL.
INDEX: 0L, $ ; The index number of the current selection.
SELECTION:Ptr_New() $ ; A pointer to the current selection "value".
SELF:Obj_New() } ; The object reference of the compound widget.
PUBLIC OBJECT METHODS:
GetID -- A function with no arguments that returns the widget identifier
of the droplist widget.
droplistID = droplistObj->GetID()
GetIndex -- A function with no arguments that returns the index
number of the current droplist selection.
currentIndex = droplistObj->GetIndex()
GetSelection -- A function with no arguments that returns the current
droplist selection.
currentSelection = droplistObj->GetSelection()
GetUValue -- A function with no arguments that returns the "user value"
of the compound widget i.e., the value set with the UVALUE keyword).
myUValue = droplistObj->GetUValue()
GetValues -- A function with no arguments that returns the "values" or
"selections" for the droplist.
possibleSelections = droplistObj->GetValues()
Resize -- A procedure that sets the X screen size of the droplist. It is
defined like this:
PRO Resize, newSize, ParentSize=parentSize
The "newSize" keyword is the new X screen size. If this argument is
missing, the screen X size of the compound widget's parent is used.
The parentSize keyword is an output keyword that returns the X screen
size of the compound widget's parent.
droplistObj->Resize, 400
Note that not all devices (e.g., X Windows devices) support droplist resizing.
SetIndex -- A procedure that sets the current droplist selection based on
the given index. This is equivalent to Widget_Control, droplistID, Set_Droplist_Select=newIndex
droplistObj->SetIndex, newIndex
SetSelection -- Whereas a regular droplist widget can only be set by index
number, this compound widget can also be set by a "selection". The new selection
can be any data type and corresponds to one of the "values" of the droplist.
droplistObj->SetSelection, newSelection
EXAMPLE:
An example program is provided at the end of the FSC_DROPLIST code. To run it,
type these commands:
IDL> .Compile FSC_DROPLIST
IDL> Example
MODIFICATION HISTORY:
Written by: David Fanning, 17 Jan 2000. DWF.
Added FORMAT and SPACES keywords 28 April 2000. DWF.
Fixed a small problem with event processing when the EVENT_FUNC keyword
was used. 29 Dec 2000. DWF.
(See pro/psconfig/fsc_droplist.pro)
NAME:
FSC_FIELD
PURPOSE:
The purpose of this compound widget is to provide an alternative
to the CW_FIELD widget offered in the IDL distribution. One weakness
of the CW_FIELD compound widget is that the text widgets do not
look editable to the users on Windows platforms. This program
corrects that deficiency and adds some features that I think
will be helpful. For example, you can now assign an event handler
to the compound widget, ask for positive numbers only, and limit
the number of digits in a number, or the number of digits to the
right of a decimal point. The program is written as a widget object,
which allows the user to call object methods directly, affording
even more flexibility in use. This program replaces the earlier
programs FSC_INPUTFIELD and COYOTE_FIELD.
The program consists of a label widget next to a one-line text widget.
The "value" of the compound widget is shown in the text widget. If the
value is a number, it will not be possible (generally) to type
alphanumeric values in the text widget. String values behave like
strings in any one-line text widget.
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:
General programming.
TYPICAL CALLING SEQUENCE:
fieldID = FSC_FIELD(parent, Title="X Size:", Value=256, Object=fieldObject, Digits=3)
INPUT PARAMETERS:
parent -- The parent widget ID of the compound widget. Required.
INPUT KEYWORDS:
COLUMN Set this keyword to have the Label widget above the Text widget.
The default is to have the Label widget in a row with the Text widget.
CR_ONLY Set this keyword if you only want Carriage Return events returned to
your event handler. If this keyword is not set, all events are returned.
Setting this keyword has no effect unless either the EVENT_PRO or
EVENT_FUNC keyword is used.
DECIMAL Set this keyword to the number of digits to the right of the decimal
point in floating point or double precision numbers. Ignored for STRING values.
DIGITS Set this keyword to the number of digits permitted in integer numbers.
EVENT_FUNC Set this keyword to the name of an event handler function. If this
keyword is undefined and the Event_Pro keyword is undefined,
all compound widget events are handled internally and not
passed on to the parent widget.
EVENT_PRO Set this keyword to the name of an event handler procedure. If this
keyword is undefined and the Event_Func keyword is undefined,
all compound widget events are handled internally and not
passed on to the parent widget.
FIELDFONT The font name for the text in the text widget.
FRAME Set this keyword to put a frame around the compound widget.
LABEL_LEFT Set this keyword to align the text on the label to the left.
LABEL_RIGHT Set this keyword to align the text on the label to the right.
LABELFONT The font name for the text in the label widget.
LABELSIZE The X screen size of the label widget.
NAME A string containing the name of the object. The default is ''.
NOEDIT Set this keyword to allow no user editing of the input text widget.
NONSENSITIVE Set this keyword to make the input text widget non-sensitive.
POSITIVE Set this keyword if you want only positive numbers allowed.
SCR_XSIZE The X screen size of the compound widget.
SCR_YSIZE The Y screen size of the compound widget.
TITLE The string text placed on the label widget.
UNDEFINED Set this keyword to the value to use for "undefined" values. If
not set, then !Value.F_NAN is used for numerical fields and a
NULL string is used for string fields. This applies to values
obtained with the GET_VALUE method or the GET_VALUE function.
UVALUE A user value for any purpose.
VALUE The "value" of the compound widget. Any type of integer, floating, or string
variable is allowed. The data "type" is determined automatically from the
value supplied with this keyword. Be sure you set the type appropriately for
your intended use of the value.
XSIZE The X size of the text widget in the usual character units.
OUTPUT KEYWORDS:
OBJECT Set this keyword to a named variable to receive the compound widget's
object reference. This is required if you wish to call methods on the object.
Note that the object reference is also available in the event structure
generated by the widget object. Note that the object reference will be
necessary if you want to get or set values in the compound widget.
COMMON BLOCKS:
None.
RESTRICTIONS:
None.
EVENT STRUCTURE:
All events are handled internally unless either the Event_Pro or Event_Func
keywords are used to assign an event handler to the compound widget. By
default all events generated by the text widget are passed to the assigned
event handler. If you wish to receive only Carriage Return events, set the
CR_Only keyword.
event = { FSC_FIELD_EVENT, $ ; The name of the event structure.
ID: 0L, $ ; The ID of the compound widget's top-level base.
TOP: 0L, $ ; The widget ID of the top-level base of the hierarchy.
HANDLER: 0L, $ ; The event handler ID. Filled out by IDL.
OBJECT: Obj_New(), $ ; The "self" object reference. Provided so you can call methods.
VALUE: Ptr_New(), $ ; A pointer to the widget value.
TYPE:"" ; A string indicating the type of data in the VALUE field.
}
Note that if the field is "empty", the VALUE will be a pointer
to an undefined variable. You should check this value before you
use it. You code will look something like this:
IF N_Elements(*event.value) EQ 0 THEN $
Print, 'Current Value UNDEFINED.' ELSE $
Print, 'Current Value: ', *event.value
GETTING and SETTING VALUES:
Almost all the properties of the widget can be obtained or set via
the object's GetProperty and SetProperty methods (described below).
Traditional compound widgets have the ability to get and set the "value"
of the compound widget identifier (e.g., fieldID in the calling
sequence above). Unfortunately, it is impossible to retreive a variable
in this way when the variable is undefined. In practical terms, this
means that the undefined variable must be set to *something*. You can
determine what that something is with the UNDEFINED keyword, or I will set
it to !VALUES.F_NAN for numerical fields and to the null string for string
fields. In any case, you will have to check for undefined variables before
you try to do something with the value. For a numerical field, the code
might look something like this:
fieldID = FSC_FIELD(parent, Title="X Size:", Value=256, Object=fieldObject, Digits=3)
currentValue = fieldObject->Get_Value()
IF Finite(currentValue) EQ 0 THEN Print, 'Value is Undefined' ELSE Print, currentValue
Additional examples are provided in the numerical example fields in Example Program below.
Setting the value of the compound widget is the same as calling the Set_Value
method on the object reference. In other words, these two statements are equivalent.
fieldObject->Set_Value, 45.4
Widget_Control, fieldID, Set_Value=45.4
The data type of the value is determined from the value itself. Be sure you set it appropriately.
OBJECT PROCEDURE METHODS:
GetProperty -- This method allows various properties of the widget to be
returned via output keywords. The keywords that are available are:
CR_Only -- A flag, if set, means only report carriage return events.
DataType -- The data type of the field variable.
Decimal -- Set this keyword to the number of digits to the right of the decimal
point in FLOATVALUE and DOUBLEVALUE numbers.
Digits -- Set this keyword to the number of digits permitted in INTERGERVALUE and LONGVALUE numbers.
Event_Func -- The name of the event handler function.
Event_Pro -- The name of the event handler function.
Name -- A scalar string name of the object.
NoEdit -- A 1 means the widget is non-editable.
NonSensitive -- A 1 means the widget is non-sensitive.
NonSensitive -- Set this keyword to make the widget non-sensitive.
Positive -- Indicates if the Positive number flag is set (1) or not (0).
UValue -- The user value assigned to the compound widget.
Value -- The "value" of the compound widget.
MoveTab -- This method moves the focus to the widget identified in the "next" field,
which must be set with the SetTabNext method. No parameters. Called automatically
when a TAB character is typed in the text widget.
Resize -- This method allows you to resize the compound widget's text field.
The value parameter is an X screen size for the entire widget. The text
widget is sized by using the value obtained from this value minus the
X screen size of the label widget.
objectRef->Resize, screen_xsize_value
Set_Value -- This method allows you to set the "value" of the field. It takes
one positional parameter, which is the value.
objectRef->Set_Value, 5
SetEdit -- This procedure turns editing on (value of 1) or off (value of 0).
SetProperty -- This method allows various properties of the widget to be
set via input keywords. The keywords that are available are:
CR_Only -- Set this keyword if you only want Carriage Return events.
Decimal -- Set this keyword to the number of digits to the right of the decimal
point in FLOATVALUE and DOUBLEVALUE numbers.
Digits -- Set this keyword to the number of digits permitted in INTERGERVALUE and LONGVALUE numbers.
Event_Func -- Set this keyword to the name of an Event Function.
Event_Pro -- Set this keyword to the name of an Event Procedure.
LabelSize -- The X screen size of the Label Widget.
Name -- A scalar string name of the object. (default = '')
NoEdit -- Set this keyword to make the widget non-editable.
NonSensitive -- Set this keyword to make the widget non-sensitive.
Positive -- Set this keyword to indicate only positive numbers are allowed.
Scr_XSize -- The X screen size of the text widget.
Scr_YSize -- The Y screen size of the text widget.
Title -- The text to go on the Label Widget.
UValue -- A user value for any purpose.
Value -- The "value" of the compound widget.
XSize -- The X size of the Text Widget.
SetSensitive -- This procedure turns text widget sensitivity on (value of 1) or off (value of 0).
OBJECT FUNCTION METHODS:
Get_Value -- Returns the "value" of the field. No parameters. Will be undefined
if a "number" field is blank. Should be checked before using:
IF N_Elements(objectRef->Get_Value()) NE 0 THEN Print, Value is: ', objectRef->Get_Value()
GetID -- Returns the widget identifier of the compound widget's top-level base.
(The first child of the parent widget.) No parameters.
GetLabelSize -- Returns the X screen size of the label widget. No parameters.
GetTextID -- Returns the widget identifier of the compound widget's text widget.
No parameters.
GetTextSize -- Returns the X screen size of the text widget. No parameters.
PRIVATE OBJECT METHODS:
Although there is really no such thing as a "private" method in IDL's
object implementation, some methods are used internally and not meant to
be acessed publicly. Here are a few of those methods. I list them because
it may be these private methods are ones you wish to override in subclassed
objects.
MoveTab -- This method moves the cursor to end of the text in the widget identified
by the nexttab field. (This will be set with the SetTabNext method.)
Text_Events -- The main event handler method for the compound widget. All
text widget events are processed here.
ReturnValue -- This function method accepts a string input value and converts
it to the type of data requested by the user.
Validate -- This function method examines all text input and removes unwanted
characters, depending upon the requested data type for the field. It makes it
impossible, for example, to type alphanumeric characters in an INTEGER field.
EXAMPLE:
An example program is provided at the end of the FSC_FIELD code. To run it,
type these commands:
IDL> .Compile FSC_Field
IDL> Example
MODIFICATION HISTORY:
Written by: David Fanning, 18 October 2000. Based heavily on an earlier
FSC_INPUTFIELD program and new ideas about the best way to write
widget objects.
Added LABEL_LEFT, LABEL_RIGHT, and UNDEFINED keywords. 29 Dec 2000. DWF.
Modified the way the value is returned in the GET_VALUE method and the
GET_VALUE function. Modified Example program to demonstrate. 30 Dec 2000. DWF.
Added NOEDIT and NONSENSITIVE keywords, with corresponding SETEDIT and SETSENNSITIVE
methods. 19 Jan 2001. DWF.
Actually followed through with the changes I _said_" I made 29 Dec 2000. (Don't ask....) 13 June 2001. DWF.
Added GetTextSize and GetLabelSize methods for obtaining the X screen
size of the text and label widgets, respectively. 21 July 2001. DWF.
Fixed a problem in SetProperty method where I was setting self.xsize, which doesn't exist. 24 April 2002. DWF.
(See pro/psconfig/fsc_field.pro)
NAME:
FSC_FILESELECT
PURPOSE:
The purpose of this compound widget is to provide a means
by which the user can type or select a file name. The
program is written as an "object widget", meaning that
the guts of the program is an object of class FSC_FILESELECT.
This is meant to be an example of the obvious advantages of
writing compound widget programs as objects.
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:
General programming.
CALLING SEQUENCE:
filenameID = FSC_FileSelect(parent)
INPUT PARAMETERS:
parent -- The parent widget ID of the compound widget. Required.
INPUT KEYWORDS:
Event_Pro -- The event handler procedure for this compound widget.By default: "".
Event_Func -- The event handler function for this compound widget. By default: "".
If neither EVENT_PRO or EVENT_FUNC is defined, program events are handled internally by the compound widget.
DirectoryName -- The initial name of the directory. By defaut: current directory.
Filename -- The initial file name in the filename text widget.
Filter -- The file filter. By default: "*".
Frame -- Set this keyword for a frame around the compound widget.
LabelFont -- The font for the label widget. By default: "".
LabelName -- The text on the label widgt. By default: "Filename: ".
LabelSize -- The X screen size of the label widget. By default: 0.
MustExist -- A flag that indicates selected files must exist. By default: 0.
NoMaxSize -- A flag to prohibit automatic text widget sizing. By default: 0.
If this keyword is not set, the compound widget will automatically resize itself to
the largest widget in its parent base widget. It will do this by changing the size of
the text widgets holding the file and directory names.
Read -- Set this keyword to have file selection for reading a file. By default: 1.
SelectDirectory -- The default directory for file selection. In other words, this is the
default directory for DIALOG_PICKFILE, which is accessed via the BROWSE buttons.
SelectFont -- The font for the "Browse" button. By default: "".
SelectTitle -- The title bar text on the file selection dialog. By default: "Select a File...".
TextFont -- The font for the filename text widget. By default: "".
UValue -- User value for any purpose.
Write -- Set this keyword to open a file for writing. By default: 0.
XSize -- The X size of the text widget holding the filename. By default: StrLen(filename) * 1.5 > 40.
OUTPUT KEYWORDS:
ObjectRef -- Assign this keyword to an output variable that will hold the internal object reference.
With the object reference you can call object methods to easily change many properties of
the compound widget.
COMMON BLOCKS:
None.
RESTRICTIONS:
Probably doesn't work correctly on VMS systems :-( If you can help, please
contact me. I don't have a VMS system to test on.
EVENT STRUCTURE:
All events are handled internally unless either the Event_Pro or Event_Func
keywords are used to assign an event handler to the compound widget. All events
generated by the text widgets are passed to the assigned event handler.
event = { CW_FILESELECT, $ ; The name of the event structure.
ID: 0L, $ ; The ID of the compound widget's top-level base.
TOP: 0L, $ ; The widget ID of the top-level base of the hierarchy.
HANDLER: 0L, $ ; The event handler ID. Filled out by IDL.
Basename: "", $ ; The base filename without directory specifiers.
Filename: "", $ ; The fully qualified filename.
Directory: "", $ ; The name of the current file directory.
}
EXAMPLE:
An example program is provided at the end of the FSC_FILESELECT code. To run it,
type these commands:
IDL> .Compile fsc_fileselect
IDL> Example
Or, if you want to obtain the object reference, type this:
IDL> Example, theObject
Now you can call the object's methods. For example:
IDL theObject->SetProperty, XSize=150
GETTING and SETTING VALUES:
So as not to disrupt the accepted paradigm in using compound widgets, you
can use the return value of the FSC_FILESELECT function with WIDGET_CONTROL to
get and set the "value" of the widget.
Widget_Control, filenameID, Set_Value='C:\RSI\IDL52\DATA\cyclone.dat'
The program will automatically separate the file name portion of the value
from the directory portion and put things in the correct text widgets.
Similarly, you can get the "value" of the widget:
Widget_Control, filenameID, Set_Value=theValue
Print, theValue
C:\RSI\IDL52\DATA\cyclone.dat
The return value is the fully qualified file path to the file.
USING OBJECT METHODS to CHANGE PROGRAM PROPERTIES:
If you obtain the object reference, you have a great deal more control
over the properties of the compound widget. You obtain the object reference
by calling the function like this:
filenameID = FSC_FILESELECT(parent, ObjectRef=theObject)
OBJECT PROCEDURE METHODS:
GetProperty -- This method allows various properties of the widget to be
returned via output keywords. The keywords that are available are:
DirectoryName -- The current directory.
Event_Func -- The name of the event handler function for this compound widget.
Event_Pro -- The name of the event handler procedure for this compound widget.
Filename -- The current base filename.
Filter -- The current file filter.
LabelName -- The text on the label widget.
LabelSize -- The X screen size of the label widget.
MustExist -- A flag that indicates selected files must exist to be selected.
Parent -- The parent widget of the compound widget.
Read=read -- The file selection for reading flag.
SelectTitle -- The title bar text on the file selection dialog.
TLB -- The top-level base of the compound widget.
UValue -- The user value of the compound widget.
Write -- The file selection for writing flag.
XSize -- The X size of the text widget holding the filename.
LabelSize -- This method makes sure that the directory name and file name labels
are the same size. Normally, this procedure is called internally. No parameters.
MatchSize -- This method resizes the compound widget so that it is as long as the
the longest widget in the parent base widget. This is done automatically upon
realization unless the NOMAXSIZE keyword is set. The method aids in writing
resizeable widget programs.
SetProperty -- This method allows various properties of the widget to be
set via input keywords. The keywords that are available are:
DirectoryName -- The current directory.
Event_Func -- The name of the event handler function for this compound widget.
Event_Pro -- The name of the event handler procedure for this compound widget.
Filename -- The current base filename.
Filter -- The current file filter.
LabelName -- The text on the label widget.
LabelSize -- The X screen size of the label widget.
MustExist -- A flag that indicates selected files must exist to be selected.
Read -- The file selection for reading flag.
SelectTitle -- The title bar text on the file selection dialog.
UValue -- The user value of the compound widget.
Write -- The file selection for writing flag.
XSize -- The X size of the text widget holding the filename.
OBJECT FUNCTION METHODS:
GetFileName -- Returns the fully qualified filename. No parameters.
GetTLB -- Returns the top-level base ID of the compound widget. No Parameters.
Inspect_DirectoryName -- Inspects the directory name for correctness. Requires one positional parameter.
directoryName -- The name of the directory from the directory text widget.
textSelection -- The current text selection position.
At the moment all this does is remove any blank characters from either
end of the directory name and makes sure the last character of the directory
name does not end in a subdirectory specifier (except for VMS).
Inspect_Filename -- Inspects the file name for correctness. Requires one positional parameter.
filename -- The name of the file from the filename text widget.
textSelection -- The current text selection position.
At the moment all this does is remove any blank characters from either
end of the file name
MODIFICATION HISTORY:
Written by: David W. Fanning, 21 NOV 1999.
Fixed bug in File Name selection button. 18 MAR 2000. DWF.
Fixed an error in which directory the Browse buttons should start
searching. 29 SEP 2000. DWF.
Previously returned events only for typing in text widgets. Now
Browse button events are also returned. 29 SEP 2000. DWF.
Fixed a bug in setting the file filter. 29 SEP 2000. DWF.
Removed the Directory Browse button 10 AUG 2002. DWF.
Added ERROR_MESSAGE to error handling. 10 AUG 2002. DWF.
Changed the ability to specify a file filter as a string array, instead
of just as a scalar string. This required the use of a pointer, which
meant that I had to remove the FILTER field from the CW_FILESELECT
event structure to avoid likely memory leakage. This is a dangerous
change because it means programs that relied on this (I expect there
are very, very few) will break and it goes against my philosopy of
keeping my programs backward compatible. Let me know if you have
problems. In testing, I discoved no problems in my own code. 31 OCT 2002. DWF.
Fixed a problem with DIALOG_PICKFILE that sometimes allowed users to change
directories without selecting a file. 3 Nov 2002. DWF.
(See pro/psconfig/fsc_fileselect.pro)
NAME:
FSC_INPUTFIELD
PURPOSE:
The purpose of this compound widget is to provide an alternative
to the CW_FIELD widget offered in the IDL distribution. What has
always bothered me about CW_FIELD is that the text widgets do not
look editable to the users on Windows platforms. This program
corrects that deficiency and adds some features that I think
would be helpful. For example, you can now assign an event handler
to the compound widget. The program is written entirely as an object.
A companion program, COYOTE_FIELD, has much the same functionality,
but is written as a traditional compound widget. The point of writing
the same program in two different ways is to give you the opportunity
to compare and contrast the two methods. I personally think there
is no substitute for the power of object programs. :-)
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:
General programming.
CALLING SEQUENCE:
objectRef = FSC_INPUTFIELD(parent, Title='X Size: ", Value=256, /IntegerValue)
INPUT PARAMETERS:
parent -- The parent widget ID of the compound widget. Required.
INPUT KEYWORDS:
Column -- Set this keyword to have the Label Widget above the Text Widget.
CR_Only -- Set this keyword if you only want Carriage Return events. If
this keyword is not set, all events are returned. No events
are returned unless the EVENT_PRO or EVENT_FUNC keywords are used.
Decimal -- Set this keyword to the number of digits to the right of the decimal
point in FLOATVALUE and DOUBLEVALUE numbers.
Digits -- Set this keyword to the number of digits permitted in INTERGERVALUE and LONGVALUE numbers.
DoubleValue -- Set this keyword if you want DOUBLE values returned.
Event_Func -- Set this keyword to the name of an Event Function. If this
keyword is undefined and the Event_Pro keyword is undefined,
all compound widget events are handled internally and not
passed on to the parent widget.
Event_Pro -- Set this keyword to the name of an Event Procedure. If this
keyword is undefined and the Event_Func keyword is undefined,
all compound widget events are handled internally and not
passed on to the parent widget.
FieldFont -- The font name for the text in the Text Widget.
FloatValue -- Set this keyword for FLOAT values.
Frame -- Set this keyword to put a frame around the compound widget.
IntegerValue -- Set this keyword for INTEGER values.
LabelFont -- The font name for the text in the Label Widget.
LabelSize -- The X screen size of the Label Widget.
LongValue -- Set this keyword for LONG values.
Name -- A scalar string name of the object. (default = '')
Positive -- Set this keyword if you want only positive numbers allowed.
Row=row -- Set this keyword to have the Label beside the Text Widget. (The default.)
Scr_XSize -- The X screen size of the compound widget.
Scr_YSize -- The Y screen size of the compound widget.
StringValue -- Set this keyword for STRING values. (The default.)
Title -- The text to go on the Label Widget.
UValue -- A user value for any purpose.
Value -- The "value" of the compound widget.
XSize -- The X size of the Text Widget.
COMMON BLOCKS:
None.
RESTRICTIONS:
None.
EVENT STRUCTURE:
All events are handled internally unless either the Event_Pro or Event_Func
keywords are used to assign an event handler to the compound widget. By
default all events generated by the text widget are passed to the assigned
event handler. If you wish to receive only Carriage Return events, set the
CR_Only keyword.
event = { FSC_FIELD, $ ; The name of the event structure.
ID: 0L, $ ; The ID of the compound widget's top-level base.
TOP: 0L, $ ; The widget ID of the top-level base of the hierarchy.
HANDLER: 0L, $ ; The event handler ID. Filled out by IDL.
ObjRef: Obj_New(), $ ; The "self" object reference. Provided so you can call methods.
Value: Ptr_New(), $ ; A pointer to the widget value.
Type:"" ; A string indicating the type of data in the VALUE field.
} ; Values are "INT", "LONG", "FLOAT", "DOUBLE", or "STRING".
GETTING and SETTING VALUES:
Almost all the properties of the widget can be obtained or set via
the object's GetProperty and SetProperty methods (described below).
But since traditional compound widgets have the ability to get and
set the value of the compound widget, this capability is implemented
as special methods.
To get the value of the field, do this: value = objectRef->Get_Value()
To set the value of the field, so this: objectRef->Set_Value, value, /IntegerValue
The proper keyword should be used to set the data type of the value. If a keyword
is not used, the data type is determined from the value itself.
OBJECT PROCEDURE METHODS:
GetProperty -- This method allows various properties of the widget to be
returned via output keywords. The keywords that are available are:
CR_Only -- A flag, if set, means only report carriage return events.
DataType -- The data type of the field variable.
Decimal -- Set this keyword to the number of digits to the right of the decimal
point in FLOATVALUE and DOUBLEVALUE numbers.
Digits -- Set this keyword to the number of digits permitted in INTERGERVALUE and LONGVALUE numbers.
Event_Func -- The name of the event handler function.
Event_Pro -- The name of the event handler function.
Positive -- Indicates if the Positive number flag is set (1) or not (0).
UValue -- The user value assigned to the compound widget.
Value -- The "value" of the compound widget.
Name -- A scalar string name of the object.
MoveTab -- This method moves the focus to the widget identified in the "next" field,
which must be set with the SetTabNext method. No parameters. Called automatically
when a TAB character is typed in the text widget.
Resize -- This method allows you to resize the compound widget's text field.
The value parameter is an X screen size for the entire widget. The text
widget is sized by using the value obtained from this value minus the
X screen size of the label widget.
objectRef->Resize, screen_xsize_value
Set_Value -- This method allows you to set the "value" of the field. It takes
one positional parameter, which is the value.
objectRef->Set_Value, 5
Keywords available are these to set the type of the data. If keywords
are not used, the data type is determined from the value.
DoubleValue -- Set this keyword if you want DOUBLE values returned.
FloatValue -- Set this keyword for FLOAT values.
IntegerValue -- Set this keyword for INTEGER values.
LongValue -- Set this keyword for LONG values.
StringValue -- Set this keyword for STRING values. (The default.)
SetProperty -- This method allows various properties of the widget to be
set via input keywords. The keywords that are available are:
CR_Only -- Set this keyword if you only want Carriage Return events.
Decimal -- Set this keyword to the number of digits to the right of the decimal
point in FLOATVALUE and DOUBLEVALUE numbers.
Digits -- Set this keyword to the number of digits permitted in INTERGERVALUE and LONGVALUE numbers.
DoubleValue -- Set this keyword if you want DOUBLE values returned.
Event_Func -- Set this keyword to the name of an Event Function.
Event_Pro -- Set this keyword to the name of an Event Procedure.
FloatValue -- Set this keyword for FLOAT values.
IntegerValue -- Set this keyword for INTEGER values.
LabelSize -- The X screen size of the Label Widget.
LongValue -- Set this keyword for LONG values.
Name -- A scalar string name of the object. (default = '')
Positive -- Set this keyword to indicate only positive numbers are allowed.
Scr_XSize -- The X screen size of the text widget.
Scr_YSize -- The Y screen size of the text widget.
StringValue -- Set this keyword for STRING values. (The default.)
Title -- The text to go on the Label Widget.
UValue -- A user value for any purpose.
Value -- The "value" of the compound widget.
XSize -- The X size of the Text Widget.
OBJECT FUNCTIONS METHODS:
Get_Value -- Returns the "value" of the field. No parameters. Will be undefined
if a "number" field is blank. Should be checked before using:
IF N_Elements(objectRef->Get_Value()) NE 0 THEN Print, Value is: ', objectRef->Get_Value()
GetID -- Returns the widget identifier of the compound widget's top-level base.
(The first child of the parent widget.) No parameters.
GetLabelSize -- Returns the X screen size of the label widget. No parameters.
GetTextID -- Returns the widget identifier of the compound widget's text widget.
No parameters.
GetTextSize -- Returns the X screen size of the text widget. No parameters.
PRIVATE OBJECT METHODS:
Although there is really no such thing as a "private" method in IDL's
object implementation, some methods are used internally and not meant to
be acessed publicly. Here are a few of those methods. I list them because
it may be these private methods are ones you wish to override in subclassed
objects.
MoveTab -- This method moves the cursor to end of the text in the widget identified
by the nexttab field. (This will be set with the SetTabNext method.)
Text_Events -- The main event handler method for the compound widget. All
text widget events are processed here.
ReturnValue -- This function method accepts a string input value and converts
it to the type of data requested by the user.
Validate -- This function method examines all text input and removes unwanted
characters, depending upon the requested data type for the field. It makes it
impossible, for example, to type alphanumeric characters in an INTEGER field.
EXAMPLE:
An example program is provided at the end of the FSC_INPUTFIELD code. To run it,
type these commands:
IDL> .Compile FSC_InputField
IDL> Example
MODIFICATION HISTORY:
Written by: David Fanning, 23 NOV 1999.
Added DECIMAL and DIGITS keywords, 2 Jan 2000, DWF.
Changed the calling sequence to that of a function rather than an object
creation call. This is more familiar to users of compound widgets. 4 Jan 00. DWF.
Added GetID and Resize methods. 7 Jan 00. DWF.
Added the Positive keyword and functionality. 12 Jan 00. DWF
Modified (slightly) the behavior on deleting characters. 12 Jan 00. DWF.
If a number field is blank, the Get_Value method will now return an undefined variable.
Be sure you check this value before you use it for something! 17 Jan 00. DWF.
Fixed a small typo: "aveDecimal" to "haveDecimal". 10 March 2000. DWF.
Added the ability to tab between FSC_INPUTFIELD widgets with the SetTabNext,
MoveTab, and GetTextID methods. 31 July 2000. DWF.
Added NAME field property, a scalar string name for the object 2 AUG 2000 BT
Added ObjRef field to the FSC_FIELD event structure and added field selection
for the TAB events added 31 July. 7 AUG 2000. DWF
Added GetTextSize and GetLabelSize methods for obtaining the X screen
size of the text and label widgets, respectively. 30 Jan 2001. DWF.
(See pro/psconfig/fsc_inputfield.pro)
NAME:
FSC_PLOTWINDOW
PURPOSE:
The purpose of this compound widget is to create a resizeable
"plot window" inside a larger "page window". I'm not sure it
has any value except as a utility routine for the PostScript
configuration object FSC_PSCONFIG__DEFINE, but it's a neat
program anyway. :-)
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 routine for FSC_PSCONFIG__DEFINE.
CALLING SEQUENCE:
plotwindowObject = CW_PlotWindow(parent)
REQUIRED INPUT PARAMETERS:
parent - The parent base widget of this compound widget.
RETURN VALUE:
plotwindowObject - The object reference of the compound widget.
KEYWORDS:
COLOR - If set, display the window in "color". This is the default on 24-bit devices.
DEBUG - Set this keyword to turn traceback error handling on in the error handling code.
EVENT_PRO - The event procedure for the widget. Required for events to be generated. Otherwise, all events are handled internally.
LANDSCAPE - If set, display the page in landscape mode. Otherwise the page is display in portrait mode.
PAGESIZE - The "pagesize" of the widget. Possible values are: "LETTER", "LEDGER", "LEGAL", "A4", and "DISPLAY".
UNITS - A string indicating INCHES or CENTIMETER units. DEVICE units represented by a null string, "".
UVALUE - A user value for the caller of this program.
WINDOWCOLOR - A three-element array specifying the background window color (RGB).
WINDOWSIZE - The size of the "window" on the page. A four-element array of normalized coordinates in the form [x0, y0, x1, y1].
EVENT STRUCTURE:
The event structure that is returned from this compound widget is defined like this,
where the sizes and offsets locate the target "window" on the page in normalized units:
event = {ID:0L, TOP:0L, HANDLER:0L, XSize:0.0, YSize:0.0, XOffset:0.0, YOffset:0.0}
MODIFICATIONS:
Written by David Fanning, 31 January 2000.
Fixed a small bug that prevented it working on Macintosh computers. 26 Sept 2000. DWF.
Added a "DISPLAY" page size, so the program can be used to position
plots and other graphics in a display window. The "page area" will
have the same aspect ratio is the current graphics window. 17 March 2001. DWF.
(See pro/psconfig/fsc_plotwindow.pro)
NAME:
FSC_PSCONFIG__DEFINE
PURPOSE:
The purpose of this program is to implement an object that
can keep track of--and allow the user to change--the current
configuration of the PostScript device.
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:
General programming.
DOCUMENTATION:
Complete documentation for the FSC_PSCONFIG object, including
keyword and method descriptions, and example programs using the object
can be found on the Coyote's Guide to IDL Programming web page:
http://www.dfanning.com/programs/docs/fsc_psconfig.html
Or, if you would prefer, you can download a self-contained PDF file:
http://www.dfanning.com/programs/docs/fsc_psconfig.pdf
KEYWORDS:
Any keyword accepted by the FSC_PSCONFIG object can be used with
this program. Here are a few of the most popular keywords.
Bits_per_Pixel - The number of image bits saved for each image pixel: 2, 4, or 8. The default is 8.
Color - Set this keyword to select Color PostScript output. Turned on by default.
DefaultSetup - Set this keyword to the "name" of a default style. Current styles (you can easily
create and add your own to the source code) are the following:
"System (Portrait)" - The normal "default" system set-up. Also, "System".
"System (Landscape)" - The normal "default" landscape system set-up.
"Centered (Portrait)" - The window centered on the page. Also, "Center" or "Centered".
"Centered (Landscape)" - The window centered on the landscape page. Also, "Landscape".
"Square (Portrait)" - A square plot, centered on the page.
"Square (Landscape)" - A square plot, centered on the landscape page.
"Figure (Small)" - A small encapsulated figure size, centered on page. Also, "Encapsulated" or "Encapsulate".
"Figure (Large)" - A larger encapsulated figure size, centered on page. Also, "Figure".
"Color (Portrait)" - A "centered" plot, with color turned on. Also, "Color".
"Color (Landscape)" - A "centered" landscape plot, with color turned on.
Directory - Set this keyword to the name of the starting directory. The current directory is used by default.
Encapsulate - Set this keyword to select Encapsulated PostScript output. Turned off by default.
European - Set this keyword to indicate "european" mode (i.e., A4 page and centimeter units). Turned off by default.
Filename - Set thie keyword to the name of the PostScript file. The default is "idl.ps".
Inches - Set this keyword to indicate sizes and offsets are in inches as opposed to centimeters. Set by European keyword by default.
Landscape - Set this keyword to select Landscape page output. Portrait page output is the default.
PageType - Set this keyword to the "type" of page. Possible values are:
"Letter" - 8.5 by 11 inches. (Default, unless the European keyword is set.)
"Legal" - 8.5 by 14 inches.
"Ledger" - 11 by 17 inches.
"A4" - 21.0 by 29.7 centimeters. (Default, if the European keyword is set.)
XOffset - Set this keyword to the X Offset. Uses "System (Portrait)" defaults. (Note: offset calculated from lower-left corner of page.)
XSize - Set this keyword to the X size of the PostScript "window". Uses "System (Portrait)" defaults.
YOffset - Set this keyword to the Y Offset. Uses "System (Portrait)" defaults. (Note: offset calculated from lower-left corner of page.)
YSize - Set this keyword to the Y size of the PostScript "window". Uses "System (Portrait)" defaults.
In addition, the following keywords can be used:
CANCEL -- An output keyword that will be set to 1 if the user
chooses the Cancel button on the form. It will be 0 otherwise.
FONTINFO -- Set this keyword is you wish to have font information
appear on the form. The default is to not include font information.
FONTTYPE -- Set this keyword to a named variable that will indicate
the user's preference for font type. Values will be -1 (Hershey fonts),
0 (hardware fonts), and 1 (true-type fonts). This keyword will always
return -1 unless the FONTINFO keyword has also been set.
GROUP_LEADER -- Set this keyword to a widget identifier of the widget
you wish to be a group leader for this program.
EXAMPLE:
A simple sequence of using the object would look something like this:
psObject = Obj_New("FSC_PSCONFIG")
psObject->GUI
psKeywords = psObject->GetKeywords()
thisDevice = !D.Name
Set_Plot, 'PS'
Device, _Extra=psKeywords
TVImage, image
Device, /Close_File
Set_Plot, thisDevice
Obj_Destroy, psObject
Note that the object can also be called from the PS_CONFIG interface:
psKeywords = PSConfig()
OTHER PROGRAMS NEEDED:
The following programs are required to run this one:
fsc_droplist.pro
fsc_fileselect.pro
fsc_field.pro
fsc_plotwindow
MODIFICATIONS:
Written by David W. Fanning, 31 January 2000.
Added capability to call GUI methods when the current graphics device
doesn't support windows. Device is restored when the GUI exits. 11 May 2000. DWF.
Changed the default value for the Color keyword to 1. 16 May 2000. DWF.
Fixed a bug where filename changed when switching Setups. 8 AUG 2000. DWF.
Fixed a bug when saving setup in Landscape mode. 8 AUG 2000. DWF.
Added the ability to Get and Set the object's name via the SetProperty
and a very abbreviated GetProperty method. Also added a GetName method. 26 SEP 2000. DWF.
Fixed a problem in which the proper configuration was not restored if in Landscape mode. 20 Nov 2000. DWF.
Made a number of modifications at the request of Martin Schultz. 4 Dec 2000. DWF.
Fixed a bug when setting file and directory names with the SetProperty method. 18 Dec 2000. DWF.
Fixed a small problem in initializing the page size properly. 3 Jan 2001. DWF.
Corrected a problem that resulted from a change to FSC_DROPLIST. 6 Jan 2001. DWF.
Added the ability to restore the font type instead of always reverting to !P.Font. 7 Jan 2001. DWF.
Increased the length of the file/directory name fields. 7 Jan 2001. DWF.
Fixed another problem with Landscape mode interacting with A4 paper size. 7 Jan 2001. DWF.
Seems I only half fixed the previous problem. :-( 26 April 2001. DWF.
Forgot to update program to reflect change in FSC_FIELD. Fixed 26 April 2001. DWF.
Changed BOOKMAN keyword to BKMAN to avoid conflict with BOOKSTYLE keyword. 26 April 2001. DWF.
Modified the System Defaults to say "None" if none is used. Improved documentation. 10 September 2001. DWF.
Added the ability to specify a filename at the same time as a Default Setup. 10 September 2001. DWF.
Fixed a small problem in not setting new page sizes appropriately. 22 May 2002. DWF.
(See pro/psconfig/fsc_psconfig__define.pro)
NAME: func_ccm_fitrv, params PURPOSE: compute chi2 for the ccm_fitrv function CALLING SEQUENCE: called via a fitting program -- see ccm_fitrv.pro INPUTS: params - R_V = params[0]; norm = params[1] OUTPUTS: chi2 - chi squared for fit. COMMENTS: wavelength, redfac, and weights are passed via common block. unit weights are assumed if none are passed. REVISION HISTORY: 2003-Sep-10 Written by D. Finkbeiner & N.Padmanabhan, Princeton
(See pro/dust/func_ccm_fitrv.pro)
NAME:
func_fit
PURPOSE:
Fit X, Y positions to a functional form.
CALLING SEQUENCE:
res = func_fit( x, y, ncoeff, [invvar=, function_name=, $
ia=, inputans=, yfit=, double=double, _EXTRA= ]
INPUTS:
x - X values (independent variable)
y - Y values (dependent variable)
ncoeff - Number of coefficients to fit
invvar - Weight values (inverse variance)
OPTIONAL KEYWORDS:
function_name - Function to fit; options are:
'legendre'
'chebyshev'
Default to 'legendre'
ia - Array specifying free (1) and fixed (0) variables [NCOEFF]
inputans - If holding parameters fixed, set this array to those values
[NCOEFF]
double - If set, or if X, Y, or INVVAR are double-precision, then
return double-precision values
_EXTRA - Optional keywords for fitting function
OUTPUTS:
res - Fit coefficients [NCOEFF]
OPTIONAL OUTPUTS:
yfit - Fit evaluated at the points X
COMMENTS:
EXAMPLES:
BUGS:
PROCEDURES CALLED:
fchebyshev()
flegendre()
fpoly()
REVISION HISTORY:
10-Sep-1999 Written by S. Burles
16-Nov-1999 Modified by D. Schlegel to never fit more coefficients
than there are data points.
10-Jul-2001 Added fpoly, S. Burles
(See pro/trace/func_fit.pro)
NAME: garea PURPOSE: Calculate area of spherical polygon by calling mangle utility garea CALLING SEQUENCE: area=garea(polygon [, tol=, /verbose]) INPUTS: polygon - spherical polygon specification OPTIONAL INPUTS: tol - tolerance (arcsec) verbose - don't suppress garea output OUTPUTS: OPTIONAL INPUT/OUTPUTS: COMMENTS: EXAMPLES: BUGS: PROCEDURES CALLED: REVISION HISTORY: 07-Nov-2002 Written by Mike Blanton, NYU
(See pro/mangle/garea.pro)
NAME:
GAUSS1
AUTHOR:
Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
craigm@lheamail.gsfc.nasa.gov
PURPOSE:
Compute Gaussian curve given the mean, sigma and area.
MAJOR TOPICS:
Curve and Surface Fitting
CALLING SEQUENCE:
YVALS = GAUSS1(XVALS, [MEAN, SIGMA, AREA], SKEW=skew)
DESCRIPTION:
This routine computes the values of a Gaussian function whose
X-values, mean, sigma, and total area are given. It is meant to be
a demonstration for curve-fitting.
XVALS can be an array of X-values, in which case the returned
Y-values are an array as well. The second parameter to GAUSS1
should be an array containing the MEAN, SIGMA, and total AREA, in
that order.
INPUTS:
X - Array of X-values.
[MEAN, SIGMA, AREA] - the mean, sigma and total area of the
desired Gaussian curve.
INPUT KEYWORD PARAMETERS:
SKEW - You may specify a skew value. Default is no skew.
PEAK - if set then AREA is interpreted as the peak value rather
than the area under the peak.
RETURNS:
Returns the array of Y-values.
EXAMPLE:
p = [2.2D, 1.4D, 3000.D]
x = dindgen(200)*0.1 - 10.
y = gauss1(x, p)
Computes the values of the Gaussian at equispaced intervals
(spacing is 0.1). The gaussian has a mean of 2.2, standard
deviation of 1.4, and total area of 3000.
REFERENCES:
MODIFICATION HISTORY:
Written, Jul 1998, CM
Correct bug in normalization, CM, 01 Nov 1999
Optimized for speed, CM, 02 Nov 1999
Added copyright notice, 25 Mar 2001, CM
Added PEAK keyword, 30 Sep 2001, CM
$Id: gauss1.pro,v 1.2 2006/02/07 22:38:32 schlegel Exp $
(See pro/mpfit/gauss1.pro)
NAME:
GAUSS1P
AUTHOR:
Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
craigm@lheamail.gsfc.nasa.gov
PURPOSE:
Compute Gaussian curve given the mean, sigma and area (procedure).
MAJOR TOPICS:
Curve and Surface Fitting
CALLING SEQUENCE:
GAUSS1, XVALS, [MEAN, SIGMA, AREA], YVALS, SKEW=skew
DESCRIPTION:
This routine computes the values of a Gaussian function whose
X-values, mean, sigma, and total area are given. It is meant to be
a demonstration for curve-fitting.
XVALS can be an array of X-values, in which case the returned
Y-values are an array as well. The second parameter to GAUSS1
should be an array containing the MEAN, SIGMA, and total AREA, in
that order.
INPUTS:
X - Array of X-values.
[MEAN, SIGMA, AREA] - the mean, sigma and total area of the
desired Gaussian curve.
YVALS - returns the array of Y-values.
KEYWORD PARAMETERS:
SKEW - You may specify a skew value. Default is no skew.
EXAMPLE:
p = [2.2D, 1.4D, 3000.D]
x = dindgen(200)*0.1 - 10.
gauss1p, x, p, y
Computes the values of the Gaussian at equispaced intervals
(spacing is 0.1). The gaussian has a mean of 2.2, standard
deviation of 1.4, and total area of 3000.
REFERENCES:
MODIFICATION HISTORY:
Transcribed from GAUSS1, 13 Dec 1999, CM
Added copyright notice, 25 Mar 2001, CM
$Id: gauss1p.pro,v 1.2 2006/02/07 22:38:32 schlegel Exp $
(See pro/mpfit/gauss1p.pro)
NAME: GAUSS2 AUTHOR: Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770 craigm@lheamail.gsfc.nasa.gov PURPOSE: Compute Gaussian curve given the mean, sigma and area. MAJOR TOPICS: Curve and Surface Fitting CALLING SEQUENCE: YVALS = GAUSS2(X, Y, [XCENT, YCENT, SIGMA, PEAK]) DESCRIPTION: This routine computes the values of a Gaussian function whose X-values, mean, sigma, and total area are given. It is meant to be a demonstration for curve-fitting. XVALS can be an array of X-values, in which case the returned Y-values are an array as well. The second parameter to GAUSS1 should be an array containing the MEAN, SIGMA, and total AREA, in that order. INPUTS: X - 2-dimensional array of "X"-values. Y - 2-dimensional array of "Y"-values. XCENT - X-position of gaussian centroid. YCENT - Y-position of gaussian centroid. SIGMA - sigma of the curve (X and Y widths are the same). PEAK - the peak value of the gaussian function. RETURNS: Returns the array of Y-values. EXAMPLE: p = [2.2D, -0.7D, 1.4D, 3000.D] x = (dindgen(200)*0.1 - 10.) # (dblarr(200) + 1) y = (dblarr(200) + 1) # (dindgen(200)*0.1 - 10.) z = gauss2(x, y, p) Computes the values of the Gaussian at equispaced intervals in X and Y (spacing is 0.1). The gaussian has a centroid position of (2.2, -0.7), standard deviation of 1.4, and peak value of 3000. REFERENCES: MODIFICATION HISTORY: Written, 02 Oct 1999, CM Added copyright notice, 25 Mar 2001, CM $Id: gauss2.pro,v 1.2 2006/02/07 22:38:32 schlegel Exp $
(See pro/mpfit/gauss2.pro)
NAME:
gausspix1d
PURPOSE:
Routine to evaluate a 1D gaussian function (plus polynomial terms)
integrated over a pixel of width 1.
CALLING SEQUENCE:
gausspix, x, a, f, pder
INPUTS:
x - Dependent variable [NX].
a - Coefficients:
A[0] = center of the Gaussian in X
A[1] = sigma width of the Gaussian
A[2] = normalization of the Gaussian; total area = A[1] * A[2]
A[3...] = polynomial coefficients for background terms
OPTIONAL INPUTS:
OUTPUTS:
f - Evaluated function [NX].
pder - Array of partial derivatives [NX,NCOEFF].
OPTIONAL OUTPUTS:
COMMENTS:
This routine can be passed as a function to the IDL CURVEFIT function.
If X is type DOUBLE, then the return values are also type DOUBLE;
otherwise they are type FLOAT.
EXAMPLES:
BUGS:
PROCEDURES CALLED:
REVISION HISTORY:
04-Aug-2000 Written by D. Schlegel, Princeton
(See pro/math/gausspix1d.pro)
NAME:
gauss_overlap
PURPOSE: (one line)
calculate log integral, covariance, and mean of product of two gaussians
DESCRIPTION:
calculate log integral, covariance, and mean of product of two gaussians
CATEGORY:
Numerical
CALLING SEQUENCE:
gauss_overlap,mean1,covar1,mean2,covar2,mean=mean,covar=covar, $
logint=logint, invcovar=invcovar, /input_invcovar
INPUTS:
mean1 - [N] mean of first gaussian
covar1 - [N, N] covariance of first gaussian
mean2 - [N] mean of second gaussian
covar2 - [N, N] covariance of second gaussian
OPTIONAL INPUT PARAMETERS:
KEYWORD PARAMETERS:
/input_invcovar - covar1, covar2 are actually inverse covars
OUTPUTS:
mean - mean of global gaussian
covar - covariance of global gaussian
invcovar - inverse covariance of global gaussian
logint - natural log of integral of global gaussian
COMMON BLOCKS:
SIDE EFFECTS:
RESTRICTIONS:
PROCEDURE:
MODIFICATION HISTORY:
Blanton and Roweis 2003-02-18j
(See pro/math/gauss_overlap.pro)
NAME:
gridnd
PURPOSE:
determine positions on a grid, for easy access
CALLING SEQUENCE:
gridnd, x [, ix=, grid=, ngrid=, binsize=, igrid= ]
INPUTS:
x - [M,N] positions in M-dimensions
OPTIONAL INPUTS:
binsize - grid size (default 1.)
OUTPUTS:
grid - [nx[0]*nx[1]*...*nx[M-1]] set of pointers to particles in
each cell
ngrid - [nx[0]*nx[1]*nx[2]*...*nx[M-1]] number of particles in
each cell
igrid - [N] position in grid
xminmax - [2,M] limits of grid
nx - [M] dimensions of grid
COMMENTS:
This code is BETA! Use at your own risk.
REVISION HISTORY:
12-Oct-2005 Written by Mike Blanton, NYU
(See pro/math/gridnd.pro)
NAME:
group_indx
PURPOSE:
given group indices, yield multiplicity, plus an index linked list
CALLING SEQUENCE:
group_indx, ingroup, multgroup=multgroup, firstgroup=firstgroup, $
nextgroup=nextgroup
INPUTS:
ingroup - [N] group # of each element
OUTPUTS:
multgroup - [Ngroup] multiplicity of each group
firstgroup - [Ngroup] first member of each group
nextgroup - [N] for each member, the next member of its group
(-1) if no more
COMMENTS:
BUGS:
REVISION HISTORY:
2003-03-05 written by Michael Blanton (NYU)
(See pro/misc/group_indx.pro)
NAME: group_on_matches PURPOSE: given a list of objects and matches between them, find the groups CALLING SEQUENCE: group_on_matches, matches [, first=, next=, mult=, in=] INPUTS: matches - [N] array of pointers to list of which objects are matched OUTPUTS: first - [Ngroup] first member of each group mult - [Ngroup] multiplicity of each group in - [N] what group an object is in next - [N] next member of group an object is in (-1 if last) REVISION HISTORY: 2005-Oct-3 Written by Mike Blanton, NYU
(See pro/math/group_on_matches.pro)
NAME:
grow_object
PURPOSE:
Identify objects as the contiguous non-zero pixels in an image.
CALLING SEQUENCE:
mask = grow_object( image, [ xstart=, ystart=, putval=, /diagonal, nadd= ]
INPUTS:
image - Integer-valued image vector or array, where non-zero pixel
values indicate that an object touches that pixel.
OPTIONAL INPUTS:
xstart - Starting X position(s) for assembling the object; default to
settting all pixels where IMAGE != 0.
ystart - Starting Y position(s) for assembling the object; default to
settting all pixels where IMAGE != 0.
putval - Object ID(s) to put in MASK as positive-valued long integer;
default to a unique integer (starting at 1) for each object.
This can either be a scalar, or a vector with one element
per XSTART,YSTART position.
diagonal - If set, then consider diagonally-offset pixels as contigous
as well as pixels simply to the left, right, down, or up.
OUTPUTS:
mask - Mask with object IDs; zeros indicate that there is no object
in that pixel, and positive values are used as object IDs.
Negative values are not allowed.
OPTIONAL OUTPUTS:
nadd - Number of pixels added to all objects
COMMENTS:
Find the pixels that make up an "object" as the contiguous non-zero
pixels in IMAGE that touch the pixel XSTART,YSTART. All such pixels
have MASK set to PUTVAL.
If XSTART,YSTART,PUTVAL are not specified, then all objects are found
in the image and assigned unique object IDs in MASK starting at 1.
Note that in this case, max(MASK) is the number of objects.
The memory usage is 9*(nx+2)*(ny+2) bytes in addition to the input
image, where [nx,ny] are the dimensions of the input image.
EXAMPLES:
Create a random image of 0s and 1s, and identify all contiguous pixels
as objects:
IDL> image=smooth(randomu(123,100,100),5) GT 0.55 & mask = 0
IDL> mask = grow_object(image)
BUGS:
PROCEDURES CALLED:
Dynamic link to grow_obj.c
REVISION HISTORY:
20-May-2003 Written by D. Schlegel, Princeton
(See pro/image/grow_object.pro)
NAME:
gsc_nsky
PURPOSE:
Generate IDL structure for GSC catalogue at dec > -30 and m < 18.0
CALLING SEQUENCE:
gsc_nsky, [ catall ]
INPUTS:
<data files in $PHOTO_DATA/gsc>
OUTPUTS:
<data file (binary FITS table) in $PHOTO_DATA/kocat>
OPTIONAL OUTPUTS:
catall - Structure containing all objects dec > -30 deg
INPUT FILES:
$GSC_DIR/n????/*.gsc
$GSC_DIR/s????/*.gsc
OUTPUT FILES:
$GSC_DIR/gsc-Nsky.fits
EXAMPLES:
COMMENTS:
Note: these catalogues are written as F9.5 ASCII FITS tables. So
there is no reason to read them as double precision(?)
For more information see gsc/readme.txt
This can take a long time to run.
PROCEDURES CALLED:
djs_angle_match()
gsc_read_table()
mwrfits
REVISION HISTORY:
Written 2002-Mar-27 by D. Finkbeiner
(See pro/astrom/gsc_nsky.pro)
NAME:
gsc_read_table
PURPOSE:
Read one table from the GSC (Guide star catalogue)
CALLING SEQUENCE:
cat=gsc_read_table(fname, maglim=maglim, poserrlim=poserrlim)
INPUTS:
fname - file name(s) of catalogue FITS table (e.g. 0060.gsc )
(can be array)
KEYWORDS:
maglim - array of [lomag, himag] magnitudes to keep
poserrlim - discard stars with poserr higher than this limit
OUTPUTS:
cat - structure returned by function call
EXAMPLES:
COMMENTS:
Note: these catalogues are written as F9.5 ASCII FITS tables. So
there is no reason to read them as double precision(?)
REVISION HISTORY:
2002-Mar-27 Written by D. Finkbeiner, Princeton
(See pro/astrom/gsc_read_table.pro)
NAME:
GSSSPUTAST
PURPOSE:
Put GSSS astrometry parameters into a given FITS header.
CALLING SEQUENCE:
gsssputast, hdr, astr
INPUTS:
hdr - FITS header, string array. HDR will be updated to contain
the supplied astrometry.
astr - IDL structure containing the GSSS Astrometry information
.CTYPE[2] = ['RA---GSS','DEC--GSS']
.CRVAL[2] = plate center Ra, Dec (from PLTRAH, PLTRAM etc.)
.XLL,.YLL = offsets lower lefthand corner (integers)
.AMDX[13],.AMDY[13] = 12 transformation coefficients
.XSZ,.YSZ = X and Y pixel size in microns
.PLTSCL = plate scale in arc sec/mm
.PPO3,.PPO6 = orientation coefficients
OUTPUTS:
hdr - (Modified) FITS header with updated astrometry cards.
A brief HISTORY record is also added.
REVISION HISTORY:
Written 4 Nov 2000 - D. Finkbeiner
(See pro/astrom/gsssputast.pro)
NAME: gverts PURPOSE: Get vertices along edge of a polygon CALLING SEQUENCE: verts=gverts(polygon) INPUTS: polygon - spherical polygon specification OUTPUTS: verts - [3,N] locations of vertices OPTIONAL INPUT/OUTPUTS: COMMENTS: EXAMPLES: BUGS: PROCEDURES CALLED: REVISION HISTORY: 31-Jan-2002 Written by Mike Blanton, NYU
(See pro/mangle/gverts.pro)
NAME:
hdr2struct
PURPOSE:
Convert a string array with the format of a FITS header
into a single structure
CALLING SEQUENCE:
struct = hdr2struct(hdr)
INPUTS:
hdr: FITS-(like) header (array of strings)
OUTPUTS:
struct: Single structure with keyword(s) and comment(s)
OPTIONAL INPUTS:
COMMENTS:
Only passes back anonymous structures as it appends as it works
through all the header keywords. Use struct_append to make an
array from an array of headers.
PROCEDURES CALLED:
headfits()
REVISION HISTORY:
17-Jul-2001 Written by Burles
(See pro/fits/hdr2struct.pro)
NAME:
healcart_header
PURPOSE:
Generate mock header for healcart image
CALLING SEQUENCE:
header=healcart_header([ind, nside=nside])
OPTIONAL INPUTS:
ind - healcart index array, used only for size information
KEYWORDS:
nside - used for size information
OUTPUTS:
header - FITS header appropriate for atv
RESTRICTIONS:
Must be used with idlutils version of atv and xy2ad.
EXAMPLES:
COMMENTS:
Defines header for the approximately Cartesian reprojection of the
healpix map defined by healcart_ind.pro.
atv knows how to use this header, even though it is not standard
FITS.
Either nside or ind MUST be set.
REVISION HISTORY:
2003-May-10 Written by Douglas Finkbeiner, Princeton
(See pro/healpix/healcart_header.pro)
NAME:
healcart_ind
PURPOSE:
Generate index list for healcart projection
CALLING SEQUENCE:
ind = healcart_ind(data, /nest)
INPUTS:
data - array to determine size (not used for anything else)
if single element, interpret as Nside.
KEYWORDS:
nest - return index list for nested ordering
OUTPUTS:
ind - index array to transform healpix to quasi-cartesian
EXAMPLES:
ind = healcart_ind(kband, /nest)
atv, kband[ind]
COMMENTS:
This routine returns indices for the "healcart" projection,
which preserves the ring -> row mapping but stretches in
longitude to make a (nearly) Cartesian projection.
This routine should only be used for examining healpix maps -- any
quantitative computations should only be done on the healpix sphere.
Note: there are 4N-1 rows, not 4N
REVISION HISTORY:
2003-Feb-12 Written by Douglas Finkbeiner, Princeton
(See pro/healpix/healcart_ind.pro)
Returns the number of healpix pixels for a given resolution. npix = healnpix(res,[/nside]) If nside is set, then it returns nside Nikhil Padmanabhan, Princeton, July 29,2003
(See pro/healpix/healnpix.pro)
NAME: healpix2alm PURPOSE: Compute spherical harmonic transform (Alm) of a healpix map CALLING SEQUENCE: Alm = healpix2alm(data, lmax=lmax) INPUTS: data - healpix array [npix, nmap] (must be real) KEYWORDS: lmax - maximum l to compute (Default???) OUTPUTS: Alm - dcomplex array of Alm[l, m, nmap] (lmax by lmax) OPTIONAL OUTPUTS: RESTRICTIONS: EXAMPLES: COMMENTS: Note - the Ylm are not even perfectly orthonormal on the healpix sphere print,total(spher_harm(theta,phi,5,3,/doub)*conj(spher_harm(theta,phi,9,3,/doub)))*!dpi*4,format='(F20.10)' REVISION HISTORY: 2003-Feb-19 Written by Douglas Finkbeiner, Princeton 2003-Nov-12 Can call with multiple maps at a time - DPF & NP
(See pro/healpix/healpix2alm.pro)
A rapid power spectrum computation
code. Doesn't try to do *anything*
fancy or clever --- just straight
spherical transforms and averaging.
cl = healpix_cl(data, [lmax=lmax], cross=cross_data)
data === healpix array in ring format (can be multiple maps)
lmax=lmax === lmax sent to healpix2alm
cross === If you want to compute a cross power spectrum,
then send the second healpix map here. Must be the
same resolution
Nikhil Padmanabhan, Princeton
August 25, 2003
(See pro/healpix/healpix_cl.pro)
NAME:
healpix_ring_weight
PURPOSE:
read healpix ring weight files
CALLING SEQUENCE:
wt = healpix_ring_weight(nside, iring=iring)
INPUTS:
nside - healpix nside
OUTPUTS:
wt = the ring weights (4*nside-1 element array)
OPTIONAL OUTPUTS:
iring = ring number index array for each pixel (12*nside^2 array)
RESTRICTIONS:
breaks at nside > 8192
BUGS:
The method of computing iring is really dumb and slow, but works.
COMMENTS:
Gorski stores weight-1 as a float; we return weight as a double.
Because the weight array is symmetric, Gorski only stores half; we
return the whole array for simplicity.
The new mrdfits() (in v5_0_2b) replaces a " " in binary fits table
field names with "_" instead of removing it. Current version of
this routine works with both new and old mrdfits().
REVISION HISTORY:
2003-Mar-11 Written by Douglas Finkbeiner, Princeton
2003-Nov-12 Cache outputs - DPF & NP
2004-Aug-09 Fix fatal bug with new mrdfits().
(See pro/healpix/healpix_ring_weight.pro)
NAME: heal_rebin PURPOSE: rebin ring ordered healpix maps to different Nside CALLING SEQUENCE: newmap = heal_rebin(oldmap, newnside) INPUTS: oldmap - original map, ring order OUTPUTS: newmap - new rebinned map, ring order EXAMPLES: COMMENTS: Only call with ring-ordered maps. Use IDL rebin() if your map is already nested order. REVISION HISTORY: 2003-Dec-04 Written by Douglas Finkbeiner, Princeton
(See pro/healpix/heal_rebin.pro)
NAME: heal_smooth PURPOSE: Smooth ring-ordered healpix maps with spherical harmonic convolution CALLING SEQUENCE: smooth_map = heal_smooth(map, fwhm_arcmin, nside=, alm=, lmax= ) INPUTS: map - healpix map fwhm_arcmin - fwhm of gaussian smoothing kernel (arcmin) nside - set if map not set and alms passed alm - set if alms already known (saves time) lmax - maximum l value to use OPTIONAL INPUTS: KEYWORDS: OUTPUTS: OPTIONAL OUTPUTS: EXAMPLES: COMMENTS: Input maps must be ring ordered - use nest2ring otherwise REVISION HISTORY: 2003-Mar-14 Written by Douglas Finkbeiner, Princeton 2004-Aug-16 Avoid floating underflow in beam transform - DPF
(See pro/healpix/heal_smooth.pro)
NAME:
heliocentric
PURPOSE:
Compute correction term to add to velocities to convert to heliocentric.
CALLING SEQUENCE:
vcorr = heliocentric( ra, dec, [ epoch, jd=, tai=, $
longitude=, latitude=, altitude= ] )
INPUTS:
ra - Right ascension [degrees]
dec - Declination [degrees]
epoch - Epoch of observation for RA, DEC; default to 2000.
OPTIONAL KEYWORDS:
jd - Decimal Julian date. Note this should probably be
type DOUBLE.
tai - Number of seconds since Nov 17 1858; either JD or TAI
must be specified. Note this should probably either
be type DOUBLE or LONG64.
longitude - Longitude of observatory;
default to (360-105.820417) deg for APO
latitute - Latitude of observatory; default to 32.780361 deg for APO
altitude - Altitude of observatory in meters;
default to 2788 m for APO
OUTPUTS:
vcorr - Velocity correction term, in km/s, to add to measured
radial velocity to convert it to the heliocentric frame.
OPTIONAL OUTPUTS:
COMMENTS:
EXAMPLES:
BUGS:
PROCEDURES CALLED:
baryvel
ct2lst
REVISION HISTORY:
09-May-2000 Written by S. Burles & D. Schlegel
(See pro/coord/heliocentric.pro)
NAME: helio_to_lg PURPOSE: Convert heliocentric redshifts to Local-Group-centric redshifts. CALLING SEQUENCE: z_lg = helio_to_lg(z_helio,ra,dec) INPUTS: z_helio - heliocentric redshift RA - right ascension (deg, J2000) Dec - declination (deg, J2000) OUTPUTS: z_lg - local-group-centric redshift REVISION HISTORY: Originally imported by Hogg, 2002-08 or so. MRB corrected sign error in correction 2004-04-08 (affected tags v5_0_0 and previous)
(See pro/coord/helio_to_lg.pro)
NAME:
hms2dec
PURPOSE:
convert base-sixty string to decimal
CALLING SEQUENCE:
decimal = hms2dec(hmsstring)
INPUTS:
hmsstring - e.g. 'HH:MM:SS.S' or 'HHhMMmSS.S' or 'HH MM SS.S' etc.
OUTPUTS:
decimal - double-precision decimal number
RESTRICTIONS:
EXAMPLES:
ra = hms2dec(ra_string)*15
COMMENTS:
The strpos() loop below looks awkward but is probably a lot
faster than repstr()
I left most of the 20th century code intact, so I wouldn't
introduce any change in behavior.
REVISION HISTORY:
Written by Douglas Finkbeiner in ancient times
2000-Nov-29 fixed to handle "d" properly! - DPF
2005-Sep-16 call self recursively for array - DPF
(See pro/coord/hms2dec.pro)
NAME: Hogg_ARROW
PURPOSE: Draw a vector(s) with an arrow head
CATEGORY: Graphics
CALLING SEQUENCE:
Hogg_ARROW, x0, y0, x1, y1
INPUTS:
(x0, y0) = coordinates of beginning of vector(s). May be arrays
or scalars. Coordinates are in DEVICE coordinates
unless otherwise specified.
(x1, y1) = coordinates of endpoint (head) of vector.
x0, y0, x1, y1 must all have the same number of elements.
KEYWORD PARAMETERS:
DATA - if set, implies that coordinates are in data coords.
NORMALIZED - if set, coordinates are specified in normalized coords.
HSIZE = size of arrowhead. Default = 1/64th the width of the device,
(!D.X_SIZE / 64.).
If the size is positive, it is assumed to be in device
coordinate units. If it is NEGATIVE, then the head length
is set to the vector length * abs(hsize), giving heads
proportional in size to the bodies. The size is defined as
the length of each of the lines (separated by 60 degrees)
that make the head.
COLOR = drawing color. Default = highest color index.
HTHICK = thickness of heads. Default = 1.0.
SOLID = if set, make a solid arrow, using polygon fills, looks better
for thick arrows.
THICK = thickness of body. Default = 1.0.
HEAD_ANGLE = half-angle of arrow head in degrees. Default = 30.0
OUTPUTS:
No explicit outputs.
SIDE EFFECTS:
RESTRICTIONS:
PROCEDURE:
Straightforward.
Examples:
Draw an arrow from (100,150) to (300,350) in DEVICE units.
Hogg_ARROW, 100, 150, 300, 350
Draw a sine wave with arrows from the line Y=0 to
sin(x/4).
X = FINDGEN(50)
Y = SIN(x/4) ;Make sin wave
PLOT, X, Y
Hogg_ARROW, X, REPLICATE(0,50), X, Y, /DATA
MODIFICATION HISTORY:
DMS, Feb, 1992.
DMS, Sept, 1992. Added /SOLID.
2005-03-08 - added head_angle -- Hogg (NYU)
(See pro/plot/hogg_arrow.pro)
NAME: hogg_autocrop_image PURPOSE: remove whitespace border on image read by read_image REVISION HISTORY: 2003-01-31 written - Hogg
(See pro/plot/hogg_autocrop_image.pro)
NAME:
hogg_bwify
PURPOSE:
make b/w JPG image from color JPG image
INPUTS:
infile - file name of color image
outfile - file name for b/w image
OPTIONAL INPUTS:
rebinfactor - make outfile smaller by factor rebinfactor
BUGS:
- Just uses the r image; it should have various options for how to
make the b/w image from the color one.
- Always inverts; this should be an option.
REVISION HISTORY:
2004-01-07 commented - Hogg
(See pro/rgbcolor/hogg_bwify.pro)
NAME: hogg_directions PURPOSE: Overplot directions to other sky locations on a picture of the sky. INPUTS: aref,dref - reference RA,Dec aa,dd - RA,Dec lists for things to point to name - list of names of those things hdr - FITS header with relevant astrometry structure OPTIONAL INPUTS: length - length of arrows in degrees; default 1/60 OUTPUTS: [overlay on currently open plot] BUGS: - Not tested. - Doesn't work with GSSS headers. - Hacks from nw_ad_grid duplicated here, stupidly. REVISION HISTORY: 2005-09-11 started - Hogg (NYU)
(See pro/rgbcolor/hogg_directions.pro)
NAME:
hogg_greyscale_plot
PURPOSE:
Make a pretty greyscale plot from an astronomical image.
CALLING SEQUENCE:
hogg_greyscale_plot, data,filename
INPUTS:
data the image
filename name for the output PostScript file
OPTIONAL INPUTS:
pixscale units per pixel, eg arcmin/pixel
scalename units, eg "arcmin"
lo,hi levels to appear totally black (lo) and totally white (hi)
(these are in terms of sigma if sigma keyword is set); if
hi<lo, the image is made negative
title title for the plot
xpt,ypt x and y vectors of points to overplot -- set symbols with
psym and !P.SYMSIZE
psym plotting symbol (may be vector)
OUTPUTS:
a PostScript file called filename
KEYWORDS:
sigma when set, take lo and hi to be in terms of the sigma in the
center part of the image from djs_iterstat, and relative to the
mean from iterstat
noaxes don't plot axes and labels
COMMENTS:
The source code can be easily modified to include contouring. In fact
the next revision ought to add optional contouring keywords and inputs.
BUGS/FEATURES:
There may be something wrong with the axes; check few-pixel images.
No contouring available (but see "COMMENTS" and the source code).
Probably doesn't work on multi-plot pages; not really checked.
REVISION HISTORY:
1999-08-01 Written - Hogg
2001-05-01 Fonts improved - Hogg
2002-09-16 Added overplotting - Hogg
(See pro/plot/hogg_greyscale_plot.pro)
NAME: hogg_histogram PURPOSE: Multi-dimensional histogramming function. CALLING SEQUENCE: hist = hogg_histogram(data,range,nbin,weight=weight,err=err) INPUTS: data - [d,M] array of d-dimensional data values range - [2,d] min and max value for every dimension nbin - [d] array of numbers of bins in each direction OPTIONAL INPUTS: weight - [M] array of weights for the data points OUTPUTS: hist - [d,P] array of numbers of points (or total weight) in each bin OPTIONAL OUTPUTS: err - [d,P] array of Poisson errors BUGS: Slow -- very slow. Not memory-efficient. Doesn't deal well with small bin sizes. Doesn't output grid bin positions. COMMENTS: Doesn't divide by bin "volumes". REVISION HISTORY: 2003-07-17 written - Hogg (NYU and NYC Criminal Court)
(See pro/image/hogg_histogram.pro)
NAME: hogg_iau_name PURPOSE: properly format astronomical source names to the IAU convention INPUTS: ra - J2000 deg dec - J2000 deg prefix - survey prefix OPTIONAL INPUTS: precision - how many decimal places to put on dec; ra gets one more COMMENTS: Defaults to SDSS name conventions. Don't EVER use goddard/pro/astro/adstring.pro. BUGS: Enforces J2000 "J". Doesn't deal properly with precision<0 names, which *can* exist. REVISION HISTORY: 2004-10-24 started by Hogg (NYU)
(See pro/misc/hogg_iau_name.pro)
NAME:
hogg_image_overlay
PURPOSE:
Bitmap PostScript file to make an image overlay.
CALLING SEQUENCE:
overlay= hogg_image_overlay(psfile,naxis1,naxis2)
EXAMPLES:
INPUTS:
psfile - input filename
naxis1 - width in pixels to make overlay
naxis2 - height in pixels
OPTIONAL INPUTS:
factor - integer factor to use for antialiasing; default 2;
set to 1 for no antialiasing
OUTPUT:
overlay - overlay with plot material added
COMMENTS:
BUGS:
- Relies on horrifying UNIX bitmapping code.
- Makes insecure intermediate PPM file.
DEPENDENCIES:
pstopnm etc
REVISION HISTORY:
2004-02-28 written - Hogg
(See pro/rgbcolor/hogg_image_overlay.pro)
NAME:
hogg_image_overlay_plot
PURPOSE:
Make bitmapped overlay for rgb images.
CALLING SEQUENCE:
hogg_image_overlay_plot, xx,yy,naxis1,naxis2,overlay, $
[extras for plot procedure]
EXAMPLES:
INPUTS:
xx,yy - points to plot
naxis1 - width in pixels to make overlay
naxis2 - height in pixels
overlay - overlay to be added to (fine if not set)
[extras] - plotting inputs, just like for "plot" procedure
OPTIONAL INPUTS:
factor - integer factor to use for antialiasing; default 2;
set to 1 for no antialiasing
OUTPUT:
overlay - overlay with plot material added
COMMENTS:
- Never makes axes!
BUGS:
- Relies on horrifying UNIX bitmapping code.
- Makes insecure intermediate PS file.
DEPENDENCIES:
pstopnm etc
REVISION HISTORY:
2004-02-28 written - Hogg
(See pro/rgbcolor/hogg_image_overlay_plot.pro)
NAME: hogg_interval PURPOSE: find best interval for tickmarks on a plot INPUTS: range - the range for the axis OPTIONAL INPUTS: nticks - the approximate, desired number of ticks; default 5 BUGS: Goes insane if range contains NaN. REVISION HISTORY: 2002-03-25 written - Hogg
(See pro/plot/hogg_interval.pro)
NAME:
hogg_iterated_ad2xy
PURPOSE:
Same as ad2xy, but assuming that xy2ad is perfect.
COMMENTS:
Starts with a first guess that everything is at (x,y)=(0,0) and
then uses Newton's method to iterate to the correct (x,y)
values.
INPUTS:
a,d - vectors of RA,Dec
astr - astrometric structure
OPTIONAL INPUTS:
tol - maximum allowed angular difference (deg) between input
a,d values and the values obtained by running xy2ad on
the output; default to 0.01/3600.0 (0.01 arcsec)
OUTPUTS:
x,y - vectors of x,y
REVISION HISTORY:
2005-09-04 started - Hogg (NYU)
(See pro/astrom/hogg_iterated_ad2xy.pro)
NAME:
hogg_iter_linfit
PURPOSE:
Perform iterated linear least-squares fit with sigma-clipping.
COMMENTS:
Solves the over-constrained equation yy=aa##xx, where the yy are
the "data" and the xx are the "parameters".
CALLING SEQUENCE:
hogg_iter_linfit, aa,yy,ww,xx [,covar=covar]
INPUTS:
aa - input matrix, either transposition is fine
yy - input vector of data in equation yy=aa##xx
ww - weights for the components of yy; should be proportional to
(1/err^2); these are assumed to be exactly (1/err)^2 if keyword
"truesigma" is set
OPTIONAL INPUTS:
nsigma - number of sigma for clipping; defaults to 3.0
maxiter - maximum number of clipping iterations; defaults to 100
KEYWORDS
median - clip by deviation from median rather than from mean
verbose - output blow-by-blow
sacred - don't update ww values to indicate clipped-out data points
truesigma - don't rescale weights and covariance matrix -- assume that the
supplied weights are exactly 1/sigma^2
OUTPUTS:
xx - output parameters in equation yy=aa##xx
covar - covariance matrix for the fit parameters
ww - ww values set to zero where data points clipped, and re-
scaled so that chisq^2 is unity per degree of freedom, unless
keyword "sacred" is set
EXAMPLE:
Linear regression of ydata (with inverse variance ydata_ivar) on
xdata, with 5-sigma clipping:
aa= dblarr(2,n_elements(xdata))
aa[0,*]=1.D0
aa[1,*]=xdata
hogg_iter_linfit, aa, ydata, ydata_ivar, coeffs, covar=covar, nsigma=5
Resulting coefficients are in coeffs[0] and coeffs[1]
BUGS:
Covariance matrix is an approximation which assumes that the rms of the
fit is consistent with the errors in the yy, or something like that.
This could be changed if the input weights were always the true
1/sigma^2 values.
REVISION HISTORY:
2000-Jun-03 written by Hogg, IAS
2000-Jun-12 output covariance matrix - Hogg
2000-Sep-06 added sacred keyword and updated ww matrix - Hogg
2001-Apr-10 allow rejected points to return to fit - Hogg
(See pro/math/hogg_iter_linfit.pro)
NAME:
hogg_make_astr
PURPOSE:
Generate the astrometric header for a particular pointing and
orientation.
CALLING SEQUENCE:
astr= hogg_make_astr(racen,deccen,dra,ddec $
[,pixscale=pixscale] [etc])
INPUTS:
racen - Central RA [deg]
deccen - Central DEC [deg]
dra - Size in the X dimension; default to 0.5 deg
ddec - Size in the Y dimension; default to 0.5 deg
OPTIONAL INPUTS:
pixscale - Pixel scale (deg); default 1.0/3600
orientation - angle (deg) for the north vector to make relative to
straight up (y direction), CCW being positive
npixround - round array dimensions (naxis1 and naxis2) to nearest
factor of npixround; default to 8.
KEYWORDS:
orthographic - Make orthographic "-SIN" header instead of
gnomonic "-TAN" header.
OUTPUTS:
astr - Astrometry structure with NAXIS keyword added
OPTIONAL OUTPUTS:
pixscale - Set, if not input
COMMENTS:
EXAMPLES:
BUGS:
REVISION HISTORY:
2003-Nov-21 Written by D. Schlegel (Princeton) & D. Hogg (NYU)
2003-Dec-02 Modified to produce simpler headers - Hogg
2004-Apr-18 Use make_astr to define astrom structure - DPF
2004-Jun-17 Modified to make "orthographic" headers on request - Hogg
2005-Aug-31 Changed name and put into idlutils - Hogg
(See pro/astrom/hogg_make_astr.pro)
NAME:
hogg_make_image_label
PURPOSE:
make text label for RGB images
CALLING SEQUENCE:
label= hogg_make_image_label(title,naxis1, [subtitle1=,subtitle2=])
EXAMPLES:
label= hogg_make_image_label('M51',2048, $
subtitle1='data from the Sloan Digital Sky Survey', $
subtitle2='image by Hogg, Wherry, Blanton, Finkbeiner, Schlegel')
INPUTS:
title - main title text
naxis1 - width in pixels to make the label
OPTIONAL INPUTS:
subtitle1 - first subtitle
subtitle2 - second subtitle; defaults to idlutils plug
OUTPUT:
label - [naxis1,n2] image containing text
COMMENTS:
BUGS:
- Format and label padding all hard-wired.
- Makes insecure temporary LaTeX file etc.
- Relies on horrifying UNIX bitmapping code.
- Slightly odd behavior if subtitles 1 and 2 are both empty.
DEPENDENCIES:
LaTeX etc
pstopnm etc
REVISION HISTORY:
2003-12-05 written - Hogg
(See pro/rgbcolor/hogg_make_image_label.pro)
NAME:
hogg_manyd_meanplot
PURPOSE:
plot N+1-dimensional data sets, in the mean!
INPUTS:
weight [N] array of data-point weights
point [d,N] array of data points - N vectors of dimension d
zdim index of quantity to be averaged in the plots
psfilename name for PostScript file; if no filename is given, then the
plots will simply be sent to the currently active device
OPTIONAL INPUTS:
nsig number of sigma for half-width of each plot; default 5
dbin [d] array of bin widths for averaging
label [d] array of axis labels; default 'x_i'
range [2,d] array of plotting ranges
xdims,ydims indices of data dimensions to use on each x and y axis
axis_char_scale size of characters on labels
default_font font command to send to set font for plotting
KEYWORDS:
[etc] [options for hogg_meanplot, see documentation]
OUTPUTS:
OPTIONAL OUTPUTS:
BUGS:
WAY too much duplicated code with hogg_manyd_scatterplot.
DEPENDENCIES:
REVISION HISTORY:
2003-01-12 translated from hogg_manyd_scatterplot
(See pro/plot/hogg_manyd_meanplot.pro)
NAME:
hogg_manyd_scatterplot
PURPOSE:
plot N-dimensional data sets
INPUTS:
weight [N] array of data-point weights
point [d,N] array of data points - N vectors of dimension d
psfilename name for PostScript file; if no filename is given, then the
plots will simply be sent to the currently active device
OPTIONAL INPUTS:
nsig number of sigma for half-width of each plot; default 5
label [d] array of axis labels; default 'x_i'
range [2,d] array of plotting ranges
xdims,ydims indices of data dimensions to use on each x and y axis
axis_char_scale size of characters on labels
default_font font command to send to set font for plotting
extrafun name of procedure to call after each plot for overplotting
(procedure takes two inputs: d1 and d2 indicating
x and y dimensions of the current plot)
title puts string title on top of page
KEYWORDS:
nodata don't plot anything at all, just axes!
meanweight - plot the mean of the weight values that land in
that pixel, rather than the total; don't use
with /conditional!
[etc] [options for hogg_scatterplot, see documentation]
OUTPUTS:
OPTIONAL OUTPUTS:
manyd [nx,ny,NX,NY] data
BUGS:
Can get infinite plot ranges.
DEPENDENCIES:
hogg_plot_defaults
hogg_scatterplot
plus much, much more
REVISION HISTORY:
2002-12-14 re-constructed from ex_max_plot -- Hogg
(See pro/plot/hogg_manyd_scatterplot.pro)
NAME:
hogg_mcmc
PURPOSE:
Make a Markov Chain Monte Carlo chain.
INPUTS:
seed - random number seed for randomu()
step_func - function that takes a step in parameter space
like_func - function that computes the likelihood
nstep - number of links
pars - initial parameters (can be an array or structure)
KEYWORDS:
log - like_func returns log_e(likelihood), not straight
likelihood
OUTPUTS:
pars - array of parameters, sorted from most to least likely
like - array of likelihoods for the pars
REVISION HISTORY:
2005-03-31 started - Hogg
(See pro/mcmc/hogg_mcmc.pro)
NAME:
hogg_mcmc_step
PURPOSE:
Make one step in a Markov Chain Monte Carlo.
INPUTS:
seed - random number seed for randomu()
pars - initial parameters (can be an array or structure)
like - initial likelihood
step_func - function that takes a step in parameter space
like_func - function that computes the likelihood
KEYWORDS:
log - like_func returns log_e(likelihood), not straight
likelihood
OUTPUTS:
newpars - new parameters
newlike - new likelihood
BUGS:
- I made up the algorithm based on things I sort-of remember.
REVISION HISTORY:
2005-03-31 started - Hogg
(See pro/mcmc/hogg_mcmc_step.pro)
NAME: hogg_mcmc_test PURPOSE: Test the hogg_mcmc code. REVISION HISTORY: 2005-03-31 started - Hogg
(See pro/mcmc/hogg_mcmc_test.pro)
NAME:
hogg_meanplot
PURPOSE:
plot sliding mean of one quantity vs two others
COMMENTS:
Doesn't overplot -- only plots. This is because IDL blots
out any other information on the plot anyway.
INPUTS:
x,y - data values
z - quantity to average
OPTIONAL INPUTS:
weight - weighting for data points; default unity
xrange - x range; default to the number > minnum area
yrange - y range; same default
dxbin - size of boxes in x-dir; default to a function of
first and second moments
dybin - size of boxes in y-dir; same default
levels - contour levels; default to a function of image range
minnum - minimum number of points in a sliding box to plot;
default 100
c_colors - fill colors
c_thick - contour line thicknesses
axis_char_scale - scale to apply to axis labels
nearest - take mean over nearest few points based on this number
(instead of a fixed smoothing scale)
KEYWORDS:
nofill - don't fill the contours with color
noperimeter - don't plot contour at minnum
nobox - don't plot box
nolines - don't plot lines between contours
nodata - don't plot anything other than axes
maskonly - plot only the minnum mask
nocontourlabels - don't label the contours
input_mean - don't recalculate means, use input in bin_mean
overplot - don't remake axes, just plot over
OPTIONAL INPUT/OUTPUTS:
bin_mean - calculated mean value (or input mean value if
/input_mean set) in each bin
bin_scatter - calculated scatter around the mean in each bin
bin_weight - total weight in each bin
bin_number - total number of data points in each bin
COMMENTS:
"nearest" input should be used with caution --- this is generally
a BAD way to smooth!
REVISION HISTORY:
2003-01-08 written - Hogg
(See pro/plot/hogg_meanplot.pro)
NAME: HOGG_MRDFITS PURPOSE: Wrapper on MRDFITS() to read in a FITS file one chunk at a time CALLING SEQUENCE: INPUTS: see MRDFITS KEYWORDS: see MRDFITS nrowchunk - Number of rows to read at a time; default to 2880 COMMENTS: Useful when "columns" is set, so you can get a couple of columns without holding the whole file in memory OUTPUTS: see MRDFITS REVISION HISTORY: 2002-02-08 written by Hogg
(See pro/fits/hogg_mrdfits.pro)
NAME:
hogg_name2radec
PURPOSE:
Takes properly-formatted iau name in "J" format and converts it into ra,dec
USE AT YOUR OWN RISK; NO IMPLIED WARRANTY
EXAMPLES:
IDL> hogg_name2radec, 'SDSS_J013713.84-092820.4',ra,dec
IDL> print, ra,dec
24.307671 -9.4723336
IDL> print, hogg_iau_name(ra,dec)
SDSS J013713.84-092820.4
INPUTS:
name - name
OUTPUTS:
ra - J2000 deg
dec - J2000 deg
OPTIONAL INPUTS:
COMMENTS:
Doesn't require anything particular *before* the J, but it assumes
(dumbly) that the RA begins at the last J.
BUGS:
USE AT YOUR OWN RISK; NO IMPLIED WARRANTY
Requires J2000 "J".
Ultra-brittle.
REVISION HISTORY:
2004-10-22 started by you know who
(See pro/misc/hogg_name2radec.pro)
NAME: hogg_ned_name2radec PURPOSE: Takes a name, throws it at NED, retreives RA, Dec (J2000) USE AT YOUR OWN RISK; NO IMPLIED WARRANTY INPUTS: name - name OUTPUTS: ra - J2000 deg dec - J2000 deg OPTIONAL INPUTS: COMMENTS: BUGS: Does nasty things to the name to format it for URL-ifying. USE AT YOUR OWN RISK; NO IMPLIED WARRANTY. Relies on NED not changing in any substantial way! DEPENDENCIES: wget REVISION HISTORY: 2005-02-01 started by you know who
(See pro/misc/hogg_ned_name2radec.pro)
NAME: hogg_oplot_covar PURPOSE: Wrapper for oplot that plots covariance ellipses. CALLING SEQUENCE: hogg_oplot_covar, x,y,covar,... INPUT: x,y - [N] arrays of points covar - [2,2,N] array of symmetric covariance matrices KEYWORDS: fill - make filled rather than outlined ellipses OPTIONAL INPUTS: nsigma - plot n-sigma ellipse (default to 1) color - color or vector of [N] colors thick - line thickness or vector of [N] line thicknesses [keywords for IDL plot] COMMENTS: Allows color to be a [N] array. REVISION HISTORY: 2002-04-11 written by Hogg
(See pro/plot/hogg_oplot_covar.pro)
NAME:
hogg_plothist
PURPOSE:
plot histogram of weighted points
INPUTS:
x - data values
OPTIONAL INPUTS:
weight - weighting for data points; default unity
npix - number of bins in range
xrange - x range; default minmax(x)
yrange - y range; default chosen dumbly!
[etc] - extras passed to "plot" command
KEYWORDS:
overplot - overplot, don't plot anew
ploterr - plot Poisson error bars too
log - take log_10 before plotting
meanweight - plot the mean of the weights in each bin rather than
the total of the weights; don't divide by binwidth
totalweight - plot the total weight; don't divide by binwidth
dontplot - just calculate, do not plot anything
OPTIONAL OUTPUTS:
xvec - [npix] vector of x values of grid pixel centers
hist - the histogram itself (ie, the total weight in each
bin divided by the binwidth).
err - the Poisson uncertainties on each point (ie, the
sqrt of the sum of the squares of the weights,
divided by the binwidth).
COMMENTS:
Divides total weight in each bin by binwidth, unless /totalweight
or /meanweight is set.
BUGS:
Doesn't check inputs.
Super-slow!
REVISION HISTORY:
2002-12-14 written -- Hogg
(See pro/plot/hogg_plothist.pro)
NAME: hogg_plot_defaults PURPOSE: Set plotting defaults for all "hogg_" plots CALLING SEQUENCE: hogg_plot_defaults REVISION HISTORY: 2003-01-08 written - Hogg
(See pro/plot/hogg_plot_defaults.pro)
NAME: hogg_read_postscript PURPOSE: read in a postscript file as an IDL data image INPUTS: filename OPTIONAL INPUTS: resolution - in dots per inch; default 75 KEYWORDS: noantialias - don't do Hogg's antialiasing trick OUTPUTS: image - [3,N,N] array of byte images for R,G,B planes BUGS: Makes DUMB temporary files; I am sure there is a way to make smart ones. REVISION HISTORY: 2003-01-31 written - Hogg
(See pro/plot/hogg_read_postscript.pro)
NAME: hogg_rgb_entropy PURPOSE: Compute "entropy" of an RGB representation of an image INPUTS: colors - [nx,ny,3] image of values in range [0.0,1.0] bits - number of bits to assign per pixel per color (default 4) OUTPUT: entropy - entropy of the representation BUGS: REVISION HISTORY: 2004-03-20 started - Hogg
(See pro/rgbcolor/hogg_rgb_entropy.pro)
NAME:
hogg_scatterplot
PURPOSE:
plot greyscale scatterplot with contours
COMMENTS:
Doesn't overplot -- only plots. This is because the IDL tvscl blots
out any other information on the plot.
Compares cumulated grid to the *total* weight -- ie, including points
outside the range (which is what you want; trust me).
INPUTS:
x,y - data values
OPTIONAL INPUTS:
weight - weighting for data points; default unity
xnpix - width of greyscale grid in pixels; default 0.3*sqrt(N)
ynpix - height of greyscale grid in pixels; same default
xrange - x range; default minmax(x)
yrange - y range; default minmax(y)
levels - contour levels; default in source code
quantiles - quantiles to plot on conditional plot; default
[0.25,0.5,0.75]
cthick - thickness for contours
exponent - stretch greyscale at exponent power; default 1.0
satfrac - fraction of pixels to saturate in greyscale; default 0
darkest - darkest shade at saturation; default 127; lower darker
outliers_psym - NEEDS DOCUMENTATION
outliers_color - NEEDS DOCUMENTATION
outliers_symsize - NEEDS DOCUMENTATION
[etc] - extras passed to "plot" command
KEYWORDS:
conditional - normalize each column separately
labelcont - label contours with numbers
internal_weight - use only the points in the image to determine
contours
nogreyscale - don't plot the greyscale
adqgreyscale - do greyscale in the "ADQ" style (only works when
conditional is set)
outliers - NEEDS DOCUMENTATION
meanweight - plot the mean of the weight values that land in
that pixel, rather than the total; don't use
with /conditional!
OPTIONAL OUTPUTS:
xvec - [xnpix] vector of x values of grid pixel centers
yvec - [ynpix] vector of y values of grid pixel centers
grid - the greyscale grid [xnpix,ynpix] that was plotted
cumimage - the cumulated grid [xnpix,ynpix] that was contoured
outquantiles - the plotted quantiles (when /conditional is set)
ioutliers - indices of outlier points
COMMENTS:
When output, the grid is in units of unit_weight, not in
unit_weight per unit_x per unit_y (as you would want to do if
you wanted to directly compare two results using different
resolution grids); the user will have to convert to that themselves.
BUGS:
Doesn't check inputs.
Ought to specify saturation not as a fraction of pixels, but as a fraction
of the total weight (ie, saturate inside a particular, specifiable
confidence region). This mod is trivial.
Ought to specify min and max grey levels, and contour colors.
Contour thicknesses hard-coded to unity.
DEPENDENCIES:
hogg_histogram
plus much, much more
REVISION HISTORY:
2002-12-04 written --- Hogg
(See pro/plot/hogg_scatterplot.pro)
NAME:
hogg_sky_direction
PURPOSE:
Return the direction (Delta-alpha,Delta-delta) of one RA, Dec
relative to a reference RA, Dec.
CALLING SEQUENCE:
hogg_sky_direction, aref,dref,ap,dp,Da,Dd
INPUT:
aref,dref - reference RA,Dec
ap,dp - RA,Dec of the point to which the arrow points
OUTPUT:
Da - Delta-alpha (small change in RA*cos(Dec)) for arrow
Dd - Delta-delta (small change in Dec) for arrow
COMMENTS:
- Da,Dd comprise a vector of arbitrary length; it is the user's
responsibility to re-scale it.
- Da is not a change in RA, but a change in RA*cos(Dec).
BUGS:
- Inputs must all be scalars or else hell breaks loose.
REVISION HISTORY:
2005-09-10 started - Hogg (NYU)
(See pro/coord/hogg_sky_direction.pro)
NAME:
hogg_snap_integer
PURPOSE:
Randomly snap floats or doubles to nearest integers up and down so
that the mean is correct on average.
CALLING SEQUENCE:
ii= hogg_snap_integer(seed,xx)
INPUTS:
seed - long seed for randomu
xx - array of floating point numbers
OUTPUTS:
ii - array of integers
BUGS:
Relies on "true" being 1.
REVISION HISTORY:
2003-08-13 written - Hogg
(See pro/math/hogg_snap_integer.pro)
NAME:
hogg_strsplit
PURPOSE:
split strings on whitespace, except inside double quotes, plus other
stuff specialized for yanny_read
BUGS:
demolishes the string
REVISION HISTORY:
2002-10-10 written - Hogg
(See pro/yanny/hogg_strsplit.pro)
NAME:
hogg_tp_shift
PURPOSE:
Shift tangent point on the sphere (CRVAL, in RA, Dec units),
adjusting simultaneously the CD matrix (to deal with coordinate
issues near the celestial poles). The idea is to shift the WCS
without substantially rotating the tangent-plane coordinates, even
when near the poles.
INPUTS:
astr - astrometry structure
crval - new crval (tangent point on the sphere) to insert
OUTPUTS:
- new astrometry structure
REVISION HISTORY:
2005-08-21 started - Hogg (NYU)
(See pro/astrom/hogg_tp_shift.pro)
NAME:
hogg_unquoted_regex
PURPOSE:
return the regex which matches the first occurence of the given
regex not inside quotemarks
INPUT:
regex - naked regular expression
OPTIONAL INPUT:
quotemark - thing to use as the quotation mark, default to '"'
REVISION HISTORY:
2002-10-11 written - Hogg
(See pro/yanny/hogg_unquoted_regex.pro)
NAME:
hogg_usersym
PURPOSE:
make an n-sided plotting point
USAGE:
hogg_usersym, N [,scale=scale,/diagonal]
plot, x,y,psym=8
INPUTS:
N - number of sides on the polygon
OPTIONAL INPUTS:
scale - linear size
_extra - keywords for usersym (see usersym help page)
eg, /fill or thick=thick
KEYWORDS
diagonal - rotate symbol through 1/2 of 1/N turns
REVISION HISTORY:
2002-04-09 written - Hogg
(See pro/plot/hogg_usersym.pro)
NAME:
hogg_weighted_mean_surface
PURPOSE:
make an image of the weighted mean for a 2-d set of measurements
CALLING SEQUENCE:
images = weighted_mean_surface(x,y,weight,quantity,xbin,ybin,dx,dy)
INPUTS:
x,y - [N] values of measurements
quantity - [N] measurements themselves
weight - [N] weights for measurements
xbin,ybin - [nx],[ny] vectors of coordinates of image pixel centers
dx,dy - size of sliding box in which means are taken
OPTIONAL INPUTS:
boot_seed - if set, use as seed for a bootstrap resampling trial
nearest - use nearest few points based on this number, rather
than a fixed smoothing (use with caution!)
OUTPUTS:
images - [nx,ny,4] output images of number of contributing
points (image 0), total weight used (image 1), total
square weight used (image 2), and weighted mean (image 3)
COMMENTS:
BUGS:
REVISION HISTORY:
2003-01-11 written - Hogg
(See pro/plot/hogg_weighted_mean_surface.pro)
NAME:
hst_guidetest
PURPOSE:
Decide if a list of potential HST guide stars are good by looking
at the 2MASS and UCAC catalogs
CALLING SEQUENCE:
hst_guidetest, [ ra, dec, name=, filename=, searchrad=, select_tags=, $
goodrad= ]
INPUTS:
OPTIONAL INPUTS:
ra - RA for each star [degrees]
dec - Declination for each star [degrees]
name - Name for each star; default to STAR-1, STAR-2, etc.
filename - Input ASCII file name with at least 3 columns:
name, RA, Dec (where the coordinates are in degrees);
if set, then this overrides the inputs RA, DEC, NAME
searchrad - Search radius between input coorinates and 2MASS and UCAC;
default to 5./3600 degrees
goodrad - Maximum distance for a "good" HST guide star; default
to 1.5/3600 arcsec
select_tags- Names of tags to print
OUTPUTS:
OPTIONAL OUTPUTS:
COMMENTS:
The default is to return the following:
NAME - The object names either from the first column of FILENAME,
or from the input NAME
DIST - Distance in arcsec to the nearest 2MASS star
BL_FLG - Blend flags in J,H,K-bands, should be "111"
CC_FLG - Contamination flags in J,H,K-bands, should be "000"
GAL_CONTAM - Extended source contamination flag, should be "0"
MP_FLG - Minor planet flag, should be "0"
UCAC_DIST - Distance in arcsec to the nearest UCAC star
GOOD - Set to "BAD" if there is not a 2MASS and UCAC isolated star
within GOODRAD arcsec, or if any of the other, above flags have
suspicious values; note that it will always say "BAD" for
stars at high declination where UCAC does not have coverage
Note that the UCAC astrometric catalog includes stars in the
magnitude range R = [8,16] (approximately) from declination -90
to between Dec +40 and +52. It discards stars within 3 arcsec
of any other star.
Refer to the following 2MASS documentation for a description
of the 2MASS data structure:
http://tdc-www.harvard.edu/software/catalogs/tmc.format.html
Refer to the following web site for the UCAC astrometric catalog:
http://ad.usno.navy.mil/ucac/
EXAMPLES:
BUGS:
PROCEDURES CALLED:
djs_diff_angle()
struct_addtags()
struct_print
struct_selecttags()
tmass_read()
ucac_read()
REVISION HISTORY:
09-Jul-2005 Written by D. Schlegel, LBL
(See pro/2mass/hst_guidetest.pro)
NAME: iau_to_radec PURPOSE: convert an IAU name to RA and DEC CALLING SEQUENCE: iau_to_radec, name, ra, dec INPUTS: name - IAU name OUTPUTS: ra, dec - coords REVISION HISTORY: 2005-10-24 Blanton (NYU)
(See pro/misc/iau_to_radec.pro)
NAME: idlutils_so_ext PURPOSE: returns appropriate dynamic library extension given arch CALLING SEQUENCE: so_ext= idlutils_so_ext() COMMENTS: necessary to deal with non-standard .dylib extension on darwin REVISION HISTORY: 20-Feb-2004 Written by M. Blanton, NYU
(See pro/misc/idlutils_so_ext.pro)
NAME: idlutils_version PURPOSE: Return the version name for the product idlutils CALLING SEQUENCE: vers = idlutils_version() INPUTS: OUTPUTS: vers - Version name for the product idlutils COMMENTS: If this version is not tagged by CVS, then we return 'NOCVS: TOPLEVEL' where TOPLEVEL is the last directory in the environment variable $IDLUTILS_DIR. For example, if you are using a version of the code in the directory '/u/schlegel/idlutils/v0_0', then this returns 'NOCVS:v0_0'. BUGS: PROCEDURES CALLED: ; REVISION HISTORY: 01-Dec-1999 Written by D. Schlegel, Princeton.
(See pro/misc/idlutils_version.pro)
NAME:
IMGEXP
PURPOSE:
This function expands the array <Image> to fill the current plotting
window. This routine works for both X and PostScript devices. The
optional scales <XS> and <YS> are likewise transformed and returned
in option parameters <Out_XS> and <Out_YS>.
CATEGORY:
Image expansion.
CALLING SEQUENCE:
Result = IMGEXP(Image, XS, YS, Out_XS, Out_YS, X_Ran, Y_Ran)
INPUTS:
Image: Two-dimensional array to be expanded.
OPTIONAL INPUTS:
XS: Vector of x-axis values. The length must equal the number of
rows in <Image>
YS: Vector of y-axis values. The length must equal the number of
columns in <Image>
KEYWORD PARAMETERS:
ASPECT= Set this keyword to the aspect ratio (width/height) of the
pixels. /ASPECT is the same as ASPECT=1 and produces square
pixels.
/INTERPOLATE:
Set this switch to enable bilinear interpolation for pixels
in the expanded image. See /PS_INTERP_SIZE for information
on using this switch on a PostScript device.
MASKVALUE=
Set this keyword to the value that uninterpolated pixels around
the border of the image should be given. The default is
-9999.0. Interpolation is not performed beyond the centers of
the original pixels.
PS_INTERP_SIZE=
Since PostScript devices have scalable pixels it is necessary
to force expansion to at most this many pixels in either
dimension. The default is 256. (It's really more complicated
than this. Read the code if you need to know.)
POSITION=
Set this keyword to the variable that is to hold the four-
element vector containing the device coordinates of the
plotting region that will contain the expanded image. This
is designed to be used by subsequent TV and PLOT commands.
/NO_EXPAND:
Set this switch to prevent the image from being expanded
to fill the plotting window. An aspect ration of 1:1 is
forced for PostScript output so that it conforms to the X
window view.
OUTPUTS:
Result: This function returns an expanded version of the input <Image>
possibly interpolated.
OPTIONAL OUTPUTS:
Out_XS: Vector of x-axis values corresponding the the expanded image.
Out_YS: Vector of y-axis values corresponding the the expanded image.
X_Ran: Two-element vector that contains the full x-axis range
including the width of the pixels. It is designed to be used
as input to the PLOT command.
Y_Ran: Two-element vector that contains the full y-axis range
including the height of the pixels. It is designed to be used
as input to the PLOT command.
RESTRICTIONS:
This routine may work for other devices, but it has only been tested
on 'X' and 'PS'.
PROCEDURE:
Straight forward. :-)
EXAMPLE:
p = 0
big = IMGEXP(small, lon, lat, biglon, biglat, xr, yr, Position=p)
TVSCL, big, p(0), p(1), /Device
Plot, [0,1], /NoData, /NoErase, Position=p, /Device, $
XRange=xr, YRange=yr
junk = IMGSCL( ) ;prints out a "Usage:" line
MODIFICATION HISTORY:
Written by: Fen Tamanaha, July 9, 1993. Release 2.1
July 16, 1993 Fen: (2.2) Added /No_Expand keyword
Jan 10, 2000 D. Finkbeiner - added _extra pass-through to Plot
(See pro/plot/imgexp.pro)
NAME: IMGSCL PURPOSE: This function mimics BYTSCL() except that it maps the input range into a byte range from 1 through TOP. A byte value of 0 is reserved for elements containing MASKVALUE usually assigned for bad pixels or those without data. The function can also perform logarithmic scaling of the data into byte values. Use of the LEVELS keyword will scale all value within a given level to a single byte value. CATEGORY: Image scaling. CALLING SEQUENCE: Result = IMGSCL(Array) INPUTS: Array: Two-dimensional array to be expanded. KEYWORD PARAMETERS: MIN= The minimum value of Array to be considered. If MIN is not provided, Array is searched for its minimum value. All values less than or equal to MIN are set to 1 in the Result. MAX= The maximum value of Array to be considered. If MAX is not provided, Array is searched for its maximum value. All values greater than or equal to MAX are set to TOP in the Result. TOP= The maximum value of the scaled result. If TOP is not specified, 255 is used. Note that the minimum value of the scaled result is always 1 (NOT 0 as in BYTSCL). LEVELS= Set this keyword to a vector of data value boundaries between which all elements of the Array have the same scaled byte value. e.g. LEVELS=[0,1,2,5] maps all values below 0 and above 5 to 0B, map values between 0 and 1 to 1B, map values between 1 and 2 to 128B, and map values between 2 and 5 to 255B. /LOG: Set this switch to cause a logarithmic mapping. This is overridden by the LEVELS keyword. MASKVALUE= Set this keyword to the value that pixels with bad data or no data have been flagged with. These will be mapped to 0B. OUTPUTS: Result: This function returns a byte array between 1 and TOP for data in Array between MIN and MAX. RESTRICTIONS: PROCEDURE: Straight forward. :-) EXAMPLE: image = IMGSCL(array, Min=-1, Top=!D.Table_Size-1, /Log, Mask=-9999.0) TV, image image = IMGSCL(array, Levels=[0,1,2,4,8,16,32]) TV, image ;plot with 6 colors plus the background MODIFICATION HISTORY: Written by: Fen Tamanaha, July 10, 1993. Release 2.1
(See pro/plot/imgscl.pro)
NAME:
interp_profmean
PURPOSE:
Interpolates a radial profile of the sort output by photo
CALLING SEQUENCE:
interp_profmean,nprof,profmean,radius,maggies, [maggieserr=, profradius= $
proferr=, radiusscale=, maggiesscale=]
INPUTS:
nprof - number of measured elements in the profile
profmean - values (in maggies) in the profile [15]
radius - a set of values to interpolate to [N]
maggies - calculated maggies
OPTIONAL INPUTS:
proferr - errors in profile
profradius - boundaries of annuli in profile (set to photo default
in arcsec)
radiusscale - asinh scale for radii
maggiesscale - asinh scale for maggieses
OUTPUTS:
maggieserr - calculated error
OPTIONAL INPUT/OUTPUTS:
COMMENTS:
Set up for using the profMean in the fpObjc files of the SDSS,
input and output in maggies (or any linear measure of surface
brightness)
EXAMPLES:
BUGS:
Slow.
PROCEDURES CALLED:
REVISION HISTORY:
16-Jan-2002 Written by Mike Blanton, NYU
(See pro/image/interp_profmean.pro)
NAME:
intrv
PURPOSE:
Find the segment between breakpoints which contain each value in
the array x. The minimum breakpoint is nbkptord -1, and the maximum
is nbkpt - nbkptord - 1. This routine is required by the bspline
IDL routines, and is similar in function to the slatec version.
CALLING SEQUENCE:
indx = intrv(x, fullbkpt, nbkptord)
INPUTS:
x - data x values
fullbkpt - Breakpoint vector returned by efc
nbkptord - Order of b-splines (4 is cubic)
RETURNS:
indx - position of array elements with respect to breakpoints.
OUTPUTS:
OPTIONAL KEYWORDS:
OPTIONAL OUTPUTS:
COMMENTS:
does the same function as intrv, although slower but easier to follow
sorting is done here
Again, assumes x is monotonically increasing
EXAMPLES:
REVISION HISTORY:
31-Aug-2000 Written by Scott Burles, FNAL
(See pro/bspline/intrv.pro)
NAME:
ishealpix
PURPOSE:
Determine if array represents a healpix image
CALLING SEQUENCE:
type = ishealpix(image)
INPUTS:
image - input array to be tested
npix - number of pixels - set if image not set
KEYWORDS:
silent - suppress messages.
true - test for true color (not implemented)
OUTPUTS:
type - image type; 1=healpix, 0=not healpix
COMMENTS:
Define healpix as an array of 12*2^(2*N) pixels for pos. integer N.
A looser definition is possible for ring ordering, but not for
nested ordering.
Must set either image or npix
REVISION HISTORY:
2003-Dec-05 Written by Douglas Finkbeiner, Princeton
(See pro/healpix/ishealpix.pro)
NAME: is_cap_used PURPOSE: Returns whether a cap is used in use_caps CALLING SEQUENCE: is_cap_used,use_caps,indx INPUTS: use_caps - bit mask indicating which cap is used indx - number indicating which cap we are interestedin OPTIONAL INPUTS: OUTPUTS: OPTIONAL INPUT/OUTPUTS: COMMENTS: EXAMPLES: BUGS: Number of caps limited to 32 PROCEDURES CALLED: REVISION HISTORY: 09-Nov-2002 Written by MRB (NYU)
(See pro/mangle/is_cap_used.pro)
NAME: is_file_readable CALLING SEQUENCE: good= is_file_readable(filename,/compress) OUTPUT: good - 1 if good, 0 if bad BUGS: - NOT extensively tested. REVISION HISTORY: 2005-06-03 converted from Schlegel email to code - Hogg
(See pro/misc/is_file_readable.pro)
NAME: is_in_cap PURPOSE: Is an xyz (or radec) position in a given cap? CALLING SEQUENCE: result=is_in_cap(ra=, dec=, xyz=, cap ) INPUTS: ra - set of ra values dec - set of dec values xyz - xyz value(s) (overrides ra and dec) cap - single cap to check OPTIONAL INPUTS: OUTPUTS: OPTIONAL INPUT/OUTPUTS: COMMENTS: Either ra and dec, or xyz must be set; xyz overrides ra and dec EXAMPLES: BUGS: PROCEDURES CALLED: REVISION HISTORY: 01-Oct-2002 Written by MRB (NYU)
(See pro/mangle/is_in_cap.pro)
NAME: is_in_polygon PURPOSE: Is an xyz (or radec) position in a given polygon? CALLING SEQUENCE: result=is_in_polygon(xyz=, ra=, dec= , polygon) INPUTS: ra - set of ra values dec - set of dec values xyz - xyz value(s) (overrides ra and dec) polygon - polygon with caps to check OPTIONAL INPUTS: ncaps - override polygon.ncaps (if ncaps < polygon.ncaps) OUTPUTS: OPTIONAL INPUT/OUTPUTS: COMMENTS: Either ra and dec, or xyz must be set; xyz overrides ra and dec EXAMPLES: BUGS: PROCEDURES CALLED: REVISION HISTORY: 01-Oct-2002 Written by MRB (NYU)
(See pro/mangle/is_in_polygon.pro)
NAME: is_in_window PURPOSE: Is an xyz (or radec) position in any of a given list of polygons? CALLING SEQUENCE: result=is_in_window(xyz=, ra=, dec= , polygons) INPUTS: polygons - polygons with caps to check OPTIONAL INPUTS: ra - [N] set of ra values dec - [N] set of dec values xyz - [3,N] xyz value(s) (overrides ra and dec) ncaps - override polygon.ncaps (if ncaps < polygon.ncaps) OUTPUTS: result - [N] 1 if in window, 0 otherwise OPTIONAL OUTPUTS: in_polygon - [N] which polygon each ra,dec is in (-1 if none) COMMENTS: Either ra and dec, or xyz must be set; xyz overrides ra and dec REVISION HISTORY: 01-Oct-2002 Written by MRB (NYU)
(See pro/mangle/is_in_window.pro)
NAME: labelloc PURPOSE: convert fractional positions in X and Y to those appropriate for xyouts CALLING SEQUENCE: labelloc, xfrac, yfrac, xloc, yloc INPUTS: xfrac,yfrac - fractional distances from axes in x and y OUTPUTS: xloc, yloc - units appropriate for xyouts REVISION HISTORY: 2003-11-21 started - Blanton
(See pro/misc/labelloc.pro)
NAME:
legendre_zero
PURPOSE:
Compute zeros of the m=0 Legendre polynomials
CALLING SEQUENCE:
thzero = legendre_zero(l)
INPUTS:
l - order of Legendre polynomial Pl0(x) to compute
KEYWORDS:
OUTPUTS:
thzero - theta values of zeros [radians]
EXAMPLES:
COMMENTS:
Just calls fx_root. We need the common block and the function
legfn.
REVISION HISTORY:
2003-Feb-21 Written by Douglas Finkbeiner, Princeton
(See pro/math/legendre_zero.pro)
NAME: lg_to_helio PURPOSE: Convert to heliocentric redshifts from Local-Group-centric redshifts. CALLING SEQUENCE: z_helio = lg_to_helio(z_lg,ra,dec) INPUTS: z_lg - local-group-centric redshift RA - right ascension (deg, J2000) Dec - declination (deg, J2000) OUTPUTS: z_helio - heliocentric redshift REVISION HISTORY: Originally imported by Hogg, 2002-08 or so. MRB corrected sign error in correction 2004-04-08 (affected tags v5_0_0 and previous)
(See pro/coord/lg_to_helio.pro)
NAME:
ll2uv
PURPOSE:
To convert from longitude/latitude to unit vectors
CALLING SEQUENCE:
uv = ll2uv(lon_lat)
INPUT:
(n,2) longitude/latitude array
OUTPUT:
(n,3) unit vector array
SUBROUTINES CALLED:
None
REVISION HISTORY
SPR 9923 26-AUG-1992 Change unit vector output array to float type
J.M. Gales
29-March-2001 Added double keyword - Doug Finkbeiner, Princeton
(See pro/astrom/ll2uv.pro)
NAME:
lle
PURPOSE: (one line)
Perform local linear embedding
DESCRIPTION:
Uses Sam Roweis's local linear embedding technique to reduce the
dimensionality of a data set.
CATEGORY:
Mathematical
CALLING SEQUENCE:
lle, data, ncoords, coords, weights=weights
INPUTS:
data - [p,N] data to be reduced
ncoords - number of output dimensions desired
OUTPUTS:
coords - [ncoords,N] embedding coordinates
OPTIONAL OUTPUTS PARAMETERS:
weights - reconstruction weights
OPTIONAL INPUT PARAMETERS:
KEYWORD PARAMETERS:
COMMON BLOCKS:
SIDE EFFECTS:
BUGS:
Not completed yet, do not use
RESTRICTIONS:
PROCEDURE:
MODIFICATION HISTORY:
2003-05-14 - Written by Michael Blanton (NYU)
(See pro/math/lle.pro)
NAME:
lle_sm
PURPOSE: (one line)
create sparse matrix from full matrix for LLE routines
DESCRIPTION:
rather crappy sparse matrix format for NxM matrix:
.N - number of rows
.M - number of columns
.VALS - each nonzero value
.NINDX - row of each nonzero value
.MINDX - column of each nonzero value
but it handles nonsquare matrices
CATEGORY:
Numerical
CALLING SEQUENCE:
sparse_matrix= lle_sm(full_matrix)
INPUTS:
full_matrix - complete NxM matrix
OPTIONAL INPUT PARAMETERS:
KEYWORD PARAMETERS:
OUTPUTS:
sparse_matrix - full_matrix transformed into above format
COMMON BLOCKS:
SIDE EFFECTS:
RESTRICTIONS:
always at double precision
PROCEDURE:
MODIFICATION HISTORY:
Blanton 2003-05-26
(See pro/math/lle_sm.pro)
NAME:
lle_sm_full
PURPOSE: (one line)
create full matrix from full matrix for LLE routines
DESCRIPTION:
rather crappy sparse matrix format for NxM matrix:
.N - number of rows
.M - number of columns
.VALS - each nonzero value
.NINDX - row of each nonzero value
.MINDX - column of each nonzero value
but it handles nonsquare matrices
CATEGORY:
Numerical
CALLING SEQUENCE:
full_matrix= lle_sm_full(sparse_matrix)
INPUTS:
sparse_matrix - matrix in above format
OPTIONAL INPUT PARAMETERS:
KEYWORD PARAMETERS:
OUTPUTS:
full_matrix - complete NxM matrix
COMMON BLOCKS:
SIDE EFFECTS:
RESTRICTIONS:
always at double precision
PROCEDURE:
MODIFICATION HISTORY:
Blanton 2003-05-26
(See pro/math/lle_sm_full.pro)
NAME:
lle_sm_mult
PURPOSE: (one line)
multiply two sparse matrices kind of efficiently for LLE routines
DESCRIPTION:
rather crappy sparse matrix format for NxM matrix:
.N - number of rows
.M - number of columns
.VALS - each nonzero value
.NINDX - row of each nonzero value
.MINDX - column of each nonzero value
but it handles nonsquare matrices
CATEGORY:
Numerical
CALLING SEQUENCE:
cc= lle_sm_mult(aa,bb)
INPUTS:
aa - [N,M] sparse matrix input
bb - [M,P] sparse matrix input
OPTIONAL INPUT PARAMETERS:
KEYWORD PARAMETERS:
OUTPUTS:
cc - [N,P] sparse matrix output (should be equal to idl's aa#bb)
COMMON BLOCKS:
SIDE EFFECTS:
RESTRICTIONS:
always at double precision
PROCEDURE:
MODIFICATION HISTORY:
Blanton 2003-05-26
(See pro/math/lle_sm_mult.pro)
NAME:
lle_sm_transpose
PURPOSE: (one line)
transpose a sparse matrix for the LLE routines
DESCRIPTION:
transposes the rather crappy sparse matrix format for NxM matrix:
.N - number of rows
.M - number of columns
.VALS - each nonzero value
.NINDX - row of each nonzero value
.MINDX - column of each nonzero value
but it handles nonsquare matrices
CATEGORY:
Numerical
CALLING SEQUENCE:
mattrans= lle_sm_transpose(mat)
INPUTS:
mat - matrix in above format
OPTIONAL INPUT PARAMETERS:
KEYWORD PARAMETERS:
OUTPUTS:
mattrans - transposed matrix in above format
COMMON BLOCKS:
SIDE EFFECTS:
RESTRICTIONS:
PROCEDURE:
MODIFICATION HISTORY:
Blanton 2003-05-26
(See pro/math/lle_sm_transpose.pro)
NAME:
local_extragalactic
PURPOSE:
returns list of local extragalactic locations and names to plot
CALLING SEQUENCE:
local_extragalactic, ra, dec, cz_lg, names, list=list
OPTIONAL INPUTS:
list - list of names to match to (default:
['VIRGO_CLUSTER', 'URSA_MAJOR_CLUSTER', $
'PISCES_CLUSTER', 'COMA_CLUSTER' ] )
OUTPUTS:
ra - [N] ra (J2000 deg)
dec - [N] dec (J2000 deg)
cz_lg - [N] local group frame cz
names - [N] object name
(See pro/coord/local_extragalactic.pro)
NAME:
logsum
PURPOSE: (one line)
sum quantities when you have them as logs (preserving dynamic range)
CATEGORY:
Numerical
CALLING SEQUENCE:
res= logsum(logs [,/double])
KEYWORD PARAMETERS:
/double - assume double precision input (otherwise assumes float)
RESTRICTIONS:
seems to not have expected precision
MODIFICATION HISTORY:
Blanton and Roweis 2003-02-18
(See pro/math/logsum.pro)
NAME: lookback PURPOSE: Compute lookback time (for c/H_0=1). CALLING SEQUENCE: t= lookback(z,OmegaM,OmegaL) INPUTS: z - redshift or vector of redshifts OmegaM - Omega-matter at z=0 OmegaL - Omega-Lambda at z=0 OPTIONAL INPUTS: KEYWORDS OUTPUTS: lookback time in units of the Hubble time 1/H_0 COMMENTS: BUGS: The integrator is crude, slow and repetetive. May not work for pathological parts of the OmegaM-OmegaL plane. EXAMPLES: PROCEDURES CALLED: dlookbackdz() REVISION HISTORY: 2001-May-12 Written by Hogg (NYU)
(See pro/cosmography/lookback.pro)
NAME:
lookforgzip
PURPOSE:
Look for a gzip-ed file,
CALLING SEQUENCE:
thisfile = lookforgzip( filename, count= )
INPUTS:
filename - Input file name w/out any ".gz" or ".Z" extension
OPTIONAL KEYWORDS:
OUTPUTS:
thisfile - Returns input file name with no extension if it exists,
otherwise a ".gz" extension if that exists,
otherwise a ".Z" extension if that exists,
otherwise '' if none of the above exist.
OPTIONAL OUTPUTS:
count - Number of files that matched
COMMENTS:
This routine uses FINDFILE().
EXAMPLES:
BUGS:
PROCEDURES CALLED:
REVISION HISTORY:
20-Oct-2000 Written by S. Burles, FNAL
(See pro/misc/lookforgzip.pro)
NAME: lumdis PURPOSE: Compute luminosity distances (for c/H_0=1). CALLING SEQUENCE: D= lumdis(z,OmegaM,OmegaL, weq=weq) INPUTS: z - redshift or vector of redshifts OmegaM - Omega-matter at z=0 OmegaL - Omega-Lambda at z=0 OPTIONAL INPUTS: weq - Equation of state (default=-1) KEYWORDS OUTPUTS: luminosity distance in units of the Hubble length c/H_0 COMMENTS: BUGS: May not work for pathological parts of the OmegaM-OmegaL plane. EXAMPLES: PROCEDURES CALLED: propmotdis() REVISION HISTORY: 25-Jun-2000 Written by Hogg (IAS) 2004-Sep-8, Added equation of state for OmegaL, Padmanabhan (Princeton)
(See pro/cosmography/lumdis.pro)
NAME: make_dec_cap PURPOSE: Creates a structure containing a cap expressing a limit in dec CALLING SEQUENCE: cap=make_dec_cap(declimit, [,sign= ] INPUTS: declimit - limit on dec OPTIONAL INPUTS: sign - sign of the cap (default 1.) OUTPUTS: OPTIONAL INPUT/OUTPUTS: COMMENTS: EXAMPLES: BUGS: PROCEDURES CALLED: REVISION HISTORY: 01-Oct-2002 Written by MRB (NYU)
(See pro/mangle/make_dec_cap.pro)
NAME:
MAKE_HTML_HELP
PURPOSE:
Given a list of IDL procedure files (.PRO), VMS text library
files (.TLB), or directories that contain such files, this procedure
generates a file in the HTML format that contains the documentation
for those routines that contain a DOC_LIBRARY style documentation
template. The output file is compatible with World Wide Web browsers.
CATEGORY:
Help, documentation.
CALLING SEQUENCE:
MAKE_HTML_HELP, Sources, Outfile
INPUTS:
Sources: A string or string array containing the name(s) of the
.pro or .tlb files (or the names of directories containing
such files) for which help is desired. If a source file is
a VMS text library, it must include the .TLB file extension.
If a source file is an IDL procedure, it must include the .PRO
file extension. All other source files are assumed to be
directories.
Outfile: The name of the output file which will be generated.
KEYWORDS:
TITLE: If present, a string which supplies the name that
should appear as the Document Title for the help.
VERBOSE: Normally, MAKE_HTML_HELP does its work silently.
Setting this keyword to a non-zero value causes the procedure
to issue informational messages that indicate what it
is currently doing. !QUIET must be 0 for these messages
to appear.
STRICT: If this keyword is set to a non-zero value, MAKE_HTML_HELP will
adhere strictly to the HTML format by scanning the
the document headers for characters that are reserved in
HTML (<,>,&,"). These are then converted to the appropriate
HTML syntax in the output file. By default, this keyword
is set to zero (to allow for faster processing).
LINKFILES: If this keyword is set to a non-zero value,
MAKE_HTML_HELP will generate "file" links to the idl
procedures documented on the web page created by this
code.
COMMON BLOCKS:
None.
SIDE EFFECTS:
A help file with the name given by the Outfile argument is
created.
RESTRICTIONS:
The following rules must be followed in formatting the .pro
files that are to be searched.
(a) The first line of the documentation block contains
only the characters ";+", starting in column 1.
(b) There must be a line which contains the string "NAME:",
which is immediately followed by a line containing the
name of the procedure or function being described in
that documentation block. If this NAME field is not
present, the name of the source file will be used.
(c) The last line of the documentation block contains
only the characters ";-", starting in column 1.
(d) Every other line in the documentation block contains
a ";" in column 1.
Note that a single .pro file can contain multiple procedures and/or
functions, each with their own documentation blocks. If it is desired
to have "invisible" routines in a file, i.e. routines which are only
for internal use and should not appear in the help file, simply leave
out the ";+" and ";-" lines in the documentation block for those
routines.
No reformatting of the documentation is done.
MODIFICATION HISTORY:
July 5, 1995, DD, RSI. Original version.
July 13, 1995, Mark Rivers, University of Chicago. Added support for
multiple source directories and multiple documentation
headers per .pro file.
July 17, 1995, DD, RSI. Added code to alphabetize the subjects;
At the end of each description block in the HTML file,
added a reference to the source .pro file.
July 18, 1995, DD, RSI. Added STRICT keyword to handle angle brackets.
July 19, 1995, DD, RSI. Updated STRICT to handle & and ".
Changed calling sequence to accept .pro filenames, .tlb
text librarie names, and/or directory names.
Added code to set default subject to name of file if NAME
field is not present in the doc header.
February 10, 1998, MWC, UC Berkeley. Added purpose to the line
which is output for each routine in the tableof
contents. This used to just contain the name.
April 1, 1998, MWC, UC Berkeley. Added option to create file
link to the location of the procedure being documented.
(See pro/misc/make_html_help.pro)
NAME: make_ra_cap PURPOSE: Creates a structure containing a cap expressing a limit in ra CALLING SEQUENCE: cap=make_ra_cap(ralimit, [,sign= ]) INPUTS: ralimit - limit on ra OPTIONAL INPUTS: sign - sign of the cap (default 1.) REVISION HISTORY: 01-Oct-2002 Written by MRB (NYU)
(See pro/mangle/make_ra_cap.pro)
NAME: map_nest2ring PURPOSE: Convert a full-sky map in nested order to ring order CALLING SEQUENCE: ringmap=map_nest2ring(nestmap) INPUTS: nestmap - healpix map in nested order OUTPUTS: ringmap - healpix map in ring order COMMENTS: REVISION HISTORY: 2003-Dec-04 Written by Douglas Finkbeiner, Princeton
(See pro/healpix/map_nest2ring.pro)
NAME: map_ring2nest PURPOSE: Convert a full-sky map in ring order to nested order CALLING SEQUENCE: nestmap=map_ring2nest(ringmap) INPUTS: ringmap - healpix map in ring order OUTPUTS: nestmap - healpix map in nested order COMMENTS: REVISION HISTORY: 2003-Dec-04 Written by Douglas Finkbeiner, Princeton
(See pro/healpix/map_ring2nest.pro)
NAME: matchnd PURPOSE: match two sets of points on a grid CALLING SEQUENCE: matchnd, x1, x2, distance [, m1=, m2=, d12=, nmatch= ] INPUTS: x1 - [M,N1] positions in M-dimensions x2 - [M,N2] positions in M-dimensions distance - match distance OUTPUTS: m1 - [nmatch] matches to x1 m2 - [nmatch] matches to x2 d12 - [nmatch] distance between matches nmatch - number of matches COMMENTS: This code is BETA! Use at your own risk. REVISION HISTORY: 12-Oct-2005 Written by Mike Blanton, NYU
(See pro/math/matchnd.pro)
NAME:
memshift
PURPOSE:
Shift elements in an array, which can be a structure array.
CALLING SEQUENCE:
memshift, array, isrc, idest, nmove
INPUTS:
array - Array of any type except string or pointer; structures
are allowed
isrc - Starting position in memory to copy from
idest - Starting position in memory to copy to
nmove - Number of array elements to copy
OPTIONAL INPUTS:
OUTPUT:
array - (Modified.)
OPTIONAL OUTPUTS:
COMMENTS:
This routine is equivalent to the IDL command:
array[idest:idest+nmove-1] = array[isrc:isrc+nmove-1]
but is faster, at least on the Linux platform. Note that the
memory in the source and destination can be overlapping.
The C code calls the Unix memmove() function.
If an attempt is made to copy out-of-bounds, then this procedure
intentionally crashes using the MESSAGE function.
EXAMPLES:
BUGS:
PROCEDURES CALLED:
Dynamic link to memshift.o
REVISION HISTORY:
18-Oct-2003 Written by David Schlegel, Princeton.
(See pro/math/memshift.pro)
NAME:
mjd2datelist
PURPOSE:
Construct a list of MJDs and date strings spanning a range of MJDs
(useful for plot limits).
CALLING SEQUENCE:
mjd2datelist, mjstart, [ mjend, step=, mjdlist=, datelist= ]
INPUTS:
mjstart - Starting modified Julian date to span.
OPTIONAL INPUTS:
mjend - Ending modified Julian date to span; if not set, then
only the date string for MJSTART is returned.
step - Step in either 'year', '6month', 'month', or 'day';
default to 'year', or 'day' if MJEND not set.
OUTPUTS:
OPTIONAL OUTPUTS:
mjlist - List of modified Julian dates (MJDs)
datelist - List of dates in the form DD-MMM-YYYY, where MMM is
the first three letters of the month name.
COMMENTS:
This routine returns a list of MJDs and date strings spaced by
the amount specified by STEP that span the range [MJSTART,MJEND].
If using STEP='year', the output list will be on the first date
of each year and [MJSTART,MJEND] will fall internal to that list.
If using STEP='month', the output list will be on each 01-Jan
and 01-Jul. If using STEP='month', the output list will be on
the first of each month.
EXAMPLES:
Construct a list of all the Jan 1st dates that span the dates
of the SDSS spectroscopic survey:
IDL> mjd2datelist, 51433, 52356, mjdlist=mjdlist, datelist=datelist
IDL> print, mjdlist
51179.500 51544.500 51910.500 52275.500 52640.500
IDL> print, datelist
01-Jan-1999 01-Jan-2000 01-Jan-2001 01-Jan-2002 01-Jan-2003
BUGS:
PROCEDURES CALLED:
INTERNAL SUPPORT ROUTINES:
REVISION HISTORY:
26-Mar-2002 Written by D. Schlegel, Princeton
(See pro/coord/mjd2datelist.pro)
NAME:
mmeval
PURPOSE:
evaluate a matrix multiply sparsely
CALLING SEQUENCE:
mmeval, cc, bb, aa
INPUTS:
cc - sparse matrix struct (see below) [nz,ny]
bb - [nx, nz] matrix
aa - [nx, ny] matrix
OUTPUTS:
cc - sparse matrix struct (see below) [nz,ny]
COMMENTS:
The matrix multiply of bb.aa is evaluated specified by the sparse
matrix structure of cc.
The sparse matrix structure referred to above is:
.VAL[NVAL] - actual values in matrix
.X[NVAL] - columns for each value in matrix
.NX - number of columns
.NY - number of rows
.ROWSTART[NY] - starting position of each row in VAL, X
.NXROW[NY] - number of columns in each now
This code is called by nmf_sparse.
REVISION HISTORY:
2005-Feb-5 Written by Mike Blanton, NYU
Adapted from Matlab code of Sam Roweis
(See pro/math/mmeval.pro)
NAME:
mmsparse
PURPOSE:
multiply a regular matrix by a sparse matrix
CALLING SEQUENCE:
mmsparse, cc, bb, aasparse
INPUTS:
bb - sparse matrix struct (see below) [nx, nz] of inverse var
aasparse - sparse matrix struct (see below) [nx, ny]
OUTPUTS:
cc - [nz, ny] result
COMMENTS:
The sparse matrix structure referred to above is:
.VAL[NVAL] - actual values in matrix
.X[NVAL] - columns for each value in matrix
.NX - number of columns
.NY - number of rows
.ROWSTART[NY] - starting position of each row in VAL, X
.NXROW[NY] - number of columns in each now
This code is called by nmf_sparse.
REVISION HISTORY:
2005-Feb-5 Written by Mike Blanton, NYU
Adapted from Matlab code of Sam Roweis
(See pro/math/mmsparse.pro)
NAME:
modfitscard
PURPOSE:
Modify FITS card(s) in a file without changing the data.
CALLING SEQUENCE:
modfitscard, filename, card, value, [ comment, /delete, $
_EXTRA=KeywordsForSxaddpar ]
INPUTS:
filename - File name(s) to modify; this can be an array of file names,
and it can include wildcards
card - Name of FITS card(s) to add or modify
OPTIONAL INPUTS:
value - New value(s) for FITS card; mandatory card if DELETE not set;
must have the same number of elements as CARD.
comment - Comment to appear in the card after its value; passed to
the routine SXADDPAR. If specified, it must have the same
number of elements as CARD.
delete - If set, then delete all cards CARD from the header;
VALUE is ignored if set.
OUTPUTS:
OPTIONAL OUTPUTS:
COMMENTS:
EXAMPLES:
Modify the value of the DATE keyword in the primary header of all FITS
files with '666' or '777' in the file name:
IDL> modfitscard, ['*666*.fits','*777*.fits'], 'DATE', '1994-03-23'
BUGS:
This routine calls DJS_MODFITS, which allows the size of the header
to be changed.
Wildcards are not supported for CARD, so you cannot say something like
IDL> modfitscard, 'test.fits', 'DATE*', '1994-03-23' ; Will not work!
PROCEDURES CALLED:
djs_modfits
headfits()
sxaddpar
REVISION HISTORY:
19-Apr-2000 Written by David Schlegel, Princeton.
(See pro/fits/modfitscard.pro)
NAME: moon_zenith PURPOSE: Compute zenith angle of moon, given TAI CALLING SEQUENCE: zenithang = moon_zenith(TAI, [longitude=, latitude=]) INPUTS: TAI - time in seconds since MJD 0 OPTIONAL KEYWORDS: longitude - longitude of observatory [deg] - default to APO latitude - latitude of observatory [deg] OUTPUTS: zenithang - zenith angle of the moon [deg] COMMENTS: TAI must be specified. BUGS: Uses geocentric coords, should correct for position on Earth PROCEDURES CALLED: moonpos REVISION HISTORY: 2001-Apr-06 Written by D. Finkbeiner, APO
(See pro/coord/moon_zenith.pro)
NAME:
MPCHILIM
AUTHOR:
Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
craigm@lheamail.gsfc.nasa.gov
UPDATED VERSIONs can be found on my WEB PAGE:
http://cow.physics.wisc.edu/~craigm/idl/idl.html
PURPOSE:
Compute confidence limits for chi-square statistic
MAJOR TOPICS:
Curve and Surface Fitting, Statistics
CALLING SEQUENCE:
DELCHI = MPCHILIM(PROB, DOF, [/SIGMA, /CLEVEL, /SLEVEL ])
DESCRIPTION:
The function MPCHILIM() computes confidence limits of the
chi-square statistic for a desired probability level. The returned
values, DELCHI, are the limiting chi-squared values: a chi-squared
value of greater than DELCHI will occur by chance with probability
PROB:
P_CHI(CHI > DELCHI; DOF) = PROB
In specifying the probability level the user has three choices:
* give the confidence level (default);
* give the significance level (i.e., 1 - confidence level) and
pass the /SLEVEL keyword; OR
* give the "sigma" of the probability (i.e., compute the
probability based on the normal distribution) and pass the
/SIGMA keyword.
Note that /SLEVEL, /CLEVEL and /SIGMA are mutually exclusive.
INPUTS:
PROB - scalar or vector number, giving the desired probability
level as described above.
DOF - scalar or vector number, giving the number of degrees of
freedom in the chi-square distribution.
RETURNS:
Returns a scalar or vector of chi-square confidence limits.
KEYWORD PARAMETERS:
SLEVEL - if set, then PROB describes the significance level.
CLEVEL - if set, then PROB describes the confidence level
(default).
SIGMA - if set, then PROB is the number of "sigma" away from the
mean in the normal distribution.
EXAMPLES:
print, mpchilim(0.99d, 2d, /clevel)
Print the 99% confidence limit for a chi-squared of 2 degrees of
freedom.
print, mpchilim(5d, 2d, /sigma)
Print the "5 sigma" confidence limit for a chi-squared of 2
degrees of freedom. Here "5 sigma" indicates the gaussian
probability of a 5 sigma event or greater.
P_GAUSS(5D) = 1D - 5.7330314e-07
REFERENCES:
Algorithms taken from CEPHES special function library, by Stephen
Moshier. (http://www.netlib.org/cephes/)
MODIFICATION HISTORY:
Completed, 1999, CM
Documented, 16 Nov 2001, CM
Reduced obtrusiveness of common block and math error handling, 18
Nov 2001, CM
$Id: mpchilim.pro,v 1.1 2006/02/07 22:38:32 schlegel Exp $
(See pro/mpfit/mpchilim.pro)
NAME:
MPCHITEST
AUTHOR:
Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
craigm@lheamail.gsfc.nasa.gov
UPDATED VERSIONs can be found on my WEB PAGE:
http://cow.physics.wisc.edu/~craigm/idl/idl.html
PURPOSE:
Compute the probability of a given chi-squared value
MAJOR TOPICS:
Curve and Surface Fitting, Statistics
CALLING SEQUENCE:
PROB = MPCHITEST(CHI, DOF, [/SIGMA, /CLEVEL, /SLEVEL ])
DESCRIPTION:
The function MPCHITEST() computes the probability for a value drawn
from the chi-square distribution to equal or exceed the given value
CHI. This can be used for confidence testing of a measured value
obeying the chi-squared distribution.
P_CHI(X > CHI; DOF) = PROB
In specifying the returned probability level the user has three
choices:
* return the confidence level when the /CLEVEL keyword is passed;
OR
* return the significance level (i.e., 1 - confidence level) when
the /SLEVEL keyword is passed (default); OR
* return the "sigma" of the probability (i.e., compute the
probability based on the normal distribution) when the /SIGMA
keyword is passed.
Note that /SLEVEL, /CLEVEL and /SIGMA are mutually exclusive.
INPUTS:
CHI - chi-squared value to be tested.
DOF - scalar or vector number, giving the number of degrees of
freedom in the chi-square distribution.
RETURNS:
Returns a scalar or vector of probabilities, as described above,
and according to the /SLEVEL, /CLEVEL and /SIGMA keywords.
KEYWORD PARAMETERS:
SLEVEL - if set, then PROB describes the significance level
(default).
CLEVEL - if set, then PROB describes the confidence level.
SIGMA - if set, then PROB is the number of "sigma" away from the
mean in the normal distribution.
EXAMPLES:
print, mpchitest(1300d,1252d)
Print the probability for a chi-squared value with 1252 degrees of
freedom to exceed a value of 1300, as a confidence level.
REFERENCES:
Algorithms taken from CEPHES special function library, by Stephen
Moshier. (http://www.netlib.org/cephes/)
MODIFICATION HISTORY:
Completed, 1999, CM
Documented, 16 Nov 2001, CM
Reduced obtrusiveness of common block and math error handling, 18
Nov 2001, CM
$Id: mpchitest.pro,v 1.1 2006/02/07 22:38:32 schlegel Exp $
(See pro/mpfit/mpchitest.pro)
NAME:
MPCURVEFIT
AUTHOR:
Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
craigm@lheamail.gsfc.nasa.gov
UPDATED VERSIONs can be found on my WEB PAGE:
http://cow.physics.wisc.edu/~craigm/idl/idl.html
PURPOSE:
Perform Levenberg-Marquardt least-squares fit (replaces CURVEFIT)
MAJOR TOPICS:
Curve and Surface Fitting
CALLING SEQUENCE:
YFIT = MPCURVEFIT(X, Y, WEIGHTS, P, [SIGMA,] FUNCTION_NAME=FUNC,
ITER=iter, ITMAX=itmax,
CHISQ=chisq, NFREE=nfree, DOF=dof,
NFEV=nfev, COVAR=covar, [/NOCOVAR, ] [/NODERIVATIVE, ]
FUNCTARGS=functargs, PARINFO=parinfo,
FTOL=ftol, XTOL=xtol, GTOL=gtol, TOL=tol,
ITERPROC=iterproc, ITERARGS=iterargs,
NPRINT=nprint, QUIET=quiet,
ERRMSG=errmsg, STATUS=status)
DESCRIPTION:
MPCURVEFIT fits a user-supplied model -- in the form of an IDL
function -- to a set of user-supplied data. MPCURVEFIT calls
MPFIT, the MINPACK-1 least-squares minimizer, to do the main
work.
Given the data and their uncertainties, MPCURVEFIT finds the best
set of model parameters which match the data (in a least-squares
sense) and returns them in the parameter P.
MPCURVEFIT returns the best fit function.
The user must supply the following items:
- An array of independent variable values ("X").
- An array of "measured" *dependent* variable values ("Y").
- An array of weighting values ("WEIGHTS").
- The name of an IDL function which computes Y given X ("FUNC").
- Starting guesses for all of the parameters ("P").
There are very few restrictions placed on X, Y or FUNCT. Simply
put, FUNCT must map the "X" values into "Y" values given the
model parameters. The "X" values may represent any independent
variable (not just Cartesian X), and indeed may be multidimensional
themselves. For example, in the application of image fitting, X
may be a 2xN array of image positions.
MPCURVEFIT carefully avoids passing large arrays where possible to
improve performance.
See below for an example of usage.
USER FUNCTION
The user must define a function which returns the model value. For
applications which use finite-difference derivatives -- the default
-- the user function should be declared in the following way:
PRO MYFUNCT, X, P, YMOD
; The independent variable is X
; Parameter values are passed in "P"
YMOD = ... computed model values at X ...
END
The returned array YMOD must have the same dimensions and type as
the "measured" Y values.
User functions may also indicate a fatal error condition
using the ERROR_CODE common block variable, as described
below under the MPFIT_ERROR common block definition.
See the discussion under "ANALYTIC DERIVATIVES" and AUTODERIVATIVE
in MPFIT.PRO if you wish to compute the derivatives for yourself.
AUTODERIVATIVE is accepted and passed directly to MPFIT. The user
function must accept one additional parameter, DP, which contains
the derivative of the user function with respect to each parameter
at each data point, as described in MPFIT.PRO.
CONSTRAINING PARAMETER VALUES WITH THE PARINFO KEYWORD
The behavior of MPFIT can be modified with respect to each
parameter to be fitted. A parameter value can be fixed; simple
boundary constraints can be imposed; limitations on the parameter
changes can be imposed; properties of the automatic derivative can
be modified; and parameters can be tied to one another.
These properties are governed by the PARINFO structure, which is
passed as a keyword parameter to MPFIT.
PARINFO should be an array of structures, one for each parameter.
Each parameter is associated with one element of the array, in
numerical order. The structure can have the following entries
(none are required):
.VALUE - the starting parameter value (but see the START_PARAMS
parameter for more information).
.FIXED - a boolean value, whether the parameter is to be held
fixed or not. Fixed parameters are not varied by
MPFIT, but are passed on to MYFUNCT for evaluation.
.LIMITED - a two-element boolean array. If the first/second
element is set, then the parameter is bounded on the
lower/upper side. A parameter can be bounded on both
sides. Both LIMITED and LIMITS must be given
together.
.LIMITS - a two-element float or double array. Gives the
parameter limits on the lower and upper sides,
respectively. Zero, one or two of these values can be
set, depending on the values of LIMITED. Both LIMITED
and LIMITS must be given together.
.PARNAME - a string, giving the name of the parameter. The
fitting code of MPFIT does not use this tag in any
way. However, the default ITERPROC will print the
parameter name if available.
.STEP - the step size to be used in calculating the numerical
derivatives. If set to zero, then the step size is
computed automatically. Ignored when AUTODERIVATIVE=0.
This value is superceded by the RELSTEP value.
.RELSTEP - the *relative* step size to be used in calculating
the numerical derivatives. This number is the
fractional size of the step, compared to the
parameter value. This value supercedes the STEP
setting. If the parameter is zero, then a default
step size is chosen.
.MPSIDE - the sidedness of the finite difference when computing
numerical derivatives. This field can take four
values:
0 - one-sided derivative computed automatically
1 - one-sided derivative (f(x+h) - f(x) )/h
-1 - one-sided derivative (f(x) - f(x-h))/h
2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)
Where H is the STEP parameter described above. The
"automatic" one-sided derivative method will chose a
direction for the finite difference which does not
violate any constraints. The other methods do not
perform this check. The two-sided method is in
principle more precise, but requires twice as many
function evaluations. Default: 0.
.MPMAXSTEP - the maximum change to be made in the parameter
value. During the fitting process, the parameter
will never be changed by more than this value in
one iteration.
A value of 0 indicates no maximum. Default: 0.
.TIED - a string expression which "ties" the parameter to other
free or fixed parameters. Any expression involving
constants and the parameter array P are permitted.
Example: if parameter 2 is always to be twice parameter
1 then use the following: parinfo(2).tied = '2 * P(1)'.
Since they are totally constrained, tied parameters are
considered to be fixed; no errors are computed for them.
[ NOTE: the PARNAME can't be used in expressions. ]
.MPPRINT - if set to 1, then the default ITERPROC will print the
parameter value. If set to 0, the parameter value
will not be printed. This tag can be used to
selectively print only a few parameter values out of
many. Default: 1 (all parameters printed)
Future modifications to the PARINFO structure, if any, will involve
adding structure tags beginning with the two letters "MP".
Therefore programmers are urged to avoid using tags starting with
the same letters; otherwise they are free to include their own
fields within the PARINFO structure, and they will be ignored.
PARINFO Example:
parinfo = replicate({value:0.D, fixed:0, limited:[0,0], $
limits:[0.D,0]}, 5)
parinfo(0).fixed = 1
parinfo(4).limited(0) = 1
parinfo(4).limits(0) = 50.D
parinfo(*).value = [5.7D, 2.2, 500., 1.5, 2000.]
A total of 5 parameters, with starting values of 5.7,
2.2, 500, 1.5, and 2000 are given. The first parameter
is fixed at a value of 5.7, and the last parameter is
constrained to be above 50.
INPUTS:
X - Array of independent variable values.
Y - Array of "measured" dependent variable values. Y should have
the same data type as X. The function FUNCT should map
X->Y.
WEIGHTS - Array of weights to be used in calculating the
chi-squared value. If WEIGHTS is specified then the ERR
parameter is ignored. The chi-squared value is computed
as follows:
CHISQ = TOTAL( (Y-FUNCT(X,P))^2 * ABS(WEIGHTS) )
Here are common values of WEIGHTS:
1D/ERR^2 - Normal weighting (ERR is the measurement error)
1D/Y - Poisson weighting (counting statistics)
1D - Unweighted
P - An array of starting values for each of the parameters of the
model. The number of parameters should be fewer than the
number of measurements. Also, the parameters should have the
same data type as the measurements (double is preferred).
Upon successful completion the new parameter values are
returned in P.
If both START_PARAMS and PARINFO are passed, then the starting
*value* is taken from START_PARAMS, but the *constraints* are
taken from PARINFO.
SIGMA - The formal 1-sigma errors in each parameter, computed from
the covariance matrix. If a parameter is held fixed, or
if it touches a boundary, then the error is reported as
zero.
If the fit is unweighted (i.e. no errors were given, or
the weights were uniformly set to unity), then SIGMA will
probably not represent the true parameter uncertainties.
*If* you can assume that the true reduced chi-squared
value is unity -- meaning that the fit is implicitly
assumed to be of good quality -- then the estimated
parameter uncertainties can be computed by scaling SIGMA
by the measured chi-squared value.
DOF = N_ELEMENTS(X) - N_ELEMENTS(P) ; deg of freedom
CSIGMA = SIGMA * SQRT(CHISQ / DOF) ; scaled uncertainties
RETURNS:
Returns the array containing the best-fitting function.
KEYWORD PARAMETERS:
CHISQ - the value of the summed, squared, weighted residuals for
the returned parameter values, i.e. the chi-square value.
COVAR - the covariance matrix for the set of parameters returned
by MPFIT. The matrix is NxN where N is the number of
parameters. The square root of the diagonal elements
gives the formal 1-sigma statistical errors on the
parameters IF errors were treated "properly" in MYFUNC.
Parameter errors are also returned in PERROR.
To compute the correlation matrix, PCOR, use this:
IDL> PCOR = COV * 0
IDL> FOR i = 0, n-1 DO FOR j = 0, n-1 DO $
PCOR(i,j) = COV(i,j)/sqrt(COV(i,i)*COV(j,j))
If NOCOVAR is set or MPFIT terminated abnormally, then
COVAR is set to a scalar with value !VALUES.D_NAN.
DOF - number of degrees of freedom, computed as
DOF = N_ELEMENTS(DEVIATES) - NFREE
Note that this doesn't account for pegged parameters (see
NPEGGED).
ERRMSG - a string error or warning message is returned.
FTOL - a nonnegative input variable. Termination occurs when both
the actual and predicted relative reductions in the sum of
squares are at most FTOL (and STATUS is accordingly set to
1 or 3). Therefore, FTOL measures the relative error
desired in the sum of squares. Default: 1D-10
FUNCTION_NAME - a scalar string containing the name of an IDL
procedure to compute the user model values, as
described above in the "USER MODEL" section.
FUNCTARGS - A structure which contains the parameters to be passed
to the user-supplied function specified by FUNCT via
the _EXTRA mechanism. This is the way you can pass
additional data to your user-supplied function without
using common blocks.
By default, no extra parameters are passed to the
user-supplied function.
GTOL - a nonnegative input variable. Termination occurs when the
cosine of the angle between fvec and any column of the
jacobian is at most GTOL in absolute value (and STATUS is
accordingly set to 4). Therefore, GTOL measures the
orthogonality desired between the function vector and the
columns of the jacobian. Default: 1D-10
ITER - the number of iterations completed.
ITERARGS - The keyword arguments to be passed to ITERPROC via the
_EXTRA mechanism. This should be a structure, and is
similar in operation to FUNCTARGS.
Default: no arguments are passed.
ITERPROC - The name of a procedure to be called upon each NPRINT
iteration of the MPFIT routine. It should be declared
in the following way:
PRO ITERPROC, FUNCT, p, iter, fnorm, FUNCTARGS=fcnargs, $
PARINFO=parinfo, QUIET=quiet, ...
; perform custom iteration update
END
ITERPROC must either accept all three keyword
parameters (FUNCTARGS, PARINFO and QUIET), or at least
accept them via the _EXTRA keyword.
FUNCT is the user-supplied function to be minimized,
P is the current set of model parameters, ITER is the
iteration number, and FUNCTARGS are the arguments to be
passed to FUNCT. FNORM should be the
chi-squared value. QUIET is set when no textual output
should be printed. See below for documentation of
PARINFO.
In implementation, ITERPROC can perform updates to the
terminal or graphical user interface, to provide
feedback while the fit proceeds. If the fit is to be
stopped for any reason, then ITERPROC should set the
common block variable ERROR_CODE to negative value (see
MPFIT_ERROR common block below). In principle,
ITERPROC should probably not modify the parameter
values, because it may interfere with the algorithm's
stability. In practice it is allowed.
Default: an internal routine is used to print the
parameter values.
ITMAX - The maximum number of iterations to perform. If the
number is exceeded, then the STATUS value is set to 5
and MPFIT returns.
Default: 200 iterations
NFEV - the number of FUNCT function evaluations performed.
NFREE - the number of free parameters in the fit. This includes
parameters which are not FIXED and not TIED, but it does
include parameters which are pegged at LIMITS.
NOCOVAR - set this keyword to prevent the calculation of the
covariance matrix before returning (see COVAR)
NODERIVATIVE - if set, then the user function will not be queried
for analytical derivatives, and instead the
derivatives will be computed by finite differences
(and according to the PARINFO derivative settings;
see above for a description).
NPRINT - The frequency with which ITERPROC is called. A value of
1 indicates that ITERPROC is called with every iteration,
while 2 indicates every other iteration, etc. Note that
several Levenberg-Marquardt attempts can be made in a
single iteration.
Default value: 1
PARINFO - Provides a mechanism for more sophisticated constraints
to be placed on parameter values. When PARINFO is not
passed, then it is assumed that all parameters are free
and unconstrained. Values in PARINFO are never
modified during a call to MPFIT.
See description above for the structure of PARINFO.
Default value: all parameters are free and unconstrained.
QUIET - set this keyword when no textual output should be printed
by MPFIT
STATUS - an integer status code is returned. All values other
than zero can represent success. It can have one of the
following values:
0 improper input parameters.
1 both actual and predicted relative reductions
in the sum of squares are at most FTOL.
2 relative error between two consecutive iterates
is at most XTOL
3 conditions for STATUS = 1 and STATUS = 2 both hold.
4 the cosine of the angle between fvec and any
column of the jacobian is at most GTOL in
absolute value.
5 the maximum number of iterations has been reached
6 FTOL is too small. no further reduction in
the sum of squares is possible.
7 XTOL is too small. no further improvement in
the approximate solution x is possible.
8 GTOL is too small. fvec is orthogonal to the
columns of the jacobian to machine precision.
TOL - synonym for FTOL. Use FTOL instead.
XTOL - a nonnegative input variable. Termination occurs when the
relative error between two consecutive iterates is at most
XTOL (and STATUS is accordingly set to 2 or 3). Therefore,
XTOL measures the relative error desired in the approximate
solution. Default: 1D-10
YERROR - upon return, the root-mean-square variance of the
residuals.
EXAMPLE:
; First, generate some synthetic data
npts = 200
x = dindgen(npts) * 0.1 - 10. ; Independent variable
yi = gauss1(x, [2.2D, 1.4, 3000.]) ; "Ideal" Y variable
y = yi + randomn(seed, npts) * sqrt(1000. + yi); Measured, w/ noise
sy = sqrt(1000.D + y) ; Poisson errors
; Now fit a Gaussian to see how well we can recover
p0 = [1.D, 1., 1000.] ; Initial guess
yfit = mpcurvefit(x, y, 1/sy^2, p0, $ ; Fit a function
FUNCTION_NAME='GAUSS1P',/autoderivative)
print, p
Generates a synthetic data set with a Gaussian peak, and Poisson
statistical uncertainty. Then the same function is fitted to the
data to see how close we can get. GAUSS1 and GAUSS1P are
available from the same web page.
COMMON BLOCKS:
COMMON MPFIT_ERROR, ERROR_CODE
User routines may stop the fitting process at any time by
setting an error condition. This condition may be set in either
the user's model computation routine (MYFUNCT), or in the
iteration procedure (ITERPROC).
To stop the fitting, the above common block must be declared,
and ERROR_CODE must be set to a negative number. After the user
procedure or function returns, MPFIT checks the value of this
common block variable and exits immediately if the error
condition has been set. By default the value of ERROR_CODE is
zero, indicating a successful function/procedure call.
REFERENCES:
MINPACK-1, Jorge More', available from netlib (www.netlib.org).
"Optimization Software Guide," Jorge More' and Stephen Wright,
SIAM, *Frontiers in Applied Mathematics*, Number 14.
MODIFICATION HISTORY:
Translated from MPFITFUN, 25 Sep 1999, CM
Alphabetized documented keywords, 02 Oct 1999, CM
Added QUERY keyword and query checking of MPFIT, 29 Oct 1999, CM
Check to be sure that X and Y are present, 02 Nov 1999, CM
Documented SIGMA for unweighted fits, 03 Nov 1999, CM
Changed to ERROR_CODE for error condition, 28 Jan 2000, CM
Copying permission terms have been liberalized, 26 Mar 2000, CM
Propagated improvements from MPFIT, 17 Dec 2000, CM
Corrected behavior of NODERIVATIVE, 13 May 2002, CM
Documented RELSTEP field of PARINFO (!!), CM, 25 Oct 2002
Make more consistent with comparable IDL routines, 30 Jun 2003, CM
Minor documentation adjustment, 03 Feb 2004, CM
Fix error in documentation, 26 Aug 2005, CM
$Id: mpcurvefit.pro,v 1.2 2006/02/07 22:38:32 schlegel Exp $
(See pro/mpfit/mpcurvefit.pro)
NAME:
MPFIT
AUTHOR:
Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
craigm@lheamail.gsfc.nasa.gov
UPDATED VERSIONs can be found on my WEB PAGE:
http://cow.physics.wisc.edu/~craigm/idl/idl.html
PURPOSE:
Perform Levenberg-Marquardt least-squares minimization (MINPACK-1)
MAJOR TOPICS:
Curve and Surface Fitting
CALLING SEQUENCE:
parms = MPFIT(MYFUNCT, start_parms, FUNCTARGS=fcnargs, NFEV=nfev,
MAXITER=maxiter, ERRMSG=errmsg, NPRINT=nprint, QUIET=quiet,
FTOL=ftol, XTOL=xtol, GTOL=gtol, NITER=niter,
STATUS=status, ITERPROC=iterproc, ITERARGS=iterargs,
COVAR=covar, PERROR=perror, BESTNORM=bestnorm,
PARINFO=parinfo)
DESCRIPTION:
MPFIT uses the Levenberg-Marquardt technique to solve the
least-squares problem. In its typical use, MPFIT will be used to
fit a user-supplied function (the "model") to user-supplied data
points (the "data") by adjusting a set of parameters. MPFIT is
based upon MINPACK-1 (LMDIF.F) by More' and collaborators.
For example, a researcher may think that a set of observed data
points is best modelled with a Gaussian curve. A Gaussian curve is
parameterized by its mean, standard deviation and normalization.
MPFIT will, within certain constraints, find the set of parameters
which best fits the data. The fit is "best" in the least-squares
sense; that is, the sum of the weighted squared differences between
the model and data is minimized.
The Levenberg-Marquardt technique is a particular strategy for
iteratively searching for the best fit. This particular
implementation is drawn from MINPACK-1 (see NETLIB), and seems to
be more robust than routines provided with IDL. This version
allows upper and lower bounding constraints to be placed on each
parameter, or the parameter can be held fixed.
The IDL user-supplied function should return an array of weighted
deviations between model and data. In a typical scientific problem
the residuals should be weighted so that each deviate has a
gaussian sigma of 1.0. If X represents values of the independent
variable, Y represents a measurement for each value of X, and ERR
represents the error in the measurements, then the deviates could
be calculated as follows:
DEVIATES = (Y - F(X)) / ERR
where F is the analytical function representing the model. You are
recommended to use the convenience functions MPFITFUN and
MPFITEXPR, which are driver functions that calculate the deviates
for you. If ERR are the 1-sigma uncertainties in Y, then
TOTAL( DEVIATES^2 )
will be the total chi-squared value. MPFIT will minimize the
chi-square value. The values of X, Y and ERR are passed through
MPFIT to the user-supplied function via the FUNCTARGS keyword.
Simple constraints can be placed on parameter values by using the
PARINFO keyword to MPFIT. See below for a description of this
keyword.
MPFIT does not perform more general optimization tasks. See TNMIN
instead. MPFIT is customized, based on MINPACK-1, to the
least-squares minimization problem.
USER FUNCTION
The user must define a function which returns the appropriate
values as specified above. The function should return the weighted
deviations between the model and the data. For applications which
use finite-difference derivatives -- the default -- the user
function should be declared in the following way:
FUNCTION MYFUNCT, p, X=x, Y=y, ERR=err
; Parameter values are passed in "p"
model = F(x, p)
return, (y-model)/err
END
See below for applications with analytical derivatives.
The keyword parameters X, Y, and ERR in the example above are
suggestive but not required. Any parameters can be passed to
MYFUNCT by using the FUNCTARGS keyword to MPFIT. Use MPFITFUN and
MPFITEXPR if you need ideas on how to do that. The function *must*
accept a parameter list, P.
In general there are no restrictions on the number of dimensions in
X, Y or ERR. However the deviates *must* be returned in a
one-dimensional array, and must have the same type (float or
double) as the input arrays.
User functions may also indicate a fatal error condition using the
ERROR_CODE common block variable, as described below under the
MPFIT_ERROR common block definition (by setting ERROR_CODE to a
number between -15 and -1).
ANALYTIC DERIVATIVES
In the search for the best-fit solution, MPFIT by default
calculates derivatives numerically via a finite difference
approximation. The user-supplied function need not calculate the
derivatives explicitly. However, if you desire to compute them
analytically, then the AUTODERIVATIVE=0 keyword must be passed. As
a practical matter, it is often sufficient and even faster to allow
MPFIT to calculate the derivatives numerically, and so
AUTODERIVATIVE=0 is not necessary.
Also, the user function must be declared with one additional
parameter, as follows:
FUNCTION MYFUNCT, p, dp, X=x, Y=y, ERR=err
model = F(x, p)
if n_params() GT 1 then begin
; Compute derivatives
dp = make_array(n_elements(x), n_elements(p), value=x(0)*0)
for i = 0, n_elements(p)-1 do $
dp(*,i) = FGRAD(x, p, i)
endif
return, (y-model)/err
END
where FGRAD(x, p, i) is a user function which must compute the
derivative of the model with respect to parameter P(i) at X. When
finite differencing is used for computing derivatives (ie, when
AUTODERIVATIVE=1), the parameter DP is not passed. Therefore
functions can use N_PARAMS() to indicate whether they must compute
the derivatives or not.
Derivatives should be returned in the DP array. DP should be an m x
n array, where m is the number of data points and n is the number
of parameters. dp(i,j) is the derivative at the ith point with
respect to the jth parameter.
The derivatives with respect to fixed parameters are ignored; zero
is an appropriate value to insert for those derivatives. Upon
input to the user function, DP is set to a vector with the same
length as P, with a value of 1 for a parameter which is free, and a
value of zero for a parameter which is fixed (and hence no
derivative needs to be calculated). This input vector may be
overwritten as needed.
If the data is higher than one dimensional, then the *last*
dimension should be the parameter dimension. Example: fitting a
50x50 image, "dp" should be 50x50xNPAR.
CONSTRAINING PARAMETER VALUES WITH THE PARINFO KEYWORD
The behavior of MPFIT can be modified with respect to each
parameter to be fitted. A parameter value can be fixed; simple
boundary constraints can be imposed; limitations on the parameter
changes can be imposed; properties of the automatic derivative can
be modified; and parameters can be tied to one another.
These properties are governed by the PARINFO structure, which is
passed as a keyword parameter to MPFIT.
PARINFO should be an array of structures, one for each parameter.
Each parameter is associated with one element of the array, in
numerical order. The structure can have the following entries
(none are required):
.VALUE - the starting parameter value (but see the START_PARAMS
parameter for more information).
.FIXED - a boolean value, whether the parameter is to be held
fixed or not. Fixed parameters are not varied by
MPFIT, but are passed on to MYFUNCT for evaluation.
.LIMITED - a two-element boolean array. If the first/second
element is set, then the parameter is bounded on the
lower/upper side. A parameter can be bounded on both
sides. Both LIMITED and LIMITS must be given
together.
.LIMITS - a two-element float or double array. Gives the
parameter limits on the lower and upper sides,
respectively. Zero, one or two of these values can be
set, depending on the values of LIMITED. Both LIMITED
and LIMITS must be given together.
.PARNAME - a string, giving the name of the parameter. The
fitting code of MPFIT does not use this tag in any
way. However, the default ITERPROC will print the
parameter name if available.
.STEP - the step size to be used in calculating the numerical
derivatives. If set to zero, then the step size is
computed automatically. Ignored when AUTODERIVATIVE=0.
This value is superceded by the RELSTEP value.
.RELSTEP - the *relative* step size to be used in calculating
the numerical derivatives. This number is the
fractional size of the step, compared to the
parameter value. This value supercedes the STEP
setting. If the parameter is zero, then a default
step size is chosen.
.MPSIDE - the sidedness of the finite difference when computing
numerical derivatives. This field can take four
values:
0 - one-sided derivative computed automatically
1 - one-sided derivative (f(x+h) - f(x) )/h
-1 - one-sided derivative (f(x) - f(x-h))/h
2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)
Where H is the STEP parameter described above. The
"automatic" one-sided derivative method will chose a
direction for the finite difference which does not
violate any constraints. The other methods do not
perform this check. The two-sided method is in
principle more precise, but requires twice as many
function evaluations. Default: 0.
.MPMAXSTEP - the maximum change to be made in the parameter
value. During the fitting process, the parameter
will never be changed by more than this value in
one iteration.
A value of 0 indicates no maximum. Default: 0.
.TIED - a string expression which "ties" the parameter to other
free or fixed parameters as an equality constraint. Any
expression involving constants and the parameter array P
are permitted.
Example: if parameter 2 is always to be twice parameter
1 then use the following: parinfo(2).tied = '2 * P(1)'.
Since they are totally constrained, tied parameters are
considered to be fixed; no errors are computed for them.
[ NOTE: the PARNAME can't be used in expressions. ]
.MPPRINT - if set to 1, then the default ITERPROC will print the
parameter value. If set to 0, the parameter value
will not be printed. This tag can be used to
selectively print only a few parameter values out of
many. Default: 1 (all parameters printed)
.MPFORMAT - IDL format string to print the parameter within
ITERPROC. Default: '(G20.6)' An empty string will
also use the default.
Future modifications to the PARINFO structure, if any, will involve
adding structure tags beginning with the two letters "MP".
Therefore programmers are urged to avoid using tags starting with
the same letters; otherwise they are free to include their own
fields within the PARINFO structure, and they will be ignored.
PARINFO Example:
parinfo = replicate({value:0.D, fixed:0, limited:[0,0], $
limits:[0.D,0]}, 5)
parinfo(0).fixed = 1
parinfo(4).limited(0) = 1
parinfo(4).limits(0) = 50.D
parinfo(*).value = [5.7D, 2.2, 500., 1.5, 2000.]
A total of 5 parameters, with starting values of 5.7,
2.2, 500, 1.5, and 2000 are given. The first parameter
is fixed at a value of 5.7, and the last parameter is
constrained to be above 50.
HARD-TO-COMPUTE FUNCTIONS: "EXTERNAL" EVALUATION
The normal mode of operation for MPFIT is for the user to pass a
function name, and MPFIT will call the user function multiple times
as it iterates toward a solution.
Some user functions are particularly hard to compute using the
standard model of MPFIT. Usually these are functions that depend
on a large amount of external data, and so it is not feasible, or
at least highly impractical, to have MPFIT call it. In those cases
it may be possible to use the "(EXTERNAL)" evaluation option.
In this case the user is responsible for making all function *and
derivative* evaluations. The function and Jacobian data are passed
in through the EXTERNAL_FVEC and EXTERNAL_FJAC keywords,
respectively. The user indicates the selection of this option by
specifying a function name (MYFUNCT) of "(EXTERNAL)". No
user-function calls are made when EXTERNAL evaluation is being
used.
At the end of each iteration, control returns to the user, who must
reevaluate the function at its new parameter values. Users should
check the return value of the STATUS keyword, where a value of 9
indicates the user should supply more data for the next iteration,
and re-call MPFIT. The user may refrain from calling MPFIT
further; as usual, STATUS will indicate when the solution has
converged and no more iterations are required.
Because MPFIT must maintain its own data structures between calls,
the user must also pass a named variable to the EXTERNAL_STATE
keyword. This variable must be maintained by the user, but not
changed, throughout the fitting process. When no more iterations
are desired, the named variable may be discarded.
INPUTS:
MYFUNCT - a string variable containing the name of the function to
be minimized. The function should return the weighted
deviations between the model and the data, as described
above.
For EXTERNAL evaluation of functions, this parameter
should be set to a value of "(EXTERNAL)".
START_PARAMS - An array of starting values for each of the
parameters of the model. The number of parameters
should be fewer than the number of measurements.
Also, the parameters should have the same data type
as the measurements (double is preferred).
This parameter is optional if the PARINFO keyword
is used (but see PARINFO). The PARINFO keyword
provides a mechanism to fix or constrain individual
parameters. If both START_PARAMS and PARINFO are
passed, then the starting *value* is taken from
START_PARAMS, but the *constraints* are taken from
PARINFO.
RETURNS:
Returns the array of best-fit parameters.
KEYWORD PARAMETERS:
AUTODERIVATIVE - If this is set, derivatives of the function will
be computed automatically via a finite
differencing procedure. If not set, then MYFUNCT
must provide the (analytical) derivatives.
Default: set (=1)
NOTE: to supply your own analytical derivatives,
explicitly pass AUTODERIVATIVE=0
BESTNORM - the value of the summed squared weighted residuals for
the returned parameter values, i.e. TOTAL(DEVIATES^2).
COVAR - the covariance matrix for the set of parameters returned
by MPFIT. The matrix is NxN where N is the number of
parameters. The square root of the diagonal elements
gives the formal 1-sigma statistical errors on the
parameters IF errors were treated "properly" in MYFUNC.
Parameter errors are also returned in PERROR.
To compute the correlation matrix, PCOR, use this example:
IDL> PCOR = COV * 0
IDL> FOR i = 0, n-1 DO FOR j = 0, n-1 DO $
PCOR(i,j) = COV(i,j)/sqrt(COV(i,i)*COV(j,j))
If NOCOVAR is set or MPFIT terminated abnormally, then
COVAR is set to a scalar with value !VALUES.D_NAN.
DOF - number of degrees of freedom, computed as
DOF = N_ELEMENTS(DEVIATES) - NFREE
Note that this doesn't account for pegged parameters (see
NPEGGED).
ERRMSG - a string error or warning message is returned.
EXTERNAL_FVEC - upon input, the function values, evaluated at
START_PARAMS. This should be an M-vector, where M
is the number of data points.
EXTERNAL_FJAC - upon input, the Jacobian array of partial
derivative values. This should be a M x N array,
where M is the number of data points and N is the
number of parameters. NOTE: that all FIXED or
TIED parameters must *not* be included in this
array.
EXTERNAL_STATE - a named variable to store MPFIT-related state
information between iterations (used in input and
output to MPFIT). The user must not manipulate
or discard this data until the final iteration is
performed.
FASTNORM - set this keyword to select a faster algorithm to
compute sum-of-square values internally. For systems
with large numbers of data points, the standard
algorithm can become prohibitively slow because it
cannot be vectorized well. By setting this keyword,
MPFIT will run faster, but it will be more prone to
floating point overflows and underflows. Thus, setting
this keyword may sacrifice some stability in the
fitting process.
FTOL - a nonnegative input variable. Termination occurs when both
the actual and predicted relative reductions in the sum of
squares are at most FTOL (and STATUS is accordingly set to
1 or 3). Therefore, FTOL measures the relative error
desired in the sum of squares. Default: 1D-10
FUNCTARGS - A structure which contains the parameters to be passed
to the user-supplied function specified by MYFUNCT via
the _EXTRA mechanism. This is the way you can pass
additional data to your user-supplied function without
using common blocks.
Consider the following example:
if FUNCTARGS = { XVAL:[1.D,2,3], YVAL:[1.D,4,9],
ERRVAL:[1.D,1,1] }
then the user supplied function should be declared
like this:
FUNCTION MYFUNCT, P, XVAL=x, YVAL=y, ERRVAL=err
By default, no extra parameters are passed to the
user-supplied function, but your function should
accept *at least* one keyword parameter. [ This is to
accomodate a limitation in IDL's _EXTRA
parameter-passing mechanism. ]
GTOL - a nonnegative input variable. Termination occurs when the
cosine of the angle between fvec and any column of the
jacobian is at most GTOL in absolute value (and STATUS is
accordingly set to 4). Therefore, GTOL measures the
orthogonality desired between the function vector and the
columns of the jacobian. Default: 1D-10
ITERARGS - The keyword arguments to be passed to ITERPROC via the
_EXTRA mechanism. This should be a structure, and is
similar in operation to FUNCTARGS.
Default: no arguments are passed.
ITERPRINT - The name of an IDL procedure, equivalent to PRINT,
that ITERPROC will use to render output. ITERPRINT
should be able to accept at least four positional
arguments. In addition, it should be able to accept
the standard FORMAT keyword for output formatting; and
the UNIT keyword, to redirect output to a logical file
unit (default should be UNIT=1, standard output).
These keywords are passed using the ITERARGS keyword
above. The ITERPRINT procedure must accept the _EXTRA
keyword.
ITERPROC - The name of a procedure to be called upon each NPRINT
iteration of the MPFIT routine. ITERPROC is always
called in the final iteration. It should be declared
in the following way:
PRO ITERPROC, MYFUNCT, p, iter, fnorm, FUNCTARGS=fcnargs, $
PARINFO=parinfo, QUIET=quiet, DOF=dof, ...
; perform custom iteration update
END
ITERPROC must either accept all three keyword
parameters (FUNCTARGS, PARINFO and QUIET), or at least
accept them via the _EXTRA keyword.
MYFUNCT is the user-supplied function to be minimized,
P is the current set of model parameters, ITER is the
iteration number, and FUNCTARGS are the arguments to be
passed to MYFUNCT. FNORM should be the chi-squared
value. QUIET is set when no textual output should be
printed. DOF is the number of degrees of freedom,
normally the number of points less the number of free
parameters. See below for documentation of PARINFO.
In implementation, ITERPROC can perform updates to the
terminal or graphical user interface, to provide
feedback while the fit proceeds. If the fit is to be
stopped for any reason, then ITERPROC should set the
common block variable ERROR_CODE to negative value
between -15 and -1 (see MPFIT_ERROR common block
below). In principle, ITERPROC should probably not
modify the parameter values, because it may interfere
with the algorithm's stability. In practice it is
allowed.
Default: an internal routine is used to print the
parameter values.
ITERSTOP - Set this keyword if you wish to be able to stop the
fitting by hitting the predefined ITERKEYSTOP key on
the keyboard. This only works if you use the default
ITERPROC.
ITERKEYSTOP - A keyboard key which will halt the fit (and if
ITERSTOP is set and the default ITERPROC is used).
ITERSTOPKEY may either be a one-character string
with the desired key, or a scalar integer giving the
ASCII code of the desired key.
Default: 7b (control-g)
NOTE: the default value of ASCI 7 (control-G) cannot
be read in some windowing environments, so you must
change to a printable character like 'q'.
MAXITER - The maximum number of iterations to perform. If the
number is exceeded, then the STATUS value is set to 5
and MPFIT returns.
Default: 200 iterations
NFEV - the number of MYFUNCT function evaluations performed.
NFREE - the number of free parameters in the fit. This includes
parameters which are not FIXED and not TIED, but it does
include parameters which are pegged at LIMITS.
NITER - the number of iterations completed.
NOCOVAR - set this keyword to prevent the calculation of the
covariance matrix before returning (see COVAR)
NPEGGED - the number of free parameters which are pegged at a
LIMIT.
NPRINT - The frequency with which ITERPROC is called. A value of
1 indicates that ITERPROC is called with every iteration,
while 2 indicates every other iteration, etc. Be aware
that several Levenberg-Marquardt attempts can be made in
a single iteration. Also, the ITERPROC is *always*
called for the final iteration, regardless of the
iteration number.
Default value: 1
PARINFO - Provides a mechanism for more sophisticated constraints
to be placed on parameter values. When PARINFO is not
passed, then it is assumed that all parameters are free
and unconstrained. Values in PARINFO are never
modified during a call to MPFIT.
See description above for the structure of PARINFO.
Default value: all parameters are free and unconstrained.
PERROR - The formal 1-sigma errors in each parameter, computed
from the covariance matrix. If a parameter is held
fixed, or if it touches a boundary, then the error is
reported as zero.
If the fit is unweighted (i.e. no errors were given, or
the weights were uniformly set to unity), then PERROR
will probably not represent the true parameter
uncertainties.
*If* you can assume that the true reduced chi-squared
value is unity -- meaning that the fit is implicitly
assumed to be of good quality -- then the estimated
parameter uncertainties can be computed by scaling PERROR
by the measured chi-squared value.
DOF = N_ELEMENTS(X) - N_ELEMENTS(PARMS) ; deg of freedom
PCERROR = PERROR * SQRT(BESTNORM / DOF) ; scaled uncertainties
QUIET - set this keyword when no textual output should be printed
by MPFIT
RESDAMP - a scalar number, indicating the cut-off value of
residuals where "damping" will occur. Residuals with
magnitudes greater than this number will be replaced by
their logarithm. This partially mitigates the so-called
large residual problem inherent in least-squares solvers
(as for the test problem CURVI, http://www.maxthis.com/-
curviex.htm). A value of 0 indicates no damping.
Default: 0
Note: RESDAMP doesn't work with AUTODERIV=0
STATUS - an integer status code is returned. All values greater
than zero can represent success (however STATUS EQ 5 may
indicate failure to converge). It can have one of the
following values:
-16 a parameter or function value has become infinite or an
undefined number. This is usually a consequence of
numerical overflow in the user's model function, which
must be avoided.
-15 to -1
these are error codes that either MYFUNCT or ITERPROC
may return to terminate the fitting process (see
description of MPFIT_ERROR common below). If either
MYFUNCT or ITERPROC set ERROR_CODE to a negative number,
then that number is returned in STATUS. Values from -15
to -1 are reserved for the user functions and will not
clash with MPFIT.
0 improper input parameters.
1 both actual and predicted relative reductions
in the sum of squares are at most FTOL.
2 relative error between two consecutive iterates
is at most XTOL
3 conditions for STATUS = 1 and STATUS = 2 both hold.
4 the cosine of the angle between fvec and any
column of the jacobian is at most GTOL in
absolute value.
5 the maximum number of iterations has been reached
6 FTOL is too small. no further reduction in
the sum of squares is possible.
7 XTOL is too small. no further improvement in
the approximate solution x is possible.
8 GTOL is too small. fvec is orthogonal to the
columns of the jacobian to machine precision.
9 A successful single iteration has been completed, and
the user must supply another "EXTERNAL" evaluation of
the function and its derivatives. This status indicator
is neither an error nor a convergence indicator.
XTOL - a nonnegative input variable. Termination occurs when the
relative error between two consecutive iterates is at most
XTOL (and STATUS is accordingly set to 2 or 3). Therefore,
XTOL measures the relative error desired in the approximate
solution. Default: 1D-10
EXAMPLE:
p0 = [5.7D, 2.2, 500., 1.5, 2000.]
fa = {X:x, Y:y, ERR:err}
p = mpfit('MYFUNCT', p0, functargs=fa)
Minimizes sum of squares of MYFUNCT. MYFUNCT is called with the X,
Y, and ERR keyword parameters that are given by FUNCTARGS. The
resulting parameter values are returned in p.
COMMON BLOCKS:
COMMON MPFIT_ERROR, ERROR_CODE
User routines may stop the fitting process at any time by
setting an error condition. This condition may be set in either
the user's model computation routine (MYFUNCT), or in the
iteration procedure (ITERPROC).
To stop the fitting, the above common block must be declared,
and ERROR_CODE must be set to a negative number. After the user
procedure or function returns, MPFIT checks the value of this
common block variable and exits immediately if the error
condition has been set. This value is also returned in the
STATUS keyword: values of -1 through -15 are reserved error
codes for the user routines. By default the value of ERROR_CODE
is zero, indicating a successful function/procedure call.
COMMON MPFIT_PROFILE
COMMON MPFIT_MACHAR
COMMON MPFIT_CONFIG
These are undocumented common blocks are used internally by
MPFIT and may change in future implementations.
THEORY OF OPERATION:
There are many specific strategies for function minimization. One
very popular technique is to use function gradient information to
realize the local structure of the function. Near a local minimum
the function value can be taylor expanded about x0 as follows:
f(x) = f(x0) + f'(x0) . (x-x0) + (1/2) (x-x0) . f''(x0) . (x-x0)
----- --------------- ------------------------------- (1)
Order 0th 1st 2nd
Here f'(x) is the gradient vector of f at x, and f''(x) is the
Hessian matrix of second derivatives of f at x. The vector x is
the set of function parameters, not the measured data vector. One
can find the minimum of f, f(xm) using Newton's method, and
arrives at the following linear equation:
f''(x0) . (xm-x0) = - f'(x0) (2)
If an inverse can be found for f''(x0) then one can solve for
(xm-x0), the step vector from the current position x0 to the new
projected minimum. Here the problem has been linearized (ie, the
gradient information is known to first order). f''(x0) is
symmetric n x n matrix, and should be positive definite.
The Levenberg - Marquardt technique is a variation on this theme.
It adds an additional diagonal term to the equation which may aid the
convergence properties:
(f''(x0) + nu I) . (xm-x0) = -f'(x0) (2a)
where I is the identity matrix. When nu is large, the overall
matrix is diagonally dominant, and the iterations follow steepest
descent. When nu is small, the iterations are quadratically
convergent.
In principle, if f''(x0) and f'(x0) are known then xm-x0 can be
determined. However the Hessian matrix is often difficult or
impossible to compute. The gradient f'(x0) may be easier to
compute, if even by finite difference techniques. So-called
quasi-Newton techniques attempt to successively estimate f''(x0)
by building up gradient information as the iterations proceed.
In the least squares problem there are further simplifications
which assist in solving eqn (2). The function to be minimized is
a sum of squares:
f = Sum(hi^2) (3)
where hi is the ith residual out of m residuals as described
above. This can be substituted back into eqn (2) after computing
the derivatives:
f' = 2 Sum(hi hi')
f'' = 2 Sum(hi' hj') + 2 Sum(hi hi'') (4)
If one assumes that the parameters are already close enough to a
minimum, then one typically finds that the second term in f'' is
negligible [or, in any case, is too difficult to compute]. Thus,
equation (2) can be solved, at least approximately, using only
gradient information.
In matrix notation, the combination of eqns (2) and (4) becomes:
hT' . h' . dx = - hT' . h (5)
Where h is the residual vector (length m), hT is its transpose, h'
is the Jacobian matrix (dimensions n x m), and dx is (xm-x0). The
user function supplies the residual vector h, and in some cases h'
when it is not found by finite differences (see MPFIT_FDJAC2,
which finds h and hT'). Even if dx is not the best absolute step
to take, it does provide a good estimate of the best *direction*,
so often a line minimization will occur along the dx vector
direction.
The method of solution employed by MINPACK is to form the Q . R
factorization of h', where Q is an orthogonal matrix such that QT .
Q = I, and R is upper right triangular. Using h' = Q . R and the
ortogonality of Q, eqn (5) becomes
(RT . QT) . (Q . R) . dx = - (RT . QT) . h
RT . R . dx = - RT . QT . h (6)
R . dx = - QT . h
where the last statement follows because R is upper triangular.
Here, R, QT and h are known so this is a matter of solving for dx.
The routine MPFIT_QRFAC provides the QR factorization of h, with
pivoting, and MPFIT_QRSOLV provides the solution for dx.
REFERENCES:
MINPACK-1, Jorge More', available from netlib (www.netlib.org).
"Optimization Software Guide," Jorge More' and Stephen Wright,
SIAM, *Frontiers in Applied Mathematics*, Number 14.
More', Jorge J., "The Levenberg-Marquardt Algorithm:
Implementation and Theory," in *Numerical Analysis*, ed. Watson,
G. A., Lecture Notes in Mathematics 630, Springer-Verlag, 1977.
MODIFICATION HISTORY:
Translated from MINPACK-1 in FORTRAN, Apr-Jul 1998, CM
Fixed bug in parameter limits (x vs xnew), 04 Aug 1998, CM
Added PERROR keyword, 04 Aug 1998, CM
Added COVAR keyword, 20 Aug 1998, CM
Added NITER output keyword, 05 Oct 1998
D.L Windt, Bell Labs, windt@bell-labs.com;
Made each PARINFO component optional, 05 Oct 1998 CM
Analytical derivatives allowed via AUTODERIVATIVE keyword, 09 Nov 1998
Parameter values can be tied to others, 09 Nov 1998
Fixed small bugs (Wayne Landsman), 24 Nov 1998
Added better exception error reporting, 24 Nov 1998 CM
Cosmetic documentation changes, 02 Jan 1999 CM
Changed definition of ITERPROC to be consistent with TNMIN, 19 Jan 1999 CM
Fixed bug when AUTDERIVATIVE=0. Incorrect sign, 02 Feb 1999 CM
Added keyboard stop to MPFIT_DEFITER, 28 Feb 1999 CM
Cosmetic documentation changes, 14 May 1999 CM
IDL optimizations for speed & FASTNORM keyword, 15 May 1999 CM
Tried a faster version of mpfit_enorm, 30 May 1999 CM
Changed web address to cow.physics.wisc.edu, 14 Jun 1999 CM
Found malformation of FDJAC in MPFIT for 1 parm, 03 Aug 1999 CM
Factored out user-function call into MPFIT_CALL. It is possible,
but currently disabled, to call procedures. The calling format
is similar to CURVEFIT, 25 Sep 1999, CM
Slightly changed mpfit_tie to be less intrusive, 25 Sep 1999, CM
Fixed some bugs associated with tied parameters in mpfit_fdjac, 25
Sep 1999, CM
Reordered documentation; now alphabetical, 02 Oct 1999, CM
Added QUERY keyword for more robust error detection in drivers, 29
Oct 1999, CM
Documented PERROR for unweighted fits, 03 Nov 1999, CM
Split out MPFIT_RESETPROF to aid in profiling, 03 Nov 1999, CM
Some profiling and speed optimization, 03 Nov 1999, CM
Worst offenders, in order: fdjac2, qrfac, qrsolv, enorm.
fdjac2 depends on user function, qrfac and enorm seem to be
fully optimized. qrsolv probably could be tweaked a little, but
is still <10% of total compute time.
Made sure that !err was set to 0 in MPFIT_DEFITER, 10 Jan 2000, CM
Fixed small inconsistency in setting of QANYLIM, 28 Jan 2000, CM
Added PARINFO field RELSTEP, 28 Jan 2000, CM
Converted to MPFIT_ERROR common block for indicating error
conditions, 28 Jan 2000, CM
Corrected scope of MPFIT_ERROR common block, CM, 07 Mar 2000
Minor speed improvement in MPFIT_ENORM, CM 26 Mar 2000
Corrected case where ITERPROC changed parameter values and
parameter values were TIED, CM 26 Mar 2000
Changed MPFIT_CALL to modify NFEV automatically, and to support
user procedures more, CM 26 Mar 2000
Copying permission terms have been liberalized, 26 Mar 2000, CM
Catch zero value of zero a(j,lj) in MPFIT_QRFAC, 20 Jul 2000, CM
(thanks to David Schlegel <schlegel@astro.princeton.edu>)
MPFIT_SETMACHAR is called only once at init; only one common block
is created (MPFIT_MACHAR); it is now a structure; removed almost
all CHECK_MATH calls for compatibility with IDL5 and !EXCEPT;
profiling data is now in a structure too; noted some
mathematical discrepancies in Linux IDL5.0, 17 Nov 2000, CM
Some significant changes. New PARINFO fields: MPSIDE, MPMINSTEP,
MPMAXSTEP. Improved documentation. Now PTIED constraints are
maintained in the MPCONFIG common block. A new procedure to
parse PARINFO fields. FDJAC2 now computes a larger variety of
one-sided and two-sided finite difference derivatives. NFEV is
stored in the MPCONFIG common now. 17 Dec 2000, CM
Added check that PARINFO and XALL have same size, 29 Dec 2000 CM
Don't call function in TERMINATE when there is an error, 05 Jan
2000
Check for float vs. double discrepancies; corrected implementation
of MIN/MAXSTEP, which I still am not sure of, but now at least
the correct behavior occurs *without* it, CM 08 Jan 2001
Added SCALE_FCN keyword, to allow for scaling, as for the CASH
statistic; added documentation about the theory of operation,
and under the QR factorization; slowly I'm beginning to
understand the bowels of this algorithm, CM 10 Jan 2001
Remove MPMINSTEP field of PARINFO, for now at least, CM 11 Jan
2001
Added RESDAMP keyword, CM, 14 Jan 2001
Tried to improve the DAMP handling a little, CM, 13 Mar 2001
Corrected .PARNAME behavior in _DEFITER, CM, 19 Mar 2001
Added checks for parameter and function overflow; a new STATUS
value to reflect this; STATUS values of -15 to -1 are reserved
for user function errors, CM, 03 Apr 2001
DAMP keyword is now a TANH, CM, 03 Apr 2001
Added more error checking of float vs. double, CM, 07 Apr 2001
Fixed bug in handling of parameter lower limits; moved overflow
checking to end of loop, CM, 20 Apr 2001
Failure using GOTO, TERMINATE more graceful if FNORM1 not defined,
CM, 13 Aug 2001
Add MPPRINT tag to PARINFO, CM, 19 Nov 2001
Add DOF keyword to DEFITER procedure, and print degrees of
freedom, CM, 28 Nov 2001
Add check to be sure MYFUNCT is a scalar string, CM, 14 Jan 2002
Addition of EXTERNAL_FJAC, EXTERNAL_FVEC keywords; ability to save
fitter's state from one call to the next; allow '(EXTERNAL)'
function name, which implies that user will supply function and
Jacobian at each iteration, CM, 10 Mar 2002
Documented EXTERNAL evaluation code, CM, 10 Mar 2002
Corrected signficant bug in the way that the STEP parameter, and
FIXED parameters interacted (Thanks Andrew Steffl), CM, 02 Apr
2002
Allow COVAR and PERROR keywords to be computed, even in case of
'(EXTERNAL)' function, 26 May 2002
Add NFREE and NPEGGED keywords; compute NPEGGED; compute DOF using
NFREE instead of n_elements(X), thanks to Kristian Kjaer, CM 11
Sep 2002
Hopefully PERROR is all positive now, CM 13 Sep 2002
Documented RELSTEP field of PARINFO (!!), CM, 25 Oct 2002
Error checking to detect missing start pars, CM 12 Apr 2003
Add DOF keyword to return degrees of freedom, CM, 30 June 2003
Always call ITERPROC in the final iteration; add ITERKEYSTOP
keyword, CM, 30 June 2003
Correct bug in MPFIT_LMPAR of singularity handling, which might
likely be fatal for one-parameter fits, CM, 21 Nov 2003
(with thanks to Peter Tuthill for the proper test case)
Minor documentation adjustment, 03 Feb 2004, CM
Correct small error in QR factorization when pivoting; document
the return values of QRFAC when pivoting, 21 May 2004, CM
Add MPFORMAT field to PARINFO, and correct behavior of interaction
between MPPRINT and PARNAME in MPFIT_DEFITERPROC (thanks to Tim
Robishaw), 23 May 2004, CM
Add the ITERPRINT keyword to allow redirecting output, 26 Sep
2004, CM
Correct MAXSTEP behavior in case of a negative parameter, 26 Sep
2004, CM
Fix bug in the parsing of MINSTEP/MAXSTEP, 10 Apr 2005, CM
Fix bug in the handling of upper/lower limits when the limit was
negative (the fitting code would never "stick" to the lower
limit), 29 Jun 2005, CM
Small documentation update for the TIED field, 05 Sep 2005, CM
$Id: mpfit.pro,v 1.2 2006/02/07 22:38:32 schlegel Exp $
(See pro/mpfit/mpfit.pro)
NAME:
MPFIT2DFUN
AUTHOR:
Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
craigm@lheamail.gsfc.nasa.gov
UPDATED VERSIONs can be found on my WEB PAGE:
http://cow.physics.wisc.edu/~craigm/idl/idl.html
PURPOSE:
Perform Levenberg-Marquardt least-squares fit to a 2-D IDL function
MAJOR TOPICS:
Curve and Surface Fitting
CALLING SEQUENCE:
parms = MPFIT2DFUN(MYFUNCT, X, Y, Z, ERR, start_parms, ...)
DESCRIPTION:
MPFIT2DFUN fits a user-supplied model -- in the form of an IDL
function -- to a set of user-supplied data. MPFIT2DFUN calls
MPFIT, the MINPACK-1 least-squares minimizer, to do the main
work. MPFIT2DFUN is a specialized version for two-dimensional
data.
Given the data and their uncertainties, MPFIT2DFUN finds the best set
of model parameters which match the data (in a least-squares
sense) and returns them in an array.
The user must supply the following items:
- Two arrays of independent variable values ("X", "Y").
- An array of "measured" *dependent* variable values ("Z").
- An array of "measured" 1-sigma uncertainty values ("ERR").
- The name of an IDL function which computes Z given (X,Y) ("MYFUNCT").
- Starting guesses for all of the parameters ("START_PARAMS").
There are very few restrictions placed on X, Y, Z, or MYFUNCT.
Simply put, MYFUNCT must map the (X,Y) values into Z values given
the model parameters. The (X,Y) values are usually the independent
X and Y coordinate positions in the two dimensional plane, but need
not be.
MPFIT2DFUN carefully avoids passing large arrays where possible to
improve performance.
See below for an example of usage.
USER FUNCTION
The user must define a function which returns the model value. For
applications which use finite-difference derivatives -- the default
-- the user function should be declared in the following way:
FUNCTION MYFUNCT, X, Y, P
; The independent variables are X and Y
; Parameter values are passed in "P"
ZMOD = ... computed model values at (X,Y) ...
return, ZMOD
END
The returned array YMOD must have the same dimensions and type as
the "measured" Z values.
User functions may also indicate a fatal error condition
using the ERROR_CODE common block variable, as described
below under the MPFIT_ERROR common block definition.
See the discussion under "ANALYTIC DERIVATIVES" and AUTODERIVATIVE
in MPFIT.PRO if you wish to compute the derivatives for yourself.
AUTODERIVATIVE is accepted and passed directly to MPFIT. The user
function must accept one additional parameter, DP, which contains
the derivative of the user function with respect to each parameter
at each data point, as described in MPFIT.PRO.
CREATING APPROPRIATELY DIMENSIONED INDEPENDENT VARIABLES
The user must supply appropriate independent variables to
MPFIT2DFUN. For image fitting applications, this variable should
be two-dimensional *arrays* describing the X and Y positions of
every *pixel*. [ Thus any two dimensional sampling is permitted,
including irregular sampling. ]
If the sampling is regular, then the x coordinates are the same for
each row, and the y coordinates are the same for each column. Call
the x-row and y-column coordinates XR and YC respectively. You can
then compute X and Y as follows:
X = XR # (YC*0 + 1) eqn. 1
Y = (XR*0 + 1) # YC eqn. 2
For example, if XR and YC have the following values:
XR = [ 1, 2, 3, 4, 5,] ;; X positions of one row of pixels
YC = [ 15,16,17 ] ;; Y positions of one column of
pixels
Then using equations 1 and 2 above will give these values to X and
Y:
X : 1 2 3 4 5 ;; X positions of all pixels
1 2 3 4 5
1 2 3 4 5
Y : 15 15 15 15 15 ;; Y positions of all pixels
16 16 16 16 16
17 17 17 17 17
Using the above technique is suggested, but *not* required. You
can do anything you wish with the X and Y values. This technique
only makes it easier to compute your model function values.
CONSTRAINING PARAMETER VALUES WITH THE PARINFO KEYWORD
The behavior of MPFIT can be modified with respect to each
parameter to be fitted. A parameter value can be fixed; simple
boundary constraints can be imposed; limitations on the parameter
changes can be imposed; properties of the automatic derivative can
be modified; and parameters can be tied to one another.
These properties are governed by the PARINFO structure, which is
passed as a keyword parameter to MPFIT.
PARINFO should be an array of structures, one for each parameter.
Each parameter is associated with one element of the array, in
numerical order. The structure can have the following entries
(none are required):
.VALUE - the starting parameter value (but see the START_PARAMS
parameter for more information).
.FIXED - a boolean value, whether the parameter is to be held
fixed or not. Fixed parameters are not varied by
MPFIT, but are passed on to MYFUNCT for evaluation.
.LIMITED - a two-element boolean array. If the first/second
element is set, then the parameter is bounded on the
lower/upper side. A parameter can be bounded on both
sides. Both LIMITED and LIMITS must be given
together.
.LIMITS - a two-element float or double array. Gives the
parameter limits on the lower and upper sides,
respectively. Zero, one or two of these values can be
set, depending on the values of LIMITED. Both LIMITED
and LIMITS must be given together.
.PARNAME - a string, giving the name of the parameter. The
fitting code of MPFIT does not use this tag in any
way. However, the default ITERPROC will print the
parameter name if available.
.STEP - the step size to be used in calculating the numerical
derivatives. If set to zero, then the step size is
computed automatically. Ignored when AUTODERIVATIVE=0.
This value is superceded by the RELSTEP value.
.RELSTEP - the *relative* step size to be used in calculating
the numerical derivatives. This number is the
fractional size of the step, compared to the
parameter value. This value supercedes the STEP
setting. If the parameter is zero, then a default
step size is chosen.
.MPSIDE - the sidedness of the finite difference when computing
numerical derivatives. This field can take four
values:
0 - one-sided derivative computed automatically
1 - one-sided derivative (f(x+h) - f(x) )/h
-1 - one-sided derivative (f(x) - f(x-h))/h
2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)
Where H is the STEP parameter described above. The
"automatic" one-sided derivative method will chose a
direction for the finite difference which does not
violate any constraints. The other methods do not
perform this check. The two-sided method is in
principle more precise, but requires twice as many
function evaluations. Default: 0.
.MPMINSTEP - the minimum change to be made in the parameter
value. During the fitting process, the parameter
will be changed by multiples of this value. The
actual step is computed as:
DELTA1 = MPMINSTEP*ROUND(DELTA0/MPMINSTEP)
where DELTA0 and DELTA1 are the estimated parameter
changes before and after this constraint is
applied. Note that this constraint should be used
with care since it may cause non-converging,
oscillating solutions.
A value of 0 indicates no minimum. Default: 0.
.MPMAXSTEP - the maximum change to be made in the parameter
value. During the fitting process, the parameter
will never be changed by more than this value.
A value of 0 indicates no maximum. Default: 0.
.TIED - a string expression which "ties" the parameter to other
free or fixed parameters. Any expression involving
constants and the parameter array P are permitted.
Example: if parameter 2 is always to be twice parameter
1 then use the following: parinfo(2).tied = '2 * P(1)'.
Since they are totally constrained, tied parameters are
considered to be fixed; no errors are computed for them.
[ NOTE: the PARNAME can't be used in expressions. ]
Future modifications to the PARINFO structure, if any, will involve
adding structure tags beginning with the two letters "MP".
Therefore programmers are urged to avoid using tags starting with
the same letters; otherwise they are free to include their own
fields within the PARINFO structure, and they will be ignored.
PARINFO Example:
parinfo = replicate({value:0.D, fixed:0, limited:[0,0], $
limits:[0.D,0]}, 5)
parinfo(0).fixed = 1
parinfo(4).limited(0) = 1
parinfo(4).limits(0) = 50.D
parinfo(*).value = [5.7D, 2.2, 500., 1.5, 2000.]
A total of 5 parameters, with starting values of 5.7,
2.2, 500, 1.5, and 2000 are given. The first parameter
is fixed at a value of 5.7, and the last parameter is
constrained to be above 50.
INPUTS:
MYFUNCT - a string variable containing the name of an IDL
function. This function computes the "model" Z values
given the X,Y values and model parameters, as described above.
X - Array of "X" independent variable values, as described above.
These values are passed directly to the fitting function
unmodified.
Y - Array of "Y" independent variable values, as described
above. X and Y should have the same data type.
Z - Array of "measured" dependent variable values. Z should have
the same data type as X and Y. The function MYFUNCT should
map (X,Y)->Z.
ERR - Array of "measured" 1-sigma uncertainties. ERR should have
the same data type as Z. ERR is ignored if the WEIGHTS
keyword is specified.
START_PARAMS - An array of starting values for each of the
parameters of the model. The number of parameters
should be fewer than the number of measurements.
Also, the parameters should have the same data type
as the measurements (double is preferred).
This parameter is optional if the PARINFO keyword
is used (see MPFIT). The PARINFO keyword provides
a mechanism to fix or constrain individual
parameters. If both START_PARAMS and PARINFO are
passed, then the starting *value* is taken from
START_PARAMS, but the *constraints* are taken from
PARINFO.
RETURNS:
Returns the array of best-fit parameters.
KEYWORD PARAMETERS:
BESTNORM - the value of the summed, squared, weighted residuals
for the returned parameter values, i.e. the chi-square value.
COVAR - the covariance matrix for the set of parameters returned
by MPFIT. The matrix is NxN where N is the number of
parameters. The square root of the diagonal elements
gives the formal 1-sigma statistical errors on the
parameters IF errors were treated "properly" in MYFUNC.
Parameter errors are also returned in PERROR.
To compute the correlation matrix, PCOR, use this:
IDL> PCOR = COV * 0
IDL> FOR i = 0, n-1 DO FOR j = 0, n-1 DO $
PCOR(i,j) = COV(i,j)/sqrt(COV(i,i)*COV(j,j))
If NOCOVAR is set or MPFIT terminated abnormally, then
COVAR is set to a scalar with value !VALUES.D_NAN.
DOF - number of degrees of freedom, computed as
DOF = N_ELEMENTS(DEVIATES) - NFREE
Note that this doesn't account for pegged parameters (see
NPEGGED).
ERRMSG - a string error or warning message is returned.
FTOL - a nonnegative input variable. Termination occurs when both
the actual and predicted relative reductions in the sum of
squares are at most FTOL (and STATUS is accordingly set to
1 or 3). Therefore, FTOL measures the relative error
desired in the sum of squares. Default: 1D-10
FUNCTARGS - A structure which contains the parameters to be passed
to the user-supplied function specified by MYFUNCT via
the _EXTRA mechanism. This is the way you can pass
additional data to your user-supplied function without
using common blocks.
By default, no extra parameters are passed to the
user-supplied function.
GTOL - a nonnegative input variable. Termination occurs when the
cosine of the angle between fvec and any column of the
jacobian is at most GTOL in absolute value (and STATUS is
accordingly set to 4). Therefore, GTOL measures the
orthogonality desired between the function vector and the
columns of the jacobian. Default: 1D-10
ITERARGS - The keyword arguments to be passed to ITERPROC via the
_EXTRA mechanism. This should be a structure, and is
similar in operation to FUNCTARGS.
Default: no arguments are passed.
ITERPROC - The name of a procedure to be called upon each NPRINT
iteration of the MPFIT routine. It should be declared
in the following way:
PRO ITERPROC, MYFUNCT, p, iter, fnorm, FUNCTARGS=fcnargs, $
PARINFO=parinfo, QUIET=quiet, ...
; perform custom iteration update
END
ITERPROC must either accept all three keyword
parameters (FUNCTARGS, PARINFO and QUIET), or at least
accept them via the _EXTRA keyword.
MYFUNCT is the user-supplied function to be minimized,
P is the current set of model parameters, ITER is the
iteration number, and FUNCTARGS are the arguments to be
passed to MYFUNCT. FNORM should be the
chi-squared value. QUIET is set when no textual output
should be printed. See below for documentation of
PARINFO.
In implementation, ITERPROC can perform updates to the
terminal or graphical user interface, to provide
feedback while the fit proceeds. If the fit is to be
stopped for any reason, then ITERPROC should set the
common block variable ERROR_CODE to negative value (see
MPFIT_ERROR common block below). In principle,
ITERPROC should probably not modify the parameter
values, because it may interfere with the algorithm's
stability. In practice it is allowed.
Default: an internal routine is used to print the
parameter values.
MAXITER - The maximum number of iterations to perform. If the
number is exceeded, then the STATUS value is set to 5
and MPFIT returns.
Default: 200 iterations
NFEV - the number of MYFUNCT function evaluations performed.
NITER - the number of iterations completed.
NOCOVAR - set this keyword to prevent the calculation of the
covariance matrix before returning (see COVAR)
NPRINT - The frequency with which ITERPROC is called. A value of
1 indicates that ITERPROC is called with every iteration,
while 2 indicates every other iteration, etc. Note that
several Levenberg-Marquardt attempts can be made in a
single iteration.
Default value: 1
PARINFO - Provides a mechanism for more sophisticated constraints
to be placed on parameter values. When PARINFO is not
passed, then it is assumed that all parameters are free
and unconstrained. Values in PARINFO are never
modified during a call to MPFIT.
See description above for the structure of PARINFO.
Default value: all parameters are free and unconstrained.
PERROR - The formal 1-sigma errors in each parameter, computed
from the covariance matrix. If a parameter is held
fixed, or if it touches a boundary, then the error is
reported as zero.
If the fit is unweighted (i.e. no errors were given, or
the weights were uniformly set to unity), then PERROR
will probably not represent the true parameter
uncertainties. *If* you can assume that the true reduced
chi-squared value is unity -- meaning that the fit is
implicitly assumed to be of good quality -- then the
estimated parameter uncertainties can be computed by
scaling PERROR by the measured chi-squared value.
DOF = N_ELEMENTS(Z) - N_ELEMENTS(PARMS) ; deg of freedom
PCERROR = PERROR * SQRT(BESTNORM / DOF) ; scaled uncertainties
QUIET - set this keyword when no textual output should be printed
by MPFIT
STATUS - an integer status code is returned. All values other
than zero can represent success. It can have one of the
following values:
0 improper input parameters.
1 both actual and predicted relative reductions
in the sum of squares are at most FTOL.
2 relative error between two consecutive iterates
is at most XTOL
3 conditions for STATUS = 1 and STATUS = 2 both hold.
4 the cosine of the angle between fvec and any
column of the jacobian is at most GTOL in
absolute value.
5 the maximum number of iterations has been reached
6 FTOL is too small. no further reduction in
the sum of squares is possible.
7 XTOL is too small. no further improvement in
the approximate solution x is possible.
8 GTOL is too small. fvec is orthogonal to the
columns of the jacobian to machine precision.
WEIGHTS - Array of weights to be used in calculating the
chi-squared value. If WEIGHTS is specified then the ERR
parameter is ignored. The chi-squared value is computed
as follows:
CHISQ = TOTAL( (Z-MYFUNCT(X,Y,P))^2 * ABS(WEIGHTS) )
Here are common values of WEIGHTS:
1D/ERR^2 - Normal weighting (ERR is the measurement error)
1D/Z - Poisson weighting (counting statistics)
1D - Unweighted
XTOL - a nonnegative input variable. Termination occurs when the
relative error between two consecutive iterates is at most
XTOL (and STATUS is accordingly set to 2 or 3). Therefore,
XTOL measures the relative error desired in the approximate
solution. Default: 1D-10
YFIT - the best-fit model function, as returned by MYFUNCT.
EXAMPLE:
p = [2.2D, -0.7D, 1.4D, 3000.D]
x = (dindgen(200)*0.1 - 10.) # (dblarr(200) + 1)
y = (dblarr(200) + 1) # (dindgen(200)*0.1 - 10.)
zi = gauss2(x, y, p)
sz = sqrt(zi>1)
z = zi + randomn(seed, 200, 200) * sz
p0 = [0D, 0D, 1D, 10D]
p = mpfit2dfun('GAUSS2', x, y, z, sz, p0)
Generates a synthetic data set with a Gaussian peak, and Poisson
statistical uncertainty. Then the same function (but different
starting parameters) is fitted to the data to see how close we can
get.
It is especially worthy to notice that the X and Y values are
created as full images, so that a coordinate is attached to each
pixel independently. This is the format that GAUSS2 accepts, and
the easiest for you to use in your own functions.
COMMON BLOCKS:
COMMON MPF