Home Download Tutorial 1 Tutorial 2 Tutorial 3 Tutorial 4 Tutorial 5

List of Routines

ULYSSAnalyse a spectrum
ULY_CHIMAPCreate a chi2 map
ULY_CHIMAP_INIT Initialize the chi square map structure
ULY_CHIMAP_PLOT Plot a chi square map
ULY_CHIMAP_READ Read in a chi square map file
ULY_CHIMAP_WRITE Write a chi square map in a file
ULY_CMP_NAME Create a unique name for a fit component
ULY_CMP_SELECT Make a 2d vector describing an axis of the parameters space
ULY_FIT Fit a spectrum with a non-linear model
ULY_FIT_INIT Call the initialization function for each component of the fit
ULY_FIT_LIN Fit the linear coefficients and return the best fit
ULY_LSF Determine the line-spread function (LSF)
ULY_LSF_PLOT Plot a LSF file
ULY_LSF_SMOOTH Smooth a LSF file
ULY_PLOT_INIT Initialize plotting variables
ULY_PLOT_SAVE Make a hardcopy of a plot.
ULY_SOLUT_SPLOT Plot the result of a fit done with ULY_FIT
ULY_SOLUT_SREAD Read a solution file written by ULY_SOLUT_SWRITE
ULY_SOLUT_SWRITE Save the fit solution structure returned by ULY_FIT in a FITS file
ULY_SOLUT_TPLOT Plot a result file of ULYSS
ULY_SOLUT_TPRINT Print the solution of a fit
ULY_SOLUT_TREAD Read the solution of a fit from a .res file
ULY_SOLUT_TWRITE Save the solution of a fit to an ascii file
ULY_SPECT_ALLOC, ULY_SPECT_FREE Allocate/free a spectrum structure
ULY_SPECT_EXTRACT Extract part of a spectrum
ULY_SPECT_GET Retrieve information from a spectrum structure.
ULY_SPECT_LINREBIN Rebin a spectrum in linear wavelength scale
ULY_SPECT_LOGREBIN Rebin logarithmically a spectrum
ULY_SPECT_LOSVDCONVOL Convolve a spectrum with a losvd
ULY_SPECT_LSFCONVOL Convolve a spectrum or a population model
ULY_SPECT_PLOT Plot 1d or 2d fits files
ULY_SPECT_READ Read a a spectrum from a FITS file
ULY_STARTUP Compile the ULySS programs
ULY_TEST Test the ULySS package

Routine Descriptions

ULYSS

[Next Routine] [List of Routines]
 NAME:
                  ULYSS
 PURPOSE:
                  Analyse a spectrum
 USAGE:
                  ulyss,
                  <spectrum>,<cmp> or MODEL_FILE=<model_file>
                  [, POSITION=<position>]
                  [, ERR_SP=<err_sp>][, SNR=<snr>]
                  [, VELSCALE]
                  [, KMOMENT=<kmoment>][, SG=<sg>][, DG=<dg>][, DL=<dl>]
                  [, ADEGREE=<ad>][, MDEGREE=<md>][, POLPEN=<polpen>]
                  [, LMIN=<lmin>][, LMAX=<lmax>]
                  [, NSIMUL=<nsimul>]
                  [, KFIX=<kfix>][, KPEN=<kpen>]
                  [, /CLEAN]
                  [, /QUIET]
                  [, SOLUTION=<solution>]
                  [, /ALL_SOLUTIONS]
                  [, FILE_OUT=<result_file>]
                  [, MODECVG=<modecvg)]
                  [, /PLOT]
                  
 DESCRIPTION:
      Main procedure of the ULySS package.
      Reads the observed spectrum, the models, and makes the fit (with uly_fit).

      ULYSS fits a spectrum with a linear combination of non-linear components
      convolved with a given line-of-sight velocity distribution (LOSVD) 
      and multiplied by a polynomial continuum. The linear or non-linear
      parameters may be bounded (for example force a non-negative
      combination of components).

      The fit is a Levenberg-Marquart local minimization for the non-linear
      parameters and a bounded-values least square for the linear ones.
      Any parameter can be bounded of fixed. The algorithm is described 
      in ULY_FIT.

      Line-of-sight velocity distribution (LOSVD):

      Velocity dispersion:
      The velocity dispersion computed by the program is
      sigma_ulyss = sqrt(sigma_obs^2 - sigma_model^2). Where
      sigma_obs = sqrt(sigma_physical^2 + sigma_instrumental^2) and
      sigma_model is the dispersion in the model. For ELODIE-based models, 
      sigma_model is 13 km/s; For MILES-based models, it is ~58km/s. 
      sigma_instrumental is the instrumental broadening of the observation.
      If the relative line-spread function of the spectrograph is injected in
      the model, then sigma_ulyss = sigma_phys.

      Logarithmic sampling:
      The line of sight velocity distribution is measured as a broadening of 
      the spectral features due to Doppler shift. The wavelength shift is 
      related to the redshift z by: (l1-l0)/l0 = z, where l1 and l0 are 
      respectively the shifted and restframe wavelengths. (If we neglect the 
      relativistic term, z=v/c, where v is the velocity shift and c the speed 
      of light). As the wavelength shift depends on the wavelength, when 
      sampled linearly in wavelength, a spectrum is not simply 'translated'. 
      However, with a logarithmic sampling the shift becomes a translation, 
      and the effect of the LOSVD can be written as a convolution.

      Note also to take care of the composition of the partial shift: 
      If a shift z1 is applied in ULY_SPECT_READ, and if ULYSS finds
      a 'residual' shift z2, the total redshift is:
      1 + z = (1 + z1)(1 + z2), when z1xz2 is small it is close to 1+z1+z2.

      Relativistic correction to compute the radial velocity:

      In special relativity, the relation between z and v is: 
      1 + z = sqrt(c+v/c-v) = (1 + v/c) / sqrt(1-(v/c)^2). 
      (The last term is the Lorentz factor, gamma: 1+z = gamma (1+v/c)). 
      At low redshift, the Newtonian approximation is: z=v/c

      This formula can be inverted into:
      v/c = ((1+z)^2 - 1) / ((1+z)^2 + 1) 
      (z=1 corresponds to v = 0.6 c = 180000 km/s)

      ULySS determines cz, and no relativistic correction is applied.
      The transformation above must be used to determine v from cz.

      In many cases computing cz is sufficient. The databases, LEDA or NED
      give cz that is somehow inproperly sometime called a 'velocity'.

      Computation of the velocity dispersion:

      ULySS determines the cz dispersion, and in general this shall be
      converted into a *velocity* dispersion to carry on dynamics (for
      example to apply the Virial Theorem).
      Fortunately, sigma_cz and sigma are usually very similar.

      To be rigorous, two effects shall be considered (i) the effect of the 
      composition of redshifts, and (ii) the relativistic correction.
      Lets write the redshift of a star with v=sigma, in the galaxy's restframe
      zs = (1 + sigma/c) / sqrt(1-(sigma/c)^2) - 1
      And the residual redshift of the barycenter of the galaxy (after
      de-redshifting the spectrum, for example using ULY_SPECT_READ): zb.
      The cz dispersion is: sigma_cz = c (1+zb) zs
      The two corrective terms are usually negligible at any redshift.
      The first order correction pointed by Harrison (1974 ApJ, 191, L51)
      for clusters of galaxies does not apply here.

 ARGUMENTS:
   <spectrum>     Input
                  File name, or 'spect' structure containing 1d spectrum
                  to be analysed with uly_fit.
                  A 'spect' structure is returned by, e.g. ULY_SPECT_READ.
   <cmp>          Input
                  Array of model's components, see ULY_FIT.
                  Prior calls to ULY_STAR, ULY_TGM, ULY_SSP and/or ULY_LINE
                  can define this array and set the guesses and constraints
                  on the free parameters.
                  MODEL_FILE can be given instead.

 KEYWORDS:

   The following keywords are handled by ULYSS itself, or shared
   by the different tasks.

   MODEL_FILE     Input, filename 
                  When <cmp> is not provided, this keyword may give the
                  name of a FITS file containing the model to fit.
                  <cmp> and MODEL_FILE are mutually exclusive.
                  Note that using MODEL_FILE is less flexible that using
                  the component-definition functions. See ULY_SSP, ULY_TGM or 
                  other component-definition functions for more capabilities.

   SNR            Input, float
                  Mean signal to noise ratio the of analyzed spectrum.
                  This parameter is used to derive the errors if the error 
                  spectrum is not attached to the input spectrum and if ERR_SP
                  is not given.  It will generate a constant error spectrum.
                  SNR is ignored if an error spectrum is available.

   NSIMUL         Input, integer
                  To make Monte-Carlo simulations, set with this keyword 
                  the number of simulations. These simulations are
                  made adding a Gaussian noise equivalent to the estimated
                  noise. To take into account the correlation of the noise
                  introduced along the data processing (for example, 
                  resulting of an oversampling), the noise is generated
                  on a vector of length npix/dof_factor, and then rebinned
                  to npix. Where npix is the actual number of pixels, and
                  dof_factor characterizes the correlation of the noise. 
                  (dof_factor is included in the spect structure, 
                  ULY_SPECT_LOGREBIN and the other smoothing or resampling  
                  routines modify it consistently).

   /QUIET       
                  Set this keyword to supress the printing of information and
                  results.

   FILE_OUT       
                  The names of the result file are constructed by appending 
                  '.res' and '.fits' to this variable.  
                  The '.res' ASCII file contains the values of the parameters 
                  and their uncertainties. If the file pre-exists, new records
                  are appended. This file can be used by ULY_SOLUT_TPRINT, 
                  ULY_SOLUT_TPLOT, ...
                  The FITS file contains the spectrum, the bestfit, the 
                  polynomials and the mask of good pixels. In can be plotted 
                  with ULY_SOLUT_SPLOT.
                  If neither FILE_OUT or SOLUTION are specified, output files 
                  with prefix 'output' are created

   SOLUTION
                  Output structure containing all fitted parameters and their
                  respective errors. See ULY_FIT for details.

   /ALL_SOLUTIONS
                  When <cmp> specifies a grid of guesses (for global 
                  minimization), this keyword tells to return all the local 
                  solutions. By default, only the best solution is returned.

   /PLOT            
                  Set this keyword to display the fit using ULY_SOLUT_SPLOT.
 
   POSITION
                  When a multidimensional dataset is to be analysed, like a
                  long-slit spectrum, stacked spectra or cube, the keyword
                  specifies the position of the 1D spectrum to analyse. It can
                  be a scalar or an array of the same dimension as the dataset
                  (not counting the spectral dimension).

   VELSCALE       [km/s] default=conserve the number of pixels
                  Sampling. Size of the pixel after the rebinning in logarithm
                  of wavelength.

   The following keywords are handled by the reading function ULY_SPECT_READ,
   and are therefore relevant only if <spectrum> is a file name (if <spectrum>
   is a spect structure, ULY_SPECT_READ is not called).
   Check in the documentation of ULY_SPECT_READ for further information.

   SG             [dimensionless] default=0
                  Guess for the redshift z. This keyword is handled by
                  uly_spect_read to shift the data. (the guess for the 
                  minimization is set to 0, and cannot by changed).
                  This value must be quite precise: An error by more than 3 or
                  5 times the velocity dispersion may prevent the fit to 
                  converge.

   LMIN,LMAX      [Angstrom]
                  Minimum and maximum wavelength. These parameters can
                  be vectors to define several fitting intervals.

   ERR_SP        
                  Name of a FITS file containing the error spectrum.
                  (In some cases the error spectrum may be included in the 
                  same file as the signal, see ULY_SPECT_READ)

   The following keywords are handled by ULY_FIT. Check its documentation 
   for further information.

   KMOMENT        
                  Number of terms of the LOSVD.
                  The terms are in the order: [cz, sigma, h3, h4, h5,
                  h6]. By default, KMOMENT=2, i.e. a Gaussian LOSVD
                  is fitted.

   DG             [km/s] 
                  Guess or fixed value for the velocity dispersion.
                  This guess is not very critical, and the default value 
                  of 1 pixel is generally satisfactory.
                  
   DL             [km/s] 
                  2-elements array giving the limits for the fitted velocity dispersion.
                  
   KFIX   
                  Array used to fix some of the parameters of the LOSVD,
                  0 means that the parameter is free; 1 that it is fixed.
                  The parameters are specified in the following order:
                  [cz, sigma, h3, h4, h5, h6]. cz and sigma must be
                  given in km/s.

   KPEN           
                  Kinematics penalty parameter for the Gauss-Hermite 
                  coefficients. Default is no penalization (KPEN=0).
                  This penalisation is described in Cappellari & Emmsellem 
                  2004, PASP 116, 138. The actual value should be chosen
                  carefully (performing Monte-Carlo simulations), but values
                  in the range 0.5 to 1.0 shall be a good starting guess.
                  See more information in ULY_FIT.

   ADEGREE
                  Default -1; Degree of additive polynomial, 
                  -1: no additive polynomial

   MDEGREE
                  Default 10; Degree of multiplicative polynomial  
 
   POLPEN
                  Automatic selection of significant terms in the 
                  multiplicative polynomial. See ULY_FIT_LIN.

   CLEAN
                  Set this keyword to iteratively detect and clip the outiers.
                  The algorithm is described in ULY_FIT.

   MODECVG
                  Keyword passed to ULY_FIT (see the documentation there)

 EXAMPLE:
   1. Simple and quite limited examples:
     Lets first select a spectrum file provided in the package for tests:
     (the variable uly_root is set in uly_startup.pro to point to ULySS
      root directory)
           star = uly_root+'/data/cflib_114642.fits'

     Analyse this file with default parameters (Determine the broadening 
     by comparing to the solar spectrum):
           ulyss, star

     Determine the atmospheric parameters of this star with the Elodie.3.2
     interpolator
           ulyss, star, MODEL_FILE=uly_root+'/models/elodie32_flux_tgm.fits'

     Analyse a stellar population with a Pegase_HR/Elodie.3.1 grid of SSPs:
           galaxy = uly_root+'/data/VazMiles_z-0.40t07.94.fits'
           ulyss, galaxy, MODEL_FILE=uly_root+'/models/PHR_Elodie31.fits'

     Analyse a spectrum previously read and convolved
           galaxy = uly_root+'/data/VazMiles_z-0.40t07.94.fits'
           spectrum = uly_spect_read(galaxy, VELSCALE=velscale)
           spectrum = uly_spect_losvdconvol(spectrum, 0., 30., 0, 0, /OVER)
           ulyss, spectrum, MODEL=uly_root+'/models/PHR_Elodie31.fits'

   2. More advanced usages
     In real cases, the model should be defined before calling ULYSS,
     in order to choose the guesses, add constraints on the parameters,
     or define a composite model.

     Analyse a stellar population with Pegase_HR/Elodie.3.1
           galaxy = uly_root+'/data/VazMiles_z-0.40t07.94.fits'
           cmp1 = uly_ssp(AG=[1000.], ZG=[0], AL=[200.,3000.])
           cmp2 = uly_ssp(AG=[10000.], ZG=[0], AL=[3000., 12000.])
           cmp = [cmp1, cmp2]
           ulyss, galaxy, cmp, /PLOT

     See the routines ULY_SSP, ULY_TGM, ULY_STAR, ...
     to define model-components which can be assembled together as a vector.
     
 AUTHOR:
                  Mina Koleva, 03/03/2006

 HISTORY:
     2006/03/03    Created by Mina Koleva for stellar population fitting
     2007/07/06    Change keywords,rewrite doc... 
     2008/05/27    Restructured and made to fit any model, Ph. Prugniel

