MUSE Pipeline Reference Manual  2.5.2
muse_wavecalib.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) 2005-2017 European Southern Observatory
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20  */
21 
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25 
26 /*----------------------------------------------------------------------------*
27  * Includes *
28  *----------------------------------------------------------------------------*/
29 #if HAVE_POPEN && HAVE_PCLOSE
30 #define _BSD_SOURCE /* force popen/pclose, mkdtemp definitions from stdio/stdlib */
31 #endif
32 #include <cpl.h>
33 #include <math.h>
34 #include <string.h>
35 
36 #include "muse_wavecalib.h"
37 #include "muse_instrument.h"
38 
39 #include "muse_combine.h"
40 #include "muse_cplwrappers.h"
41 #include "muse_data_format_z.h"
42 #include "muse_dfs.h"
43 #include "muse_tracing.h"
44 #include "muse_utils.h"
45 
46 /*----------------------------------------------------------------------------*
47  * Debugging Macros *
48  * Set these to 1 or higher for (lots of) debugging output *
49  *----------------------------------------------------------------------------*/
50 #define SEARCH_DEBUG 0 /* debugging in muse_wave_lines_search(), 1 or higher */
51 #define SEARCH_DEBUG_FILES 0 /* save different versions of the columns into *
52  * FITS files in muse_wave_lines_search() */
53 #define DEBUG_GAUSSFIT 0 /* debugging the Gaussian fit in muse_wave_lines_search() */
54 #define MUSE_WAVE_LINES_SEARCH_SHIFT_WARN 3.0 /* [pix] output debug message if *
55  * a shift of more than this occurs */
56 #define MUSE_WAVE_LINE_FIT_MAXSHIFT 2.0 /* [pix] don't use the fit when a shift *
57  * of more than this is detected */
58 #define MUSE_WAVE_LINE_HANDLE_SHIFT_LIMIT 0.25 /* [pix] maximum shift between *
59  * adjacent CCD columns */
60 
61 /*----------------------------------------------------------------------------*/
65 /*----------------------------------------------------------------------------*/
66 
69 /*----------------------------------------------------------------------------*/
94 /*----------------------------------------------------------------------------*/
96  { "lampno", CPL_TYPE_INT, "", "%d", "Number of the lamp", CPL_TRUE },
97  { "lampname", CPL_TYPE_STRING, "", "%s", "Name of the lamp", CPL_TRUE },
98  { "x", CPL_TYPE_DOUBLE, "pix", "%.2f", "x-position on CCD", CPL_TRUE },
99  { "y", CPL_TYPE_DOUBLE, "pix", "%.2f", "first-guess y-position on CCD", CPL_TRUE },
100  { "peak", CPL_TYPE_DOUBLE, "pix", "%g", "Peak of line", CPL_TRUE },
101  { "center", CPL_TYPE_DOUBLE, "pix", "%.4f", "Gaussian line center", CPL_TRUE },
102  { "cerr", CPL_TYPE_DOUBLE, "pix", "%.4f", "error estimate of line center", CPL_TRUE },
103  { "sigma", CPL_TYPE_DOUBLE, "pix", "%.3f", "Gaussian sigma", CPL_TRUE },
104  { "fwhm", CPL_TYPE_DOUBLE, "pix", "%.3f", "Gaussian FWHM", CPL_TRUE },
105  { "flux", CPL_TYPE_DOUBLE, "count", "%g", "Gaussian area (flux)", CPL_TRUE },
106  { "bg", CPL_TYPE_DOUBLE, "count", "%.2f", "background level", CPL_TRUE },
107  { "mse", CPL_TYPE_DOUBLE, "", "%e", "mean squared error", CPL_TRUE },
108  { "lambda", CPL_TYPE_DOUBLE, "Angstrom", "%9.3f",
109  "identified wavelength of the line", CPL_TRUE },
110  { NULL, 0, NULL, NULL, NULL, CPL_FALSE }
111 };
112 
113 /*----------------------------------------------------------------------------*/
117 /*----------------------------------------------------------------------------*/
119  { "slice", CPL_TYPE_INT, "", "%02d", "slice number", CPL_TRUE},
120  { "iteration", CPL_TYPE_INT, "", "%d", "iteration", CPL_TRUE},
121  { "x", CPL_TYPE_INT, "pix", "%04d", "x-position on CCD", CPL_TRUE},
122  { "y", CPL_TYPE_FLOAT, "pix", "%8.3f", "y-position on CCD", CPL_TRUE},
123  { "lambda", CPL_TYPE_FLOAT, "Angstrom", "%8.3f", "wavelength", CPL_TRUE},
124  { "residual", CPL_TYPE_DOUBLE, "Angstrom", "%.4e", "residual at this point", CPL_TRUE},
125  { "rejlimit", CPL_TYPE_DOUBLE, "Angstrom", "%.4e",
126  "rejection limit for this iteration", CPL_TRUE},
127  { NULL, 0, NULL, NULL, NULL, CPL_FALSE }
128 };
129 
130 /* corresponds to muse_wave_weighting_type, *
131  * keep in sync with those values! */
132 const char *muse_wave_weighting_string[] = {
133  "uniform",
134  "centroid error",
135  "per-line RMS scatter",
136  "centroid error plus per-line RMS scatter"
137 };
138 
139 /*----------------------------------------------------------------------------*/
156 /*----------------------------------------------------------------------------*/
158 muse_wave_params_new(cpl_propertylist *aHeader)
159 {
160  muse_wave_params *p = cpl_malloc(sizeof(muse_wave_params));
161  /* set defaults */
162  p->xorder = 2;
163  p->yorder = 6;
164  p->detsigma = 1.;
165  p->ddisp = 0.05; /* from 1.20...1.30 Angstrom/pixel */
166  p->tolerance = 0.1;
167  p->linesigma = -1.;
168  p->rflag = CPL_FALSE; /* do not create a residuals table by default */
169  p->residuals = NULL;
170  p->fitsigma = -1.;
172  p->targetrms = 0.03;
173  if (aHeader) { /* otherwise p->mode stays zero which means WFM-NOAO-N */
174  p->mode = muse_pfits_get_mode(aHeader);
175  cpl_msg_debug(__func__, "Set mode %s (%d)", muse_pfits_get_insmode(aHeader),
176  p->mode);
177  }
178  return p;
179 }
180 
181 /*----------------------------------------------------------------------------*/
191 /*----------------------------------------------------------------------------*/
192 void
194 {
195  if (!aParams) {
196  return;
197  }
198  cpl_table_delete(aParams->residuals);
199  aParams->residuals = NULL;
200  memset(aParams, 0, sizeof(muse_wave_params)); /* null out everything */
201  cpl_free(aParams);
202 }
203 
204 /*----------------------------------------------------------------------------*/
216 /*----------------------------------------------------------------------------*/
217 static void
218 muse_wave_calib_qc_peaks(cpl_table *aLines, cpl_propertylist *aHeader,
219  const unsigned short aSlice)
220 {
221  char keyword[KEYWORD_LENGTH];
222  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LINES_PEAK_MEAN, aSlice);
223  cpl_propertylist_append_float(aHeader, keyword,
224  cpl_table_get_column_mean(aLines, "peak"));
225  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LINES_PEAK_STDEV, aSlice);
226  cpl_propertylist_append_float(aHeader, keyword,
227  cpl_table_get_column_stdev(aLines, "peak"));
228  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LINES_PEAK_MIN, aSlice);
229  cpl_propertylist_append_float(aHeader, keyword,
230  cpl_table_get_column_min(aLines, "peak"));
231  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LINES_PEAK_MAX, aSlice);
232  cpl_propertylist_append_float(aHeader, keyword,
233  cpl_table_get_column_max(aLines, "peak"));
234  if (aSlice != 20) {
235  return;
236  }
237  /* if we are in slice 20 (a slice that is near the middle of a stack, *
238  * so should never be vignetted, loop through all possible lamps */
239  int n, nlamps = muse_pfits_get_lampnum(aHeader);
240  for (n = 1; n < nlamps; n++) {
241  /* select and extract all table entries matching the lamp */
242  cpl_table_unselect_all(aLines);
243  cpl_table_or_selected_int(aLines, "lampno", CPL_EQUAL_TO, n);
244  cpl_table *lamplines = cpl_table_extract_selected(aLines);
245  if (cpl_table_get_nrow(lamplines) < 1) {
246  cpl_table_delete(lamplines);
247  continue;
248  }
249  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LAMPl_LINES_PEAK_MEAN,
250  aSlice, n);
251  cpl_propertylist_append_float(aHeader, keyword,
252  cpl_table_get_column_mean(lamplines, "peak"));
253  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LAMPl_LINES_PEAK_STDEV,
254  aSlice, n);
255  cpl_propertylist_append_float(aHeader, keyword,
256  cpl_table_get_column_stdev(lamplines, "peak"));
257  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LAMPl_LINES_PEAK_MAX,
258  aSlice, n);
259  cpl_propertylist_append_float(aHeader, keyword,
260  cpl_table_get_column_max(lamplines, "peak"));
261  cpl_table_delete(lamplines);
262  } /* for n (all lamps) */
263 } /* muse_wave_calib_qc_peaks() */
264 
265 /*----------------------------------------------------------------------------*/
274 /*----------------------------------------------------------------------------*/
275 static void
276 muse_wave_calib_qc_fwhm_old(cpl_table *aLines, cpl_propertylist *aHeader,
277  cpl_vector *aRefLam, const unsigned short aSlice)
278 {
279  int nlines = cpl_table_get_nrow(aLines);
280 
281  /* track the minimum and maximum resolutions and their wavelengths */
282  double Rmin = DBL_MAX, Rmax = -DBL_MAX, wlmin = DBL_MAX, wlmax = -DBL_MAX;
283 
284  /* convert the properties of the relevant lines from the respective *
285  * table columns into vectors for easy statistics computation */
286  cpl_vector *fwhms = cpl_vector_new(nlines),
287  *resol = cpl_vector_new(cpl_vector_get_size(aRefLam));
288  int i, iresol = 0;
289  for (i = 0; i < nlines; i++) {
290  /* FWHM is directly accessible, but needs to be converted to Angstrom */
291  cpl_errorstate prestate = cpl_errorstate_get();
292  double fwhm = cpl_table_get(aLines, "fwhm", i, NULL), /* in [pix] */
293  sampling = kMuseSpectralSamplingA, /* sensible default in [A/pix] */
294  lambda = cpl_table_get(aLines, "lambda", i, NULL),
295  s1 = (lambda - cpl_table_get(aLines, "lambda", i - 1, NULL))
296  / (cpl_table_get(aLines, "center", i, NULL)
297  - cpl_table_get(aLines, "center", i - 1, NULL)),
298  s2 = (cpl_table_get(aLines, "lambda", i + 1, NULL)
299  - cpl_table_get(aLines, "lambda", i, NULL))
300  / (cpl_table_get(aLines, "center", i + 1, NULL)
301  - cpl_table_get(aLines, "center", i, NULL));
302  if (!cpl_errorstate_is_equal(prestate)) {
303  cpl_errorstate_set(prestate); /* reset "Access beyond boundaries" errors */
304  }
305  if (i == 0) { /* no lower one */
306  sampling = s2;
307  } else if (i == nlines - 1) { /* no higher one */
308  sampling = s1;
309  } else {
310  sampling = (s1 + s2) / 2.;
311  }
312  fwhm *= sampling; /* now in [A] */
313  cpl_vector_set(fwhms, i, fwhm);
314  /* spectral resolution R for this line R = lambda / dlambda */
315  double R = lambda / fwhm;
316  /* compare wavelength to those lines in the FWHM reference list */
317  if (fabs(cpl_vector_get(aRefLam, cpl_vector_find(aRefLam, lambda)) - lambda)
318  < FLT_EPSILON) {
319  if (R < Rmin) {
320  Rmin = R;
321  wlmin = lambda;
322  }
323  if (R > Rmax) {
324  Rmax = R;
325  wlmax = lambda;
326  }
327  cpl_vector_set(resol, iresol++, R);
328  }
329  } /* for i (all arc lines) */
330  cpl_vector_set_size(resol, iresol);
331 
332  char keyword[KEYWORD_LENGTH];
333  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LINES_FWHM_MEAN, aSlice);
334  cpl_propertylist_append_float(aHeader, keyword, cpl_vector_get_mean(fwhms));
335  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LINES_FWHM_STDEV, aSlice);
336  cpl_propertylist_append_float(aHeader, keyword, cpl_vector_get_stdev(fwhms));
337  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LINES_FWHM_MIN, aSlice);
338  cpl_propertylist_append_float(aHeader, keyword, cpl_vector_get_min(fwhms));
339  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LINES_FWHM_MAX, aSlice);
340  cpl_propertylist_append_float(aHeader, keyword, cpl_vector_get_max(fwhms));
341  cpl_vector_delete(fwhms);
342 
343  cpl_msg_debug(__func__, "Average spectral resolution in IFU %hhu is R=%4.0f, "
344  "ranging from %4.0f (at %6.1fA) to %4.0f (at %6.1fA)",
345  muse_utils_get_ifu(aHeader), cpl_vector_get_mean(resol),
346  Rmin, wlmin, Rmax, wlmax);
347  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_RESOL, aSlice);
348  cpl_propertylist_append_float(aHeader, keyword, cpl_vector_get_mean(resol));
349  cpl_vector_delete(resol);
350 } /* muse_wave_calib_qc_fwhm_old() */
351 
352 /*----------------------------------------------------------------------------*/
360 /*----------------------------------------------------------------------------*/
361 static void
362 muse_wave_calib_qc_fwhm(cpl_table *aFWHM, cpl_propertylist *aHeader,
363  const unsigned short aSlice)
364 {
365  /* compute the spectral resolution at each wavelength, as *
366  * R = lambda / fwhm *
367  * where both lambda and fwhm are [Angstrom] */
368  cpl_table_duplicate_column(aFWHM, "R", aFWHM, "lambda");
369  cpl_table_divide_columns(aFWHM, "R", "fwhm");
370  cpl_table_set_column_unit(aFWHM, "R", "");
371 
372 #if 0 /* AIT Gaussian FWHM */
373  /* range < 600 nm (as in PR5) */
374  cpl_table_unselect_all(aFWHM);
375  cpl_table_or_selected_double(aFWHM, "lambda", CPL_LESS_THAN, 6000.);
376  cpl_table *tblue = cpl_table_extract_selected(aFWHM);
377  /* range > 800 nm (as in PR5) */
378  cpl_table_unselect_all(aFWHM);
379  cpl_table_or_selected_double(aFWHM, "lambda", CPL_GREATER_THAN, 8000.);
380  cpl_table *tred = cpl_table_extract_selected(aFWHM);
381  /* range 600 - 800 nm (as in PR5) */
382  cpl_table_unselect_all(aFWHM);
383  cpl_table_or_selected_double(aFWHM, "lambda", CPL_NOT_LESS_THAN, 6000.);
384  cpl_table_and_selected_double(aFWHM, "lambda", CPL_NOT_GREATER_THAN, 8000.);
385  cpl_table *tgreen = cpl_table_extract_selected(aFWHM);
386 #if 0
387  printf("all:\n");
388  cpl_table_dump(aFWHM, 0, 100000, stdout);
389  fflush(stdout);
390  printf("blue:\n");
391  cpl_table_dump(tblue, 0, 100000, stdout);
392  fflush(stdout);
393  printf("green:\n");
394  cpl_table_dump(tgreen, 0, 100000, stdout);
395  fflush(stdout);
396  printf("red:\n");
397  cpl_table_dump(tred, 0, 100000, stdout);
398  fflush(stdout);
399 #endif
400 #endif /* AIT Gaussian FWHM */
401 
402  /* fill the QC parameters */
403  char keyword[KEYWORD_LENGTH];
404  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_RESOL, aSlice);
405  double rmean = cpl_table_get_column_mean(aFWHM, "R");
406  cpl_propertylist_update_float(aHeader, keyword, rmean);
407 
408  double fmean = cpl_table_get_column_mean(aFWHM, "fwhm"),
409  fstdev = cpl_table_get_column_stdev(aFWHM, "fwhm"),
410  flo = cpl_table_get_column_min(aFWHM, "fwhm"),
411  fhi = cpl_table_get_column_max(aFWHM, "fwhm");
412  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LINES_FWHM_MEAN, aSlice);
413  cpl_propertylist_update_float(aHeader, keyword, fmean);
414  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LINES_FWHM_STDEV, aSlice);
415  cpl_propertylist_update_float(aHeader, keyword, fstdev);
416  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LINES_FWHM_MIN, aSlice);
417  cpl_propertylist_update_float(aHeader, keyword, flo);
418  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LINES_FWHM_MAX, aSlice);
419  cpl_propertylist_update_float(aHeader, keyword, fhi);
420 
421 #if 0 /* AIT Gaussian FWHM */
422  /* output all the stuff as debug messages */
423  cpl_msg_debug(__func__, "Gaussian FWHM [%s]:\n"
424  "\tFWHM all (%d values)\t%.3f +/- %.3f (%.3f) %.3f...%.3f\n"
425  "\tFWHM blue (%d values)\t%.3f +/- %.3f (%.3f)\n"
426  "\tFWHM green (%d values)\t%.3f +/- %.3f (%.3f)\n"
427  "\tFWHM red (%d values)\t%.3f +/- %.3f (%.3f)",
428  cpl_table_get_column_unit(aFWHM, "fwhm"),
429  (int)cpl_table_get_nrow(aFWHM), fmean, fstdev, flo, fhi,
430  cpl_table_get_column_median(aFWHM, "fwhm"),
431  (int)cpl_table_get_nrow(tblue),
432  cpl_table_get_column_mean(tblue, "fwhm"),
433  cpl_table_get_column_stdev(tblue, "fwhm"),
434  cpl_table_get_column_median(tblue, "fwhm"),
435  (int)cpl_table_get_nrow(tgreen),
436  cpl_table_get_column_mean(tgreen, "fwhm"),
437  cpl_table_get_column_stdev(tgreen, "fwhm"),
438  cpl_table_get_column_median(tgreen, "fwhm"),
439  (int)cpl_table_get_nrow(tred),
440  cpl_table_get_column_mean(tred, "fwhm"),
441  cpl_table_get_column_stdev(tred, "fwhm"),
442  cpl_table_get_column_median(tred, "fwhm"));
443  cpl_msg_debug(__func__, "Gaussian spectral resolution R:\n"
444  "\tR all (%d values)\t%.1f +/- %.1f (%.1f) %.1f...%.1f\n"
445  "\tR blue (%d values)\t%.1f +/- %.1f (%.1f)\n"
446  "\tR green (%d values)\t%.1f +/- %.1f (%.1f)\n"
447  "\tR red (%d values)\t%.1f +/- %.1f (%.1f)",
448  (int)cpl_table_get_nrow(aFWHM), rmean,
449  cpl_table_get_column_stdev(aFWHM, "R"),
450  cpl_table_get_column_median(aFWHM, "R"),
451  cpl_table_get_column_min(aFWHM, "R"),
452  cpl_table_get_column_max(aFWHM, "R"),
453  (int)cpl_table_get_nrow(tblue),
454  cpl_table_get_column_mean(tblue, "R"),
455  cpl_table_get_column_stdev(tblue, "R"),
456  cpl_table_get_column_median(tblue, "R"),
457  (int)cpl_table_get_nrow(tgreen),
458  cpl_table_get_column_mean(tgreen, "R"),
459  cpl_table_get_column_stdev(tgreen, "R"),
460  cpl_table_get_column_median(tgreen, "R"),
461  (int)cpl_table_get_nrow(tred),
462  cpl_table_get_column_mean(tred, "R"),
463  cpl_table_get_column_stdev(tred, "R"),
464  cpl_table_get_column_median(tred, "R"));
465  cpl_table_delete(tblue);
466  cpl_table_delete(tgreen);
467  cpl_table_delete(tred);
468 #endif /* AIT Gaussian FWHM */
469  cpl_table_erase_column(aFWHM, "R");
470 } /* muse_wave_calib_qc_fwhm() */
471 
472 /*----------------------------------------------------------------------------*/
484 /*----------------------------------------------------------------------------*/
485 static void
486 muse_wave_calib_qc_lambda(muse_image *aImage, const unsigned short aSlice,
487  cpl_polynomial **aTrace, cpl_polynomial *aFit)
488 {
489  int ny = cpl_image_get_size_y(aImage->data);
490  unsigned char ifu = muse_utils_get_ifu(aImage->header);
491 
492  /* wavelength differences at bottom and top of each slice as QC parameters */
493  double xbotl = cpl_polynomial_eval_1d(aTrace[MUSE_TRACE_LEFT], 1, NULL),
494  xbotr = cpl_polynomial_eval_1d(aTrace[MUSE_TRACE_RIGHT], 1, NULL),
495  xtopl = cpl_polynomial_eval_1d(aTrace[MUSE_TRACE_LEFT], ny, NULL),
496  xtopr = cpl_polynomial_eval_1d(aTrace[MUSE_TRACE_RIGHT], ny, NULL);
497  cpl_vector *pos = cpl_vector_new(2);
498  cpl_vector_set(pos, 0, xbotl);
499  cpl_vector_set(pos, 1, 1);
500  double wlbotl = cpl_polynomial_eval(aFit, pos);
501  cpl_vector_set(pos, 0, xbotr);
502  cpl_vector_set(pos, 1, 1);
503  double wlbotr = cpl_polynomial_eval(aFit, pos);
504  cpl_vector_set(pos, 0, xtopl);
505  cpl_vector_set(pos, 1, ny);
506  double wltopl = cpl_polynomial_eval(aFit, pos);
507  cpl_vector_set(pos, 0, xtopr);
508  cpl_vector_set(pos, 1, ny);
509  double wltopr = cpl_polynomial_eval(aFit, pos);
510 #if 0
511  cpl_msg_debug(__func__, "Wavelengths at slice corners in slice %hu of IFU %hhu: "
512  "botl(%.2f,1)=%f, botr(%.2f,1)=%f, topl(%.2f,%d)=%f, topr(%.2f,%d)"
513  "=%f", aSlice, ifu, xbotl, wlbotl, xbotr, wlbotr,
514  xtopl, ny, wltopl, xtopr, ny, wltopr);
515 #endif
516  char *keyword = cpl_sprintf(QC_WAVECAL_SLICEj_DWLEN_BOT, aSlice);
517  cpl_propertylist_append_float(aImage->header, keyword, wlbotl - wlbotr);
518  cpl_free(keyword);
519  keyword = cpl_sprintf(QC_WAVECAL_SLICEj_DWLEN_TOP, aSlice);
520  cpl_propertylist_append_float(aImage->header, keyword, wltopl - wltopr);
521  cpl_free(keyword);
522 
523 #define DWLEN_WARN_LIMIT_N 6.5 /* 5.7 Angstrom differences can happen... */
524 #define DWLEN_WARN_LIMIT_E 5.9 /* ... at the bottom in both modes */
525  double limit = DWLEN_WARN_LIMIT_E;
526  cpl_errorstate prestate = cpl_errorstate_get();
527  if (muse_pfits_get_mode(aImage->header) != MUSE_MODE_WFM_NONAO_E &&
528  muse_pfits_get_mode(aImage->header) != MUSE_MODE_WFM_AO_E) {
529  limit = DWLEN_WARN_LIMIT_N;
530  }
531  cpl_errorstate_set(prestate); /* swallow possible error about missing INS MODE */
532  if (fabs(wlbotl - wlbotr) > limit) {
533  cpl_msg_warning(__func__, "Wavelength differences at bottom of slice %hu "
534  "of IFU %hhu are large (%f Angstrom)!", aSlice, ifu,
535  wlbotl - wlbotr);
536  }
537  if (fabs(wltopl - wltopr) > DWLEN_WARN_LIMIT_E) { /* strict limit at red end */
538  cpl_msg_warning(__func__, "Wavelength differences at top of slice %hu of IFU "
539  "%hhu are large (%f Angstrom)!", aSlice, ifu, wltopl - wltopr);
540  }
541 
542  /* generate some arbitrary evaluation point, approx. at *
543  * the slice center, and compute the wavelength there. */
544  const double yc = (1. + ny) / 2.,
545  xc = cpl_polynomial_eval_1d(aTrace[MUSE_TRACE_CENTER], yc, NULL);
546  cpl_vector_set(pos, 0, xc);
547  cpl_vector_set(pos, 1, yc);
548  keyword = cpl_sprintf(QC_WAVECAL_SLICEj_WLPOS, aSlice);
549  cpl_propertylist_append_float(aImage->header, keyword, yc);
550  cpl_free(keyword);
551  keyword = cpl_sprintf(QC_WAVECAL_SLICEj_WLEN, aSlice);
552  cpl_propertylist_append_float(aImage->header, keyword,
553  cpl_polynomial_eval(aFit, pos));
554  cpl_free(keyword);
555  cpl_vector_delete(pos);
556 } /* muse_wave_calib_qc_lambda() */
557 
558 /*----------------------------------------------------------------------------*/
571 /*----------------------------------------------------------------------------*/
572 static void
573 muse_wave_calib_output_summary(const cpl_propertylist *aHeader,
574  const cpl_table *aWave)
575 {
576  unsigned char ifu = muse_utils_get_ifu(aHeader);
577  if (!aWave) {
578  cpl_msg_warning(__func__, "Wavelength solution missing for IFU %hhu, no "
579  "summary!", ifu);
580  return;
581  }
582  cpl_vector *found = cpl_vector_new(kMuseSlicesPerCCD),
583  *ident = cpl_vector_new(kMuseSlicesPerCCD),
584  *used = cpl_vector_new(kMuseSlicesPerCCD),
585  *resolution = cpl_vector_new(kMuseSlicesPerCCD);
586  unsigned short islice;
587  for (islice = 0; islice < kMuseSlicesPerCCD; islice++) {
588  char keyword[KEYWORD_LENGTH];
589  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LINES_NDET,
590  (unsigned short)(islice + 1));
591  cpl_vector_set(found, islice, cpl_propertylist_get_int(aHeader, keyword));
592  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_LINES_NID,
593  (unsigned short)(islice + 1));
594  cpl_vector_set(ident, islice, cpl_propertylist_get_int(aHeader, keyword));
595  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_FIT_NLINES,
596  (unsigned short)(islice + 1));
597  cpl_vector_set(used, islice, cpl_propertylist_get_int(aHeader, keyword));
598  snprintf(keyword, KEYWORD_LENGTH, QC_WAVECAL_SLICEj_RESOL,
599  (unsigned short)(islice + 1));
600  cpl_vector_set(resolution, islice, cpl_propertylist_get_float(aHeader, keyword));
601  } /* for islice (all kMuseSlicesPerCCD) */
602  cpl_msg_info(__func__, "Summary of wavelength solution for IFU %hhu:\n"
603  "\tDetections per slice: %d ... %d\n"
604  "\tIdentified lines per slice: %d ... %d\n"
605  "\tLines per slice used in fit: %d ... %d\n"
606  "\tRMS of fit [Angstrom]: %5.3f +/- %5.3f (%5.3f ... %5.3f)\n"
607  "\tMean spectral resolution R: %6.1f +/- %5.1f", ifu,
608  (int)cpl_vector_get_min(found), (int)cpl_vector_get_max(found),
609  (int)cpl_vector_get_min(ident), (int)cpl_vector_get_max(ident),
610  (int)cpl_vector_get_min(used), (int)cpl_vector_get_max(used),
611  sqrt(cpl_table_get_column_mean(aWave, MUSE_WAVECAL_TABLE_COL_MSE)),
612  sqrt(cpl_table_get_column_stdev(aWave, MUSE_WAVECAL_TABLE_COL_MSE)),
613  sqrt(cpl_table_get_column_min(aWave, MUSE_WAVECAL_TABLE_COL_MSE)),
614  sqrt(cpl_table_get_column_max(aWave, MUSE_WAVECAL_TABLE_COL_MSE)),
615  cpl_vector_get_mean(resolution), cpl_vector_get_stdev(resolution));
616  cpl_vector_delete(found);
617  cpl_vector_delete(ident);
618  cpl_vector_delete(used);
619  cpl_vector_delete(resolution);
620 } /* muse_wave_calib_output_summary() */
621 
622 /*----------------------------------------------------------------------------*/
668 /*----------------------------------------------------------------------------*/
669 cpl_table *
670 muse_wave_calib(muse_image *aImage, cpl_table *aTrace, cpl_table *aLinelist,
671  muse_wave_params *aParams)
672 {
673  if (!aImage) {
674  cpl_error_set_message(__func__, CPL_ERROR_NULL_INPUT, "arc image missing!");
675  return NULL;
676  }
677  unsigned char ifu = muse_utils_get_ifu(aImage->header);
678  /* variance always has to be larger than zero */
679  double minstat = cpl_image_get_min(aImage->stat);
680  if (minstat <= 0.) {
681  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_INPUT, "arc image %d does"
682  " not have valid STAT extension in IFU %hhu (minimum "
683  "is %e)!", 0, ifu, minstat);
684  return NULL;
685  }
686 
687  if (!aTrace) {
688  cpl_error_set_message(__func__, CPL_ERROR_NULL_INPUT, "trace table missing "
689  "for IFU %hhu, cannot create wavelength calibration!",
690  ifu);
691  return NULL;
692  } else if (cpl_table_get_nrow(aTrace) != kMuseSlicesPerCCD) {
693  cpl_error_set_message(__func__, CPL_ERROR_INCOMPATIBLE_INPUT, "trace table "
694  "not valid for this dataset of IFU %hhu!", ifu);
695  return NULL;
696  }
697 
698  if (!aLinelist) {
699  cpl_error_set_message(__func__, CPL_ERROR_NULL_INPUT, "no arc line list "
700  "supplied for IFU %hhu!", ifu);
701  return NULL;
702  }
703  if (!aParams) {
704  cpl_error_set_message(__func__, CPL_ERROR_NULL_INPUT, "wavelength "
705  "calibration parameters missing for IFU %hhu!", ifu);
706  return NULL;
707  }
709  cpl_error_set_message(__func__, CPL_ERROR_UNSUPPORTED_MODE,
710  "unknown weighting scheme for IFU %hhu", ifu);
711  return NULL;
712  }
713 
714  /* do not support smaller mock datasets any more */
715  int nx = cpl_image_get_size_x(aImage->data),
716  ny = cpl_image_get_size_y(aImage->data);
717  if (ny < 4000) {
718  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_INPUT, "this dataset of "
719  "IFU %hhu is too small (%dx%d pix) to be supported",
720  ifu, nx, ny);
721  return NULL;
722  }
723 
724  cpl_msg_info(__func__, "Using polynomial orders %hu (x) and %hu (y), %s "
725  "weighting, assuming initial sampling of %.3f +/- %.3f Angstrom"
726  "/pix, in IFU %hhu", aParams->xorder, aParams->yorder,
727  muse_wave_weighting_string[aParams->fitweighting],
728  kMuseSpectralSamplingA, aParams->ddisp, ifu);
729 
730  cpl_vector *vreflam = muse_wave_lines_get(aLinelist, 5, 0.);
731  if (!vreflam) {
732  cpl_error_set_message(__func__, CPL_ERROR_BAD_FILE_FORMAT, "could not "
733  "create list of FWHM reference arc wavelengths for "
734  "IFU %hhu", ifu);
735  return NULL;
736  }
737 
738  int debug = getenv("MUSE_DEBUG_WAVECAL")
739  ? atoi(getenv("MUSE_DEBUG_WAVECAL")) : 0;
740  char fn_debug[100];
741  FILE *fp_debug = NULL;
742  if (debug >= 3) {
743  snprintf(fn_debug, 99, "MUSE_DEBUG_WAVE_LINES-%02hhu.ascii", ifu);
744  cpl_msg_info(__func__, "Will write all single line fits to \"%s\"", fn_debug);
745  fp_debug = fopen(fn_debug, "w");
746  if (fp_debug) {
747  fprintf(fp_debug, "#slice x y lambda lambdaerr\n");
748  }
749  }
750 
751  /* loop over all slices */
752  cpl_propertylist_erase_regexp(aImage->header, "^"QC_WAVECAL_SLICE_PREFIX, 0);
753  cpl_table *wavecaltable = NULL;
754  unsigned short islice;
755  for (islice = 0; islice < kMuseSlicesPerCCD; islice++) {
756  if (debug > 0) {
757  printf("\n\nSlice %d of IFU %hhu\n", (int)islice + 1, ifu);
758  fflush(stdout);
759  }
760  /* get the tracing polynomials for this slice */
761  cpl_polynomial **ptrace = muse_trace_table_get_polys_for_slice(aTrace,
762  islice + 1);
763  if (!ptrace) {
764  cpl_msg_warning(__func__, "slice %2d of IFU %hhu: tracing polynomials "
765  "missing!", (int)islice + 1, ifu);
766  continue;
767  }
768 
769  /* detect all lines in the center of the slice */
770  int imid = lround(cpl_polynomial_eval_1d(ptrace[MUSE_TRACE_CENTER],
771  ny/2., NULL));
772  if (imid < 1 || imid > nx) {
773  cpl_msg_warning(__func__, "slice %2d of IFU %hhu: faulty trace polynomial"
774  " detected", (int)islice + 1, ifu);
775  muse_trace_polys_delete(ptrace);
776  continue; /* next slice */
777  }
778  /* create muse_image from the spectrum in which we want to search lines */
779  const int kWidth = 3;
780  int k, kcol1 = imid - kWidth/2, kcol2 = kcol1 + kWidth;
781  muse_imagelist *collist = muse_imagelist_new();
782  for (k = kcol1; k <= kcol2; k++) {
783  muse_image *column = muse_image_new();
784  column->data = cpl_image_extract(aImage->data, k, 1, k, ny);
785  column->dq = cpl_image_extract(aImage->dq, k, 1, k, ny);
786  column->stat = cpl_image_extract(aImage->stat, k, 1, k, ny);
787  column->header = cpl_propertylist_new();
788  muse_imagelist_set(collist, column, k - kcol1);
789  }
790  muse_image *column = muse_combine_median_create(collist);
791  cpl_propertylist_append_string(column->header, "BUNIT",
792  muse_pfits_get_bunit(aImage->header));
793  muse_imagelist_delete(collist);
794 
795  /* now search, measure, and store the lines */
796  cpl_table *detlines = muse_wave_lines_search(column, aParams->detsigma,
797  islice + 1, ifu);
798  if (!detlines) {
799  cpl_error_set_message(__func__, CPL_ERROR_DATA_NOT_FOUND, "problem when "
800  "searching for arc lines in slice %d of IFU %hhu, "
801  "columns %d..%d", (int)islice + 1, ifu, kcol1, kcol2);
802  muse_image_delete(column);
803  cpl_vector_delete(vreflam);
804  muse_trace_polys_delete(ptrace);
805  cpl_table_delete(wavecaltable);
806  cpl_table_delete(aParams->residuals);
807  aParams->residuals = NULL;
808  return NULL;
809  }
810  /* clean up only here, to not disturb error message above */
811  muse_image_delete(column);
812  if (debug >= 2) {
813  printf("Detected arc lines in slice %d of IFU %hhu:\n", (int)islice + 1, ifu);
814  cpl_table_dump(detlines, 0, cpl_table_get_nrow(detlines), stdout);
815  fflush(stdout);
816  }
817 
818  /* identify the lines that we detected, and see if there are enough *
819  * for the polynomial order in y-direction to fit a polynomial */
820  int nfound = cpl_table_get_nrow(detlines);
821  /* get all arc lines, taking into account the detection limit */
822  double minflux = cpl_table_get_column_min(detlines, "flux") * 1.15;
823  cpl_vector *vlambda = muse_wave_lines_get(aLinelist, 1, minflux);
824  muse_wave_lines_identify(detlines, vlambda, aParams);
825  cpl_vector_delete(vlambda);
826  int nlines = cpl_table_get_nrow(detlines);
827  cpl_msg_debug(__func__, "Identified %d of %d arc lines in slice %d of IFU "
828  "%hhu (column %d, %d..%d)", nlines, nfound, (int)islice + 1, ifu,
829  imid, kcol1, kcol2);
830  if (debug >= 2) {
831  printf("Identified arc lines with wavelengths in slice %d of IFU %hhu:\n",
832  (int)islice + 1, ifu);
833  cpl_table_dump(detlines, 0, cpl_table_get_nrow(detlines), stdout);
834  fflush(stdout);
835  }
836 
837  /* the first QC parameter does even make sense without lines */
838  char *keyword = cpl_sprintf(QC_WAVECAL_SLICEj_LINES_NDET,
839  (unsigned short)(islice + 1));
840  cpl_propertylist_append_int(aImage->header, keyword, nfound);
841  cpl_free(keyword);
842 
843  if (nlines < aParams->yorder + 1) {
844  /* could apparently not identify enough lines, or an error occured */
845  cpl_msg_error(__func__, "Could not identify enough arc lines in slice %d"
846  " of IFU %hhu (%d of %d, required %d)", (int)islice + 1, ifu,
847  nlines, nfound, (int)aParams->yorder + 1);
848  muse_trace_polys_delete(ptrace);
849  cpl_table_delete(detlines);
850  continue; /* work on next slice immediately */
851  }
852 
853  /* the next set of QC parameters */
854  muse_wave_calib_qc_peaks(detlines, aImage->header, islice + 1);
855  muse_wave_calib_qc_fwhm_old(detlines, aImage->header, vreflam, islice + 1);
856  /* above we wrote the number of detected lines, now is the number of *
857  * arc lines really used in the fit, i.e. the identified ones */
858  keyword = cpl_sprintf(QC_WAVECAL_SLICEj_LINES_NID, (unsigned short)(islice + 1));
859  cpl_propertylist_append_int(aImage->header, keyword, nlines);
860  cpl_free(keyword);
861 
862  /* positions matrix and wavelengths vector to be used for the 2D polynomial *
863  * fit; just set and initial size of 1, it has to be resized with every line */
864  cpl_matrix *xypos = cpl_matrix_new(2, 1);
865  cpl_vector *lambdas = cpl_vector_new(1),
866  *dlambdas = NULL;
867  if (aParams->fitweighting != MUSE_WAVE_WEIGHTING_UNIFORM) {
868  dlambdas = cpl_vector_new(1);
869  }
870  int ientry = 0; /* index for these two structures */
871 
872  /* for all identified arc lines, work on the original input data */
873  int j;
874  for (j = 0; j < nlines; j++) {
875  /* convenient access to some properties of this identified line */
876  double lambda = cpl_table_get(detlines, "lambda", j, NULL);
877  double ypos = cpl_table_get(detlines, "center", j, NULL);
878  /* better fix the Gaussian sigmas, otherwise *
879  * the fit might run astray in low S/N cases */
880  double sigma = cpl_table_get(detlines, "sigma", j, NULL);
881  int n = 0,
882  halfwidth = 2.*cpl_table_get(detlines, "fwhm", j, NULL); /* 2*FWHM */
883  /* get both slice edges and the center */
884  double dleft = cpl_polynomial_eval_1d(ptrace[MUSE_TRACE_LEFT],
885  ypos, NULL),
886  dright = cpl_polynomial_eval_1d(ptrace[MUSE_TRACE_RIGHT],
887  ypos, NULL),
888  dmid = (dleft + dright) / 2.;
889  int ileft = ceil(dleft),
890  iright = floor(dright);
891 #if 0
892  cpl_msg_debug(__func__, "limits at y=%f: %f < %f < %f", ypos, dleft, dmid,
893  dright);
894 #endif
895 
896  /* table to store line fits for this one arc line */
897  cpl_table *fittable = muse_cpltable_new(muse_wavelines_def,
898  (int)kMuseSliceHiLikelyWidth + 5);
899 
900  /* From the center of the slice move outwards and fit the line *
901  * until we have arrived at the edge of the slice */
902  int i;
903  for (i = dmid; i >= ileft; i--) {
904  cpl_error_code rc = muse_wave_line_fit_single(aImage, i, ypos, halfwidth,
905  sigma, fittable, ++n);
906  if (rc != CPL_ERROR_NONE) { /* do not count this line */
907  --n;
908  }
909  }
910 #if 0
911  printf("arc line j=%d, columns i=%d...", j + 1, i);
912 #endif
913  for (i = dmid + 1; i <= iright; i++) {
914  cpl_error_code rc = muse_wave_line_fit_single(aImage, i, ypos, halfwidth,
915  sigma, fittable, ++n);
916  if (rc != CPL_ERROR_NONE) { /* do not count this line */
917  --n;
918  }
919  }
920  /* now remove rows with invalid entries, i.e. those that were not *
921  * filled with the properties of the fit -- cpl_table_erase_invalid() *
922  * does not work, it deletes all columns */
923  cpl_table_select_all(fittable);
924  cpl_table_and_selected_invalid(fittable, "center");
925  cpl_table_erase_selected(fittable);
926 #if 0
927  printf("line %d, %d line fits\n", j + 1, i);
928  cpl_table_dump(fittable, 0, n, stdout);
929  fflush(stdout);
930 #endif
931  cpl_errorstate state = cpl_errorstate_get();
932  muse_wave_line_fit_iterate(fittable, -1, aParams);
933  int npos = cpl_table_get_nrow(fittable);
934  if (npos <= aParams->xorder) {
935  cpl_msg_debug(__func__, "Polynomial fit failed in slice %d of IFU %hhu"
936  " for line at %.3fA (y-position near %.2f pix): %s",
937  (int)islice + 1, ifu, lambda, ypos, cpl_error_get_message());
938  cpl_errorstate_set(state);
939  }
940 #if 0
941  else {
942  printf("%s: line %2d, %d line fits, %d with low residuals:\n", __func__,
943  j + 1, i, npos);
944  cpl_table_dump(fittable, 0, npos, stdout);
945  fflush(stdout);
946  }
947 #endif
948 
949  /* resize matrix/vector to be able to fit all new entries */
950  cpl_matrix_resize(xypos, 0, 0,
951  0, ientry + npos - cpl_matrix_get_ncol(xypos));
952  cpl_vector_set_size(lambdas, ientry + npos);
953  if (aParams->fitweighting != MUSE_WAVE_WEIGHTING_UNIFORM) {
954  cpl_vector_set_size(dlambdas, ientry + npos);
955  }
956 
957  /* now add the final fit positions */
958  int ipos;
959  for (ipos = 0; ipos < npos; ipos++) {
960  /* set x-position (CCD column) in the first matrix row */
961  cpl_matrix_set(xypos, 0, ientry, cpl_table_get(fittable, "x", ipos, NULL));
962  /* y-position on CCD (center of Gauss fit) into second matrix row */
963  cpl_matrix_set(xypos, 1, ientry, cpl_table_get(fittable, "center", ipos, NULL));
964  /* the vector has to contain as many lambda entries */
965  cpl_vector_set(lambdas, ientry, lambda);
966  /* pretend that errors in Gaussian fit are errors in wavelength, *
967  * scale according to the nominal Angstrom/pix sampling of MUSE, *
968  * everything else would be too complicated for little gain */
969  if (aParams->fitweighting != MUSE_WAVE_WEIGHTING_UNIFORM) {
970  cpl_vector_set(dlambdas, ientry, cpl_table_get(fittable, "cerr", ipos, NULL)
971  * kMuseSpectralSamplingA);
972  }
973 
974  ientry++; /* next position in this matrix/vector combo */
975  if (fp_debug) {
976  fprintf(fp_debug, " %02d %04d %9.4f %10.4f %e\n", (int)islice + 1,
977  (int)cpl_table_get(fittable, "x", ipos, NULL),
978  cpl_table_get(fittable, "center", ipos, NULL), lambda,
979  cpl_table_get(fittable, "cerr", ipos, NULL) * kMuseSpectralSamplingA);
980  }
981  }
982  cpl_table_delete(fittable);
983  } /* for j (all identified arc lines) */
984  cpl_table_delete(detlines);
985 
986  /* Compute two-dimensional wavelength solution for each slice. */
987  cpl_polynomial *poly = NULL; /* polynomial for wavelength solution */
988  double mse = 0; /* mean squared error */
989  cpl_error_code rc = muse_wave_poly_fit(xypos, lambdas, dlambdas,
990  &poly, &mse, aParams, islice + 1);
991  cpl_matrix_delete(xypos);
992  int nfinal = muse_cplvector_count_unique(lambdas);
993  cpl_vector_delete(lambdas);
994  cpl_vector_delete(dlambdas);
995  /* above we wrote detected and identified lines, here *
996  * save the ones that actually survived the fit */
997  keyword = cpl_sprintf(QC_WAVECAL_SLICEj_FIT_NLINES, (unsigned short)(islice + 1));
998  cpl_propertylist_append_int(aImage->header, keyword, nfinal);
999  cpl_free(keyword);
1000  /* collect QC on wavelengths */
1001  muse_wave_calib_qc_lambda(aImage, islice + 1, ptrace, poly);
1002  /* trace polynomials are not needed further */
1003  muse_trace_polys_delete(ptrace);
1004 
1005  if (rc != CPL_ERROR_NONE) { /* failure */
1006  cpl_msg_warning(__func__, "Something went wrong while fitting in slice "
1007  "%d of IFU %hhu: %s", (int)islice + 1, ifu,
1008  cpl_error_get_message_default(rc));
1009  cpl_polynomial_delete(poly);
1010  continue; /* try next slice immediately */
1011  }
1012 
1013  if (!wavecaltable) {
1014  /* create output table with one row for each slice; no need to *
1015  * check return code, it can only fail for negative lengths */
1016  wavecaltable = muse_wave_table_create(kMuseSlicesPerCCD,
1017  aParams->xorder, aParams->yorder);
1018  }
1019  rc = muse_wave_table_add_poly(wavecaltable, poly, mse,
1020  aParams->xorder, aParams->yorder, islice);
1021 
1022  /* use the number of wavelengths as indicator of the lines used for the *
1023  * fit and record it as QC parameter */
1024  keyword = cpl_sprintf(QC_WAVECAL_SLICEj_FIT_RMS, (unsigned short)(islice + 1));
1025  cpl_propertylist_append_float(aImage->header, keyword, sqrt(mse));
1026  cpl_free(keyword);
1027 
1028  if (rc != CPL_ERROR_NONE) {
1029  cpl_msg_warning(__func__, "Could not write polynomial to wavecal table "
1030  "for slice %d of IFU %hhu: %s", (int)islice + 1, ifu,
1031  cpl_error_get_message_default(rc));
1032  }
1033  /* clean up, ignore any failure with this */
1034  cpl_polynomial_delete(poly);
1035  } /* for islice (all kMuseSlicesPerCCD) */
1036  cpl_vector_delete(vreflam);
1037  if (fp_debug) {
1038  cpl_msg_info(__func__, "Done writing line fits to \"%s\"", fn_debug);
1039  fclose(fp_debug);
1040  }
1041 
1042  muse_wave_calib_output_summary(aImage->header, wavecaltable);
1043 #if 0
1044  if (cpl_msg_get_level() == CPL_MSG_DEBUG) {
1045  cpl_table_dump(wavecaltable, 0, 3, stdout); fflush(stdout);
1046  }
1047 #endif
1048 
1049  return wavecaltable;
1050 } /* muse_wave_calib() */
1051 
1052 /*----------------------------------------------------------------------------*/
1114 /*----------------------------------------------------------------------------*/
1115 cpl_table *
1116 muse_wave_calib_lampwise(muse_imagelist *aImages, cpl_table *aTrace,
1117  cpl_table *aLinelist, muse_wave_params *aParams)
1118 {
1119  if (!aImages || muse_imagelist_get_size(aImages) < 1) {
1120  cpl_error_set_message(__func__, CPL_ERROR_NULL_INPUT, "arc imagelist is "
1121  "missing or empty!");
1122  return NULL;
1123  }
1124  unsigned char ifu = muse_utils_get_ifu(muse_imagelist_get(aImages, 0)->header);
1125  if (!aTrace) {
1126  cpl_error_set_message(__func__, CPL_ERROR_NULL_INPUT, "trace table missing "
1127  "for IFU %hhu, cannot create wavelength calibration!",
1128  ifu);
1129  return NULL;
1130  } else if (cpl_table_get_nrow(aTrace) != kMuseSlicesPerCCD) {
1131  cpl_error_set_message(__func__, CPL_ERROR_INCOMPATIBLE_INPUT, "trace table "
1132  "not valid for this dataset of IFU %hhu!", ifu);
1133  return NULL;
1134  }
1135  if (!aLinelist) {
1136  cpl_error_set_message(__func__, CPL_ERROR_NULL_INPUT, "no arc line list "
1137  "supplied for IFU %hhu!", ifu);
1138  return NULL;
1139  }
1140  if (!aParams) {
1141  cpl_error_set_message(__func__, CPL_ERROR_NULL_INPUT, "wavelength "
1142  "calibration parameters missing for IFU %hhu!", ifu);
1143  return NULL;
1144  }
1146  cpl_error_set_message(__func__, CPL_ERROR_UNSUPPORTED_MODE,
1147  "unknown weighting scheme for IFU %hhu", ifu);
1148  return NULL;
1149  }
1150 
1151  muse_image *firstimage = muse_imagelist_get(aImages, 0);
1152  int nx = cpl_image_get_size_x(firstimage->data),
1153  ny = cpl_image_get_size_y(firstimage->data);
1154  /* do not support binned exposures */
1155  if (ny < 4000) {
1156  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_INPUT, "this dataset of "
1157  "IFU %hhu is too small (%dx%d pix) to be supported",
1158  ifu, nx, ny);
1159  return NULL;
1160  }
1161 
1162  cpl_msg_info(__func__, "Using polynomial orders %hu (x) and %hu (y), %s "
1163  "weighting, assuming initial sampling of %.3f +/- %.3f Angstrom"
1164  "/pix, in IFU %hhu", aParams->xorder, aParams->yorder,
1165  muse_wave_weighting_string[aParams->fitweighting],
1166  kMuseSpectralSamplingA, aParams->ddisp, ifu);
1167 
1168  cpl_propertylist_erase_regexp(firstimage->header, "^"QC_WAVECAL_SLICE_PREFIX, 0);
1169  char *lamp = muse_utils_header_get_lamp_names(firstimage->header, ',');
1170  cpl_msg_debug(__func__, "Image 1 was taken with lamp %s", lamp);
1171  cpl_free(lamp);
1172  unsigned int k;
1173  for (k = 1; k < muse_imagelist_get_size(aImages); k++) {
1174  int nxk = cpl_image_get_size_x(muse_imagelist_get(aImages, k)->data),
1175  nyk = cpl_image_get_size_y(muse_imagelist_get(aImages, k)->data);
1176  if (nxk != nx || nyk != ny) {
1177  cpl_error_set_message(__func__, CPL_ERROR_INCOMPATIBLE_INPUT, "arc "
1178  "imagelist is not uniform (image %u is %dx%d, "
1179  "first image is %dx%d)", k + 1, nxk, nyk, nx, ny);
1180  return NULL;
1181  }
1182  cpl_propertylist_erase_regexp(muse_imagelist_get(aImages, k)->header,
1183  "^"QC_WAVECAL_SLICE_PREFIX, 0);
1184  lamp = muse_utils_header_get_lamp_names(muse_imagelist_get(aImages, k)->header, ',');
1185  cpl_msg_debug(__func__, "Image %d was taken with lamp %s", k + 1, lamp);
1186  cpl_free(lamp);
1187  } /* for k (all images in list except first) */
1188 
1189  cpl_vector *vreflam = muse_wave_lines_get(aLinelist, 5, 0.);
1190  if (!vreflam) {
1191  cpl_error_set_message(__func__, CPL_ERROR_BAD_FILE_FORMAT, "could not "
1192  "create list of FWHM reference arc wavelengths for "
1193  "IFU %hhu", ifu);
1194  return NULL;
1195  }
1196  cpl_table *wavecal = NULL;
1197  int debug = getenv("MUSE_DEBUG_WAVECAL")
1198  ? atoi(getenv("MUSE_DEBUG_WAVECAL")) : 0;
1199  char fn_debug[100];
1200  FILE *fp_debug = NULL;
1201  if (debug >= 3) {
1202  snprintf(fn_debug, 99, "MUSE_DEBUG_WAVE_LINES-%02hhu.ascii", ifu);
1203  cpl_msg_info(__func__, "Will write all single line fits to \"%s\"", fn_debug);
1204  fp_debug = fopen(fn_debug, "w");
1205  if (fp_debug) {
1206  fprintf(fp_debug, "#slice x y lambda lambdaerr\n");
1207  }
1208  }
1209 
1210  /* loop over all slices */
1211  unsigned short islice;
1212  for (islice = 0; islice < kMuseSlicesPerCCD; islice++) {
1213  if (debug > 0) {
1214  printf("\n\nSlice %d of IFU %hhu\n", (int)islice + 1, ifu);
1215  fflush(stdout);
1216  }
1217  /* get the tracing polynomials for this slice */
1218  cpl_polynomial **ptrace = muse_trace_table_get_polys_for_slice(aTrace,
1219  islice + 1);
1220  if (!ptrace) {
1221  cpl_msg_warning(__func__, "slice %2d of IFU %hhu: tracing polynomials "
1222  "missing!", (int)islice + 1, ifu);
1223  continue;
1224  }
1225  /* detect all lines in the center of the slice */
1226  const int imid = lround(cpl_polynomial_eval_1d(ptrace[MUSE_TRACE_CENTER],
1227  ny/2., NULL)),
1228  iWidth = 3,
1229  icol1 = imid - iWidth/2,
1230  icol2 = icol1 + iWidth;
1231  if (imid < 1 || imid > nx) {
1232  cpl_msg_warning(__func__, "slice %2d of IFU %hhu: faulty trace polynomial"
1233  "detected", (int)islice + 1, ifu);
1234  muse_trace_polys_delete(ptrace);
1235  continue; /* next slice */
1236  }
1237  cpl_table *detlines = NULL;
1238  int ndet = 0;
1239  for (k = 0; k < muse_imagelist_get_size(aImages); k++) {
1240  muse_image *arc = muse_imagelist_get(aImages, k);
1241  /* create muse_image from the spectrum in which we want to search lines */
1242  muse_imagelist *collist = muse_imagelist_new();
1243  int i;
1244  for (i = icol1; i <= icol2; i++) {
1245  muse_image *column = muse_image_new();
1246  column->data = cpl_image_extract(arc->data, i, 1, i, ny);
1247  column->dq = cpl_image_extract(arc->dq, i, 1, i, ny);
1248  column->stat = cpl_image_extract(arc->stat, i, 1, i, ny);
1249  muse_imagelist_set(collist, column, i - icol1);
1250  } /* for i (neighboring image columns) */
1251  muse_image *column = muse_combine_median_create(collist);
1252  cpl_propertylist_append_string(column->header, "BUNIT",
1254  muse_imagelist_delete(collist);
1255 
1256  /* now search, measure, and store the lines */
1257  cpl_table *detections = muse_wave_lines_search(column, aParams->detsigma,
1258  islice + 1, ifu);
1259  muse_image_delete(column);
1260  int nlampdet = cpl_table_get_nrow(detections); /* det. with this lamp */
1261  ndet += nlampdet; /* detections of all lamps */
1262  char *lampname = muse_utils_header_get_lamp_names(arc->header, ',');
1263  cpl_table_fill_column_window_string(detections, "lampname", 0, nlampdet,
1264  lampname);
1265  cpl_array *lampnumbers = muse_utils_header_get_lamp_numbers(arc->header);
1266  cpl_table_fill_column_window_int(detections, "lampno", 0, nlampdet,
1267  cpl_array_get_int(lampnumbers, 0, NULL));
1268  cpl_array_delete(lampnumbers);
1269  /* get arc lines for this lamp from original list */
1270  double minflux = cpl_table_get_column_min(detections, "flux") * 1.15;
1271  cpl_vector *ionlambdas = muse_wave_lines_get_for_lamp(aLinelist, lampname,
1272  1, minflux);
1273  cpl_free(lampname);
1274  muse_wave_lines_identify(detections, ionlambdas, aParams);
1275  cpl_vector_delete(ionlambdas);
1276 
1277  if (!detlines) {
1278  detlines = detections;
1279  } else {
1280  cpl_table_insert(detlines, detections, cpl_table_get_nrow(detlines));
1281  cpl_table_delete(detections);
1282  }
1283  } /* for k (all images in list) */
1284  cpl_propertylist *order = cpl_propertylist_new();
1285  cpl_propertylist_append_bool(order, "y", CPL_FALSE);
1286  cpl_table_sort(detlines, order);
1287  cpl_propertylist_delete(order);
1288  int nlines = cpl_table_get_nrow(detlines);
1289  if (debug >= 2) {
1290  printf("Detected and identified %d arc lines in slice %d of IFU %hhu:\n",
1291  nlines, (int)islice + 1, ifu);
1292  cpl_table_dump(detlines, 0, cpl_table_get_nrow(detlines), stdout);
1293  fflush(stdout);
1294  }
1295  /* the first QC parameter does even make sense without lines */
1296  char *keyword = cpl_sprintf(QC_WAVECAL_SLICEj_LINES_NDET, (unsigned short)(islice + 1));
1297  cpl_propertylist_append_int(firstimage->header, keyword, ndet);
1298  cpl_free(keyword);
1299 
1300  if (nlines < aParams->yorder + 1) {
1301  /* could apparently not identify enough lines, or an error occured */
1302  cpl_error_set_message(__func__, CPL_ERROR_DATA_NOT_FOUND, "could not "
1303  "detect and/or identify enough arc lines in slice "
1304  "%d of IFU %hhu (%d of %d, required %d)",
1305  (int)islice + 1, ifu, nlines, ndet, (int)aParams->yorder + 1);
1306  muse_trace_polys_delete(ptrace);
1307  cpl_table_delete(detlines);
1308  continue; /* work on next slice immediately */
1309  }
1310  cpl_msg_info(__func__, "Identified %d of %d detected arc lines in slice %d"
1311  " of IFU %hhu (column %d, %d..%d)", nlines, ndet, (int)islice + 1,
1312  ifu, imid, icol1, icol2);
1313 
1314  /* the next set of QC parameters */
1315  muse_wave_calib_qc_peaks(detlines, firstimage->header, islice + 1);
1316  /* above we wrote the number of detected lines, now is the number of *
1317  * arc lines really used in the fit, i.e. the identified ones */
1318  keyword = cpl_sprintf(QC_WAVECAL_SLICEj_LINES_NID, (unsigned short)(islice + 1));
1319  cpl_propertylist_append_int(firstimage->header, keyword, nlines);
1320  cpl_free(keyword);
1321 
1322  /* convert y and lambda into matrix and vector for an initial, *
1323  * vertical, inverse 1D fit */
1324  cpl_vector *cen = cpl_vector_new(nlines);
1325  cpl_matrix *lbda = cpl_matrix_new(1, nlines);
1326  int idx;
1327  for (idx = 0; idx < nlines; idx++) {
1328  cpl_vector_set(cen, idx, cpl_table_get(detlines, "center", idx, NULL));
1329  cpl_matrix_set(lbda, 0, idx, cpl_table_get(detlines, "lambda", idx, NULL));
1330  }
1331 #if 0
1332  char *fn = cpl_sprintf("slice%02d_lbda1.dat", (int)islice + 1);
1333  FILE *file = fopen(fn, "w");
1334  cpl_matrix_dump(lbda, file);
1335  fclose(file);
1336  cpl_free(fn);
1337 #endif
1338  double mse1d, chisq1d;
1339  cpl_polynomial *fit
1340  = muse_utils_iterate_fit_polynomial(lbda, cen, NULL, detlines,
1341  aParams->yorder, 3.,
1342  &mse1d, &chisq1d);
1343 #if 0
1344  cpl_vector *res = cpl_vector_new(cpl_vector_get_size(cen));
1345  cpl_vector_fill_polynomial_fit_residual(res, cen, NULL, fit, lbda, NULL);
1346  cpl_bivector *biv = cpl_bivector_wrap_vectors(cen, res);
1347  cpl_plot_bivector(NULL, NULL, NULL, biv);
1348  cpl_bivector_unwrap_vectors(biv);
1349  cpl_vector_delete(res);
1350 #endif
1351  if (debug >= 1) {
1352  printf("Initial (inverse) polynomial fit in slice %2d of IFU %hhu "
1353  "(RMS = %f, chisq = %e, %d of %d input points left)\n", (int)islice + 1,
1354  ifu, sqrt(mse1d), chisq1d, (int)cpl_vector_get_size(cen), nlines);
1355  cpl_polynomial_dump(fit, stdout);
1356  fflush(stdout);
1357  }
1358  nlines = cpl_vector_get_size(cen);
1359 #if 0
1360  fn = cpl_sprintf("slice%02hu_lbda2.dat", islice + 1);
1361  file = fopen(fn, "w");
1362  cpl_matrix_dump(lbda, file);
1363  fclose(file);
1364  cpl_free(fn);
1365 #endif
1366  cpl_vector_delete(cen);
1367  cpl_matrix_delete(lbda);
1368 
1369  /* positions matrix and wavelengths vector to be used for the 2D polynomial *
1370  * fit; just set and initial size of 1, it has to be resized with every line */
1371  cpl_matrix *xypos = cpl_matrix_new(2, 1);
1372  cpl_vector *lambdas = cpl_vector_new(1),
1373  *dlambdas = NULL;
1374  if (aParams->fitweighting != MUSE_WAVE_WEIGHTING_UNIFORM) {
1375  dlambdas = cpl_vector_new(1);
1376  }
1377  int ientry = 0; /* index for these two structures */
1378 
1379  /* now measure all bright, single lines taken from the input linelist */
1380  cpl_table *fwhmtable = muse_cpltable_new(muse_wavelines_def, 0);
1381  cpl_table_set_column_unit(fwhmtable, "fwhm", "Angstrom");
1382  int j, narclines = cpl_table_get_nrow(aLinelist);
1383  for (j = 0; j < narclines; j++) {
1384  int quality = cpl_table_get_int(aLinelist, MUSE_LINE_CATALOG_QUALITY, j, NULL);
1385  if (quality <= 1) {
1386  continue; /* skip unwanted line */
1387  }
1388 
1389  /* use the lamp name to find the corresponding exposure for arc line */
1390  const char *lampname = muse_wave_lines_get_lampname(aLinelist, j);
1391  muse_image *arc = NULL;
1392  for (k = 0; k < muse_imagelist_get_size(aImages); k++) {
1393  arc = muse_imagelist_get(aImages, k);
1394  char *thislamp = muse_utils_header_get_lamp_names(arc->header, ',');
1395  cpl_boolean match = CPL_FALSE;
1396  if (lampname && thislamp) {
1397  match = strncmp(lampname, thislamp, strlen(lampname)) == 0;
1398  }
1399  cpl_free(thislamp);
1400  if (match) {
1401  break;
1402  }
1403  } /* for k (all images in list) */
1404 
1405  cpl_table *fittable = NULL;
1406  if (quality == 2) { /* multiplet */
1407  fittable = muse_wave_line_handle_multiplet(arc, aLinelist, j, fit, ptrace,
1408  aParams, islice + 1, debug);
1409  } else {
1410  fittable = muse_wave_line_handle_singlet(arc, aLinelist, j, fit, ptrace,
1411  aParams, islice + 1, debug);
1412  }
1413  if (!fittable) {
1414  continue;
1415  }
1416  int nnew = cpl_table_get_nrow(fittable);
1417 
1418  /* resize matrix/vector to be able to fit all new entries */
1419  cpl_matrix_resize(xypos, 0, 0,
1420  0, ientry + nnew - cpl_matrix_get_ncol(xypos));
1421  cpl_vector_set_size(lambdas, ientry + nnew);
1422  if (aParams->fitweighting != MUSE_WAVE_WEIGHTING_UNIFORM) {
1423  cpl_vector_set_size(dlambdas, ientry + nnew);
1424  }
1425 
1426  /* now add the final fit positions */
1427  cpl_table_set_column_unit(fittable, "fwhm", ""); /* ongoing unit conversion */
1428  int ipos;
1429  for (ipos = 0; ipos < nnew; ipos++) {
1430  /* set x-position (CCD column) in the first matrix row */
1431  cpl_matrix_set(xypos, 0, ientry, cpl_table_get(fittable, "x", ipos, NULL));
1432  /* y-position on CCD (center of Gauss fit) into second matrix row */
1433  cpl_matrix_set(xypos, 1, ientry, cpl_table_get(fittable, "center", ipos, NULL));
1434  /* the vector has to contain as many lambda entries */
1435  double lambda = cpl_table_get(fittable, "lambda", ipos, NULL);
1436  cpl_vector_set(lambdas, ientry, lambda);
1437  /* Pretend that errors in Gaussian fit are errors in wavelength, *
1438  * use the first-guess 1D solution to convert from pix to Angstrom. */
1439  double dlbda;
1440  cpl_polynomial_eval_1d(fit, lambda, &dlbda); /* not interested in result */
1441  double cerr = 0.;
1442  if (aParams->fitweighting != MUSE_WAVE_WEIGHTING_UNIFORM) {
1443  cerr = cpl_table_get(fittable, "cerr", ipos, NULL) / dlbda;
1444  cpl_vector_set(dlambdas, ientry, cerr);
1445  }
1446  /* now that we have the actual sampling, also convert FWHM to Angstrom */
1447  int err;
1448  double fwhm = cpl_table_get(fittable, "fwhm", ipos, &err) / dlbda;
1449  if (!err) {
1450  cpl_table_set(fittable, "fwhm", ipos, fwhm);
1451  }
1452  ientry++; /* next position in this matrix/vector combo */
1453  if (fp_debug) {
1454  fprintf(fp_debug, " %02d %04d %9.4f %10.4f %e\n", (int)islice + 1,
1455  (int)cpl_table_get(fittable, "x", ipos, NULL),
1456  cpl_table_get(fittable, "center", ipos, NULL), lambda, cerr);
1457  }
1458  } /* for ipos (all fittable rows) */
1459  cpl_table_set_column_unit(fittable, "fwhm", "Angstrom");
1460  /* append relevant lines to extra table to compute FWHM and R later */
1461  cpl_table_select_all(fittable);
1462  cpl_table_and_selected_invalid(fittable, "fwhm");
1463  cpl_table_erase_selected(fittable);
1464  cpl_table_insert(fwhmtable, fittable, cpl_table_get_nrow(fwhmtable));
1465  cpl_table_delete(fittable);
1466  } /* for j (all arc lines) */
1467  /* reset original line quality info */
1468  cpl_table_abs_column(aLinelist, MUSE_LINE_CATALOG_QUALITY);
1469  cpl_table_delete(detlines);
1470  cpl_polynomial_delete(fit);
1471  muse_wave_calib_qc_fwhm(fwhmtable, firstimage->header, islice + 1);
1472  cpl_table_delete(fwhmtable);
1473 
1474  /* Compute two-dimensional wavelength solution for each slice. */
1475  cpl_polynomial *poly = NULL; /* polynomial for wavelength solution */
1476  double mse2d;
1477  cpl_error_code rc = muse_wave_poly_fit(xypos, lambdas, dlambdas,
1478  &poly, &mse2d, aParams, islice + 1);
1479  cpl_msg_info(__func__, "Polynomial fit of %"CPL_SIZE_FORMAT" of %d positions"
1480  " in slice %d of IFU %hhu gave an RMS of %f Angstrom",
1481  cpl_vector_get_size(lambdas), ientry, (int)islice + 1, ifu,
1482  sqrt(mse2d));
1483  cpl_matrix_delete(xypos);
1484  int nfinal = muse_cplvector_count_unique(lambdas);
1485  cpl_vector_delete(lambdas);
1486  cpl_vector_delete(dlambdas);
1487  /* above we wrote detected and identified lines, here *
1488  * save the ones that actually survived the fit */
1489  keyword = cpl_sprintf(QC_WAVECAL_SLICEj_FIT_NLINES, (unsigned short)(islice + 1));
1490  cpl_propertylist_append_int(firstimage->header, keyword, nfinal);
1491  cpl_free(keyword);
1492  /* collect QC on wavelengths */
1493  muse_wave_calib_qc_lambda(firstimage, islice + 1, ptrace, poly);
1494  /* trace polynomials are not needed further */
1495  muse_trace_polys_delete(ptrace);
1496 
1497  if (rc != CPL_ERROR_NONE) { /* failure of the polynomial fit */
1498  cpl_error_set_message(__func__, rc, "a failure while computing the two-di"
1499  "mensional polynomial fit in slice %d of IFU %hhu",
1500  (int)islice + 1, ifu);
1501  cpl_polynomial_delete(poly);
1502  continue; /* try next slice immediately */
1503  }
1504 
1505  if (!wavecal) {
1506  /* create output table with one row for each slice; no need to *
1507  * check return code, it can only fail for negative lengths */
1508  wavecal = muse_wave_table_create(kMuseSlicesPerCCD,
1509  aParams->xorder, aParams->yorder);
1510  }
1511  rc = muse_wave_table_add_poly(wavecal, poly, mse2d,
1512  aParams->xorder, aParams->yorder, islice);
1513 
1514  /* use the number of wavelengths as indicator of the lines used for the *
1515  * fit and record it as QC parameter */
1516  keyword = cpl_sprintf(QC_WAVECAL_SLICEj_FIT_RMS, (unsigned short)(islice + 1));
1517  cpl_propertylist_append_float(firstimage->header, keyword, sqrt(mse2d));
1518  cpl_free(keyword);
1519 
1520  if (rc != CPL_ERROR_NONE) {
1521  cpl_msg_warning(__func__, "Could not write polynomial to wavecal table "
1522  "for slice %d of IFU %hhu: %s", (int)islice + 1, ifu,
1523  cpl_error_get_message_default(rc));
1524  }
1525  /* clean up, ignore any failure with this */
1526  cpl_polynomial_delete(poly);
1527  } /* for islice (all kMuseSlicesPerCCD) */
1528  cpl_vector_delete(vreflam);
1529  if (fp_debug) {
1530  cpl_msg_info(__func__, "Done writing line fits to \"%s\"", fn_debug);
1531  fclose(fp_debug);
1532  }
1533 
1534  muse_wave_calib_output_summary(firstimage->header, wavecal);
1535  /* copy the QC parameters to the other image headers */
1536  for (k = 1; k < muse_imagelist_get_size(aImages); k++) {
1537  cpl_propertylist *header = muse_imagelist_get(aImages, k)->header;
1538  cpl_propertylist_erase_regexp(header, "^"QC_WAVECAL_SLICE_PREFIX, 0);
1539  cpl_propertylist_copy_property_regexp(header, firstimage->header, "^ESO QC", 0);
1540  } /* for k (all images in list except first) */
1541 
1542  return wavecal;
1543 } /* muse_wave_calib_lampwise() */
1544 
1545 /*----------------------------------------------------------------------------*/
1562 /*----------------------------------------------------------------------------*/
1563 cpl_boolean
1565 {
1566  cpl_ensure(aTable && aTable->table && aTable->header, CPL_ERROR_NULL_INPUT,
1567  CPL_FALSE);
1568  /* check the table */
1569  int nrow = cpl_table_get_nrow(aTable->table);
1570  cpl_ensure(nrow > 0, CPL_ERROR_NULL_INPUT, CPL_FALSE);
1571  cpl_ensure(muse_cpltable_check(aTable->table, muse_line_catalog_def)
1572  == CPL_ERROR_NONE, CPL_ERROR_DATA_NOT_FOUND, CPL_FALSE);
1573 
1574  /* check the version */
1575  if (!cpl_propertylist_has(aTable->header, MUSE_HDR_LINE_CATALOG_VERSION)) {
1576  cpl_error_set_message(__func__, CPL_ERROR_INCOMPATIBLE_INPUT, "%s does not "
1577  "contain a VERSION header entry!",
1578  MUSE_TAG_LINE_CATALOG);
1579  return CPL_FALSE;
1580  }
1581  int version = cpl_propertylist_get_int(aTable->header,
1582  MUSE_HDR_LINE_CATALOG_VERSION);
1583 #define LINE_CATALOG_EXPECTED_VERSION 3
1584  if (version != LINE_CATALOG_EXPECTED_VERSION) {
1585  cpl_error_set_message(__func__, CPL_ERROR_BAD_FILE_FORMAT, "VERSION = %d "
1586  "is wrong, we need a %s with VERSION = %d", version,
1587  MUSE_TAG_LINE_CATALOG, LINE_CATALOG_EXPECTED_VERSION);
1588  return CPL_FALSE;
1589  }
1590  return CPL_TRUE;
1591 } /* muse_wave_lines_check() */
1592 
1593 /*----------------------------------------------------------------------------*/
1615 /*----------------------------------------------------------------------------*/
1616 cpl_vector *
1617 muse_wave_lines_get(cpl_table *aTable, int aGoodnessLimit, double aFluxLimit)
1618 {
1619  cpl_ensure(aTable, CPL_ERROR_NULL_INPUT, NULL);
1620  int nrow = cpl_table_get_nrow(aTable);
1621  cpl_ensure(nrow > 0, CPL_ERROR_NULL_INPUT, NULL);
1622 
1623  cpl_ensure(cpl_table_has_column(aTable, MUSE_LINE_CATALOG_LAMBDA) == 1
1624  && cpl_table_has_column(aTable, MUSE_LINE_CATALOG_QUALITY) == 1,
1625  CPL_ERROR_DATA_NOT_FOUND, NULL);
1626 
1627  /* convert the usable wavelengths into a vector */
1628  cpl_vector *lambdas = cpl_vector_new(nrow);
1629  int i, pos = 0;
1630  for (i = 0; i < nrow; i++) {
1631  double lambda = cpl_table_get(aTable, MUSE_LINE_CATALOG_LAMBDA, i, NULL),
1632  flux = cpl_table_get(aTable, MUSE_LINE_CATALOG_FLUX, i, NULL);
1633 
1634  /* make sure that the arc line table is sorted, to simplify debugging */
1635  if (i > 0 && lambda < cpl_table_get(aTable, MUSE_LINE_CATALOG_LAMBDA, i-1,
1636  NULL)) {
1637  cpl_error_set_message(__func__, CPL_ERROR_INCOMPATIBLE_INPUT, "%s is not "
1638  "sorted by increasing lambda (at row %d)!",
1639  MUSE_TAG_LINE_CATALOG, i+1);
1640  cpl_vector_delete(lambdas);
1641  return NULL;
1642  }
1643 
1644  if (cpl_table_get(aTable, MUSE_LINE_CATALOG_QUALITY, i, NULL)
1645  < aGoodnessLimit || flux < aFluxLimit) {
1646  /* this is apparently a line that should not be used */
1647  continue;
1648  }
1649  cpl_vector_set(lambdas, pos, lambda);
1650  pos++;
1651  } /* for i (all table rows) */
1652  if (!pos) { /* setting the size to zero does not work! */
1653  cpl_vector_delete(lambdas);
1654  cpl_error_set_message(__func__, CPL_ERROR_DATA_NOT_FOUND, "No lines with "
1655  "%s >= %d found", MUSE_LINE_CATALOG_QUALITY,
1656  aGoodnessLimit);
1657  return NULL;
1658  }
1659  /* cut vector size to contain the usable wavelengths */
1660  cpl_vector_set_size(lambdas, pos);
1661 
1662  /* remove lines that are too close together, i.e. within 1.5 Angstrom */
1663  for (i = 0; i < cpl_vector_get_size(lambdas) - 1; i++) {
1664  double l1 = cpl_vector_get(lambdas, i),
1665  l2 = cpl_vector_get(lambdas, i + 1);
1666  if ((l2 - l1) < 1.5) {
1667  cpl_msg_debug(__func__, "Excluding lines at %.3f and %.3f (d = %.3f) "
1668  "Angstrom", l1, l2, l2 - l1);
1669  muse_cplvector_erase_element(lambdas, i + 1);
1670  muse_cplvector_erase_element(lambdas, i);
1671  i--; /* stay at this index to see what moved here */
1672  }
1673  } /* for i (all vector entries) */
1674 #if 0
1675  printf("%d arc lines in input list are usable:\n", pos);
1676  cpl_vector_dump(lambdas, stdout);
1677 #endif
1678  cpl_msg_debug(__func__, "Using a list of %d %s arc lines (from %6.1f to %6.1f "
1679  "Angstrom)", pos,
1680  aGoodnessLimit == 1 ? "good"
1681  : (aGoodnessLimit == 5 ? "FWHM reference"
1682  : "all"),
1683  cpl_vector_get(lambdas, 0),
1684  cpl_vector_get(lambdas, cpl_vector_get_size(lambdas) - 1));
1685 
1686  return lambdas;
1687 } /* muse_wave_lines_get() */
1688 
1689 /*----------------------------------------------------------------------------*/
1706 /*----------------------------------------------------------------------------*/
1707 cpl_vector *
1708 muse_wave_lines_get_for_lamp(cpl_table *aTable, const char *aLamp,
1709  int aGoodnessLimit, double aFluxLimit)
1710 {
1711  cpl_ensure(aTable && aLamp, CPL_ERROR_NULL_INPUT, NULL);
1712  int nrow = cpl_table_get_nrow(aTable);
1713  cpl_ensure(nrow > 0, CPL_ERROR_NULL_INPUT, NULL);
1714 
1715  cpl_table_unselect_all(aTable);
1716  int i;
1717  for (i = 0; i < nrow; i++) {
1718  const char *lampname = muse_wave_lines_get_lampname(aTable, i);
1719  if (!strcmp(lampname, aLamp)) {
1720  cpl_table_select_row(aTable, i);
1721  }
1722  } /* for i (all table rows) */
1723  cpl_table *lamplines = cpl_table_extract_selected(aTable);
1724 #if 0
1725  printf("lamplines for %s\n", aLamp);
1726  cpl_table_dump(lamplines, 0, 10000, stdout);
1727  fflush(stdout);
1728 #endif
1729  cpl_vector *lamplambdas = muse_wave_lines_get(lamplines, aGoodnessLimit,
1730  aFluxLimit);
1731  cpl_table_delete(lamplines);
1732  return lamplambdas;
1733 } /* muse_wave_lines_get_for_lamp() */
1734 
1735 /*----------------------------------------------------------------------------*/
1749 /*----------------------------------------------------------------------------*/
1750 const char *
1751 muse_wave_lines_get_lampname(cpl_table *aTable, const int aIdx)
1752 {
1753  cpl_ensure(aTable, CPL_ERROR_NULL_INPUT, "Unknown_Lamp");
1754  const char *ion = cpl_table_get_string(aTable, "ion", aIdx);
1755  cpl_ensure(ion, CPL_ERROR_ILLEGAL_INPUT, "Unknown_Lamp");
1756 
1757  /* for the HgCd lamp we have "HgI", "CdI", and "Hg_or_Cd" */
1758  if (!strncmp(ion, "Hg", 2) || !strncmp(ion, "Cd", 2)) {
1759  return "HgCd";
1760  }
1761  /* for the Ne lamp we have only "NeI" */
1762  if (!strncmp(ion, "Ne", 2)) {
1763  return "Ne";
1764  }
1765  /* for the Xe lamp we have "XeI" and "XeII" */
1766  if (!strncmp(ion, "Xe", 2)) {
1767  return "Xe";
1768  }
1769  return "Unknown_Lamp";
1770 } /* muse_wave_lines_get_lampname() */
1771 
1772 /*----------------------------------------------------------------------------*/
1779 /*----------------------------------------------------------------------------*/
1780 cpl_boolean
1781 muse_wave_lines_covered_by_data(double aLambda, muse_ins_mode aMode)
1782 {
1783  if ((aLambda > kMuseUsefulLambdaMax) || (aLambda < kMuseUsefulELambdaMin)) {
1784  return CPL_FALSE;
1785  }
1786  /* first check the modes without a gap */
1787  if ((aMode <= MUSE_MODE_WFM_NONAO_N) && (aLambda >= kMuseUsefulNLambdaMin)) {
1788  return CPL_TRUE;
1789  }
1790  if ((aMode == MUSE_MODE_WFM_NONAO_E) && (aLambda >= kMuseUsefulELambdaMin)) {
1791  return CPL_TRUE;
1792  }
1793  /* NFM does not have a gap in the lamp calibrations, either */
1794  if ((aMode == MUSE_MODE_NFM_AO_N) && (aLambda >= kMuseUsefulNFMLambdaMin)) {
1795  return CPL_TRUE;
1796  }
1797  /* now the AO modes, with gap */
1798  if ((aMode == MUSE_MODE_WFM_AO_E) && (aLambda >= kMuseUsefulELambdaMin) &&
1799  ((aLambda <= kMuseNaLambdaMin) || (aLambda >= kMuseNaLambdaMax))) {
1800  return CPL_TRUE;
1801  }
1802  if ((aMode >= MUSE_MODE_WFM_AO_N) && (aLambda >= kMuseUsefulAOLambdaMin) &&
1803  ((aLambda <= kMuseNa2LambdaMin) || (aLambda >= kMuseNa2LambdaMax))) {
1804  return CPL_TRUE;
1805  }
1806  /* whatever is left now, has to be outside the common wavelength range */
1807  return CPL_FALSE;
1808 } /* muse_wave_lines_covered_by_data() */
1809 
1810 /*----------------------------------------------------------------------------*/
1837 /*----------------------------------------------------------------------------*/
1838 cpl_table *
1839 muse_wave_lines_search(muse_image *aColumnImage, double aSigma,
1840  const unsigned short aSlice, const unsigned char aIFU)
1841 {
1842 #if !SEARCH_DEBUG_FILES
1843  UNUSED_ARGUMENT(aSlice);
1844 #endif
1845  cpl_ensure(aColumnImage, CPL_ERROR_NULL_INPUT, NULL);
1846  cpl_ensure(cpl_image_get_min(aColumnImage->stat) > 0.,
1847  CPL_ERROR_DATA_NOT_FOUND, NULL);
1848  cpl_ensure(aSigma > 0., CPL_ERROR_ILLEGAL_INPUT, NULL);
1849 
1850 #define SEARCH_SUBTRACT_BG 1
1851 #if SEARCH_SUBTRACT_BG
1852  /* Subtract any large scale background using a median-filtered spectrum. *
1853  * In the longer run, maybe a polynomial fit to the median-smoothed data *
1854  * should be used instead, because it does not create extra noise. */
1855  cpl_image *bgmedian = cpl_image_duplicate(aColumnImage->data);
1856  cpl_image_fill_noise_uniform(bgmedian, -FLT_MIN, FLT_MIN);
1857 #define BG_KERNEL_WIDTH 51
1858  cpl_mask *filter = cpl_mask_new(1, BG_KERNEL_WIDTH);
1859  cpl_mask_not(filter);
1860  cpl_image_filter_mask(bgmedian, aColumnImage->data, filter, CPL_FILTER_MEDIAN,
1861  CPL_BORDER_FILTER);
1862  cpl_mask_delete(filter);
1863 #if SEARCH_DEBUG_FILES
1864  char fn[FILENAME_MAX];
1865  sprintf(fn, "column_slice%02hu.fits", aSlice);
1866  muse_image_save(aColumnImage, fn);
1867  sprintf(fn, "column_slice%02hu_bgmedian.fits", aSlice);
1868  cpl_image_save(bgmedian, fn, CPL_TYPE_FLOAT, NULL, CPL_IO_CREATE);
1869 #endif
1870  cpl_image *bgsub = cpl_image_subtract_create(aColumnImage->data, bgmedian);
1871  cpl_image_delete(bgmedian);
1872 #if SEARCH_DEBUG_FILES
1873  sprintf(fn, "column_slice%02hu_bgsub.fits", aSlice);
1874  cpl_image_save(bgsub, fn, CPL_TYPE_FLOAT, NULL, CPL_IO_CREATE);
1875 #endif
1876 #endif
1877 
1878  /* create the S/N image */
1879  cpl_image *N = cpl_image_power_create(aColumnImage->stat, 0.5), /* noise */
1880 #if SEARCH_SUBTRACT_BG
1881  *SN = cpl_image_divide_create(bgsub, N); /* S/N image */
1882  cpl_image_delete(bgsub);
1883 #else
1884  *SN = cpl_image_divide_create(aColumnImage->data, N); /* S/N image */
1885 #endif
1886  cpl_image_delete(N);
1887 #if SEARCH_DEBUG_FILES
1888  sprintf(fn, "column_slice%02hu_SN.fits", aSlice);
1889  cpl_image_save(SN, fn, CPL_TYPE_FLOAT, NULL, CPL_IO_CREATE);
1890 #endif
1891 
1892  /* use median statistics of the S/N image to determine the detection limit */
1893  double mdev, median = cpl_image_get_median_dev(SN, &mdev),
1894  limitSN = fmax(0.1, median + aSigma*mdev);
1895  cpl_mask *mask = cpl_mask_threshold_image_create(SN, limitSN, FLT_MAX);
1896  cpl_size nlines = 0; /* number of detected lines */
1897  cpl_image *label = cpl_image_labelise_mask_create(mask, &nlines);
1898  cpl_mask_delete(mask);
1899 #if SEARCH_DEBUG_FILES
1900  sprintf(fn, "column_slice%02hu_label.fits", aSlice);
1901  cpl_image_save(label, fn, CPL_TYPE_USHORT, NULL, CPL_IO_CREATE);
1902 #endif
1903 #if SEARCH_DEBUG || SEARCH_DEBUG_FILES
1904  double mean = cpl_image_get_mean(SN),
1905  stdev = cpl_image_get_stdev(SN),
1906  min = cpl_image_get_min(SN),
1907  max = cpl_image_get_max(SN);
1908  cpl_msg_debug(__func__, "%"CPL_SIZE_FORMAT" lines found; parameters: sigma=%f, "
1909  "med=%f+/-%f " "mean=%f+/-%f min/max=%f/%f limit(S/N)=%f", nlines,
1910  aSigma, median, mdev, mean, stdev, min, max, limitSN);
1911 #endif
1912  cpl_image_delete(SN);
1913 
1914  /* create table to store the fit results of all the lines */
1915  cpl_table *linesresult = muse_cpltable_new(muse_wavelines_def, nlines);
1916 
1917  /* now loop through all the detected lines and measure them */
1918  int i;
1919  for (i = 0; i < nlines; i++) {
1920  /* create mask for this label to isolate line (note that i starts at 0!) */
1921  cpl_mask *linemask = cpl_mask_threshold_image_create(label, i+0.5, i+1.5);
1922  int masksize = cpl_mask_get_size_y(linemask);
1923 
1924  /* determine the edges of the labeled region and the center of the line */
1925  int j = 1;
1926  while (j <= masksize && cpl_mask_get(linemask, 1, j) == CPL_BINARY_0) {
1927  j++;
1928  }
1929  int lopix = j;
1930  while (j <= masksize && cpl_mask_get(linemask, 1, j) == CPL_BINARY_1) {
1931  j++;
1932  }
1933  int hipix = j - 1;
1934  double cenpix = (hipix + lopix) / 2.;
1935 #if SEARCH_DEBUG
1936  int err;
1937  cpl_msg_debug(__func__, "line %d lo/hi/cen=%d,%d,%f: values=%f,%f", i + 1,
1938  lopix, hipix, cenpix,
1939  cpl_image_get(aColumnImage->data, 1, lopix, &err),
1940  cpl_image_get(aColumnImage->data, 1, hipix, &err));
1941 #endif
1942  cpl_mask_delete(linemask);
1943  if (lopix == hipix) {
1944  /* one pixel is not enough for a solid detection: *
1945  * set to some very low area / flux to be deleted below */
1946  cpl_table_set(linesresult, "flux", i, -1.);
1947  continue;
1948  }
1949 
1950  /* Enlarge region to be sure to measure the whole line (correct *
1951  * width!). As long as the pixel values are smaller than on the *
1952  * edges, and we don't go too far this should be OK. */
1953 #define MAXENLARGE 5
1954  /* reference pixel value (lower edge of mask) */
1955  int err0, err1 = 0, err2 = 0;
1956  double valref = cpl_image_get(aColumnImage->data, 1, lopix, &err0);
1957  cpl_errorstate prestate = cpl_errorstate_get();
1958  j = lopix;
1959  double value = -FLT_MAX;
1960  while (err1 == 0 && value < valref && (lopix - j) <= MAXENLARGE) {
1961  j--; /* enlarge downwards */
1962  value = cpl_image_get(aColumnImage->data, 1, j, &err1);
1963  }
1964  lopix = j + 1; /* set new lower edge */
1965 
1966  /* reference pixel value (lower edge of mask) */
1967  valref = cpl_image_get(aColumnImage->data, 1, hipix, &err2);
1968  j = hipix;
1969  value = -FLT_MAX;
1970  while (err2 == 0 && value < valref && (j - hipix) <= MAXENLARGE) {
1971  j++; /* enlarge upwards */
1972  value = cpl_image_get(aColumnImage->data, 1, j, &err2);
1973  }
1974  hipix = j - 1; /* set new upper edge */
1975  if (lopix > hipix) {
1976  /* guard against weird data, which would cause vector creation to fail */
1977  continue;
1978  }
1979 #if SEARCH_DEBUG
1980  cpl_msg_debug(__func__, "region=%d...%d, size=%d", lopix, hipix,
1981  hipix - lopix + 1);
1982 #endif
1983  if (err1 < 0 || err2 < 0) {
1984  cpl_errorstate_set(prestate); /* clean possible "Access beyond boundaries" */
1985  }
1986 
1987  /* fill vectors */
1988  cpl_vector *positions = cpl_vector_new(hipix - lopix + 1), /* for positions */
1989  *values = cpl_vector_new(hipix - lopix + 1), /* for pixel values */
1990  *valuessigma = cpl_vector_new(hipix - lopix + 1); /* sigma values */
1991  int k;
1992  for (j = lopix, k = 0; j <= hipix; j++, k++) {
1993  cpl_vector_set(positions, k, j);
1994  cpl_vector_set(values, k, cpl_image_get(aColumnImage->data, 1, j, &err0));
1995  /* when setting pixel value from stat extension, use *
1996  * square root, here we need the sigma not the variance: */
1997  cpl_vector_set(valuessigma, k, sqrt(cpl_image_get(aColumnImage->stat,
1998  1, j, &err0)));
1999  }
2000 
2001 #if SEARCH_DEBUG
2002  cpl_bivector *biv = cpl_bivector_wrap_vectors(positions, values);
2003  cpl_bivector_dump(biv, stdout);
2004  cpl_bivector_unwrap_vectors(biv);
2005 #endif
2006 
2007  /* fit Gaussian */
2008  /* compute position, sigma, area, background offset, and mean squared error */
2009  double center, cerr, sigma, area, bglevel, mse;
2010  cpl_matrix *covariance;
2011  prestate = cpl_errorstate_get();
2012  cpl_error_code rc = cpl_vector_fit_gaussian(positions, NULL, values,
2013  valuessigma, CPL_FIT_ALL,
2014  &center, &sigma, &area, &bglevel,
2015  &mse, NULL, &covariance);
2016 
2017  /* try to treat some possible problems */
2018  if (rc == CPL_ERROR_CONTINUE) { /* fit didn't converge */
2019  /* estimate position error as sigma^2/area as CPL docs suggest *
2020  * no warning necessary in this case, print a debug message */
2021  cerr = sqrt(sigma * sigma / area);
2022  cpl_msg_debug(__func__, "Gaussian fit in slice %hu of IFU %hhu around "
2023  "position %6.1f: %s", aSlice, aIFU, cenpix,
2024  cpl_error_get_message());
2025 #if DEBUG_GAUSSFIT
2026  if (cpl_msg_get_log_level() == CPL_MSG_DEBUG) {
2027  /* CPL_ERROR_CONTINUE often occurs if there is another peak on the edge *
2028  * of the input positions/data array, so print it out in debug mode */
2029  cpl_bivector *bv = cpl_bivector_wrap_vectors(positions, values);
2030  printf("Gaussian fit: %f+/-%f, %f, %f, %f %f\nand the input data:\n",
2031  center, cerr, bglevel, area, sigma, mse);
2032  cpl_bivector_dump(bv, stdout);
2033  cpl_bivector_unwrap_vectors(bv);
2034  fflush(stdout);
2035  }
2036 #endif
2037  } else if (rc == CPL_ERROR_SINGULAR_MATRIX || !covariance) {
2038  cerr = sqrt(sigma * sigma / area);
2039  cpl_msg_debug(__func__, "Gaussian fit in slice %hu of IFU %hhu around "
2040  "position %6.1f: %s", aSlice, aIFU, cenpix,
2041  cpl_error_get_message());
2042  } else if (rc != CPL_ERROR_NONE) {
2043  /* although this is unlikely to occur, better print some warning *
2044  * and do something to the data to give this fit less weight in *
2045  * the final computation of the solution */
2046  cpl_msg_debug(__func__, "Gaussian fit in slice %hu of IFU %hhu around "
2047  "position %6.1f: %s", aSlice, aIFU, cenpix,
2048  cpl_error_get_message());
2049  cerr = 100.; /* set a high centering error */
2050  } else {
2051  /* no error returned, everything should have worked nicely *
2052  * take the centering error from the covariance matrix */
2053  cerr = sqrt(cpl_matrix_get(covariance, 0, 0));
2054 #if SEARCH_DEBUG
2055  cpl_matrix_dump(covariance, stdout);
2056 #endif
2057  cpl_matrix_delete(covariance);
2058  }
2059  cpl_errorstate_set(prestate); /* now we can reset the status */
2060  if (fabs(center - cenpix) > MUSE_WAVE_LINES_SEARCH_SHIFT_WARN) {
2061  cpl_msg_debug(__func__, "Large shift in Gaussian centering in slice %hu "
2062  "of IFU %hhu: initial %7.2f, fit %7.2f", aSlice, aIFU,
2063  cenpix, center);
2064  }
2065 
2066  /* save all results of this fit into the output table *
2067  * (no need to fill the x-position into the "x" column) */
2068  cpl_table_set(linesresult, "y", i, cenpix);
2069  /* set actual peak value in the table using cpl_vector_get_max() is safe, *
2070  * because the vector is constructed to be small enough to not include *
2071  * neighboring lines and so the likelihood of including cosmic rays is low */
2072  cpl_table_set(linesresult, "peak", i, cpl_vector_get_max(values));
2073  cpl_table_set(linesresult, "center", i, center);
2074  cpl_table_set(linesresult, "cerr", i, cerr);
2075  cpl_table_set(linesresult, "fwhm", i, CPL_MATH_FWHM_SIG * sigma);
2076  cpl_table_set(linesresult, "sigma", i, sigma);
2077  cpl_table_set(linesresult, "flux", i, area);
2078  cpl_table_set(linesresult, "bg", i, bglevel);
2079  cpl_table_set(linesresult, "mse", i, mse);
2080 
2081  cpl_vector_delete(positions);
2082  cpl_vector_delete(values);
2083  cpl_vector_delete(valuessigma);
2084 #if SEARCH_DEBUG
2085  printf("%s: results of fit stored in table row %d:\n", __func__, i + 1);
2086  cpl_table_dump(linesresult, i, 1, stdout);
2087  fflush(stdout);
2088 #endif
2089  } /* for i (all detected lines) */
2090  cpl_image_delete(label);
2091 
2092  /* again loop through all the table lines, and remove unlikely detections */
2093  cpl_table_unselect_all(linesresult);
2094  for (i = 0; i < cpl_table_get_nrow(linesresult); i++) {
2095  if (cpl_table_get(linesresult, "cerr", i, NULL) > kMuseArcMaxCenteringError ||
2096  cpl_table_get(linesresult, "fwhm", i, NULL) < kMuseArcMinFWHM ||
2097  cpl_table_get(linesresult, "fwhm", i, NULL) > kMuseArcMaxFWHM ||
2098  cpl_table_get(linesresult, "flux", i, NULL) < kMuseArcMinFlux) {
2099  cpl_table_select_row(linesresult, i);
2100  }
2101  } /* for i (all detected lines) */
2102  cpl_table_erase_selected(linesresult);
2103 
2104  return linesresult;
2105 } /* muse_wave_lines_search() */
2106 
2107 /*----------------------------------------------------------------------------*/
2127 /*----------------------------------------------------------------------------*/
2128 cpl_error_code
2129 muse_wave_lines_identify(cpl_table *aLines, cpl_vector *aLambdas,
2130  const muse_wave_params *aParams)
2131 {
2132  cpl_ensure_code(aLines && aLambdas, CPL_ERROR_NULL_INPUT);
2133 
2134  /* convert detected lines from the table into a simple vector */
2135  int i, nlines = cpl_table_get_nrow(aLines);
2136  cpl_vector *vcenter = cpl_vector_new(nlines);
2137  for (i = 0; i < nlines; i++) {
2138  cpl_vector_set(vcenter, i, cpl_table_get(aLines, "center", i, NULL));
2139  } /* for i (all lines) */
2140 #if 0
2141  cpl_vector_dump(vcenter, stdout);
2142 #endif
2143  double dmin = kMuseSpectralSamplingA - kMuseSpectralSamplingA * aParams->ddisp,
2144  dmax = kMuseSpectralSamplingA + kMuseSpectralSamplingA * aParams->ddisp;
2145  cpl_bivector *id_lines = cpl_ppm_match_positions(vcenter, aLambdas, dmin, dmax,
2146  aParams->tolerance, NULL, NULL);
2147 #if 0
2148  cpl_msg_debug(__func__, "%"CPL_SIZE_FORMAT" identified lines (of %"
2149  CPL_SIZE_FORMAT" detected lines and %"CPL_SIZE_FORMAT
2150  " from linelist)", cpl_bivector_get_size(id_lines),
2151  cpl_vector_get_size(vcenter), cpl_vector_get_size(aLambdas));
2152  cpl_bivector_dump(id_lines, stdout);
2153  fflush(stdout);
2154 #endif
2155  cpl_vector_delete(vcenter);
2156 
2157 #if 0
2158  printf("detected lines before cleanup:\n");
2159  cpl_table_dump(aLines, 0, nlines, stdout);
2160  fflush(stdout);
2161 #endif
2162  /* now go through the detected lines and remove all unidentified */
2163  const double *id_center = cpl_bivector_get_x_data_const(id_lines),
2164  *id_lambda = cpl_bivector_get_y_data_const(id_lines);
2165  cpl_table_unselect_all(aLines);
2166  int j, nid = cpl_bivector_get_size(id_lines);
2167  for (i = 0, j = 0; i < cpl_table_get_nrow(aLines) && id_center && id_lambda; i++) {
2168 #if 0
2169  cpl_msg_debug(__func__, "c=%f, l=%f, c_det=%f", id_center[j], id_lambda[j],
2170  cpl_table_get(aLines, "center", i, NULL));
2171 #endif
2172  if (j < nid && fabs(id_center[j] - cpl_table_get(aLines, "center", i, NULL))
2173  < DBL_EPSILON) {
2174  /* found the same line, append the wavelength */
2175  cpl_table_set(aLines, "lambda", i, id_lambda[j]);
2176  j++;
2177  continue;
2178  }
2179  cpl_table_select_row(aLines, i); /* not matching, delete this line */
2180  } /* for i (detected lines) and j (identified lines) */
2181  cpl_table_erase_selected(aLines);
2182  cpl_bivector_delete(id_lines);
2183  int debug = getenv("MUSE_DEBUG_WAVECAL")
2184  ? atoi(getenv("MUSE_DEBUG_WAVECAL")) : 0;
2185  if (debug >= 2) {
2186  printf("identified %d lines, %"CPL_SIZE_FORMAT" after cleanup:\n", nid,
2187  cpl_table_get_nrow(aLines));
2188  cpl_table_dump(aLines, 0, nid, stdout);
2189  fflush(stdout);
2190  }
2191  nid = cpl_table_get_nrow(aLines);
2192  /* check that after identification enough lines are still there */
2193  if (nid <= 0) {
2194  return CPL_ERROR_DATA_NOT_FOUND;
2195  } else if (nid < aParams->yorder + 1) {
2196  return CPL_ERROR_ILLEGAL_OUTPUT;
2197  }
2198  return CPL_ERROR_NONE;
2199 } /* muse_wave_lines_identify() */
2200 
2201 /*----------------------------------------------------------------------------*/
2233 /*----------------------------------------------------------------------------*/
2234 cpl_table *
2235 muse_wave_line_handle_singlet(muse_image *aImage, cpl_table *aLinelist,
2236  unsigned int aIdx, cpl_polynomial *aPoly,
2237  cpl_polynomial **aTrace,
2238  const muse_wave_params *aParams,
2239  const unsigned short aSlice, int aDebug)
2240 {
2241  cpl_ensure(aImage && aLinelist && aPoly && aTrace, CPL_ERROR_NULL_INPUT, NULL);
2242 
2243  /* Fix the Gaussian sigmas for lines that are not FWHM reference lines, *
2244  * otherwise the fit might run astray in low S/N cases. A negative sigma *
2245  * signifies constant value to fitting routine. */
2246  double sigma = kMuseSliceSlitWidthA / kMuseSpectralSamplingA / CPL_MATH_FWHM_SIG;
2247  /* if not reference line, set it negative, so that it is fixed in the fit */
2248  if (cpl_table_get(aLinelist, MUSE_LINE_CATALOG_QUALITY, aIdx, NULL) != 5) {
2249  sigma *= -1;
2250  }
2251  int halfwidth = 3.*kMuseSliceSlitWidthA / kMuseSpectralSamplingA; /* 3*FWHM */
2252 
2253  /* convenient access to some properties of the current line */
2254  double lambda = cpl_table_get(aLinelist, MUSE_LINE_CATALOG_LAMBDA, aIdx, NULL),
2255  ypos = cpl_polynomial_eval_1d(aPoly, lambda, NULL);
2256  if ((ypos - halfwidth) < 1 ||
2257  (ypos + halfwidth) > cpl_image_get_size_y(aImage->data)) {
2258  if (aDebug >= 2) {
2259  cpl_msg_debug(__func__, "%f is supposed to lie near %.3f in slice %2hu of"
2260  " IFU %hhu, i.e. outside!", lambda, ypos, aSlice,
2261  muse_utils_get_ifu(aImage->header));
2262  }
2263  return NULL;
2264  }
2265  if (aDebug >= 2) {
2266  cpl_msg_debug(__func__, "%f is supposed to lie near %.3f in slice %2hu of "
2267  "IFU %hhu", lambda, ypos, aSlice,
2268  muse_utils_get_ifu(aImage->header));
2269  }
2270  /* get both slice edges and the center */
2271  double dleft = cpl_polynomial_eval_1d(aTrace[MUSE_TRACE_LEFT],
2272  ypos, NULL),
2273  dright = cpl_polynomial_eval_1d(aTrace[MUSE_TRACE_RIGHT],
2274  ypos, NULL),
2275  dmid = (dleft + dright) / 2.;
2276  int ileft = ceil(dleft),
2277  iright = floor(dright);
2278 #if 0
2279  cpl_msg_debug(__func__, "limits at y=%f: %f < %f < %f", ypos, dleft, dmid,
2280  dright);
2281 #endif
2282 
2283  /* table to store line fits for this one arc line */
2284  cpl_table *fittable = muse_cpltable_new(muse_wavelines_def,
2285  (int)kMuseSliceHiLikelyWidth + 5);
2286 
2287  /* From the center of the slice move outwards and fit the line *
2288  * until we have arrived at the edge of the slice */
2289  double y = ypos;
2290  int i, n = 0;
2291  for (i = dmid; i >= ileft; i--) {
2292  cpl_error_code rc = muse_wave_line_fit_single(aImage, i, y, halfwidth,
2293  sigma, fittable, ++n);
2294  if (rc != CPL_ERROR_NONE) { /* do not count this line */
2295  --n;
2296  } else {
2297  double ynew = cpl_table_get(fittable, "center", n - 1, NULL);
2298  if (fabs(y - ynew) < MUSE_WAVE_LINE_HANDLE_SHIFT_LIMIT) {
2299  y = ynew;
2300  }
2301  }
2302  } /* for i (columns to left of slice middle) */
2303 #if 0
2304  printf("arc line aIdx=%u, columns i=%d...", aIdx + 1, i);
2305 #endif
2306  y = ypos; /* start at middle y position again */
2307  for (i = dmid + 1; i <= iright; i++) {
2308  cpl_error_code rc = muse_wave_line_fit_single(aImage, i, ypos, halfwidth,
2309  sigma, fittable, ++n);
2310  if (rc != CPL_ERROR_NONE) { /* do not count this line */
2311  --n;
2312  } else {
2313  double ynew = cpl_table_get(fittable, "center", n - 1, NULL);
2314  if (fabs(y - ynew) < MUSE_WAVE_LINE_HANDLE_SHIFT_LIMIT) {
2315  y = ynew;
2316  }
2317  }
2318  } /* for i (columns to right of slice middle) */
2319  /* now remove rows with invalid entries, i.e. those that were not *
2320  * filled with the properties of the fit -- cpl_table_erase_invalid() *
2321  * does not work, it deletes all columns */
2322  cpl_table_select_all(fittable);
2323  cpl_table_and_selected_invalid(fittable, "center");
2324  cpl_table_erase_selected(fittable);
2325  cpl_table_fill_column_window(fittable, "lambda", 0,
2326  cpl_table_get_nrow(fittable), lambda);
2327 #if 0
2328  printf("line %u, %d line fits\n", aIdx + 1, n);
2329  cpl_table_dump(fittable, 0, n, stdout);
2330  fflush(stdout);
2331 #endif
2332  /* and reject deviant fits */
2333  muse_wave_line_fit_iterate(fittable, lambda, aParams);
2334  int npos = cpl_table_get_nrow(fittable);
2335  if (npos <= 0) {
2336  cpl_msg_warning(__func__, "Polynomial fit failed in slice %hu of IFU %hhu "
2337  "for line %u (y-position near %.2f pix): %s", aSlice,
2338  muse_utils_get_ifu(aImage->header), aIdx + 1, ypos,
2339  cpl_error_get_message());
2340  }
2341 #if 0
2342  else {
2343  printf("%s: line %2u, %d line fits, %d with low residuals:\n", __func__,
2344  aIdx + 1, n, npos);
2345  cpl_table_dump(fittable, 0, npos, stdout);
2346  fflush(stdout);
2347  }
2348 #endif
2349  return fittable;
2350 } /* muse_wave_line_handle_singlet() */
2351 
2352 /*----------------------------------------------------------------------------*/
2388 /*----------------------------------------------------------------------------*/
2389 cpl_table *
2390 muse_wave_line_handle_multiplet(muse_image *aImage, cpl_table *aLinelist,
2391  unsigned int aIdx, cpl_polynomial *aPoly,
2392  cpl_polynomial **aTrace,
2393  const muse_wave_params *aParams,
2394  const unsigned short aSlice, int aDebug)
2395 {
2396  cpl_ensure(aImage && aLinelist && aPoly && aTrace, CPL_ERROR_NULL_INPUT, NULL);
2397 
2398  /* search for the other line(s) of the multiplet */
2399 #define MULTIPLET_SEARCH_RANGE 40. /* 40 Angstrom for NeI 7024...7059 */
2400  unsigned int nlines = 1; /* for the moment we know of one line of the multiplet */
2401  double lbda1 = cpl_table_get(aLinelist, MUSE_LINE_CATALOG_LAMBDA, aIdx, NULL);
2402  const char *lamp1 = muse_wave_lines_get_lampname(aLinelist, aIdx);
2403  cpl_vector *lambdas = cpl_vector_new(nlines),
2404  *fluxes = cpl_vector_new(nlines);
2405  cpl_vector_set(lambdas, 0, lbda1);
2406  cpl_vector_set(fluxes, 0, cpl_table_get(aLinelist, MUSE_LINE_CATALOG_FLUX,
2407  aIdx, NULL));
2408  double lambda;
2409  unsigned int j = aIdx;
2410  for (lambda = cpl_table_get(aLinelist, MUSE_LINE_CATALOG_LAMBDA, ++j, NULL);
2411  fabs(lambda - lbda1) < MULTIPLET_SEARCH_RANGE;
2412  lambda = cpl_table_get(aLinelist, MUSE_LINE_CATALOG_LAMBDA, ++j, NULL)) {
2413  int quality = cpl_table_get(aLinelist, MUSE_LINE_CATALOG_QUALITY, j, NULL);
2414  const char *lamp = muse_wave_lines_get_lampname(aLinelist, j);
2415  if (quality == 2 && !strcmp(lamp1, lamp)) { /* duplet of the same lamp */
2416  nlines++;
2417  cpl_vector_set_size(lambdas, nlines);
2418  cpl_vector_set_size(fluxes, nlines);
2419  cpl_vector_set(lambdas, nlines - 1, lambda);
2420  double flux = cpl_table_get(aLinelist, MUSE_LINE_CATALOG_FLUX, j, NULL);
2421  cpl_vector_set(fluxes, nlines - 1, flux);
2422  /* invert the sign of the quality, so that this line is not found again */
2423  cpl_table_set(aLinelist, MUSE_LINE_CATALOG_QUALITY, j, -quality);
2424  }
2425  } /* for lambda */
2426 
2427  if (aDebug >= 2) {
2428  printf("found multiplet of lamp %s with %u lines:\n", lamp1, nlines);
2429  cpl_bivector *bv = cpl_bivector_wrap_vectors(lambdas, fluxes);
2430  cpl_bivector_dump(bv, stdout);
2431  cpl_bivector_unwrap_vectors(bv);
2432  fflush(stdout);
2433  }
2434 
2435  /* positive sigma: using negative value (= fixed parameter in fit) actually *
2436  * causes higher deviations, worse RMS in the global fit, so leave it free */
2437  double sigma = kMuseSliceSlitWidthA / kMuseSpectralSamplingA / CPL_MATH_FWHM_SIG;
2438  int halfwidth = 3.*kMuseSliceSlitWidthA / kMuseSpectralSamplingA; /* 3*FWHM */
2439 
2440  cpl_vector *ypos = cpl_vector_new(nlines);
2441  for (j = 0; j < nlines; j++) {
2442  double yp = cpl_polynomial_eval_1d(aPoly, cpl_vector_get(lambdas, j), NULL);
2443  cpl_vector_set(ypos, j, yp);
2444  } /* for j */
2445  double ypos1 = cpl_vector_get(ypos, 0),
2446  ypos2 = cpl_vector_get(ypos, nlines - 1);
2447  cpl_bivector *peaks = cpl_bivector_wrap_vectors(ypos, fluxes);
2448  if ((ypos1 - halfwidth) < 1 ||
2449  (ypos2 + halfwidth) > cpl_image_get_size_y(aImage->data)) {
2450  if (aDebug >= 2) {
2451  cpl_msg_debug(__func__, "%f is supposed to lie at %.3f..%.3f in slice "
2452  "%2hu of IFU %hhu, i.e. outside!", lambda, ypos1, ypos2,
2453  aSlice, muse_utils_get_ifu(aImage->header));
2454  }
2455  cpl_bivector_delete(peaks);
2456  cpl_vector_delete(lambdas);
2457  return NULL;
2458  }
2459  if (aDebug >= 2) {
2460  cpl_msg_debug(__func__, "%f is supposed to lie at %.3f..%.3f in slice %2hu "
2461  "of IFU %hhu", lambda, ypos1, ypos2, aSlice,
2462  muse_utils_get_ifu(aImage->header));
2463  }
2464  /* get both slice edges and the center */
2465  double dleft = cpl_polynomial_eval_1d(aTrace[MUSE_TRACE_LEFT],
2466  (ypos1 + ypos2)/2., NULL),
2467  dright = cpl_polynomial_eval_1d(aTrace[MUSE_TRACE_RIGHT],
2468  (ypos1 + ypos2)/2., NULL),
2469  dmid = (dleft + dright) / 2.;
2470  int ileft = ceil(dleft),
2471  iright = floor(dright);
2472 
2473  /* table to store line fits for this one arc line */
2474  cpl_table *fittable = muse_cpltable_new(muse_wavelines_def,
2475  ((int)kMuseSliceHiLikelyWidth + 5) * nlines);
2476 
2477  /* From the center of the slice move outwards and fit the *
2478  * line until we have arrived at the edge of the slice */
2479  cpl_bivector *bp = cpl_bivector_duplicate(peaks),
2480  *bpgood = cpl_bivector_duplicate(peaks);
2481  int i, n = 0;
2482  for (i = dmid; i >= ileft; i--) {
2483  n += nlines;
2484  cpl_error_code rc = muse_wave_line_fit_multiple(aImage, i, bp, lambdas,
2485  halfwidth, sigma, fittable, n);
2486  if (rc != CPL_ERROR_NONE) { /* do not count this fit */
2487  cpl_bivector_delete(bp);
2488  bp = cpl_bivector_duplicate(bpgood);
2489  n -= nlines;
2490  } else {
2491  cpl_vector *shifts = cpl_vector_duplicate(cpl_bivector_get_x(bp));
2492  cpl_vector_subtract(shifts, cpl_bivector_get_x(bpgood));
2493  double shift = cpl_vector_get_median(shifts); /* may be non-const! */
2494  cpl_vector_delete(shifts);
2495  if (fabs(shift) < MUSE_WAVE_LINE_HANDLE_SHIFT_LIMIT) {
2496  cpl_bivector_delete(bpgood);
2497  bpgood = cpl_bivector_duplicate(bp);
2498  } else {
2499  cpl_bivector_delete(bp);
2500  bp = cpl_bivector_duplicate(bpgood);
2501  }
2502  } /* else (good fit) */
2503  } /* for i (columns to left of slice middle) */
2504  cpl_bivector_delete(bp);
2505  cpl_bivector_delete(bpgood);
2506  bp = cpl_bivector_duplicate(peaks);
2507  bpgood = cpl_bivector_duplicate(peaks);
2508  for (i = dmid + 1; i <= iright; i++) {
2509  n += nlines;
2510  cpl_error_code rc = muse_wave_line_fit_multiple(aImage, i, bp, lambdas,
2511  halfwidth, sigma, fittable, n);
2512  if (rc != CPL_ERROR_NONE) { /* do not count this fit */
2513  cpl_bivector_delete(bp);
2514  bp = cpl_bivector_duplicate(bpgood);
2515  n -= nlines;
2516  } else {
2517  cpl_vector *shifts = cpl_vector_duplicate(cpl_bivector_get_x(bp));
2518  cpl_vector_subtract(shifts, cpl_bivector_get_x(bpgood));
2519  double shift = cpl_vector_get_median(shifts); /* may be non-const! */
2520  cpl_vector_delete(shifts);
2521  if (fabs(shift) < MUSE_WAVE_LINE_HANDLE_SHIFT_LIMIT) {
2522  cpl_bivector_delete(bpgood);
2523  bpgood = cpl_bivector_duplicate(bp);
2524  } else {
2525  cpl_bivector_delete(bp);
2526  bp = cpl_bivector_duplicate(bpgood);
2527  }
2528  } /* else (good fit) */
2529  } /* for i (columns to right of slice middle) */
2530  cpl_bivector_delete(bp);
2531  cpl_bivector_delete(bpgood);
2532  /* now remove rows with invalid entries, i.e. those that *
2533  * were not filled with the properties of the fit */
2534  cpl_table_select_all(fittable);
2535  cpl_table_and_selected_invalid(fittable, "center");
2536  cpl_table_erase_selected(fittable);
2537  cpl_bivector_delete(peaks);
2538  /* and reject deviant fits */
2539  for (j = 0; j < nlines; j++) {
2540  muse_wave_line_fit_iterate(fittable, cpl_vector_get(lambdas, j), aParams);
2541  } /* for i */
2542  cpl_vector_delete(lambdas);
2543 
2544  return fittable;
2545 } /* muse_wave_line_handle_multiplet() */
2546 
2547 /*----------------------------------------------------------------------------*/
2578 /*----------------------------------------------------------------------------*/
2579 cpl_error_code
2580 muse_wave_line_fit_single(muse_image *aImage, int aX, double aY, int aHalfWidth,
2581  double aSigma, cpl_table *aFitTable, int aRowsNeeded)
2582 {
2583  cpl_ensure_code(aImage && aImage->data && aImage->stat && aFitTable,
2584  CPL_ERROR_NULL_INPUT);
2585 #if 0
2586  cpl_msg_debug(__func__, "%d %d %d -> %d, %d", aX, (int)aY, aHalfWidth,
2587  2*aHalfWidth+1, aRowsNeeded);
2588 #endif
2589  /* determine area on the input image, copy area into the vectors */
2590  cpl_vector *positions = cpl_vector_new(2*aHalfWidth+1),
2591  *values = cpl_vector_new(2*aHalfWidth+1),
2592  *valuessigma = cpl_vector_new(2*aHalfWidth+1);
2593  int i, j, ny = cpl_image_get_size_y(aImage->data);
2594  for (i = (int)aY - aHalfWidth, j = 0; i <= (int)aY + aHalfWidth && i <= ny;
2595  i++, j++) {
2596  int err;
2597  cpl_vector_set(positions, j, i);
2598  cpl_vector_set(values, j, cpl_image_get(aImage->data, aX, i, &err));
2599  cpl_vector_set(valuessigma, j,
2600  sqrt(cpl_image_get(aImage->stat, aX, i, &err)));
2601  }
2602 #if 0
2603  printf("input vectors: positions, values\n");
2604  cpl_bivector *biv = cpl_bivector_wrap_vectors(positions, values);
2605  cpl_bivector_dump(biv, stdout);
2606  fflush(stdout);
2607  cpl_bivector_unwrap_vectors(biv);
2608 #if 0
2609  printf("input vectors: values, valuessigma\n");
2610  biv = cpl_bivector_wrap_vectors(values, valuessigma);
2611  cpl_bivector_dump(biv, stdout);
2612  fflush(stdout);
2613  cpl_bivector_unwrap_vectors(biv);
2614 #endif
2615 #endif
2616 
2617  /* do the Gaussfit */
2618  cpl_errorstate prestate = cpl_errorstate_get();
2619  double center, cerror, area, bglevel, mse;
2620  cpl_matrix *covariance = NULL;
2621  cpl_fit_mode mode = CPL_FIT_ALL;
2622  double sigma = aSigma;
2623  if (sigma < 0) {
2624  mode = CPL_FIT_CENTROID | CPL_FIT_AREA | CPL_FIT_OFFSET;
2625  sigma *= -1;
2626  }
2627  cpl_error_code rc
2628  = cpl_vector_fit_gaussian(positions, NULL, values, valuessigma, mode,
2629  &center, &sigma, &area, &bglevel, &mse, NULL,
2630  &covariance);
2631 #if 0
2632  printf("--> rc=%d (%d) %s %#x %#x\n", rc, CPL_ERROR_NONE,
2633  cpl_error_get_message(), covariance, &covariance);
2634  fflush(stdout);
2635 #endif
2636  cpl_vector_delete(positions);
2637  cpl_vector_delete(values);
2638  cpl_vector_delete(valuessigma);
2639  /* Determine goodness of fit and try to treat some possible problems. *
2640  * (This is partly copied from muse_wave_lines_search().) */
2641  /* if no error happened, take the centering error from the covariance matrix */
2642  if (covariance) {
2643  cerror = sqrt(cpl_matrix_get(covariance, 0, 0));
2644  cpl_matrix_delete(covariance);
2645  } else { /* a missing covariance matrix is bad */
2646  cpl_msg_debug(__func__, "Gauss fit produced no covariance matrix (y=%.3f in "
2647  "column=%d): %s", aY, aX, cpl_error_get_message());
2648  cpl_errorstate_set(prestate);
2649  return rc == CPL_ERROR_NONE ? CPL_ERROR_ILLEGAL_OUTPUT : rc;
2650  }
2651  if (rc == CPL_ERROR_CONTINUE) { /* fit didn't converge */
2652  /* estimate position error as sigma^2/area as CPL docs *
2653  * suggest and pretend that everything worked fine */
2654  cerror = sqrt(sigma * sigma / area);
2655  cpl_errorstate_set(prestate);
2656  rc = CPL_ERROR_NONE;
2657  }
2658  if (rc != CPL_ERROR_NONE) {
2659  /* some other, probably more serious error, don't use this fit */
2660  cpl_msg_debug(__func__, "Gauss fit failed with some error (y=%.3f in "
2661  "column=%d): %s", aY, aX, cpl_error_get_message());
2662  cpl_errorstate_set(prestate);
2663  return rc;
2664  }
2665  if (fabs(center - aY) > MUSE_WAVE_LINE_FIT_MAXSHIFT) {
2666  /* too big shift, don't use this fit */
2667  cpl_msg_debug(__func__, "Gauss fit gave unexpectedly large offset "
2668  "(shifted %.3f pix from y=%.3f in column=%d)",
2669  center - aY, aY, aX);
2670  return CPL_ERROR_ACCESS_OUT_OF_RANGE;
2671  }
2672 
2673  /* store the results in the table, after making sure it is large enough */
2674  if (cpl_table_get_nrow(aFitTable) < aRowsNeeded) {
2675  cpl_table_set_size(aFitTable, aRowsNeeded);
2676  }
2677  cpl_table_set(aFitTable, "center", aRowsNeeded - 1, center);
2678  cpl_table_set(aFitTable, "cerr", aRowsNeeded - 1, cerror);
2679  cpl_table_set(aFitTable, "sigma", aRowsNeeded - 1, sigma);
2680  if (mode == CPL_FIT_ALL) { /* is FWHM reference line, store the FWHM */
2681  cpl_table_set(aFitTable, "fwhm", aRowsNeeded - 1, CPL_MATH_FWHM_SIG * sigma);
2682  }
2683  cpl_table_set(aFitTable, "flux", aRowsNeeded - 1, area);
2684  cpl_table_set(aFitTable, "bg", aRowsNeeded - 1, bglevel);
2685  cpl_table_set(aFitTable, "mse", aRowsNeeded - 1, mse);
2686  cpl_table_set(aFitTable, "x", aRowsNeeded - 1, aX);
2687  cpl_table_set(aFitTable, "y", aRowsNeeded - 1, aY);
2688 
2689 #if 0
2690  printf("--> Gaussian fit: %f +/- %f, %f\n", center, cerror, area);
2691  fflush(stdout);
2692 #endif
2693  return rc;
2694 } /* muse_wave_line_fit_single() */
2695 
2696 /*----------------------------------------------------------------------------*/
2734 /*----------------------------------------------------------------------------*/
2735 cpl_error_code
2736 muse_wave_line_fit_multiple(muse_image *aImage, int aX, cpl_bivector *aPeaks,
2737  cpl_vector *aLambdas, int aHalfWidth, double aSigma,
2738  cpl_table *aFitTable, int aRowsNeeded)
2739 {
2740  cpl_ensure_code(aImage && aImage->data && aImage->stat && aFitTable,
2741  CPL_ERROR_NULL_INPUT);
2742  cpl_vector *ypeaks = cpl_bivector_get_x(aPeaks),
2743  *fluxes = cpl_bivector_get_y(aPeaks);
2744  int np = cpl_vector_get_size(ypeaks);
2745  double yp1 = cpl_vector_get(ypeaks, 0),
2746  yp2 = cpl_vector_get(ypeaks, np - 1);
2747  int i1 = floor(yp1),
2748  i2 = ceil(yp2);
2749 #if 0
2750  cpl_msg_debug(__func__, "%d %d..%d %d -> %d", aX, i1, i2, aHalfWidth,
2751  aRowsNeeded);
2752 #endif
2753  /* determine area on the input image, copy area into the vectors */
2754  int npoints = (i2 + aHalfWidth) - (i1 - aHalfWidth) + 1;
2755  cpl_vector *positions = cpl_vector_new(npoints),
2756  *values = cpl_vector_new(npoints),
2757  *valuessigma = cpl_vector_new(npoints);
2758  double minval = DBL_MAX; /* 1st-guess fit value */
2759  int i, j, ny = cpl_image_get_size_y(aImage->data);
2760  for (i = i1 - aHalfWidth, j = 0; i <= i2 + aHalfWidth && i <= ny; i++, j++) {
2761  int err;
2762  cpl_vector_set(positions, j, i);
2763  double value = cpl_image_get(aImage->data, aX, i, &err);
2764  cpl_vector_set(values, j, value);
2765  if (value < minval) {
2766  minval = value;
2767  }
2768  cpl_vector_set(valuessigma, j,
2769  sqrt(cpl_image_get(aImage->stat, aX, i, &err)));
2770  }
2771  minval = minval > 0 ? minval : 0.;
2772 #if 0
2773  printf("input vectors: positions, values\n");
2774  cpl_bivector *biv = cpl_bivector_wrap_vectors(positions, values);
2775  cpl_bivector_dump(biv, stdout);
2776  fflush(stdout);
2777  cpl_bivector_unwrap_vectors(biv);
2778 #endif
2779  cpl_bivector *bvalues = cpl_bivector_wrap_vectors(values, valuessigma);
2780 
2781  /* do the multi-Gauss fit */
2782  /* parameters: slope, background, sigma, np * center, np * flux */
2783  cpl_vector *poly = cpl_vector_new(2);
2784  cpl_vector_set(poly, 0, minval);
2785  cpl_vector_set(poly, 1, 0.);
2786  /* record the index of the expected strongest line, and its position */
2787  cpl_array *afluxes = cpl_array_wrap_double(cpl_vector_get_data(fluxes), np);
2788  cpl_size imaxflux;
2789  cpl_array_get_maxpos(afluxes, &imaxflux);
2790  double yposmax = cpl_vector_get(ypeaks, imaxflux);
2791  cpl_array_unwrap(afluxes);
2792  /* do the fit, store the errorstate before */
2793  cpl_errorstate prestate = cpl_errorstate_get();
2794  double sigma = aSigma,
2795  mse, chisq;
2796  cpl_matrix *covariance;
2797  cpl_error_code rc = muse_utils_fit_multigauss_1d(positions, bvalues, ypeaks,
2798  &sigma, fluxes, poly,
2799  &mse, &chisq, &covariance);
2800  cpl_vector_delete(positions);
2801  cpl_bivector_delete(bvalues);
2802 
2803  /* Determine goodness of fit and try to treat some possible problems. *
2804  * (This is partly copied from muse_wave_lines_search().) */
2805  /* if no error happened, take the centering error from the covariance matrix */
2806  if (!covariance) { /* a missing covariance matrix is bad */
2807  cpl_msg_debug(__func__, "Multi-Gauss fit produced no covariance matrix (y=%."
2808  "3f..%.3f in column=%d): %s", yp1, yp2, aX, cpl_error_get_message());
2809  cpl_errorstate_set(prestate);
2810  cpl_vector_delete(poly);
2811  return rc == CPL_ERROR_NONE ? CPL_ERROR_ILLEGAL_OUTPUT : rc;
2812  }
2813  if (rc != CPL_ERROR_NONE) {
2814  /* some other, probably more serious error, don't use this fit */
2815  cpl_msg_debug(__func__, "Multi-Gauss fit failed with some error (y=%.3f..%."
2816  "3f in column=%d): %s", yp1, yp2, aX, cpl_error_get_message());
2817  cpl_errorstate_set(prestate);
2818  cpl_matrix_delete(covariance);
2819  cpl_vector_delete(poly);
2820  return rc;
2821  }
2822  /* did the center of the brightest line shift too much? */
2823  double yfitmax = cpl_vector_get(ypeaks, imaxflux);
2824  if (fabs(yposmax - yfitmax) > MUSE_WAVE_LINE_FIT_MAXSHIFT) {
2825  cpl_msg_debug(__func__, "Multi-Gauss fit gave unexpectedly large offset "
2826  "(shifted %.3f pix from y=%.3f..%.3f in column=%d)",
2827  yposmax - yfitmax, yp1, yp2, aX);
2828  cpl_matrix_delete(covariance);
2829  cpl_vector_delete(poly);
2830  return CPL_ERROR_ACCESS_OUT_OF_RANGE;
2831  }
2832  /* are any of the fluxes negative? */
2833  double yfitmin = cpl_vector_get_min(fluxes);
2834  if (yfitmin < 0) {
2835  cpl_msg_debug(__func__, "Multi-Gauss fit gave negative flux (%e in "
2836  "multiplet from y=%.3f..%.3f in column=%d)", yfitmin,
2837  yp1, yp2, aX);
2838  cpl_matrix_delete(covariance);
2839  cpl_vector_delete(poly);
2840  return CPL_ERROR_ILLEGAL_OUTPUT;
2841  }
2842 
2843  /* store the results in the table, after making sure it is large enough */
2844  if (cpl_table_get_nrow(aFitTable) < aRowsNeeded) {
2845  cpl_table_set_size(aFitTable, aRowsNeeded);
2846  }
2847  /* first record the common values */
2848  cpl_table_fill_column_window(aFitTable, "mse", aRowsNeeded - np, np, mse);
2849  cpl_table_fill_column_window(aFitTable, "x", aRowsNeeded - np, np, aX);
2850  cpl_table_fill_column_window(aFitTable, "sigma", aRowsNeeded - np, np, sigma);
2851  /* multiplets are never FWHM reference lines, do not store FWHM */
2852  for (i = 0, j = aRowsNeeded - np; i < np; i++, j++) {
2853  cpl_table_set(aFitTable, "lambda", j, cpl_vector_get(aLambdas, i));
2854  cpl_table_set(aFitTable, "y", j, cpl_vector_get(ypeaks, i));
2855  double center = cpl_vector_get(ypeaks, i);
2856  cpl_table_set(aFitTable, "center", j, center);
2857  /* centroid errors are starting with row/column index 3 in the matrix, *
2858  * the first ones are the two polynomial coeffs and the sigma */
2859  double cerror = sqrt(cpl_matrix_get(covariance, 3 + i, 3 + i));
2860  cpl_table_set(aFitTable, "cerr", j, cerror);
2861  cpl_table_set(aFitTable, "flux", j, cpl_vector_get(fluxes, i));
2862  /* evaluate the linear background level at the fitted center */
2863  double bg = cpl_vector_get(poly, 0) + cpl_vector_get(poly, 1) * center;
2864  cpl_table_set(aFitTable, "bg", j, bg);
2865  } /* for i, j */
2866  cpl_vector_delete(poly);
2867  cpl_matrix_delete(covariance);
2868 #if 0
2869  printf("stored %d fitted multiplet values:\n", np);
2870  cpl_table_dump(aFitTable, aRowsNeeded - np - 2 < 0 ? 0 : aRowsNeeded - np - 2, np + 5, stdout);
2871  fflush(stdout);
2872 #endif
2873 
2874  return rc;
2875 } /* muse_wave_line_fit_multiple() */
2876 
2877 /*----------------------------------------------------------------------------*/
2916 /*----------------------------------------------------------------------------*/
2917 cpl_error_code
2918 muse_wave_line_fit_iterate(cpl_table *aFitTable, double aLambda,
2919  const muse_wave_params *aParams)
2920 {
2921  cpl_ensure_code(aFitTable, CPL_ERROR_NULL_INPUT);
2922  int npos = cpl_table_get_nrow(aFitTable);
2923  cpl_ensure_code(npos > 0, CPL_ERROR_ILLEGAL_INPUT);
2924  double rsigma = aParams->linesigma < 0 ? 2.5 : aParams->linesigma;
2925 
2926  /* select all entries with the requested wavelength */
2927  cpl_table *fittable = NULL;
2928  if (aLambda > 0) {
2929  cpl_table_unselect_all(aFitTable);
2930  cpl_table_or_selected_double(aFitTable, "lambda", CPL_EQUAL_TO, aLambda);
2931  npos = cpl_table_count_selected(aFitTable);
2932  cpl_ensure_code(npos > 0, CPL_ERROR_ILLEGAL_INPUT);
2933  fittable = cpl_table_extract_selected(aFitTable);
2934  cpl_table_erase_selected(aFitTable);
2935  } else {
2936  fittable = aFitTable;
2937  }
2938 
2939  /* convert "x" and "center" columns into matrix and vector for the fit */
2940  cpl_matrix *pos = cpl_matrix_new(1, npos);
2941  cpl_vector *val = cpl_vector_new(npos);
2942  int i;
2943  for (i = 0; i < npos; i++) {
2944  cpl_matrix_set(pos, 0, i, cpl_table_get(fittable, "x", i, NULL));
2945  cpl_vector_set(val, i, cpl_table_get(fittable, "center", i, NULL));
2946  }
2947 
2948  /* use the iterative polynomial field to throw out bad entries in fittable */
2949  cpl_errorstate state = cpl_errorstate_get();
2950  double mse;
2951  cpl_polynomial *fit = muse_utils_iterate_fit_polynomial(pos, val, NULL, fittable,
2952  aParams->xorder, rsigma,
2953  &mse, NULL);
2954  cpl_matrix_delete(pos);
2955  cpl_vector_delete(val);
2956  cpl_polynomial_delete(fit);
2957  if (!cpl_errorstate_is_equal(state)) {
2958  /* this implies less than xorder entries left, and is really bad; set the *
2959  * error to something high enough to basically exclude these points */
2960  cpl_table_fill_column_window(fittable, "cerr",
2961  0, cpl_table_get_nrow(fittable), 10.);
2962  } else if (aParams->fitweighting == MUSE_WAVE_WEIGHTING_SCATTER) {
2963  /* replace the original centroid error with the fit RMS */
2964  cpl_table_fill_column_window(fittable, "cerr",
2965  0, cpl_table_get_nrow(fittable), sqrt(mse));
2966  } else if (aParams->fitweighting == MUSE_WAVE_WEIGHTING_CERRSCATTER) {
2967  /* add RMS of fit to individual error in quadrature: *
2968  * cerr = sqrt(cerr^2 + mse) */
2969  cpl_table_power_column(fittable, "cerr", 2.); /* cerr^2 */
2970  cpl_table_add_scalar(fittable, "cerr", mse); /* + mse */
2971  cpl_table_power_column(fittable, "cerr", 0.5); /* sqrt() */
2972  }
2973 #if 0
2974  printf("line at %.3f Angstrom: rms = %f (mean error %f)\n", aLambda,
2975  sqrt(mse), cpl_table_get_column_mean(fittable, "cerr"));
2976  cpl_table_dump(fittable, 0, npos, stdout);
2977  fflush(stdout);
2978 #endif
2979  if (aLambda > 0) { /* need to copy results back into input table */
2980  cpl_table_insert(aFitTable, fittable, cpl_table_get_nrow(aFitTable));
2981  cpl_table_delete(fittable);
2982  }
2983  return CPL_ERROR_NONE;
2984 } /* muse_wave_line_fit_iterate() */
2985 
2986 /*----------------------------------------------------------------------------*/
2998 /*----------------------------------------------------------------------------*/
2999 static inline double
3000 muse_wave_ipow(double x, unsigned int y)
3001 {
3002  if (!y) {
3003  return 1;
3004  }
3005  if (y == 1) {
3006  return x;
3007  }
3008  double x2 = x*x;
3009  if (y == 2) {
3010  return x2;
3011  }
3012  if (y == 3) {
3013  return x2*x;
3014  }
3015  if (y == 4) {
3016  return x2*x2;
3017  }
3018  double result;
3019  /* Handle least significant bit in y here in order to avoid an unnecessary *
3020  * multiplication of x - which could cause an over- or underflow */
3021  result = y & 1 ? x : 1.; /* 0^0 is 1, while any other power of 0 is 0 */
3022  while (y >>= 1) {
3023  x *= x;
3024  if (y & 1) { /* Process least significant bit in y */
3025  result *= x;
3026  }
3027  }
3028  return result;
3029 } /* muse_wave_ipow() */
3030 
3031 /*----------------------------------------------------------------------------*/
3046 /*----------------------------------------------------------------------------*/
3047 static int
3048 muse_wave_poly_2d(const double xy[], const double p[], double *f)
3049 {
3050  unsigned short xorder = p[0],
3051  yorder = p[1];
3052  /* add up the polynomial orders */
3053  *f = 0;
3054  double x = xy[0],
3055  y = xy[1];
3056  unsigned int i, idx = 2;
3057  for (i = 0; i <= xorder; i++) {
3058  double xi = muse_wave_ipow(x, i);
3059  unsigned int j; /* y order */
3060  for (j = 0; j <= yorder; j++) {
3061  *f += p[idx++] * xi * muse_wave_ipow(y, j);
3062  } /* for j */
3063  } /* for i */
3064  return 0;
3065 } /* muse_wave_poly_2d() */
3066 
3067 /*----------------------------------------------------------------------------*/
3080 /*----------------------------------------------------------------------------*/
3081 static int
3082 muse_wave_dpoly_2d(const double xy[], const double p[], double f[])
3083 {
3084  unsigned short xorder = p[0],
3085  yorder = p[1];
3086  f[0] = f[1] = 0; /* derivatives regarding the polynomial orders are zero */
3087  /* now the real derivatives, they don't contain the coefficients any more */
3088  double x = xy[0],
3089  y = xy[1];
3090  unsigned int i, idx = 2;
3091  for (i = 0; i <= xorder; i++) {
3092  double xi = muse_wave_ipow(x, i);
3093  unsigned int j; /* y order */
3094  for (j = 0; j <= yorder; j++) {
3095  f[idx++] = xi * muse_wave_ipow(y, j);
3096  } /* for j */
3097  } /* for i */
3098  return 0;
3099 } /* muse_wave_poly_x2y5_deriv() */
3100 
3101 /*----------------------------------------------------------------------------*/
3143 /*----------------------------------------------------------------------------*/
3144 cpl_error_code
3145 muse_wave_poly_fit(cpl_matrix *aXYPos, cpl_vector *aLambdas, cpl_vector *aDLambdas,
3146  cpl_polynomial **aPoly, double *aMSE, muse_wave_params *aParams,
3147  const unsigned short aSlice)
3148 {
3149  cpl_ensure_code(aPoly && aXYPos && aLambdas, CPL_ERROR_NULL_INPUT);
3150 
3151  /* filter the input measurements by wavelengths, and exclude those *
3152  * outside the valid range, depending on the instrument mode */
3153  int ii, nin = cpl_vector_get_size(aLambdas),
3154  nout = 0;
3155 #if 0
3156  cpl_msg_debug(__func__, "Testing coverage for mode %d.", aParams->mode);
3157 #endif
3158  for (ii = 0; ii < cpl_vector_get_size(aLambdas); ii++) {
3159  double lambda = cpl_vector_get(aLambdas, ii);
3160  if (muse_wave_lines_covered_by_data(lambda, aParams->mode)) {
3161  nout++;
3162  continue;
3163  }
3164 #if 0
3165  cpl_msg_debug(__func__, "line at %.3f Angstrom outside range", lambda);
3166 #endif
3167  cpl_matrix_erase_columns(aXYPos, ii, 1);
3168  muse_cplvector_erase_element(aLambdas, ii);
3169  if (aDLambdas) {
3170  muse_cplvector_erase_element(aDLambdas, ii);
3171  }
3172  ii--; /* stay at this position */
3173  }
3174  cpl_msg_debug(__func__, "%d of %d measurements should have valid wavelengths.",
3175  nout, nin);
3176 
3177 #if 0
3178  printf("aXYPos (%"CPL_SIZE_FORMAT"x%"CPL_SIZE_FORMAT"):\n",
3179  cpl_matrix_get_ncol(aXYPos), cpl_matrix_get_nrow(aXYPos));
3180  cpl_matrix_dump(aXYPos, stdout);
3181  printf("aLambdas (%"CPL_SIZE_FORMAT"):\n", cpl_vector_get_size(aLambdas));
3182  cpl_vector_dump(aLambdas, stdout);
3183  printf("aDLambdas (%"CPL_SIZE_FORMAT"):\n", cpl_vector_get_size(aDLambdas));
3184  cpl_vector_dump(aDLambdas, stdout);
3185  fflush(stdout);
3186 #endif
3187  double rsigma = aParams->fitsigma < 0 ? 3.0 : aParams->fitsigma;
3188  int debug = getenv("MUSE_DEBUG_WAVECAL")
3189  ? atoi(getenv("MUSE_DEBUG_WAVECAL")) : 0;
3190  /* prepare the polynomial for two dimensions */
3191  *aPoly = cpl_polynomial_new(2);
3192 
3193  double rms = -1; /* start with negative (= invalid) RMS */
3194  int large_residuals = 1, /* init to force a first fit */
3195  niter = 1;
3196  while (large_residuals > 0) {
3197  /* set some typical fit error by default */
3198  cpl_error_code errfit = CPL_ERROR_SINGULAR_MATRIX;
3199 
3200  if (aDLambdas) { /* use our own polynomial fitting with weighting */
3201  /* the lvmq function wants N rows of dimension D=2 *
3202  * instead of the other way around... */
3203  cpl_matrix *xypos = cpl_matrix_transpose_create(aXYPos);
3204 
3205  int npar = 2 + (aParams->xorder + 1) * (aParams->yorder + 1);
3206  cpl_vector *pars = cpl_vector_new(npar);
3207  /* pre-fill all but the zero-order with zero as the first guess value */
3208  cpl_vector_fill(pars, 0.);
3209  /* the polynomial orders go first into the array */
3210  cpl_vector_set(pars, 0, aParams->xorder);
3211  cpl_vector_set(pars, 1, aParams->yorder);
3212  cpl_vector_set(pars, 2, 5000.); /* near lower edge of lambda range */
3213  cpl_array *aflags = cpl_array_new(npar, CPL_TYPE_INT);
3214  /* most are real (free == 1) parameters, except the first two */
3215  cpl_array_set_int(aflags, 0, 0); /* fixed xorder */
3216  cpl_array_set_int(aflags, 1, 0); /* fixed yorder */
3217  cpl_array_fill_window_int(aflags, 2, npar - 2, 1);
3218  int *pflags = cpl_array_get_data_int(aflags);
3219  errfit = cpl_fit_lvmq(xypos, /* sigma_x (unsupported) */NULL,
3220  aLambdas, aDLambdas, pars, pflags,
3221  muse_wave_poly_2d, muse_wave_dpoly_2d,
3222  CPL_FIT_LVMQ_TOLERANCE, CPL_FIT_LVMQ_COUNT,
3223  CPL_FIT_LVMQ_MAXITER, NULL, NULL, NULL);
3224  cpl_array_delete(aflags);
3225  cpl_size k = 2; /* coefficients start at the 3rd vector entry */
3226  unsigned short i;
3227  for (i = 0; i <= aParams->xorder; i++) {
3228  unsigned short j;
3229  for (j = 0; j <= aParams->yorder; j++) {
3230  cpl_size pows[2] = { i, j }; /* trick to access the polynomial */
3231  cpl_polynomial_set_coeff(*aPoly, pows,
3232  cpl_vector_get(pars, k++));
3233  } /* for j */
3234  } /* for i */
3235  cpl_matrix_delete(xypos);
3236  cpl_vector_delete(pars);
3237  } else {
3238  /* use CPL polynomial fitting for everything else */
3239  const cpl_boolean sym = CPL_FALSE;
3240  const cpl_size mindeg2d[] = { 0, 0 },
3241  maxdeg2d[] = { aParams->xorder, aParams->yorder };
3242  errfit = cpl_polynomial_fit(*aPoly, aXYPos, &sym, aLambdas, NULL,
3243  CPL_TRUE, mindeg2d, maxdeg2d);
3244  } /* CPL polynomial fitting */
3245 #if 0
3246  printf("polynomial (orders=%hu/%hu, degree=%"CPL_SIZE_FORMAT"):\n",
3247  aParams->xorder, aParams->yorder, cpl_polynomial_get_degree(*aPoly));
3248  cpl_polynomial_dump(*aPoly, stdout);
3249  fflush(stdout);
3250 #endif
3251 
3252  if (errfit) {
3253  /* the fit failed, complain and abort */
3254  cpl_msg_error(__func__, "The polynomial fit in slice %hu failed: %s",
3255  aSlice, cpl_error_get_message());
3256 
3257 #if 0
3258  /* more fancy plotting of input datapoints *
3259  * (color coded lambda over x/y-position) */
3260  FILE *gp = popen("gnuplot -persist", "w");
3261  if (gp) {
3262  /* plot title with fit details */
3263  fprintf(gp, "set title \"2D polynomial fit residuals (failed fit: "
3264  "\'%s\')\n", cpl_error_get_message());
3265  /* set nice palette */
3266  fprintf(gp, "set palette defined ( 0 \"dark-violet\","
3267  "1 \"dark-blue\", 4 \"green\", 6 \"yellow\", 8 \"orange\","
3268  "9 \"red\", 10 \"dark-red\")\n");
3269  fprintf(gp, "unset key\n");
3270  cpl_matrix *xpos = cpl_matrix_extract_row(aXYPos, 0);
3271  fprintf(gp, "set xrange [%f:%f]\n", cpl_matrix_get_min(xpos),
3272  cpl_matrix_get_max(xpos));
3273  cpl_matrix_delete(xpos);
3274  fprintf(gp, "set cbrange [%f:%f]\n", cpl_vector_get_min(aLambdas),
3275  cpl_vector_get_max(aLambdas));
3276  fprintf(gp, "plot \"-\" w p pal\n");
3277 
3278  printf("# X Y lambda\n");
3279  int n;
3280  for (n = 0; n < cpl_vector_get_size(aLambdas); n++) {
3281  printf("%4d %7.2f %8.3f\n", (int)cpl_matrix_get(aXYPos, 0, n),
3282  cpl_matrix_get(aXYPos, 1, n), cpl_vector_get(aLambdas, n));
3283  fprintf(gp, "%f %f %f\n", cpl_matrix_get(aXYPos, 0, n),
3284  cpl_matrix_get(aXYPos, 1, n), cpl_vector_get(aLambdas, n));
3285  }
3286  fflush(stdout);
3287  fprintf(gp, "EOF\n");
3288  pclose(gp);
3289  }
3290 #endif
3291 
3292  /* make sure we delete the polynomial */
3293  cpl_polynomial_delete(*aPoly);
3294  *aPoly = NULL; /* make sure we can detect the failure */
3295  return CPL_ERROR_ILLEGAL_OUTPUT;
3296  } /* if failed fit */
3297 
3298  int npoints = cpl_vector_get_size(aLambdas);
3299  cpl_vector *res = cpl_vector_new(npoints);
3300  /* the aDLambdas parameter (the errors of the datapoints) do not *
3301  * change the filled vector, just the chi**2 which we don't need */
3302  cpl_vector_fill_polynomial_fit_residual(res, aLambdas, aDLambdas, *aPoly,
3303  aXYPos, NULL);
3304  /* compute the mean-squared error, without any weighting, in any case */
3305  double mse = 0;
3306  /* compute a (weighted) mean-squared error, if we know the error bars */
3307  if (aDLambdas) { /* no errors given, equal weights for all points */
3308  double wsum = 0;
3309  int i;
3310  for (i = 0; i < npoints; i++) {
3311  double weight = 1. / cpl_vector_get(aDLambdas, i);
3312  mse += pow(cpl_vector_get(res, i), 2) * weight;
3313  wsum += weight;
3314  } /* for i */
3315  mse /= wsum;
3316  } else {
3317  mse = cpl_vector_product(res, res) / npoints;
3318  }
3319  double rlimit = rsigma * sqrt(mse); /* limit using possibly weighted RMS */
3320  if (debug) {
3321  printf("Resulting 2D polynomial of slice %hu (%d points, RMS = %f dRMS = "
3322  "%f), %.1f-sigma limit now %f (target RMS = %f):\n", aSlice,
3323  npoints, sqrt(mse), rms < 0 ? 0. : rms - sqrt(mse), rsigma, rlimit,
3324  aParams->targetrms);
3325  if (debug > 1) {
3326  cpl_polynomial_dump(*aPoly, stdout);
3327  }
3328  fflush(stdout);
3329  }
3330 #if 0
3331  /* simple plotting of intermediate residuals *
3332  * (value over arbitrary x-position in vector) */
3333  cpl_plot_vector("set title \"res\"\n", "", "", res);
3334 #endif
3335  if (aParams->rflag) { /* dump debug information into table, if requested */
3336  int nnew = cpl_vector_get_size(res),
3337  nrow = aParams->residuals ? cpl_table_get_nrow(aParams->residuals) : 0;
3338  /* create the residuals table if wanted and not yet existing */
3339  if (!aParams->residuals) {
3340  aParams->residuals = muse_cpltable_new(muse_wavedebug_def, nnew);
3341  cpl_table_set_column_savetype(aParams->residuals, "slice", CPL_TYPE_UCHAR);
3342  } else { /* resize table as needed to fill in the new entries */
3343  cpl_table_set_size(aParams->residuals, nrow + nnew);
3344  }
3345  cpl_table_fill_column_window_int(aParams->residuals, "slice",
3346  nrow, nnew, aSlice);
3347  cpl_table_fill_column_window_int(aParams->residuals, "iteration",
3348  nrow, nnew, niter);
3349  cpl_table_fill_column_window_double(aParams->residuals, "rejlimit",
3350  nrow, nnew, rlimit);
3351  int n;
3352  for (n = 0; n < cpl_vector_get_size(res); n++) {
3353  cpl_table_set_int(aParams->residuals, "x", nrow + n,
3354  (int)cpl_matrix_get(aXYPos, 0, n));
3355  cpl_table_set_float(aParams->residuals, "y", nrow + n,
3356  cpl_matrix_get(aXYPos, 1, n));
3357  cpl_table_set_float(aParams->residuals, "lambda", nrow + n,
3358  cpl_vector_get(aLambdas, n));
3359  cpl_table_set_double(aParams->residuals, "residual", nrow + n,
3360  cpl_vector_get(res, n));
3361  } /* for n (all wavelengths) */
3362  if (debug) {
3363  cpl_msg_debug(__func__, "%"CPL_SIZE_FORMAT" entries in residuals table "
3364  "after iteration %d of slice %hu",
3365  cpl_table_get_nrow(aParams->residuals), niter, aSlice);
3366  }
3367  } /* if debug table */
3368  niter++;
3369 
3370  /* if the fit is already good enough, we don't *
3371  * need to go through point rejection any more */
3372  cpl_boolean isgoodenough = (rms < 0 ? CPL_FALSE : rms - sqrt(mse) < 0.001)
3373  || (sqrt(mse) <= aParams->targetrms);
3374  large_residuals = 0;
3375  int i;
3376  for (i = 0; !isgoodenough && i < cpl_vector_get_size(res); i++) {
3377  /* compare this residual value to the RMS value */
3378  if (fabs(cpl_vector_get(res, i)) < rlimit) {
3379  /* good fit at this point */
3380  continue;
3381  }
3382  /* bad residual, remove element, from residuals vector and the data vectors */
3383 #if 0
3384  cpl_msg_debug(__func__, "residual = %f (position %fx%f, lambda=%f+/-%f)",
3385  cpl_vector_get(res, i),
3386  cpl_matrix_get(aXYPos, 0, i), cpl_matrix_get(aXYPos, 1, i),
3387  cpl_vector_get(aLambdas, i),
3388  aDLambdas ? cpl_vector_get(aDLambdas, i) : 1.);
3389 #endif
3390  if (cpl_vector_get_size(res) == 1) {
3391  cpl_msg_debug(__func__, "trying to remove the last vector/matrix "
3392  "element when checking against fit sigma (slice %hu)",
3393  aSlice);
3394  break;
3395  }
3396  /* remove bad element from the fit structures... */
3398  cpl_matrix_erase_columns(aXYPos, i, 1);
3399  muse_cplvector_erase_element(aLambdas, i);
3400  if (aDLambdas) {
3401  muse_cplvector_erase_element(aDLambdas, i);
3402  }
3403 
3404  large_residuals++;
3405  i--; /* we stay at this position to see what moved here */
3406  } /* for i */
3407 
3408  rms = sqrt(mse);
3409  if (!large_residuals) {
3410  /* no large residuals (any more), so this is the final solution */
3411 
3412  /* save the mean squared error */
3413  if (aMSE) {
3414  *aMSE = mse;
3415  }
3416  } /* if !large_residuals */
3417 
3418  cpl_vector_delete(res);
3419  } /* while large_residuals */
3420 
3421  return CPL_ERROR_NONE;
3422 } /* muse_wave_poly_fit() */
3423 
3424 /*----------------------------------------------------------------------------*/
3434 /*----------------------------------------------------------------------------*/
3435 cpl_table *
3436 muse_wave_table_create(const unsigned short aNSlices, const unsigned short aXOrder,
3437  const unsigned short aYOrder)
3438 {
3439  cpl_table *table = cpl_table_new(aNSlices);
3440  cpl_ensure(table, CPL_ERROR_UNSPECIFIED, NULL);
3441 
3442  /* create column for slice number*/
3443  cpl_table_new_column(table, MUSE_WAVECAL_TABLE_COL_SLICE_NO, CPL_TYPE_INT);
3444  cpl_table_set_column_unit(table, MUSE_WAVECAL_TABLE_COL_SLICE_NO, "No");
3445  cpl_table_set_column_format(table, MUSE_WAVECAL_TABLE_COL_SLICE_NO, "%2d");
3446 
3447  /* create columns for all coefficients, so loop over fit orders */
3448  unsigned short i;
3449  for (i = 0; i <= aXOrder; i++) {
3450  unsigned short j;
3451  for (j = 0; j <= aYOrder; j++) {
3452  /* create column name, start coefficient names at 0 */
3453  char *colname = cpl_sprintf(MUSE_WAVECAL_TABLE_COL_COEFF, i, j);
3454  cpl_table_new_column(table, colname, CPL_TYPE_DOUBLE);
3455  /* fit coeff are in wavelength space */
3456  cpl_table_set_column_unit(table, colname, "Angstrom");
3457  cpl_table_set_column_format(table, colname, "%12.5e");
3458  cpl_free(colname);
3459  }
3460  }
3461  /* create column for mean squared error of fitting parameters */
3462  cpl_table_new_column(table, MUSE_WAVECAL_TABLE_COL_MSE, CPL_TYPE_DOUBLE);
3463  cpl_table_set_column_format(table, MUSE_WAVECAL_TABLE_COL_MSE, "%f");
3464 
3465  return table;
3466 } /* muse_wave_table_create() */
3467 
3468 /*----------------------------------------------------------------------------*/
3482 /*----------------------------------------------------------------------------*/
3483 cpl_error_code
3484 muse_wave_table_add_poly(cpl_table *aTable, cpl_polynomial *aPoly,
3485  double aMSE, unsigned short aXOrder,
3486  unsigned short aYOrder, const unsigned short aRow)
3487 {
3488  cpl_ensure_code(aTable && aPoly, CPL_ERROR_NULL_INPUT);
3489  cpl_ensure_code(cpl_polynomial_get_dimension(aPoly) == 2,
3490  CPL_ERROR_ILLEGAL_INPUT);
3491 
3492  /* row numbers start at 0 but the numbers in the table should start with 1 */
3493  cpl_table_set_int(aTable, MUSE_WAVECAL_TABLE_COL_SLICE_NO, aRow, aRow + 1);
3494  cpl_table_set_double(aTable, MUSE_WAVECAL_TABLE_COL_MSE, aRow, aMSE);
3495 
3496  /* i and j loop over all orders of the polynomial */
3497  unsigned short i;
3498  for (i = 0; i <= aXOrder; i++) {
3499  unsigned short j;
3500  for (j = 0; j <= aYOrder; j++) {
3501  cpl_size pows[2] = { i, j }; /* trick to access the polynomial */
3502 
3503  char *colname = cpl_sprintf(MUSE_WAVECAL_TABLE_COL_COEFF, i, j);
3504  cpl_error_code rc = cpl_table_set_double(aTable, colname, aRow,
3505  cpl_polynomial_get_coeff(aPoly,
3506  pows));
3507  if (rc != CPL_ERROR_NONE) {
3508  cpl_msg_warning(__func__, "Problem writing %f to field %s in "
3509  "wavelength table: %s",
3510  cpl_polynomial_get_coeff(aPoly, pows), colname,
3511  cpl_error_get_message());
3512  cpl_polynomial_dump(aPoly, stdout);
3513  cpl_table_dump(aTable, aRow, 1, stdout);
3514  fflush(stdout);
3515  }
3516  cpl_free(colname);
3517  } /* for j (polynomial orders in y) */
3518  } /* for i (polynomial orders in x) */
3519 
3520  return CPL_ERROR_NONE;
3521 } /* muse_wave_table_add_poly() */
3522 
3523 /*----------------------------------------------------------------------------*/
3538 /*----------------------------------------------------------------------------*/
3539 cpl_error_code
3540 muse_wave_table_get_orders(const cpl_table *aWave, unsigned short *aXOrder,
3541  unsigned short *aYOrder)
3542 {
3543  cpl_ensure_code(aWave && aXOrder && aYOrder, CPL_ERROR_NULL_INPUT);
3544  cpl_array *cols = cpl_table_get_column_names(aWave);
3545 
3546  /* second last entry will contain highest order (last is MSE) */
3547  const char *highcol = cpl_array_get_string(cols, cpl_array_get_size(cols) - 2);
3548  char *colname = cpl_strdup(highcol); /* duplicate it so that we can manipulate it */
3549  cpl_array_delete(cols);
3550 
3551  /* we can directly get the value of the last digit */
3552  *aYOrder = atoi(colname+4);
3553  /* now null out the last digit so that we can get the first one only */
3554  colname[4] = '\0';
3555  *aXOrder = atoi(colname+3);
3556  cpl_free(colname);
3557 
3558  return CPL_ERROR_NONE;
3559 } /* muse_wave_table_get_orders() */
3560 
3561 /*----------------------------------------------------------------------------*/
3582 /*----------------------------------------------------------------------------*/
3583 cpl_polynomial *
3584 muse_wave_table_get_poly_for_slice(const cpl_table *aTable,
3585  const unsigned short aSlice)
3586 {
3587  cpl_ensure(aTable, CPL_ERROR_NULL_INPUT, NULL);
3588  cpl_ensure(aSlice >= 1 && aSlice <= kMuseSlicesPerCCD,
3589  CPL_ERROR_ILLEGAL_INPUT, NULL);
3590  /* search for row containing the requested slice, first to access it *
3591  * in a possibly incomplete table, and second to check its presence! */
3592  int irow, nrow = cpl_table_get_nrow(aTable);
3593  for (irow = 0; irow < nrow; irow++) {
3594  int err;
3595  unsigned short slice = cpl_table_get_int(aTable,
3596  MUSE_WAVECAL_TABLE_COL_SLICE_NO,
3597  irow, &err);
3598  if (slice == aSlice && !err) {
3599  break;
3600  }
3601  } /* for irow */
3602  cpl_ensure(irow < nrow, CPL_ERROR_DATA_NOT_FOUND, NULL);
3603 
3604  cpl_polynomial *pwave = cpl_polynomial_new(2);
3605  char colname[15]; /* "wlc" plus max 2x5 chars for the numbers */
3606  unsigned short wavexorder, waveyorder;
3607  muse_wave_table_get_orders(aTable, &wavexorder, &waveyorder);
3608  unsigned short l;
3609  for (l = 0; l <= wavexorder; l++) {
3610  unsigned short k;
3611  for (k = 0; k <= waveyorder; k++) {
3612  cpl_size pows[2] = { l, k }; /* trick to access the polynomial */
3613  sprintf(colname, MUSE_WAVECAL_TABLE_COL_COEFF, l, k);
3614  int err;
3615  cpl_polynomial_set_coeff(pwave, pows,
3616  cpl_table_get_double(aTable, colname, irow,
3617  &err));
3618  if (err != 0) { /* broken table entry */
3619  cpl_polynomial_delete(pwave);
3620  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_OUTPUT, "Wavelength "
3621  "calibration table broken in slice %hu (row index"
3622  " %d) column %s", aSlice, irow, colname);
3623  return NULL;
3624  } /* if */
3625  } /* for k */
3626  } /* for l */
3627  return pwave;
3628 } /* muse_wave_table_get_poly_for_slice() */
3629 
3630 /*----------------------------------------------------------------------------*/
3653 /*----------------------------------------------------------------------------*/
3654 cpl_image *
3655 muse_wave_map(muse_image *aImage, const cpl_table *aWave,
3656  const cpl_table *aTrace)
3657 {
3658  cpl_ensure(aImage && aWave && aTrace, CPL_ERROR_NULL_INPUT, NULL);
3659  int nx = cpl_image_get_size_x(aImage->data),
3660  ny = cpl_image_get_size_y(aImage->data);
3661  cpl_image *wavemap = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);
3662  cpl_ensure(wavemap, cpl_error_get_code(), NULL);
3663  unsigned char ifu = muse_utils_get_ifu(aImage->header);
3664 
3665  /* get output image buffer as pointer */
3666  float *wdata = cpl_image_get_data_float(wavemap);
3667 
3668  unsigned short wavexorder, waveyorder;
3669  muse_wave_table_get_orders(aWave, &wavexorder, &waveyorder);
3670  cpl_msg_debug(__func__, "Order for trace solution is %d, for wavelength "
3671  "solution %hu/%hu, IFU %hhu", muse_trace_table_get_order(aTrace),
3672  wavexorder, waveyorder, ifu);
3673 
3674  /* loop through all slices */
3675  unsigned short islice;
3676  for (islice = 0; islice < kMuseSlicesPerCCD; islice++) {
3677 #if 0
3678  cpl_msg_debug(__func__, "Starting to process slice %d of IFU %hhu",
3679  (int)islice + 1, ifu);
3680 #endif
3681 
3682  /* fill the wavelength calibration polynomial for this slice */
3683  cpl_polynomial *pwave = muse_wave_table_get_poly_for_slice(aWave, islice + 1);
3684  /* vector for the position within the slice (for evaluation *
3685  * of the wavelength solution in two dimensions */
3686  cpl_vector *pos = cpl_vector_new(2);
3687 
3688  /* get the tracing polynomials for this slice */
3689  cpl_polynomial **ptrace = muse_trace_table_get_polys_for_slice(aTrace,
3690  islice + 1);
3691  if (!ptrace) {
3692  cpl_msg_warning(__func__, "slice %2d of IFU %hhu: tracing polynomials "
3693  "missing!", (int)islice + 1, ifu);
3694  continue;
3695  }
3696 #if 0
3697  printf("polynomials for slice %d:\n", (int)islice + 1);
3698  cpl_polynomial_dump(ptrace[MUSE_TRACE_LEFT], stdout);
3699  cpl_polynomial_dump(ptrace[MUSE_TRACE_RIGHT], stdout);
3700  cpl_polynomial_dump(pwave, stdout);
3701  fflush(stdout);
3702 #endif
3703 
3704  /* within each slice, loop from bottom to top */
3705  int j;
3706  for (j = 1; j <= ny; j++) {
3707  /* determine the slice edges for this vertical *
3708  * position so that we can loop over those pixels */
3709  int ileft = ceil(cpl_polynomial_eval_1d(ptrace[MUSE_TRACE_LEFT],
3710  j, NULL)),
3711  iright = floor(cpl_polynomial_eval_1d(ptrace[MUSE_TRACE_RIGHT],
3712  j, NULL));
3713  /* try to detect faulty polynomials */
3714  if (ileft < 1 || iright > nx || ileft > iright) {
3715  cpl_msg_warning(__func__, "slice %2d of IFU %hhu: faulty polynomial "
3716  "detected at y=%d", (int)islice + 1, ifu, j);
3717  break; /* skip the rest of this slice */
3718  }
3719  cpl_vector_set(pos, 1, j); /* vertical pos. for wavelength evaluation */
3720 
3721  /* now loop over all pixels of this slice horizontally */
3722  int i;
3723  for (i = ileft; i <= iright; i++) {
3724  cpl_vector_set(pos, 0, i); /* horiz. pos. for wavelength evaluation */
3725 
3726  /* compute the wavelength of this pixel */
3727  wdata[(i-1) + (j-1)*nx] = cpl_polynomial_eval(pwave, pos);
3728  } /* for i (horizontal pixels) */
3729  } /* for j (vertical direction) */
3730 
3731  /* we are now done with this slice, clean up */
3732  muse_trace_polys_delete(ptrace);
3733  cpl_polynomial_delete(pwave);
3734  cpl_vector_delete(pos);
3735  } /* for islice */
3736 
3737  return wavemap;
3738 } /* muse_wave_map() */
3739 
3740 /*----------------------------------------------------------------------------*/
3765 /*----------------------------------------------------------------------------*/
3766 cpl_error_code
3767 muse_wave_plot_residuals(cpl_table *aTable, unsigned char aIFU,
3768  unsigned short aSlice, unsigned int aIter,
3769  cpl_boolean aPlotLambda, cpl_vector *aCuts)
3770 {
3771 #if HAVE_POPEN && HAVE_PCLOSE
3772  cpl_ensure_code(aTable, CPL_ERROR_NULL_INPUT);
3773  cpl_error_code rc = muse_cpltable_check(aTable, muse_wavedebug_def);
3774  cpl_ensure_code(rc == CPL_ERROR_NONE, rc);
3775 
3776  FILE *gp = popen("gnuplot", "w");
3777  if (!gp) {
3778  return CPL_ERROR_ASSIGNING_STREAM;
3779  }
3780 
3781  /* select relevant rows in the table */
3782  cpl_table_unselect_all(aTable); /* start clean */
3783 
3784  int n, nrow = cpl_table_get_nrow(aTable),
3785  error = 0;
3786  if (aSlice == 0) {
3787  printf("Selecting data of all slices");
3788  if (aIFU > 0) {
3789  printf(" of IFU %hhu", aIFU);
3790  }
3791  printf(".\n");
3792 
3793  const int *slice = cpl_table_get_data_int_const(aTable, "slice"),
3794  *iter = cpl_table_get_data_int_const(aTable, "iteration");
3795  if (!aIter) { /* last iteration */
3796  fprintf(stderr, "Selecting data of last iteration of all slices\n");
3797  /* the last row of each slice number is the one with the last iteration */
3798  int sliceno = slice[nrow - 1],
3799  iterlast = iter[nrow - 1];
3800  for (n = nrow - 2; n >= 0; n--) {
3801  if (slice[n] == sliceno && iter[n] != iterlast) {
3802  cpl_table_select_row(aTable, n);
3803  }
3804  if (slice[n] != sliceno) { /* previous slice, reset comparison */
3805  sliceno = slice[n];
3806  iterlast = iter[n];
3807  }
3808  } /* for n (table rows) */
3809  cpl_table_erase_selected(aTable);
3810  /* plot title with some details */
3811  fprintf(gp, "set title \"");
3812  if (aIFU > 0) {
3813  fprintf(gp, "IFU %hhu, ", aIFU);
3814  }
3815  fprintf(gp, "slices %d..%d, iterations %d..%d: 2D polynomial fit "
3816  "residuals (limits %f..%f)\n",
3817  (int)cpl_table_get_column_min(aTable, "slice"),
3818  (int)cpl_table_get_column_max(aTable, "slice"),
3819  (int)cpl_table_get_column_min(aTable, "iteration"),
3820  (int)cpl_table_get_column_max(aTable, "iteration"),
3821  cpl_table_get_column_min(aTable, "rejlimit"),
3822  cpl_table_get_column_max(aTable, "rejlimit"));
3823  } else {
3824  printf("Selecting data of iteration %d.\n", aIter);
3825  for (n = 0; n < nrow; n++) {
3826  if (iter[n] != (int)aIter) {
3827  cpl_table_select_row(aTable, n);
3828  }
3829  } /* for n (table rows) */
3830  cpl_table_erase_selected(aTable);
3831  /* plot title with some details */
3832  fprintf(gp, "set title \"");
3833  if (aIFU > 0) {
3834  fprintf(gp, "IFU %hhu, ", aIFU);
3835  }
3836  fprintf(gp, "slices %d..%d, iteration %d: 2D polynomial fit residuals "
3837  "(limits %f..%f)\n",
3838  (int)cpl_table_get_column_min(aTable, "slice"),
3839  (int)cpl_table_get_column_max(aTable, "slice"), aIter,
3840  cpl_table_get_column_min(aTable, "rejlimit"),
3841  cpl_table_get_column_max(aTable, "rejlimit"));
3842  }
3843  } else {
3844  printf("Selecting data of ");
3845  if (aIFU > 0) {
3846  printf("IFU %hhu ", aIFU);
3847  }
3848  printf("slice %hu.\n", aSlice);
3849  const int *slice = cpl_table_get_data_int_const(aTable, "slice");
3850  for (n = 0; n < nrow; n++) {
3851  if (slice[n] != aSlice) {
3852  cpl_table_select_row(aTable, n);
3853  }
3854  } /* for n (table rows) */
3855  cpl_table_erase_selected(aTable);
3856  nrow = cpl_table_get_nrow(aTable);
3857  cpl_table_unselect_all(aTable);
3858 
3859  const int *iter = cpl_table_get_data_int_const(aTable, "iteration");
3860  if (!aIter) { /* last iteration */
3861  /* table is sorted, so last iteration is that of the last row */
3862  aIter = iter[nrow - 1];
3863  }
3864  printf("Selecting data of iteration %d.\n", aIter);
3865  for (n = 0; n < nrow; n++) {
3866  if (iter[n] != (int)aIter) {
3867  cpl_table_select_row(aTable, n);
3868  }
3869  } /* for n (table rows) */
3870  cpl_table_erase_selected(aTable);
3871 
3872  /* plot title with some details */
3873  fprintf(gp, "set title \"");
3874  if (aIFU > 0) {
3875  fprintf(gp, "IFU %hhu, ", aIFU);
3876  }
3877  fprintf(gp, "slice %hu, iteration %d: 2D polynomial fit residuals "
3878  "(limit=%f)\n", aSlice, aIter,
3879  cpl_table_get_double(aTable, "rejlimit", 0, &error));
3880  } /* single slice */
3881 
3882  /* data access */
3883  nrow = cpl_table_get_nrow(aTable);
3884  cpl_ensure_code(nrow > 0, CPL_ERROR_DATA_NOT_FOUND);
3885  printf("Plotting %d points.\n", nrow);
3886  const int *x = cpl_table_get_data_int_const(aTable, "x");
3887  const float *y = cpl_table_get_data_float_const(aTable, "y"),
3888  *lambda = cpl_table_get_data_float_const(aTable, "lambda");
3889  const double *r = cpl_table_get_data_double_const(aTable, "residual");
3890  /* *rlimit = cpl_table_get_data_double_const(aTable, "rejlimit"); */
3891 
3892  /* determine plotting limits */
3893  int xmin = cpl_table_get_column_min(aTable, "x") - 2,
3894  xmax = cpl_table_get_column_max(aTable, "x") + 2;
3895  float ymin = cpl_table_get_column_min(aTable, "y") - 2,
3896  ymax = cpl_table_get_column_max(aTable, "y") + 2,
3897  lmin = cpl_table_get_column_min(aTable, "lambda") - 2,
3898  lmax = cpl_table_get_column_max(aTable, "lambda") + 2;
3899  double rmin = cpl_table_get_column_min(aTable, "residual"),
3900  rmax = cpl_table_get_column_max(aTable, "residual");
3901  if (aCuts && cpl_vector_get_size(aCuts) == 2) {
3902  rmin = cpl_vector_get(aCuts, 0);
3903  rmax = cpl_vector_get(aCuts, 1);
3904  }
3905 
3906  /* set nice palette */
3907  fprintf(gp, "set palette defined ( 0 \"dark-violet\","
3908  "1 \"dark-blue\", 4 \"green\", 6 \"yellow\", 8 \"orange\","
3909  "9 \"red\", 10 \"dark-red\")\n");
3910  fprintf(gp, "unset key\n");
3911  printf("Setting plotting limits: [%d:%d][%.2f:%.2f][%.4f:%.4f]\n",
3912  xmin, xmax, aPlotLambda ? lmin : ymin, aPlotLambda ? lmax : ymax,
3913  rmin, rmax);
3914  fprintf(gp, "set xrange [%d:%d]\n", xmin, xmax);
3915  if (aPlotLambda) {
3916  fprintf(gp, "set yrange [%f:%f]\n", lmin, lmax);
3917  } else {
3918  fprintf(gp, "set yrange [%f:%f]\n", ymin, ymax);
3919  }
3920  fprintf(gp, "set cbrange [%f:%f]\n", rmin, rmax);
3921  fprintf(gp, "set view map\n");
3922  fprintf(gp, "splot \"-\" w p pal\n");
3923  for (n = 0; n < nrow; n++) {
3924  if (aPlotLambda) {
3925  fprintf(gp, "%d %f %e\n", x[n], lambda[n], r[n]);
3926  } else {
3927  fprintf(gp, "%d %f %e\n", x[n], y[n], r[n]);
3928  }
3929  }
3930  fprintf(gp, "EOF\n");
3931  fflush(gp);
3932  /* request keypress, so that working with the mouse keeps *
3933  * working and gnuplot has enough time to actually draw all *
3934  * the stuff before the files get removed */
3935  printf("Press ENTER to end program and close plot\n");
3936  getchar();
3937  pclose(gp);
3938  return CPL_ERROR_NONE;
3939 #else /* no HAVE_POPEN && HAVE_PCLOSE */
3940  return CPL_ERROR_UNSUPPORTED_MODE;
3941 #endif /* HAVE_POPEN && HAVE_PCLOSE */
3942 } /* muse_wave_plot_residuals() */
3943 
3944 /*----------------------------------------------------------------------------*/
3971 /*----------------------------------------------------------------------------*/
3972 cpl_error_code
3973 muse_wave_plot_column(cpl_table *aCTable, cpl_table *aRTable,
3974  unsigned char aIFU, unsigned short aSlice,
3975  unsigned int aColumn, unsigned int aIter,
3976  cpl_boolean aPlotRes)
3977 {
3978 #if HAVE_POPEN && HAVE_PCLOSE
3979  cpl_ensure_code(aCTable && aRTable, CPL_ERROR_NULL_INPUT);
3980  cpl_error_code rc = muse_cpltable_check(aRTable, muse_wavedebug_def);
3981  cpl_ensure_code(rc == CPL_ERROR_NONE, rc);
3982  /* WAVECAL_TABLE doesn't has a _def structure to check, so test orders */
3983  unsigned short xorder, yorder;
3984  muse_wave_table_get_orders(aCTable, &xorder, &yorder);
3985  cpl_ensure_code(xorder > 0 && yorder > 0, CPL_ERROR_ILLEGAL_INPUT);
3986  cpl_ensure_code(aSlice >= 1 && aSlice <= kMuseSlicesPerCCD,
3987  CPL_ERROR_ACCESS_OUT_OF_RANGE);
3988 
3989  FILE *gp = popen("gnuplot", "w");
3990  if (!gp) {
3991  return CPL_ERROR_ASSIGNING_STREAM;
3992  }
3993 
3994  /* select relevant rows in the table */
3995  cpl_table_unselect_all(aRTable); /* start clean */
3996 
3997  printf("Selecting data of ");
3998  if (aIFU > 0) {
3999  printf("IFU %hhu ", aIFU);
4000  }
4001  printf("slice %hu.\n", aSlice);
4002  const int *slice = cpl_table_get_data_int_const(aRTable, "slice");
4003  int n, nrow = cpl_table_get_nrow(aRTable);
4004  for (n = 0; n < nrow; n++) {
4005  if (slice[n] != aSlice) {
4006  cpl_table_select_row(aRTable, n);
4007  }
4008  } /* for n (table rows) */
4009  cpl_table_erase_selected(aRTable);
4010  nrow = cpl_table_get_nrow(aRTable);
4011  cpl_ensure_code(nrow > 0, CPL_ERROR_DATA_NOT_FOUND);
4012  cpl_table_unselect_all(aRTable);
4013 
4014  const int *iter = cpl_table_get_data_int_const(aRTable, "iteration");
4015  if (!aIter) { /* last iteration */
4016  /* table is sorted, so last iteration is that of the last row */
4017  aIter = iter[nrow - 1];
4018  }
4019  printf("Selecting data of iteration %d.\n", aIter);
4020  for (n = 0; n < nrow; n++) {
4021  if (iter[n] != (int)aIter) {
4022  cpl_table_select_row(aRTable, n);
4023  }
4024  } /* for n (table rows) */
4025  cpl_table_erase_selected(aRTable);
4026  nrow = cpl_table_get_nrow(aRTable);
4027  cpl_ensure_code(nrow > 0, CPL_ERROR_DATA_NOT_FOUND);
4028  cpl_table_unselect_all(aRTable);
4029 
4030  unsigned int col1 = cpl_table_get_column_min(aRTable, "x"),
4031  col2 = cpl_table_get_column_max(aRTable, "x");
4032  if (aColumn > 0) {
4033  col1 = col2 = aColumn;
4034  } else if (aColumn > (unsigned)kMuseOutputXRight) {
4035  /* approximate central column of the slice */
4036  col1 = col2 = (col1 + col2) / 2;
4037  }
4038  printf("Plotting data of columns %u..%u.\n", col1, col2);
4039 
4040  /* determine plotting limits */
4041  float ymin = cpl_table_get_column_min(aRTable, "y") - 10,
4042  ymax = cpl_table_get_column_max(aRTable, "y") + 10,
4043  lmin = cpl_table_get_column_min(aRTable, "lambda") - 10,
4044  lmax = cpl_table_get_column_max(aRTable, "lambda") + 10;
4045  double rmin = cpl_table_get_column_min(aRTable, "residual") * 1.03,
4046  rmax = cpl_table_get_column_max(aRTable, "residual") * 1.03;
4047  /* plot title with some details */
4048  fprintf(gp, "set title \"");
4049  if (aIFU > 0) {
4050  fprintf(gp, "IFU %hhu, ", aIFU);
4051  }
4052  fprintf(gp, "slice %hu, iteration %d, column %u..%u: polynomial and ", aSlice,
4053  aIter, col1, col2);
4054  printf("Setting plotting limits: ");
4055  if (aPlotRes) {
4056  fprintf(gp, "residuals (limit=%f)\"\n",
4057  cpl_table_get_double(aRTable, "rejlimit", 0, NULL));
4058  printf("[%.2f:%.2f][%.4f:%.4f]\n", lmin, lmax, rmin, rmax);
4059  fprintf(gp, "set xrange [%f:%f]\n", lmin, lmax);
4060  fprintf(gp, "set yrange [%f:%f]\n", rmin, rmax);
4061  fprintf(gp, "set xlabel \"Wavelength [Angstrom]\"\n");
4062  fprintf(gp, "set ylabel \"Residuals [Angstrom]\"\n");
4063  } else {
4064  fprintf(gp, "arc line positions\"\n");
4065  printf("[%.2f:%.2f][%.2f:%.2f]\n", ymin, ymax, lmin, lmax);
4066  fprintf(gp, "set xrange [%g:%g]\n", ymin, ymax);
4067  fprintf(gp, "set yrange [%f:%f]\n", lmin, lmax);
4068  fprintf(gp, "set xlabel \"y-position [pix]\"\n");
4069  fprintf(gp, "set ylabel \"Wavelength [Angstrom]\"\n");
4070  }
4071  fprintf(gp, "set key outside below\n");
4072  fprintf(gp, "set samples 1000\n"); /* more samples so that one can zoom in */
4073 
4074  /* create gnuplot polynomial from table coefficients */
4075  fprintf(gp, "p(x,y) = 0 ");
4076  if (!aPlotRes) { /* create full polynomial */
4077  unsigned short i;
4078  for (i = 0; i <= xorder; i++) {
4079  unsigned short j;
4080  for (j = 0; j <= yorder; j++) {
4081  char *coeff = cpl_sprintf(MUSE_WAVECAL_TABLE_COL_COEFF, i, j);
4082  double cvalue = cpl_table_get(aCTable, coeff, aSlice - 1, NULL);
4083  cpl_free(coeff);
4084  fprintf(gp, " + (%g) * x**(%hu) * y**(%hu)", cvalue, i, j);
4085  } /* for j (y orders) */
4086  } /* for i (x orders) */
4087  }
4088  fprintf(gp, "\n");
4089 
4090  const int *x = cpl_table_get_data_int_const(aRTable, "x");
4091  const float *y = cpl_table_get_data_float_const(aRTable, "y"),
4092  *lambda = cpl_table_get_data_float_const(aRTable, "lambda");
4093  const double *r = cpl_table_get_data_double_const(aRTable, "residual");
4094 
4095  /* distribute columns over 256 color values */
4096  double dcol = (col2 - col1) / 255.;
4097  if (dcol == 0.) { /* take care not to produce NANs below when dividing */
4098  dcol = 1.;
4099  }
4100  /* construct the plot command as a single long line */
4101  fprintf(gp, "plot ");
4102  if (aPlotRes) {
4103  fprintf(gp, "0 t \"\", "); /* plot line to represent solution */
4104  }
4105  unsigned int ncol, npoints = 0;
4106  for (ncol = col1; ncol <= col2; ncol++) {
4107  /* plot polynomial and values for the specified CCD column */
4108  int red = (ncol - col1) / dcol, /* red */
4109  grn = (col2 - ncol) / dcol, /* green */
4110  blu = 0; /* blue */
4111  if (aPlotRes) {
4112  fprintf(gp, "\"-\" u 2:3 t \"col %u\" w p ps 0.8 lt rgb \"#%02x%02x%02x\"",
4113  ncol, red, grn, blu);
4114  } else {
4115  /* create data values from polynomial and residuals for given CCD column */
4116  fprintf(gp, "p(%u, x) t \"\" w l lw 0.7 lt rgb \"#%02x%02x%02x\", "
4117  "\"-\" u 1:(p(%u,$1)+$3) t \"col %u\" w p ps 0.8 lt rgb \"#%02x%02x%02x\"",
4118  ncol, red, grn, blu, ncol, ncol, red, grn, blu);
4119  }
4120  if (ncol == col2) {
4121  fprintf(gp, "\n"); /* end the plot command */
4122  } else {
4123  fprintf(gp, ", "); /* plot command of next column to come */
4124  }
4125  } /* for ncol (relevant columns) */
4126  for (ncol = col1; ncol <= col2; ncol++) {
4127  for (n = 0; n < nrow; n++) {
4128  if (x[n] == (int)ncol) {
4129  fprintf(gp, "%f %f %g\n", y[n], lambda[n], r[n]);
4130  npoints++;
4131  }
4132  }
4133  fprintf(gp, "EOF\n");
4134  } /* for ncol (relevant columns) */
4135  printf("Plotted %u points.\n", npoints);
4136  fflush(gp);
4137  /* request keypress, so that working with the mouse keeps *
4138  * working and gnuplot has enough time to actually draw all *
4139  * the stuff before the files get removed */
4140  printf("Press ENTER to end program and close plot\n");
4141  getchar();
4142  pclose(gp);
4143  return CPL_ERROR_NONE;
4144 #else /* no HAVE_POPEN && HAVE_PCLOSE */
4145  return CPL_ERROR_UNSUPPORTED_MODE;
4146 #endif /* HAVE_POPEN && HAVE_PCLOSE */
4147 } /* muse_wave_plot_column() */
4148 
cpl_table * muse_wave_lines_search(muse_image *aColumnImage, double aSigma, const unsigned short aSlice, const unsigned char aIFU)
Search and store emission lines in a column of an arc frame.
cpl_table * muse_wave_calib_lampwise(muse_imagelist *aImages, cpl_table *aTrace, cpl_table *aLinelist, muse_wave_params *aParams)
Find wavelength calibration solution using a list of arc images with different lamps.
cpl_table * muse_wave_calib(muse_image *aImage, cpl_table *aTrace, cpl_table *aLinelist, muse_wave_params *aParams)
Find wavelength calibration solution on an arc frame.
cpl_polynomial ** muse_trace_table_get_polys_for_slice(const cpl_table *aTable, const unsigned short aSlice)
construct polynomial from the trace table entry for the given slice
cpl_error_code muse_wave_table_get_orders(const cpl_table *aWave, unsigned short *aXOrder, unsigned short *aYOrder)
Determine the x- and y-order of the polynomial stored in a wavelength calibration table...
muse_wave_params * muse_wave_params_new(cpl_propertylist *aHeader)
Allocate a wavelength parameters structure and fill it with defaults.
Structure definition for a collection of muse_images.
int muse_trace_table_get_order(const cpl_table *aTable)
determine order of tracing polynomial from table
cpl_error_code muse_wave_plot_residuals(cpl_table *aTable, unsigned char aIFU, unsigned short aSlice, unsigned int aIter, cpl_boolean aPlotLambda, cpl_vector *aCuts)
Fancy plotting of wavelength calibration residuals (color coded over x/y-position) using gnuplot...
void muse_image_delete(muse_image *aImage)
Deallocate memory associated to a muse_image object.
Definition: muse_image.c:85
muse_wave_weighting_type fitweighting
cpl_polynomial * muse_wave_table_get_poly_for_slice(const cpl_table *aTable, const unsigned short aSlice)
Construct polynomial from the wavelength calibration table entry for the given slice.
const char * muse_pfits_get_insmode(const cpl_propertylist *aHeaders)
find out the observation mode
Definition: muse_pfits.c:1383
cpl_vector * muse_wave_lines_get_for_lamp(cpl_table *aTable, const char *aLamp, int aGoodnessLimit, double aFluxLimit)
Load wavelengths for a given lamp from a linelist table into a vector.
cpl_error_code muse_wave_lines_identify(cpl_table *aLines, cpl_vector *aLambdas, const muse_wave_params *aParams)
Identify the wavelength of arc detected lines using pattern matching.
void muse_wave_params_delete(muse_wave_params *aParams)
Deallocate memory associated to a wavelength parameters structure.
unsigned char muse_utils_get_ifu(const cpl_propertylist *aHeaders)
Find out the IFU/channel from which this header originated.
Definition: muse_utils.c:98
cpl_image * data
the data extension
Definition: muse_image.h:46
muse_ins_mode mode
cpl_boolean rflag
cpl_error_code muse_wave_poly_fit(cpl_matrix *aXYPos, cpl_vector *aLambdas, cpl_vector *aDLambdas, cpl_polynomial **aPoly, double *aMSE, muse_wave_params *aParams, const unsigned short aSlice)
Compute the wavelength solution from the sample positions and the respective wavelengths.
cpl_table * muse_wave_table_create(const unsigned short aNSlices, const unsigned short aXOrder, const unsigned short aYOrder)
Create the table to save te wave wavelength calibration coefficients.
muse_image * muse_combine_median_create(muse_imagelist *aImages)
Median combine a list of input images.
Definition: muse_combine.c:316
cpl_image * stat
the statistics extension
Definition: muse_image.h:64
void muse_imagelist_delete(muse_imagelist *aList)
Free the memory of the MUSE image list.
cpl_vector * muse_wave_lines_get(cpl_table *aTable, int aGoodnessLimit, double aFluxLimit)
Load usable wavelengths from a linelist table into a vector.
cpl_table * residuals
const char * muse_pfits_get_bunit(const cpl_propertylist *aHeaders)
find out the unit string
Definition: muse_pfits.c:223
cpl_boolean muse_wave_lines_check(muse_table *aTable)
Check that a LINE_CATALOG has the expected format.
Structure definition of MUSE three extension FITS file.
Definition: muse_image.h:40
int muse_pfits_get_lampnum(const cpl_propertylist *aHeaders)
query the number of lamps installed
Definition: muse_pfits.c:1483
cpl_table * muse_wave_line_handle_multiplet(muse_image *aImage, cpl_table *aLinelist, unsigned int aIdx, cpl_polynomial *aPoly, cpl_polynomial **aTrace, const muse_wave_params *aParams, const unsigned short aSlice, int aDebug)
Handle fitting of all multiplets across the columns a given slice.
cpl_propertylist * header
the FITS header
Definition: muse_image.h:72
cpl_error_code muse_cpltable_check(const cpl_table *aTable, const muse_cpltable_def *aDef)
Check whether the table contains the fields of the definition.
unsigned int muse_imagelist_get_size(muse_imagelist *aList)
Return the number of stored images.
void muse_trace_polys_delete(cpl_polynomial *aPolys[])
Delete the multi-polynomial array created in relation to tracing.
cpl_image * dq
the data quality extension
Definition: muse_image.h:56
cpl_table * muse_cpltable_new(const muse_cpltable_def *aDef, cpl_size aLength)
Create an empty table according to the specified definition.
const char * muse_wave_lines_get_lampname(cpl_table *aTable, const int aIdx)
Associate the ion listed in a linelist table row to a lamp name.
cpl_boolean muse_wave_lines_covered_by_data(double aLambda, muse_ins_mode aMode)
Check, if a given wavelength is covered by a given instrument mode.
muse_image * muse_imagelist_get(muse_imagelist *aList, unsigned int aIdx)
Get the muse_image of given list index.
cpl_error_code muse_cplvector_erase_element(cpl_vector *aVector, int aElement)
delete the given element from the input vector
Structure containing wavelength calibration parameters.
cpl_polynomial * muse_utils_iterate_fit_polynomial(cpl_matrix *aPos, cpl_vector *aVal, cpl_vector *aErr, cpl_table *aExtra, const unsigned int aOrder, const double aRSigma, double *aMSE, double *aChiSq)
Iterate a polynomial fit.
Definition: muse_utils.c:2234
unsigned short xorder
cpl_table * table
The table.
Definition: muse_table.h:49
cpl_error_code muse_wave_table_add_poly(cpl_table *aTable, cpl_polynomial *aPoly, double aMSE, unsigned short aXOrder, unsigned short aYOrder, const unsigned short aRow)
Save the given polynomials to the wavelength calibration table.
cpl_image * muse_wave_map(muse_image *aImage, const cpl_table *aWave, const cpl_table *aTrace)
Write out a wavelength map for visual checks.
const muse_cpltable_def muse_line_catalog_def[]
Structure to store a table together with a property list.
Definition: muse_table.h:43
const muse_cpltable_def muse_wavedebug_def[]
MUSE wavelength calibration residuals table definition.
cpl_error_code muse_utils_fit_multigauss_1d(const cpl_vector *aX, const cpl_bivector *aY, cpl_vector *aCenter, double *aSigma, cpl_vector *aFlux, cpl_vector *aPoly, double *aMSE, double *aRedChisq, cpl_matrix **aCovariance)
Carry out a multi-Gaussian fit of data in a vector.
Definition: muse_utils.c:1558
char * muse_utils_header_get_lamp_names(cpl_propertylist *aHeader, char aSep)
Concatenate names of all active calibration lamps.
Definition: muse_utils.c:989
cpl_propertylist * header
the header
Definition: muse_table.h:56
cpl_array * muse_utils_header_get_lamp_numbers(cpl_propertylist *aHeader)
List numbers of all active calibration lamps.
Definition: muse_utils.c:1056
cpl_error_code muse_wave_plot_column(cpl_table *aCTable, cpl_table *aRTable, unsigned char aIFU, unsigned short aSlice, unsigned int aColumn, unsigned int aIter, cpl_boolean aPlotRes)
Plot wavelength calibration polynomial and data or residuals using gnuplot.
cpl_error_code muse_image_save(muse_image *aImage, const char *aFilename)
Save the three image extensions and the FITS headers of a MUSE image to a file.
Definition: muse_image.c:405
cpl_error_code muse_wave_line_fit_iterate(cpl_table *aFitTable, double aLambda, const muse_wave_params *aParams)
Use a low-order polynomial to find and discard bad values for line centroid fits of single arc line a...
muse_imagelist * muse_imagelist_new(void)
Create a new (empty) MUSE image list.
cpl_error_code muse_wave_line_fit_single(muse_image *aImage, int aX, double aY, int aHalfWidth, double aSigma, cpl_table *aFitTable, int aRowsNeeded)
Fit a Gaussian to a single emission line in an arc frame and do simple error handling.
unsigned short yorder
cpl_size muse_cplvector_count_unique(const cpl_vector *aVector)
Count the number of unique entries in a given vector.
Definition of a cpl table structure.
muse_image * muse_image_new(void)
Allocate memory for a new muse_image object.
Definition: muse_image.c:66
cpl_error_code muse_wave_line_fit_multiple(muse_image *aImage, int aX, cpl_bivector *aPeaks, cpl_vector *aLambdas, int aHalfWidth, double aSigma, cpl_table *aFitTable, int aRowsNeeded)
Fit a multi-Gaussian to a multiplet of arc emission lines and do simple error handling.
cpl_error_code muse_imagelist_set(muse_imagelist *aList, muse_image *aImage, unsigned int aIdx)
Set the muse_image of given list index.
const muse_cpltable_def muse_wavelines_def[]
MUSE wavelength calibration arc line fit properties table definition.
cpl_table * muse_wave_line_handle_singlet(muse_image *aImage, cpl_table *aLinelist, unsigned int aIdx, cpl_polynomial *aPoly, cpl_polynomial **aTrace, const muse_wave_params *aParams, const unsigned short aSlice, int aDebug)
Handle fitting of all single lines across the columns a given slice.
muse_ins_mode muse_pfits_get_mode(const cpl_propertylist *aHeaders)
find out the observation mode
Definition: muse_pfits.c:1352