File: irplib_flat.c

package info (click to toggle)
cpl-plugin-sinfo 2.5.2%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 8,512 kB
  • ctags: 3,661
  • sloc: ansic: 82,282; sh: 11,405; makefile: 711; python: 278
file content (402 lines) | stat: -rw-r--r-- 12,974 bytes parent folder | download | duplicates (11)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/* $Id: irplib_flat.c,v 1.15 2007-08-07 12:15:41 llundin Exp $
 *
 * This file is part of the irplib package
 * 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, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
 */

/*
 * $Author: llundin $
 * $Date: 2007-08-07 12:15:41 $
 * $Revision: 1.15 $
 * $Name: not supported by cvs2svn $
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

/*-----------------------------------------------------------------------------
                                   Includes
 -----------------------------------------------------------------------------*/

#include <math.h>
#include <cpl.h>

#include "irplib_flat.h"

/*-----------------------------------------------------------------------------
                            Functions prototypes
 -----------------------------------------------------------------------------*/

static double * irplib_flat_fit_proportional(double *, double *, int) ;

/*----------------------------------------------------------------------------*/
/**
 * @defgroup irplib_flat    Functions for flatfielding 
 */
/*----------------------------------------------------------------------------*/

/**@{*/

/*----------------------------------------------------------------------------*/
/**
  @brief    Compute a flat-field out of a set of exposures.
  @param    raw     Input image set 
  @param    mode    0 for proportional, 1 for robust fit
  @return   1 newly allocated set of 2 or 3 images 

  The input is assumed to be a cube containing planes of different intensities 
  (usually increasing or decreasing). Typical inputs are: twilight data sets, 
  halogen lamp, or skies of different airmasses in the thermal regime.

  The input image list must be of type float.
  
  In robust mode, the output is a set of 3 images. 
  The first image contains a regression map, i.e. for each pixel position on 
  the detector, a curve is plotted of the pixel intensity in each plane 
  against the median intensity of the plane. A slope is fit, and the gain 
  factor is stored into this first image.

  The second image contains the y-intercepts of the slope fit. It is usually 
  good to check it out in case of failures.

  The third image contains the sum of squared errors for each fit.
  The fit is using a robust least-squares criterion rejecting outliers. This 
  is the algorithm to use with big telescopes like the VLT, which collect so 
  much light that objects are actually seen in the twilight sky.  

  In proportional mode, the output is a set of 2 images.
  The first image contains a regression map.
  The second image contains the sum of squared errors for each fit.
 */
/*----------------------------------------------------------------------------*/
cpl_imagelist * irplib_flat_fit_set(
        cpl_imagelist   *   raw,
        int                 mode)
{
    double          *   plane_med    = NULL ;
    double          *   slope        = NULL ;
    cpl_image       *   gain         = NULL ;
    double          *   pgain        = NULL ;
    cpl_image       *   intercept    = NULL ;
    double          *   pintercept   = NULL ;
    cpl_image       *   sq_err       = NULL ;
    double          *   psq_err      = NULL ;
    double          *   timeline     = NULL ;
    float           *   raw_im_data  = NULL ;
    cpl_imagelist   *   result       = NULL ;
    const int           nx = cpl_image_get_size_x(cpl_imagelist_get(raw, 0));
    const int           ny = cpl_image_get_size_y(cpl_imagelist_get(raw, 0));
    const int           ni = cpl_imagelist_get_size(raw);
    int                 i, j ;

    /* Check entries */
    if (raw==NULL) return NULL ;
    if ((mode != 0) && (mode != 1)) return NULL ;
    if (cpl_image_get_type(cpl_imagelist_get(raw, 0)) != CPL_TYPE_FLOAT)
        return NULL ;
    if (cpl_imagelist_get_size(raw) <= 1) return NULL ;

    /* Compute median for all planes */
    plane_med = cpl_malloc(ni * sizeof(double)) ;
    for (i=0 ; i<ni ; i++)
        plane_med[i] = cpl_image_get_median(cpl_imagelist_get(raw, i));

    /* Create result images */
    gain = cpl_image_new(nx, ny, CPL_TYPE_DOUBLE) ;
    pgain = cpl_image_get_data_double(gain) ;
    if (mode == 1) {
        intercept = cpl_image_new(nx, ny, CPL_TYPE_DOUBLE) ;
        pintercept = cpl_image_get_data_double(intercept) ;
    }
    sq_err = cpl_image_new(nx, ny, CPL_TYPE_DOUBLE) ;
    psq_err = cpl_image_get_data_double(sq_err) ;
    timeline = cpl_malloc(ni * sizeof(double)) ;

    /* Loop on all pixel positions */
    cpl_msg_info(cpl_func, "Computing gains for all positions (long)...") ;
    for (i=0 ; i<nx * ny ; i++) {
        /* extract time line */
        for (j=0 ; j<ni ; j++) {
            raw_im_data = cpl_image_get_data_float(cpl_imagelist_get(raw, j)) ;
            timeline[j] = (double)raw_im_data[i] ;
        }
        /* Fit slope to this time line */
        if (mode == 1) {
            slope = irplib_flat_fit_slope_robust(plane_med, timeline, ni) ;
            pintercept[i] = slope[0] ;
            pgain[i]      = slope[1] ;
            psq_err[i]    = slope[2] ;
            /* Set results in output images */
        } else {
            slope = irplib_flat_fit_proportional(plane_med, timeline, ni) ;
            /* Set results in output images */
            pgain[i]      = slope[0] ;
            psq_err[i]    = slope[1] ;
        }
        cpl_free(slope);
    }
    cpl_free(plane_med) ;
    cpl_free(timeline) ;

    /* Return */
    result = cpl_imagelist_new() ;
    if (mode == 1) {
        cpl_imagelist_set(result, gain, 0) ;
        cpl_imagelist_set(result, intercept, 1) ;
        cpl_imagelist_set(result, sq_err, 2) ;
    } else {
        cpl_imagelist_set(result, gain, 0) ;
        cpl_imagelist_set(result, sq_err, 1) ;
    }
    return result ;
}