(See pgm/ulyss.pro)


ULY_CHIMAP

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

 PURPOSE:
               Create a chi2 map

 USAGE:
               chimap = uly_chimap(<spectrum>, <cmp>, [proj]
                                   [, VELSCALE=<velscale>]
                                   [, LMIN=<lmin>][, LMAX=<lmax>]
                                   [, SG=<sg>][, DG=<dg>]
                                   [, KMOMENT=<kmoment>][, KFIX=<kfix>]
                                   [, ERR_SP=<err_sp>]
                                   [, SNR=<snr>]
                                   [, XNODE=<xnode>][, YNODE=<ynode>]
                                   [, ADEGREE=<adegree>][, MDEGREE=<mdegree>]
                                   [, PLOT=<plot>][, /PS]
                                   [, /CLEAN]
                                   [, QUIET=<quiet>]
                                   [, FILE_OUT=<file_out>])

 DESCRIPTION:
      Explore the the parameter space in search for the best fitting model. 
      At each node of the grid the other parameters are optimized.

 ARGUMENTS:
   <spectrum>  Input
               File name, or 'spectrum' structure containing 1d spectrum
               A 'spectrum' structure is returned by,
               e.g. ULY_SPECT_READ.

   <cmp>       Input
               Structure returned from user function for defining
               component (see for exampl ULY_SSP/ ULY_TGM)
               it can be a vector of components (like [cmp1, cmp2, ...])

   [proj]      Optional Input
		The 2x2 matrix defining the projection of the chimap
               in the space of n parameters to be fitted, for example
               to plot the age of the first
               comp. (so it is component = 0, parameter = 0), and the
               fraction of the second component (burst) (comp = 1,
               param=-1), the projection should be [[0,0],[1,-1]]. 
               In a case that components and parameters are
               unknown leave this parameter free.




 KEYWORDS:
   [VELSCALE]    [km/s]
                 Velocity scale for which the chi square is computed.
                 Default: The model velocity scale.

   [LMIN]        [ANGSTROM]
                 Standard 'good region' descriptor. No default.

   [LMAX]        [ANGSTROM]
                 Standard 'good region' descriptor. No default.

   [SG]          [km/s]
                 Guess for the redshift.
                 The input spectrum is shifted by this quantity when
                 it is read (the guess for the minimization is set
                 to 0, and cannot by changed).
                 This value must be quite precise: An error by more than
                 3 or 5 times the velocity dispersion may prevent the
                 fit to converge.

   [DG]          [km/s] 
                 Guess or fixed value for the velocity dispersion.
                 This guess is not very critical, and the default value 
                 of 1 pixel is generally satisfactory.

   [ERR_SP]      
                 1d file containing the error of the spectrum to analyse;
                 relevant only in the case where a file name is given for
                 <spectrum>.

   [KMOMENT]        
                 Number of terms of the LOSVD.
                 The terms are in the order: [cz, sigma, h3, h4, h5,
                 h6]. By default, KMOMENT=2, i.e. a Gaussian LOSVD
                 is fitted.

   [KFIX]        Default: The kinematics parameters are free.
                 Array used to fix some of the parameters of the LOSVD,
                 0 means that the parameter is free; 1 that it is fixed.
                 The parameters are specified in the following order:
                 [cz, sigma, h3, h4, h5, h6]. cz and sigma must be
                 given in km/s.

   [SNR]         default=100
                 Mean signal to noise ratio the of analyzed spectrum.
                 This parameter is used to derive the errors if the
                 error spectrum is not attached to the input spectrum
                 and if ERR_SP is not given. 
                 It will generate a constant error spectrum.

   [XNODE]       
                 X values at which the chi square is computed.
                 If an integer scalar is given, take is as the number of nodes
                 and use the limits of the grid.
                 Default: a 10 points regular spaced grid between the limits

   [YNODE]       
                 Y at which the chi square is computed.
                 If an integer scalar is given, take is as the number of nodes
                 and use the limits of the grid.
                 Default: a 10 points regular spaced grid between the limits

   [ADEGREE]     
                 degree of the *additive* Legendre polynomial
                 Default: -1

   [MDEGREE]     
                 degree of the *multiplicative* Legendre polynomial
                 Default: 10

   [/PLOT]       
                 Plot the solution of a fit with ULY_SOLUT_SPLOT as well
                 as the chi square map with ULY_CHIMAP_PLOT at each
                 grid node. Default is not to plot at each node.

   [/PS] or [PS='filename.ps']
      	          Makes a postcript hardcopy of the plot. When using /PS the
                 filename is called 'chimap.ps'. To use a different name,
                 specify it with PS='other_name.ps'. 

   [/CLEAN]      set this keyword to use the iterative kappa-sigma clipping.

   [QUIET]       
                 Verbosity control
  
   [FILE_OUT]    
                 Ouput filename in which the Chisq map is written.
                 Formally this file is in fits format. 
                 Default is to not write the file.

 RETURN VALUE:
                 Returns the computed chi square map structure.

 EXAMPLE:
    file_test = uly_root+'/data/VazMiles_z-0.40t07.94.fits'
    cmp = uly_ssp()
    map = uly_chimap(file_test, cmp, [[0,0],[0,1]], /quiet)

 AUTHOR:
               Mina Koleva, Antoine Bouchard

 HISTORY:
          2008/07/31 creation, using earlier version from AB

 KNOWN BUGS:
   If you want to fix the fraction better give
               nodes. Usually the values of the fraction are not known
               apriori. So it is better to fit once your spectrum to see
               the order of the magnitude of the fraction and then
               make chi2 maps.

(See pgm/uly_chimap.pro)


ULY_CHIMAP_INIT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
              ULY_CHIMAP_INIT
 PURPOSE:
              Initialize the chi square map structure

 USAGE:
              map = uly_chimap_init(<n_xnode>, <n_ynode>)

 ARGUMENTS:
	X_NODE, Y_NODE
	       The number of x and y nodes of the chi square map structure.

 RETURN VALUE:
              Initialized chi square map structure. Which contains:
       .map   	2d array with the computed chi2 values over xnode/ynode
       .xnode 	nodes on the abscissa where the chi2 is computed 
       .ynode 	nodes on the ordinate where the chi2 is computed 
       .xtitle	name of the x variable (for example age, tempreture...)
       .ytitle	name of the y variable (for example velocity, Fe/H...)
       .xunit 	units of the x variable (for example Myr, C...)
       .yunit 	units of the y variable (for example km/s, dex...)

 AUTHOR:
              Antoine Bouchard
 HISTORY:
              2008/02/08

(See pgm/uly_chimap_init.pro)


ULY_CHIMAP_PLOT

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

 PURPOSE:
              Plot a chi square map

 USAGE:
              uly_chimap_plot, <chimap>
                       [, /PS] or [PS='filename.ps']  
                       [, /NOSCALEBAR]
                       [, XRANGE=xrange][, YRANGE=yrange]
                       [, /XLOG][, /YLOG]
              		[, PLOT_VAR=<plot_var>]
			[, /QUIET]
			[, ...extra keywords]

 ARGUMENTS:
    <chimap>: An input map structure, or FITS file containing the map.
              Chi2 maps are generated with the function CHIMAP.
              The function CHIMAP_READ may be used to read such a file
              and return a map structure, or the name of the file can 
              directly be passed here.
 KEYWORDS:
    /PS or PS='filename.ps'
   	       Makes a postcript hardcopy of the plot. When using /PS the
              filename is called 'chimap.ps'. To use a different name,
              specify it with PS='other_name.ps'.

    /OVERPLOT 
              Overplots on an existing graphics.
    
    /NOSCALEBAR
              When a halftone map is drawn, setting this keyword suppress
              the scale bar which is otherwise plotted on the right side.

    /QUIET  Suppress some message printed on the screen.

    XRANGE YRANGE
              Two-elements arrays specifying the range for respectively
              the X and Y axes.
 
    CHIRANGE
              Two-elements arrays specifying the range of chi2 values
              corresponding to the extreme countours and/or colours.

    /XLOG /YLOG
              Plot X (resp. Y) axis in logarithmic scale.

    [ ...Extra keywords]
	       All extra keywords are passed to uly_plot_init, if PLOT_VAR
	       is not defined.

 DESCRIPTION:
    Draw a chi2 map with optionally halftone background and iso-contours
    overlay. The node of the local and absolute minima are figured by
    overplotted symbols (note that these minima are the position of
    the pixels of the map and do not generally coincide with the
    result of the minimization since the map has a limited resolution).

 HISTORY:
              Antoine Bouchard, 2008/02/08, created

(See pgm/uly_chimap_plot.pro)


ULY_CHIMAP_READ

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
              ULY_CHIMAP_READ
 PURPOSE:
              Read in a chi square map file

 USAGE:       chi = uly_chimap_read(<file>)

 ARGUMENTS:
    FILE:     Name of the file saved by ULY_CHIMAP_WRITE (string)

 RETURN VALUE:
              Chi-square map structure. The structure containing:
	       .map   2d array with the computed chi2 values over xnode/ynode
	       .xnode nodes on the abscissa where the chi2 is computed 
	       .ynode nodes on the ordinate where the chi2 is computed 
	       .xtitle  name of the x variable (for examp. age, tempreture...)
	       .ytitle  name of the y variable (for examp. velocity, Fe/H...)
	       .xunit units of the x variable (for examp. Myr, C...)
	       .yunit units of the y variable (for examp. km/s, dex...)


 DEPENDENCE:  ULY_CHIMAP_INIT

 HISTORY:
     creation: Antoine Bouchard 2008/02/08

(See pgm/uly_chimap_read.pro)


ULY_CHIMAP_WRITE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
              ULY_CHIMAP_WRITE
 PURPOSE:
              Write a chi square map in a file

 USAGE:
              uly_chimap_write, <chimap>, <outfile>

 ARGUMENTS:
    <chimap>   Chimap structure created by ULY_CHIMAP
    <outfile>  FITS file where the result is saved

 AUTHOR:
              Antoine Bouchard
 HISTORY:
              2008/02/08

(See pgm/uly_chimap.pro)


