The kmo_flat recipe
===============================================================

.. data:: kmo_flat

Synopsis
--------

Create master flatfield frame and badpixel map to be used during science reduction

Description
-----------

This recipe creates the master flat field and calibration frames needed for 
spatial calibration for all three detectors. It must be called after the 
kmo_dark-recipe, which generates a bad pixel mask (badpixel_dark.fits). The 
bad pixel mask will be updated in this recipe (goes into badpixel_flat.fits).

As input at least 3 dark frames, 3 frames with the flat lamp on are recommen-
ded. Additionally a badpixel mask from kmo_dark is required.


The badpixel mask contains 0 for bad pixels and 1 for good ones.


The structure of the resulting xcal and ycal frames is quite complex since the
arrangement of the IFUs isn't just linear on the detector. Basically the inte-
ger part of the calibration data shows the offset of each pixels centre in mas
(Milli arcsec) from the field centre. The viewing of an IFU is 2800mas 
(14pix*0.2arcsec/pix). So the values in these two frames will vary between 
+/-1500 (One would expect 1400, but since the slitlets aren't expected to be 
exactly vertical, the values can even go up to around 1500). Additionally in 
the calibration data in y-direction the decimal part of the data designates 
the IFU to which the slitlet corresponds to (for each detector from 1 to 8).

Because of the irregular arrangement of the IFUs not all x-direction calibra-
tion data is found in xcal and similarly not all y-direction calibration data
is located in ycal. For certain IFUs they are switched and/or flipped in x- or
y-direction:
For IFUs 1,2,3,4,13,14,15,16:		x- and y- data is switched
For IFUs 17,18,19,20:			y-data is flipped 
For IFUs 21,22,23,24:			x-data is flipped 
For IFUs 5,6,7,8,9,10,11,12:		x- and y- data is switched and x- and 
                                      y- data is flipped

Furthermore frames can be provided for several rotator angles. In this case
the resulting calibration frames for each detector are repeatedly saved as 
extension for every angle.


Advanced features:
------------------
To create the badpixel mask the edges of all slitlets are fitted to a polyno-
mial. Since it can happen that some of these fits (3 detectors * 8 IFUs * 
14slitlets * 2 edges  (left and right edge of slitlet)= 672 edges) fail, the
fit parameters are themselves fitted again to detect any outliers. By default
the parameters of all left and all right edges are grouped individually and 
then fitted using chebyshev polynomials. The advantage of a chebyshev polyno-
mial is, that it consists in fact of a series of orthogonal polynomials. This
implies that the parameters of the polynomials are independent. This fact pre-
destines the use of chebyshev polynomials for our case. So each individual pa-
rameter can be examined independently. The reason why the left and right edges
are fitted individually is that there is a systematic pattern specific to 
these groups. The reason for this pattern is probably to be found in the opti-
cal path the light is traversing.


The behaviour of this fitting step can be influenced via environment parameters:
* KF_ALLPARS (default: 1)
  When set to 1 all coefficients of the polynomial of an edge are to be cor-
  rected, also when just one of these coefficients is an outlier. When set to
  0 only the outlier is to be corrected.

* KF_CH (default: 1)
  When set to 1 chebyshev polynomials are used to fit the fitted parameters.

  When set to 0 normal polynomials are used.

* KF_SIDES (default: 2)
  This variable can either be set to 1 or 2. When set to 2 the left and right
  edges are examined individually. When set to 1 all edges are examined as one
  group.

* KF_FACTOR(default: 4)
  This factor defines the threshold factor. All parameters deviating 
  KF_FACTOR*stddev are to be corrected

Input files
^^^^^^^^^^^^
::

   DO                    KMOS                                                  
   category              Type   Explanation                    Required #Frames
   --------              -----  -----------                    -------- -------
   FLAT_ON               RAW    Flatlamp-on exposures             Y       1-n  
                                (at least 3 frames recommended)                
   FLAT_OFF              RAW    Flatlamp-off exposures            Y       1-n  
                                (at least 3 frames recommended)                
   BADPIXEL_DARK         B2D    Bad pixel mask                    Y        1   