/* @cond */
#define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a))
#define MAX_ITERATE     30
/* @endcond */
/*----------------------------------------------------------------------------*/
/**
  @brief    Fit a slope to a list of points (robust fit).
  @param    x   x coordinates 
  @param    y   y coordinates 
  @param    np  number of points 
  @return   Pointer to newly allocated array of 3 doubles.

  The slope to fit has the following kind of equation:
  y = c[0] + c[1] * x

  The returned coefficients are defined as:
  c[0] is the y-intercept.
  c[1] is the slope.
  c[2] is the median squared error of the fit.
  This is a very robust slope fit. It tolerates up to 50% of outliers in input.
 */
/*----------------------------------------------------------------------------*/
double * irplib_flat_fit_slope_robust(
        double  *   x,
        double  *   y,
        int         np)
{
    double      *   c ;
    double          aa, bb, bcomp, b1, b2, del, abdevt, f, f1, f2, sigb, temp,
                    d, sum ;
    double          sx, sy, sxy, sxx, chisq ;
    cpl_vector  *   arr ;
    double      *   parr ;
    double          aa_ls, bb_ls ;
    int             iter ;
    int             i ;

    /* Check entries */
    if (x==NULL || y==NULL) return NULL ;

    c = cpl_malloc(3 * sizeof(double)) ;

    sx = sy = sxx = sxy = 0.00 ;
    for (i=0 ; i<np ; i++) {
        sx  += x[i];
        sy  += y[i];
        sxy += x[i] * y[i];
        sxx += x[i] * x[i];
    }

    del = np * sxx - sx * sx;
    aa_ls = aa  = (sxx * sy - sx * sxy) / del;
    bb_ls = bb  = (np * sxy - sx * sy) / del;

    chisq = 0.00 ;
    for (i=0;i<np;i++) {
        temp = y[i] - (aa+bb*x[i]) ;
        temp *= temp ;
        chisq += temp ;
    }

    arr = cpl_vector_new(np) ;
    parr = cpl_vector_get_data(arr) ;
    sigb = sqrt(chisq/del);
    b1   = bb ;

    bcomp = b1 ;
    sum = 0.00 ;
    for (i=0 ; i<np ; i++) {
            parr[i] = y[i] - bcomp * x[i];
        }
    aa = cpl_vector_get_median(arr); /* arr permuted */
    abdevt = 0.0;
    for (i=0 ; i<np ; i++) {
        d = y[i] - (bcomp * x[i] + aa);
        abdevt += fabs(d);
        if (fabs(y[i]) > 1e-7) d /= fabs(y[i]);
        if (fabs(d) > 1e-7) sum += (d >= 0.0 ? x[i] : -x[i]);
    }
    f1 = sum ;
    b2   = bb + SIGN(3.0 * sigb, f1);
    bcomp = b2 ;
    sum = 0.00 ;
    for (i=0 ; i<np ; i++) parr[i] = y[i] - bcomp * x[i];
    aa = cpl_vector_get_median(arr);  /* arr permuted */
    abdevt = 0.0;
    for (i=0 ; i<np ; i++) {
        d = y[i] - (bcomp * x[i] + aa);
        abdevt += fabs(d);
        if (fabs(y[i]) > 1e-7) d /= fabs(y[i]);
        if (fabs(d) > 1e-7) sum += (d >= 0.0 ? x[i] : -x[i]);
    }
    f2 = sum ;

    if (fabs(b2-b1)<1e-7) {
        c[0] = aa ;
        c[1] = bb ;
        c[2] = abdevt / (double)np;
        cpl_vector_delete(arr);
        return c ;
    }

    iter = 0 ;
    while (f1*f2 > 0.0) {
        bb = 2.0*b2-b1;
        b1 = b2;
        f1 = f2;
        b2 = bb;

        bcomp = b2 ;
        sum = 0.00 ;
        for (i=0 ; i<np ; i++) parr[i] = y[i] - bcomp * x[i];
        aa = cpl_vector_get_median(arr); /* arr permuted */
        abdevt = 0.0;
        for (i=0 ; i<np ; i++) {
            d = y[i] - (bcomp * x[i] + aa);
            abdevt += fabs(d);
            if (fabs(y[i]) > 1e-7) d /= fabs(y[i]);
            if (fabs(d) > 1e-7) sum += (d >= 0.0 ? x[i] : -x[i]);
        }
        f2 = sum ;
        iter++;
        if (iter>=MAX_ITERATE) break ;
    }
    if (iter>=MAX_ITERATE) {
        c[0] = aa_ls ;
        c[1] = bb_ls ;
        c[2] = -1.0 ;
        cpl_vector_delete(arr);
        return c ;
    }

    sigb = 0.01 * sigb;
    while (fabs(b2-b1) > sigb) {
        bb = 0.5 * (b1 + b2) ;
        if ((fabs(bb-b1)<1e-7) || (fabs(bb-b2)<1e-7)) break;
        bcomp = bb ;
        sum = 0.00 ;
        for (i=0 ; i<np ; i++) parr[i] = y[i] - bcomp * x[i];
        aa = cpl_vector_get_median(arr); /* arr permuted */
        abdevt = 0.0;
        for (i=0 ; i<np ; i++) {
            d = y[i] - (bcomp * x[i] + aa);
            abdevt += fabs(d);
            if (fabs(y[i]) > 1e-7) d /= fabs(y[i]);
            if (fabs(d) > 1e-7) sum += (d >= 0.0 ? x[i] : -x[i]);
        }
        f = sum ;

        if (f*f1 >= 0.0) {
            f1=f;
            b1=bb;
        } else {
            f2=f;
            b2=bb;
        }
    }
    cpl_vector_delete(arr) ;
    c[0]=aa;
    c[1]=bb;
    c[2]=abdevt/np;
    return c ;
}
#undef MAX_ITERATE
#undef SIGN


