IDL Help for IDLSPEC2D

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:36:32 2006.


List of Routines


Routine Descriptions

APOALL

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

 PURPOSE:
   Run APOREDUCE on one or many nights of data.

 CALLING SEQUENCE:
   apoall, [ mjd=, mjstart=, mjend=, minexp=, copydir= ]

 INPUTS:

 OPTIONAL INPUTS:
   mjd        - Look for raw data files in RAWDIR/MJD; default to '*' to
                search all subdirectories.  Note that this need not be
                integer-valued, but could be for example '51441_test'.
   mjstart    - Starting MJD.
   mjend      - Ending MJD.
   minexp     - Minimum exposure time for science frames; default to 0 sec.
   copydir    - Copy the output log files to this directory; default to none.

 OUTPUT:

 COMMENTS:
   The files are sorted before being sent to APOREDUCE.  For each plate,
   reduce all the biases/darks, then all the flats, then all the arcs,
   and finally all of the science/smear frames.

   Look for the raw sdR files in $RAWDATA_DIR/$MJD, the plPlugMapM files
   in $ASTROLOG_DIR/$MJD, and put the outputs in $SPECTROLOG_DIR/$MJD.
   If that last environment variable is not set, then put the outputs
   in the same directory as the sdR files.

 EXAMPLES:
   Rerun the SOS code on the spectro data from MJD 53682, putting
   the results in the current directory:
     IDL> setenv, 'RAWDATA_DIR=.'
     IDL> apoall, mjd=53682

 BUGS:

 PROCEDURES CALLED:
   aporeduce
   djs_filepath()
   get_mjd_dir()
   sdsshead()
   sxpar()

 REVISION HISTORY:
   27-May-2000  Written by David Schlegel, Princeton.

(See pro/apo2d/apoall.pro)


APOFIX

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

 PURPOSE:
   Add line to sdHdrFix file to denote change in FITS header for sdR files.

 CALLING SEQUENCE:
   apofix, expnum, [ card, value, camera=, /bad, /test, /not_sos ]

 INPUTS:
   expnum     - Exposure number

 OPTIONAL INPUTS:
   card       - FITS header keyword to change; this is case-insensitive,
                so that 'exptime' is the same as 'EXPTIME'.
   value      - New value for FITS header keyword.
   camera     - Camera name in which to change values, e.g. 'b1', 'r1',
                'b2' or 'r2'.  A '?' can be used as a wildcard, for example
                '?2' to denote a change to both 'b2' and 'r2'.  Default to
                '??' to denote a change to sdR files for all 4 cameras.
   bad        - If set, then declare the specified exposure number to be bad.
                This is equivalent to setting QUALITY='bad'.
   test       - If set, then declare the specified exposure number to be test.
                This is equivalent to setting QUALITY='test'.
   not_sos    - This keyword can be set to run this proc on a machine
                that is not named "sos".  This would only be done for
                testing purposes, or if Son-of-Spectro has been moved
                to another machine.

 OUTPUT:

 OPTIONAL OUTPUTS:

 COMMENTS:
   Only the following keywords can be modified with this procedure:
     CAMERAS, FLAVOR, PLATEID, NAME, EXPTIME, TAI-BEG, TAI-END, TAI,
     FFS, FF, NE, HGCD, OBSCOMM, QUALITY
   The AIRMASS is not read from the header, but computed from RADEG,DECDEG
   and the TAI-BEG,TAI-END keywords.
   Refer to the Son-of-Spectro documentation for the specifics of
   valid values for each keyword.

   Note that string values must be enclosed in single- or double-quotes.
   Numeric values should not be in quotes.  Double-precision numbers should
   be written with "d" notation, for example 3.14d7 instead of 3.14e7.

 EXAMPLES:
   Fix the exposure time for exposure #1234 to be 900 sec:
     IDL> apofix, 1234, 'exptime', 900

   Fix the TAI time for exposure #1234 to be 4.443852968d+09
   (use the "d" notation for double-precision, even though it
   will appear in the sdHdrFix file with an "e"):
     IDL> apofix, 1234, 'TAI', 4.443852968d+09

   Declare exposure #1234 as bad:
     IDL> apofix, 1234, /bad
   or equivalently:
     IDL> apofix, 1234, 'quality', 'bad'

   Only declare the 'b1' camera bad for exposure number 1234:
     IDL> apofix, 1234, /bad, camera='b1'

   The wrong NAME is in the header, which is necessary to identify
   the proper plug-map file.  If the correct plug-map file
   is plPlugMapM-0328-52277-01, then edit as follows:
     IDL> apofix, 1234, 'name', '0328-52277-01'

 BUGS:

 PROCEDURES CALLED:
   djs_lockfile()
   djs_modfits
   djs_unlockfile
   fileandpath()
   fits_wait
   headfits()
   struct_append
   sxpar()
   yanny_read

 REVISION HISTORY:
   22-Apr-2002  Written by D. Schlegel, Princeton

(See pro/apo2d/apofix.pro)


