MUSE Pipeline Reference Manual  2.5.2
muse_autocalib.c
1 /* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set sw=2 sts=2 et cin: */
3 /*
4  * This file is part of the MUSE Instrument Pipeline
5  * Copyright (C) 2014-2017 Laure Piqueras, Simon Conseil
6  * (CRAL - Observatoire de Lyon)
7  * (C) 2017-2018 European Southern Observatory
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22  */
23 
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27 
28 /*----------------------------------------------------------------------------*
29  * Includes *
30  *----------------------------------------------------------------------------*/
31 #include <cpl.h>
32 #include <math.h>
33 #include <string.h>
34 
35 #include "muse_autocalib.h"
36 #include "muse_instrument.h"
37 
38 #include "muse_data_format_z.h"
39 #include "muse_pfits.h"
40 #include "muse_utils.h"
41 
42 /*----------------------------------------------------------------------------*
43  * Macros *
44  *----------------------------------------------------------------------------*/
45 #define MAPIDX(i, s, q) (kMuseNumIFUs * kMuseSlicesPerCCD * ((q)-1) \
46  + kMuseSlicesPerCCD * ((i)-1) + (s) - 1)
47 
48 /*----------------------------------------------------------------------------*/
55 /*----------------------------------------------------------------------------*/
58 /* Compute the arithmetic mean */
59 static void
60 muse_autocalib_mean(float *data, int n, double x[3], int *indx)
61 {
62  double mean = 0.0,
63  sum_deviation = 0.0;
64  int i;
65  for (i = 0; i < n; i++) {
66  mean += data[indx[i]];
67  }
68  mean = mean / n;
69  for (i = 0; i < n; i++) {
70  sum_deviation += (data[indx[i]] - mean) * (data[indx[i]] - mean);
71  }
72  x[0] = mean;
73  x[1] = sqrt(sum_deviation / n);
74 }
75 
76 /* Compute median */
77 static double
78 muse_autocalib_median(float *data, int n, int *indx)
79 {
80  cpl_array *arr = cpl_array_new(n, CPL_TYPE_FLOAT);
81  cpl_size i;
82  for (i = 0; i < n; i++) {
83  cpl_array_set(arr, i, data[indx[i]]);
84  }
85 
86  double med = cpl_array_get_median(arr);
87  cpl_array_delete(arr);
88 
89  return med;
90 }
91 
92 /* Compute the arithmetic mean and MAD sigma */
93 static void
94 muse_autocalib_mean_mad(float *data, int n, double x[3], int *indx)
95 {
96  double mean = 0.0,
97  median = 0.0;
98  int i;
99  float *work = (float *)cpl_malloc(n * sizeof(float));
100  int *ind = (int *)cpl_malloc(n * sizeof(int));
101 
102  for (i = 0; i < n; i++) {
103  mean += data[indx[i]];
104  }
105  mean = mean / n;
106 
107  median = muse_autocalib_median(data, n, indx);
108  for (i = 0; i < n; i++) {
109  ind[i] = i;
110  work[i] = fabs(data[indx[i]] - median);
111  }
112  x[0] = mean;
113  x[1] = muse_autocalib_median(work, n, ind) * 1.4826;
114  cpl_free(ind);
115  cpl_free(work);
116 }
117 
118 /* Iterative sigma-clipping of array elements *
119  * return x[0] = mean, x[1] = std, x[2] = n *
120  * index must be initialized. */
121 static void
122 muse_autocalib_mean_sigma_clip(float *data, int n, double x[3], int nmax,
123  double nclip_low, double nclip_up, int nstop,
124  int *indx)
125 {
126  double clip_lo, clip_up;
127  muse_autocalib_mean(data, n, x, indx);
128  x[2] = n;
129  double med;
130  med = muse_autocalib_median(data, n, indx);
131  clip_lo = med - (nclip_low * x[1]);
132  clip_up = med + (nclip_up * x[1]);
133 
134  int i, ni = 0;
135  for (i = 0; i < n; i++) {
136  if ((data[indx[i]] < clip_up) && (data[indx[i]] > clip_lo)) {
137  ni = ni + 1;
138  }
139  }
140  if (ni < nstop || ni == n) {
141  return;
142  }
143  if (nmax > 0) {
144  ni = 0;
145  for (i = 0; i < n; i++) {
146  if ((data[indx[i]] < clip_up) && (data[indx[i]] > clip_lo)) {
147  indx[ni] = indx[i];
148  ni = ni + 1;
149  }
150  }
151  nmax = nmax - 1;
152  muse_autocalib_mean_sigma_clip(data, ni, x, nmax, nclip_low, nclip_up,
153  nstop, indx);
154  }
155 }
156 
157 /* Iterative MAD sigma-clipping of array elements *
158  * return x[0] = median, x[1] = MAD std, x[2] = n */
159 static void
160 muse_autocalib_mean_madsigma_clip(float *data, int n, double x[3], int nmax,
161  double nclip_low, double nclip_up, int nstop,
162  int *indx)
163 {
164  double clip_lo, clip_up;
165  muse_autocalib_mean_mad(data, n, x, indx);
166  x[2] = n;
167  double med;
168  med = muse_autocalib_median(data, n, indx);
169  clip_lo = med - (nclip_low * x[1]);
170  clip_up = med + (nclip_up * x[1]);
171 
172  int i, ni = 0;
173  for (i = 0; i < n; i++) {
174  if ((data[indx[i]] < clip_up) && (data[indx[i]] > clip_lo)) {
175  ni = ni + 1;
176  }
177  }
178  if (ni < nstop || ni == n) {
179  return;
180  }
181  if (nmax > 0) {
182  ni = 0;
183  for (i = 0; i < n; i++) {
184  if ((data[indx[i]] < clip_up) && (data[indx[i]] > clip_lo)) {
185  indx[ni] = indx[i];
186  ni = ni + 1;
187  }
188  }
189  nmax = nmax - 1;
190  muse_autocalib_mean_madsigma_clip(data, ni, x, nmax, nclip_low, nclip_up,
191  nstop, indx);
192  }
193 }
194 
195 static void
196 muse_autocalib_minmax(float data[], int n, int *indx, float res[])
197 {
198  int i;
199  double min, max;
200 
201  if (n == 1) {
202  res[0] = data[indx[0]];
203  res[1] = data[indx[0]];
204  return;
205  }
206 
207  if (data[indx[0]] > data[indx[1]]) {
208  max = data[indx[0]];
209  min = data[indx[1]];
210  } else {
211  max = data[indx[1]];
212  min = data[indx[0]];
213  }
214 
215  for (i = 2; i < n; i++) {
216  if (data[indx[i]] > max) {
217  max = data[indx[i]];
218  } else if (data[indx[i]] < min) {
219  min = data[indx[i]];
220  }
221  }
222  res[0] = min;
223  res[1] = max;
224 }
225 
226 static void
227 muse_autocalib_minmax_int(unsigned short data[], int n, int *indx,
228  unsigned int res[])
229 {
230  int i;
231  unsigned int min, max;
232 
233  if (n == 1) {
234  res[0] = data[indx[0]];
235  res[1] = data[indx[0]];
236  return;
237  }
238 
239  if (data[indx[0]] > data[indx[1]]) {
240  max = data[indx[0]];
241  min = data[indx[1]];
242  } else {
243  max = data[indx[1]];
244  min = data[indx[0]];
245  }
246 
247  for (i = 2; i < n; i++) {
248  if (data[indx[i]] > max) {
249  max = data[indx[i]];
250  } else if (data[indx[i]] < min) {
251  min = data[indx[i]];
252  }
253  }
254  res[0] = min;
255  res[1] = max;
256 }
257 
258 static void
259 muse_autocalib_slice_mean(float *data, unsigned short *xpix, int n, double x[3],
260  int *indx, unsigned int min_pix)
261 {
262  unsigned int minmax[2];
263  muse_autocalib_minmax_int(xpix, n, indx, minmax);
264 
265  int nx = (minmax[1] - minmax[0] + 1);
266  int *ind = (int *)cpl_malloc(n * sizeof(int));
267  float *meanarr = (float *)cpl_malloc(nx * sizeof(float));
268 
269  int meancount = 0;
270  unsigned int i;
271  for (i = minmax[0]; i <= minmax[1]; i++) {
272  int j, count = 0;
273  for (j = 0; j < n; j++) {
274  if (xpix[indx[j]] == i) {
275  ind[count++] = indx[j];
276  }
277  }
278  if (count > 50) {
279  muse_autocalib_mean(data, count, x, ind);
280  meanarr[meancount] = x[0];
281  meancount++;
282  }
283  }
284  if (meancount < (int)min_pix) {
285  x[0] = 0;
286  x[1] = 0;
287  x[2] = 0;
288  } else {
289  int j;
290  for (j = 0; j < meancount; j++) {
291  ind[j] = j;
292  }
293  muse_autocalib_mean_madsigma_clip(meanarr, meancount, x, 15, 3, 3, 15, ind);
294  }
295 
296  cpl_free(ind);
297  cpl_free(meanarr);
298 }
299 
300 /*---------------------------------------------------------------------------*/
326 /*---------------------------------------------------------------------------*/
327 cpl_error_code
329  muse_table **aFactors)
330 {
331  cpl_ensure_code(aPixtable, CPL_ERROR_NULL_INPUT);
332  if (cpl_propertylist_has(aPixtable->header, MUSE_HDR_PT_AUTOCAL_NAME) &&
333  !strncmp(cpl_propertylist_get_string(aPixtable->header,
335  "slice-median", 13)) {
336  cpl_msg_info(__func__, "pixel table already auto-calibrated: skipping "
337  "correction");
338  return CPL_ERROR_NONE;
339  }
340 
341  /* --- Hardcoded Parameters -----------------------------------------------*/
342  /* XXX use real parameters for these? If so, we *
343  * need to make the isAO branch below smarter! */
344  float lbdabins[] = { 0, 5000, 5265, 5466, 5658, 5850, 6120, 6440, 6678,
345  6931, 7211, 7450, 7668, 7900, 8120, 8330, 8565, 8731,
346  9012, 9275, 10000 };
347  unsigned short nlbin = 20;
348  /* Minimum number of pixels for which we have a flux in one slice, *
349  * and maximum number that can happen at all in the MUSE slice. */
350  unsigned int min_pix_per_slice = 20,
351  max_pix_per_slice = (kMuseOutputYTop
352  * ceil(kMuseSliceHiLikelyWidth));
353 
354  /* Clipping parameters */
355  int nmax = 15, nstop = 20;
356  double nclip_low = 3.0, nclip_up = 3.0;
357  /*-------------------------------------------------------------------------*/
358 
359  cpl_boolean isAO = muse_pfits_get_mode(aPixtable->header)
360  >= MUSE_MODE_WFM_AO_E;
361  if (isAO) {
362  /* only one range around the NaD gap, remove the 5850 entry */
363  memmove(lbdabins+5, lbdabins+6, 15 * sizeof(float));
364  nlbin--;
365  }
366 
367  cpl_msg_info(__func__, "Running self-calibration, using %d lambda ranges "
368  "(%s mode)", nlbin, isAO ? "AO" : "non-AO");
369  double cputime = cpl_test_get_cputime(),
370  walltime = cpl_test_get_walltime();
371 
372  double x[3], x1[3], x2[3], *refx;
373  float tot_flux, refflux, minmax[2], oldcorr, meanq, threshq;
374 
375  unsigned char *ifu, *sli;
376  unsigned short *xpix;
377  muse_pixtable_origin_decode_all(aPixtable, &xpix, NULL, &ifu, &sli);
378  cpl_size npix = muse_pixtable_get_nrow(aPixtable);
379  unsigned int *quad = (unsigned int *)cpl_malloc(npix * sizeof(unsigned int));
380 
381  /* For each slice and wavelength bin, store the number of *
382  * values, the correction, and the indices of the values */
383  int *npts = (int *)cpl_malloc(kMuseNumIFUs * kMuseSlicesPerCCD * nlbin
384  * sizeof(int));
385  float *corr = (float *)cpl_malloc(kMuseNumIFUs * kMuseSlicesPerCCD * nlbin
386  * sizeof(float));
387  int *indmap[nlbin * kMuseNumIFUs * kMuseSlicesPerCCD];
388 
389  cpl_size k;
390  for (k = 0; k < kMuseNumIFUs * kMuseSlicesPerCCD * nlbin; k++) {
391  npts[k] = 0;
392  corr[k] = 1.0;
393  indmap[k] = (int *)cpl_malloc(max_pix_per_slice * sizeof(int));
394  }
395 
396  float *data = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_DATA),
397  *stat = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_STAT),
398  *lbda = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_LAMBDA);
399 
400  cpl_boolean debug = getenv("MUSE_DEBUG_AUTOCALIB") ? CPL_TRUE : CPL_FALSE;
401 
402  /* loop through all pixels and fill the remaining buffers */
403  cpl_msg_debug(__func__, "Computing lambda indices...");
404  cpl_size n;
405 #if _OPENMP >= 201107 /* needed for atomic capture, see below */
406  #pragma omp parallel for default(none) private(k) \
407  shared(aPixtable, data, ifu, indmap, lbda, lbdabins, nlbin, npix, \
408  npts, quad, sli)
409 #endif
410  for (n = 0; n < npix; n++) {
411  unsigned short q;
412  for (q = 1; q < nlbin+1; q++) {
413  if ((lbda[n] >= lbdabins[q-1]) && (lbda[n] < lbdabins[q])) {
414  quad[n] = q;
415  break;
416  }
417  }
418  if (cpl_table_is_selected(aPixtable->table, n)) {
419  k = MAPIDX(ifu[n], sli[n], quad[n]);
420  int i;
421  /* atomic capture is new in OpenMP v3.1 (or _OPENMP=201107), */
422 #if _OPENMP >= 201107 /* needed for atomic capture */
423  #pragma omp atomic capture
424 #endif
425  i = npts[k]++;
426  indmap[k][i] = n;
427  }
428  }
429 
430  float *slice_flux = (float *)cpl_malloc(kMuseSlicesPerCCD * kMuseNumIFUs
431  * sizeof(float)),
432  *ifu_flux = (float *)cpl_malloc(kMuseNumIFUs * 2 * sizeof(float));
433  int *slice_ind1 = (int *)cpl_malloc(kMuseSlicesPerCCD * sizeof(int)),
434  *slice_ind2 = (int *)cpl_malloc(kMuseSlicesPerCCD * sizeof(int)),
435  *tot_ind = (int *)cpl_malloc(kMuseNumIFUs * kMuseSlicesPerCCD
436  * sizeof(int));
437  cpl_msg_debug(__func__, "Computing reference levels and corrections...");
438  unsigned short q;
439  for (q = 0; q < nlbin; q++) {
440  if (debug) {
441  cpl_msg_debug(__func__, "Computing reference levels (lambda range: "
442  "%.1f - %.1f Angstrom)...", lbdabins[q], lbdabins[q+1]);
443  }
444  int i, tot_count = 0;
445  for (i = 0; i < kMuseNumIFUs; i++) {
446  if (debug) {
447  cpl_msg_debug(__func__, "- IFU %02d", i+1);
448  }
449  int slice_count1 = 0,
450  slice_count2 = 0;
451  unsigned short s;
452  for (s = 0; s < kMuseSlicesPerCCD; s++) {
453  k = MAPIDX(i+1, s+1, q+1);
454  int slidx = kMuseSlicesPerCCD * i + s;
455  if (npts[k] > 100) {
456  muse_autocalib_slice_mean(data, xpix, npts[k], x, indmap[k],
457  min_pix_per_slice);
458  if (x[2] > min_pix_per_slice) {
459  slice_flux[slidx] = x[0];
460  if (s < kMuseSlicesPerCCD/2) {
461  slice_ind1[slice_count1++] = slidx;
462  } else {
463  slice_ind2[slice_count2++] = slidx;
464  }
465  tot_ind[tot_count++] = slidx;
466  } else {
467  slice_flux[slidx] = NAN;
468  }
469  } else {
470  slice_flux[slidx] = NAN;
471  }
472  /* cpl_msg_debug(__func__, " - SLICE %02hu : %f (%d)", s+1, */
473  /* slice_flux[slidx], npts[k]); */
474  } /* for s */
475 
476  if (!slice_count1) {
477  ifu_flux[2 * i] = 0.0;
478  } else {
479  muse_autocalib_minmax(slice_flux, slice_count1, slice_ind1, minmax);
480  muse_autocalib_mean_madsigma_clip(slice_flux, slice_count1, x, nmax,
481  nclip_low, nclip_up, nstop,
482  slice_ind1);
483  if (debug) {
484  cpl_msg_debug(__func__, " - 1: Min max = %f %f / Mean = %f (%f, %d)",
485  minmax[0], minmax[1], x[0], x[1], (int)x[2]);
486  }
487  ifu_flux[2 * i] = x[0];
488 
489  if (isnan(x[0])) {
490  cpl_msg_warning(__func__, "Mean IFU flux is NAN (IFU %02d, lambda range"
491  " %.1f - %.1f Angstrom)", i+1, lbdabins[q],
492  lbdabins[q+1]);
493  }
494  }
495 
496  if (!slice_count2) {
497  ifu_flux[2 * i + 1] = 0.0;
498  } else {
499  muse_autocalib_minmax(slice_flux, slice_count2, slice_ind2, minmax);
500  muse_autocalib_mean_madsigma_clip(slice_flux, slice_count2, x, nmax,
501  nclip_low, nclip_up, nstop,
502  slice_ind2);
503  if (debug) {
504  cpl_msg_debug(__func__, " - 2: Min max = %f %f / Mean = %f (%f, %d)",
505  minmax[0], minmax[1], x[0], x[1], (int)x[2]);
506  }
507  ifu_flux[2 * i + 1] = x[0];
508 
509  if (isnan(x[0])) {
510  cpl_msg_warning(__func__, "Mean IFU flux is NAN (IFU %02d, lambda range"
511  " %.1f - %.1f Angstrom)", i+1, lbdabins[q],
512  lbdabins[q+1]);
513  }
514  }
515 
516  /* Use mean ifu flux for slices without useful values */
517  for (s = 0; s < kMuseSlicesPerCCD; s++) {
518  int slidx = kMuseSlicesPerCCD * i + s;
519  if (isnan(slice_flux[slidx])) {
520  if (s < kMuseSlicesPerCCD/2) {
521  slice_flux[slidx] = ifu_flux[2 * i];
522  } else {
523  slice_flux[slidx] = ifu_flux[2 * i + 1];
524  }
525  }
526  } /* for s */
527  } /* for i */
528  if (!tot_count) {
529  cpl_msg_warning(__func__, "No values in this lambda range (%.1f - %.1f "
530  "Angstrom)", lbdabins[q], lbdabins[q+1]);
531  continue;
532  }
533  muse_autocalib_minmax(slice_flux, tot_count, tot_ind, minmax);
534  if (debug) {
535  cpl_msg_debug(__func__, "- Min max : %f %f", minmax[0], minmax[1]);
536  }
537 
538  muse_autocalib_mean_sigma_clip(slice_flux, tot_count, x, nmax, nclip_low,
539  nclip_up, nstop, tot_ind);
540  if (debug) {
541  cpl_msg_debug(__func__, "- Total flux : %f (%f, %d)", x[0], x[1],
542  (int)x[2]);
543  }
544  tot_flux = x[0];
545 
546  if (debug) {
547  cpl_msg_debug(__func__, "Computing corrections...");
548  }
549  for (i = 0; i < kMuseNumIFUs; i++) {
550  if (debug) {
551  cpl_msg_debug(__func__, "- IFU %02d", i+1);
552  }
553  int slice_count1 = 0,
554  slice_count2 = 0;
555  unsigned short s;
556  for (s = 0; s < kMuseSlicesPerCCD; s++) {
557  k = MAPIDX(i+1, s+1, q+1);
558  int slidx = kMuseSlicesPerCCD * i + s;
559  if (npts[k] != 0) {
560  if (s < kMuseSlicesPerCCD/2) {
561  slice_ind1[slice_count1++] = k;
562  } else {
563  slice_ind2[slice_count2++] = k;
564  }
565  corr[k] = tot_flux / slice_flux[slidx];
566  /* cpl_msg_debug(__func__, " - SLICE %02hu : %f", s+1, corr[k]); */
567  }
568  } /* for s */
569  if ((slice_count1 + slice_count2) == 0) {
570  cpl_msg_warning(__func__, "No values in this IFU (%02d, lambda range: "
571  "%.1f - %.1f Angstrom)", i+1, lbdabins[q],
572  lbdabins[q+1]);
573  continue;
574  }
575 
576  if (slice_count1) {
577  muse_autocalib_minmax(corr, slice_count1, slice_ind1, minmax);
578  muse_autocalib_mean_madsigma_clip(corr, slice_count1, x1, nmax,
579  nclip_low, nclip_up, nstop,
580  slice_ind1);
581  if (debug) {
582  cpl_msg_debug(__func__, " - 1: Min max = %f %f / Mean = %f (%f, %d)",
583  minmax[0], minmax[1], x1[0], x1[1], (int)x1[2]);
584  }
585  }
586 
587  if (slice_count2) {
588  muse_autocalib_minmax(corr, slice_count2, slice_ind2, minmax);
589  muse_autocalib_mean_madsigma_clip(corr, slice_count2, x2, nmax,
590  nclip_low, nclip_up, nstop,
591  slice_ind2);
592  if (debug) {
593  cpl_msg_debug(__func__, " - 2: Min max = %f %f / Mean = %f (%f, %d)",
594  minmax[0], minmax[1], x2[0], x2[1], (int)x2[2]);
595  }
596  }
597 
598  /* cpl_msg_debug(__func__, " - Checking slice corrections (%.1f sigma clip)...", */
599  /* aClip); */
600  for (s = 0; s < kMuseSlicesPerCCD; s++) {
601  k = MAPIDX(i+1, s+1, q+1);
602  if (s < kMuseSlicesPerCCD/2) {
603  if (!slice_count1) {
604  continue;
605  }
606  refx = x1;
607  refflux = ifu_flux[2 * i];
608  } else {
609  if (!slice_count2) {
610  continue;
611  }
612  refx = x2;
613  refflux = ifu_flux[2 * i + 1];
614  }
615  if (fabs(corr[k] - refx[0]) > aClip * refx[1]) {
616  oldcorr = corr[k];
617  corr[k] = tot_flux / refflux;
618  if (debug) {
619  cpl_msg_debug(__func__, " - SLICE %02hu : %f -> Using IFU Mean : "
620  "%f", s+1, oldcorr, corr[k]);
621  }
622  }
623  } /* for s */
624  } /* for i */
625  } /* for q */
626 
627  /* create optional output table with determined properties */
628  if (aFactors) {
629  *aFactors = muse_table_new();
630  (*aFactors)->table = muse_cpltable_new(muse_autocal_results_def,
631  kMuseNumIFUs * kMuseSlicesPerCCD * nlbin);
632  /* create header based on the input pixel table */
633  (*aFactors)->header = cpl_propertylist_duplicate(aPixtable->header);
634  cpl_propertylist_erase_regexp((*aFactors)->header, MUSE_HDR_PT_REGEXP, 0);
635  /* save original correction factor as extra column */
636  cpl_table_new_column((*aFactors)->table, "corr_orig", CPL_TYPE_DOUBLE);
637  } /* if aFactors */
638 
639  cpl_msg_debug(__func__, "Cleaning and recording corrections...");
640  // XXX hack: reset faulty correction factors...
641  int nnan = 0;
642  for (k = 0; k < kMuseNumIFUs * kMuseSlicesPerCCD * nlbin; k++) {
643  if (isnan(corr[k])) {
644  corr[k] = 1.;
645  nnan++;
646  }
647  }
648  if (nnan > 0) {
649  cpl_msg_warning(__func__, "%d of %d wavelength bins in %d slices stay "
650  "uncorrected!", nnan, kMuseNumIFUs * kMuseSlicesPerCCD * nlbin,
651  kMuseNumIFUs * kMuseSlicesPerCCD);
652  }
653  int i;
654  for (i = 1; i <= kMuseNumIFUs; i++) {
655  unsigned short s;
656  for (s = 1; s <= kMuseSlicesPerCCD; s++) {
657  for (q = 1; q <= nlbin; q++) {
658  k = MAPIDX(i, s, q);
659  if (aFactors) {
660  /* record slice properties in the table */
661  cpl_table_set_int((*aFactors)->table, "ifu", k, i);
662  cpl_table_set_int((*aFactors)->table, "sli", k, s);
663  cpl_table_set_int((*aFactors)->table, "quad", k, q);
664  cpl_table_set_int((*aFactors)->table, "npts", k, npts[k]);
665  cpl_table_set_double((*aFactors)->table, "corr", k, corr[k]);
666  /* store wavelength range in header */
667  if (i == 1 && s == 1) {
668  char *kw1 = cpl_sprintf("ESO DRS MUSE LAMBDA%d MIN", q),
669  *kw2 = cpl_sprintf("ESO DRS MUSE LAMBDA%d MAX", q);
670  cpl_propertylist_append_float((*aFactors)->header, kw1, lbdabins[q-1]);
671  cpl_propertylist_append_float((*aFactors)->header, kw2, lbdabins[q]);
672  cpl_propertylist_set_comment((*aFactors)->header, kw1,
673  "[Angstrom] lower end of wavelength range");
674  cpl_propertylist_set_comment((*aFactors)->header, kw2,
675  "[Angstrom] upper end of wavelength range");
676  cpl_free(kw1);
677  cpl_free(kw2);
678  } /* if first slice */
679  }
680 
681  cpl_size kprev, knext;
682  if (q == 1) {
683  kprev = MAPIDX(i, s, q+1);
684  knext = MAPIDX(i, s, q+2);
685  } else if (q == nlbin) {
686  kprev = MAPIDX(i, s, q-1);
687  knext = MAPIDX(i, s, q-2);
688  } else {
689  kprev = MAPIDX(i, s, q-1);
690  knext = MAPIDX(i, s, q+1);
691  }
692  meanq = (corr[kprev] + corr[knext]) / 2.;
693  threshq = CPL_MAX(0.03, 3 * fabsf(corr[kprev] - corr[knext]));
694  if (fabsf(corr[k] - meanq) > threshq) {
695  if (aFactors) { /* store both original and revised factor */
696  cpl_table_set_double((*aFactors)->table, "corr_orig", k, corr[k]);
697  cpl_table_set_double((*aFactors)->table, "corr", k, meanq);
698  }
699  if (debug) {
700  cpl_msg_debug(__func__, "- %02d / %02hu / %02hu : %f -> %f",
701  i, s, q, corr[k], meanq);
702  }
703  corr[k] = meanq;
704  } /* if */
705  } /* for q */
706  } /* for s */
707  } /* for i */
708 
709  cpl_msg_debug(__func__, "Applying corrections...");
710  #pragma omp parallel for default(none) private(k) \
711  shared(corr, data, ifu, npix, quad, sli, stat)
712  for (n = 0; n < npix; n++) {
713  k = MAPIDX(ifu[n], sli[n], quad[n]);
714  float c = corr[k];
715  data[n] *= c;
716  stat[n] *= c * c;
717  }
718  muse_utils_memory_dump("ac_max");
719 
720  /* cleanup the remaining allocations */
721  for (k = 0; k < kMuseNumIFUs * kMuseSlicesPerCCD * nlbin; k++) {
722  cpl_free(indmap[k]);
723  }
724  cpl_free(slice_flux);
725  cpl_free(ifu_flux);
726  cpl_free(slice_ind1);
727  cpl_free(slice_ind2);
728  cpl_free(tot_ind);
729  cpl_free(ifu);
730  cpl_free(sli);
731  cpl_free(quad);
732  cpl_free(xpix);
733  cpl_free(npts);
734  cpl_free(corr);
735 
736  /* add the header */
737  cpl_propertylist_update_string(aPixtable->header, MUSE_HDR_PT_AUTOCAL_NAME,
738  "slice-median");
739  char *comment = cpl_sprintf(MUSE_HDR_PT_AUTOCAL_COMMENT, aClip);
740  cpl_propertylist_set_comment(aPixtable->header, MUSE_HDR_PT_AUTOCAL_NAME,
741  comment);
742  cpl_free(comment);
743 
744  cpl_msg_debug(__func__, "... done. Self-calibration took %gs (CPU time), %gs "
745  "(wall-clock)", cpl_test_get_cputime() - cputime,
746  cpl_test_get_walltime() - walltime);
747 
748  return CPL_ERROR_NONE;
749 } /* muse_autocalib_slice_median() */
750 
751 /*---------------------------------------------------------------------------*/
769 /*---------------------------------------------------------------------------*/
770 muse_mask *
771 muse_autocalib_create_mask(muse_image *aImage, double aNSigma,
772  const char *aQCPrefix)
773 {
774  cpl_ensure(aImage, CPL_ERROR_NULL_INPUT, NULL);
775 
777 
778  double median, mad;
779  median = cpl_image_get_mad(aImage->data, &mad);
780  double t0 = median - aNSigma * mad,
781  t1 = median + aNSigma * mad;
782  cpl_msg_info(__func__, "Computing sky mask (median = %g, mad = %g)", median,
783  mad);
784 
785  /* create output mask with pixels between min and threshold */
786  muse_mask *selected = muse_mask_new();
787  selected->mask = cpl_mask_threshold_image_create(aImage->data, t0, t1);
788  cpl_mask_not(selected->mask);
789 #if 0
790  muse_mask_save(selected, "muse_autocalib_mask1.fits");
791 #endif
792 
793  /* Use a morphological opening to remove the single pixel detections */
794  /* These two should not be able to fail */
795  cpl_mask *kernel = cpl_mask_new(3, 3);
796  cpl_mask_not(kernel);
797 
798  cpl_mask_filter(selected->mask, selected->mask, kernel, CPL_FILTER_OPENING,
799  CPL_BORDER_COPY);
800  cpl_mask *tmp = cpl_mask_duplicate(selected->mask);
801  cpl_mask_filter(tmp, selected->mask, kernel, CPL_FILTER_DILATION,
802  CPL_BORDER_NOP);
803  cpl_mask_filter(selected->mask, tmp, kernel, CPL_FILTER_DILATION,
804  CPL_BORDER_NOP);
805  cpl_mask_delete(tmp);
806  cpl_mask_delete(kernel);
807 
808  cpl_mask_not(selected->mask);
809 
810  /* add threshold as QC parameter */
811  selected->header = cpl_propertylist_duplicate(aImage->header);
812  if (aQCPrefix) {
813  char keyword[KEYWORD_LENGTH];
814  snprintf(keyword, KEYWORD_LENGTH, "%s LOWLIMIT", aQCPrefix);
815  cpl_propertylist_append_double(selected->header, keyword, t0);
816  snprintf(keyword, KEYWORD_LENGTH, "%s THRESHOLD", aQCPrefix);
817  cpl_propertylist_append_double(selected->header, keyword, t1);
818  }
819 
820 #if 0
821  muse_mask_save(selected, "muse_autocalib_mask2.fits");
822 #endif
823 
824  return selected;
825 } /* muse_autocalib_create_mask() */
826 
#define MUSE_HDR_PT_AUTOCAL_NAME
const muse_cpltable_def muse_autocal_results_def[]
cpl_image * data
the data extension
Definition: muse_image.h:46
cpl_size muse_pixtable_get_nrow(const muse_pixtable *aPixtable)
get the number of rows within the pixel table
void muse_utils_memory_dump(const char *aMarker)
Display the current memory usage of the given program.
Definition: muse_utils.c:2702
muse_table * muse_table_new(void)
Allocate memory for a new muse_table object.
Definition: muse_table.c:63
Structure definition of MUSE three extension FITS file.
Definition: muse_image.h:40
cpl_table * table
The pixel table.
cpl_propertylist * header
the FITS header
Definition: muse_image.h:72
cpl_error_code muse_pixtable_origin_decode_all(muse_pixtable *aPixtable, unsigned short **aX, unsigned short **aY, unsigned char **aIFU, unsigned char **aSlice)
Fill arrays with decoded entries from the origin column.
#define MUSE_PIXTABLE_DATA
Definition: muse_pixtable.h:48
cpl_table * muse_cpltable_new(const muse_cpltable_def *aDef, cpl_size aLength)
Create an empty table according to the specified definition.
Structure definition of MUSE pixel table.
cpl_error_code muse_mask_save(muse_mask *aMask, const char *aFilename)
Save the data and the FITS headers of a MUSE mask to a file.
Definition: muse_mask.c:143
cpl_error_code muse_autocalib_slice_median(muse_pixtable *aPixtable, double aClip, muse_table **aFactors)
Correct the background level of the slices (port from MPDAF).
Structure to store a table together with a property list.
Definition: muse_table.h:43
muse_mask * muse_mask_new(void)
Allocate memory for a new muse object.
Definition: muse_mask.c:61
muse_mask * muse_autocalib_create_mask(muse_image *aImage, double aNSigma, const char *aQCPrefix)
Create Select spaxels to be considered as sky for autocalibration.
#define MUSE_PIXTABLE_STAT
Definition: muse_pixtable.h:50
Handling of "mask" files.
Definition: muse_mask.h:43
cpl_error_code muse_image_reject_from_dq(muse_image *aImage)
Reject pixels of a muse_image depending on its DQ data.
Definition: muse_image.c:863
#define MUSE_PIXTABLE_LAMBDA
Definition: muse_pixtable.h:53
cpl_propertylist * header
the FITS header
Definition: muse_mask.h:56
cpl_mask * mask
The mask data.
Definition: muse_mask.h:49
muse_ins_mode muse_pfits_get_mode(const cpl_propertylist *aHeaders)
find out the observation mode
Definition: muse_pfits.c:1352
cpl_propertylist * header
The FITS header.