ULY_CMP_NAME

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

 PURPOSE:        
		  Create a unique name for a fit component
              
 USAGE:
                 name_unique = uly_cmp_name([name])

 ARGUMENTS:
     [NAME]:  
		  Proposed name

 DESCRIPTION:
     ULY_CMP_NAME returns a unique name for a fit component.
     If the proposed name is already used, a new
     name is searched by appending a number. If no name is passed
     in input, the routine creates one like 'cmp<n>', where <n> is
     a number (incremented after each call to this routine).

     The name is also trimmed from embedded space characters, and
     the characters '_' are replaced with '-'.

     ULY_CMP_NAME is used by ULY_SSP, ULY_STAR, ULY_TGM when a fit
     component is being defined.

 HISTORY:
     CREATION  2008/08/10 Philippe Prugniel

(See pgm/uly_cmp_name.pro)


ULY_CMP_SELECT

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

 NAME:
               ULY_CMP_SELECT

 PURPOSE:
               Make a 2d vector describing an axis of the parameters space

 USAGE:
               axis = uly_cmp_select(cmp)

 DESCRIPTION:
      Called from chi2/convergence map program it is used to select a 
      projection.

      An axis of the parameters space is described by a two-elements
      vector. The first element indicates the number of the component
      or is -1 if the parameter is one of those of the LOSVD.
      The second element is the order number of the parameter in the 
      component or LOSVD; it is -1 for the weight.

      The user is prompted for information describing the axis.

 ARGUMENT:
          CMP  previously defined component

 RETURN VALUE:
          AXIS a 2 elements vector: code for the projection of the component  

 EXAMPLE:
               cmp = uly_ssp()
               axis = uly_cmp_select(cmp)

 AUTHOR:
               Mina Koleva

 HISTORY:
          2008/07/31 creation

(See pgm/uly_chimap.pro)