APOFLUXCALIB

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

 PURPOSE:
   Generate the flux-calibration vectors for use by APOPLOT.

 CALLING SEQUENCE:
   apofluxcalib, [ platenum, mjd= ]

 INPUTS:
   platenum - Plate number for obtaining the fluxing vectors; default to 406
   mjd      - Modified Julian Date for above plate; default to plate 406
              on MJD 51817 if neither is specified

 OPTIONAL INPUTS:

 OUTPUTS:

 OPTIONAL OUTPUTS:

 COMMENTS:
   The output files spFluxcalib-$CAMERA.fits should be moved to
   the directory $IDLSPEC2D_DIR/examples for use by APOPLOT.

   For reference (excerpted from PR #6766):
     Here is the list of 10 main-survey plates with the
     highest S/N per minute in all cameras (where I've looked
     up to plate 650 in the Spectro-2D v5 beta reductions):
              398       51789
              402       51793
              406       51817
              406       51900
              411       51817
              416       51811
              418       51817
              431       51877
              436       51883
              439       51877

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   bspline_iterfit()
   bspline_valu()
   headfits()
   mrdfits()
   mwrfits
   readspec
   traceset2xy

 REVISION HISTORY:
   04-Dec-2001  Written by D. Schlegel, Princeton

(See pro/apo2d/apofluxcalib.pro)


APOHEADER

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

 PURPOSE:
   Print the subset of interesting header keywords from the raw sdR files.

 CALLING SEQUENCE:
   apoheader, expnum, [ mjd= ]

 INPUTS:
   expnum     - Exposure number

 OPTIONAL INPUTS:
   mjd        - Optionally specify the MJD for the subdirectory in which
                to search for the file.  This will greatly speed things up.

 OUTPUT:

 OPTIONAL OUTPUTS:

 COMMENTS:

 EXAMPLES:
   Print out all FITS header keywords of interest for exposure # 14728
   (assuming that exposure is still on disk somewhere under $RAWDATA_DIR):
     IDL> apoheader, 14728

 BUGS:

 PROCEDURES CALLED:
   fileandpath()
   fits_wait
   sdsshead()
   sxpar()

 REVISION HISTORY:
   24-Apr-2002  Written by D. Schlegel, Princeton

(See pro/apo2d/apoheader.pro)


APOPLOT

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

 PURPOSE:
   Routine for plotting spectra from the Son-of-Spectro outputs at APO.

 CALLING SEQUENCE:
   apoplot, plate, [ fiberid, mjd=, expnum=, nsmooth=, nmed=, psfile=, $
    /magsort, /netimage, _EXTRA= ]

 INPUTS:
   plate      - Plate number

 OPTIONAL INPUTS:
   fiberid    - Fiber number(s); if not set, then plot all fibers for plate.
   mjd        - MJD number; if not set, then select the most recent MJD
                in the $SPECTROLOG_DIR directory.
   expnum     - If set, then plot only these exposure numbers for this plate
                rather than all exposure numbers for this plate.
   nsmooth    - If set, then boxcar smooth the object spectra with a
                width equal to NSMOOTH.
   nmed       - If set, then median filter the object spectra with a
                width equal to NMED.
   psfile     - If set, then send plot to a PostScript file instead of
                to the SPLOT interactive widget.  The PostScript file name
                can be set explicitly, e.g. with PSFILE='test.ps'.  Or if
                you simply set this as a flag, e.g. with /PSFILE, then the
                default file name is spec-pppp-mmmmm-fff.ps,
                where pppp=plate number, mmmmm=MJD, fff=fiber ID.
   magsort    - If set and FIBERID is not, then plot all fibers from
                the brightest object to the faintest.
   netimage   - If set, then launch a Netscape browser with the object
                image from Steve Kent's web site.  This only works if
                Netscape is running and has permissions at the site
                "http://sdssmosaic.fnal.gov:8015".
                This is disabled if PSFILE is set.
   _EXTRA     - Kewords for SPLOT, such as XRANGE, YRANGE, THICK.

 OUTPUTS:

 OPTIONAL OUTPUTS:

 COMMENTS:
   The Son-of-Spectro outputs are first read from the file:
     $SPECTROLOG_DIR/$MJD/logsheet-$MJD.fits
   This then points to the other files that are read:
     $SPECTROLOG_DIR/$MJD/fflat-$MJD-$PLATE-$EXPNUM-$CAMERA.fits
     $SPECTROLOG_DIR/$MJD/wset-$MJD-$PLATE-$EXPNUM-$CAMERA.fits
     $SPECTROLOG_DIR/$MJD/sci-$PLATE-$CAMERA-$EXPNUM.fits

   If $SPECTROLOG_DIR is not set, then it is assumed to be
     /data/spectro/spectrologs

   The plotting range is set by the 5th and 95th percentiles of the data.
   Note that there are a horrendous amount of cosmic rays in the data
   as extracted by Son-of-Spectro.

   The flux-calibration is very rudimentary, always using the same
   four curves for the four cameras.

 EXAMPLES:
   Plot the spectrum of plate 401, fiber #100 using the SPLOT plotting tool:
     IDL> apoplot, 401, 100
   The spectra from the first exposure (blue and red) are shown as white.
   Other exposures are shown in other colors, and are labelled as such.
   The mouse buttons will zoom in (left), recenter (center), or zoom out
   (right).  The frame can be saved as a PostScript file by selecting
   File->WriteEPS from the left-hand corner. 

   Make the same plot, but boxcar-smooth the spectrum and limit the
   wavelength range to [4000,5000] Angstroms:
     IDL> apoplot, 401, 100, nsmooth=10, xrange=[5000,6000]

   Some plates are observed on multiple nights. To select one of the two
   observations of plate 306: 
     IDL> apoplot, 306, 20, mjd=51690
   This will only work if you have the Son-of-Spectro outputs for that
   date on your disk.

   Loop through all the spectra for plate 401, interactively:
     IDL> apoplot, 401

   Plot all the spectra from plate 401 to a single PostScript file:
     IDL> apoplot, 401, /psfile

 BUGS:

 DATA FILES:
   $IDLSPEC2D_DIR/examples/spFluxcalib-$CAMERA.fits

 PROCEDURES CALLED:
   djs_maskinterp()
   djs_median()
   djs_oplot
   djs_plot
   fcalib_default()
   get_mjd_dir()
   soplot
   splot
   sdss_flagname()
   sxyouts

 INTERNAL SUPPORT ROUTINES:
   apoplot1

 REVISION HISTORY:
   04-Dec-2001  Written by D. Schlegel, Princeton

(See pro/apo2d/apoplot.pro)


APOPLOTARC

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

 PURPOSE:
   Routine for plotting arc spectra from the Son-of-Spectro outputs at APO.

 CALLING SEQUENCE:
   apoplotarc, expnum, [ camname=, mjd=, everyn=, psfile=, _EXTRA= ]

 INPUTS:
   expnum     - Exposure number

 OPTIONAL INPUTS:
   camname    - Camera name; default to 'r1'
   mjd        - MJD; must be set if this exposure is not in the most
                recent MJD directory
   everyn     - Plot every EVERYN-th spectrum; default to 40, which will
                plot fiber numbers 1, 41, 81, ...281.
   psfile     - If set, then send plot to a PostScript file instead of
                to the SPLOT interactive widget.  The PostScript file name
                can be set explicitly, e.g. with PSFILE='test.ps'.  Or if
                you simply set this as a flag, e.g. with /PSFILE, then the
                default file name is arc-pppp-cc-eeeeeeee.ps,
                where pppp=plate number, cc=camname, eeeeeeee=exposure number.
   _EXTRA     - Kewords for SPLOT, such as XRANGE, YRANGE, THICK.

 OUTPUTS:

 OPTIONAL OUTPUTS:

 COMMENTS:
   The arc spectrum is plotted as a red line.  The individual
   arc values at each pixel in the arc fibers are plotted as points.

   The Son-of-Spectro outputs are first read from the file:
     $SPECTROLOG_DIR/$MJD/logsheet-$MJD.fits
   This then points to the other files that are read:
     $SPECTROLOG_DIR/$MJD/fflat-$MJD-$PLATE-$EXPNUM-$CAMERA.fits
     $SPECTROLOG_DIR/$MJD/wset-$MJD-$PLATE-$EXPNUM-$CAMERA.fits
     $SPECTROLOG_DIR/$MJD/sci-$PLATE-$CAMERA-$EXPNUM.fits

   If $SPECTROLOG_DIR is not set, then it is assumed to be
     /data/spectro/spectrologs

 EXAMPLES:
   Plot the arc spectrum for exposure number 9437 taken in the most
   recent night's data in the r1-camera, using the SPLOT plotting tool:
     IDL> apoplotarc, 9437
   The mouse buttons will zoom in (left), recenter (center), or zoom out
   (right).  The frame can be saved as a PostScript file by selecting
   File->WriteEPS from the left-hand corner. 

   Make the same plot, but change the Y limits and write a PostScript file:
     IDL> apoplotarc, 9437, yrange=[0,1000], /psfile

 BUGS:

 PROCEDURES CALLED:
   djs_oplot
   djs_plot
   get_mjd_dir()
   soplot
   splot

 REVISION HISTORY:
   20-Nov-2002  Written by D. Schlegel, Princeton

(See pro/apo2d/apoplotarc.pro)


APOPLOTGEOM

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

 PURPOSE:
   Routine for plotting arc geometry from the Son-of-Spectro outputs at APO.

 CALLING SEQUENCE:
   apoplotgeom, plate, [ camname=, mjd=, psfile=, _EXTRA= ]

 INPUTS:
   plate      - Plate number

 OPTIONAL INPUTS:
   camname    - Camera name; default to 'r1'
   mjd        - MJD; must be set if this exposure is not in the most
                recent MJD directory
   psfile     - If set, then send plot to a PostScript file instead of
                to the SPLOT interactive widget.  The PostScript file name
                can be set explicitly, e.g. with PSFILE='test.ps'.  Or if
                you simply set this as a flag, e.g. with /PSFILE, then the
                default file name is arc-pppp-cc-eeeeeeee.ps,
                where pppp=plate number, cc=camname, eeeeeeee=exposure number.
   _EXTRA     - Kewords for SPLOT, such as XRANGE, YRANGE, THICK.

 OUTPUTS:

 OPTIONAL OUTPUTS:

 COMMENTS:
   The arc spectrum is plotted as a red line.  The individual
   arc values at each pixel in the arc fibers are plotted as points.

   The Son-of-Spectro outputs are first read from the file:
     $SPECTROLOG_DIR/$MJD/logsheet-$MJD.fits
   This then points to the other files that are read:
     $SPECTROLOG_DIR/$MJD/fflat-$MJD-$PLATE-$EXPNUM-$CAMERA.fits
     $SPECTROLOG_DIR/$MJD/wset-$MJD-$PLATE-$EXPNUM-$CAMERA.fits
     $SPECTROLOG_DIR/$MJD/sci-$PLATE-$CAMERA-$EXPNUM.fits

   If $SPECTROLOG_DIR is not set, then it is assumed to be
     /data/spectro/spectrologs

 EXAMPLES:
   Plot the arc spectrum for exposure number 9425 taken in the most
   recent night's data in the r1-camera, using the SPLOT plotting tool:
     IDL> apoplotgeom, 9425
   The mouse buttons will zoom in (left), recenter (center), or zoom out
   (right).  The frame can be saved as a PostScript file by selecting
   File->WriteEPS from the left-hand corner. 

   Make the same plot, but change the Y limits and write a PostScript file:
     IDL> apoplotgeom, 9425, yrange=[0,1000], /psfile

 BUGS:

 PROCEDURES CALLED:
   djs_oplot
   djs_plot
   get_mjd_dir()
   soplot
   splot

 REVISION HISTORY:
   20-Nov-2002  Written by D. Schlegel, Princeton

(See pro/apo2d/apoplotgeom.pro)


APOPLOTSKY

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

 PURPOSE:
   Routine for plotting sky spectra from the Son-of-Spectro outputs at APO.

 CALLING SEQUENCE:
   apoplotsky, expnum, [ camname=, mjd=, psfile=, _EXTRA= ]

 INPUTS:
   expnum     - Exposure number

 OPTIONAL INPUTS:
   camname    - Camera name; default to 'r1'
   mjd        - MJD; must be set if this exposure is not in the most
                recent MJD directory
   psfile     - If set, then send plot to a PostScript file instead of
                to the SPLOT interactive widget.  The PostScript file name
                can be set explicitly, e.g. with PSFILE='test.ps'.  Or if
                you simply set this as a flag, e.g. with /PSFILE, then the
                default file name is sky-pppp-cc-eeeeeeee.ps,
                where pppp=plate number, cc=camname, eeeeeeee=exposure number.
   _EXTRA     - Kewords for SPLOT, such as XRANGE, YRANGE, THICK.

 OUTPUTS:

 OPTIONAL OUTPUTS:

 COMMENTS:
   The supersky spectrum is plotted as a red line.  The individual
   sky values at each pixel in the sky fibers are plotted as points.

   The Son-of-Spectro outputs are first read from the file:
     $SPECTROLOG_DIR/$MJD/logsheet-$MJD.fits
   This then points to the other files that are read:
     $SPECTROLOG_DIR/$MJD/fflat-$MJD-$PLATE-$EXPNUM-$CAMERA.fits
     $SPECTROLOG_DIR/$MJD/wset-$MJD-$PLATE-$EXPNUM-$CAMERA.fits
     $SPECTROLOG_DIR/$MJD/sci-$PLATE-$CAMERA-$EXPNUM.fits

   If $SPECTROLOG_DIR is not set, then it is assumed to be
     /data/spectro/spectrologs

 EXAMPLES:
   Plot the sky spectrum for exposure number 9425 taken in the most
   recent night's data in the r1-camera, using the SPLOT plotting tool:
     IDL> apoplotsky, 9425
   The mouse buttons will zoom in (left), recenter (center), or zoom out
   (right).  The frame can be saved as a PostScript file by selecting
   File->WriteEPS from the left-hand corner. 

   Make the same plot, but change the Y limits and write a PostScript file:
     IDL> apoplotsky, 9425, yrange=[0,1000], /psfile

 BUGS:

 PROCEDURES CALLED:
   djs_oplot
   djs_plot
   get_mjd_dir()
   soplot
   splot

 REVISION HISTORY:
   20-Nov-2002  Written by D. Schlegel, Princeton

(See pro/apo2d/apoplotsky.pro)


APOREDUCE

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

 PURPOSE:
   Quick on-the-mountain reduction pipeline for 1 file at a time.

 CALLING SEQUENCE:
   aporeduce, filename, [ indir=, outdir=, $
    plugfile=, plugdir=, minexp=, $
    copydir=, /no_diskcheck ]

 INPUTS:
   filename   - Raw spectroscopic image file name(s) of any flavor; this
                can be an array of file names, but cannot include wildcards

 OPTIONAL INPUTS:
   indir      - Input directory for FILENAME; default to './'
   outdir     - Output directory for reduced data and log files;
                default to INDIR
   plugfile   - Name of plugmap file (Yanny parameter file); default to
                'plPlugMapM-'+NAME+'.par', where NAME is taken from that
                keyword in the file FILENAME
   plugdir    - Input directory for PLUGFILE; default to INDIR
   minexp     - Minimum exposure time for science frames; default to 0 sec
                so that any frame with a non-negative exposure time is
                reduced.
   copydir    - If set, then copy the output log files to this directory using
                "scp" copy (not "scp1" any longer).  Make an additional copy
                of the HTML file called 'logsheet-current.html'.
   no_diskcheck- If set, then do not do the check for filling input or
                output disks.  (This option is always set by the APOALL proc).

 OUTPUT:

 OPTIONAL OUTPUTS:

 COMMENTS:
   After reducing any 'r2' frame, we re-generate the HTML file and optionally
   copy it to the file specified by COPYDIR.

   The copy of the file "logsheet-current.html" also has a line of Java-script
   added that does an auto-refresh every 60 seconds.

 EXAMPLES:

 BUGS:
   scp1 does not exist on sos.apo.nmsu.edu, reverted to scp

 INTERNAL SUPPORT ROUTINES:
   apo_diskcheck

 PROCEDURES CALLED:
   apo_appendlog
   apo_log2html
   apo_plotsn
   djs_filepath()
   fits_wait()
   get_tai
   idlspec2d_version()
   idlutils_version()
   quickextract()
   quicktrace()
   quickwave()
   splog
   tai2airmass()

 REVISION HISTORY:
   30-Apr-2000  Written by D. Schlegel & S. Burles, APO

(See pro/apo2d/aporeduce.pro)


APO_APPENDLOG

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

 PURPOSE:
   Append to logfile as written by APOREDUCE.

 CALLING SEQUENCE:
   apo_appendlog, logfile, rstruct, tstruct

 INPUTS:
   logfile    - FITS logfile as written by APOREDUCE.
   rstruct    - Structure to append to the log file with reduced data info
   tstruct    - Structure to append to the log file with WARNING/ABORT strings

 OPTIONAL INPUTS:

 OUTPUT:

 OPTIONAL OUTPUTS:

 COMMENTS:

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   djs_lockfile()
   djs_modfits
   djs_unlockfile
   headfits()
   idlutils_version()
   idlspec2d_version()
   modfits
   mrdfits()
   mwrfits
   splog
   sxaddpar
   struct_append()

 REVISION HISTORY:
   02-Dec-2000  Written by D. Schlegel, Princeton

(See pro/apo2d/apo_appendlog.pro)


APO_CHECKLIMITS()

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   apo_checklimits()

 PURPOSE:
   Convert output FITS file from APOREDUCE to HTML format.

 CALLING SEQUENCE:
   markstring = apo_checklimits(flavor, field, camera, value, [ /html ] )

 INPUTS:
   flavor     - FLAVOR to match in the opLimits file.
   field      - FIELD to match in the opLimits file.
   camera     - CAMERA to match in the opLimits file.
   value      - Value to test in the opLimits file.  If this is a
                string value, then one matches to STRVAL in that file.
                Otherwise, test for values within [LOVALUE,HIVALUE].

 OPTIONAL INPUTS:
   html       - If set, then convert the color name in MARKSTRING into
                an HTML string.  For example, a return value of 'red'
                becomes '<B><FONT COLOR="#FF0000">'.

 OUTPUT:
   markstring - Return the COLOR from the opLimits file.

 OPTIONAL OUTPUTS:

 COMMENTS:

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:

 DATA FILES:
   $IDLSPEC2D_DIR/examples/opLimits.par

 REVISION HISTORY:
   30-Apr-2000  Written by D. Schlegel, APO

(See pro/apo2d/apo_checklimits.pro)


APO_LOG2HTML

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

 PURPOSE:
   Convert output FITS file from APOREDUCE to HTML format.

 CALLING SEQUENCE:
   apo_log2html, logfile, [ htmlfile ]

 INPUTS:
   logfile    - Input log file as a FITS binary file with an extension
                for each frame reduced; this file is written by APOREDUCE.

 OPTIONAL INPUTS:
   htmlfile   - Output log file in HTML format; default to the same name
                as LOGFILE, replacing the '.fits' extension with '.html'

 OUTPUT:

 OPTIONAL OUTPUTS:

 COMMENTS:

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   apo_checklimits()
   copy_struct_inx
   djs_filepath()
   djs_findfile()
   djs_lockfile()
   djs_unlockfile
   fileandpath()
   headfits()
   mrdfits
   repstr()
   sxpar()

 INTERNAL SUPPORT ROUTINES:
   apo_color2hex()
   apo_log_header()
   apo_log_endfile()
   apo_log_tableline()
   apo_log_beginplate()
   apo_log_endplate()
   apo_log_fields()

 REVISION HISTORY:
   30-Apr-2000  Written by D. Schlegel, APO

(See pro/apo2d/apo_log2html.pro)


APO_PLOTBIAS

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

 PURPOSE:
   Plot the histogram of bias values for all 4 cameras of a single exposure

 CALLING SEQUENCE:
   apo_plotbias, expnum, [ plotfile= ]

 INPUTS:
   expnum     - Exposure number

 OPTIONAL INPUTS:
   plotfile   - Plot file; if set, then send plot to this PostScript file
                rather than to the default (X) display.

 OUTPUT:

 OPTIONAL OUTPUTS:

 COMMENTS:
   The histogram of bias values is plotted for all (4) camera files that
   match the given exposure number.

   A fiducial line is drawn as a thick blue line.  This line approximates
   what we expect to see for each camera.

   If $RAWDATA_DIR is not set, then it is assumed to be
     /data/spectro

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   dfpsclose
   dfpsplot
   djs_filepath()
   djs_icolor()
   djs_xyouts
   fileandpath()
   headfits()
   plothist
   quickbias
   sdssproc
   struct_append()
   sxpar()

 REVISION HISTORY:
   06-Dec-2000  Written by D. Schlegel, Princeton

(See pro/apo2d/apo_plotbias.pro)


APO_PLOTSN

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

 PURPOSE:
   Generate S/N plot for one plate from a FITS logfile written by APOREDUCE.

 CALLING SEQUENCE:
   apo_plotsn, logfile, plate, [ plugdir=, plotfile= ]

 INPUTS:
   logfile    - Logfile as written by APOREDUCE.  This is a FITS file
                with an HDU of information for each reduced frame.
   plate      - Plate number to plot.

 OPTIONAL KEYWORDS:
   plugdir    - Input directory for PLUGFILE; default to '.'
                The name of the plugmap file is taken from the first
                structure in the LOGFILE.
   plotfile   - Name of plot file; if not specified then send plot to
                current device.

 OUTPUT:

 OPTIONAL OUTPUTS:

 COMMENTS:

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   apo_checklimits()
   djs_lockfile()
   djs_unlockfile
   mrdfits
   plotsn
   sortplugmap()
   splog
   readplugmap()

 REVISION HISTORY:
   02-May-2000  Written by D. Schlegel, APO

(See pro/apo2d/apo_plotsn.pro)


ARCFIT_GUESS

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

 PURPOSE:
   Determine initial wavelength solution by comparing spectrum to arc spectrum

 CALLING SEQUENCE:
   wset = arcfit_guess( spec, loglam, intensity, color=color, $
    [ func=func, bestcorr=bestcorr, acoeff=, dcoeff=, nsteps= ] )

 INPUTS:
   spec       - 1-D spectrum
   loglam     - Log-lambda of arc lines
   intensity  - Intensity of arc lines

 REQUIRED KEYWORDS:
   color      - 'red' or 'blue'

 OPTIONAL KEYWORDS:
   func       - Name of fitting function; default to 'legendre'
   acoeff     - central values of coefficents to explore
   dcoeff     - range (-.5*dcoeff to .5*dcoeff) of values to explore
   nsteps     - array of steps to use

 OUTPUTS:
   wset       - traceset (pix -> lambda)

 OPTIONAL OUTPUTS:
   bestcorr   - Correlation coefficient with simulated arc spectrum

 COMMENTS:

 EXAMPLES:

 BUGS:

 INTERNAL SUPPORT PROCEDURES:
   tset_struc()
   arcfit_iter()

 PROCEDURES CALLED:
   traceset2xy()
   xy2traceset

 REVISION HISTORY:
   18-Nov-1999  Written by D. Schlegel, Princeton.
                Excised code from FITARCIMAGE.
   01-Dec-2000  added acoeff, dcoeff, nsteps keywords

(See pro/spec2d/arcfit_guess.pro)


ATMDISP_COR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   atmdisp_cor
 
 PURPOSE:
   Atmospheric dispersion causes wavelength dependent lightloss from 
   fiber spectra.  The mean atmospheric dispersion experienced by the 
   standard stars on each plate is automatically corrected for as part of
   the flux calibration.  However, any shift in the centering of the 
   spectroscopic targets in the fibers across the plate will result in 
   differences in atmospheric dispersion as a function of plate position.
   These centering errors -- caused by small errors in the plate scale or
   rotation -- can produce flux calibration errors of up to 20%.  This
   procedure is designed to correct for these.

   Synthetic magnitudes are computed from the spectra on 1 half-plate and
   compared to the photo fiber magnitudes.  The residuals are fit as a 
   function of plate x/y position with a 3rd order polynomial. The (g-r) 
   offsets of this fit are then mapped into an atmospheric dispersion 
   correction.  This mapping makes use of models of the atmospheric dispersion
   of point sources observed with 2" seeing through 3" fibers at a variety
   of airmasses.  The absolute light loss is mapped using the r-band mag
   residuals.  A vector of wavelength dependent corrections is returned.

 CALLING SEQUENCE:

   atm_model = atmdisp_cor(loglam, flux, plugtag, hdr, title = title, $
                           surfgr_sig = surfgr_sig)

 INPUTS:
   loglam  - wavelength array of input spectra in log10(Angstroms) [npix]
   flux    - flux array from 1 half plate [npix, nfiber] (nfiber~320)
   plugtag - plugmap [nfiber] -- used for mags, plate x/y, sky & standard ID
   hdr     - image header -- used for aquiring airmass info (maybe also
             seeing and guiding in the future)

 OUTPUT:
   A model of the atmospheric dispersion correction for each fiber is
   returned [npix, nfiber].  (To correct: flux_cor = flux / atm_model)
   Plots are generated showing the (g-r) and r mag offsets as a function 
   of plate x/y before and after the correction.  Histograms are produced
   as well.
 
 KEYWORDS:
   title     -  title of output plots (usually plate/mjd/specid)
   surfgr_sig - sigma of 2d fit to the (g-r) offsets -- this is a good
                indicator of how big the correction is.

 COMMENTS:
   This function requires an external source of info about the effects
   of atmospheric dispersion as a function of wavelength.  This info is
   stored in structures in IDLSPEC2D_DIR/etc/.  They are named 
   'atmdisp_vec_am' + airmass + 'see2.0.fit' where airmass is a value from
   1.1 - 1.5.

 BUGS:
   Galaxies and stars respond differently to atmospheric dispersion beause
   of thier different spatial extent.  The mean correction which is 
   derived here is really that appropriate for the average galaxy -- 
   so corrections for point sources are likely to be underestimated a bit.
   To do this right the spatial profile of each object should be taken into
   account.

 EXAMPLES:

 PROCEDURES CALLED:
   djs_icolor()
   djs_iterstat()
   djs_oplot
   djs_sfit_iter()
   filter_thru()
   gaussfit()
   legend
   linterp
   mrdfits
   plothist
   traceset2xy
   
 INTERNAL SUPPORT ROUTINES:
   sphoto_xy

 REVISION HISTORY:
   Created 12-Aug-2003 by C. Tremonti, Steward Observatory

(See pro/fluxfix/atmdisp_cor.pro)


ATVRAWSPEC

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

 PURPOSE:
   Display a 2D spectroscopic image with bad columns marked in red.

 CALLING SEQUENCE:
   atvrawspec, filename, _EXTRA=KeywordsForATV

 INPUTS:
   filename   - Either a raw SDSS file name, or a 2D pixel flat or 2D bias

 OPTIONAL KEYWORDS:
   _EXTRA     - Extra keywords for ATV, such as MIN,MAX

 OUTPUTS:

 OPTIONAL OUTPUTS:

 COMMENTS:

 EXAMPLES:
   Display a 2D pixel flat with a reasonable display stretch:
   IDL> atvrawspec, 'pixflat-52069-b1.fits', min=0.9, max=1.1

   Display a 2D bias with a reasonable display stretch:
   IDL> atvrawspec, 'pixbias-52069-b1.fits', min=-5, max=10

 BUGS:

 PROCEDURES CALLED:
   atv
   atvplot
   djs_filepath()
   findopfile()
   headfits()
   sdssproc
   yanny_free
   yanny_read

 DATA FILES:
   $IDLSPEC2D_DIR/examples/opBC*par

 REVISION HISTORY:
   26-Feb-2002  Written by D. Schlegel, Princeton

(See pro/apo2d/atvrawspec.pro)


BADFMAGS

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

 PURPOSE:
   Find any F stars where the magnitudes in the calibObj files are grossly
   discrepent from the plug-map files.

 CALLING SEQUENCE:
   badfmags, [ maxdiff= ]

 INPUTS:

 OPTIONAL INPUTS:
   maxdiff - Maximum r-band magnitude difference; default to 0.4

 OUTPUTS:

 OPTIONAL OUTPUTS:

 COMMENTS:
   This routine looks for calibration F stars that have very
   discrepent magnitudes in the plug-map file vs. the calibObj files.
   Only the r-band magnitudes are compared, and they must differ by
   at least MAXDIFF in order to trigger a warning.

   Before comparing the magnitudes, first offset all the F star
   magnitudes by their median difference.

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   platelist
   readspec
   splog

 REVISION HISTORY:
   10-Feb-2004  Written by D. Schlegel, Princeton

(See pro/plan/badfmags.pro)


BADFSTARS

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

 PURPOSE:
   Find bad F stars used for spectro-photometry in the Spectro-2D reductions

 CALLING SEQUENCE:
   badfstars, [ /doplot ]

 INPUTS:

 OPTIONAL INPUTS:
   doplot     - If set, then use PLOTSPEC to plot all the bad spectra

 OUTPUTS:

 OPTIONAL OUTPUTS:

 COMMENTS:
   This procedure looks at all the objects labelled as either
   OBJTYPE='SPECTROPHOTO_STD' or 'REDDEN_STD' in the spAll.fits file.
   These are considered to be bad F stars if the following conditions
   are satisfied:
     WCOVERAGE > 0.10
     (|cz| > 500 km/sec) OR (not an B,A,F,G-type star)
   These objects are then listed in the file 'badfstars.log', and then
   plotted if /DOPLOT is set.

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   hogg_mrdfits()
   plotspec

 REVISION HISTORY:
   06-Feb-2004  Written by D. Schlegel, Princeton

(See pro/plan/badfstars.pro)


BANDPASSFILTER

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

 PURPOSE:

 CALLING SEQUENCE:
   newdata = bandpassfilter( datafft, [ klo_cut=, khi_cut= ] )

 INPUTS:
   datafft    - Vector of Fourier-transformed data

 OPTIONAL KEYWORDS:
   klo_cut    - Low-frequency cutoff
   khi_cut    - High-frequency cutoff

 OUTPUTS:
   newdata    - Filtered version of DATAFFT

 OPTIONAL OUTPUTS:

 COMMENTS:
   Units???

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:

 REVISION HISTORY:
   30-Mar-2000  Written by D. Schlegel, APO

(See pro/spec1d/bandpassfilter.pro)


BANDPASSINFO

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
   bandpassinfo
 PURPOSE:
   Return information about SDSS bandpasses u,g,r,i,z.
 COMMENTS:
   This routine can be used to convert filternames into numbers and back.
   If band is passed as a string, it gets whitespace-trimmed before use.
 CALLING SEQUENCE:
   bandpassinfo, band,index=index,name=name,wave=wave,fwhm=fwhm,zero=zero
 INPUTS:
   band    - a name (ugriz) or index (01234), or a vector of them
 OPTIONAL KEYWORDS:
 OUTPUTS:
 OPTIONAL OUTPUTS:
   index     - the band's index number (0-4)
   name      - name ('u' through 'z')
   wave      - central wavelength in Angstroms
   fwhm      - width of the bandpass in Angstroms
   zero      - the flux in Jy of a zero-magnitude source
   blueindex - the index (0-3) of the blue bandpass of the k-correction color
   redindex  - the index (1-4) of the red bandpass of the k-correction color
   colorname - the name of the color ('(u-g)' through '(i-z)')
 BUGS:
   Returns 0's (u's) or 4's (z's) where the input is wacky.
   Computes even unnecessary things (this could be fixed with some calls to
     keyword_set().
 PROCEDURES CALLED:
 REVISION HISTORY:
   2000-Jun-28  Written by Hogg (IAS)

(See pro/science/bandpassinfo.pro)


BATCH1D

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

 PURPOSE:
   Batch process Spectro-1D reductions based upon existing 2D plate files.

 CALLING SEQUENCE:
   batch1d, [ fullplatefile, topdir=, upsversion=, nice=, /clobber ]

 INPUTS:

 OPTIONAL INPUTS:
   fullplatefile - Plate files to reduce; default to all files matching
                   '*/spPlate*.fits' from the top-level directory.
   topdir     - Top directory for reductions; default to current directory.
   upsversion - If set, then do a "setup idlspec2d $UPSVERSION" on the 
                remote machine before executing the IDL job.  This allows
                you to batch jobs using a version other than that which
                is declared current under UPS.
   nice       - Unix nice-ness for spawned jobs; default to 19.
   clobber    - If set, then reduce all specified plates, overwriting
                any previous reductions.

 OUTPUTS:

 OPTIONAL OUTPUTS:

 COMMENTS:
   The list of hosts and protocols should be in the Yanny parameter file
   specified in the file TOPDIR/batch1d.par if it exists, or the default
   file "$IDLSPEC2D_DIR/examples/batch1d.par" is used.

   If using machines in Peyton, set
     topdir='/peyton/scr/spectro0/data/2d_v4'
   A plate is considered not reduced if any of the "spPlate*.par" files
   do not have a corresponding "spDiag1d*.log" file.

   The command is piped to the bash shell on the remote machine, so IDL
   and the idlspec2d product must be present when running "bash --login".
   Normally, your .bashrc file should set up all the necessary path info.
   If the UPSVERSION keyword is used, then the UPS "setup" command must
   also be set up in the .bashrc file.

   The command that is spawned will look something like (but all in one line):
     ssh1 wire1.princeton.edu 'cd /u/dss/spectro;
       echo "DISPLAY=; setup idlspec2d v4_9_6; /bin/nice -n 10
       idl 0406/spPlate-0406-51817.batch" | bash --login >& /dev/null'

   The $DISPLAY environment variable is always set to "" on the remote
   machine to make certain that we only use one IDL license per machine.
   (Any IDL jobs that have the same the username, machine name, and $DISPLAY
   use the same license.)

 EXAMPLES:

 BUGS:

 DATA FILES:
   $IDLSPEC2D_DIR/examples/batch1d.par

 PROCEDURES CALLED:
   djs_batch
   djs_filepath()
   fileandpath()
   splog
   yanny_free
   yanny_read

 REVISION HISTORY:
   17-Oct-2000  Written by D. Schlegel, Princeton

(See pro/spec1d/batch1d.pro)


BATCH2D

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

 PURPOSE:
   Batch process Spectro-2D reductions based upon already-built plan files.

 CALLING SEQUENCE:
   batch2d, [ platenums, topdir=, platestart=, plateend=, $
    mjd=, mjstart=, mjend=, upsversion=, nice=, /clobber ]

 INPUTS:

 OPTIONAL INPUTS:
   platenums  - Plate numbers to reduce; default to '*'
   topdir     - Top directory for reductions; default to current directory.
   platestart - Starting plate number.
   plateend   - Ending plate number.
   mjd        - MJD dates to reduce; default to all.
                Select based upon the MJD of the combine plan file, and
                reduce data from all nights needed for that combined plate+MJD.
   mjstart    - Starting MJD dates to reduce.
   mjend      - Ending MJD dates to reduce.
   upsversion - If set, then do a "setup idlspec2d $UPSVERSION" on the
                remote machine before executing the IDL job.  This allows
                you to batch jobs using a version other than that which
                is declared current under UPS.
   nice       - Unix nice-ness for spawned jobs; default to 19.
   clobber    - If set, then reduce all specified plates, overwriting
                any previous reductions.

 OUTPUTS:

 OPTIONAL OUTPUTS:

 COMMENTS:
   The list of hosts and protocols should be in the Yanny parameter file
   specified in the file TOPDIR/batch2d.par if it exists, or the default
   file "$IDLSPEC2D_DIR/examples/batch2d.par" is used.

   If using machines in Peyton, set
     topdir='/peyton/scr/spectro0/data/2d_v4'
   A plate is considered not reduced if any of the "spPlan2d*.par" files
   do not have a corresponding "spDiag2d*.log" file.

   The command is piped to the bash shell on the remote machine, so IDL
   and the idlspec2d product must be present when running "bash --login".
   Normally, your .bashrc file should set up all the necessary path info.
   If the UPSVERSION keyword is used, then the UPS "setup" command must
   also be set up in the .bashrc file.

   The command that is spawned will look something like (but all in one line):
     ssh1 wire1.princeton.edu 'cd /u/dss/spectro;
       echo "DISPLAY=; setup idlspec2d v4_9_6; /bin/nice -n 10
       idl 0406/spPlancomb-0406-51817.batch" | bash --login >& /dev/null'

   The $DISPLAY environment variable is always set to "" on the remote
   machine to make certain that we only use one IDL license per machine.  
   (Any IDL jobs that have the same the username, machine name, and $DISPLAY 
   use the same license.)

 EXAMPLES:

 BUGS:

 DATA FILES:
   $IDLSPEC2D_DIR/examples/batch2d.par

 PROCEDURES CALLED:
   concat_dir()
   djs_batch
   djs_filepath()
   fileandpath()
   get_mjd_dir()
   mjd_match()
   repstr()
   splog
   yanny_free
   yanny_read
   yanny_par()

 INTERNAL SUPPORT ROUTINES:
   batch2d_nolog()
   batch2d_rawfiles()
   batch2d_combfiles()

 REVISION HISTORY:
   17-Oct-2000  Written by D. Schlegel, Princeton

(See pro/spec2d/batch2d.pro)


BIN_SPECTRA

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

 PURPOSE:
   Make binned spectra for the purposes of fitting for the 
   bandpasses 

 CALLING SEQUENCE:
   bin_spectra, flux, binbounds

 INPUTS:
   flux   - flux in a set of spectra [NPIX,NSPEC]
   invvar   - inverse variance in a set of spectra [NPIX,NSPEC]
   binbounds   - boundaries of desired bins

 OPTIONAL INPUTS:

 OPTIONAL KEYWORDS:

 OUTPUTS:
   binflux  - binned flux

 COMMENTS:
   Not currently binning the variances. Sorry.

 EXAMPLES:

 PROCEDURES CALLED:

 DATA FILES:

 REVISION HISTORY:
   05-APr-2000  Written by M. Blanton, Fermiland

(See pro/spec1d/bin_spectra.pro)


CALCSCATIMAGE

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

 PURPOSE:
   Just return smoothed scattered light image

 CALLING SEQUENCE:
   scatfit = calcscatimage(ansimage, yrow, nscatbkpts=nscatbkpts, $
            ymin=ymin, ymax=ymax, fullrows=fullrows)

 INPUTS:
     ansimage  -  Keyword Output from extract_image
     yrow      -  Array of rows extracted in first pass 

 OPTIONAL KEYWORDS:
     ymin      -  lower limit for chebyshev background (default 0)
     ymax      -  upper limit for chebyshev background (default 2047)
     fullrows  -  number of rows in full image (default 2048)

 OUTPUTS:
    scatfit    - Image of scattered light from smoothing polynomials

 OPTIONAL OUTPUTS:

 COMMENTS:

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   bspline_valu()
   bspline_iterfit()
   fchebyshev()

 REVISION HISTORY:
   29-Sep-2000  Written by S. Burles, FNAL, adopted from fitansimage

(See pro/spec2d/calcscatimage.pro)


CATPLOT

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

 PURPOSE:
   Modified version of SPLOT by Tremonti for inspecting spectra.

 CALLING SEQUENCE:
   catplot, [x], y, $
    [color=, psym=, symsize=, thick= ]

   soplot, [x], y, [/autoscale], $
    [color=, psym=, symsize=, thick= ]

   sxyouts, x, y, string, [alignment=, charsize=, charthick=, color=, $
    font=, orientation= ]

   serase, [nerase, /norefresh]

 INPUTS:

 OUTPUT:

 COMMENTS:
   This code is based upon Aaron Barth's ATV procedure.

   SpInspect added to menu bar.  "Open SpInspect File" brings up a
   dialogue box.  The spInspect File must have the format 
   spInspect-pppp-mmmmm-inspector.par.  Upon loading this file, plotspec
   is called to loop through the fibers on the specified plate.  No
   changes are written to the spInspect File until "Update SpInspect File"
   is selected from the menu bar.

 EXAMPLES:

 BUGS:
   Doesn't use the passed XRANGE, YRANGE properly yet...
   Move around widgets to be more compact above plotting window.
   Write splot_readfits.
   Make POSITION= changeable based upon CHARSIZE.
   Gaussian fitting or integrated gaussian fitting.
   Allow one to step through an image row at a time? Or link to ATV?
   Use the WCS in splot_gettrack.
   Add widget button option to fix Y range or let it float, or fix YMIN=0.
   Include options for plotting contours, etc?
   Options for XLOG, YLOG
   For FITS files, take XTITLE, YTITLE from header
   Option to pass header as param in SPLOT
   SpInspect only reads the 1st of semi-colon separated variables in
     the manual_comments field.  (Writes them just fine!) 

 PROCEDURES CALLED:
   fits_read

 INTERNAL SUPPORT ROUTINES:
   splot_gausspix
   splot_startup
   splot_clearkeylist
   splot_displayall
   splot_readfits
   splot_writeeps
   splot_cleartext
   splot_zoom
   splot_gettrack
   splot_event
   splot_shutdown
   splot_resize
   splot_icolor()
   splot_setheader
   splot_headinfo
   splot_headinfo_event
   splot_plot1plot
   splot_plot1text
   splot_plotwindow
   splot_plotall
   sxyouts
   splot_move_cursor
   splot_set_minmax
   splot_get_minmax
   splot_refresh
   splot_help
   splot_help_event
   splot_plotparam_refresh
   splot_plotparam
   splot_plotparam_event
   serase
   splot_autoscale
   soplot
   splot
   splot_spinspect_new
   splot_spinspect_update
   splot_spinspect_event
   splot_spinspect

 REVISION HISTORY:
   28-Sep-1999  Written by David Schlegel, Princeton.
   19-Jun-2001  Gaussfit amplitude was wrong - fixed - D. Finkbeiner
   17-Jun-2002  Added spInspect procedures - C. Tremonti
                Modified splot_startup, splot_events

(See pro/spec1d/catplot.pro)


CHUNKINFO

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

 PURPOSE:
   Return chunk information for a given plate number.

 CALLING SEQUENCE:
   cinfo = chunkinfo(plateid)

 INPUTS:

 OPTIONAL INPUTS:
   plateid     - Plate ID number; scalar or array of integers

 OUTPUTS:
   cinfo       - Structure with chunk information for each plate

 OPTIONAL OUTPUTS:

 COMMENTS:

 EXAMPLES:

 BUGS:

 DATA FILES:
   $IDLSPEC2D_DIR/etc/spChunkList.par

 PROCEDURES CALLED:
   yanny_free
   yanny_read

 REVISION HISTORY:
   08-Feb-2001  Written by D. Schlegel, Princeton

(See pro/spec2d/chunkinfo.pro)


COLLIMATE

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

 PURPOSE:
   Compute the spectrograph collimation focus from Hartmann mask exposures.

 CALLING SEQUENCE:
   collimate, expnum1, [ expnum2, docams=, indir=, nregx=, nregy=, $
    maxshift=, /nocheck ]

 INPUTS:
   expnum1    - First exposure number of raw sdR file.

 OPTIONAL KEYWORDS:
   expnum2    - Second exposure number; default to EXPNUM1+1.
   docams     - Cameras to analyze; default to ['b1','b2','r1','r2'].
   indir      - Input directory for files; default to searching for
                files in $RAWDATA_DIR/*.  If $RAWDATA_DIR is not set,
                then it is assumed to be /data/spectro.
   nregx      - Number of sub-regions in the X dimension; default to 8.
   nregy      - Number of sub-regions in the Y dimension; default to 8.
   maxshift   - Maximum pixel shift to search in both X and Y; default to 3.
   nocheck    - If set, then assume that the 1st exposure is Hartmann-l,
                and the 2nd exposure is Hartmann-r, rather than looking at
                the OBSCOMM header keyword.  This correct keywords are
                added by the SOP goSpecFocus command, but will not be if
                you simply move the collimator and shutters yourself.

 OUTPUTS:

 OPTIONAL OUTPUTS:

 COMMENTS:
   The focus of the collimator is measured by comparing two Hartmann
   exposures of arc lamps, and looking for shifts in the arc line positions.
   A linear correlation coefficient is computed independently in NREGX
   by NREGY regions on each CCD as a function of pixel shifts of the 2nd
   image in both X and Y.  The best-focus value is found in each region
   by maximizing the linear correlation in the Y (wavelength) direction.
   
   The following files are output for each camera:
     Collimate-$MJD-$CAMERA-$EXPNUM1.log
     Collimate-$MJD-$CAMERA-$EXPNUM1.ps

   The position of the Hartmann shutters is read from the OBSCOMM header
   keywords.  It is expected to be '{focus, hartmann l}' for one exposure
   and '{focus, hartmann r}' for the other (in either order).  It is assumed
   that the collimator position is identical for both exposures.

   The sense of the pixel shifts reported is what one would have to shift
   the Hartmann-r exposure by in Y to agree with the Hartmann-l exposure.

 EXAMPLES:
   Solve for the focus of all 4 CCD's from exposures 10812+10813
   on MJD 52161 (assuming the files exist in /data/spectro/52161):
     IDL> collimate, 10812

 BUGS:

 PROCEDURES CALLED:
   dfpsclose
   dfpsplot
   djs_filepath()
   djs_icolor()
   djs_svdfit()
   sdssproc
   splog
   sxpar()

 INTERNAL SUPPORT ROUTINES:
   collimate_obscomm()

 REVISION HISTORY:
   28-Mar-2002  Written by D. Schlegel, Princeton.

(See pro/apo2d/collimate.pro)


COMBINE1FIBER

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

 PURPOSE:
   Combine several spectra of the same object, or resample a single spectrum.

 CALLING SEQUENCE:
   combine1fiber, inloglam, objflux, [ objivar, finalmask=, indisp=, skyflux=,$
    newloglam=, newflux=, newivar=, andmask=, ormask=, newdisp=, newsky=, $
    nord=, binsz=, bkptbin=, maxsep=, _EXTRA=KeywordsForReject, /verbose ]

 INPUTS:
   inloglam       - Wavelengths in log10-Angstroms [NPIX,NSPEC]
   objflux        - Flux [NPIX,NSPEC]

 REQUIRED KEYWORDS:
   newloglam      - Wavelengths for output evaluation, also in log10-Angstroms
                    [NNEWPIX]

 OPTIONAL INPUTS:
   objivar        - Inverse variance [NPIX,NSPEC]
   finalmask      - Pixel mask [NPIX,NSPEC]
   indisp         - Dispersion values [NPIX,NSPEC]
   skyflux        - Sky flux vectors [NPIX,NSPEC]
   binsz          - Bin separation for INLOGLAM; if not set, then default
                    to INLOGLAM[1]-INLOGLAM[0].
   nord           - Order of spline fit; default to 3.
   bkptbin        - Break point binning; default to 1.2 * BINSZ.
   maxsep         - Maximum separation between input wavelengths.  The spline
                    fit is split into pieces, with the breaks wherever this
                    spacing is exceeded.  Default to 2.0 * BINSZ.
   _EXTRA         - Keywords for DJS_REJECT().
   verbose        - If set, then output messages about bad break points and
                    masked data points.

 OUTPUTS:

 OPTIONAL OUTPUTS:
   finalmask      - Modified from its input by setting the COMBINEREJ bit
                    for deviant pixels in individual spectra that have
                    been rejected.
   objivar        - Modified from itts input by setting to zero wherever
                    the COMBINEREJ bit has been set in FINALMASK.
   newflux        - Resampled flux [NNEWPIX].
   newivar        - Resampled inverse variance [NNEWPIX].
   andmask        - Resampled mask. For each mask bit, set that bit only if
                    every input spectrum at this wavelength has that bit set
                    (e.g., this is a logical AND) [NNEWPIX].
   ormask         - Resampled mask. For each mask bit, set that bit if any
                    of the input spectra at this wavelength has that bit set
                    (e.g., this is a logical OR) [NNEWPIX].
   newdisp        - Resampled dispersion values [NNEWPIX].
   newsky         - Resampled sky flux [NNEWPIX].

 COMMENTS:
   One can pass this routine a single spectrum to be fit by a spline and
   re-sampled, in which case all the inputs (such as FLUX) are 1-dimensional
   arrays.  Or, one can pass it several spectra, in which case these inputs
   are 2-dimensional arrays.

   There's also some code in here to grow masked regions by another pixel
   on either end if the region is more than 3 pixels wide.

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   bspline_iterfit()
   bspline_valu()
   djs_laxisgen()
   djs_maskinterp()
   djs_median()
   pixelmask_bits()
   splog

 REVISION HISTORY:
   02-Jan-2000  Written by D. Schlegel; modified from COMBINE2DOUT

(See pro/spec2d/combine1fiber.pro)


COMPUTECHI2

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

 PURPOSE:
   Solve the linear set of equations Ax=b using SVD

 CALLING SEQUENCE:
   chi2 = computechi2( bvec, sqivar, amatrix, $
    [ acoeff=, dof=, yfit=, covar=, var= ] )

 INPUTS:
    bvec      - b vector in Ax=b [N]
    sqivar    - Errors in b as 1/sigma [N]
    amatrix   - A matrix in Ax=b [N,M]

 OPTIONAL INPUTS:

 OUTPUTS:
   chi2       - Chi^2 of the fit

 OPTIONAL OUTPUTS:
   acoeff     - Fit parameters x in Ax=b [M]
   dof        - Degrees of freedom in the fit, equal to the number of
                equations where SQIVAR is not zero minus the number of
                fit parameters (M)
   yfit       - Evaluation of the best-fit at each data point [N]
   covar      - Covariance matrix [M,M]
   var        - Variances [M], which is equivalent to the diagonal
                entries of COVAR

 COMMENTS:

 EXAMPLES:
   The following example creates a data vector with 20 measurements
   and their errors.  A linear fit is performed using the LINFIT()
   function and this function, which are equivalent:
     n = 20
     x = dindgen(n)
     y = 10.d0 * smooth(randomu(-1234,n),10)
     sqivar = 0.5 + randomu(-4321,n)
     acoeff = linfit(x,y,measure_errors=1./sqivar,covar=covar)
     print, acoeff, covar
     templates = [[dblarr(n)+1],[dindgen(n)]]
     chi2 = computechi2(y,sqivar,templates,acoeff=acoeff,covar=covar)
     print, acoeff, covar

 BUGS:

 PROCEDURES CALLED:

 REVISION HISTORY:
   07-Aug-2000  Written by D. Schlegel, Princeton

(See pro/spec1d/computechi2.pro)


CORRECT_DLAM

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

 PURPOSE:
   Correct ADU/pixel to ADU/d(log-lambda)

 CALLING SEQUENCE:
   correct_dlam, flux, fluxivar, wset, dlam=dlam

 INPUTS:
   flux       - Flux
   fluxivar   - Flux inverse variance
   wset       - Wavelength coefficient trace-set

 OPTIONAL KEYWORDS:
   dlam       - Log-lambda pixel size to convert to; default to 1.0d-4

 OUTPUTS:
   flux       - (Modified.)
   fluxivar   - (Modified.)

 OPTIONAL OUTPUTS:

 COMMENTS:
   Make a map of the size of each pixel in delta-(log10-Angstroms),
   and re-normalize the flux to ADU/d(log10-Angstroms).

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   divideflat
   traceset2xy

 REVISION HISTORY:
   04-Oct-2000  Written by S. Burles, FNAL

(See pro/spec2d/correct_dlam.pro)


DAYTIME_TEST

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

 PURPOSE:
   Look for spectro exposures taken during the day and not marked as test.

 CALLING SEQUENCE:
   daytime_test

 INPUTS:

 OPTIONAL INPUTS:

 OUTPUT:

 OPTIONAL OUTPUTS:

 COMMENTS:
   Find all the files matching '$RAWDATA_DIR/$MJD/sdR-b1-????????.fit*',
   and print a warning message for any science, flat, or arc exposures
   that are not marked as test exposures, and were taken during the
   daytime.  The warnings are also printed to the file 'daytime.log'.

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   djs_diff_angle()
   get_mjd_dir()
   get_tai
   headfits()
   sdsshead()
   splog
   sunpos
   sxpar()
   zenpos

 INTERNAL SUPPORT PROCEDURES:
   daytime_test1

 REVISION HISTORY:
   27-Apr-2003  Written by David Schlegel, Princeton (not checked in then)

(See pro/plan/daytime_test.pro)


DESIGN_MULTIPLATE

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

 PURPOSE:
   Routine to design a plate with several pointings.

 CALLING SEQUENCE:
   design_multiplate, stardata, [ tilenums=, platenums=, racen=, deccen=, $
    guidetiles=, apotemperature=apotemperature, /addfund, /norename ]

 INPUTS:
   stardata   - Structure with data for each star; must contain the
                fields RA, DEC, MAG[5], PRIORITY, HOLETYPE, TILENUM.
                HOLETYPE can be either 'OBJECT' or 'GUIDE'; objects with
                other values are ignored.  Other elements in the structure
                will be copied into the output plug-map files.
                If OBJTYPE is not passed in this structure, then it is set to
                'SERENDIPITY_MANUAL' for all HOLETYPE='OBJECT'.
                Stars with TILENUM=0 can only be used as guide stars.
   racen      - RA center for each tile
   deccen     - DEC center for each tile

 OPTIONAL INPUTS:
   tilenums   - Array of tile numbers; default to the unique list of
                tile numbers in STARDATA.TILENUM, but exclude the number zero.
   platenums  - Array of plate numbers; default to the same as TILENUMS.
   guidetiles - Tile number for each of the 11 guide fibers.  There exist
                default values for the cases 1,2,3 or 4 tiles.
   apotemperature - Design temperature for APO; default to 5 deg C.
   addfund    - If set, then add one more tile+plate with 9 or 10 holes
                in a line of declination from guide fiber #11 for the
                nearest of the 5 SDSS fundamental standard stars.
                We try to place 10 of these holes, spaced by 1 arcmin, but
                one can be knocked out by the guide-fiber alignment hole.
                This tile is given the TILEID=max(TILEID)+1, PLATEID=0.
   norename   - The default is to rename the output plugMapP files to
                plate names like 800,800B,800C,... if the first plate
                number is 800.  Set this keyword to keep the names as
                they are passed in PLATENUMS.

 OUTPUTS:

 OPTIONAL OUTPUTS:

 COMMENTS:
   There is no attempt to move plate centers such that a guide fiber
   can be re-used in another pointing.

   Objects are assigned according to their priority.  If none are specified
   with STARDATA.PRIORITY, then random priorities between 1 and 100 are
   assigned.  We reserve priorities of 0 and [2^31-2,2^31] for internal
   purposes.

 EXAMPLES:

 BUGS:
   These SDSS primary standards coordinates were not quite correct
   in the design of the initial set of special plates.  See the comments
   in the code.

 PROCEDURES CALLED:
   concat_dir()
   cpbackup
   current_mjd()
   djs_diff_angle()
   djs_laxisgen()
   plate_rotate
   yanny_free
   yanny_par()
   yanny_read
   yanny_write

 INTERNAL SUPPORT ROUTINES:
   design_append()

 REVISION HISTORY:
   21-Nov-2001  Written by D. Schlegel, Princeton

(See pro/plate/design_multiplate.pro)


DESIGN_PLATE

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

 PURPOSE:
   Routine to design a single plate.

 CALLING SEQUENCE:
   design_plate, stardata, [ racen=, deccen=, tilenum=, platenum=, $
    airtemp=, nstd=, nminsky=, nextra=, ngtarg=, /southern ]

 INPUTS:
   stardata   - Structure with data for each star; must contain the
                fields RA, DEC, MAG[5], HOLETYPE, OBJTYPE.
                HOLETYPE should be either 'OBJECT' or 'GUIDE'.
                Special values of OBJTYPE are 'SKY' and 'SPECTROPHOTO_STD'.
                Other elements in the structure (such as PRIMTARGET,...)
                will be copied into the output plug-map files.
   racen      - RA center for tile
   deccen     - DEC center for tile

 OPTIONAL INPUTS:
   tilenum    - Tile number; default to 1.
   platenum   - Plate number; default to the same as TILENUMS.
   airtemp    - Design temperature for APO; default to 5 deg C.
   nstd       - Number of spectro-photo standards; default to 8.
                This will be split with NSTD/2 standards on the North
                half of the plate, and the same number on the South.
   nminsky    - Minimum number of sky fibers; default to 32.
   nextra     - Number of extra fibers to assign, beyond the 640 science
                fibers.  In principle, this should be 0.  In practice,
                the "fiberPlates" code in the PLATE product will either
                crash or multiply-assign fibers to the same object unless
                there are extra objects.  Default to 10.
   ngtarg     - Number of times to target a guide star for each guide
                star position; default to 1 (e.g., exactly 11 guide stars).
                Selecting more gives the PLATE code more options, and
                may prevent it from crashing in some cases.
   southern   - If set, then set the Southern target-selection bit
                in both PRIMTARGET and SECTARGET for all objects.

 OUTPUTS:

 OPTIONAL OUTPUTS:

 COMMENTS:
   Priorities can be specified with PRIORITY in the input structure;
   otherwise, they are assigned randomly.

   We always assign guide stars first, then spectro-photo standards,
   then objects, then skies.  So the priorities are relevant only
   within each of those categories.

   This script generates the following files:
     plObs.par
     plPlan.par
     plPlugMapT-$TILE.par
   The commands from the SDSS "plate" product generate the following files:
     makePlates - Generate plPlugMapP-$PLATE.par
     fiberPlates - Generate plOverlay-$PLATE.par, and **overwrite**
                   the file plPlugMapP-$PLATE.par
     makeFanuc - Generate plFanuc-$PLATE.par
     makeDrillPos - Generate plMeas-$PLATE.par, plDrillPos-$PLATE.par
     use_cs3 - Generates no files.  Simply reports fiber collisions.
     makePlots - Generate plOverlay-$PLATE.ps

   When there is a problem, the "fiberPlates" script outputs error
   messages like:
     collision at 554 = {307 125 6 160 47} OBJECT with...
     collision at 565 = {307 125 2 168 4015} COHERENT_SKY with...

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   concat_dir()
   current_mjd()
   djs_diff_angle()
   splog
   yanny_readone()
   yanny_write

 INTERNAL SUPPORT ROUTINES:
   radec_to_xyfocal
   design_append()

 REVISION HISTORY:
   14-Jan-2002  Written by D. Schlegel, Princeton

(See pro/plate/design_plate.pro)


DIVIDEFLAT

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

 PURPOSE:
   Divide an extracted image with a fiber-flat

 CALLING SEQUENCE:
   divideflat, flux, fflat, [ invvar=, minval=, /quiet ]

 INPUTS:
   flux       - Array of extracted flux from a flat-field image [Nrow,Ntrace]
   fflat      - Array of flat-field flat-field vectors [Nrow,Ntrace]

 OPTIONAL KEYWORDS:
   invvar     - Inverse variance map for FLUX [Nrow,Ntrace]
   minval     - Minimum value to consider good for flat-field;
                default to 0.03.
   quiet      - don't print to splog?

 OUTPUTS:

 OPTIONAL OUTPUTS:

 COMMENTS:
   We no longer utilize or set FIBERMASK 
   Wherever the fiber is denoted bad in FIBERMASK, or wherever FFLAT is
   <= MINVAL, we set FLUX=FLUXIVAR=0.

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   splog

 REVISION HISTORY:
   17-Nov-1999  Written by S. Burles, Chicago
   23-Nov-1999  Modified by D. Schlegel, Princeton

(See pro/spec2d/divideflat.pro)


DJS_ITER_SFIT

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

 PURPOSE:
   Surface-fitting code to tabulated data (with iterateive rejection).

 CALLING SEQUENCE:
   acoeff = djs_sfit_iter(fval, xval, yval, degreex, degreey, $
            sqivar=, yfit=, mask=, maxdev=, maxrej=, $
            upper=, lower=, maxiter=, freeiter=, outmask=)

 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
   mask      - Input mask for fitting and rejection (1=good, 0=bad)
   maxdev    - Rejcet pts w/ abs(data - model) > maxdev (passed to djs_reject)
   upper     - Rejcet pts w/ data > model + upper*sigma (passed to djs_reject)
   lower     - Rejcet pts w/ data > model + lower*sigma (passed to djs_reject)
   maxiter   - Maximum # of rejection iterations 
   freeiter  - Rejected points accumulate for this # of iterations,
               then the mask is reset to the input mask

 OUTPUTS:
   acoeff    - Fit coefficients as [DEGREEX+1,DEGREEY+1] array

 OPTIONAL OUTPUTS:
   yfit      - Fit values
   outmask   - Masked points used in final iteration (1=used, 0=rejected)

 COMMENTS:

 EXAMPLES:

 BUGS:
   Doesn't like NaNs

 PROCEDURES CALLED:
   djs_reject
   splog

 REVISION HISTORY:
   12-Aug-2003  Adapted from djs_sfit by C. Tremonti, Steward Observatory

(See pro/fluxfix/djs_sfit_iter.pro)


DR1LIST_BEST

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

 PURPOSE:
   Determine which plates *should* have been in DR1 that match the tiles
   of those actually chosen.

 CALLING SEQUENCE:
   dr1list_best

 INPUTS:

 OPTIONAL INPUTS:

 OUTPUT:

 OPTIONAL OUTPUTS:

 COMMENTS:
   Outputs are written to the file 'jill.out'.

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   platelist
   struct_print

 REVISION HISTORY:
   22-Aug-2002  Written by David Schlegel, Princeton (not checked in then)

(See pro/plan/dr1list_best.pro)


ELODIE_BEST

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

 PURPOSE:
   Find the best-fit Elodie spectrum to a set of spectra.

 CALLING SEQUENCE:
   res = elodie_best(objflux, objivar, $
    hdr=, objloglam0=, objdloglam=, zmin=, zmax=, fitindx= ])

 INPUTS:
   objflux    - Flux for spectra [NPIX,NOBJECT]
   objivar    - Inverse variance of flux [NPIX,NOBJECT]

 OPTIONAL INPUTS:
   hdr        - FITS header for objects, used to construct the wavelengths
                from the following keywords: COEFF0, COEFF1.
                Must be specified if OBJLOGLAM0,OBJDLOGLAM are not set.
   objloglam0 - Zero-pint of log-10(Angstrom) wavelength mapping of OBJFLUX.
   objdloglam - Wavelength spacing for OBJFLUX in log-10(Angstrom).
   zmin       - Minimum redshift to consider; default to -0.00333
                (-1000 km/sec).
   zmax       - Minimum redshift to consider; default to +0.00333
                (+1000 km/sec).
   fitindx    - If set, then only fit for the objects specified by
                these indices.  Set to -1 to not fit any objects (but
                return empty output structures); default to fitting all.

 OUTPUTS:
   res        - Output structure with result for each object [NOBJECT].
                The following elements are from the FITS header of the
                best-fit Elodie spectrum:
                  ELODIE_FILENAME   - Filename
                  ELODIE_OBJECT     - Object name
                  ELODIE_SPTYPE     - Spectral type
                  ELODIE_BV         - (B-V) color
                  ELODIE_TEFF       - T_effective
                  ELODIE_LOGG       - Log10(gravity)
                  ELODIE_FEH        - [Fe/H]
                  ELODIE_Z_MODELERR - The standard deviation in redshift
                                      amongst the 12 best-fit stars
                The following elements are from the ZFIND() function:
                  ELODIE_Z          - Redshift
                  ELODIE_Z_ERR      - Redshift error
                  ELODIE_RCHI2      - Reduced chi^2
                  ELODIE_DOF        - Degrees of freedom for fit

 OPTIONAL OUTPUTS:

 COMMENTS:
   Any stars labelled as possible binary or triple stars are ignored.

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   djs_maskinterp()
   read_elodie()
   splog
   sxpar()
   zfind()

 INTERNAL SUPPORT ROUTINES:
   elodie_struct()

 REVISION HISTORY:
   11-Mar-2002  Written by D. Schlegel, Princeton

(See pro/spec1d/elodie_best.pro)


EXTRACT_BOXCAR

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

 PURPOSE:
   Extract the total flux within a boxcar window at many positions.

 CALLING SEQUENCE:
   fextract = extract_boxcar( fimage, xcen, ycen, [radius=radius] )

 INPUTS:
   fimage     - Image
   xcen       - Initial guesses for X centers
   ycen       - Y positions corresponding to "xcen" (expected as integers)

 OPTIONAL KEYWORDS:
   radius     - Radius of extraction; default to 3.0

 OUTPUTS:
   fextract   - Extracted flux at each position specified by (xcen, ycen)

 OPTIONAL OUTPUTS:

 COMMENTS:

 EXAMPLES:

 PROCEDURES CALLED:
   Dynamic link to extract_boxcar.c

 REVISION HISTORY:
   24-Mar-1999  Written by David Schlegel, Princeton.

(See pro/spec2d/extract_boxcar.pro)


EXTRACT_IMAGE

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

 PURPOSE:
   Extract the fiber profile flux for an entire image

 CALLING SEQUENCE:
   extract_image(fimage, invvar, xcen, sigma, flux, [finv, yrow=,
              ymodel=, fscat=, proftype=, ansimage=,
              wfixed=, mask=mask, pixelmask=,  reject=, wsigma=, 
              nPoly=, maxIter=, highrej=, lowrej=,
              fitans=, whopping=, /relative, 
              nband= ])

 INPUTS:
   fimage     - Image [NCOL,NROW]
   invvar     - Inverse variance [NCOL,NROW]
   xcen       - Initial guesses for X centers [NROW,NFIBER]
   sigma      - Input sigma of gaussian profile; default to 1.0 pixels.
                This can be a scalar, an [NFIBER] vector, or
                an [NROW,NFIBER] array.

 OPTIONAL KEYWORDS:
   yrow       - List of row numbers (0-indexed) to extract; default to all.
   proftype   - currently, one can only use 1: Gaussian (scalar)
              - or                          2: Exp Cubic
              - or                          3: Double Gaussian
              - or              4: Exp Cubic with doublewide Gaussian
   wfixed     - array of 1's and zero's which set which parameters are fixed.
                e.g. [1] just gaussian's with fixed width sigma
                     [1, 1] fit gaussian + sigma correction
                     [1, 0, 1] fit gaussian + center correction
                     [1, 1, 1] fit gaussian + sigma and center corrections.   
   mask       - byte mask: 1 is good and 0 is bad [NCOL,NROW] 
   pixelmask  - bits set due to extraction rejection [NROW,NFIBER]
   reject     - Array setting rejection threshholds; defaults are set
                in EXTRACT_ROW().
   nPoly      - order of chebyshev scattered light background; default to 4
   nband      - band-width of full covariance fiber profile matrix;
                default to 1.
   maxIter    - maximum number of profile fitting iterations; default to 20
   highrej    - positive sigma deviation to be rejected (default 10.0)
   lowrej     - negative sigma deviation to be rejected (default 10.0)
   fitans     - ratio of profiles to do in single profile fitting
   relative   - Scale rejection thresholds by reduced chi-squared (default 0)
   whopping   - traces which have WHOPPINGingly high counts, and need extra
                background terms
   wsigma     - sigma width of whopping profile (exponential, default 25)
   oldreject  - ???

 OUTPUTS:
   flux       - Total extracted flux in each profile [nRowExtract,NFIBER]

 OPTIONAL OUTPUTS:
   ansimage   - Coefficients of fit for each row [nCoeff,nRow]
   mask       - Modified by setting the values of bad pixels to 0
   finv       - Estimated inverse variance each profile [nRowExtract,NFIBER]
   ymodel     - Model best fit of row [NCOL,NROW]
   fscat      - Scattered light contribution in each fiber [NROW,NFIBER]
   pimage     - ???
   chisq      - Chi^2 of each row [NROW]

 COMMENTS:

 EXAMPLES:

 PROCEDURES CALLED:
   calcflux
   extract_row()
   pixelmask_bits()
   splog

 REVISION HISTORY:
   08-Aug-1999  Written by Scott Burles, Chicago 
   22-Aug-2000  Added banded-matrix possibility 

(See pro/spec2d/extract_image.pro)


EXTRACT_OBJECT

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

 PURPOSE:

   Performs all object extraction tasks
      0) Locate bright fibers, and test image background
      1) 4 Step Optimal extraction
      2) Tweak to sky lines
      3) Sky subtraction
      4) Flux calibration
      5) Telluric correction

 CALLING SEQUENCE:
   extract_object, outname, objhdr, image, invvar, plugsort, wset, $
    xarc, lambda, xtrace, fflat, fibermask, proftype=, color=, $
    [ widthset=, dispset=, skylinefile=, plottitle=, superflatset=, $
    /do_telluric ]

 INPUTS:
   outname    - Name of outputs FITS file
   objhdr     - Header cards from object image
   image      - Object image [nx,ny]
   invvar     - Inverse Variance of object image [nx,ny]
   plugsort   - Plugmap structure for [ntrace] spectra
   wset       - Wavelength solution from arc line spectra
   xarc       - centroids measured in arc line spectra
   lambda     - air wavelengths corresponding to xarc
   xtrace     - spatial traces from flat field
   fflat      - 1d flat field vectors
   fibermask  - Fiber status bits, set nonzero for bad status [NFIBER]
   proftype   - Which type of profile should we use, (default=1 Gaussian)
   superflatset- If present, then divide by median superflat! ???
   color      - ???
   widthset   - ???
   dispset    - ???
   skylinefile- ???

 REQUIRED KEYWORDS:
   color      - camera color (red or blue)

 OPTIONAL KEYWORDS:
   plottitle  - Prefix for titles in QA plots.
   do_telluric- If set, then perform telluric-corrections for the red CCDs;
                the default is to no longer do this, because the v5 code
                does this in the later flux-calibration steps

 OUTPUTS:
   A fits file is output in outname, which contains
      FLOAT flambda [NX,NTRACE]
      FLOAT flambda_invvar [NX,NTRACE]
      LONG finalmask [NX,NTRACE]
      STRUCT vacuum wavelengths
      STRUCT wavelength dispersion
      STRUCT plugmap [NTRACE]

 OPTIONAL OUTPUTS:

 COMMENTS:

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   calcscatimage()
   divideflat
   djs_median()
   djs_oplot
   djs_plot
   extract_boxcar()
   extract_image
   fibermask_bits()
   fitsn()
   fitvacset()
   get_tai
   heliocentric()
   locateskylines
   mwrfits
   pixelmask_bits()
   qaplot_scatlight
   qaplot_skydev
   qaplot_skyline
   qaplot_skyshift
   qaplot_skysub
   skyline_dispersion()
   skysubtract
   smooth_halo2d()
   spadd_guiderinfo
   splog
   sxaddpar
   sxpar()
   telluric_corr
   traceset2xy
   find_whopping()

 INTERNAL SUPPORT ROUTINES:

 REVISION HISTORY:
   24-Jan-2000  Written by S. Burles, Chicago
   26-Jul-2001  Also pass proftype and superflatset

(See pro/spec2d/extract_object.pro)


EXTRACT_PROFILE

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

 PURPOSE:
   Extract the flux with profile weighting at centroid positions.

 CALLING SEQUENCE:
   fextract = extract_profile( fimage, invvar, xcen, ycen, 
                  [ferror=ferror, fscattered=fscattered, fwidth=fwidth, 
                   sigma=sigma, nPoly=nPoly, maxIter=maxIter,
                   refit=refit, highrej=highrej, lowrej=lowrej, boxap=boxap])

 INPUTS:
   fimage     - Image[nCol,nRow]
   invvar     - Inverse Variance[nCol,nRow]
   xcen       - Initial guesses for X centers[nFibers,nRow]
   ycen       - Y positions corresponding to "xcen[nFibers]" [nRow]

 OPTIONAL KEYWORDS:
   ferror     - error array (-1 if bad pixel)
   fscattered - scattered light contribution 
   fwidth     - final profile width used

   sigma      - sigma of gaussian profile; default to 1.0
   nPoly      - order of chebyshev scattered light background; default to 5
   maxIter    - maximum number of profile fitting iterations; default to 5
   refit      - order of chebyshev to fit to profile widths vs. row,
			default is 0, which does no refitting
   highrej    - positive sigma deviation to be rejected (default 5.0)
   lowrej     - negative sigma deviation to be rejected (default 5.0)
   boxap      - boxcar aperture size in pixels 
			default is 0, which does no boxcar extraction

 OUTPUTS:
   fextract   -  Extracted flux at each position specified by (xcen, ycen)
                  [nFibers,nRow]
		2: Scattered light estimate
		3: Final profile width 
		4: Boxcar extracted flux

 OPTIONAL OUTPUTS:

 COMMENTS:

 EXAMPLES:

 PROCEDURES CALLED:
   Dynamic link to extract_profile.c

 REVISION HISTORY:
   24-Mar-1999  David Schlegel, Princeton.
   24-Jun-1999  Stolen and modified by Scott Burles, Chicago.

(See pro/spec2d/extract_profile.pro)


EXTRACT_ROW[1]

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

 PURPOSE:
   Fit the fiber profiles and background in a single row with least squares

 CALLING SEQUENCE:
   ans = extract_row( fimage, invvar, xcen, sigma, [ymodel=, fscat=, 
              proftype=, wfixed=, inputans=, iback=, bfixarr=, xvar=,
              mask=, relative=, diagonal=, fullcovar=, wfixarr=, npoly=,
              maxiter=, lowrej=, highrej=, niter=, squashprofile=,
              whopping=, wsigma=, pixelmask=, reject=, reducedChi=,
              nBand=  ])

 INPUTS:
   fimage     - Vector [nCol]
   invvar     - Inverse variance [nCol]
   xcen       - Initial guesses for X centers [nFiber]
   sigma      - Sigma of gaussian profile; (scalar or [nFiber])

 OPTIONAL KEYWORDS:
   proftype   - Select profile type:
                  1: Gaussian
                  2: (exponential)^3
                  3: (exponential)^2.5
                Default to 1.
   inputans   - Input fit, excluding background and whopping terms
                [ncoeff*nFiber]
                The array is sorted as follows:
                  [ncoeff] values for fiber #0
                   ...
                  [ncoeff] values for fiber #(nFiber-1)
   relative   - Set to use reduced chi-square to scale rejection threshold
   squashprofile - ???
   npoly      - Order of chebyshev scattered light background; default to 5
   nband      - Band-width of covariance matrix of fiber profiles: default 1
   maxiter    - Maximum number of profile fitting iterations; default to 10
   lowrej     - Negative sigma deviation to be rejected; default to 5
   highrej    - Positive sigma deviation to be rejected; default to 5
   whopping   - X locations to center additional "whopping" terms to describe
                the exponentail tails of flux near bright fibers; default
                to -1, which means not to use any such terms.
   wsigma     - Sigma width for exponential whopping profiles; default to 25
   reject     - Three-element array setting partial and full rejection
                thresholds for profiles; default [0.2, 0.6, 0.6].
                When there is less than REJECT[2] of the area is left,
                  then drop fitting of all higher-order terms.
                When there is less than REJECT[1] of the area is left,
                  then the pixel is rejected (inverse variance is set to 0).
                When there is less than REJECT[0] of the area is left,
                  then assume that there's no fiber there, and don't fit
                  for that fiber at all.

 MODIFIED INPUTS (OPTIONAL):
   wfixed     - Array to describe which parameters to fix in the profile;
                0=fixed, 1=float; default to [1].
                The number of parameters to fit per fiber is determined
                this way; e.g. nCoeff = n_elements(wfixed), so the default
                is to fit only 1 parameter per fiber.  For the (default)
                Gaussian profile, this is the height of the Gaussian.
                Note that WFIXED is used to build the array WFIXARR.
   iback      - 1D array of input background coeff 
                (needed if fixed parameters are non-zero)
   bfixarr    - 1D integer array to specify which terms of the background
                coefficients to fix; 0=fixed, 1=float.
   wfixarr    - 1D integer array to specify which parameters in the full fit
                to fix; 0=fixed, 1=float.
                The array is sorted as follows:
                  [ncoeff] values for fiber #0
                   ...
                  [ncoeff] values for fiber #(nFiber-1)
                  [npoly] values for the background polynomial terms
                  [whoppingct] values for the whopping terms
   xvar       - X values of fimage and invvar; default is findgen(NX).
   mask       - Image mask: 1=good, 0=bad [NX]
   pixelmask  - Bits set for each fiber due to extraction rejection [nFiber]

 OUTPUTS:
   ans        - Output fit [ncoeff*nFiber+npoly+whoppingct]
                The array is sorted as follows:
                  [nFiber] values for coefficient #0
                   ...
                  [nFiber] values for coefficient #(nCoeff-1)
                  [npoly] values for the background polynomial terms
                  [whoppingct] values for the whopping terms
                Note this array is **not** sorted as INPUTANS or WFIXARR!

 OPTIONAL OUTPUTS:
   ymodel     - Evaluation of best fit [nCol]
   fscat      - Scattered light contribution in each fiber [nFiber]
   diagonal   - 1D diagonal of covariance matrix.  Currently, this is
                the diagonal from the Cholesky decompostion, which is
                1/error[j].  [ncoeff*nFiber+npoly+whoppingct]
   fullcovar  - 2D covariance matrix.  This is a symmetric matrix, and we
                only fill the lower triangle.  Computing this increases CPU
                time by a factor of 2 or 3.
   niter      - Number of rejection iterations performed
   reducedChi - Reduced chi ???

 COMMENTS:

 BUGS:
    Still need to do:
       limits on chebyshev polynomial are assumed to be 0.0 <--> nx
       these may need to be optional if only partial rows are being fit

       Error codes need to be returned, currently no such codes are returned

 EXAMPLES:

 PROCEDURES CALLED:
   Dynamic link to extract_row.c

 REVISION HISTORY:
    8-Aug-1999  Written by Scott Burles, Chicago 

(See pro/spec2d/extract_row.pro)


EXTRACT_ROW[2]

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

 PURPOSE:
   Fit the fiber profiles and background in a single row with least squares
   Wrapper to extract row, which does extra testing

 CALLING SEQUENCE:
   ans = extract_row_safe( fimage, invvar, xcen, sigma, [ymodel=, fscat=, 
              proftype=, wfixed=, inputans=, iback=, bfixarr=, xvar=,
              mask=, relative=, diagonal=, fullcovar=, wfixarr=, npoly=,
              maxiter=, lowrej=, highrej=, niter=, squashprofile=,
              whopping=, wsigma=, pixelmask=, reject=, reducedChi= ])

 INPUTS:
   fimage     - Vector [nCol]
   invvar     - Inverse variance [nCol]
   xcen       - Initial guesses for X centers [nFiber]
   sigma      - Sigma of gaussian profile; (scalar or [nFiber])

 OPTIONAL KEYWORDS:
   proftype   - Select profile type:
                  1: Gaussian
                  2: (exponential)^3
                  3: (exponential)^2.5
                Default to 1.
   inputans   - Input fit, excluding background and whopping terms
                [ncoeff*nFiber]
                The array is sorted as follows:
                  [ncoeff] values for fiber #0
                   ...
                  [ncoeff] values for fiber #(nFiber-1)
   relative   - Set to use reduced chi-square to scale rejection threshold
   squashprofile - ???
   npoly      - Order of chebyshev scattered light background; default to 5
   maxiter    - Maximum number of profile fitting iterations; default to 10
   lowrej     - Negative sigma deviation to be rejected; default to 5
   highrej    - Positive sigma deviation to be rejected; default to 5
   whopping   - X locations to center additional "whopping" terms to describe
                the exponentail tails of flux near bright fibers; default
                to -1, which means not to use any such terms.
   wsigma     - Sigma width for exponential whopping profiles; default to 25
   reject     - Two-element array setting partial and full rejection
                thresholds for profiles; default [0.8, 0.2].
                What does this mean???
                When this was hardwired, it was [0.8,0.4].

 MODIFIED INPUTS (OPTIONAL):
   wfixed     - Array to describe which parameters to fix in the profile;
                0=fixed, 1=float; default to [1].
                The number of parameters to fit per fiber is determined
                this way; e.g. nCoeff = n_elements(wfixed), so the default
                is to fit only 1 parameter per fiber.  For the (default)
                Gaussian profile, this is the height of the Gaussian.
                Note that WFIXED is used to build the array WFIXARR.
   iback      - 1D array of input background coeff 
                (needed if fixed parameters are non-zero)
   bfixarr    - 1D integer array to specify which terms of the background
                coefficients to fix; 0=fixed, 1=float.
   wfixarr    - 1D integer array to specify which parameters in the full fit
                to fix; 0=fixed, 1=float.
                The array is sorted as follows:
                  [ncoeff] values for fiber #0
                   ...
                  [ncoeff] values for fiber #(nFiber-1)
                  [npoly] values for the background polynomial terms
                  [whoppingct] values for the whopping terms
   xvar       - X values of fimage and invvar; default is findgen(NX).
   mask       - Image mask: 1=good, 0=bad [NX]
   pixelmask  - Bits set for each fiber due to extraction rejection [nFiber]

 OUTPUTS:
   ans        - Output fit [ncoeff*nFiber+npoly+whoppingct]
                The array is sorted as follows:
                  [nFiber] values for coefficient #0
                   ...
                  [nFiber] values for coefficient #(nCoeff-1)
                  [npoly] values for the background polynomial terms
                  [whoppingct] values for the whopping terms
                Note this array is **not** sorted as INPUTANS or WFIXARR!

 OPTIONAL OUTPUTS:
   ymodel     - Evaluation of best fit [nCol]
   fscat      - Scattered light contribution in each fiber [nFiber]
   diagonal   - 1D diagonal of covariance matrix.  Currently, this is
                the diagonal from the Cholesky decompostion, which is
                1/error[j].  [ncoeff*nFiber+npoly+whoppingct]
   fullcovar  - 2D covariance matrix.  This is a symmetric matrix, and we
                only fill the lower triangle.  Computing this increases CPU
                time by a factor of 2 or 3.
   niter      - Number of rejection iterations performed
   reducedChi - Reduced chi ???

 COMMENTS:

 BUGS:
    Still need to do:
       limits on chebyshev polynomial are assumed to be 0.0 <--> nx
       these may need to be optional if only partial rows are being fit

       Error codes need to be returned, currently no such codes are returned

 EXAMPLES:

 PROCEDURES CALLED:
   Dynamic link to extract_row.c

 REVISION HISTORY:
    4-Feb-1999  Written by Schlegel
        

(See pro/spec2d/extract_row_safe.pro)


FCALIB_DEFAULT

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

 PURPOSE:
   Return a default flux-calibration vector

 CALLING SEQUENCE:
   calibfac = fcalib_default(camname, loglam, [exptime] )

 INPUTS:
   camname    - Camera name; 'b1', 'b2', 'r1' or 'r2'
   loglam     - Wavelengths [log-10 Angstroms]

 OPTIONAL INPUTS:
   exptime    - Rescale the fluxing vector to this exposure time [sec];
                default to the value in the spFluxcalib file header
                (probably 900 sec)

 OUTPUTS:
   calibfac   - Flux-calibration values, set to 0 if outside
                the knonwn wavelengths; the spectra in ADU should be
                divided by this

 OPTIONAL OUTPUTS:

 COMMENTS:

 EXAMPLES:

 BUGS:

 DATA FILES:
   $IDLSPEC2D_DIR/examples/spFluxcalib-$CAMERA.fits

 PROCEDURES CALLED:
   bspline_valu()
   headfits()
   mrdfits()
   sxpar()

 REVISION HISTORY:
   17-Dec-2005  Written by D. Schlegel, LBL

(See pro/spec2d/fcalib_default.pro)


FIBERFLAT

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

 PURPOSE:
   Construct the flat-field vectors from an extracted flat-field image.

 CALLING SEQUENCE:
   fflat = fiberflat( flux, fluxivar, wset, [ fibermask=fibermask, $
    minval=, ncoeff=, pixspace=, /dospline, nord=, lower=, upper=,
    /dospline, /nonorm, plottitle= ])

 INPUTS:
   flux       - Array of extracted flux from a flat-field image [Nrow,Ntrace]
   fluxivar   - Inverse variance map for FLUX.
   wset       - Wavelength solution

 OPTIONAL KEYWORDS:
   fibermask  - Fiber status bits, set nonzero for bad status [NFIBER]
   minval     - Minimum value to use in fits to flat-field vectors;
                default to 3% of the median of FLUX.
   ncoeff     - Number of coefficients used in constructing FFLAT;
                default to 3 (cubic)
   pixspace   - Approximate spacing in pixels for break points in the
                spline fits to individual fibers; default to 10 pixels.
   dospline   - If this keyword is set, then fit the flat-field vectors
                to splines (using PIXSPACE) rather than to a Legendre
                polynomial (using NCOEFF).
                This is now what we use?
   plottitle  - Title for QA plot; if not set, then do not plot.
   nonorm     - Do not normalize the fluxes in FFLAT by the super-flat.
   superflatset-Bspline set to reconstruct superflat

 PARAMETERS FOR SLATEC_SPLINEFIT:
   nord
   lower
   upper

 OUTPUTS:
   fflat      - Array of flat-field flat-field vectors for each fiber
                that remove relative flat-field variations as a function
                of wavelength between fibers [Nrow, Ntrace]

 OPTIONAL OUTPUTS:
   fibermask  - (Modified)

 COMMENTS:
   The user should first "flat-field" the input array to take out
   pixel-to-pixel variations.

   The parameters for SLATEC_SPLINEFIT are only used when generating the
   "superflat".

   The 'BADFLAT' bit is set in FIBERMASK if the mean throughput for
   a fiber is less than 0.7 times the median of all good-fiber throughputs.

   In any given fiber, set FFLAT=0 wherever there are at least 5 contiguous
   bad pixels.

 EXAMPLES:

 BUGS:

 PROCEDURES CALLED:
   fibermask_bits()
   bspline_valu()
   bspline_iterfit()
   splog
   superflat()
   traceset2xy
   xy2traceset

 REVISION HISTORY:
   14-Oct-1999  Written by D. Schlegel, APO
    3-Oct-2000  Changed over to IDL bspline routines

(See pro/spec2d/fiberflat.pro)


FIBERMASK_BITS

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

 PURPOSE:
   Return mask value corresponding to a mask condition for FIBERMASK.

 CALLING SEQUENCE:
   mask = fibermask_bits(label)

 INPUTS:
   label      - String name specifying bit

 OUTPUTS:
   mask       - Signed long set to 2^BIT, with BIT specified by LABEL.

 OPTIONAL OUTPUTS:

 COMMENTS:

 EXAMPLES:
   mask = fibermask_bits('NOPLUG') 

 BUGS:

 PROCEDURES CALLED:
   pixelmask_bits()

 REVISION HISTORY:
   23-Jan-2000 Written by S. Burles, Chicago
   14-Jul-2000 Combine with PIXELMASK_BITS() (DJS).

(See pro/spec2d/fibermask_bits.pro)


FIBER_ROLLCALL

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

 PURPOSE:
   Print the "roll call" of how many plug-map bits are set.

 CALLING SEQUENCE:
   fiber_rollcall, andmask, loglam

 INPUTS:
   andmask    - Bit mask
   loglam     - Wavelength mapping in log10(Ang)

 OPTIONAL INPUTS:

 OUTPUTS:

 OPTIONAL OUTPUTS:

 COMMENTS:

 EXAMPLES:

 BUGS:

 DATA FILES:

 PROCEDURES CALLED:
   splog
   sdss_flagname()

 INTERNAL SUPPORT ROUTINES:

 REVISION HISTORY:
   17-Feb-2004  Written by D. Schlegel & S. Burles; copied from PLATESN.

(See pro/spec2d/fiber_rollcall.pro)


FILTER_CHECK

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

 PURPOSE:
   
   Fit for the filter curves by comparing photometry and spectrophotometry

 CALLING SEQUENCE:
   
   filter_check,spallfile,binboundsfile

 INPUTS:
   spallfile      - spectro info

 OPTIONAL INPUTS:

   binboundsfile  - bin boundaries 

 OPTIONAL KEYWORDS:

 OUTPUTS:
   binRfile   - file containing output stuff

 COMMENTS:

 BUGS:

 EXAMPLES:

 PROCEDURES CALLED:

 DATA FILES:

 REVISION HISTORY:
   05-APr-2000  Written by M. Blanton, Fermiland

(See pro/spec1d/filter_check.pro)


FILTER_CHECK_CHI2

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

 PURPOSE:
   
   Calculate the chi^2 for a particular set of bandpass
   residuals. 

 CALLING SEQUENCE:
   chi2 = filter_check_chi2(binflux, binR, photocounts)

 INPUTS:
   binflux  - binned flux
   binR     - parameters to use for flux
   photocounts  - psf_band + (fiber_r-psf_r) (not dereddened)

 OPTIONAL INPUTS:

 OPTIONAL KEYWORDS:

 OUTPUTS:
   chi2  - resulting chi2

 COMMENTS:

 BUGS:

 EXAMPLES:

 PROCEDURES CALLED:

 DATA FILES:

 REVISION HISTORY:
   05-APr-2000  Written by M. Blanton, Fermiland

(See pro/spec1d/filter_check_chi2.pro)


FILTER_SELECT

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

 PURPOSE:
   
   Gather spectra based on an input file of the form 
   created by platemerge (the spAll file). Calculate the 
   ugriz throughput for each object in the plates, possibly
   putting limits on target type, MJD, or signal-to-noise
   (essentially by requiring survey quality). 

 CALLING SEQUENCE:
   filter_select, spallfile, outfile, [mjdlimits= , primtarget=,
   filter_prefix=, mingisn2=, rpsfmodel=]

 INPUTS:
   spallfile  - spAll.fit file as created by platemerge
   filter_prefix  - Use alternate prefix for filter curves to use
                    (allowed are sdss or doi) 

 OPTIONAL INPUTS:

 OPTIONAL KEYWORDS:
   mjdlimits  - Only look in a certain range of MJDs
   primtarget - Require a certain target type
   mingisn2 - Minimum plate SN^2 in g AND i

 OUTPUTS:
   outfile    - Fits file with all the spAll.fit info, but with
                synthetic ugriz replaced with the desired filter 
                curves

 COMMENTS:

 BUGS:
   Depends on spec_append, internal routine of readspec

 EXAMPLES:

 PROCEDURES CALLED:
   filter_thru()
   spec_append
   readspec
   mrdfits()
   mwrfits

 REVISION HISTORY:
   05-APr-2000  Written by M. Blanton, Fermiland

(See pro/spec1d/filter_select.pro)


FILTER_SOLVE

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

 PURPOSE:
   
   Minimize the chi^2 by varying the filter residuals. Basically
   solve Ax=b.

 CALLING SEQUENCE:
   filter_solve,binflux,photocounts,binR

 INPUTS:
   binflux  - binned flux
   photocounts  - psf_band + (fiber_r-psf_r) (not dereddened)

 OPTIONAL INPUTS:

 OPTIONAL KEYWORDS:

 OUTPUTS:

   binR     - best fit filter parameters

 COMMENTS:

 BUGS:

 EXAMPLES:

 PROCEDURES CALLED:

 DATA FILES:

 REVISION HISTORY:
   05-APr-2000  Written by M. Blanton, Fermiland

(See pro/spec1d/filter_solve.pro)


FILTER_THRU

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

 PURPOSE:
   Compute throughput in SDSS filters

 CALLING SEQUENCE:
   res = filter_thru( flux, [waveimg=, wset=, mask=, filter_prefix=, /toair ])

 INPUTS:
   flux       - Flux image [NX,NTRACE]

 OPTIONAL INPUTS:

 OPTIONAL KEYWORDS:
   waveimg    - Wavelength image in Angstroms [NX,NTRACE], or this could
                be a single vector if the wavelength mapping is the same
                for all traces (note the latter is faster to compute)
   wset       - Wavelength solution in log-lambda; required if WAVEIMG not set
   mask       - Linearly interpolate over pixels where MASK is nonzero.
                [NX,NTRACE]
   filter_prefix  - Use alternate prefix for filter curves to use
                    (allowed are sdss, doi, sdss_jun2001) [sdss_jun2001]
   toair      - Convert the wavelengths to air from vacuum before computing

 OUTPUTS:
   res        - Integrated response in all 5 SDSS filters, ordered ugriz;
                dimensions are [NTRACE,5] or [5] if NTRACE=1.

 COMMENTS:
   The filter curve files are assumed to be in $IDLUTILS_DIR/data/filters.

 EXAMPLES:

 BUGS:
   Needs waveimg to be equally spaced in log lambda (MRB 4.5.01) ???
    Now calculates pixel size in log lambda to do correct spectrophotometry

 PROCEDURES CALLED:
   vactoair
   djs_maskinterp()
   readcol
   traceset2xy

 REVISION HISTORY:
   10-Mar-2000  Written by D. Schlegel, Princeton
   05-Apr-2001  Modified by Michael Blanton to allow alternate filters

(See pro/spec2d/filter_thru.pro)


FINDSPEC

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

 PURPOSE:
   Routine for finding SDSS spectra that match a given RA, DEC.

 CALLING SEQUENCE:
   findspec, [ra, dec, infile=, outfile=, searchrad=, slist=, $
    /best, /print ]

 INPUTS:

 OPTIONAL INPUTS:
   ra         - Right ascension; scalar or array in degrees.
   dec        - Declination; scalar or array in degrees.
   infile     - Input file with RA, DEC positions, one per line.
                If set, then this over-rides values passed in RA,DEC.
   outfile    - If set, then print matches to this file.
   searchrad  - Search radius in degrees; default to 3./3600 (3 arcsec).
   best       - If set, then return the best match for each location, where
                best is defined to be the closest object on the plate with
                the best S/N.
                This also forces the return of one structure element in SLIST
                per position, so that you get exactly a paired list between
                RA,DEC and SLIST.
   print      - If set, then print matches to the terminal.

 OUTPUTS:

 OPTIONAL OUTPUTS:
   slist      - Structure containing information for each match.

 COMMENTS:
   The search radius is set to within 1.55 degress of a plate center,
   then within 3 arcsec of an object.

 EXAMPLES:
   Make a file "file.in" with the following two lines:
     218.7478    -0.3745007
     217.7803    -0.8900855

   Then run the command:
     IDL> findspec,infile='file.in'

   This should print:
     PLATE   MJD FIBERID            RA            DEC
     ----- ----- ------- ------------- --------------
       306 51637     101      218.7478     -0.3745007
       306 51637     201      217.7803     -0.8900855

 BUGS:

 PROCEDURES CALLED:
  djs_readcol
  djs_diff_angle()
  platelist
  readspec
  struct_print

 REVISION HISTORY:
   15-Feb-2001  Written by David Schlegel, Princeton.

(See pro/spec1d/findspec.pro)


FIND_NMINIMA

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

 PURPOSE:
   Find one or several minima in a vector of chi^2 values.

 CALLING SEQUENCE:
   xpeak = find_nminima( yflux, [ xvec, dofarr=, nfind=, minsep=, $
    width=, ypeak=, xerr=, errcode=, npeak=, plottitle=, /doplot, /debug ]

 INPUTS:
   yflux          - Y values

 OPTIONAL INPUTS:
   xvec           - X