/**@}*/

/*----------------------------------------------------------------------------*/
/**
  @brief    Compute a=y/x for all given points
  @param    x   x coordinates 
  @param    y   y coordinates 
  @param    np  number of points 
  @return   Pointer to newly allocated array of two doubles.

  This function takes in input a list of points supposed all aligned
  on a slope going through the origin (of equation y=ax). It computes
  the slope a = y/x for all points, and returns a pointer to two
  doubles:

  \begin{itemize}
  \item The median slope.
  \item The mean squared error.
  \end{itemize}

  Returning the median of all slopes makes it very robust to outliers.
  A more precise method would be to make a histogram of all slopes and
  take the maximum (i.e. the mode of the distribution). It can be
  shown that the median approximates the mode quite well for a large
  number of points.
 */
/*----------------------------------------------------------------------------*/
#define FITPROP_BIG_SLOPE   1e30
static double * irplib_flat_fit_proportional(
        double  *   x,
        double  *   y,
        int         np)
{
    cpl_vector  *   slopes ;
    double      *   pslopes ;
    double      *   med_slope ;
    double          val ;
    double          sq_err ;
    int             i ;

    /* Check entries */
    if (x==NULL || y==NULL) return NULL ;

    slopes = cpl_vector_new(np) ;
    pslopes = cpl_vector_get_data(slopes) ;
    for (i=0 ; i<np ; i++) {
        if (fabs(x[i])>1e-30)  pslopes[i] = y[i] / x[i] ;
        else                   pslopes[i] = FITPROP_BIG_SLOPE ;
    }
    med_slope = cpl_malloc(2 * sizeof(double));
    med_slope[0] = cpl_vector_get_median(slopes); /* slopes permuted */
    cpl_vector_delete(slopes);

    sq_err = 0.00 ;
    for (i=0 ; i<np ; i++) {
        val = med_slope[0] * x[i] ;
        sq_err += (val-y[i])*(val-y[i]) ;
    }
    sq_err /= (double)np ;
    med_slope[1] = sq_err ;

    return med_slope ;
#undef FITPROP_BIG_SLOPE
}