ULY_FIT

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

 PURPOSE:
               Fit a spectrum with a non-linear model

 USAGE:
     solution = uly_fit(signalLog,                                           
                        CMP=cmp,                                             
                        KMOMENT=kmoment, KGUESS=kguess, KFIX=kfix, KPEN=kpen, KLIM=klim,
                        ADEGREE=adegree,                                     
                        MDEGREE=mdegree, POLPEN=polpen,                      
                        /CLEAN, /QUIET,                                 
                        MODECVG=modecvg,
                        /ALL_SOLUTIONS)

 ARGUMENTS:
   signalLog: structure containing the spectrum of the object to be
       fitted. The models (see CMP) and the object have to be logarithmically
       rebinned. The WCS of the spectrum is read in the structure, whose tags
       are described in the documentation of ULY_SPECT_ALLOC.

 KEYWORDS:

   CMP
       Array describing the components of the model to fit. See the
       description below.

   KMOMENT: Order of the Gauss-Hermite moments to fit. If this keyword is 
       set to 2 then only [cz,sigma] are fitted. 
       Set this keyword to 4 to fit [h3,h4] and to 6 to fit [h3,h4,h5,h6]. 
       Note that in all cases the Gauss-Hermite moments are fitted 
       (nonlinearly) *together* with [cz,sigma]. 
       If KMOMENT=0 then only the continuum polynomial, the weights of the components
       and their coefficients are fitted.

   KGUESS: vector (up to 6 elements)
       [velStart,sigmaStart,h3,h4,h5,h6] with the initial estimate for the 
       cz and the cz dispersion in km/s, and of the Gauss-Hermite coefficients.
   
   KLIM: 2D floating array. The first dimension are the low/high bounds. and the second
       the parameter of the LOSVD (cz, sigma, h3 ,...)
       The limits on cz and sigma are in km/s.

   KFIX: vector of  zeros or ones (corresponds to "KGUESS"). 1 means
       that the corresponding LOSVD parameter is fixed during the minimization
       procedure. For example, to fix the velocity dispersion, specify
       kfix=[0,1]

   KPEN: This parameter biases the (h3,h4,...) measurements towards zero
       (Gaussian LOSVD) unless their inclusion significantly decreases the
       error in the fit. By default KPEN=0, meaning that the penalization is
       disabled. With a strictly positive value, the solution (including cz 
       and sigma]) will be less noisy. When using penalization, it is adivised
       to test the choice of KPEN with Monte-Carlo simulations. A value in the
       range 0.5 to 1.0 shall be a good starting guess. This keyword 
       corresponds to the parameter lambda in Cappellari & Emsellem (2004, 
       PASP 116, 138, Eqn. 9). 
       Note that the penalty depends on the *relative* change of the fit 
       residuals, so it is insensitive to proper scaling of the noise. A 
       nonzero KPEN can be safely used even without a reliable error spectrum,
       or with equal weighting for all pixels.
       The implementation of penalization was taken from the ppxf program
       by M. Cappellari.

   ADEGREE: degree of the *additive* Legendre polynomial used to correct the
       template continuum shape during the fit. Set ADEGREE = -1 not to 
       include any additive polynomial. By default, no additive term is used.
       

   MDEGREE: degree of the *multiplicative* Legendre polynomial 
       used to correct the continuum shape during the fit (default: 10). The
       zero degree multiplicative polynomial is always included in the fit as
       it corresponds to the weights assigned to the components.

   POLPEN
       Parameter to select only the significant terms of the multiplicative
       polynomial. See ULY_FIT_LIN for details.

   /CLEAN: set this keyword to iteratively detect and clip the outiers.
       See below the description of the clipping algorithm.
   
   /QUIET
       Set this keyword to suppress messages printed on the screen.

   /ALL_SOLUTIONS: If CMP contains more than a single guess for each free 
       parmeter (ie. a vector of guesses for at least parameter), all the 
       'local' solutions are returned in the form of an array.
       Otherwise, just the best solution is returned.
   MODECVG: 0,1 or 2
       when n_cmp>1 and md>0 the determination of the weights and of mulpol is
       not a linear process, and at present we need iteration to converge... 
       and unfortunately, our current approach is slow (we tried to accelerate
       it but we failed for the moment to obtain a stable solution).
       However, in most cases, the LM iteration will converge even if 
       ULY_FIT_LIN does not converge at each step.
       So, we are currently offering three options:
        MODECVG=0 (the default one), this is the fastest, but 
          it happens that the solution is missed
        MODECVG=1 (the convergence is achieved only once for each
          LM iteration, it is not reached for the derivatives
        MODECVG=2, uly_fit_lin always converge, but this is slow
       We are actively working at solving the problem and make something fast 
       and reliable.

 OUTPUT:
   solution:
     Output structure containing the solution of the fit. It can
     be printed/plotted by ULY_SOLUT_PRINT, ULY_SOLUT_TPLOT,
     ULY_SOLUT_TWRITE, ... Its detailed content is described later
     in this document.

     The solution structure may be passed to ULY_SOLUT_TPRINT, 
     ULY_SOLUT_PLOT, ULY_SOLUT_TWRITE, ...


 DESCRIPTION:
   Fit a spectrum with a linear combination of non-linear components, 
   convolved with a LOSVD. Multiplicative and additive Legendre
   polynomials can also be included in the model.

   The usage of ULY_FIT requires to specify the characteristics of the
   LOSVD function (number of free parameters), the degrees of the polynomials,
   and the 'description' of the model to fit.

   The model to fit is described by the CMP argument. Since the model
   is a linear combination of components, CMP is an array whose individual
   element is a structure describing one of these components.
   See the routine ULY_SSP for an example of how to define CMP.
   Other types of components may be defined by the user (need some 
   programming).

   The CMP array may contains vectors of guesses for some parameters.
   In this case, ULY_FIT will perform a local minimization for each
   possible combination of these guesses and return the best solution
   or the whole array of solutions if the keyword /ALL_SOLUTIONS is
   given.

   FITTING PROCEDURE:
   The 'non-linear' parameters of the components of the model are determined
   with the Levenberg-Marquart (LM) routine MPFIT implemented by C. Markwardt
   and the other parameters (weight of each components, coefficients of 
   the multiplicative and additive polynomials) are fitted linearly
   at each iteration of the LM process.

   LINE-OF-SIGHT VELOCITY DISTRIBUTION (LOSVD):
   The line-of-sight velocity distribution (LOSVD) is described by a
   Gaussian plus Gauss-Hermite expansion (V, sigma, h3, h4, h5, h6).
   The fit is performed in pixels space using the Penalized Pixel
   Fitting method described in Cappellari M., Emsellem E., 2004, 
   PASP, 116, 138.

   CLIPPING ALGORITHM:
   The goal is to exclude the outliers of the fit when the /CLEAN keyword
   is specified. This reduces the sensitivity of a fit to spikes or
   undesirable features due to an unperfect observation, treatment or 
   model.
   The principle is to re-iterate the fit after the outliers are 
   identified from the residuals and masked.
   After a fit, the most descrepant pixels are identified using a
   kappa x sigma detection limit (sigma is the standard deviation
   of the residuals, and kappa a numerical factor). Kappa is chosen
   as the lowest of 3,4,5 or 7 in order to find at maximum 3% of
   outliers. An additional condition is that an outlier cannot be
   explained by a small mismatch in wavelength (this is achieved by
   comparing the residuals with the gradients of the model; this is 
   particularly important if the model includes emission lines).
   The immediate neighbours of the outliers are also masked if they
   depart by 2 x sigma (this will for example detect some residuals of
   sky subtraction). Finally, the features detected as outliers are
   tracked until their absolute value decreases is above 1 sigma. This
   achieve a clean removal of emission lines that are not in the model.
   Up to 5 cleaning iterations are made if the algorithm does not converge.

 DESCRIPTION OF A COMPONENT OF THE MODEL TO FIT:
   This section of the documentation will be mostly useful to users
   intending to write their own model component. Some usual components
   are included in the package, and to use them the following
   information is not needed.

   The ULY_FIT program fit a linear combination of non-linear components
   convolved with a LOSVD and multiplied by a polynomial.
   Each component is described by a CMP structure, and therefore the
   complete fit is described by an array of CMP.

   See the functions ULY_SSP or ULY_TGM for practical examples
   of definition of a CMP.

   The CMP structure contains all the information about a component,
   like in particular the name of the functions to use to initialize
   and to evaluate the corresponding spectrum and the list and
   characteristics of its parameters. It is also used to return the
   results of the fit...

   The CMP array may be passed to ULYSS, ULY_FIT or other routines
 
   An individual component, element of CMP, is a structure made as:
       .name     : Name of the component (string)
                   This name must be unique for a given fit, the concatenation
                   of .name and .para.name must identify a free parameter.
       .descr    : Description of the component (string)
                   Essentially for display and information purpose.
       .init_fun : Name of the initialization routine (string)
                   The initialization routine has the following template:
                   cmp = <init_fun>(cmp, WAVERANGE=wave, VELSCALE=vels,
                                    QUIET=quiet)
                   where the input arguments are cmp, a single component
                   WAVERANGE=dblarr(2), the range of wavelength of the
                   generated model (must be the same as the observation),
                   VELSCALE the velocity scale (size of the pixel) in km/s,
                   and QUIET the verbosity control.
                   <init_fun> is called by the routine ULY_FIT_INIT
                   when the fit is performed.
                   <init_fun> normally creates .eval_data described below.
                   If no initialization is required this tag may be kept
                   as a null string.
       .init_data: data passed to init_fun (pointer)
       .eval_fun : name of the routine to evaluate the component (string)
                   The evaluation function has the template:
                   spectrum = <eval_fun>(*cmp.eval_data, (*cmp.para).value)
                   Where 'spectrum' the the array containing the spectrum 
                   of the component of the model.
                   *cmp.eval_data and (*cmp.para).value are described below.
                   For SSP models (computed with ULY_SSP_INTERP,
                   eval_fun='SSP' may be used instead of 
                   eval_fun='uly_ssp_interp' (slightly faster).
                   If the model can be evaluated as: spectrum=*cmp.eval_data
                   i. e. if there is no free parameter, eval_fun='STAR'
                   may be used.
       .eval_data: data passed to eval_fun (pointer)
                   Usually generated by the initialization routine
                   like for example a grid of models convolved by the
                   proper LSF that eval_fun will interpolate.
       .para     : description of the parameters (array of pointers)
                   Each free parameter of the model is described by the
                   structure whose members are:
            .name      : name of the parameter unique for a single component
            .unit      : unit of the parameter (display purpose)
            .guess     : (double) Starting value of the fit
            .fixed     : 0 if the parameter is free, 1 if it is fixed
            .limited   : 0 if no limit is set, 1 if limits are set
            .limits    : dble array [low, high] of bounds on the parameters
            .step      : (double) step for numerical derivation
            .value     : (double) final value of the parameter
            .error     : (double) uncertainty on value
            .dispf     : (string) indicate how to display the value
                         Empty if the parameters is directly printed
                         or 'exp' to print exp(value) and compute error
                         as err*exp(value)
       .start   : WCS of the component, starting wavelength
       .step    : WCS of the component, step 
       .npix    : WCS of the component, number of pixels
       .sampling: WCS of the component, sampling mode (0:linear, 1:log, 2:unused)
       .mask    : mask of pixels (array) good=1, bad=0
       .weight  : (double) Weight of the component, result of the fit
       .e_weight: (double) Error on .weight
       .l_weight: (double) light fraction of the weight
       .lim_weig: dble array [low, high] of bounds on the weights

 DESCRIPTION OF THE SOLUTION STRUCTURE:
   The solution structure returned by ULY_FIT has the following members:
      .TITLE      : Description of the fit (name of the fitted file)
      .HDR        : header as read from the analysed spectrum
      .START      : WCS of the spectrum, starting wavelength
      .STEP       : WCS of the spectrum, step in wavelength
      .SAMPLING   : WCS 0:Linear/1:log/2:irregular
      .DATA       : The input spectrum which is fitted
      .ERR        : The error spectrum 
      .BESTFIT    : spect structure containing the best fitting model
                    including the LOSVD convolution and add/mult polynomials
      .MASK       : Binary mask: 1: Fitted pixels, 0: Rejected pixels
      .DOF_FACTOR : Ratio (number of pixels/number of independent pixels)
      .CHISQ      : Reduced chi2
      .ADDCONT    : Array with additive continuum
      .MULCONT    : Array with multiplicative continuum
      .ADDCOEF    : Coefficients of the additive polynomial (if used)
      .MULCOEF    : Coefficients of the multiplicative polynomial (if used)
      .LOSVD      : Fitted parameters of the LOSVD
      .E_LOSVD    : Errors on the fitted LOSVD parameters
      .CMP        : Array describing the components of the model,
                    the fitted value of the parameters and their errors,
                    see above the description of the CMP structure.

 REQUIRED ROUTINES:
     MPFIT: by C.B. Markwardt from http://astrog.physics.wisc.edu/~craigm/idl/
     ROBUST_SIGMA: by H. Freudenreich from http://idlastro.gfsc.nasa.gov/

 HISTORY AND CREDITS:
    This program is part of the ULySS package, currently under development
    by ULYSS team (Ph. Prugniel, M. Koleva, A. Bouchard & Y. Wu) 
    ulyss@obs.univ-lyon1.fr

    The developments started from the ppxf program from Cappellari
    (http://www.strw.leidenuniv.nl/~mcappell/idl/ ; Cappellari &
    Emsellem (2004, PASP, 116, 138) ), based
    on  the Levenberg-Marquart routine, MPFIT from Craig Markwardt
    (http://astrog.physics.wisc.edu/~craigm/idl/fitting.html)
 
    The parametric minimisation on age/metallicity was started by
    I. Chilingarian, Obs. de Lyon & N. Bavouzet, Obs. de Paris.
    

(See pgm/uly_fit.pro)


ULY_FIT_INIT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
              ULY_FIT_INIT
 PURPOSE:
              Call the initialization function for each component of the fit
              
 USAGE:
              status = uly_fit_init(cmp, WAVERANGE=lamrange, 
                                         VELSCALE=velscale, QUIET=quiet)
 ARGUMENTS:
     cmp : The array describing the model to fit, see ULY_FIT.

 KEYWORDS:
     WAVERANGE : (Input 2 elements double precision array) 
                 Wavelength range, in Angstrom.
     VELSCALE  : (input) Size of the pixel in km/s.
     QUIET     : Set this keyword to suppress some informational messages.

 RETURN VALUE:
     status is an error status, 0 for a sucessful completion.

 DESCRIPTION:
     The model to fit is described in the cmp array that can be created
     by, e.g., ULY_SSP. Each element of this array is a structure describing 
     one component of the fit. One of the member of this structure is
     the name of the initialization function, and ULY_FIT executes these
     functions for each of the components.

     The initialization consists in operations that can be made once at
     the beginning to save computations at the time of the 'evaluation'.
     For example, the initialization may read a file, resample a model
     grid as the observation ...

     ULY_FIT_INIT must be called after reading the observation (because
     it needs to know the sampling and wavelength range) but before 
     executing the fitting procedure ULY_FIT.

 HISTORY:
              Philippe Prugniel, 2008/05 created

(See pgm/uly_fit_init.pro)


ULY_FIT_LIN

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
		ULY_FIT_LIN
 PURPOSE:
		Fit the linear coefficients and return the best fit

 USAGE:
    bestfit = uly_fit_lin(ADEGREE=adegree, 
                      PAR_LOSVD=par_losvd, CMP=cmp,         
                      SPECTRUM=SignalLog,                   
                      GOODPIXELS=goodPixels, 
                      VOFF=voff,                          
                      MPOLY=mpoly, ADDCONT=addcont,         
                      POLPEN=polpen [,/LUM_WEIGHT] [,/QUIET])

 DESCRIPTION:
    Evaluate the different components of the model to fit and convolve
    them with the LOSVD for a given set of the free parameters.
    Determine the optimal weight of each component and the coefficients
    of the multiplicative and additive continuum (linear fit).
    Return the best fitting model.
 
    This function is called at each step of the Levenberg-Marquart
    minimization performed in ULY_FIT to compute the values of the
    non-linear parameters of the components and LOSVD.

    For performance reasons, the large data arrays are passed through 
    commons (not as arguments).

 KEYWORDS:
               See also the documentation of uly_fit
   ADEGREE (input)
      Degree of additive polynomial, -1 if no additive polynomial
   POLPEN (input)
      Bias level of the multiplicative polynomial. This keyword can be 
      used to reduce the effect of insignificant terms of the multiplicative
      polynomial.
      Terms whose coefficients are smaller, in absolute value, than <polpen> 
      times their statistical error are amorted by the factor 
      (abs(coef)/(<polpen>*err))^2.
      This feature is active only if MDEGREE>0. <polpen>=2 seems a 
      reasonable choice.
      By default,  no bias is applied.
   PAR_LOSVD (input)
      Parameters of the LOSVD, array of 0 to 6 numbers ordered as: 
      [cz, sigma, h3, h4, h5, h6], cz and sigma are in pixels.
   SPECTRUM  (input)
      Structure containing the spectrum to analyse and its associated error.
      It is used to determine the weight of each pixel (.err) and to
      fit the multiplicative continuum (.data)
   GOODPIXELS (input)
      List of pixels to be used in the fit.
   VOFF (input)
      Velocity offset between the spectrum to analyse and the model. km/s.
   CMP       (Input & output)
      Array of components to fit (see documentation in ULY_FIT)
      In output CMP.WEIGHT is updated with the weight of each component 
      computed by this routine.
   MPOLY  (Input/output)
      multiplicative continuum Legendre polynomial
      structure {lmdegree, mpolcoefs, poly}
      .LMDEGREE (integer), Input, maximum degree of legendre polynomials.
         Unchanged in output.
      .MPOLCOEFS (double 1D array), LMDEGREE+1 terms.
         Output: updated values of the coefficients
         The input values of the coefficients are ignored.
      .POLY (1D array)
         Input: polynomial determined at a previous iterration
         Output: updated value of the polynomial (consistent with .MPOLCOEFS)
      Usually MPOLY is initialized by ULY_FIT, but if it is NULL in input,
      it is initialized to contain a degree 0 polynomial (scaling factor).
   ADDCONT (output)
      Additive polynomial (array).
   /LUM_WEIGHT
      Instruct to compute the luminosity weights and the errors on the
      weights.
   /QUIET
      Set this keyword to run silently.

 AUTHOR:
		Mina Koleva, Philippe Prugniel
               with credit to Michele Cappellari & Igor Chilingarian
               for initial development
 HISTORY:
    The principle of solving the linear dependences within the Levenberg-Marquart
    function evaluation is borrowed from M. Cappellari in his ppxf package.
    v.1.0      From early development by M. Cappelleri & I. Chilingarian
    v.2.0      Separated from the main program, Mina Koleva Sep 2005
    v.2.3      Changing the interpolation (improve performance): mk 2007/03/01
    v.3.0      Interpolating between different Mg/Fe: mk 2007/04/17
    v.4.0      Ph. Prugniel 2007/12/14: linear fit of mult pol. Cache Legendre
    v.5.0      Ph. Prugniel, 2008/05/27: general n-components fit
    v.6        Ph. Prugniel, 2011/02: Implement Tikhonov regularisation
    v.7        Ph. Prugniel, 2015/09: Major debugging and improvements

(See pgm/uly_fit_lin.pro)


ULY_LSF

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

 PURPOSE:
              Determine the line-spread function (LSF)

 USAGE:
                uly_lsf, <spectrum>, <cmp>, <width>, <step>,   $
                            FILE_OUT=file_out, /PLOT, /QUIET, /CLEAN, $
                            KMOMENT=<kmoment>, DG=<dg>, DL=<dl>,      $
                            KFIX=<kfix>, KPEN=<kpen>,                 $
                            MDEGREE=<mdegree>, ADEGREE=<adegree>,     $
                            VELSCALE=<velscale>

 ARGUMENTS:
     <spectrum>       Filename or spectrum structure containing the spectrum
                      to be analysed for the LSF.
     <cmp>            Component structure containing the reference high
                      resolution spectrum. The LSF of <spectrum> will be
                      determined relatively to <cmp>
                      In the simplest case, <cmp> can be a reference spectrum
                      loaded with ULY_STAR, or it can be an interpolated
                      stellar model (see ULY_TGM) or any other model, or even
                      an array of several cmp.
                      During the analysis, eventual non-linear parameters
                      will be adjusted.
     <width>, <step>  scalars, [Angstrom] 
                      The LSF is measured in a succession of chunks of width 
                      <width> separated by <step>.
         
 KEYWORDS:
     FILE_OUT         Name of the output file.
                      Defaulted to 'output.lsf'
     KMOMENT, DG, DL, KFIX, KPEN
                      LOSVD parameters passed to ULySS.
                      They are used to determine which terms of the LSF to fit.
     MDEGREE, ADEGREE, VELSCALE
                      Parameters passed to ULySS.
                      Remember that MDEGREE (and ADEGREE) apply to the (small)
                      chunks of spectra of width <width>, so, this parameters
                      should be smaller than when the whole spectrum is
                      analysed at once.
     PLOT             Set this keyword if you want to display the
                      losvd fit using the program ULY_SOLUT_SPLOT.
     CLEAN
                      Set this keyword to perform a kappa-sigma clipping
                      of the outliers.
     QUIET            Verbosity control

 EXAMPLE:
   In the following example, we determine the relative LSF between a
   spectrum to analyse and a model extracted from a grid.
   Then we smooth this LSF and use it to analyse the spectrum.

   filetest = uly_root+'/data/VazMiles_z-0.40t07.94.fits.fits'
   model = uly_ssp_extr(filetest, uly_root+'/models/PHR_Elodie31.fits' ,[6000.,-0.4,0.], SIG=30)
   cmp = uly_star(model)
   uly_lsf, filetest, cmp, 200, 100, FIL='vaz.lsf', /QUIET
   heap_free, cmp
   uly_lsf_plot, 'vaz.lsf' 
   uly_lsf_smooth, 'vaz.lsf', 'vazs.lsf'
   uly_lsf_plot, 'vazs.lsf' 
   cmp = uly_ssp(LSF='vazs.lsf')
   ulyss, filetest, cmp, /PLOT

 LSF ANALYSIS AND INJECTION:
 
   A spectrum is characterized by its line spread function, LSF, ie. the 
   instrumental broadening of the spectral lines. This is the analog of the 
   PSF for images. The LSF can be modeled by a Gaussian or more generally 
   by a Gauss-Hermite expansion of a Gaussian.
   
   For an observation, the LSF depends on the spectrograph and on the slit, 
   it generally changes with the wavelength and, in the case of 2 or 3D 
   spectra, with the position in the field. On the other side, the model
   used to analyse this observation has also a finite resolution, i.e.
   has a specific LSF hopefully finer than the one of the observation.
   Therefore to analyse an observation we have to take into account the
   relative LSF of the observation with respect to the model. This is of 
   a primordial importance when studying the internal kinematics (physical 
   broadening of the lines) of an astronomical source.  
   
   The process to properly take the LSF into consideration consists in 
   two phases: (i) The determination of the relative LSF and (ii) its 
   injection into the model, so that the result is comparable to an
   observed spectrum.  
   
   Choice of the LSF standard
   
   In standard cases, the LSF can be considered as stable for a set of 
   observations, for example for an observing run, or for a given setup of 
   an instrument. In this case it is possible to determine it once using 
   the calibration and standard stars observations. There are
   different ways to determine the LSF.
   
   1) Using the arc spectrum used for the wavelength calibration. 
   The profile of the lines can be determined at different wavelength 
   and position in the field (sigma, h3, h4). 
   This method is currently not implemented in ULySS and requires 
   some precaution because of blends of the lines and limited sampling.  
   
   2) Using a twilight spectrum, and compare it with the solar spectrum 
   having the same LSF as the model. The input aperture is uniformly
   illuminated. This is the preferred method.
   
   3) Using a spectrum from a star for which a spectrum with the same LSF 
   as the model is available. The critical aspect of this method is 
   to be sure that the stellar light is uniformly distributed over
   then entrance aperture or that the resultion is not determined by
   the size and shape of the entrance aperture.
   
   4) Using a spectrum of a star of known atmospheric parameter,
   and analyse it with the output of a library interpolator. Or use a
   spectrum of a star with unknown atmospheric parameters and determine
   first these parameters with ULySS (see ULY_TGM).
   
   Finally, if no stellar spectrum is available, the analysis can be done 
   with an observation of a galaxy and the internal kinematics of all 
   objects in the series will be determined relatively to this reference. 
   (choose the galaxy with the smallest velocity dispersion or decrease 
   the width of the measured LSF by a fixed amount (use the keyword SIGMA).

   Caveat: To maximize the flux efficiency, some setups use a wide input 
   aperture (slit) that may be eventually wider than the seeing and that 
   the intrinsic resolution of the spectrograph. The result is that in 
   case of good seeing the object may be resolved in the slit, and the 
   measured broadening does not reflect the physical broadening. This is 
   a poor practice, and such observations should not be used to study 
   the internal kinematics.  
   
   Analysis of the LSF 

   The analysis of the LSF is made with the program: ULY_LSF
   which produce an ASCII file describing the LSF (see the
   Description section in this article). 
   This file may be viewed with ULY_LSF_PLOT, or smoothed with ULY_LSF_SMOOTH.

   Injection of the LSF 
 
   The LSF injection is made by: ULY_SPECT_LSFCONVOL, normally called when
   a component of the model is initialized or evaluated.
   The principle of the injection of the LSF in the model is briefly 
   introduced in Koleva et al. 2008.

 HISTORY:
   Mina Koleva,       2008/03/11, created
   Yue WU,            2009/03/05, updated
   Philippe Prugniel, 2015/08/10, updated

(See pgm/uly_lsf.pro)


ULY_LSF_PLOT

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

 PURPOSE: 
                 Plot a LSF file

 USAGE:         
                 uly_lsf_plot, <lsf_file> [, CONNECT=color][, /OVERPLOT]
                               [, XTITLE=xtitle][, YSTYLE=ystyle][, TITLE=title]
                               [, YMODE=ymode]
                               [, WAVERANGE=<wr>] [, VRANGE=vrange][, SRANGE=srange][, PLOT_VAR=<plot_var>]

 DESCRIPTION:
     Plot the relative velocity shift and instrumental velocity dispersion
     as a function of the wavelength.
     LSF (line-spread function) files are created by ULY_LSF.
       
 ARGUMENTS:
   <lsf_file>: 
                 Name of the file containing the LSF.

 KEYWORDS:
   CONNECT:
                 Set this keyword to a color name to connect the data
                 points. Example: connect='Red'
                 Default is not to connect the data points.
                 
   PLOT_VAR:
                 An input structure containing all the plot variables.
                 This structure is returned by ULY_PLOT_INIT.

   /OVERPLOT:
                 Make plot over an existing one.

   XTITLE:
                 See the IDL documentation on "Graphic Keywords". 
                 This keyword  is passed to the PLOT commands, it is defaulted to "Wavelength, A".

   YMODE:
                 Quantities represented on the Y axes:
                 0 : cz and sigma in km/s
                 1 : shift and FWHM in Angstrom 

   YSTYLE:
                 See the IDL documantation on "Graphic Keywords". 
                 This keyword  is passed to the PLOT commands, it is defaulted to 16.

   TITLE:
                 Title of the plot.

   /XLOG /YLOG
                 Plot X (resp. Y) axis in logarithmic scale.

   VRANGE SRANGE
                 Y-axis range for respectively the cz and the sigma
                 panels
   WAVERANGE        	
                 Wavelength range to be plotted
   _EXTRA 
                 including all the keyword present in ULY_PLOT_INIT

 EXAMPLE:
     Plot a LSF with blue dots, and overplot a connected black line
                 uly_lsf_plot, 'lsf.txt'
                 uly_lsf_plot, 'lsfs.txt', /OVER, LINECOL='black', PSYM=0


 AUTHOR:
         Mina Koleva, Philippe Prugniel, Antoine Bouchard 

(See pgm/uly_lsf_plot.pro)


ULY_LSF_SMOOTH

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

 PURPOSE:        
                 Smooth a LSF file

 USAGE:       
                 uly_lsf_smooth, <lsf_file>, <outfile>, [VDEG=<vdeg>], [SDEG=<sdeg>]

 ARGUMENTS:
   <lsf_file>:   Name of the file containing the LSF

   <outfile>:    Name of the file containing the smoothed LSF

 KEYWORDS:
    VDEG:        degree of polynomial, used to smooth the velocity, default=3
    SDEG:        degree of polynomial, used to smooth the dispersion, default=3
    H3DEG:       degree of polynomial, used to smooth h3, default=3
    H4DEG:       degree of polynomial, used to smooth h4, default=3

 DESCRIPTION:
     Fit the LSF determined by ULY_LSF (cz vs. wave) and (sigma vs. wave)
     respectively with degrees 3 and 2 polynomials and return the
     fitted values as a 'smoothed' LSF.

     As it is, this program is obviously a stub on which to build the 
     smoothing. We may make a more elaborated version in the future.

 DEPENDENCE:
     ULY_LSF_PLOT, READCOL (by W. Landsman, astrolib)

 AUTHOR:         Mina Koleva, Philippe Prugniel

(See pgm/uly_lsf_smooth.pro)


ULY_PLOT_INIT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:         ULY_PLOT_INIT
 
 PURPOSE:      Initialize plotting variables

 USAGE:
		uly_plot = uly_plot_init([  XSIZE=xsize]	   $
                                        [, YSIZE=ysize]	   $
                                        [, BGCOLOR=bgcolor]       $
                                        [, AXISCOLOR=axiscolor]   $
                                        [, LINECOLOR=linecolor]   $
                                        [, MODELCOLOR=modelcolor] $
                                        [, POLYCOLOR=polycolor]   $
                                        [, RESIDCOLOR=residcolor] $
                                        [, SIGMACOLOR=sigmacolor] $
                                        [, PSYM=psym]             $
                                        [, MODELPSYM=modelpsym]   $
                                        [, POLYPSYM=polypsym]     $
                                        [, RESIDPSYM=residpsym]   $
                                        [, SIGMAPSYM=sigmapsym]   $
                                        [, LINESTYLE=linestyle]   $
                                        [, MODELSTYLE=modelstyle] $
                                        [, POLYSTYLE=polystyle]   $
                                        [, RESIDSTYLE=residstyle] $
                                        [, SIGMASTYLE=sigmastyle] $
                                        [, LINETHICK=linethick]   $
                                        [, MODELTHICK=modelthick] $
                                        [, POLYTHICK=polythick]   $
                                        [, RESIDTHICK=residthick] $
                                        [, SIGMATHICK=sigmathick] $
                                        [, CHARSIZE=charsize]     $
                                        [, CHARTHICK=charthick]   $
                                        [, HALFTONECT=halftonect] $
                                        [, /HIDEHALFTONE]         $
                                        [, /HIDECONTOUR]          $
                                        [, /SHOWSIGMA]            $
                                        [, /HIDEMINIMA]           

 DESCRIPTION:
		Creates a structure containing all plotting variables, such
 		as colors, character sizes, etc.
		This task is called by the plotting tasks directly so there
		is no need to explicitly call it unless you want to change
		the plotting behaviour.
               The list of color names can be obtained as: 
                       print, FSC_COLOR(/NAMES)
 
 ARGUMENTS:
		XSIZE, YSIZE
			If no plotting window exists, create a window of this
			size, in pixels. If a plotting window already
			exists, these keywords have no effect, the
			opened window will be used. 

 		BGCOLOR
                       Color index (integer) or name (character string).
			Background color, default is 'White'.

		AXISCOLOR
                       Color index (integer) or name (character string).
			Color for the axes and decoration, default is 'Black'.

		LINECOLOR
                       Color index (integer), or name (character string).
			Main plotting line color, default is 'Blue'.

		MODELCOLOR, POLYCOLOR, RESIDCOLOR, and SIGMACOLOR
			Plotting colors for the model, polynomial, residual
			and 1 sigma level respectively. 
			Defaults are: Blue for model, red for polynomial,
			black for residual, green for sigma.

               PSYM, MODELPSYM, POLYPSYM, RESIDPSYM, SIGMAPSYM
			Plotting symbols for the line, model, polynomial, residual
			and 1 sigma level respectively.
			Defaults are 0.

		LINESTYLE, MODELSTYLE, POLYSTYLE, RESIDSTYLE, SIGMASTYLE
			Line style parameter for data, model, polynomial,
			residual and sigma level respectively, default is 0.
                       0	Solid
                       1	Dotted
                       2	Dashed
                       3	Dash Dot
                       4	Dash Dot Dot
                       5	Long Dashes 

		LINETHICK, MODELTHICK, POLYTHICK, RESIDTHICK, SIGMATHICK
			Line thickness parameter for data, model, polynomial,
			residual and sigma level respectively, default is 1.

		CHARSIZE
			Axis character size, default is 1.4.
        
               CHARTHICK
                       Axis character thick, default is 1.

		HALFTONECT
			Color table for halftone overlay in Chi2 maps.
			Default is 3 (Red Temperature). Use XLOADCT to get
			all available color tables. 

		/HIDEHALFTONE
			Set this keyword to hide the halftone overlay in
			Chi2 maps.

		/HIDECONTOUR
			Set this keyword to hide contour levels in Chi2
			maps.

		/SHOWSIGMA
			Set this keyword to show sigma levels.

		/HIDEMINIMA
			Set this keyword to hide the local and global
			minima in Chi2 maps.

 EXAMPLE:
	
		Define where to get the data:
			galaxy = uly_root+'/data/VazMiles_z-0.40t07.94.fits'
		
		Initialize the plotting variables and setting a green on
		red plot and log y axis:
			plot_var = uly_plot_init(linecolor='Blue', bgcolor='Red', /ylog)

		Set the linestyle to be hashed:
			plot_var.linestyle=2

		Set the axis color to be purple.
			plot_var.axiscolor=FSC_Color('Purple')

		Make the plot.
			uly_spect_plot, galaxy, plot_var=plot_var
 		
		Overplot a convolved version of that plot, in blue.
			plot_var.linecolor=FSC_Color('Green')
			plot_var.linestyle=0
			uly_spect_plot, galaxy, conv=[10000., 300., 0., 0.], /overplot, plot_var=plot_var

		Contemplate a truly artistic choice of color!

 DEPENDENCE:   fcs_color.pro by David Fanning

 AUTHOR:
 		Antoine Bouchard
 
 HISTORY:
		2008/08/15	Creation
 -
 CATEGORY:     ULY

(See pgm/uly_plot_init.pro)


ULY_PLOT_SAVE

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

 PURPOSE:       Make a hardcopy of a plot.
 
 USAGE:
                uly_plot_save, <filename>
                [, /JPG]
                [, /PNG]
                [, /TIFF]

 DESCRIPTION:
                After making a plot, use this command to keep a
                hardcopy of it.

 ARGUMENTS:
    <filename>  Input
                Name of the file to be writing.

 KEYWORDS:
    /JPG, /PNG, /TIFF
                Selects the output format. Default is JPG.

 HISTORY:        
    Creation    Antoine Bouchard, 5/09/2008

(See pgm/uly_plot_save.pro)


ULY_SOLUT_SPLOT

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

 PURPOSE:
               Plot the result of a fit done with ULY_FIT

 USAGE:
	        uly_solut_splot, <solution>
                       [, WAVERANGE=<waverange>]
                       [, SMOOTH_RESID=<smooth_resid>]
                       [, SMOOTH_FLUX=<smooth_flux>]
                       [, RESI_YR=<resi_yr>]
                       [, FLUX_YR=<flux_yr>]
                       [, SCAN=<scan>]
                       [, PLOT_VAR=<plot_var>]
                       [, ...extra keywords]

 DESCRIPTION:
               This task plots the result of a fit performed by ULY_FIT. It
               is also called by ULYSS if the /PLOT keyword is set. The
               plot is either on an xwindow or in a postscript file. 

 ARGUMENTS:
   <solution>	Input.
               The <solution> structure is part of the normal output from
               the ULY_FIT task. Alternatively, if ULY_FIT was used to
               generate a file containing the output, then the file name
               can also be given here. 
               A <solution> structure is also outputed by the
               ULY_SOLUT_SREAD task. 

 KEYWORDS:
   WAVERANGE:
               Array of one or two values specifying the wavelength range
               to display (values in Angstrom). By default the full range is
               displayed. If a single value is specified, it is taken as
               the beginning of the range and the interval extends to
               the end of the available wavelength range.

   SMOOTH_RESID:
               Velocity dispersion used to smooth the residuals (convolve),
               in km/s. No smoothing by default.

   SMOOTH_FLUX:
               Velocity dispersion used to smooth the flux (convolve),
               in km/s. No smoothing by default.

   RESI_YR:
               Scalar, or two-elements array. Define the Y range for the
               residuals panel. If a scalar or one-element array is 
               specified, it is the semi-amplitude of the range, centered
               on zero.

   FLUX_YR:
               Define the flux range for the flux panel.

   SCAN:       Choose which scan to plot in case of 2D file, by
               default plot the first dim.

   /XLOG /YLOG
               Plot X (resp. Y) axis in logarithmic scale.

   TITLE:
               Title of the plot.
   PLOT_VAR:
               An input structure containing all plot variables.
               This structure is returned by ULY_PLOT_INIT.

   ...Extra keywords:
               If PLOT_VAR is undefined, all extra keywords are
               passed to ULY_PLOT_INIT.
 
 EXAMPLE:
      The following example shows how to prepare a publication quality
      figure in postscript format (this example produces an acceptable
      result for a single-column graphic in a journal, eg. MNRAS).

      !P.FONT = 0
      !P.THICK = 1.5
      !X.THICK = 1.5
      !Y.THICK = 1.5
      set_plot,'ps'
      device, FILENAME='fig.ps', /COLOR, FONT_SIZE=6, XSIZE=9.5, YSIZE=5, $
              /TIMES, /ENCAPSUL
      uly_solut_splot, 'output'
      device, /CLOSE
      set_plot, 'x'

      The device command allows to set the size, position, font ...
      of the plot

 AUTHOR:
               Antoine Bouchard
 HISTORY:
               2008/02/05

(See pgm/uly_solut_splot.pro)


ULY_SOLUT_SREAD

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

 PURPOSE:
                 Read a solution file written by ULY_SOLUT_SWRITE

 USAGE:
	          SOLUTION = uly_solut_sread(<solut_file>[, STATUS=<status>])

 ARGUMENT:
   <solut_file>: Name of the FITS file containing the solution structure.
                                                            
 KEYWORD:
   [STATUS=<status>]:  
	          Returned status code. This code is either 0 for OK or an
	          error number.
                                                            
 OUTPUT:
   SOLUTION:
	          Solution structure containing the results of a previous fit
	          that has been saved on disk in the form of a FITS file.

 DESCRIPTION:
   The solution is the output from ULY_FIT, and it written by 
   ULY_SOLUT_SWRITE.

   The solut FITS file is in the SDSS style (see ULY_SPECT_READ). It
   consists in a image-type array of dimension 2. Thefirst axis is
   the wavelength described by a standard WCS. The second axis is described
   by the ARRAYi keyword series (ARRAY1 describe the first scan ...):
           ARRAY1             'DATA    ' 
           ARRAY2             'ERROR   ' 
           ARRAY3             'BESTFIT ' 
           ARRAY4   'MULTIPLICATIVE CONTINUUM' 
           ARRAY5   'ADDITIVE CONTINUUM' 
           ARRAY6             'MASK    ' 1:good, 0:bad
  
   The format of the output FITS file must be described here.

 AUTHORS:
                 Antoine Bouchard, Philippe Prugniel

 HISTORY:
                 2008/02/05

(See pgm/uly_solut_sread.pro)


ULY_SOLUT_SWRITE

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

 PURPOSE:
      Save the fit solution structure returned by ULY_FIT in a FITS file

 USAGE:
		  uly_solut_swrite, <SOLUTION>, <FILE_OUT> [,STATUS=status]

 ARGUMENTS:
   <SOLUTION>:  
		  Structure created by ULY_FIT containing the fitting results.

   <FILE_OUT>:  
		  Name of the FITS file where the solution is saved.
                                                            
 KEYWORD:
   [STATUS=status]:  
	          Returned status code. This code is either 0 for OK or an
	          error number.

 DESCRIPTION:
      A solut structure produced by ULY_FIT contains the solution of the
      it as tabular data (handled by ULY_SOLUT_TREAD / ULY_SOLUT_TWRITE)
      and as FITS data (original spectrum, best fit, multiplicative
      polynomial...) handled by ULY_SOLUT_SREAD and the present routine.

 KNOWN BUGS:
      This program cannot save 2d or 3d fits files

 HISTORY:
                 Mina Koleva, 24/02/2006, created

(See pgm/uly_solut_swrite.pro)


ULY_SOLUT_TPLOT

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

 PURPOSE:
                 Plot a result file of ULYSS
 
 USAGE:
                 uly_solut_tplot, <filename>[, PS=ps]
                                 [, SKIPLINE=skipline][, NUMLINE=numline]
                                 [, XAXIS=xaxis][, YAXIS=yaxis]
                                 [, XERROR=xerror][, YERROR=yerror]
                                 [, XRANGE=xrange][, YRANGE=yrange]
                                 [, /XLOG][, /YLOG]
                                 [, /CVG]
                                 [, HISTOGRAM=nbins]
                                 [, TITLE=title]
                                 [, QUIET=quiet]
                                 [, /OVERPLOT]

 ARGUMENT:
   <filename>    Filename or solut structure.

 KEYWORDS:
   PS            Set this keyword to generate Postscript output, otherwise
                 the procedure makes a X window plot.

   SKIPLINE      Number of lines to skip at the beginning of the .res file.
                 By default, read from the first line.

   NUMLINE       Number of lines to read from the .res file. By default
                 read the entire file.

   XAXIS YAXIS   Description of X & Y-Axes. 
                 These keywords can be either an integer number or arrays
                 of two integers describing the field number. 
                 When a single value is given, 0 is for the row index,
                 and fields in the file are numbered from 1. Each field usually
                 consists in three columns (value, error and guess)
                 or (weight, weight error and light-fraction).
                 When a 2-integers array is given, they are the "coordinates"
                 of a free parameter, as returned by ULY_CMP_SELECT.
                 If any of XAXIS or YAXIS is not given, ULY_CMP_SELECT is 
                 called to select the corresponding axis or axes.

   /XERROR /YERROR 
                 Instruct to respectively plot error bars for X-, Y-  or
                 both axes.

   XRANGE YRANGE
                 Two elements arrays specifying the range for respectively
                 the X and Y axes.

   /XLOG /YLOG
                 Plot X (resp. Y) axis in logarithmic scale.

   /CVG          Connect with vectors the guesses with the solutions
                 (convergence map).

   HISTOGRAM     Make an histogram of the column X.
                 If given the keywords XERROR, YERROR and CVG are
                 ignored. The value of HISTOGRAM is the number of bins
                 to use to build the histogram.

   TITLE:        Title of the plot.

   /QUIET        Set this keyword to eliminate information printed on
                 the terminal.

   /OVERPLOT     Overplots the result on an existing plot window.

 OUTPUT:

   STD_X, STD_Y  Set these keywords to a variable which will receive
                 the standard deviation of X,Y arrays

 DESCRIPTION:
     This program reads a .res file produced by ULYSS, and produces a scatter
     plot of one column versus another one or histogram of one column.
     Error bars can be optionally drawn on any or both axes.

     Vectors linking the guess to the solution can be shown with the keyword
     /CVG. This modes allows to study the convergence (these graphics are
     called "convergence maps"), for example to assess the sensitivity to
     the guesses and give an idea of the convergence basin.

 EXAMPLES:
   
 AUTHOR:
                 The author in UNKNOWN (probably Mina Koleva)
                 Modified by Philippe Prugniel, 2008/08/03

(See pgm/uly_solut_tplot.pro)


ULY_SOLUT_TPRINT

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

 PURPOSE:
                 Print the solution of a fit

 USAGE:      
                 uly_solut_tprint, solution     

 ARGUMENT:
   solution:     Solut structure (or array of solut) or name of a file
                 containing the solution(s)
                                                            
 OUTPUT:
                 Solut structure

 AUTHOR:
                 Mina Koleva

 HISTORY:
                 2008/02/05

(See pgm/uly_solut_tprint.pro)


ULY_SOLUT_TREAD

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

 PURPOSE:
                 Read the solution of a fit from a .res file

 USAGE:
                 solut = uly_solut_tread(<file>, STATUS=<status>)

 ARGUMENT:
   <file>:       Name of the ASCII file from where to read the solution,
                 without the '.res' extention.

 KEYWORD:
   STATUS:       Returned status code, 0=OK, other value=error
                                                            
 OUTPUT:
   solut:        Solution structure.

 AUTHOR:
                 Mina Koleva

 HISTORY:
                 2008/02/05

(See pgm/uly_solut_tread.pro)


ULY_SOLUT_TWRITE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
                 ULY_SOLUT_TWRITE
 PURPOSE:
                 Save the solution of a fit to an ascii file
 USAGE:
                 uly_solut_twrite, <solution>, <filename> [, HEAD='<command>']

 ARGUMENTS:
   <solution>:   solut structure (or array) containing the solution(s).
                 If <solution> is undefined, write only the header.
   <filename>:   Name of the file where <solution> will be saved.
                                                            
 KEYWORDS:
    HEAD         Character string to write as header or comment. It may
                 contain the command that generated <solution>.

 AUTHOR:
                 Mina Koleva
 HISTORY:
                 2008/02/05, MK, created.

(See pgm/uly_solut_twrite.pro)


ULY_SPECT_ALLOC, ULY_SPECT_FREE

[Previous Routine] [Next Routine] [List of Routines]
 NAME:           
                 ULY_SPECT_ALLOC, ULY_SPECT_FREE

 PURPOSE:       
                 Allocate/free a spectrum structure

 USAGE:
                 Spec = uly_spect_alloc[, TITLE=title][, DATA=data][, HEADER=header] 
                                       [, START=start][, STEP=step][, SAMPLING=sampling] 
                                       [, WAVELEN=wavelen][, ERR=err][, GOODPIX=goodpix] 
                                       [, DOF_FACTOR=dof_factor]
                                       [, SPECTRUM=spectrum]

                 uly_spect_free, Spec

 KEYWORDS:
   TITLE:        String describing the spectrum data

   DATA:         Data array

   HEADER:       Header (FITS structure)

   START:        Wavelength of the first pixel (relevant if sampling=0/1)

   STEP:         Step between 2 pixels (relevant if sampling=0/1)

   SAMPLING:     Sampling mode (0: linear, 1: logarithmic, 2: wavelengths list)

   WAVELEN:      Wavelength array, relevant if sampling=2

   ERR:          Error spectrum

   GOODPIX:      Good pixels list

   DOF_FACTOR:   Degree of freedom factor. Ratio between the actual
                 number of pixels and the number of independent measurements
                 (i.e. pixels on the detector). This parameter increases
                 when the spectrum is rebinned to smaller pixels.

   SPECTRUM:     Spectrum structure, initialize the new structure with
                 the content of this input variable.

 DESCRIPTION:
     Allocate/free a structure for all the spectra with linear or log 
     (i.e. linear in velocity) wavelength scaling or with explicit wavelength
     array.

     The different optional keywords that may be passed to this routine
     indicate how to initialize the structure.

     ULY_SPECT_ALLOC defines an anonymous structure containing the
     following tags:
     .title      string
                 Title                    
     .hdr        Array of character strings
                 FITS style header
     .data       integer, real or double precision array
                 Pointer on Array of the values of the flux  
     .err        integer, real or double precision array
                 Error spectrum
     .wavelen    Array of double
                 Used only if 'sampling'=2
     .goodpix    integer array
                 List of valid pixels
     .start      double precision
                 Wavelength of the centre of the first pixel
                 If 'sampling'=0, wavelength in Angstrom
                 If 'sampling'=1, log(wavelength)  (natural log)
     .step       double precision
                 Wavelength step between two pixels 
                 If 'sampling'=0, in Angstrom
                 If 'sampling'=1, logarithmic step
     .sampling   integer
                 Type of sampling scale
                 0 for linear in wavelength
                 1 for logarithmic scale  
                 2 for uneven sampling. Wavelength listed in 'wavelen'
     .dof_factor Rebinning factor

 SEE ALSO:    ULY_SPECT_GET

 AUTHOR:
      Martin France, Mina Koleva, Philippe Prugniel

(See pgm/uly_spect_alloc.pro)


ULY_SPECT_EXTRACT

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

 PURPOSE:   Extract part of a spectrum

 USAGE:
            SignalExtr = uly_spect_extract(SignalIn[, ONED=pos] 
                        [, WAVERANGE=waverange][,/OVERWRITE][,STATUS=status])
 ARGUMENTS:
     SignalIn  input data structure (spectrum)

 INPUT KEYWORD:
     ONED   Position of a 1D scan to extract from the file
            Scalar or array giving the position of the scan to extract
            along each axis after the first.

     WAVERANGE A 1 or 2 element array specifying the wavelength region to 
            extract. It must be ordered [low,high]. If only one element
            is given, it specifies the minimum wavelength to extract.

     OVERWRITE Set this keyword if SignalExtr is the same variable as
            SignalIn to prevent a memory leak

 RETURN VALUE:
     1D extracted spectrum (spect structure, see uly_spect_alloc)

 OUTPUT KEYWORD:
     STATUS=status
        status code: non-null in case of error

 DESCRIPTION:
     Extract part of a spectrum and return a 'spect' structure.

     Two options may be specified separately or together:
     - ONED is used to extract a 1D spectrum from a 2D dataset,
            like for example a long-slit spectrum.
            If the specified position is invalid, an informational
            message is issued, status is set to 1, and the routine
            returns -1.
     - WAVERANGE is used to extract a wavelength region. 
            The output spectrum is cut to the largest range containing
            the specified limits.
            If the specified value is not a 1 or 2 elements array, or if
            the specification has no intersection the the actual
            range, and informational message is issued, status is set
            to 1, and -1 is returned.

     The input data must be a 'spectrum structure', see ULY_SPECT_ALLOC.

 HISTORY:    Ph. Prugniel, 2008/01/31, created

(See pgm/uly_spect_extract.pro)


ULY_SPECT_GET

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

 PURPOSE:
   	Retrieve information from a spectrum structure.

 USAGE:
            	info = uly_spect_get(SignalIn
                                       [,/WAVERANGE]   
                                       [,/GOODPIX] 
                                       [,/HDR]
                                       [,/MASK]
                                       [,/VALID], 
                                       [STATUS=status])

 INPUT:
   SignalIn:
		Input data structure (spectrum)

 KEYWORD:
     Only one keyword is processed, according to the following priority.
     If no keyword is provided, the task assumes /VALID .

   [/WAVERANGE]:
		Returns a 2 elements double precision array giving the
		wavelength range.

   [/GOODPIX]:
        	Returns the goodpixels from the signal structre, if not set
		the task assumes all pixels are good
     
   [/HDR]:
        	Returns the FITS header of the input file, if it exists. If
		not it returns an empty string. 

   [/MASK]:
        	Returns a byte array containing the pixel mask (1 for good
		pixels, 0 for bad).
		The mask has the same length as the spectrum vector.
               If the input spectrum structure does not contains a good pixels list, 
               it is assumed that all the pixels are good.

   [/VALID]:
        	Returns a boolean: 
			0 if SignalIn is not a valid spectrum structure;
                       1 if SignalIn it is a valid structure

   [STATUS=status]
        	Returnes status code: 0 in case of success, 1 otherwise.

 RETURN VALUE:	
   INFO:
		See the description of each keyword for a description of
		the return values. In the case of an error, the return
		value is -1.

 DESCRIPTION:
     		The input data must be a 'spectrum structure', see
		ULY_SPECT_ALLOC for more information. 
		This task allows to retrieve various information about the
		structure.

 HISTORY:    
		Ph. Prugniel, 2008/01/31, created

(See pgm/uly_spect_get.pro)


ULY_SPECT_LINREBIN

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

 PURPOSE:   
                 Rebin a spectrum in linear wavelength scale

 USAGE:     
                 spect = uly_spect_linrebin(<SignalIn>, <step>)

 ARGUMENTS:
   <SignalIn>:   Input data structure (spectrum)

   <Step>:       Size of each pixel in Angstrom for the output data

 KEYWORDS:
   WAVERANGE     Input scalar or 2-elements vector. Wavelength range.
                 If a single value s passed, it is interpreted as the
                 start of the wavelength range.
                 By default, use the current range.

   FLUX_CONSERVE Input boolean.
                 Set this keyword to skip the intensity correction
                 for the change of the local pixel size.
                 If flux is conserved, intensity is not; by default
                 intensity is conserved.

   EXACT         Input boolean.
                 Specify that the output must match exactly the WCS
                 specified by <waverange> and <vsc>. Otherwise approximations
                 can be made to avoid shifts by small fractions of pixels.

   OVERWRITE     Input boolean.
                 Set this keyword if input and output spect are the
                 same variable as to prevent a memory leak

 OUTPUT:
                 Spectrum structure containing the rebinned data

 DESCRIPTION:
     This routine performs rigorously a rebinning into linearly
     spaced wavelength points. The algorithm is similar to ULY_STECT_LOGREBIN.

     The input data must be a 'spectrum structure' (see ULY_SPECT_ALLOC), 
     and the data can be sampled linearly, in log or at explicit wavelength.

     If <step> is initialized in input, this value will be used to rebin
     the input spectrum; otherwise this step is computed in order to keep 
     the same number of pixels in output as in input,the computed
     value is returned in <step>.

     The error spectrum and pixel mask, if present in (SignalIn) are
     also transformed in accordance with the signal. 

     If the data and error arrays contained in (SignalIn) have two dimensions,
     each line is rebinned similarly. 

 REQUIRED ROUTINES:  
                 XREBIN.PRO

 HISTORY:        Mina Koleva, 2007/03/01, created

(See pgm/uly_spect_linrebin.pro)


ULY_SPECT_LOGREBIN

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

 PURPOSE:  
                 Rebin logarithmically a spectrum 

 USAGE:
                 slog = uly_spect_logrebin(<spectrum> [,<vsc>])

 ARGUMENTS:
   <spectrum>:   Input, data structure (spectrum).

   <vsc>:        I/O, size of each pixel in km/s for the output data.

 KEYWORDS:
   WAVERANGE     Input scalar or 2-elements vector. Wavelength range.
                 If a single value s passed, it is interpreted as the
                 start of the wavelength range.

   FLUX_CONSERVE Input boolean.
                 Set this keyword to skip the intensity correction
                 for the change of the local pixel size.
                 If flux is conserved, intensity is not; by default
                 intensity (i.e. flux density) is conserved.

   LINEAR        Input boolean
                 Set this keyword to use a linear interpolation of the
                 cumul function. By default a spline interpolation is made.
                 A linear interpolation implies a convolution by a one-pixel
                 width boxcar function, while a spline interpolation
                 performs an implicite deconvolution of the pixels signature.
                 The difference may be sentitive in case of rebinning to
                 similar or finer pixels.

   EXACT         Input boolean.
                 Specify that the output must match exactly the WCS
                 specified by <waverange> and <vsc>. Otherwise approximations
                 can be made to avoid shifts by small fractions of pixels.

   OVERWRITE     Input boolean.
                 Set this keyword if input and output spect are the
                 same variable, to save memory and prevent a memory leak.
 OUTPUT:
                 SLOG, spectrum structure containing the log rebinned data.

 DESCRIPTION:
     This routine performs rigorously a rebinning into logarithmically
     spaced wavelength points. The algorithm consists in:
     (i) integrate the spectrum, (ii) resample (i. e. interpolate)
     this integral and (iii) differentiate the resampled integral. This
     naturally conserves the flux. The resampling is done with a spline
     or linear interpolation (see XREBIN).

     As it conserves the flux, the intensity of each pixel change
     because the size of a pixel change. As well, the shape of the
     intensity distribution changes, for example when converting a 
     linearly sampled spectrum into a log-sampled one. To alleviate
     this aspect, the function corrects by default for the change of  
     the pixel size. in is way the unit of the Intensity-axis are preserved.
     To skip this correction, use the keyword FLUX_CONSERVE.

     The input data must be a 'spectrum structure' (see ULY_SPECT_ALLOC), 
     and the data can be sampled linearly, in log or at explicit wavelength.
     
     By default the routine avoids a resampling if the input spectrum
     has the required step (<vsc>), and in that case simply extract
     the spectral range specified with <waverange>. Therefore, in this
     case the spectrum may be shifted by a fraction of pixel with respect
     to the requirement. To force a resampling to the exact grid,
     specify the keyword /EXACT. (note that in the case the constraint on the
     wavelength of the last pixel cannot be exact).

     <vsc> is the velocity scale, ie. size in km/s of each pixel in the
     log-rebinned spectrum.
     If <vsc> is initialized in input, this value will be used to rebin
     the input spectrum, otherwise the velocity scale is computed
     in order to keep the same number of pixels in output as in input.
     The computed value is returned in <vsc>.

     WAVERANGE. If a scalar or 1-element array is passed, it is the
     wavelength of the center of the output spectrum's 1st pixel in Angstrom. 
     If a 2-elements array array is passed, the wavelength range is [start, end]
     If the specified start is greater than the last wavelength of the 
     input spectrum, the routine fails with an error. 
     If the specified start is smaller than the begining of the spectrum,
     the effective start is shifted by a round number of pixels.
     If <waverange> is not passed, the spectrum is rebinned with a WCS
     so that the beginning edge of the first pixel coincide with each
     other both in input and output spectra.

     The error spectrum and pixel mask, if present in (spectrum) are
     also transformed in accordance with the signal. 

     If the data and error arrays contained in (spectrum) have two dimensions,
     all the lines are rebinned similarly. 

 SEE ALSO:       ULY_SPECT_LINREBIN, ULY_SPECT_READ

 REQUIRED ROUTINES:  
                 XREBIN.PRO

 HISTORY:        Mina Koleva (2007/03/01)
     

(See pgm/uly_spect_logrebin.pro)


ULY_SPECT_LOSVDCONVOL

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

 PURPOSE:   
                 Convolve a spectrum with a losvd

 USAGE:
                 spectr = uly_spect_losvdconvol(SignalIn, cz, sigma, h3, h4, /OVERWRITE)

 ARGUMENTS:
   SignalIn:     Input data structure (spectrum)

   cz:           Input systemic cz in km/s

   sigma:        Input velocity dispersion in km/s

   h3:           Input 3rd Hermite coefficient

   h4:           Input 4rd Hermite coefficient

 KEYWORDS:
   OVERWRITE     Set this keyword if input and output spect are the
                 same variable as to prevent a memory leak

 OUTPUT:
                 Spectrum structure containing the convolved data

 DESCRIPTION:
     The input data must be a 'spectrum structure', and the data
     can be sampled linearly or in log (see ULY_SPECT_ALLOC).
     If the sampling is not logarithmic, the routine first rebin
     the input before convolving, and the output spectrum is log sampled.

     The error spectrum and pixel mask, if present in (SignalIn) are
     also transformed in accordance with the signal. 

     If the data array contained in (SignalIn) has two dimensions,
     each line is convolved similarly. 

 HISTORY:        Ph. Prugniel (2008/01/31) created

(See pgm/uly_spect_losvdconvol.pro)


ULY_SPECT_LSFCONVOL

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

 PURPOSE:        
                 Convolve a spectrum or a population model
                 grid with a LSF.

 USAGE:          
                 uly_spect_lsfconvol, <lsf_file>, <spec>

 DESCRIPTION:
     Convolve the input <spect> with a line-spread function. <spec> can 
     be 1 to 4D spectrum, like a population model grid.

     The line-spread function, LSF, describes the intrinsic broadening 
     of a spectrum and its variation with wavelength. It can be 
     obtained with the program ULY_LSF.

     The LSF is given as a series of Gauss or Gauss-Hermite expansions 
     representing the instrumental broadening at different wavelengths.
     To inject this LSF in <spec>, first <spec> is convolved
     with each of these developments, and then the convolved spectra are
     interpolated in wavelength to restitute the LSF at each wavelength.

 ARGUMENTS:
   <lsf_file>:   Name of the file with the LSF it should contain 5
                 columns with the parameters of the LOSVD(v, s, h3,
                 h4) and the wavelength (usually the central wl were
                 the fit for determining the LOSVD parameters was obtained.) 

   <spec>:       Spectrum or a population model grid which *has to be logrebin*
                 (can use ULY_SPECT_READ).

 EXAMPLE:   
   1.Spectrum case:
      First extract template at given Teff, Logg and [Fe/H], find the relative
      change of the LSF between this template and the observed
      spectrum (cflib_114642.fits), and finally inject it, which
      means convolve this template with the derived LSF.

          obs = uly_root+'/data/cflib_114642.fits'
          template=uly_tgm_extr(obs,[6400,4.,0.])
          cmp = uly_star(template)
          uly_lsf, obs, cmp, 400, 200, FIL='lsfeg1.txt'

          uly_spect_lsfconvol, 'lsfeg1.txt', template

   2.Population model grid case:
      Interpolate at given age/met; Find the LSF of Vazdekis/Miles
      relative to PHR/Elodie3.1; read a model (PHR); and convolve
      it with the derived LSF.

         obs = uly_root+'/data/VazMiles_z-0.40t07.94.fits'
         model = uly_ssp_extr(obs, uly_root+'/models/PHR_Elodie31.fits', $
                              [6000., -0.4, 0], SIGMA=30)
         cmp = uly_star(model)
         uly_lsf, obs, cmp, 200, 100, FIL='lsfeg2.txt'

         grid = uly_ssp_read(uly_root+'/models/PHR_Elodie31.fits',VELSCALE=30)
         
         uly_spect_lsfconvol, 'lsfeg2.txt', grid  
         
      or do the lsfconvol inside ULY_SSP_READ with giving LSF file           
         newgrid = uly_ssp_read(uly_root+'/models/PHR_Elodie31.fits', $
                                VELSCALE=30, LSF='lsfeg2.txt')
    
 HISTORY: 
                 Yue WU, 21/08/2008, 
                 imitated from ULY_SPECT_LOSVDCONVOL made by Ph. Prugniel

(See pgm/uly_spect_lsfconvol.pro)


ULY_SPECT_PLOT

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

 PURPOSE:
                Plot 1d or 2d fits files

 USAGE:
		 uly_spect_plot, <spectrum>
                [, /OVERPLOT]
                [, WAVERANGE=<wr>][, YRANGE=<yr>]
                [, NORM=<norm>]
                [, ONED=<oned>]
                [, /XLOG][, /YLOG]
                [, TITLE=title]
                [, PLOT_VAR=plot_var]
                [, /QUIET]
		 

 DESCRIPTION:    
      This program plots 1d or 2d fits files. It can be used to visualize 
      the data that you may further want to analyse with ULySS package.
       
      Note: for making POSTSCRIPT files you need to setup the device 'ps'. 
      It is recommended that you plot what you would like to appear in
      your .ps file, then type "set_plot, 'ps'" and "device, fileout, /COLOR"
      (more options can be added to the command "device"), recall
      all your commands, type "device,/close" and "set_plot, 'x'".


 ARGUMENTS:
      <spectrum>	Input
                       FITS file name or 'spect' structure containing either a
                       1d or 2d spectra.
                       A 'spect' structure is returned by, e.g. ULY_SPECT_READ.
 KEYWORDS:
      /OVERPLOT
                       When this keyword is set, plots the spectra over an
                       existing plot. If color is set to a color name (eg.
                       'Red', 'Green', 'Blue'). The colors are defined as
                       in fsc_color.pro. Default is 'Blue'.
      WAVERANGE        	
                       Wavelength range to be plotted
      YRANGE        	
                       Flux range to be plotted
      NORM      	
                       2 element vector indicating the wavelength
                       range in which the flux will be normalised. Eg.
                       NORM=[3990.,4010.] will result in having the
                       average flux within this region set to 1.
      ONED
                       Position of the line to plot from a multidimensional 
                       dataset is given, set this value to the line number 
                       to extracted with ULY_SPECT_EXTRACT. Default - 1st line
      /XLOG /YLOG
                       Plot X (resp. Y) axis in logarithmic scale.
      TITLE
                       Title of the plot. Default: Name of the FITS file
      PLOT_VAR
                       An input structure containing all plot variables.
                       This structure is returned by ULY_PLOT_INIT
      ...Extra keywords
                       If PLOT_VAR is undefined, all extra keywords are
                       passed to ULY_PLOT_INIT.
      QUIET
                       Verbosity control.

 DEPENDENCIES:
                fsc_color.pro by David Fanning
                uly_spect_read.pro from ULySS

 HISTORY:        
     Creation   Mina Koleva, 22/07/2008

(See pgm/uly_spect_plot.pro)


ULY_SPECT_READ

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

 PURPOSE:
              Read a a spectrum from a FITS file

 USAGE:
    spec = uly_spect_read(<file_in>, 
                          <lmin>, <lmax>
                          [, VELSCALE=<velscale>]
                          [, SG=<sg>]
                          [, ERR_SP=<err_sp>]
                          [, SNR_SP=<snr_sp>]
                          [, MSK_SP=<msk_sp>]
                          [, DISP_AXIS=<disp_axis>]
                          [, /QUIET] )

 ARGUMENTS:
    file_in: 
	Name or logical unit (lun) of the FITS file containing a spectrum.
	Passing the lun of an already open file is particularly useful to
	read data from a given FITS extension (i. e. not necessarly the
	first). 

       For example:
          lun = fxposit('file.fits', 1)  ; to skip the first extension
          spec = uly_spect_read(lun) ; to read from the 2nd extension

    lmin,lmax: (input)
       Wavelength range to use (maybe several intervals)
                                                            
 KEYWORDS:
    VELSCALE:  Input scalar. Optional.
               Velocity scale (km/s), i.e. size of the pixel after 
               log-rebinning.
               If specified call ULY_SPECT_LOGREBIN to resample the spectrum.
               determined with ULY_SPECT_LOGREBIN.

    ERR_SP:    Input character string or integer. Optional.
               Name or lun of the input file containing the error spectrum.
               This is used in case the error spectrum is not contained
               in <file_in>. The error spectrum must have the same
               WCS as <file_in>.

    SNR_SP:    Input character string or integer. Optional. 
               Name or lun of the input file containing the SNR spectrum.
               Used if the error spectrum is not contained in <file_in>
               and if ERR_SP is not specified.

    MSK_SP:    Input character string or integer. Optional. 
               Name or lun of the input file containing the mask spectrum.
               Used if the mask is not contained in <file_in>. The mask
               must have the same WCS as <file_in>.

    SG:        Input. 
               Redshift (dimensionless) used to change the spectral WCS from
               the current frame (probably heliocentric) to the rest-frame.

    FORMAT:    Input integer (1, 2 or 3). Optional    
               Bypass the automatic format recognition and force the format.
               See below for description of the formats.

    DISP_AXIS: Input. 
               Number of the wavelength axis. Default = 1; Valid values 1/2.
               This information is used only for the format 3 (see the
               section 'Description'), and superseeds indications that 
               would be read from the header of the FITS file.

    QUIET:     Input
               Verbosity control. By default the function prints
               some information about the data it reads.

 OUTPUT:
    spect structure, see ULY_SPECT_ALLOC

 DESCRIPTION:
   Read a spectrum from a FITS file, including possibly the associated
   noise and a mask to exclude the bad regions, shift it back to the 
   restframe (if SG is given) and rebin it to a logarithmic
   wavelength scale (if VELSCALE is given).

   The return value, <spec>, is a structure containing pointers
   and has to be freed in the calling procedure as: uly_spect_free, spec
   See the documentation of ULY_SPECT_ALLOC for a description of
   this structure.

   Three different formats of FITS files for spectra are supported:
   1- SDSS style 
   2- Binary tables (BINTABLE)
   3- Image type array for 1D and long-slit spectra

   In all cases, the spectrum is supposed to contain fluxes, not log(flux).
   Whether they are absolutely, relatively or not flux-calibrated, or 
   normalized to a pseudo-continuum, is not coded in the output structure
   and is usually not critical for the analysis performed by the package. 
   Note however that the original FITS header is attached in the output
   structure, so, if necessary this information can be retrieved after
   reading the data.

   Description of the SDSS style (< DR9), format 1:
     The SDSS style allows to store wavelength resampled spectra
     together with their associated error, mask of bad regions, and
     potentially any other additional data, like for example a best
     fitted model (see our format for the solution of the fit, 
     described in the documentation of ULY_SOLUT_READ).

     The various quantities, spectrum and associated data, are stored
     on the last axis of an image array and described by the keywords
     ARRAYi, where i is the index along the last axis. The following
     values of are used by ULY_SPECT_READ:
        DATA      Flux spectrum (SPECTRUM is an alternative)
        ERROR     Error spectrum (1 sigma)
        MASK      Mask of good pixels (0=bad)

     The ARRAYi keywords are used to recognize the SDSS format. Use the FORMAT
     keyword (see above) if those keywords are absent. 

     Although this format is used by the SDSS project for 1D spectra only,
     it is easily extended here for larger dimensions by assuming that
     the associated data (DATA, ERROR...) are stacked on the last axis.

     Note also that in the SDSS project, the spectral WCS is not described
     by a standard WCS and is difficult to automatically guess from
     the other keywords (inheritance of keywords along the various steps
     of the processing gives room to ambiguous interpretation).
     The log10 scaling of SDSS data is recognized by the automatic process
     described below (though standard wcs should be in natural log).

     Note that since DR6 in SDSS the "DATA" array is called "SPECTRUM"

   Description of BINTABLE, format 2:
     There are many ways to store spectra in FITS binary tables. 
     The two main options are either to store them as columns of a
     table, or in a single cell. This latter format, which is not supported
     here, allows to store the various associated data (arrays or scalars)
     in a single row of a table, and therefore store several spectra
     in the file.
     The present reader handle spectral information stored as columns.
     Its advantage is to allow to store spectra which are not
     resampled in wavelength (or log of wavelength): A dedicated column
     may provide the wavelength of each pixel.

     The current version is limited to the reading of the output of:
     - the DEIMOS pipeline (spec2d).
     The following columns are read:
        SPEC    1D spectrum
        LAMBDA  wavelength in angstroms.
        IVAR    inverse variance array
        ORMASK  mask with 0-good and 1-bad
     - the SDSS DR9 pipeline.
        FLUX    1D spectrum
        LOGLAM  log10 wavelength in angstroms in vacuum, transformed
        to air and log while reading
        IVAR    inverse variance array
        OR_MASK is not read since it does not consist of 0 and 1 
 
   Description of image type arrays for 1/2D spectra, format 3:
      The most basic way to store 1D or long-slit spectra is as a 1/2D array. 
      The axis (or axes) being described by a WCS.

      The main disavantage of this format is the difficulty to
      associate the other data (error or mask may be stored in other
      extensions described in the main header, but there is not
      standard for this process).

      Use the ERR_SP, SNR_SP and MSK_SP keywords can be used to read the noise
      and mask for this format.

   Note about the spectral WCS:
     For the formats 1 and 3, the routine first attempts to read the standard 
     WCS described by the keywords CTYPEi, CRPIXi, CRVALi and CDi_i or CDELTi, 
     where i is the number of the spectral axis previously determined.

     If CTYPEi is absent but the other keywords present, the routine supposes
     that the wavelengths are expressed in Air (not in vacuum) and guess the 
     wavelength scaling from the world coordinate of the reference pixel 
     (CRVALi). If this value is less that 4, it is assumed that the axis is 
     in log10(wave/Angstrom). Between 4 and 9 in ln(wave/Angstrom), like if 
     CTYPEi='AWAV-LOG', and above that it is the wavelength in Ansgtrom 
     like if CTYPEi='AWAV'.

     CUNITi is never used (at present).

   Note about the conversion of vacuum wavelengths:
     The IAU definition for the conversion between Air and Vacuum
     wavelength, respectively (VAC) and (AIR) is:
       VAC = AIR * 1 + 6.4328D-5 + 2.94981D-2/(146 - sigma2) + 
             2.5540D-4/(41 - sigma2)
       where sigma2 = 1/AIR^2 (the wavelengths are in Angstrom)
     This formula is cited in Morton 1991 ApJS 77, 119

     So, approximately in the visible range: AIR = VAC / 1.00028
     (i.e. a shift of 84 km/s).
     ULY_SPECT_READ applies this approximate conversion to the WCS, to avoid
     a resampling. The IDL function VACTOAIR shall be used if a higher
     precision is required.

     The wavelength calibration of the SDSS spectra is in Heliocentric 
     VACUUM wavelength.

 EXAMPLE:
     Read a spectrum, and plot it:
       s = uly_spect_read(uly_root+'/data/VazMiles_z-0.40t07.94.fits')
       uly_spect_plot, s
     (note that the file name could have been pass directly to uly_spect_plot)

 AUTHOR:
              Mina Koleva, Philippe Prugniel

 HISTORY:
             Yue WU, 2013/01/25 - reading SDSS DR9 format
             Mina Koleva 2013/03/01 - debuging, cleaning the reading
                                      of DR9 format                                                           

(See pgm/uly_spect_read.pro)


ULY_STARTUP

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
                 ULY_STARTUP
 PURPOSE:
                 Compile the ULySS programs
 USAGE:
                 @ /galaxies2/data/prugniel/ulyss/uly_start.pro
 DESCRIPTION:
   The IDL setting for ULySS package, that can conveniently be included in
   the startup file (pointed to be the environment variable IDL_STARTUP.
   Simply add the line: @ /galaxies2/data/prugniel/ulyss/uly_start.pro
 
   The file uly_startup.pro is automatically created from the file
   uly_startup.pro.in by the configuration script when the command
   make install is issued from the shell.

(See pgm/uly_startup.pro)


ULY_TEST

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

 PURPOSE:
                 Test the ULySS package

 USAGE:
		  uly_test [, /REGRESS][, CRASH=crash][, STATUS=status]

 KEYWORDS:
   /REGRESS:     
		  If this keyword is set, perform regression tests,
                 otherwise crash tests are made.

   CRASH:        
		  0 or not set, perform all the tests
                 n, perform test #n (there are 12 test available)

   STATUS:       
		  0 if the tests succeed, "n" if test #n failed
                                                            
 DESCRIPTION:
   Perform tests of the ULySS package.
  
   At present only crash tests are executed. They test all the
   routines of the package in at minimum one configuration. The goal
   of these tests is to detect bugs in the packages introduced during
   the development.

 AUTHOR:
                 Mina Koleva, Philippe Prugniel & Yue Wu

 HISTORY:
                 14/02/2008

(See pgm/uly_test.pro)


This page was created by the ULySS routine uly_html_help.
Contact: ulyss at obs.univ-lyon1.fr Last modified: Wed Feb 24 10:42:23 2016.