Output files
^^^^^^^^^^^^
::

   DO                    KMOS
   category              Type   Explanation
   --------              -----  -----------
   MASTER_FLAT           F2D    Normalised flat field
                                (6 extensions: alternating data & noise
   BADPIXEL_FLAT         B2D    Updated bad pixel mask (3 Extensions)
   XCAL                  F2D    Calibration frame 1 (3 Extensions)
   YCAL                  F2D    Calibration frame 2 (3 Extensions)
   FLAT_EDGE             F2L    Frame containing parameters of fitted 
                                slitlets of all IFUs of all detectors

Constructor
-----------

.. method:: cpl.Recipe("kmo_flat")
   :noindex:

   Create an object for the recipe kmo_flat.

::

   import cpl
   kmo_flat = cpl.Recipe("kmo_flat")

Parameters
----------

.. py:attribute:: kmo_flat.param.badpix_thresh

    The threshold level to mark pixels as bad on the dark subtracted  frames [%]. (long; default: 35) [default=35].
.. py:attribute:: kmo_flat.param.surrounding_pixels

    The amount of bad pixels to surround a specific pixel, to let it be  marked bad as well. (long; default: 5) [default=5].
.. py:attribute:: kmo_flat.param.suppress_extension

    Suppress arbitrary filename extension.(TRUE (apply) or FALSE (don't  apply) (bool; default: False) [default=False].
.. py:attribute:: kmo_flat.param.cmethod

    Either apply "average", "median", "sum", "min_max." or "ksigma". (str;  default: 'ksigma') [default="ksigma"].
.. py:attribute:: kmo_flat.param.cpos_rej

    The positive rejection threshold for kappa-sigma-clipping (sigma).  (float; default: 3.0) [default=3.0].
.. py:attribute:: kmo_flat.param.cneg_rej

    The negative rejection threshold for kappa-sigma-clipping (sigma).  (float; default: 3.0) [default=3.0].
.. py:attribute:: kmo_flat.param.citer

    The number of iterations for kappa-sigma-clipping. (long; default: 3) [default=3].
.. py:attribute:: kmo_flat.param.cmax

    The number of maximum pixel values to clip with min/max-clipping.  (long; default: 1) [default=1].
.. py:attribute:: kmo_flat.param.cmin

    The number of minimum pixel values to clip with min/max-clipping.  (long; default: 1) [default=1].


The following code snippet shows the default settings for the available 
parameters.

::

   import cpl
   kmo_flat = cpl.Recipe("kmo_flat")

   kmo_flat.param.badpix_thresh = 35
   kmo_flat.param.surrounding_pixels = 5
   kmo_flat.param.suppress_extension = False
   kmo_flat.param.cmethod = "ksigma"
   kmo_flat.param.cpos_rej = 3.0
   kmo_flat.param.cneg_rej = 3.0
   kmo_flat.param.citer = 3
   kmo_flat.param.cmax = 1
   kmo_flat.param.cmin = 1


You may also set or overwrite some or all parameters by the recipe 
parameter `param`, as shown in the following example:

::

   import cpl
   kmo_flat = cpl.Recipe("kmo_flat")
   [...]
   res = kmo_flat( ..., param = {"badpix_thresh":35, "surrounding_pixels":5})


.. seealso:: `cpl.Recipe <http://packages.python.org/python-cpl/recipe.html>`_
   for more information about the recipe object.

Bug reports
-----------

Please report any problems to `Alex Agudo Berbel <kmos-spark@mpe.mpg.de>`_. Alternatively, you may 
send a report to the `ESO User Support Department <usd-help@eso.org>`_.

Copyright
---------

This file is part of the KMOS Instrument Pipeline
Copyright (C) 2002,2003 European Southern Observatory

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, 51 Franklin Street, Suite 500, Boston, MA  02110-1335  USA

.. codeauthor:: Alex Agudo Berbel <kmos-spark@mpe.mpg.de>
