MUSE Pipeline Reference Manual  2.5.2
muse_basicproc.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-2018 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 #include <stdio.h>
30 #include <float.h>
31 #include <math.h>
32 #include <string.h>
33 #include <cpl.h>
34 
35 #include "muse_basicproc.h"
36 
37 #include "muse_combine.h"
38 #include "muse_pfits.h"
39 #include "muse_quadrants.h"
40 #include "muse_quality.h"
41 #include "muse_utils.h"
42 #include "muse_data_format_z.h"
43 
44 /*----------------------------------------------------------------------------*
45  * Debugging Macros *
46  * Set these to 1 or higher for (lots of) debugging output *
47  *----------------------------------------------------------------------------*/
48 #define GENERATE_TEST_IMAGES 0 /* generate FITS file(s) to be used for testing */
49 
50 /*---------------------------------------------------------------------------*/
57 /*---------------------------------------------------------------------------*/
58 
61 /*---------------------------------------------------------------------------*/
83 /*---------------------------------------------------------------------------*/
85 muse_basicproc_params_new(cpl_parameterlist *aParameters, const char *aPrefix)
86 {
87  muse_basicproc_params *bpars = cpl_calloc(1, sizeof(muse_basicproc_params));
88  cpl_parameter *param;
89  param = muse_cplparamerterlist_find_prefix(aParameters, aPrefix, "overscan");
90  bpars->overscan = cpl_strdup(cpl_parameter_get_string(param));
91  param = muse_cplparamerterlist_find_prefix(aParameters, aPrefix, "ovscreject");
92  bpars->rejection = cpl_strdup(cpl_parameter_get_string(param));
93  param = muse_cplparamerterlist_find_prefix(aParameters, aPrefix, "ovscsigma");
94  cpl_errorstate state = cpl_errorstate_get();
95  bpars->ovscsigma = cpl_parameter_get_double(param);
96  if (!cpl_errorstate_is_equal(state)) { /* try again as int, may be misidentified */
97  cpl_errorstate_set(state);
98  bpars->ovscsigma = cpl_parameter_get_int(param);
99  }
100  param = muse_cplparamerterlist_find_prefix(aParameters, aPrefix, "ovscignore");
101  bpars->ovscignore = cpl_parameter_get_int(param);
102 
103  if (strstr(aPrefix, "muse_scibasic")) {
104  param = muse_cplparamerterlist_find_prefix(aParameters, aPrefix, "cr");
105  bpars->crmethod = cpl_strdup(cpl_parameter_get_string(param));
106  param = muse_cplparamerterlist_find_prefix(aParameters, aPrefix, "xbox");
107  bpars->dcrxbox = cpl_parameter_get_int(param);
108  param = muse_cplparamerterlist_find_prefix(aParameters, aPrefix, "ybox");
109  bpars->dcrybox = cpl_parameter_get_int(param);
110  param = muse_cplparamerterlist_find_prefix(aParameters, aPrefix, "passes");
111  bpars->dcrpasses = cpl_parameter_get_int(param);
112  param = muse_cplparamerterlist_find_prefix(aParameters, aPrefix, "thres");
113  state = cpl_errorstate_get();
114  bpars->dcrthres = cpl_parameter_get_double(param);
115  if (!cpl_errorstate_is_equal(state)) { /* try again as int */
116  cpl_errorstate_set(state);
117  bpars->dcrthres = cpl_parameter_get_int(param);
118  }
119  } /* if scibasic prefix */
120 
121  /* components keepflat and flatimage are automatically CPL_FALSE and NULL */
122  return bpars;
123 } /* muse_basicproc_params_new() */
124 
125 /*---------------------------------------------------------------------------*/
141 /*---------------------------------------------------------------------------*/
143 muse_basicproc_params_new_from_propertylist(const cpl_propertylist *aHeader)
144 {
145  cpl_ensure(aHeader, CPL_ERROR_NULL_INPUT, NULL);
146 
147  /* create a parameter list from the input header, so *
148  * that we can give it to muse_basicproc_params_new() */
149  cpl_parameterlist *parlist = muse_cplparameterlist_from_propertylist(aHeader, 1);
150  cpl_ensure(parlist, CPL_ERROR_ILLEGAL_INPUT, NULL);
151  const char *recipe = cpl_propertylist_get_string(aHeader, "ESO PRO REC1 ID");
152  char *prefix = cpl_sprintf("muse.%s", recipe);
153  muse_basicproc_params *bpars = muse_basicproc_params_new(parlist, prefix);
154  cpl_parameterlist_delete(parlist);
155  cpl_free(prefix);
156  return bpars;
157 } /* muse_basicproc_params_new_from_propertylist() */
158 
159 /*---------------------------------------------------------------------------*/
167 /*---------------------------------------------------------------------------*/
168 void
170 {
171  if (!aBPars) {
172  return;
173  }
174  cpl_free(aBPars->overscan);
175  cpl_free(aBPars->rejection);
176  cpl_free(aBPars->crmethod);
177  muse_image_delete(aBPars->flatimage);
178  aBPars->flatimage = NULL;
179  cpl_free(aBPars);
180 }
181 
182 /*---------------------------------------------------------------------------*/
201 /*---------------------------------------------------------------------------*/
202 static cpl_error_code
203 muse_basicproc_verify_setup(const muse_image *aImage, const muse_image *aRef)
204 {
205  cpl_ensure_code(aImage && aRef, CPL_ERROR_NULL_INPUT);
206  cpl_ensure_code(aImage->header && aRef->header, CPL_ERROR_NULL_INPUT);
207  /* shortcuts to the headers */
208  cpl_propertylist *him = aImage->header,
209  *href = aRef->header;
210  /* reference image need to have a processed category (PRO.CATG) */
211  const char *fn1 = cpl_propertylist_get_string(him, MUSE_HDR_TMP_FN),
212  *fn2 = cpl_propertylist_get_string(href, MUSE_HDR_TMP_FN),
213  *catg = muse_pfits_get_pro_catg(href);
214  if (!catg) {
215  cpl_msg_error(__func__, "\"%s\" does not contain a category (ESO.PRO.CATG)!",
216  fn2);
217  return CPL_ERROR_ILLEGAL_INPUT;
218  }
219 
220  cpl_boolean ignoreread = getenv("MUSE_DEBUG_IGNORE_READOUT")
221  && atoi(getenv("MUSE_DEBUG_IGNORE_READOUT")) > 0,
222  ignoremode = getenv("MUSE_DEBUG_IGNORE_INSMODE")
223  && atoi(getenv("MUSE_DEBUG_IGNORE_INSMODE")) > 0;
224 
225  muse_ins_mode mode1 = muse_pfits_get_mode(him),
226  mode2 = muse_pfits_get_mode(href);
227  const char *modestr1 = muse_pfits_get_insmode(him),
228  *modestr2 = muse_pfits_get_insmode(href),
229  *rawtag = cpl_propertylist_get_string(him, MUSE_HDR_TMP_INTAG);
230  int binx1 = muse_pfits_get_binx(him),
231  biny1 = muse_pfits_get_biny(him),
232  readid1 = muse_pfits_get_read_id(him),
233  binx2 = muse_pfits_get_binx(href),
234  biny2 = muse_pfits_get_biny(href),
235  readid2 = muse_pfits_get_read_id(href);
236  const char *readname1 = muse_pfits_get_read_name(him),
237  *readname2 = muse_pfits_get_read_name(href),
238  *chipname1 = muse_pfits_get_chip_name(him),
239  *chipid1 = muse_pfits_get_chip_id(him),
240  *chipname2 = muse_pfits_get_chip_name(href),
241  *chipid2 = muse_pfits_get_chip_id(href);
242  cpl_boolean chipinfo = chipname1 && chipid1
243  && chipname2 && chipid2;
244  if (!chipinfo) {
245  cpl_msg_warning(__func__, "CHIP information is missing (ESO.DET.CHIP."
246  "{NAME,ID}) from \"%s\" (%s, %s) or \"%s\" (%s, %s)",
247  fn1, chipname1, chipid1, fn2, chipname2, chipid2);
248  }
249  /* Everything should fail for non-matching binning. */
250  if (binx1 != binx2 || biny1 != biny2) {
251  cpl_msg_error(__func__, "Binning of \"%s\" (%dx%d) and \"%s\" (%dx%d) does "
252  "not match", fn1, binx1, biny1, fn2, binx2, biny2);
253  return CPL_ERROR_TYPE_MISMATCH;
254  }
255 
256  /* The pipeline should refuse to work if the bias is not taken in the *
257  * same read-out as the image that is being bias-subtracted. Hence it *
258  * should give an ERROR message when searching for bias files and stop. */
259  if (!strncmp(catg, "MASTER_BIAS", 12)) {
260  if (!ignoreread && (readid1 != readid2)) {
261  cpl_msg_error(__func__, "Read-out mode of \"%s\" (%d: %s) and \"%s\" (%d:"
262  " %s) does not match", fn1, readid1, readname1, fn2,
263  readid2, readname2);
264  return CPL_ERROR_TYPE_MISMATCH;
265  }
266  if (chipinfo && (strcmp(chipname1, chipname2) || strcmp(chipid1, chipid2))) {
267  cpl_msg_error(__func__, "CHIP information (ESO.DET.CHIP.{NAME,ID}) "
268  "does not match for \"%s\" (%s, %s) and \"%s\" (%s, %s)",
269  fn1, chipname1, chipid1, fn2, chipname2, chipid2);
270  return CPL_ERROR_TYPE_MISMATCH;
271  }
272  } /* if ref is bias */
273 
274  /* We probably need similar guards for the instrument mode, so that one *
275  * cannot use a flat-field in WFM-NOAO-N for data taken with WFM-NOAO-E. */
276  if (!strncmp(catg, "MASTER_FLAT", 12)) {
277  if (!ignoremode && (mode1 != mode2)) {
278  if (rawtag && !strncmp(rawtag, MUSE_TAG_ILLUM, strlen(MUSE_TAG_ILLUM) + 1)) {
279  /* ignore mode differences between ILLUM and other calibrations */
280  cpl_msg_debug(__func__, "Instrument modes for \"%s\" (%s, is %s) and \"%s\""
281  " (%s) do not match", fn1, modestr1, rawtag, fn2, modestr2);
282  } else {
283  cpl_msg_error(__func__, "Instrument modes for \"%s\" (%s) and \"%s\" (%s)"
284  " do not match", fn1, modestr1, fn2, modestr2);
285  return CPL_ERROR_TYPE_MISMATCH;
286  } /* else */
287  } /* if modes different */
288  } /* if ref is flat */
289 
290  /* XXX add check to not mix WFM and NFM for illuminated exposures */
291 
292  /* It should output WARNINGs (but continue processing), when other *
293  * calibrations are not in the same read-out mode or if the images *
294  * originate from different chips or chip installation dates. */
295  if (!ignoreread && (readid1 != readid2)) {
296  cpl_msg_warning(__func__, "Read-out mode of \"%s\" (%d: %s) and \"%s\" (%d:"
297  " %s) does not match", fn1, readid1, readname1, fn2,
298  readid2, readname2);
299  }
300  if (chipinfo && (strcmp(chipname1, chipname2) || strcmp(chipid1, chipid2))) {
301  cpl_msg_warning(__func__, "CHIP information (ESO.DET.CHIP.{NAME,ID,DATE}) "
302  "does not match for \"%s\" (%s, %s) and \"%s\" (%s, %s)",
303  fn1, chipname1, chipid1, fn2, chipname2, chipid2);
304  }
305 
306  return CPL_ERROR_NONE;
307 } /* muse_basicproc_verify_setup() */
308 
309 /*---------------------------------------------------------------------------*/
324 /*---------------------------------------------------------------------------*/
325 static cpl_error_code
326 muse_basicproc_overscans_compute_stats(muse_imagelist *aList,
327  muse_basicproc_params *aBPars)
328 {
329  cpl_ensure_code(aList, CPL_ERROR_NULL_INPUT);
330  unsigned int k;
331  for (k = 0; k < aList->size; k++) {
332  muse_image *image = muse_imagelist_get(aList, k);
333  if (muse_quadrants_overscan_stats(image, aBPars ? aBPars->rejection : NULL,
334  aBPars ? aBPars->ovscignore : 0)
335  != CPL_ERROR_NONE) {
336  cpl_msg_warning(__func__, "Could not compute overscan statistics in IFU "
337  "%hhu of exposure %u: %s", muse_utils_get_ifu(image->header),
338  k+1, cpl_error_get_message());
339  } /* if */
340  } /* for k (all images) */
341  return CPL_ERROR_NONE;
342 } /* muse_basicproc_overscans_compute_stats() */
343 
344 /*---------------------------------------------------------------------------*/
357 /*---------------------------------------------------------------------------*/
358 static cpl_error_code
359 muse_basicproc_correct_overscans_vpoly(muse_imagelist *aList,
360  muse_basicproc_params *aBPars)
361 {
362  cpl_ensure_code(aList, CPL_ERROR_NULL_INPUT);
363  cpl_boolean ovscvpoly = aBPars && aBPars->overscan
364  && !strncmp(aBPars->overscan, "vpoly", 5);
365  if (!ovscvpoly) {
366  cpl_msg_debug(__func__, "not vpoly: %s!", aBPars ? aBPars->overscan : "");
367  return CPL_ERROR_NONE;
368  }
369  /* vertical polyfit requested, see if there are more parameters */
370  unsigned char ovscvorder = 5;
371  double frms = 1.01,
372  fchisq = 1.04;
373  char *rest = strchr(aBPars->overscan, ':');
374  if (strlen(aBPars->overscan) > 6 && rest++) { /* try to access info after "vpoly:" */
375  ovscvorder = strtol(rest, &rest, 10);
376  if (strlen(rest++) > 0) { /* ++ to skip over the comma */
377  frms = strtod(rest, &rest);
378  if (strlen(rest++) > 0) {
379  fchisq = strtod(rest, &rest);
380  }
381  }
382  } /* if */
383  cpl_msg_debug(__func__, "vpoly: %s (vorder=%hhu, frms=%f, fchisq=%f, ignore=%u,"
384  " sigma=%.3f)", aBPars->overscan, ovscvorder, frms, fchisq,
385  aBPars->ovscignore, aBPars->ovscsigma);
386 
387  cpl_error_code rc = CPL_ERROR_NONE;
388  unsigned int k;
389  for (k = 0; k < aList->size; k++) {
390  muse_image *image = muse_imagelist_get(aList, k);
392  ovscvorder, aBPars->ovscsigma,
393  frms, fchisq);
394  if (rc != CPL_ERROR_NONE) {
395  unsigned char ifu = muse_utils_get_ifu(image->header);
396  cpl_msg_error(__func__, "Could not correct quadrants levels using vertical"
397  " overscan fit in IFU %hhu: %s", ifu, cpl_error_get_message());
398  } /* if */
399  } /* for k (all images) */
400  return rc;
401 } /* muse_basicproc_correct_overscans_vpoly() */
402 
403 /*---------------------------------------------------------------------------*/
417 /*---------------------------------------------------------------------------*/
418 static cpl_error_code
419 muse_basicproc_trim_images(muse_imagelist *aList)
420 {
421  cpl_ensure_code(aList, CPL_ERROR_NULL_INPUT);
422 
423  unsigned int k;
424  for (k = 0; k < aList->size; k++) {
425  muse_image *image = muse_imagelist_get(aList, k);
426  muse_image *trimmed = muse_quadrants_trim_image(image);
427  cpl_ensure_code(trimmed, cpl_error_get_code());
428 
429  /* setting a new one deletes the old, so no need to free |image| */
430  muse_imagelist_set(aList, trimmed, k);
431  } /* for k (all images) */
432  return muse_imagelist_is_uniform(aList) == 0 ? CPL_ERROR_NONE
433  : CPL_ERROR_ILLEGAL_OUTPUT;
434 } /* muse_basicproc_trim_images() */
435 
436 /*---------------------------------------------------------------------------*/
454 /*---------------------------------------------------------------------------*/
455 static cpl_error_code
456 muse_basicproc_correct_overscans_offset(muse_imagelist *aList,
457  muse_processing *aProcessing,
458  muse_basicproc_params *aBPars)
459 {
460  cpl_ensure_code(aList && aProcessing, CPL_ERROR_NULL_INPUT);
461  /* this only makes sense to do for inputs that are bias */
462  if (!muse_processing_check_intags(aProcessing, MUSE_TAG_BIAS, 5)) {
463  return CPL_ERROR_NONE;
464  }
465  cpl_boolean ovscoffset = aBPars && aBPars->overscan
466  && !strncmp(aBPars->overscan, "offset", 7);
467  if (!ovscoffset) {
468  return CPL_ERROR_NONE; /* no correction necessary */
469  }
470  unsigned char ifu = muse_utils_get_ifu(muse_imagelist_get(aList, 0)->header);
471  cpl_msg_info(__func__, "Running overscan correction using %u %s images in IFU"
472  " %hhu", aList->size, MUSE_TAG_BIAS, ifu);
473  muse_image *ref = muse_imagelist_get(aList, 0);
474  unsigned int k;
475  for (k = 1; k < aList->size; k++) {
477  } /* for k (all images except first) */
478  return CPL_ERROR_NONE;
479 } /* muse_basicproc_correct_overscans_offset() */
480 
481 /*---------------------------------------------------------------------------*/
506 /*---------------------------------------------------------------------------*/
507 static cpl_error_code
508 muse_basicproc_check_overscans(muse_imagelist *aList,
509  muse_processing *aProcessing,
510  muse_basicproc_params *aBPars)
511 {
512  cpl_ensure_code(aList && aProcessing, CPL_ERROR_NULL_INPUT);
513  /* files other than bias are already checked when *
514  * subtracting the bias, so we can skip this check */
515  if (!muse_processing_check_intags(aProcessing, MUSE_TAG_BIAS, 5)) {
516  return CPL_ERROR_NONE;
517  }
518  if (aList->size < 2) { /* doesn't make sense for single image lists */
519  return CPL_ERROR_NONE;
520  }
521  cpl_boolean ovscnone = aBPars && aBPars->overscan
522  && !strncmp(aBPars->overscan, "none", 5);
523  if (!ovscnone) { /* check not needed */
524  return CPL_ERROR_NONE;
525  }
526  double sigma = aBPars ? aBPars->ovscsigma : 1.;
527 
528  /* header of the first image */
529  muse_image *refimage = muse_imagelist_get(aList, 0);
530  cpl_propertylist *refheader = refimage->header;
531  cpl_error_code rc = CPL_ERROR_NONE;
532  unsigned char n, ifu = muse_utils_get_ifu(refheader);
533  for (n = 1; n <= 4; n++) {
534  /* create correct header keyword names */
535  char *keywordmean = cpl_sprintf(MUSE_HDR_OVSC_MEAN, n),
536  *keywordstdev = cpl_sprintf(MUSE_HDR_OVSC_STDEV, n);
537 
538  /* overscan stats for first image in list */
539  const char *reffn = cpl_propertylist_get_string(refheader, MUSE_HDR_TMP_FN);
540  float refmean = cpl_propertylist_get_float(refheader, keywordmean),
541  refstdev = cpl_propertylist_get_float(refheader, keywordstdev),
542  hilimit = refmean + sigma * refstdev,
543  lolimit = refmean - sigma * refstdev;
544  /* variables to create average output values */
545  double summean = refmean,
546  sumstdev = pow(refstdev, 2.);
547 
548  /* compare with the other images */
549  unsigned int k;
550  for (k = 1; k < aList->size; k++) {
551  cpl_propertylist *h = muse_imagelist_get(aList, k)->header;
552  float mean = cpl_propertylist_get_float(h, keywordmean),
553  stdev = cpl_propertylist_get_float(h, keywordstdev);
554  summean += mean;
555  sumstdev += pow(stdev, 2.) + pow(mean - refmean, 2.);
556  const char *fn = cpl_propertylist_get_string(h, MUSE_HDR_TMP_FN);
557  if (mean > hilimit || mean < lolimit) {
558  cpl_msg_error(__func__, "Overscan of IFU %hhu, quadrant %1hhu of image %u [%s] "
559  "(%.3f+/-%.3f) differs from first image [%s] (%.3f+/-%.3f)!",
560  ifu, n, k+1, fn, mean, stdev, reffn, refmean, refstdev);
561  rc = cpl_error_set(__func__, CPL_ERROR_INCOMPATIBLE_INPUT);
562  continue; /* debug output only if there was no error */
563  }
564  cpl_msg_debug(__func__, "Overscan of IFU %hhu, quadrant %1hhu of image %u [%s] "
565  "%.3f+/-%.3f (first image [%s] %.3f+/-%.3f)",
566  ifu, n, k+1, fn, mean, stdev, reffn, refmean, refstdev);
567  } /* for k (all images except first) */
568 
569  /* update values in the 1st header to be the averaged values *
570  * which should be propagated to the final combined frame */
571  summean /= aList->size;
572  sumstdev = sqrt(sumstdev) / aList->size;
573  cpl_msg_debug(__func__, "Averaged overscan values in IFU %hhu, quadrant %1hhu: "
574  "%.3f +/- %.3f (%d images)", ifu, n, summean, sumstdev, aList->size);
575  cpl_propertylist_update_float(refheader, keywordmean, summean);
576  cpl_propertylist_update_float(refheader, keywordstdev, sumstdev);
577 
578  cpl_free(keywordmean);
579  cpl_free(keywordstdev);
580  } /* for n (quadrants) */
581 
582  return rc;
583 } /* muse_basicproc_check_overscans() */
584 
585 /*---------------------------------------------------------------------------*/
604 /*---------------------------------------------------------------------------*/
605 static cpl_error_code
606 muse_basicproc_apply_badpix(muse_imagelist *aList, muse_processing *aProcessing,
607  unsigned char aIFU)
608 {
609  cpl_ensure_code(aList && aProcessing, CPL_ERROR_NULL_INPUT);
610  cpl_frameset *frames = muse_frameset_find(aProcessing->inframes,
611  MUSE_TAG_BADPIX_TABLE, aIFU,
612  CPL_FALSE);
613  if (!frames) { /* should not happen... */
614  return CPL_ERROR_NONE;
615  }
616 
617  /* loop through all frames that were found to have bad pixels for this IFU */
618  cpl_errorstate prestate = cpl_errorstate_get();
619  cpl_size iframe, nframes = cpl_frameset_get_size(frames);
620  for (iframe = 0; iframe < nframes; iframe++) {
621  cpl_frame *frame = cpl_frameset_get_position(frames, iframe);
622  const char *fn = cpl_frame_get_filename(frame);
623  char *extname = cpl_sprintf("CHAN%02hhu", aIFU);
624  cpl_table *table = muse_cpltable_load(fn, extname, muse_badpix_table_def);
625  cpl_free(extname);
626  if (!table) {
627  continue; /* file couldn't be loaded or is faulty */
628  }
629  muse_processing_append_used(aProcessing, frame, CPL_FRAME_GROUP_CALIB, 1);
630 
631  /* valid table found, loop through all entries and mark them in all images */
632  int nrow = cpl_table_get_nrow(table);
633  unsigned int k, nbadpix = 0, /* could transferred bad pixels */
634  nbadpos = 0; /* and entries with bad positions */
635  for (k = 0; k < aList->size; k++) {
636  muse_image *image = muse_imagelist_get(aList, k);
637  /* XXX need to verify the detector/chip properties here, too! */
638  int i;
639  for (i = 0; i < nrow; i++) {
640  int x = cpl_table_get(table, MUSE_BADPIX_X, i, NULL),
641  y = cpl_table_get(table, MUSE_BADPIX_Y, i, NULL);
642 
643  /* get value from table and check that getting *
644  * the value from the DQ image succeeds */
645  uint32_t dq = cpl_table_get(table, MUSE_BADPIX_DQ, i, NULL);
646  cpl_errorstate state = cpl_errorstate_get();
647  int err;
648  uint32_t value = cpl_image_get(image->dq, x, y, &err);
649  if (err != 0 || !cpl_errorstate_is_equal(state)) {
650  cpl_errorstate_set(state); /* swallow the error, nothing was changed */
651  if (k == 0) {
652  nbadpos++;
653  } /* if first image */
654  continue;
655  } /* if error occurred */
656 
657  /* OR the data in the DQ extension with what's in the badpix table */
658  cpl_image_set(image->dq, x, y, dq | value);
659  if (k == 0) {
660  nbadpix++; /* count bad pixels transferred to 1st image */
661  } /* if first image */
662  } /* for i (all table rows) */
663  } /* for k (all images) */
664  cpl_table_delete(table);
665 
666  cpl_msg_debug(__func__, "Applied %u bad pixels from %s \"%s\" in IFU %hhu.",
667  nbadpix, MUSE_TAG_BADPIX_TABLE, fn, aIFU);
668  /* warn, if there were bad entries */
669  if (nbadpos > 0) {
670  cpl_msg_warning(__func__, "\"%s\" contained %u entries outside the CCD in"
671  " IFU %hhu!", fn, nbadpos, aIFU);
672  } /* if bad entries */
673  } /* for iframe (all bad pixel tables found) */
674  cpl_frameset_delete(frames);
675  return cpl_errorstate_is_equal(prestate) ? CPL_ERROR_NONE
676  : cpl_error_get_code();
677 } /* muse_basicproc_apply_badpix() */
678 
679 /*---------------------------------------------------------------------------*/
688 /*---------------------------------------------------------------------------*/
689 static cpl_error_code
690 muse_basicproc_check_saturation(muse_imagelist *aList)
691 {
692  cpl_ensure_code(aList, CPL_ERROR_NULL_INPUT);
693  unsigned int k;
694  for (k = 0; k < aList->size; k++) {
695  muse_image *image = muse_imagelist_get(aList, k);
696  unsigned char ifu = muse_utils_get_ifu(image->header);
697  int nsaturated = muse_quality_set_saturated(image);
698  /* if we have more than 10% of saturated pixels then something is wrong */
699  int npix = cpl_image_get_size_x(image->data)
700  * cpl_image_get_size_y(image->data);
701  if (nsaturated > (0.01 * npix)) {
702  const char *fn = cpl_propertylist_get_string(image->header,
703  MUSE_HDR_TMP_FN);
704  cpl_msg_error(__func__, "Raw exposure %u [%s] is strongly saturated in "
705  "IFU %hhu (%d of %d pixels)!", k+1, fn, ifu, nsaturated,
706  npix);
707  } else if (nsaturated > (0.001 * npix)) {
708  const char *fn = cpl_propertylist_get_string(image->header,
709  MUSE_HDR_TMP_FN);
710  cpl_msg_warning(__func__, "Raw exposure %u [%s] is probably saturated in "
711  "IFU %hhu (%d of %d pixels)!", k+1, fn, ifu, nsaturated,
712  npix);
713  } else {
714  cpl_msg_debug(__func__, "Raw exposure %u in IFU %hhu (%d of %d pixels "
715  "saturated)!", k+1, ifu, nsaturated, npix);
716  }
717  cpl_propertylist_update_int(image->header, MUSE_HDR_TMP_NSAT, nsaturated);
718  } /* for k (all images) */
719  return CPL_ERROR_NONE;
720 } /* muse_basicproc_check_saturation() */
721 
722 /*---------------------------------------------------------------------------*/
735 /*---------------------------------------------------------------------------*/
736 static cpl_error_code
737 muse_basicproc_quadrant_statistics(muse_imagelist *aList,
738  muse_processing *aProcessing)
739 {
740  cpl_ensure_code(aList, CPL_ERROR_NULL_INPUT);
741  /* this only makes sense to do for inputs that are bias */
742  if (!muse_processing_check_intags(aProcessing, MUSE_TAG_BIAS, 5)) {
743  return CPL_ERROR_NONE;
744  }
745  unsigned char ifu = muse_utils_get_ifu(muse_imagelist_get(aList, 0)->header);
746  cpl_msg_info(__func__, "Computing per-quadrant medians for %u exposures in "
747  "IFU %hhu", aList->size, ifu);
748  unsigned int k;
749  for (k = 0; k < aList->size; k++) {
750  muse_image *image = muse_imagelist_get(aList, k);
751  unsigned char n;
752  for (n = 1; n <= 4; n++) {
753  cpl_size *w = muse_quadrants_get_window(muse_imagelist_get(aList, k), n);
754  float median = cpl_image_get_median_window(image->data, w[0], w[2],
755  w[1], w[3]);
756  cpl_free(w);
757  char *kw = cpl_sprintf(MUSE_HDR_TMP_QUADnMED, n);
758  cpl_propertylist_append_float(image->header, kw, median);
759  cpl_free(kw);
760  } /* for n (quadrants) */
761  } /* for k (all images) */
762  return CPL_ERROR_NONE;
763 } /* muse_basicproc_quadrant_statistics() */
764 
765 /*---------------------------------------------------------------------------*/
787 /*---------------------------------------------------------------------------*/
788 static cpl_error_code
789 muse_basicproc_apply_bias(muse_imagelist *aList, muse_processing *aProcessing,
790  unsigned char aIFU, muse_basicproc_params *aBPars)
791 {
792  cpl_ensure_code(aList && aProcessing, CPL_ERROR_NULL_INPUT);
793  cpl_frame *biasframe = muse_frameset_find_master(aProcessing->inframes,
794  MUSE_TAG_MASTER_BIAS, aIFU);
795  cpl_errorstate prestate = cpl_errorstate_get();
796  if (!biasframe) return CPL_ERROR_NONE;
797  cpl_errorstate_set(prestate);
798  const char *biasname = cpl_frame_get_filename(biasframe);
799  muse_image *biasimage = muse_image_load(biasname);
800  if (!biasimage) {
801  /* remember error message for a while, but reset the state, *
802  * before trying to load from channel extensions */
803  char *errmsg = cpl_strdup(cpl_error_get_message());
804  cpl_errorstate_set(prestate);
805  biasimage = muse_image_load_from_extensions(biasname, aIFU);
806  if (!biasimage) {
807  /* now display both the older and the new error messages, *
808  * so that they cannot be swallowed by parallelization */
809  cpl_msg_error(__func__, "%s", errmsg);
810  cpl_msg_error(__func__, "%s", cpl_error_get_message());
811  cpl_free(errmsg);
812  cpl_frame_delete(biasframe);
813  return cpl_error_get_code();
814  } /* if 2nd load failure */
815  cpl_free(errmsg);
816  cpl_msg_info(__func__, "Bias correction in IFU %hhu using \"%s[CHAN%02hhu."
817  "DATA]\"", aIFU, biasname, aIFU);
818  } else {
819  cpl_msg_info(__func__, "Bias correction in IFU %hhu using \"%s[DATA]\"",
820  aIFU, biasname);
821  }
822  /* add temporary input filename for diagnostics */
823  cpl_propertylist_append_string(biasimage->header, MUSE_HDR_TMP_FN, biasname);
824 
825  /* cross-check with the parameters of the master bias */
826  muse_basicproc_params *mbpars
828  cpl_boolean parmatch = mbpars && aBPars; /* both sets exist */
829  if (parmatch) {
830  parmatch = parmatch && mbpars->overscan && aBPars->overscan
831  && !strncmp(aBPars->overscan, mbpars->overscan,
832  CPL_MIN(strlen(aBPars->overscan), strlen(mbpars->overscan) + 1));
833  parmatch = parmatch && mbpars->rejection && aBPars->rejection
834  && !strncmp(aBPars->rejection, mbpars->rejection,
835  CPL_MIN(strlen(aBPars->rejection), strlen(mbpars->rejection) + 1));
836  parmatch = parmatch && fabs(aBPars->ovscsigma - mbpars->ovscsigma)
837  < 10 * DBL_EPSILON;
838  parmatch = parmatch && aBPars->ovscignore == mbpars->ovscignore;
839  }
840  if (!parmatch) {
841  cpl_msg_warning(__func__, "overscan parameters differ between %s and recipe"
842  " parameters!", MUSE_TAG_MASTER_BIAS);
843  } else {
844  cpl_msg_debug(__func__, "overscan parameters between %s and given "
845  "parameters nicely match", MUSE_TAG_MASTER_BIAS);
846  }
848 
849  cpl_boolean ovscoffset = aBPars && aBPars->overscan
850  && !strncmp(aBPars->overscan, "offset", 7),
851  ovscvpoly = aBPars && aBPars->overscan
852  && !strncmp(aBPars->overscan, "vpoly", 5); /* up to the : */
853  muse_processing_append_used(aProcessing, biasframe, CPL_FRAME_GROUP_CALIB, 0);
854  cpl_error_code rc = CPL_ERROR_NONE;
855  unsigned int k;
856  for (k = 0; k < aList->size && rc == CPL_ERROR_NONE; k++) {
857  muse_image *image = muse_imagelist_get(aList, k);
858  rc = muse_basicproc_verify_setup(image, biasimage);
859  if (rc != CPL_ERROR_NONE) {
860  break;
861  }
862  rc = muse_image_variance_create(image, biasimage);
863  if (ovscoffset) {
864  muse_quadrants_overscan_correct(image, biasimage);
865  } else if (ovscvpoly) {
866  /* create error message and code, if the bias was not *
867  * vpoly-handled, i.e. still has the original bias level *
868  * of ~1000 adu or > 100xsigma above ~zero */
869  cpl_boolean good = muse_quadrants_overscan_check(image, biasimage, 100.);
870  if (!good) {
871  cpl_msg_error(__func__, "Very different overscan levels found between "
872  "%s and raw exposure %u in IFU %hhu: incompatible overscan"
873  " parameters?", MUSE_TAG_MASTER_BIAS, k + 1, aIFU);
874  rc = cpl_error_set(__func__, CPL_ERROR_INCOMPATIBLE_INPUT);
875  break;
876  } /* if not good */
877  } else {
878  /* just warn above indicated sigma level, ignore failure */
879  muse_quadrants_overscan_check(image, biasimage,
880  aBPars ? aBPars->ovscsigma : 1.);
881  }
882  rc = muse_image_subtract(image, biasimage);
883 #if GENERATE_TEST_IMAGES
884  /* if we need to generate images for automated tests, here is a good *
885  * place to write them out, as they are trimmed and bias corrected */
886  if (k == 0) {
887  muse_image_save(image, "trimmed_bias_sub.fits");
888  }
889 #endif
890  } /* for k (all images) */
891  muse_image_delete(biasimage);
892  return rc;
893 } /* muse_basicproc_apply_bias() */
894 
895 /*---------------------------------------------------------------------------*/
914 /*---------------------------------------------------------------------------*/
915 static cpl_error_code
916 muse_basicproc_check_gain(muse_imagelist *aList, muse_processing *aProcessing,
917  unsigned char aIFU)
918 {
919  cpl_ensure_code(aList && aProcessing, CPL_ERROR_NULL_INPUT);
920  /* this only makes sense to do for input flat-fields */
921  if (!muse_processing_check_intags(aProcessing, MUSE_TAG_FLAT, 5)) {
922  return CPL_ERROR_NONE;
923  }
924  cpl_ensure_code(muse_imagelist_get_size(aList) >= 2,
925  CPL_ERROR_INCOMPATIBLE_INPUT);
926 
927  cpl_frame *fbias = muse_frameset_find_master(aProcessing->inframes,
928  MUSE_TAG_MASTER_BIAS, aIFU);
929  if (!fbias) {
930  /* it's OK if there is no bias frame, probably we are not in muse_bias */
931  return CPL_ERROR_NONE;
932  }
933  const char *biasname = cpl_frame_get_filename(fbias);
934  cpl_propertylist *hbias = cpl_propertylist_load(biasname, 0);
935  if (!cpl_propertylist_has(hbias, QC_BIAS_MASTER_RON)) {
936  cpl_propertylist_delete(hbias);
937  /* try to load from channel extension */
938  char *extname = cpl_sprintf("CHAN%02hhu.%s", aIFU, EXTNAME_DATA);
939  int extension = cpl_fits_find_extension(biasname, extname);
940  hbias = cpl_propertylist_load(biasname, extension);
941  cpl_free(extname);
942  }
943  cpl_frame_delete(fbias);
944  cpl_image *f1 = muse_imagelist_get(aList, 0)->data,
945  *f2 = muse_imagelist_get(aList, 1)->data;
946  cpl_propertylist *header = muse_imagelist_get(aList, 0)->header;
947  cpl_image *diff = cpl_image_subtract_create(f1, f2);
948 
949  unsigned char n;
950  for (n = 1; n <= 4; n++) {
951  cpl_size *w = muse_quadrants_get_window(muse_imagelist_get(aList, 0), n);
952  double m1 = cpl_image_get_mean_window(f1, w[0], w[2], w[1], w[3]),
953  m2 = cpl_image_get_mean_window(f2, w[0], w[2], w[1], w[3]),
954  sf = cpl_image_get_stdev_window(diff, w[0], w[2], w[1], w[3]);
955  char *keyword = cpl_sprintf(QC_BIAS_MASTERn_PREFIX" MEAN", n);
956  float mb = cpl_propertylist_get_float(hbias, keyword);
957  cpl_free(keyword);
958  keyword = cpl_sprintf(QC_BIAS_MASTER_RON, n);
959  /* the RON formula taken from Howell inverted to give sigma(b1-b2) */
960  double gainheader = muse_pfits_get_gain(header, n),
961  sb = cpl_propertylist_get_float(hbias, keyword) * sqrt(2.)
962  / gainheader, /* gain in count/adu */
963  /* the gain formula taken from Howell: */
964  gain = (m1 + m2 - 2*mb) / (sf*sf - sb*sb),
965  dgain = 1. - gain / gainheader;
966  /* output warning for difference larger than 20%, info message otherwise */
967  if (dgain > 0.2) {
968  cpl_msg_warning(__func__, "IFU %hhu, quadrant %1hhu: estimated gain %.3f "
969  "count/adu but header gives %.3f!", aIFU, n, gain,
970  gainheader);
971  } else {
972  cpl_msg_info(__func__, "IFU %hhu, quadrant %1hhu: estimated gain %.3f "
973  "count/adu (header %.3f, delta %.3f)", aIFU, n, gain,
974  gainheader, dgain);
975  }
976  cpl_free(keyword);
977  cpl_free(w);
978  } /* for n (quadrants) */
979 
980  cpl_image_delete(diff);
981  cpl_propertylist_delete(hbias);
982 
983  return CPL_ERROR_NONE;
984 } /* muse_basicproc_check_gain() */
985 
986 /*---------------------------------------------------------------------------*/
1005 /*---------------------------------------------------------------------------*/
1006 static cpl_error_code
1007 muse_basicproc_gain_override(muse_imagelist *aList,
1008  muse_processing *aProcessing, unsigned char aIFU)
1009 {
1010  cpl_ensure_code(aList && aProcessing, CPL_ERROR_NULL_INPUT);
1011 
1012  if (muse_processing_check_intags(aProcessing, MUSE_TAG_LINEARITY_BIAS, 16) ||
1013  muse_processing_check_intags(aProcessing, MUSE_TAG_LINEARITY_FLAT, 15))
1014  {
1015  return CPL_ERROR_NONE;
1016  }
1017 
1018  cpl_frame *fnonlingain = muse_frameset_find_master(aProcessing->inframes,
1019  MUSE_TAG_NONLINGAIN, aIFU);
1020  if (!fnonlingain) {
1021  /* it's OK if there is no nonlinearity frame, it's optional... */
1022  return CPL_ERROR_NONE;
1023  }
1024  if (getenv("MUSE_BASICPROC_SKIP_GAIN_OVERRIDE") &&
1025  atoi(getenv("MUSE_BASICPROC_SKIP_GAIN_OVERRIDE")) > 0) {
1026  cpl_msg_info(__func__, "Skipping gain override, although %s is given",
1027  MUSE_TAG_NONLINGAIN);
1028  return CPL_ERROR_NONE;
1029  }
1030  cpl_errorstate state = cpl_errorstate_get();
1031  const char *fn = cpl_frame_get_filename(fnonlingain);
1032  /* immediately try to load from channel extension */
1033  char *extname = cpl_sprintf("CHAN%02hhu", aIFU);
1034  int extension = cpl_fits_find_extension(fn, extname);
1035  cpl_propertylist *header = cpl_propertylist_load(fn, extension);
1036  cpl_msg_info(__func__, "Overriding gain in IFU %hhu using \"%s[%s]\"",
1037  aIFU, fn, extname);
1038  cpl_free(extname);
1039  muse_processing_append_used(aProcessing, fnonlingain, CPL_FRAME_GROUP_CALIB, 0);
1040 
1041  unsigned int k;
1042  for (k = 0; k < aList->size; k++) {
1043  muse_image *image = muse_imagelist_get(aList, k);
1044  /* XXX need to verify the detector/chip properties here, too! */
1045  unsigned char n;
1046  for (n = 1; n <= 4; n++) {
1047  /* transfer the GAIN of this quadrant into the image */
1048  double gain = muse_pfits_get_gain(header, n);
1049  char *kw = cpl_sprintf("ESO DET OUT%d GAIN", n);
1050  cpl_propertylist_update_double(image->header, kw, gain);
1051  cpl_free(kw);
1052  } /* for n (quadrants) */
1053  } /* for k (all images) */
1054  cpl_propertylist_delete(header);
1055  return cpl_errorstate_is_equal(state) ? CPL_ERROR_NONE : cpl_error_get_code();
1056 } /* muse_basicproc_gain_override() */
1057 
1058 /*---------------------------------------------------------------------------*/
1072 /*---------------------------------------------------------------------------*/
1073 static cpl_error_code
1074 muse_basicproc_adu_to_count(muse_imagelist *aList, muse_processing *aProcessing)
1075 {
1076  cpl_ensure_code(aList && aProcessing, CPL_ERROR_NULL_INPUT);
1077  /* this only makes sense to do for inputs that are not bias, and not *
1078  * inputs used to measure gain and linearity */
1079  if (muse_processing_check_intags(aProcessing, MUSE_TAG_BIAS, 5) ||
1080  muse_processing_check_intags(aProcessing, MUSE_TAG_LINEARITY_BIAS, 16) ||
1081  muse_processing_check_intags(aProcessing, MUSE_TAG_LINEARITY_FLAT, 15)) {
1082  return CPL_ERROR_NONE;
1083  }
1084 
1085  unsigned char ifu = muse_utils_get_ifu(muse_imagelist_get(aList, 0)->header);
1086  cpl_msg_info(__func__, "Converting %u exposures from adu to count (= electron)"
1087  " units in IFU %hhu", aList->size, ifu);
1088  cpl_error_code rc = CPL_ERROR_NONE;
1089  unsigned int k;
1090  for (k = 0; k < aList->size; k++) {
1092  } /* for k (all images) */
1093  return rc;
1094 } /* muse_basicproc_adu_to_count() */
1095 
1096 /*---------------------------------------------------------------------------*/
1118 /*---------------------------------------------------------------------------*/
1119 static cpl_error_code
1120 muse_basicproc_corr_nonlinearity(muse_imagelist *aList,
1121  muse_processing *aProcessing,
1122  unsigned char aIFU)
1123 {
1124  cpl_ensure_code(aList && aProcessing, CPL_ERROR_NULL_INPUT);
1125  /* this only makes sense to do for inputs that are illuminated and *
1126  * inputs which are not used to measure gain and linearity */
1127  if (muse_processing_check_intags(aProcessing, MUSE_TAG_BIAS, 5) ||
1128  muse_processing_check_intags(aProcessing, MUSE_TAG_DARK, 5) ||
1129  muse_processing_check_intags(aProcessing, MUSE_TAG_LINEARITY_BIAS, 16) ||
1130  muse_processing_check_intags(aProcessing, MUSE_TAG_LINEARITY_FLAT, 15)) {
1131  return CPL_ERROR_NONE;
1132  }
1133 
1134  cpl_frame *fnonlingain = muse_frameset_find_master(aProcessing->inframes,
1135  MUSE_TAG_NONLINGAIN, aIFU);
1136  if (!fnonlingain) {
1137  /* it's OK if there is no nonlinearity frame, it's optional... */
1138  return CPL_ERROR_NONE;
1139  }
1140  if (getenv("MUSE_BASICPROC_SKIP_NONLIN_CORR") &&
1141  atoi(getenv("MUSE_BASICPROC_SKIP_NONLIN_CORR")) > 0) {
1142  cpl_msg_debug(__func__, "Skipping nonlinearity correction, although %s is "
1143  "given", MUSE_TAG_NONLINGAIN);
1144  return CPL_ERROR_NONE;
1145  }
1146  const char *fn = cpl_frame_get_filename(fnonlingain);
1147  /* immediately try to load from channel extension */
1148  char *extname = cpl_sprintf("CHAN%02hhu", aIFU);
1149  int extension = cpl_fits_find_extension(fn, extname);
1150  cpl_propertylist *header = cpl_propertylist_load(fn, extension);
1151  cpl_msg_info(__func__, "Correcting nonlinearity in IFU %hhu using \"%s[%s]\"",
1152  aIFU, fn, extname);
1153  cpl_free(extname);
1154  muse_processing_append_used(aProcessing, fnonlingain, CPL_FRAME_GROUP_CALIB, 0);
1155 
1156  cpl_error_code rc = CPL_ERROR_NONE;
1157  unsigned int k;
1158  for (k = 0; k < aList->size; k++) {
1159  muse_image *image = muse_imagelist_get(aList, k);
1160  int nx = cpl_image_get_size_x(image->data);
1161  float *data = cpl_image_get_data_float(image->data),
1162  *stat = cpl_image_get_data_float(image->stat);
1163 
1164  /* XXX need to verify the detector/chip properties here, too! */
1165 
1166  unsigned char n;
1167  for (n = 1; n <= 4; n++) {
1168  /* create the 1D nonlinearity polynomial for this quadrant, then read *
1169  * all the parameters from the header set the polynomial up accordingly */
1170  cpl_polynomial *poly = cpl_polynomial_new(1);
1171  char *kw = cpl_sprintf(MUSE_HDR_NONLINn_ORDER, n);
1172  unsigned char o, order = cpl_propertylist_get_int(header, kw);
1173  cpl_free(kw);
1174  for (o = 0; o <= order; o++) {
1175  kw = cpl_sprintf(MUSE_HDR_NONLINn_COEFFo, n, o);
1176  cpl_size pows = o;
1177  cpl_polynomial_set_coeff(poly, &pows,
1178  cpl_propertylist_get_double(header, kw));
1179  cpl_free(kw);
1180  } /* for i (polynomial orders) */
1181  /* compute linear extrapolations */
1182  kw = cpl_sprintf(MUSE_HDR_NONLINn_LLO, n);
1183  double lolim = cpl_propertylist_get_double(header, kw);
1184  cpl_free(kw);
1185  kw = cpl_sprintf(MUSE_HDR_NONLINn_LHI, n);
1186  double hilim = cpl_propertylist_get_double(header, kw);
1187  cpl_free(kw);
1188  /* coefficients for linear extrapolation beyond low and high limits */
1189  double p1lo, p0lo = cpl_polynomial_eval_1d(poly, lolim, &p1lo),
1190  p1hi, p0hi = cpl_polynomial_eval_1d(poly, hilim, &p1hi);
1191  /* convert limits from log10(adu) to adu */
1192  lolim = pow(10, lolim);
1193  hilim = pow(10, hilim);
1194 #if 0
1195  double values[] = { 1., 20., 200., 2000., 20000., 65000.,
1196  lolim, hilim, -1. };
1197  int idx = 0;
1198  while (values[idx] > 0) {
1199  double v = values[idx],
1200  logv = log10(v);
1201  cpl_msg_debug(__func__, "%f adu -> %f log10(adu) ==> poly = %f ==> x %f",
1202  v, logv, cpl_polynomial_eval_1d(poly, logv, NULL),
1203  1. / (1. + cpl_polynomial_eval_1d(poly, logv, NULL)));
1204  idx++;
1205  } /* while */
1206  cpl_polynomial_dump(poly, stdout);
1207  fflush(stdout);
1208  cpl_msg_debug(__func__, "beyond low limit (%f adu): %f + (%f) * (log10(adu) - %f)",
1209  lolim, p0lo, p1lo, log10(lolim));
1210  cpl_msg_debug(__func__, "beyond high limit (%f adu): %f + (%f) * (log10(adu) - %f)",
1211  hilim, p0hi, p1hi, log10(hilim));
1212 #endif
1213 
1214  /* now loop through the full quadrant and correct the scaling */
1215  cpl_size *w = muse_quadrants_get_window(image, n);
1216  int i;
1217  for (i = w[0] - 1; i < w[1]; i++) {
1218  int j;
1219  for (j = w[2] - 1; j < w[3]; j++) {
1220  if (data[i + j*nx] <= 0) {
1221  continue; /* don't do anything for non-positive datapoints */
1222  }
1223  /* compute the percent-level deviation (applying to log10(adu)) */
1224  double pcor;
1225  if (data[i + j*nx] < lolim) {
1226  pcor = p0lo + p1lo * (log10(data[i + j*nx]) - log10(lolim));
1227  } else if (data[i + j*nx] > hilim) {
1228  pcor = p0hi + p1hi * (log10(data[i + j*nx]) - log10(hilim));
1229  } else {
1230  pcor = cpl_polynomial_eval_1d(poly, log10(data[i + j*nx]), NULL);
1231  }
1232  /* then derive the multiplicative correction factor */
1233  double fcor = 1. / (1. + pcor);
1234  data[i + j*nx] *= fcor;
1235  stat[i + j*nx] *= fcor*fcor;
1236  } /* for j (vertical pixels) */
1237  } /* for i (horizontal pixels) */
1238  cpl_free(w);
1239  cpl_polynomial_delete(poly);
1240  } /* for n (quadrants) */
1241  } /* for k (all images) */
1242  cpl_propertylist_delete(header);
1243 
1244  return rc;
1245 } /* muse_basicproc_corr_nonlinearity() */
1246 
1247 /*---------------------------------------------------------------------------*/
1263 /*---------------------------------------------------------------------------*/
1264 static cpl_error_code
1265 muse_basicproc_apply_dark(muse_imagelist *aList, muse_processing *aProcessing,
1266  unsigned char aIFU)
1267 {
1268  cpl_ensure_code(aList && aProcessing, CPL_ERROR_NULL_INPUT);
1269 
1270  cpl_frame *darkframe = muse_frameset_find_master(aProcessing->inframes,
1271  MUSE_TAG_MASTER_DARK, aIFU);
1272  cpl_errorstate prestate = cpl_errorstate_get();
1273  if (!darkframe) return CPL_ERROR_NONE;
1274  cpl_errorstate_set(prestate);
1275  const char *darkname = cpl_frame_get_filename(darkframe);
1276  muse_image *darkimage = muse_image_load(darkname);
1277  if (!darkimage) {
1278  char *errmsg = cpl_strdup(cpl_error_get_message());
1279  cpl_errorstate_set(prestate);
1280  darkimage = muse_image_load_from_extensions(darkname, aIFU);
1281  if (!darkimage) {
1282  cpl_msg_error(__func__, "%s", errmsg);
1283  cpl_msg_error(__func__, "%s", cpl_error_get_message());
1284  cpl_free(errmsg);
1285  cpl_frame_delete(darkframe);
1286  return cpl_error_get_code();
1287  } /* if 2nd load failure */
1288  cpl_free(errmsg);
1289  cpl_msg_info(__func__, "Dark correction in IFU %hhu using \"%s[CHAN%02hhu."
1290  "DATA]\"", aIFU, darkname, aIFU);
1291  } else {
1292  cpl_msg_info(__func__, "Dark correction in IFU %hhu using \"%s[DATA]\"",
1293  aIFU, darkname);
1294  }
1295  cpl_propertylist_append_string(darkimage->header, MUSE_HDR_TMP_FN, darkname);
1296 
1297  muse_processing_append_used(aProcessing, darkframe, CPL_FRAME_GROUP_CALIB, 0);
1298  cpl_error_code rc = CPL_ERROR_NONE;
1299  unsigned int k;
1300  for (k = 0; k < aList->size; k++) {
1301  muse_image *image = muse_imagelist_get(aList, k);
1302  rc = muse_basicproc_verify_setup(image, darkimage);
1303  if (rc != CPL_ERROR_NONE) {
1304  break;
1305  }
1306 
1307  /* duplicate the dark, because the scaling will destroy its normalization */
1308  muse_image *dark = muse_image_duplicate(darkimage);
1309  /* scale and subtract the dark by comparing exposure time *
1310  * of the dark and the other image */
1311  double scale = muse_pfits_get_exptime(image->header);
1312  if (muse_pfits_get_exptime(dark->header) > 0) {
1313  scale /= muse_pfits_get_exptime(dark->header);
1314  }
1315  rc = muse_image_scale(dark, scale);
1316  rc = muse_image_subtract(image, dark);
1317 
1318  muse_image_delete(dark);
1319  } /* for k (all images) */
1320  muse_image_delete(darkimage);
1321 
1322  return rc;
1323 } /* muse_basicproc_apply_dark() */
1324 
1325 /*---------------------------------------------------------------------------*/
1340 /*---------------------------------------------------------------------------*/
1341 static cpl_error_code
1342 muse_basicproc_apply_cr(muse_imagelist *aList,
1343  muse_basicproc_params *aBPars)
1344 {
1345  cpl_ensure_code(aList, CPL_ERROR_NULL_INPUT);
1346 
1347  /* if we didn't get cr parameters we were not supposed *
1348  * to find cosmic rays, so just return without error */
1349  cpl_boolean isdcr = aBPars && aBPars->crmethod
1350  && !strncmp(aBPars->crmethod, "dcr", 4);
1351  if (!isdcr) {
1352  return CPL_ERROR_NONE;
1353  }
1354 
1355  cpl_error_code rc = CPL_ERROR_NONE;
1356  unsigned int k;
1357  for (k = 0; k < aList->size; k++) {
1358  muse_image *image = muse_imagelist_get(aList, k);
1359  unsigned char ifu = muse_utils_get_ifu(image->header);
1360  int ncr = 0;
1361  ncr = muse_cosmics_dcr(image, aBPars->dcrxbox, aBPars->dcrybox,
1362  aBPars->dcrpasses, aBPars->dcrthres);
1363  if (ncr <= 0) {
1364  cpl_msg_error(__func__, "Cosmic ray rejection using DCR in IFU %hhu failed"
1365  " for image %u (ncr = %d): %s", ifu, k+1, ncr,
1366  cpl_error_get_message());
1367  rc = cpl_error_get_code();
1368  } else {
1369  cpl_msg_info(__func__, "Cosmic ray rejection using DCR in IFU %hhu found "
1370  "%d affected pixels in image %u", ifu, ncr, k+1);
1371  }
1372  } /* for k (all images) */
1373 
1374  return rc;
1375 } /* muse_basicproc_apply_cr() */
1376 
1377 /*---------------------------------------------------------------------------*/
1393 /*---------------------------------------------------------------------------*/
1394 static cpl_error_code
1395 muse_basicproc_apply_flat(muse_imagelist *aList, muse_processing *aProcessing,
1396  muse_basicproc_params *aBPars, unsigned char aIFU)
1397 {
1398  cpl_ensure_code(aList && aProcessing, CPL_ERROR_NULL_INPUT);
1399 
1400  cpl_frame *flatframe = muse_frameset_find_master(aProcessing->inframes,
1401  MUSE_TAG_MASTER_FLAT, aIFU);
1402  cpl_errorstate prestate = cpl_errorstate_get();
1403  if (!flatframe) return CPL_ERROR_NONE;
1404  cpl_errorstate_set(prestate);
1405  const char *flatname = cpl_frame_get_filename(flatframe);
1406  prestate = cpl_errorstate_get();
1407  muse_image *flatimage = muse_image_load(flatname);
1408  if (!flatimage) {
1409  char *errmsg = cpl_strdup(cpl_error_get_message());
1410  cpl_errorstate_set(prestate);
1411  flatimage = muse_image_load_from_extensions(flatname, aIFU);
1412  if (!flatimage) {
1413  cpl_msg_error(__func__, "%s", errmsg);
1414  cpl_msg_error(__func__, "%s", cpl_error_get_message());
1415  cpl_free(errmsg);
1416  cpl_frame_delete(flatframe);
1417  return cpl_error_get_code();
1418  } /* if 2nd load failure */
1419  cpl_free(errmsg);
1420  cpl_msg_info(__func__, "Flat-field correction in IFU %hhu using \"%s[CHAN%02hhu."
1421  "DATA]\"", aIFU, flatname, aIFU);
1422  } else {
1423  cpl_msg_info(__func__, "Flat-field correction in IFU %hhu using \"%s[DATA]\"",
1424  aIFU, flatname);
1425  }
1426  /* copy QC parameter containing integrated flux */
1427  double fflux = cpl_propertylist_get_double(flatimage->header,
1428  QC_FLAT_MASTER_INTFLUX);
1429  cpl_propertylist_append_string(flatimage->header, MUSE_HDR_TMP_FN, flatname);
1430  muse_processing_append_used(aProcessing, flatframe, CPL_FRAME_GROUP_CALIB, 0);
1431 
1432  cpl_error_code rc = CPL_ERROR_NONE;
1433  unsigned int k;
1434  for (k = 0; k < aList->size; k++) {
1435  cpl_msg_debug(__func__, "Flat-field division in IFU %hhu of image %u of %u",
1436  aIFU, k+1, aList->size);
1437  muse_image *image = muse_imagelist_get(aList, k);
1438  rc = muse_basicproc_verify_setup(image, flatimage);
1439  if (rc != CPL_ERROR_NONE) {
1440  break;
1441  }
1442  rc = muse_image_divide(image, flatimage);
1443  cpl_propertylist_update_double(image->header, MUSE_HDR_FLAT_FLUX_LAMP, fflux);
1444  } /* for k (all images) */
1445 
1446  if (aBPars && aBPars->keepflat) {
1447  aBPars->flatimage = flatimage;
1448  } else {
1449  muse_image_delete(flatimage);
1450  }
1451  return rc;
1452 } /* muse_basicproc_apply_flat() */
1453 
1454 /*---------------------------------------------------------------------------*/
1475 /*---------------------------------------------------------------------------*/
1476 static muse_imagelist *
1477 muse_basicproc_load_raw(muse_processing *aProcessing, unsigned char aIFU)
1478 {
1479  cpl_ensure(aProcessing, CPL_ERROR_NULL_INPUT, NULL);
1480 
1481  /* rawframes contains the list of input files that we want to load */
1482  cpl_frameset *rawframes = muse_frameset_check_raw(aProcessing->inframes,
1483  aProcessing->intags, aIFU);
1484  cpl_ensure(rawframes, CPL_ERROR_NULL_INPUT, NULL);
1485 
1486  muse_imagelist *images = muse_imagelist_new();
1487  unsigned int k = 0;
1488  cpl_size iframe, nframes = cpl_frameset_get_size(rawframes);
1489  for (iframe = 0; iframe < nframes; iframe++) {
1490  cpl_frame *frame = cpl_frameset_get_position(rawframes, iframe);
1491  const char *fileName = cpl_frame_get_filename(frame);
1492  int extension = muse_utils_get_extension_for_ifu(fileName, aIFU);
1493  if (extension == -1) {
1494  cpl_msg_error(__func__, "\"%s\" does not contain data from IFU %hhu",
1495  fileName, aIFU);
1496  break;
1497  }
1498  muse_image *raw = muse_image_load_from_raw(fileName, extension);
1499  if (!raw) {
1500  continue;
1501  }
1502  /* add temporary input filename for diagnostics */
1503  cpl_propertylist_append_string(raw->header, MUSE_HDR_TMP_FN, fileName);
1504  /* add temporary input tag, for use when deriving the output tag */
1505  cpl_propertylist_append_string(raw->header, MUSE_HDR_TMP_INTAG,
1506  cpl_frame_get_tag(frame));
1507 
1508  muse_imagelist_set(images, raw, k);
1509  muse_processing_append_used(aProcessing, frame, CPL_FRAME_GROUP_RAW, 1);
1510  k++;
1511  } /* for frame (all rawframes) */
1512  cpl_frameset_delete(rawframes);
1513 
1514  /* some checks if we ended up with a valid imagelist */
1515  if (!images->size) {
1516  if ((int)cpl_error_get_code() != MUSE_ERROR_CHIP_NOT_LIVE) {
1517  cpl_error_set(__func__, CPL_ERROR_ILLEGAL_OUTPUT);
1518  cpl_msg_error(__func__, "No raw images loaded for IFU %hhu", aIFU);
1519  }
1520  muse_imagelist_delete(images); /* still free the structure */
1521  return NULL;
1522  }
1523  if (muse_imagelist_is_uniform(images) != 0) {
1524  cpl_error_set(__func__, CPL_ERROR_ILLEGAL_OUTPUT);
1525  cpl_msg_error(__func__, "Non-uniform imagelist for IFU %hhu", aIFU);
1526  muse_imagelist_delete(images);
1527  return NULL;
1528  }
1529 
1530  return images;
1531 } /* muse_basicproc_load_raw() */
1532 
1533 /*---------------------------------------------------------------------------*/
1576 /*---------------------------------------------------------------------------*/
1578 muse_basicproc_load(muse_processing *aProcessing, unsigned char aIFU,
1579  muse_basicproc_params *aBPars)
1580 {
1581  if (muse_processing_check_input(aProcessing, aIFU) != CPL_ERROR_NONE) {
1582  return NULL;
1583  }
1584  muse_imagelist *images = muse_basicproc_load_raw(aProcessing, aIFU);
1585  if (!images) {
1586  return NULL;
1587  }
1588  cpl_errorstate prestate = cpl_errorstate_get();
1589  if (muse_basicproc_apply_badpix(images, aProcessing, aIFU) != CPL_ERROR_NONE) {
1590  cpl_msg_warning(__func__, "Applying bad pixel table to IFU %hhu failed: %s",
1591  aIFU, cpl_error_get_message());
1592  cpl_errorstate_set(prestate); /* this is not critical, continue */
1593  }
1594  if (muse_basicproc_check_saturation(images) != CPL_ERROR_NONE) {
1595  muse_imagelist_delete(images);
1596  return NULL;
1597  }
1598  muse_basicproc_quadrant_statistics(images, aProcessing); /* non-fatal */
1599  if (muse_basicproc_overscans_compute_stats(images, aBPars) /* incl. CR rejection */
1600  != CPL_ERROR_NONE) {
1601  muse_imagelist_delete(images); /* this failure should be fatal */
1602  return NULL;
1603  }
1604  if (muse_basicproc_correct_overscans_vpoly(images, aBPars)
1605  != CPL_ERROR_NONE) {
1606  muse_imagelist_delete(images); /* this failures should be fatal! */
1607  return NULL;
1608  }
1609  if (muse_basicproc_trim_images(images) != CPL_ERROR_NONE) {
1610  muse_imagelist_delete(images);
1611  return NULL;
1612  }
1613  if (muse_basicproc_correct_overscans_offset(images, aProcessing, aBPars)
1614  != CPL_ERROR_NONE) { /* for BIAS files only */
1615  cpl_msg_warning(__func__, "Bias-level correction using overscans failed in "
1616  "IFU %hhu: %s", aIFU, cpl_error_get_message());
1617  }
1618  if (muse_basicproc_check_overscans(images, aProcessing, aBPars)
1619  != CPL_ERROR_NONE) { /* only for BIAS files and when overscan==none */
1620  muse_imagelist_delete(images);
1621  return NULL;
1622  }
1623  muse_basicproc_gain_override(images, aProcessing, aIFU);
1624  muse_basicproc_check_gain(images, aProcessing, aIFU); /* for flats */
1625  if (muse_basicproc_apply_bias(images, aProcessing, aIFU, aBPars)
1626  != CPL_ERROR_NONE) {
1627  muse_imagelist_delete(images);
1628  return NULL;
1629  }
1630  if (muse_basicproc_corr_nonlinearity(images, aProcessing, aIFU) != CPL_ERROR_NONE) {
1631  muse_imagelist_delete(images);
1632  return NULL;
1633  }
1634  if (muse_basicproc_adu_to_count(images, aProcessing) != CPL_ERROR_NONE) {
1635  muse_imagelist_delete(images);
1636  return NULL;
1637  }
1638  if (muse_basicproc_apply_dark(images, aProcessing, aIFU) != CPL_ERROR_NONE) {
1639  muse_imagelist_delete(images);
1640  return NULL;
1641  }
1642  if (muse_basicproc_apply_cr(images, aBPars) != CPL_ERROR_NONE) {
1643  muse_imagelist_delete(images);
1644  return NULL;
1645  }
1646  if (muse_basicproc_apply_flat(images, aProcessing, aBPars, aIFU) != CPL_ERROR_NONE) {
1647  muse_imagelist_delete(images);
1648  return NULL;
1649  }
1650  return images;
1651 } /* muse_basicproc_load() */
1652 
1653 /*---------------------------------------------------------------------------*/
1666 /*---------------------------------------------------------------------------*/
1668 muse_basicproc_load_reduced(muse_processing *aProcessing, unsigned char aIFU)
1669 {
1670  muse_imagelist *images = muse_imagelist_new();
1671  cpl_frameset *redframes = muse_frameset_find_tags(aProcessing->inframes,
1672  aProcessing->intags,
1673  aIFU, CPL_FALSE);
1674  cpl_size iframe, nframes = cpl_frameset_get_size(redframes);
1675  for (iframe = 0; iframe < nframes; iframe++) {
1676  cpl_frame *frame = cpl_frameset_get_position(redframes, iframe);
1677  cpl_errorstate prestate = cpl_errorstate_get();
1678  const char *imagename = cpl_frame_get_filename(frame);
1679  muse_image *image = muse_image_load(imagename);
1680  if (!image) {
1681  cpl_errorstate_set(prestate);
1682  image = muse_image_load_from_extensions(imagename, aIFU);
1683  }
1684  muse_imagelist_set(images, image, iframe);
1685  muse_processing_append_used(aProcessing, frame, CPL_FRAME_GROUP_RAW, 1);
1686  } /* for iframe (all used frames) */
1687  cpl_frameset_delete(redframes);
1688  return images;
1689 } /* muse_basicproc_load_reduced() */
1690 
1691 /*---------------------------------------------------------------------------*/
1706 /*---------------------------------------------------------------------------*/
1707 static cpl_table *
1708 muse_basicproc_prepare_illum(muse_pixtable *aPT)
1709 {
1710  cpl_ensure(aPT && aPT->header && aPT->table,
1711  CPL_ERROR_NULL_INPUT, NULL);
1712 
1713  /* crop pixel table to small wavelength range *
1714  * and separate into per-slice tables */
1715  muse_pixtable_restrict_wavelength(aPT, 6500., 7500.);
1717  int ipt, npt = muse_pixtable_extracted_get_size(pts);
1718 
1719  unsigned char ifu = muse_utils_get_ifu(aPT->header);
1720  cpl_msg_info(__func__, "Preparing %s flat: %d slices in the data of IFU %hhu "
1721  "found.", MUSE_TAG_ILLUM, npt, ifu);
1722  cpl_table *tattached = cpl_table_new(npt);
1723  cpl_table_new_column(tattached, "slice", CPL_TYPE_INT);
1724  cpl_table_new_column(tattached, "fflat", CPL_TYPE_DOUBLE);
1725  for (ipt = 0; ipt < npt; ipt++) {
1726  uint32_t origin = cpl_table_get_int(pts[ipt]->table, MUSE_PIXTABLE_ORIGIN, 0, NULL);
1727  unsigned short slice = muse_pixtable_origin_get_slice(origin);
1728  double median = cpl_table_get_column_median(pts[ipt]->table,
1730  cpl_msg_debug(__func__, "Found median of %f in slice %d of IFU %hhu "
1731  "of illum flat.", median, slice, ifu);
1732  cpl_table_set_int(tattached, "slice", ipt, slice);
1733  cpl_table_set_double(tattached, "fflat", ipt, 1. / median);
1734  } /* for ipt */
1736  /* normalize the flat-field scales */
1737  double mean = cpl_table_get_column_mean(tattached, "fflat");
1738  cpl_msg_debug(__func__, "Normalizing whole illum-flat table if IFU %hhu to "
1739  "%e.", ifu, mean);
1740  cpl_table_multiply_scalar(tattached, "fflat", 1. / mean);
1741  cpl_table_set_column_format(tattached, "fflat", "%.6f");
1742  return tattached;
1743 } /* muse_basicproc_prepare_illum() */
1744 
1745 /*---------------------------------------------------------------------------*/
1763 /*---------------------------------------------------------------------------*/
1764 cpl_table *
1765 muse_basicproc_get_illum(muse_imagelist *aImages, cpl_table *aTrace,
1766  cpl_table *aWave, cpl_table *aGeo)
1767 {
1768  cpl_ensure(aImages && aTrace && aWave && aGeo, CPL_ERROR_NULL_INPUT, NULL);
1769 
1770  cpl_table *tattached = NULL;
1771  unsigned int k, nimages = muse_imagelist_get_size(aImages);
1772  /* also create list of illum exposures to be able to erase them at the end */
1773  cpl_boolean *isillum = cpl_calloc(nimages, sizeof(cpl_boolean));
1774  for (k = 0; k < nimages; k++) {
1775  isillum[k] = CPL_FALSE;
1776  muse_image *image = muse_imagelist_get(aImages, k);
1777  const char *tag = cpl_propertylist_get_string(image->header,
1778  MUSE_HDR_TMP_INTAG);
1779  if (tag && !strncmp(tag, MUSE_TAG_ILLUM, strlen(MUSE_TAG_ILLUM) + 1)) {
1780  isillum[k] = CPL_TRUE; /* is an attached FLAT,ILLUM */
1781  /* also verify the template ID */
1782  if (cpl_propertylist_has(image->header, "ESO TPL ID")) {
1783  const char *tplid = cpl_propertylist_get_string(image->header,
1784  "ESO TPL ID"),
1785  *fn = cpl_propertylist_get_string(image->header,
1786  MUSE_HDR_TMP_FN),
1787  *tplatt = "MUSE_wfm_cal_specflatatt",
1788  *tplill = "MUSE_wfm_cal_illum",
1789  *tpliln = "MUSE_nfm_cal_illum";
1790  if (strncmp(tplid, tplatt, strlen(tplatt) + 1) &&
1791  strncmp(tplid, tplill, strlen(tplill) + 1) &&
1792  strncmp(tplid, tpliln, strlen(tpliln) + 1)) {
1793  cpl_msg_warning(__func__, "%s input (\"%s\") was taken with neither"
1794  " %s nor %s template, but %s!", MUSE_TAG_ILLUM, fn,
1795  tplatt, tplill, tplid);
1796  } else {
1797  cpl_msg_debug(__func__, "%s input (\"%s\") was taken with template "
1798  "%s", MUSE_TAG_ILLUM, fn, tplid);
1799  } /* else */
1800  } /* if TPL.ID present */
1801  } /* if */
1802  unsigned char ifu = muse_utils_get_ifu(image->header);
1803  if (isillum[k]) {
1804  if (tattached) {
1805  cpl_msg_warning(__func__, "Image %u of %u of IFU %hhu is illum flat, "
1806  "but not the first; not using it!", k + 1, nimages, ifu);
1807  continue;
1808  }
1809  cpl_msg_debug(__func__, "Image %u of %u of IFU %hhu is illum flat.",
1810  k + 1, nimages, ifu);
1811  muse_pixtable *pt = muse_pixtable_create(image, aTrace, aWave, aGeo);
1812  tattached = muse_basicproc_prepare_illum(pt);
1814  } else {
1815  cpl_msg_debug(__func__, "Image %u of %u of IFU %hhu is not an illum flat.",
1816  k + 1, nimages, ifu);
1817  }
1818  } /* for k */
1819 
1820  /* remove the ILLUM image(s) from the image list */
1821  unsigned int k2;
1822  for (k = 0, k2 = 0; k < nimages; k++) {
1823  if (isillum[k]) {
1824  muse_image *image = muse_imagelist_unset(aImages, k2);
1825  muse_image_delete(image);
1826  } else {
1827  k2++; /* only step, if the image was not removed */
1828  }
1829  } /* for k, k2 */
1830  cpl_free(isillum);
1831 
1832  return tattached;
1833 } /* muse_basicproc_get_illum() */
1834 
1835 /*---------------------------------------------------------------------------*/
1848 /*---------------------------------------------------------------------------*/
1849 cpl_error_code
1850 muse_basicproc_apply_illum(muse_pixtable *aPT, cpl_table *aAttached)
1851 {
1852  cpl_ensure_code(aPT && aPT->header && aPT->table && aAttached,
1853  CPL_ERROR_NULL_INPUT);
1854 
1855  unsigned char ifu = muse_utils_get_ifu(aPT->header);
1856 
1858  int ipt, npt = muse_pixtable_extracted_get_size(pts);
1859  cpl_msg_info(__func__, "Applying %s flat-field in IFU %hhu (%d slices)",
1860  MUSE_TAG_ILLUM, ifu, npt);
1861  cpl_array *afactors = cpl_array_new(npt, CPL_TYPE_DOUBLE);
1862  for (ipt = 0; ipt < npt; ipt++) {
1863  uint32_t origin = cpl_table_get_int(pts[ipt]->table, MUSE_PIXTABLE_ORIGIN, 0, NULL);
1864  unsigned short slice = muse_pixtable_origin_get_slice(origin),
1865  fslice = cpl_table_get_int(aAttached, "slice", ipt, NULL);
1866  int err;
1867  double fflat = cpl_table_get_double(aAttached, "fflat", ipt, &err);
1868  if (!err && slice == fslice) {
1869  cpl_table_multiply_scalar(pts[ipt]->table, MUSE_PIXTABLE_DATA, fflat);
1870  cpl_table_multiply_scalar(pts[ipt]->table, MUSE_PIXTABLE_STAT, fflat*fflat);
1871  cpl_array_set_double(afactors, ipt, fflat);
1872  char *kw = cpl_sprintf(MUSE_HDR_PT_ILLUMi, slice);
1873  cpl_propertylist_update_double(aPT->header, kw, fflat);
1874  cpl_free(kw);
1875  } else {
1876  cpl_msg_warning(__func__, "some error (%d) occurred when applying illum-"
1877  "flat correction to slice %hu/%hu of IFU %hhu: %s", err,
1878  slice, fslice, ifu, cpl_error_get_message());
1879  } /* else */
1880  } /* for ipt */
1882  cpl_propertylist_update_double(aPT->header, MUSE_HDR_PT_ILLUM_MEAN,
1883  cpl_array_get_mean(afactors));
1884  cpl_propertylist_update_double(aPT->header, MUSE_HDR_PT_ILLUM_STDEV,
1885  cpl_array_get_stdev(afactors));
1886  cpl_array_delete(afactors);
1887  return CPL_ERROR_NONE;
1888 } /* muse_basicproc_apply_illum() */
1889 
1890 /*---------------------------------------------------------------------------*/
1907 /*---------------------------------------------------------------------------*/
1908 cpl_error_code
1910 {
1911  cpl_ensure_code(aPT && aPT->header && aPT->table && aTwilight,
1912  CPL_ERROR_NULL_INPUT);
1913 
1914  // XXX should check, if the twilight cube is of the same INS.MODE as the data
1915 
1916  unsigned char ifu = muse_utils_get_ifu(aPT->header);
1917 
1918  /* transfer the sky flat flux value */
1919  char *kw = cpl_sprintf(MUSE_HDR_FLAT_FLUX_SKY"%hhu", ifu);
1920  double flux = cpl_propertylist_get_double(aTwilight->header, kw);
1921  cpl_free(kw);
1922  cpl_propertylist_update_double(aPT->header, MUSE_HDR_FLAT_FLUX_SKY, flux);
1923 
1924  /* get the WCS from the twilight cube */
1925  int nx = cpl_image_get_size_x(cpl_imagelist_get(aTwilight->data, 0)),
1926  ny = cpl_image_get_size_y(cpl_imagelist_get(aTwilight->data, 0)),
1927  nz = cpl_imagelist_get_size(aTwilight->data);
1928  cpl_msg_debug(__func__, "Working with %d planes in twilight cube", nz);
1929  double cd12 = muse_pfits_get_cd(aTwilight->header, 1, 2),
1930  cd21 = muse_pfits_get_cd(aTwilight->header, 2, 1);
1931  if (cd12 > DBL_EPSILON || cd21 > DBL_EPSILON) {
1932  cpl_msg_warning(__func__, "Twilight cube contains WCS cross-terms (CD1_2"
1933  "=%e, CD2_1=%e), results will be inaccurate!", cd12, cd21);
1934  }
1935  // XXX guard against more rubbish (CTYPEi, CUNITi, cross-terms with axis3
1936  double crval1 = muse_pfits_get_crval(aTwilight->header, 1),
1937  crpix1 = muse_pfits_get_crpix(aTwilight->header, 1),
1938  cd11 = muse_pfits_get_cd(aTwilight->header, 1, 1),
1939  crval2 = muse_pfits_get_crval(aTwilight->header, 2),
1940  crpix2 = muse_pfits_get_crpix(aTwilight->header, 2),
1941  cd22 = muse_pfits_get_cd(aTwilight->header, 2, 2),
1942  crval3 = muse_pfits_get_crval(aTwilight->header, 3),
1943  crpix3 = muse_pfits_get_crpix(aTwilight->header, 3),
1944  cd33 = muse_pfits_get_cd(aTwilight->header, 3, 3);
1945 
1946  /* loop through the pixel table and apply the correction */
1947  float *data = cpl_table_get_data_float(aPT->table, MUSE_PIXTABLE_DATA),
1948  *stat = cpl_table_get_data_float(aPT->table, MUSE_PIXTABLE_STAT),
1949  *xpos = cpl_table_get_data_float(aPT->table, MUSE_PIXTABLE_XPOS),
1950  *ypos = cpl_table_get_data_float(aPT->table, MUSE_PIXTABLE_YPOS),
1951  *lbda = cpl_table_get_data_float(aPT->table, MUSE_PIXTABLE_LAMBDA);
1952  cpl_size irow, nrow = muse_pixtable_get_nrow(aPT),
1953  nfailed = 0;
1954  for (irow = 0; irow < nrow; irow++) {
1955  /* find closest spatial pixel in twilight cube *
1956  * using the coordinates from the pixel table */
1957  int x = lround((xpos[irow] - crval1) / cd11 + crpix1), /* nearest neighbor */
1958  y = lround((ypos[irow] - crval2) / cd22 + crpix2); /* nearest neighbor */
1959  /* boundary conditions */
1960  if (x < 1) {
1961  x = 1;
1962  }
1963  if (x > nx) {
1964  x = nx;
1965  }
1966  if (y < 1) {
1967  y = 1;
1968  }
1969  if (y > ny) {
1970  y = ny;
1971  }
1972  double z = (lbda[irow] - crval3) / cd33 + crpix3; /* plane */
1973 #if 0
1974  cpl_msg_debug(__func__, "%"CPL_SIZE_FORMAT": %.3f %.3f %.3f => %d %d %.3f",
1975  irow, xpos[irow], ypos[irow], lbda[irow], x, y, z);
1976 #endif
1977  /* get indices of the two closest image planes for linear interpolation */
1978  int zp1 = floor(z) - 1,
1979  zp2 = ceil(z) - 1;
1980  /* boundary conditions */
1981  if (zp1 < 1) {
1982  zp1 = 0;
1983  }
1984  if (zp1 >= nz) {
1985  zp1 = nz - 1;
1986  }
1987  if (zp2 < 1) {
1988  zp2 = 0;
1989  }
1990  if (zp2 >= nz) {
1991  zp2 = nz - 1;
1992  }
1993  int err1, err2;
1994  double v1 = cpl_image_get(cpl_imagelist_get(aTwilight->data, zp1),
1995  x, y, &err1),
1996  v2 = cpl_image_get(cpl_imagelist_get(aTwilight->data, zp2),
1997  x, y, &err2);
1998  double villum = 1.;
1999  double f = 1.;
2000  /* linearly interpolate the given twilight factors from both planes */
2001  if (err1 && err2) {
2002  nfailed++;
2003  continue;
2004  }
2005  if (zp1 == zp2) {
2006  villum = v1; /* same planes, just take the first value */
2007  } else if (err1) {
2008  villum = v2;
2009  } else if (err2) {
2010  villum = v1;
2011  } else { /* real interpolation */
2012  f = fabs(z - 1 - zp1);
2013  villum = v1 * (1. - f) + v2 * f;
2014  }
2015  double fillum = 1. / villum; /* the inverse as correction factor */
2016 #if 0
2017  cpl_msg_debug(__func__, "%d/%d, %f/%f -> %f -> %f => %f", zp1, zp2, v1, v2,
2018  f, villum, fillum);
2019 #endif
2020 
2021  /* multiply the data value by the inverse twilight factor */
2022  data[irow] *= fillum;
2023  /* multiply the stat value by the squared inverse twilight factor */
2024  stat[irow] *= fillum*fillum;
2025  } /* for irow (all pixel table rows) */
2026  if (nfailed) {
2027  cpl_msg_warning(__func__, "Failed to correct twilight in %"CPL_SIZE_FORMAT
2028  " of %"CPL_SIZE_FORMAT", pixels in IFU %hhu!", nfailed,
2029  nrow, ifu);
2030  } else {
2031  cpl_msg_debug(__func__, "No failures during twilight correction of %"
2032  CPL_SIZE_FORMAT" pixels in IFU %hhu", nrow, ifu);
2033  }
2034 
2035  return CPL_ERROR_NONE;
2036 } /* muse_basicproc_apply_twilight() */
2037 
2038 /*----------------------------------------------------------------------------*/
2056 /*----------------------------------------------------------------------------*/
2057 cpl_error_code
2059 {
2060  cpl_ensure_code(aPT && aPT->header && aPT->table, CPL_ERROR_NULL_INPUT);
2061 
2062  /* for the moment set values for [WFM-AO-N] (Na2 filter) upfront */
2063  float lmin = kMuseNa2LambdaMin,
2064  lmax = kMuseNa2LambdaMax;
2065  muse_ins_mode insmode = muse_pfits_get_mode(aPT->header);
2066  const char *mode = muse_pfits_get_insmode(aPT->header);
2067  if (insmode == MUSE_MODE_WFM_AO_N) {
2068  /* nothing to be done */
2069  } else if (insmode == MUSE_MODE_WFM_AO_E) {
2070  lmin = kMuseNaLambdaMin;
2071  lmax = kMuseNaLambdaMax;
2072  } else if (insmode == MUSE_MODE_NFM_AO_N) {
2073  lmin = kMuseNaGLambdaMin;
2074  lmax = kMuseNaGLambdaMax;
2075  } else {
2076  cpl_msg_warning(__func__, "No notch filter for mode %s!", mode);
2077  return CPL_ERROR_ILLEGAL_INPUT;
2078  }
2079  cpl_msg_info(__func__, "%s mode: marking NaD region (%.1f..%.1f Angstrom) of "
2080  "IFU %d as 0x%08lx", mode, lmin, lmax, aIFU, EURO3D_NOTCH_NAD);
2081  cpl_table_unselect_all(aPT->table);
2082  cpl_table_or_selected_float(aPT->table, MUSE_PIXTABLE_LAMBDA,
2083  CPL_GREATER_THAN, lmin);
2084  cpl_table_and_selected_float(aPT->table, MUSE_PIXTABLE_LAMBDA,
2085  CPL_LESS_THAN, lmax);
2086  cpl_array *asel = cpl_table_where_selected(aPT->table);
2087  cpl_size isel, nsel = cpl_array_get_size(asel);
2088  const cpl_size *sel = cpl_array_get_data_cplsize_const(asel);
2089  int *dq = cpl_table_get_data_int(aPT->table, MUSE_PIXTABLE_DQ);
2090  for (isel = 0; isel < nsel; isel++) {
2091  dq[sel[isel]] = EURO3D_NOTCH_NAD;
2092  } /* for isel (all selected table rows) */
2093  cpl_array_delete(asel);
2094 
2095  return CPL_ERROR_NONE;
2096 } /* muse_basicproc_mask_notch_filter() */
2097 
2098 /*----------------------------------------------------------------------------*/
2124 /*----------------------------------------------------------------------------*/
2125 static int
2126 muse_basicproc_combine_compare_lamp(const cpl_frame *aFrame1, const cpl_frame *aFrame2)
2127 {
2128  cpl_ensure(aFrame1 && aFrame2, CPL_ERROR_NULL_INPUT, -1);
2129  const char *fn1 = cpl_frame_get_filename(aFrame1),
2130  *fn2 = cpl_frame_get_filename(aFrame2);
2131  cpl_propertylist *head1 = cpl_propertylist_load(fn1, 0),
2132  *head2 = cpl_propertylist_load(fn2, 0);
2133  if (!head1 || !head2) {
2134  cpl_propertylist_delete(head1); /* in case one was loaded... */
2135  cpl_propertylist_delete(head2);
2136  return -1;
2137  }
2138 
2139  /* Loop through all lamps in the header and find their status. The first *
2140  * missing shutter entry will cause the FITS query to throw an error, that's *
2141  * when we stop. Otherwise, we are done when the lamp status is not equal. */
2142  int nlamp = 1, status1, status2;
2143  cpl_errorstate prestate = cpl_errorstate_get();
2144  do {
2145  /* ensure that we are dealing with the same lamps! */
2146  const char *name1 = muse_pfits_get_lamp_name(head1, nlamp),
2147  *name2 = muse_pfits_get_lamp_name(head2, nlamp);
2148  cpl_errorstate_set(prestate); /* lamps may be missing */
2149  if (name1 && name2 && strncmp(name1, name2, strlen(name1) + 1)) {
2150  cpl_error_set_message(__func__, CPL_ERROR_INCOMPATIBLE_INPUT,
2151  "Files \"%s\" and \"%s\" have incompatible lamp "
2152  "setups", fn1, fn2);
2153  cpl_propertylist_delete(head1);
2154  cpl_propertylist_delete(head2);
2155  return -1;
2156  }
2157  name1 = muse_pfits_get_shut_name(head1, nlamp);
2158  name2 = muse_pfits_get_shut_name(head2, nlamp);
2159  if (name1 && name2 && strncmp(name1, name2, strlen(name1) + 1)) {
2160  cpl_error_set_message(__func__, CPL_ERROR_INCOMPATIBLE_INPUT,
2161  "Files \"%s\" and \"%s\" have incompatible shutter "
2162  "setups", fn1, fn2);
2163  cpl_propertylist_delete(head1);
2164  cpl_propertylist_delete(head2);
2165  return -1;
2166  }
2167 
2168  status1 = muse_pfits_get_lamp_status(head1, nlamp);
2169  status2 = muse_pfits_get_lamp_status(head2, nlamp);
2170  cpl_errorstate_set(prestate); /* lamps may be missing */
2171  if (status1 != status2) {
2172  break;
2173  }
2174  status1 = muse_pfits_get_shut_status(head1, nlamp);
2175  status2 = muse_pfits_get_shut_status(head2, nlamp);
2176  if (status1 != status2) {
2177  break;
2178  }
2179  nlamp++;
2180  } while (cpl_errorstate_is_equal(prestate));
2181  cpl_errorstate_set(prestate);
2182 
2183  cpl_propertylist_delete(head1);
2184  cpl_propertylist_delete(head2);
2185  return status1 == status2;
2186 } /* muse_basicproc_combine_compare_lamp() */
2187 
2188 /*---------------------------------------------------------------------------*/
2214 /*---------------------------------------------------------------------------*/
2217  unsigned char aIFU,
2218  muse_basicproc_params *aBPars,
2219  cpl_frameset ***aLabeledFrames)
2220 {
2221  if (aLabeledFrames) { /* NULL out return pointer, in case it's given... */
2222  *aLabeledFrames = NULL; /* ... so it's always NULL in case of problems */
2223  }
2224  cpl_ensure(aProcessing, CPL_ERROR_NULL_INPUT, NULL);
2225 
2226  /* find out different lamps in input */
2227  cpl_frameset *rawframes = muse_frameset_find_tags(aProcessing->inframes,
2228  aProcessing->intags, aIFU,
2229  CPL_FALSE);
2230  char *prefix = cpl_sprintf("muse.%s", aProcessing->name);
2231  muse_combinepar *cpars = muse_combinepar_new(aProcessing->parameters,
2232  prefix);
2233  cpl_free(prefix);
2234 #if 0
2235  printf("rawframes\n");
2236  cpl_frameset_dump(rawframes, stdout);
2237  fflush(stdout);
2238 #endif
2239  cpl_size nlabels,
2240  *labels = cpl_frameset_labelise(rawframes,
2241  muse_basicproc_combine_compare_lamp,
2242  &nlabels);
2243  if (!labels || nlabels <= 1) {
2244  /* if labeling didn't work, process the list of one lamp and return */
2245  cpl_free(labels);
2246  cpl_frameset_delete(rawframes);
2247  muse_imagelist *list = muse_basicproc_load(aProcessing, aIFU, aBPars),
2248  *images = NULL;
2249  if (nlabels == 1) {
2250  muse_image *image = muse_combine_images(cpars, list);
2251  images = muse_imagelist_new();
2252  muse_imagelist_set(images, image, 0);
2253  if (aLabeledFrames) {
2254  *aLabeledFrames = cpl_calloc(1, sizeof(cpl_frameset *));
2255  (*aLabeledFrames)[0] = cpl_frameset_duplicate(aProcessing->usedframes);
2256  } /* if */
2257  } /* if only one label */
2258  muse_imagelist_delete(list);
2259  muse_combinepar_delete(cpars);
2260  return images;
2261  } /* if one of no labels */
2262 
2263 #if 0
2264  cpl_array *alabels = cpl_array_wrap_int(labels, cpl_frameset_get_size(rawframes));
2265  cpl_array_dump(alabels, 0, 1000, stdout);
2266  fflush(stdout);
2267  cpl_array_unwrap(alabels);
2268 #endif
2269  /* output list of lampwise combined images */
2270  muse_imagelist *images = muse_imagelist_new();
2271  if (aLabeledFrames) {
2272  *aLabeledFrames = cpl_calloc(nlabels, sizeof(cpl_frameset *));
2273  }
2274 
2275  /* duplicate aProcessing into a local structure the contents of which *
2276  * we can manipulate here (don't change it directly for threadsafety!) */
2277  muse_processing *proc = cpl_malloc(sizeof(muse_processing));
2278  memcpy(proc, aProcessing, sizeof(muse_processing));
2279  cpl_frameset *inframes = proc->inframes;
2280  /* copy frames with all extra frames somewhere else */
2281  cpl_frameset *auxframes = muse_frameset_find_tags(inframes, aProcessing->intags,
2282  aIFU, CPL_TRUE);
2283  /* loop through labels for all lamps */
2284  int ilabel, ipos = 0;
2285  for (ilabel = 0; ilabel < nlabels; ilabel++) {
2286  /* create new sub-frameset for this lamp */
2287  cpl_frameset *frames = cpl_frameset_extract(rawframes, labels, ilabel);
2288  /* append other files for the initial processing */
2289  cpl_frameset_join(frames, auxframes);
2290  /* substitute aProcessing->inframes */
2291  proc->inframes = frames;
2292  /* load and combine frames for this sub-frameset */
2293  muse_imagelist *list = muse_basicproc_load(proc, aIFU, aBPars);
2294  /* reinstate original aProcessing->inframes */
2295  proc->inframes = inframes;
2296  if (!list) { /* break this loop to fail the function below */
2297  muse_imagelist_delete(images);
2298  cpl_frameset_delete(frames);
2299  images = NULL;
2300  /* if muse_basicproc_load() fails then because of some missing *
2301  * calibration, and then it will already fail for the first *
2302  * ilabel; it is therefore enough to free the pointer */
2303  if (aLabeledFrames) {
2304  cpl_free(*aLabeledFrames);
2305  *aLabeledFrames = NULL;
2306  }
2307  break;
2308  }
2309 
2310  muse_image *lampimage = muse_combine_images(cpars, list);
2311  if (!lampimage) {
2312  cpl_msg_error(__func__, "Image combination failed for IFU %hhu for lamp "
2313  "with label %d of %"CPL_SIZE_FORMAT, aIFU, ilabel + 1, nlabels);
2314  muse_imagelist_delete(list);
2315  cpl_frameset_delete(frames);
2316  continue;
2317  }
2318 
2319  if (aLabeledFrames) {
2320  /* if a given frame was used now, copy its group */
2321  cpl_size iframe, nframes = cpl_frameset_get_size(frames);
2322  for (iframe = 0; iframe < nframes; iframe++) {
2323  cpl_frame *frame = cpl_frameset_get_position(frames, iframe);
2324  const char *fn = cpl_frame_get_filename(frame),
2325  *tag = cpl_frame_get_tag(frame);
2326  cpl_size iuframe, nuframes = cpl_frameset_get_size(aProcessing->usedframes);
2327  for (iuframe = 0;
2328  (iuframe < nuframes) && fn && tag; /* only check with valid info */
2329  iuframe++) {
2330  cpl_frame *uframe = cpl_frameset_get_position(aProcessing->usedframes,
2331  iuframe);
2332  const char *fnu = cpl_frame_get_filename(uframe),
2333  *tagu = cpl_frame_get_tag(uframe);
2334  if (fnu && !strncmp(fn, fnu, strlen(fn) + 1) &&
2335  tagu && !strncmp(tag, tagu, strlen(tag) + 1)) {
2336  cpl_frame_set_group(frame, cpl_frame_get_group(uframe));
2337  break;
2338  }
2339  } /* for uframe (all usedframes) */
2340  } /* for frame */
2341  (*aLabeledFrames)[ipos] = frames;
2342  } else {
2343  cpl_frameset_delete(frames);
2344  }
2345 
2346  /* transfer NSATURATION headers from invidual images to lamp-combined image */
2347  unsigned int k;
2348  for (k = 0; k < muse_imagelist_get_size(list); k++) {
2349  char *keyword = cpl_sprintf(QC_WAVECAL_PREFIXi" "QC_BASIC_NSATURATED, k+1);
2350  int nsaturated = cpl_propertylist_get_int(muse_imagelist_get(list, k)->header,
2351  MUSE_HDR_TMP_NSAT);
2352  cpl_propertylist_update_int(lampimage->header, keyword, nsaturated);
2353  cpl_free(keyword);
2354  }
2355  muse_imagelist_delete(list);
2356  /* append to imagelist */
2357  muse_imagelist_set(images, lampimage, ipos++);
2358  } /* for ilabel (labels) */
2359  cpl_free(labels);
2360  cpl_free(proc);
2361  muse_combinepar_delete(cpars);
2362  cpl_frameset_delete(rawframes);
2363  cpl_frameset_delete(auxframes);
2364 
2365  if (images && muse_imagelist_get_size(images) == 0) {
2366  muse_imagelist_delete(images);
2367  images = NULL;
2368  if (aLabeledFrames) {
2369  cpl_free(*aLabeledFrames);
2370  *aLabeledFrames = NULL;
2371  }
2372  }
2373 
2374  return images;
2375 } /* muse_basicproc_combine_images_lampwise() */
2376 
2377 /*---------------------------------------------------------------------------*/
2399 /*---------------------------------------------------------------------------*/
2400 cpl_error_code
2402  double aHalfWidth, double aBinWidth,
2403  float aLo, float aHi, unsigned char aIter)
2404 {
2405  cpl_ensure_code(aPt && aLines, CPL_ERROR_NULL_INPUT);
2406  cpl_ensure_code(cpl_array_get_type(aLines) == CPL_TYPE_DOUBLE ||
2407  cpl_array_get_type(aLines) == CPL_TYPE_FLOAT,
2408  CPL_ERROR_ILLEGAL_INPUT);
2409 
2410  double lmin = cpl_propertylist_get_float(aPt->header, MUSE_HDR_PT_LLO),
2411  lmax = cpl_propertylist_get_float(aPt->header, MUSE_HDR_PT_LHI);
2412  double shift = 0., wshift = 0.;
2413  cpl_array *errors = cpl_array_new(4, CPL_TYPE_DOUBLE);
2414  int i, n = cpl_array_get_size(aLines), nvalid = 0;
2415  for (i = 0; i < n; i++) {
2416  int err;
2417  double lambdasign = cpl_array_get(aLines, i, &err),
2418  lambda = fabs(lambdasign);
2419  if (err || lambda >= lmax || lambda <= lmin) {
2420  cpl_msg_debug(__func__, "Invalid wavelength at position %d of %d in "
2421  "skylines", i + 1, n);
2422  continue;
2423  }
2424  nvalid++;
2425  double center = muse_utils_pixtable_fit_line_gaussian(aPt, lambdasign, aHalfWidth,
2426  aBinWidth, aLo, aHi, aIter,
2427  NULL, errors),
2428  cerr = cpl_array_get_double(errors, 0, NULL);
2429  shift += (lambda - center) / cerr;
2430  wshift += 1. / cerr;
2431  cpl_msg_debug(__func__, "dlambda = %.4f +/- %.4f (for skyline at %.4f "
2432  "Angstrom)", lambda - center, cerr, lambda);
2433  } /* for i (all entries in aLines) */
2434  cpl_array_delete(errors);
2435  shift /= wshift;
2436  if (nvalid > 0 && isfinite(shift)) {
2437  cpl_msg_info(__func__, "Skyline correction (%d lines): shifting data of IFU "
2438  "%hhu by %.4f Angstrom", nvalid, muse_utils_get_ifu(aPt->header),
2439  shift);
2440  cpl_table_add_scalar(aPt->table, MUSE_PIXTABLE_LAMBDA, shift);
2441  cpl_propertylist_update_float(aPt->header, QC_SCIBASIC_SHIFT, shift);
2442  } else {
2443  cpl_propertylist_update_float(aPt->header, QC_SCIBASIC_SHIFT, 0.);
2444  }
2445  return CPL_ERROR_NONE;
2446 } /* muse_basicproc_shift_pixtable() */
2447 
2448 /*---------------------------------------------------------------------------*/
2460 /*---------------------------------------------------------------------------*/
2461 cpl_error_code
2462 muse_basicproc_stats_append_header(cpl_image *aImage, cpl_propertylist *aHeader,
2463  const char *aPrefix, unsigned aStats)
2464 {
2465  cpl_ensure_code(aImage, CPL_ERROR_NULL_INPUT);
2466 
2467  int nx = cpl_image_get_size_x(aImage),
2468  ny = cpl_image_get_size_y(aImage);
2469  return muse_basicproc_stats_append_header_window(aImage, aHeader, aPrefix,
2470  aStats, 1, 1, nx, ny);
2471 } /* muse_basicproc_stats_append_header() */
2472 
2473 /*---------------------------------------------------------------------------*/
2490 /*---------------------------------------------------------------------------*/
2491 cpl_error_code
2493  cpl_propertylist *aHeader,
2494  const char *aPrefix, unsigned aStats,
2495  int aX1, int aY1, int aX2, int aY2)
2496 {
2497  cpl_ensure_code(aImage && aHeader, CPL_ERROR_NULL_INPUT);
2498  cpl_ensure_code(aPrefix, CPL_ERROR_ILLEGAL_INPUT);
2499  cpl_ensure_code(aPrefix, CPL_ERROR_ILLEGAL_INPUT);
2500 
2501  cpl_stats *stats = cpl_stats_new_from_image_window(aImage, aStats,
2502  aX1, aY1, aX2, aY2);
2503  if (!stats) {
2504  return cpl_error_get_code();
2505  }
2506 
2507  char keyword[KEYWORD_LENGTH];
2508  if (aStats & CPL_STATS_MEDIAN) {
2509  snprintf(keyword, KEYWORD_LENGTH, "%s MEDIAN", aPrefix);
2510  cpl_propertylist_append_float(aHeader, keyword,
2511  cpl_stats_get_median(stats));
2512  }
2513  if (aStats & CPL_STATS_MEAN) {
2514  snprintf(keyword, KEYWORD_LENGTH, "%s MEAN", aPrefix);
2515  cpl_propertylist_append_float(aHeader, keyword, cpl_stats_get_mean(stats));
2516  }
2517  if (aStats & CPL_STATS_STDEV) {
2518  snprintf(keyword, KEYWORD_LENGTH, "%s STDEV", aPrefix);
2519  cpl_propertylist_append_float(aHeader, keyword, cpl_stats_get_stdev(stats));
2520  }
2521  if (aStats & CPL_STATS_MIN) {
2522  snprintf(keyword, KEYWORD_LENGTH, "%s MIN", aPrefix);
2523  cpl_propertylist_append_float(aHeader, keyword, cpl_stats_get_min(stats));
2524  }
2525  if (aStats & CPL_STATS_MAX) {
2526  snprintf(keyword, KEYWORD_LENGTH, "%s MAX", aPrefix);
2527  cpl_propertylist_append_float(aHeader, keyword, cpl_stats_get_max(stats));
2528  }
2529  if (aStats & CPL_STATS_FLUX) {
2530  snprintf(keyword, KEYWORD_LENGTH, "%s INTFLUX", aPrefix);
2531  cpl_propertylist_append_float(aHeader, keyword, cpl_stats_get_flux(stats));
2532  }
2533 
2534  cpl_stats_delete(stats);
2535 
2536  return CPL_ERROR_NONE;
2537 } /* muse_basicproc_stats_append_header_window() */
2538 
2539 /*---------------------------------------------------------------------------*/
2554 /*---------------------------------------------------------------------------*/
2555 cpl_error_code
2556 muse_basicproc_qc_saturated(muse_image *aImage, const char *aPrefix)
2557 {
2558  cpl_ensure_code(aImage && aImage->dq && aImage->header && aPrefix,
2559  CPL_ERROR_NULL_INPUT);
2560 
2561  cpl_mask *mask = cpl_mask_threshold_image_create(aImage->dq,
2562  EURO3D_SATURATED - 0.1,
2563  EURO3D_SATURATED + 0.1);
2564  int nsaturated = cpl_mask_count(mask);
2565  cpl_mask_delete(mask);
2566  /* check if the prefix has a trailing space, add it if not */
2567  char *keyword = NULL;
2568  if (aPrefix[strlen(aPrefix)-1] == ' ') {
2569  keyword = cpl_sprintf("%s%s", aPrefix, QC_BASIC_NSATURATED);
2570  } else {
2571  keyword = cpl_sprintf("%s %s", aPrefix, QC_BASIC_NSATURATED);
2572  }
2573  cpl_error_code rc = cpl_propertylist_update_int(aImage->header, keyword,
2574  nsaturated);
2575  cpl_free(keyword);
2576  return rc;
2577 } /* muse_basicproc_qc_saturated() */
2578 
cpl_error_code muse_quadrants_overscan_correct(muse_image *aImage, muse_image *aRefImage)
Adapt bias level to reference image using overscan statistics.
#define MUSE_PIXTABLE_DQ
Definition: muse_pixtable.h:49
muse_imagelist * muse_basicproc_load(muse_processing *aProcessing, unsigned char aIFU, muse_basicproc_params *aBPars)
Load the raw input files from disk and do basic processing.
#define MUSE_PIXTABLE_XPOS
Definition: muse_pixtable.h:51
Structure definition of a MUSE datacube.
Definition: muse_datacube.h:48
Structure definition for a collection of muse_images.
void muse_image_delete(muse_image *aImage)
Deallocate memory associated to a muse_image object.
Definition: muse_image.c:85
void muse_pixtable_extracted_delete(muse_pixtable **aPixtables)
Delete a pixel table array.
double muse_pfits_get_cd(const cpl_propertylist *aHeaders, unsigned int aAxisI, unsigned int aAxisJ)
find out the WCS coordinate at the reference point
Definition: muse_pfits.c:446
int muse_image_divide(muse_image *aImage, muse_image *aDivisor)
Divide a muse_image by another with correct treatment of bad pixels and variance. ...
Definition: muse_image.c:639
const char * muse_pfits_get_insmode(const cpl_propertylist *aHeaders)
find out the observation mode
Definition: muse_pfits.c:1383
double muse_utils_pixtable_fit_line_gaussian(muse_pixtable *aPixtable, double aLambda, double aHalfWidth, double aBinSize, float aLo, float aHi, unsigned char aIter, cpl_array *aResults, cpl_array *aErrors)
Fit a 1D Gaussian to a given wavelength range in a pixel table.
Definition: muse_utils.c:2442
unsigned short muse_pixtable_origin_get_slice(uint32_t aOrigin)
Get the slice number from the encoded 32bit origin number.
cpl_size * muse_quadrants_get_window(const muse_image *aImage, unsigned char aQuadrant)
Determine the data window of a given quadrant on the CCD.
int muse_image_scale(muse_image *aImage, double aScale)
Scale a muse_image with correct treatment of variance.
Definition: muse_image.c:703
int muse_pfits_get_read_id(const cpl_propertylist *aHeaders)
find out the readout mode id
Definition: muse_pfits.c:512
int muse_utils_get_extension_for_ifu(const char *aFilename, unsigned char aIFU)
Return extension number that corresponds to this IFU/channel number.
Definition: muse_utils.c:118
cpl_size muse_pixtable_extracted_get_size(muse_pixtable **aPixtables)
Get the size of an array of extracted pixel tables.
double muse_pfits_get_crval(const cpl_propertylist *aHeaders, unsigned int aAxis)
find out the WCS coordinate at the reference point
Definition: muse_pfits.c:423
const char * name
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
muse_imagelist * muse_basicproc_combine_images_lampwise(muse_processing *aProcessing, unsigned char aIFU, muse_basicproc_params *aBPars, cpl_frameset ***aLabeledFrames)
Combine several images into a lampwise image list.
muse_pixtable ** muse_pixtable_extracted_get_slices(muse_pixtable *aPixtable)
Extract one pixel table per IFU and slice.
double muse_pfits_get_gain(const cpl_propertylist *aHeaders, unsigned char aQuadrant)
find the detector gain (in units of count/adu)
Definition: muse_pfits.c:686
cpl_image * data
the data extension
Definition: muse_image.h:46
muse_image * muse_image_load_from_raw(const char *aFilename, int aExtension)
Load raw image into the data extension of a MUSE image.
Definition: muse_image.c:292
cpl_size muse_pixtable_get_nrow(const muse_pixtable *aPixtable)
get the number of rows within the pixel table
int muse_pfits_get_shut_status(const cpl_propertylist *aHeaders, int aShutter)
query the status of one shutter
Definition: muse_pfits.c:1569
#define MUSE_HDR_PT_LHI
FITS header keyword contains the upper limit of the data in spectral direction.
int muse_cosmics_dcr(muse_image *aImage, unsigned int aXBox, unsigned int aYBox, unsigned int aPasses, float aThres)
Quickly mark cosmic rays in an image using the DCR algorithm.
muse_image * muse_image_duplicate(const muse_image *aImage)
Duplicate the three image extensions and the FITS headers of a MUSE image.
Definition: muse_image.c:510
#define MUSE_HDR_PT_ILLUMi
cpl_image * stat
the statistics extension
Definition: muse_image.h:64
int muse_image_subtract(muse_image *aImage, muse_image *aSubtract)
Subtract a muse_image from another with correct treatment of bad pixels and variance.
Definition: muse_image.c:593
void muse_imagelist_delete(muse_imagelist *aList)
Free the memory of the MUSE image list.
#define MUSE_HDR_PT_ILLUM_MEAN
muse_imagelist * muse_basicproc_load_reduced(muse_processing *aProcessing, unsigned char aIFU)
Load reduced input files from disk.
muse_basicproc_params * muse_basicproc_params_new(cpl_parameterlist *aParameters, const char *aPrefix)
Create a new structure of basic processing parameters.
muse_image * flatimage
muse_image * muse_combine_images(muse_combinepar *aCPars, muse_imagelist *aImages)
Combine several images into one.
Definition: muse_combine.c:741
Structure definition of MUSE three extension FITS file.
Definition: muse_image.h:40
cpl_error_code muse_quadrants_overscan_polyfit_vertical(muse_image *aImage, unsigned aIgnore, unsigned char aOrder, double aSigma, const double aFRMS, double aFChiSq)
Correct quadrants by polynomial representation of vertical overscan.
unsigned int ovscignore
const char * muse_pfits_get_shut_name(const cpl_propertylist *aHeaders, int aShutter)
query the name of one shutter
Definition: muse_pfits.c:1548
cpl_table * table
The pixel table.
void muse_basicproc_params_delete(muse_basicproc_params *aBPars)
Free a structure of basic processing parameters.
cpl_propertylist * header
the FITS header
Definition: muse_image.h:72
cpl_boolean muse_processing_check_intags(muse_processing *aProcessing, const char *aTag, int aNChars)
Check that a tag is part of the input tags of a processing structure.
int muse_image_variance_create(muse_image *aImage, muse_image *aBias)
Create the photon noise-based variance in the stat extension.
Definition: muse_image.c:747
cpl_table * muse_cpltable_load(const char *aFile, const char *aExtension, const muse_cpltable_def aDefinition[])
Load a table from disk (and check against definition).
#define MUSE_PIXTABLE_DATA
Definition: muse_pixtable.h:48
unsigned int muse_imagelist_get_size(muse_imagelist *aList)
Return the number of stored images.
cpl_frameset * usedframes
void muse_combinepar_delete(muse_combinepar *aCPars)
Clear the combination parameters.
Definition: muse_combine.c:715
cpl_image * dq
the data quality extension
Definition: muse_image.h:56
cpl_error_code muse_pixtable_restrict_wavelength(muse_pixtable *aPixtable, double aLow, double aHigh)
Restrict a pixel table to a certain wavelength range.
double muse_pfits_get_crpix(const cpl_propertylist *aHeaders, unsigned int aAxis)
find out the WCS reference point
Definition: muse_pfits.c:401
int muse_pfits_get_biny(const cpl_propertylist *aHeaders)
find out the binning factor in y direction
Definition: muse_pfits.c:566
Structure definition of MUSE pixel table.
cpl_boolean muse_quadrants_overscan_check(muse_image *aImage, muse_image *aRefImage, double aSigma)
Compare overscan statistics of all quadrants to those of reference image.
cpl_error_code muse_basicproc_shift_pixtable(muse_pixtable *aPt, cpl_array *aLines, double aHalfWidth, double aBinWidth, float aLo, float aHi, unsigned char aIter)
Compute wavelength corrections for science data based on reference sky lines.
const char * muse_pfits_get_lamp_name(const cpl_propertylist *aHeaders, int aLamp)
query the name of one lamp
Definition: muse_pfits.c:1506
muse_image * muse_imagelist_get(muse_imagelist *aList, unsigned int aIdx)
Get the muse_image of given list index.
cpl_error_code muse_basicproc_apply_twilight(muse_pixtable *aPT, muse_datacube *aTwilight)
Apply an attached flat-field to a pixel table.
cpl_error_code muse_basicproc_stats_append_header_window(cpl_image *aImage, cpl_propertylist *aHeader, const char *aPrefix, unsigned aStats, int aX1, int aY1, int aX2, int aY2)
Compute image statistics of an image window and add them to a header.
int muse_quality_set_saturated(muse_image *aImage)
Set all pixels above the saturation limit in the bad pixel image.
Definition: muse_quality.c:473
const char * muse_pfits_get_read_name(const cpl_propertylist *aHeaders)
find out the readout mode name
Definition: muse_pfits.c:530
int muse_imagelist_is_uniform(muse_imagelist *aList)
Check that all images in the muse_imagelist have the same size.
const muse_cpltable_def muse_badpix_table_def[]
muse_combinepar * muse_combinepar_new(cpl_parameterlist *aParameters, const char *aPrefix)
Create a new set of combination parameters.
Definition: muse_combine.c:672
cpl_imagelist * data
the cube containing the actual data values
Definition: muse_datacube.h:76
void muse_processing_append_used(muse_processing *aProcessing, cpl_frame *aFrame, cpl_frame_group aGroup, int aDuplicate)
Add a frame to the set of used frames.
muse_pixtable * muse_pixtable_create(muse_image *aImage, cpl_table *aTrace, cpl_table *aWave, cpl_table *aGeoTable)
Create the pixel table for one CCD.
#define MUSE_PIXTABLE_ORIGIN
Definition: muse_pixtable.h:54
#define MUSE_HDR_PT_LLO
FITS header keyword contains the lower limit of the data in spectral direction.
const char * muse_pfits_get_chip_id(const cpl_propertylist *aHeaders)
find out the chip id
Definition: muse_pfits.c:602
cpl_error_code muse_quadrants_overscan_stats(muse_image *aImage, const char *aRejection, unsigned int aIgnore)
Compute overscan statistics of all quadrants and save in FITS header.
cpl_error_code muse_basicproc_stats_append_header(cpl_image *aImage, cpl_propertylist *aHeader, const char *aPrefix, unsigned aStats)
Compute image statistics of an image and add them to a header.
cpl_table * muse_basicproc_get_illum(muse_imagelist *aImages, cpl_table *aTrace, cpl_table *aWave, cpl_table *aGeo)
Get an illum/attached flat-field from an imagelist and prepare it for use.
int muse_pfits_get_binx(const cpl_propertylist *aHeaders)
find out the binning factor in x direction
Definition: muse_pfits.c:548
cpl_propertylist * header
the FITS header
Definition: muse_datacube.h:57
#define MUSE_PIXTABLE_STAT
Definition: muse_pixtable.h:50
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
muse_image * muse_image_load(const char *aFilename)
Load the three extensions and the FITS headers of a MUSE image from a file.
Definition: muse_image.c:228
int muse_pfits_get_lamp_status(const cpl_propertylist *aHeaders, int aLamp)
query the status of one lamp
Definition: muse_pfits.c:1527
cpl_array * intags
muse_imagelist * muse_imagelist_new(void)
Create a new (empty) MUSE image list.
#define MUSE_PIXTABLE_LAMBDA
Definition: muse_pixtable.h:53
cpl_frameset * inframes
cpl_error_code muse_basicproc_mask_notch_filter(muse_pixtable *aPT, unsigned char aIFU)
Mask the range of the NaD notch filter in the given pixel table.
muse_basicproc_params * muse_basicproc_params_new_from_propertylist(const cpl_propertylist *aHeader)
Create a structure of basic processing parameters from a FITS header.
double muse_pfits_get_exptime(const cpl_propertylist *aHeaders)
find out the exposure time
Definition: muse_pfits.c:382
cpl_error_code muse_processing_check_input(muse_processing *aProcessing, unsigned char aIFU)
Check the input files for completeness.
Structure of basic processing parameters.
const char * muse_pfits_get_pro_catg(const cpl_propertylist *aHeaders)
find out the PRO category
Definition: muse_pfits.c:159
#define MUSE_HDR_PT_ILLUM_STDEV
cpl_error_code muse_basicproc_apply_illum(muse_pixtable *aPT, cpl_table *aAttached)
Apply an illum/attached flat-field to a pixel table.
cpl_frameset * muse_frameset_check_raw(const cpl_frameset *aFrames, const cpl_array *aTags, unsigned char aIFU)
return frameset containing good raw input data
Definition: muse_utils.c:284
unsigned int size
cpl_error_code muse_image_adu_to_count(muse_image *aImage)
Convert the data units from raw adu to count (= electron) units.
Definition: muse_image.c:811
cpl_frameset * muse_frameset_find(const cpl_frameset *aFrames, const char *aTag, unsigned char aIFU, cpl_boolean aInvert)
return frameset containing data from an IFU/channel with a certain tag
Definition: muse_utils.c:160
cpl_parameter * muse_cplparamerterlist_find_prefix(cpl_parameterlist *aParameters, const char *aPrefix, const char *aName)
Return the full recipe parameter belonging to prefix and shortname.
muse_image * muse_image_load_from_extensions(const char *aFilename, unsigned char aIFU)
Load the three extensions and the FITS headers of a MUSE image from extensions of a merged file...
Definition: muse_image.c:262
#define MUSE_PIXTABLE_YPOS
Definition: muse_pixtable.h:52
void muse_pixtable_delete(muse_pixtable *aPixtable)
Deallocate memory associated to a pixel table object.
cpl_error_code muse_imagelist_set(muse_imagelist *aList, muse_image *aImage, unsigned int aIdx)
Set the muse_image of given list index.
const char * muse_pfits_get_chip_name(const cpl_propertylist *aHeaders)
find out the chip name
Definition: muse_pfits.c:584
cpl_frame * muse_frameset_find_master(const cpl_frameset *aFrames, const char *aTag, unsigned char aIFU)
find the master frame according to its CCD number and tag
Definition: muse_utils.c:505
muse_ins_mode muse_pfits_get_mode(const cpl_propertylist *aHeaders)
find out the observation mode
Definition: muse_pfits.c:1352
muse_image * muse_imagelist_unset(muse_imagelist *aList, unsigned int aIdx)
Unset the muse_image at given list index from the list.
cpl_parameterlist * parameters
muse_image * muse_quadrants_trim_image(muse_image *aImage)
Trim the input image of pre- and over-scan regions of all quadrants.
cpl_parameterlist * muse_cplparameterlist_from_propertylist(const cpl_propertylist *aHeader, int aRecNum)
Recreate a cpl_parameterlist from the RECi headers of an output MUSE product.
cpl_propertylist * header
The FITS header.
cpl_frameset * muse_frameset_find_tags(const cpl_frameset *aFrames, const cpl_array *aTags, unsigned char aIFU, cpl_boolean aInvert)
return frameset containing data from an IFU/channel with the given tag(s)
Definition: muse_utils.c:253
cpl_error_code muse_basicproc_qc_saturated(muse_image *aImage, const char *aPrefix)
Add QC parameter about saturated pixels to a muse_image.