MUSE Pipeline Reference Manual  2.5.2
muse/muse_lsf.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
20  * 02110-1301, USA.
21  */
22 
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26 
27 #define STORE_SLIT_WIDTH
28 #define STORE_BIN_WIDTH
29 
30 /*----------------------------------------------------------------------------*
31  * Includes *
32  *----------------------------------------------------------------------------*/
33 #include <math.h>
34 #include <string.h>
35 #include <fenv.h>
36 #include <cpl.h>
37 
38 #include "muse_lsf.h"
39 
40 #include "muse_instrument.h"
41 #include "muse_optimize.h"
42 #include "muse_pfits.h"
43 #include "muse_pixtable.h"
44 #include "muse_quality.h"
45 #include "muse_resampling.h"
46 #include "muse_tracing.h"
47 #include "muse_utils.h"
48 #include "muse_wavecalib.h"
49 
50 /*----------------------------------------------------------------------------*/
54 /*----------------------------------------------------------------------------*/
55 
58 /*----------------------------------------------------------------------------*/
76 /*----------------------------------------------------------------------------*/
77 static cpl_size
78 muse_lsf_check_arc_line(cpl_table *aPixtable, double aLambda)
79 {
80  cpl_size nrows = cpl_table_get_nrow(aPixtable);
81  /* If we have too few data pointe, remove the line */
82  if (nrows <= 100) {
83  return 0;
84  }
85  cpl_errorstate prestate = cpl_errorstate_get();
86  /* get origin before any more (or all?!) rows are removed */
87  uint32_t origin = cpl_table_get_int(aPixtable, MUSE_PIXTABLE_ORIGIN, 0, NULL);
88 
89  /* wrap table columns into vectors for the Gaussian fit */
90  cpl_vector *pos = cpl_vector_new(nrows);
91  cpl_vector *val = cpl_vector_new(nrows);
92  cpl_vector *err = cpl_vector_new(nrows);
93  double *d_pos = cpl_vector_get_data(pos);
94  double *d_val = cpl_vector_get_data(val);
95  double *d_err = cpl_vector_get_data(err);
96  float *d_lambda = cpl_table_get_data_float(aPixtable, MUSE_PIXTABLE_LAMBDA);
97  float *d_data = cpl_table_get_data_float(aPixtable, MUSE_PIXTABLE_DATA);
98  float *d_stat = cpl_table_get_data_float(aPixtable, MUSE_PIXTABLE_STAT);
99  cpl_size i, s = 1;
100  double bglevel = 0;
101  for (i = 0; i < nrows; i++) {
102  if (fabs(d_lambda[i] - aLambda) > 5.5) {
103  bglevel += d_data[i];
104  s += 1;
105  }
106  d_pos[i] = d_lambda[i];
107  d_val[i] = d_data[i];
108  d_err[i] = sqrt(d_stat[i]);
109  }
110  bglevel /= s;
111  double meansigma = sqrt(cpl_table_get_column_mean(aPixtable, MUSE_PIXTABLE_STAT));
112  double sigma, area, mse;
113  double xc = aLambda;
114  cpl_fit_mode fit_pars = CPL_FIT_STDEV | CPL_FIT_AREA | CPL_FIT_CENTROID;
115  cpl_vector_fit_gaussian(pos, NULL, val, NULL, fit_pars, &xc, &sigma,
116  &area, &bglevel, &mse, NULL, NULL);
117 
118  /* Subtract the fit */
119  for (i = 0; i < nrows; i++) {
120  double e = (d_pos[i] - xc)/sigma;
121  d_val[i] -= area / (CPL_MATH_SQRT2PI * sigma) * exp(-e*e/2) - bglevel;
122  }
123 
124  /* Remove all pixels that are too far from the gaussian estimate */
125  double maxerror = 0.5 * sqrt(area) + 0.15 * area;
126  cpl_size inv = 0;
127  cpl_table_unselect_all(aPixtable);
128  for (i = 0; i < nrows; i++) {
129  if ((d_val[i] < -maxerror) || (d_val[i] > maxerror)) {
130  inv++;
131  cpl_table_select_row(aPixtable, i);
132  }
133  }
134  cpl_vector_delete(pos);
135  cpl_vector_delete(val);
136  cpl_vector_delete(err);
137  cpl_table_erase_selected(aPixtable);
138  nrows = cpl_table_get_nrow(aPixtable);
139  if (nrows == 0) {
140  return 0;
141  }
142 
143  cpl_table_fill_column_window_float(aPixtable, "line_lambda",
144  0, nrows, xc);
145  cpl_table_fill_column_window_float(aPixtable, "line_flux",
146  0, nrows, area);
147  cpl_table_fill_column_window_float(aPixtable, "line_background",
148  0, nrows, bglevel);
149 
150  /* If the fit failed, just ignore the errors, and remove the line */
151  if (!cpl_errorstate_is_equal(prestate)) {
152  cpl_errorstate_set(prestate);
153  return 0;
154  }
155  /* If the flux (compared to noise) is too low, silently remove the line */
156  if (area/meansigma < 50) {
157  return 0;
158  }
159  /* If the estimated line width is too far away from our expectation,
160  remove the line */
161  if ((sigma > 3) || (sigma < 0.7)) {
162  int i_ifu = muse_pixtable_origin_get_ifu(origin);
163  int i_slice = muse_pixtable_origin_get_slice(origin);
164  cpl_msg_debug(__func__, "Slice %2i.%02i: "
165  "Ignoring line %.1f with implausible width %f (flux=%.0f)",
166  i_ifu, i_slice, aLambda, sigma, area);
167  return 0;
168  }
169  return nrows;
170 } /* muse_lsf_check_arc_line() */
171 
172 /*----------------------------------------------------------------------------*/
192 /*----------------------------------------------------------------------------*/
193 static cpl_table *
194 muse_lsf_select_arc_line(muse_pixtable *aPixtable, double aLambda,
195  double aWindow)
196 {
197  cpl_size low = muse_cpltable_find_sorted(aPixtable->table, MUSE_PIXTABLE_LAMBDA,
198  aLambda - aWindow);
199  cpl_size high = muse_cpltable_find_sorted(aPixtable->table, MUSE_PIXTABLE_LAMBDA,
200  aLambda + aWindow);
201  if (high == low) {
202  return NULL;
203  }
204  cpl_table *sel = cpl_table_extract(aPixtable->table, low + 1, high - low);
205  cpl_table_select_all(sel);
206  cpl_table_and_selected_int(sel, "dq", CPL_NOT_EQUAL_TO, 0);
207  cpl_table_erase_selected(sel);
208  if (cpl_table_get_nrow(sel) == 0) {
209  cpl_table_delete(sel);
210  return NULL;
211  }
212 
213  cpl_table_new_column(sel, "line_lambda", CPL_TYPE_FLOAT);
214  cpl_table_new_column(sel, "line_flux", CPL_TYPE_FLOAT);
215  cpl_table_new_column(sel, "line_background", CPL_TYPE_FLOAT);
216 
217  cpl_size nrows = muse_lsf_check_arc_line(sel, aLambda);
218  if (nrows == 0) {
219  cpl_table_delete(sel);
220  return NULL;
221  }
222  return sel;
223 } /* muse_lsf_select_arc_line() */
224 
225 /*----------------------------------------------------------------------------*/
248 /*----------------------------------------------------------------------------*/
251  cpl_table *aTrace, cpl_table *aWave,
252  cpl_table *aArcLines, int aQuality, double aWindow)
253 {
254  cpl_ensure(aImages, CPL_ERROR_NULL_INPUT, NULL);
255  cpl_ensure(aTrace, CPL_ERROR_NULL_INPUT, NULL);
256  cpl_ensure(aWave, CPL_ERROR_NULL_INPUT, NULL);
257  cpl_ensure(aArcLines, CPL_ERROR_NULL_INPUT, NULL);
258 
259  /* create the output pixel table with two extra columns */
260  muse_pixtable *pt = cpl_calloc(1, sizeof(muse_pixtable));
262  cpl_table_new_column(pt->table, "line_lambda", CPL_TYPE_FLOAT);
263  cpl_table_new_column(pt->table, "line_flux", CPL_TYPE_FLOAT);
264  cpl_table_new_column(pt->table, "line_background", CPL_TYPE_FLOAT);
265 
266  cpl_size i_image, n_images = muse_imagelist_get_size(aImages);
267 #if 0 /* no extra levels of parallelization in basic processing recipes */
268  #pragma omp parallel for default(none) /* as req. by Ralf */ \
269  shared(i_image, n_images, aImages, aTrace, aWave, aArcLines, \
270  aQuality, aWindow, pt)
271 #endif
272  for (i_image = 0; i_image < n_images; i_image++) {
273  muse_image *image = muse_imagelist_get(aImages, i_image);
274  muse_pixtable *pixtable = muse_pixtable_create(image, aTrace, aWave, NULL);
275  if (pixtable == NULL) {
276  continue;
277  }
278  /* create header of output pixel table, if it's not there yet */
279  if (!pt->header) {
280  pt->header = cpl_propertylist_duplicate(pixtable->header);
281  }
282  char *l = muse_utils_header_get_lamp_names(pixtable->header, '|');
283  if (strlen(l) == 0) {
284  cpl_msg_warning(__func__,
285  "Ignoring frame without arc lamp switched on");
286  cpl_free(l);
287  cpl_free(pixtable);
288  continue;
289  }
290  char *lamp = cpl_malloc(strlen(l)+3);
291  sprintf(lamp, "|%s|", l);
292  cpl_free(l);
293  cpl_size i_line;
294  cpl_size n_entries = 0;
295  muse_ins_mode insmode = muse_pfits_get_mode(pt->header);
296  muse_pixtable **slice_pixtable = muse_pixtable_extracted_get_slices(pixtable);
297  int n_slices = muse_pixtable_extracted_get_size(slice_pixtable);
298  for (i_line = 0; i_line < cpl_table_get_nrow(aArcLines); i_line++) {
299  double lambda = cpl_table_get_float(aArcLines, "lambda", i_line, NULL);
300  if (!muse_wave_lines_covered_by_data(lambda, insmode) ||
301  cpl_table_get_int(aArcLines, "quality", i_line, NULL) < aQuality) {
302  continue;
303  }
304  const char *n = muse_wave_lines_get_lampname(aArcLines, i_line);
305  char *name = cpl_malloc(strlen(n) + 3);
306  sprintf(name, "|%s|", n);
307  if (strstr(name, lamp)) {
308  int i_slice;
309 #if 0 /* no extra levels of parallelization in basic processing recipes */
310  #pragma omp parallel for default(none) /* as req. by Ralf */ \
311  shared(i_slice, n_slices, n_entries, lambda, slice_pixtable, \
312  aWindow, pt)
313 #endif
314  for (i_slice = 0; i_slice < n_slices; i_slice++) {
315  cpl_table *sel = muse_lsf_select_arc_line(slice_pixtable[i_slice],
316  lambda, aWindow);
317  if (sel) {
318 #if 0 /* no parallelization here, not necessary any more */
319  #pragma omp critical(construct_pixtable)
320 #endif
321  cpl_table_insert(pt->table, sel, cpl_table_get_nrow(pt->table));
322 #if 0 /* no parallelization here, not necessary any more */
323  #pragma omp atomic
324 #endif
325  n_entries += cpl_table_get_nrow(sel);
326  cpl_table_delete(sel);
327  }
328  }
329  }
330  cpl_free(name);
331  } /* for i_line (arc lines) */
332  muse_pixtable_extracted_delete(slice_pixtable);
333  muse_pixtable_delete(pixtable);
334  cpl_msg_info(__func__, "Using %"CPL_SIZE_FORMAT" entries with lamp %s",
335  n_entries, lamp);
336  cpl_free(lamp);
337  } /* for i_image (all images in list) */
338  return pt;
339 } /* muse_lsf_create_arcpixtable() */
340 
341 /*----------------------------------------------------------------------------*/
366 /*----------------------------------------------------------------------------*/
367 static cpl_polynomial *
368 muse_lsf_fit_polynomial(cpl_table *aPixtable, int aOrderLsf, int aOrderLambda)
369 {
370  cpl_errorstate prestate = cpl_errorstate_get();
371  cpl_size nrows = cpl_table_get_nrow(aPixtable);
372  if (nrows <= (aOrderLsf + 1) * (aOrderLambda)) {
373  return NULL;
374  }
375  double *p_dlambda = cpl_table_get_data_double(aPixtable, "d_lambda");
376  cpl_ensure(p_dlambda, CPL_ERROR_ILLEGAL_INPUT, NULL);
377  float *p_line = cpl_table_get_data_float(aPixtable, "line_lambda");
378  cpl_ensure(p_line, CPL_ERROR_ILLEGAL_INPUT, NULL);
379  float *p_data = cpl_table_get_data_float(aPixtable, MUSE_PIXTABLE_DATA);
380  cpl_ensure(p_data, CPL_ERROR_ILLEGAL_INPUT, NULL);
381  float *p_flux = cpl_table_get_data_float(aPixtable, "line_flux");
382  cpl_ensure(p_flux, CPL_ERROR_ILLEGAL_INPUT, NULL);
383  float *p_background = cpl_table_get_data_float(aPixtable, "line_background");
384  cpl_ensure(p_background, CPL_ERROR_ILLEGAL_INPUT, NULL);
385 
386  cpl_matrix *coord = cpl_matrix_new(2, nrows);
387  cpl_vector *data = cpl_vector_new(nrows);
388  double *coord_ptr = cpl_matrix_get_data(coord);
389  double *data_ptr = cpl_vector_get_data(data);
390  cpl_size i_row;
391 
392  for (i_row = 0; i_row < nrows; i_row++) {
393  coord_ptr[i_row] = p_dlambda[i_row];
394  coord_ptr[i_row + nrows] = p_line[i_row];
395  data_ptr[i_row] = (p_data[i_row] - p_background[i_row]) / p_flux[i_row];
396  }
397 
398  cpl_polynomial *p = cpl_polynomial_new(2);
399  const cpl_size maxdeg2d[] = { aOrderLsf, aOrderLambda };
400  cpl_polynomial_fit(p, coord, NULL, data, NULL, CPL_TRUE, NULL, maxdeg2d);
401  cpl_matrix_delete(coord);
402  cpl_vector_delete(data);
403 
404  if (!cpl_errorstate_is_equal(prestate)) {
405  cpl_errorstate_set(prestate);
406  return NULL;
407  }
408 
409  return p;
410 } /* muse_lsf_fit_polynomial() */
411 
412 /*----------------------------------------------------------------------------*/
441 /*----------------------------------------------------------------------------*/
442 cpl_error_code
443 muse_lsf_fit_slice(const muse_pixtable *aPixtable, cpl_image *aLsfImage,
444  muse_wcs *aWCS, double aLsfRegressionWindow)
445 {
446  cpl_ensure_code(aPixtable && aPixtable->table, CPL_ERROR_NULL_INPUT);
447  cpl_ensure_code(aLsfImage, CPL_ERROR_NULL_INPUT);
448  cpl_ensure_code(aWCS, CPL_ERROR_NULL_INPUT);
449  cpl_ensure_code(aLsfRegressionWindow > 0, CPL_ERROR_ILLEGAL_INPUT);
450 
451  cpl_size nrows = muse_pixtable_get_nrow(aPixtable);
452  if (nrows == 0) {
453  return CPL_ERROR_NONE;
454  }
455  /* work on a locally duplicated table (since we mess with the columns) */
456  cpl_table *pixtable = cpl_table_duplicate(aPixtable->table);
457  uint32_t origin = cpl_table_get_int(pixtable, MUSE_PIXTABLE_ORIGIN, 0, NULL);
458  int i_ifu = muse_pixtable_origin_get_ifu(origin);
459  int i_slice = muse_pixtable_origin_get_slice(origin);
460  cpl_msg_info(__func__, "processing slice %2i.%02i"
461  " with %"CPL_SIZE_FORMAT" entries",
462  i_ifu, i_slice, nrows);
463 
464  /* Create temporary column with (lmbda - line_lambda) and sort pixtable
465  according to this column. Sorting is important since we use it later
466  to extract the values according to the regession window using
467  find_sorted(). */
468  cpl_table_cast_column(pixtable, MUSE_PIXTABLE_LAMBDA, "d_lambda", CPL_TYPE_DOUBLE);
469  cpl_table_subtract_columns(pixtable, "d_lambda", "line_lambda");
470  cpl_propertylist *order = cpl_propertylist_new();
471  cpl_propertylist_append_bool(order, "d_lambda", CPL_FALSE);
472  cpl_table_sort(pixtable, order);
473  cpl_propertylist_delete(order);
474 
475  /* Loop over all x (LSF) data points and create a polynomial for each
476  covering the whole wavelength range */
477  cpl_size i_lsf;
478  cpl_size n_lsf = cpl_image_get_size_x(aLsfImage);
479  cpl_size n_lambda = cpl_image_get_size_y(aLsfImage);
480  for (i_lsf = 1; i_lsf <= n_lsf; i_lsf++) {
481  double x = aWCS->crval1 + (i_lsf - aWCS->crpix1) * aWCS->cd11;
482  double x_ref = CPL_MAX(x, cpl_table_get_column_min(pixtable, "d_lambda")
483  + aLsfRegressionWindow);
484  x_ref = CPL_MIN(x, cpl_table_get_column_max(pixtable, "d_lambda")
485  - aLsfRegressionWindow);
486  cpl_size low = muse_cpltable_find_sorted(pixtable, "d_lambda",
487  x_ref - aLsfRegressionWindow);
488  cpl_size high = muse_cpltable_find_sorted(pixtable, "d_lambda",
489  x_ref + aLsfRegressionWindow);
490  cpl_table *selected = cpl_table_extract(pixtable, low+1, high-low);
491  cpl_polynomial *p = muse_lsf_fit_polynomial(selected, 2, 3);
492  if (p) {
493  cpl_vector *c = cpl_vector_new(2);
494  cpl_vector_set(c, 0, x);
495  cpl_size i_lambda;
496  /* Fill the image column with the values calculated from the polynomial */
497  for (i_lambda = 1; i_lambda <= n_lambda; i_lambda++) {
498  double y = aWCS->crval2 + (i_lambda - aWCS->crpix2) * aWCS->cd22;
499  cpl_vector_set(c, 1, y);
500  double flux = cpl_polynomial_eval(p, c);
501  cpl_image_set(aLsfImage, i_lsf, i_lambda, flux);
502  }
503  cpl_vector_delete(c);
504  } else {
505  cpl_msg_warning(__func__,
506  "Failed polynomial fit %2i.%02i %.2f;"
507  " %"CPL_SIZE_FORMAT" entries",
508  i_ifu, i_slice, x, cpl_table_get_nrow(selected));
509  cpl_size i_lambda;
510  for (i_lambda = 1; i_lambda <= n_lambda; i_lambda++) {
511  cpl_image_reject(aLsfImage, i_lsf, i_lambda);
512  }
513  }
514  cpl_polynomial_delete(p);
515  cpl_table_delete(selected);
516  }
517  cpl_table_delete(pixtable);
518  /* Re-normalize total area of each LSF, since normalization may
519  not kept during the polynomial fit */
520  cpl_size i_lambda;
521  for (i_lambda = 1; i_lambda <= n_lambda; i_lambda++) {
522  double line_flux = cpl_image_get_flux_window(aLsfImage, 1, i_lambda,
523  n_lsf, i_lambda) * aWCS->cd11;
524  for (i_lsf = 1; i_lsf <= n_lsf; i_lsf++) {
525  int invalid;
526  double flux = cpl_image_get(aLsfImage, i_lsf, i_lambda, &invalid);
527  if (!invalid) {
528  cpl_image_set(aLsfImage, i_lsf, i_lambda, flux / line_flux);
529  }
530  }
531  }
532  return CPL_ERROR_NONE;
533 } /* muse_lsf_fit_slice() */
534 
535 /*----------------------------------------------------------------------------*/
544 /*----------------------------------------------------------------------------*/
546 muse_lsf_cube_new(double aLsfHalfRange, cpl_size aNLsf, cpl_size aNLambda,
547  const cpl_propertylist *aHeader)
548 {
549  muse_lsf_cube *lsf = cpl_calloc(1, sizeof(muse_lsf_cube));
550  lsf->header = cpl_propertylist_new();
551  if (aHeader) {
552  /* copy all keywords, except keys that don't belong here */
553  const char *regex = MUSE_HDR_OVSC_REGEXP"|"MUSE_WCS_KEYS"|"MUSE_HDR_PT_REGEXP;
554  cpl_propertylist_copy_property_regexp(lsf->header, aHeader, regex, 1);
555  }
556  lsf->img = cpl_imagelist_new();
557  cpl_size i;
558  for (i = 0; i < kMuseSlicesPerCCD; i++) {
559  cpl_imagelist_set(lsf->img,
560  cpl_image_new(aNLsf, aNLambda, CPL_TYPE_FLOAT), i);
561  }
562  double lsf_step = 2*aLsfHalfRange / (aNLsf - 1),
563  lambda_step = (kMuseNominalLambdaMax - kMuseNominalLambdaMin)
564  / (aNLambda - 1);
565  lsf->wcs = cpl_calloc(1, sizeof(muse_wcs));
566  lsf->wcs->cd11 = lsf_step;
567  lsf->wcs->cd12 = 0.;
568  lsf->wcs->cd21 = 0.;
569  lsf->wcs->cd22 = lambda_step;
570  lsf->wcs->crval1 = -aLsfHalfRange;
571  lsf->wcs->crval2 = kMuseNominalLambdaMin;
572  lsf->wcs->crpix1 = 1.;
573  lsf->wcs->crpix2 = 1.;
574  return lsf;
575 } /* muse_lsf_cube_new() */
576 
577 /*----------------------------------------------------------------------------*/
582 /*----------------------------------------------------------------------------*/
583 void
585 {
586  if (!aLsfCube) {
587  return;
588  }
589  cpl_propertylist_delete(aLsfCube->header);
590  cpl_imagelist_delete(aLsfCube->img);
591  cpl_free(aLsfCube->wcs);
592  cpl_free(aLsfCube);
593 } /* muse_lsf_cube_delete() */
594 
595 /*----------------------------------------------------------------------------*/
601 /*----------------------------------------------------------------------------*/
602 cpl_error_code
603 muse_lsf_cube_save(muse_lsf_cube *aLsfCube, const char *aFileName)
604 {
605  cpl_ensure_code(aLsfCube, CPL_ERROR_NULL_INPUT);
606  cpl_error_code rc = cpl_propertylist_save(aLsfCube->header, aFileName,
607  CPL_IO_CREATE);
608  if (rc != CPL_ERROR_NONE) {
609  return rc;
610  }
611  /* create the extension header */
612  cpl_propertylist *header = cpl_propertylist_new();
613  cpl_propertylist_append_string(header, "EXTNAME", "LSF_PROFILE");
614  cpl_propertylist_append_int(header, "WCSAXES", 2);
615  cpl_propertylist_append_double(header, "CD1_1", aLsfCube->wcs->cd11);
616  cpl_propertylist_append_double(header, "CD1_2", aLsfCube->wcs->cd12);
617  cpl_propertylist_append_double(header, "CD2_1", aLsfCube->wcs->cd21);
618  cpl_propertylist_append_double(header, "CD2_2", aLsfCube->wcs->cd22);
619  cpl_propertylist_append_double(header, "CRPIX1", aLsfCube->wcs->crpix1);
620  cpl_propertylist_append_double(header, "CRPIX2", aLsfCube->wcs->crpix2);
621  cpl_propertylist_append_double(header, "CRVAL1", aLsfCube->wcs->crval1);
622  cpl_propertylist_append_double(header, "CRVAL2", aLsfCube->wcs->crval2);
623  cpl_propertylist_append_string(header, "CTYPE1", "PARAM");
624  cpl_propertylist_append_string(header, "CTYPE2", "AWAV");
625  cpl_propertylist_append_string(header, "CUNIT1", "Angstrom");
626  cpl_propertylist_append_string(header, "CUNIT2", "Angstrom");
627 
628  rc = cpl_imagelist_save(aLsfCube->img, aFileName,
629  CPL_TYPE_FLOAT, header, CPL_IO_EXTEND);
630  cpl_propertylist_delete(header);
631  return rc;
632 } /* muse_lsf_cube_save() */
633 
634 /*----------------------------------------------------------------------------*/
646 /*----------------------------------------------------------------------------*/
647 muse_lsf_cube **
649 {
650  cpl_ensure(aProcessing, CPL_ERROR_NULL_INPUT, NULL);
651  muse_lsf_cube **lsf = cpl_calloc(kMuseNumIFUs, sizeof(muse_lsf_cube *));
652  unsigned char ifu, nlsfs = 0; /* count number of LSF cubes loaded */
653  for (ifu = 1; ifu <= kMuseNumIFUs; ifu++) {
654  cpl_frameset *frames = muse_frameset_find(aProcessing->inframes,
655  MUSE_TAG_LSF_PROFILE, ifu, CPL_FALSE);
656  cpl_errorstate es = cpl_errorstate_get();
657  cpl_frame *frame = cpl_frameset_get_position(frames, 0);
658  if (frame == NULL) {
659  cpl_msg_warning(__func__, "No %s (cube format) specified for IFU %2hhu!",
660  MUSE_TAG_LSF_PROFILE, ifu);
661  cpl_errorstate_set(es); /* swallow the illegal input state */
662  cpl_frameset_delete(frames);
663  continue;
664  }
665  const char *fn = cpl_frame_get_filename(frame);
666  lsf[ifu-1] = muse_lsf_cube_load(fn, ifu);
667  if (lsf[ifu-1] == NULL) {
668  cpl_msg_warning(__func__, "Could not load LSF (cube format) for IFU %2hhu "
669  "from \"%s\"!", ifu, fn);
670  cpl_frameset_delete(frames);
672  return NULL;
673  }
674  muse_processing_append_used(aProcessing, frame, CPL_FRAME_GROUP_CALIB, 1);
675  cpl_frameset_delete(frames);
676  nlsfs++;
677  } /* for ifu */
678  if (!nlsfs) {
679  cpl_msg_error(__func__, "Did not load any %ss (cube format)!",
680  MUSE_TAG_LSF_PROFILE);
682  return NULL;
683  } /* if none loaded */
684  cpl_msg_info(__func__, "Successfully loaded %s%hhu %ss (cube format).",
685  nlsfs == kMuseNumIFUs ? "all ": "", nlsfs, MUSE_TAG_LSF_PROFILE);
686  return lsf;
687 } /* muse_lsf_cube_load_all() */
688 
689 /*----------------------------------------------------------------------------*/
694 /*----------------------------------------------------------------------------*/
695 void
697 {
698  if (!aLsfCube) {
699  return;
700  }
701  int ifu;
702  for (ifu = 0; ifu < kMuseNumIFUs; ifu++) {
703  muse_lsf_cube_delete(aLsfCube[ifu]);
704  }
705  cpl_free(aLsfCube);
706 } /* muse_lsf_cube_delete_all() */
707 
708 /*----------------------------------------------------------------------------*/
716 /*----------------------------------------------------------------------------*/
718 muse_lsf_cube_load(const char *aFileName, unsigned char aIFU)
719 {
720  cpl_ensure(aFileName, CPL_ERROR_NULL_INPUT, NULL);
721 
722  /* start looking for the LSF_PROFILE extension */
723  int ext = cpl_fits_find_extension(aFileName, "LSF_PROFILE");
724  char *extname = NULL;
725  if (ext <= 0) { /* if not in an extension then look for merged name */
726  extname = cpl_sprintf("CHAN%02hhu.LSF_PROFILE", aIFU);
727  ext = cpl_fits_find_extension(aFileName, extname);
728  if (ext <= 0) { /* no extension for given IFU found */
729  cpl_free(extname);
730  cpl_error_set(__func__, CPL_ERROR_DATA_NOT_FOUND);
731  return NULL;
732  }
733  } /* if no LSF_PROFILE extension */
734  cpl_free(extname);
735 
736  muse_lsf_cube *lsf = cpl_calloc(1, sizeof(muse_lsf_cube));
737  lsf->header = cpl_propertylist_load(aFileName, 0); /* primary header */
738  lsf->img = cpl_imagelist_load(aFileName, CPL_TYPE_DOUBLE, ext);
739  lsf->wcs = cpl_calloc(1, sizeof(muse_wcs));
740  if (lsf->img == NULL) {
742  return NULL;
743  }
744  /* now load the WCS from the extension header */
745  cpl_propertylist *header = cpl_propertylist_load(aFileName, ext);
746  if (header == NULL) {
748  return NULL;
749  }
750  lsf->wcs->cd11 = muse_pfits_get_cd(header, 1, 1);
751  lsf->wcs->cd12 = muse_pfits_get_cd(header, 1, 2);
752  lsf->wcs->cd21 = muse_pfits_get_cd(header, 2, 1);
753  lsf->wcs->cd22 = muse_pfits_get_cd(header, 2, 2);
754  lsf->wcs->crpix1 = muse_pfits_get_crpix(header, 1);
755  lsf->wcs->crpix2 = muse_pfits_get_crpix(header, 2);
756  lsf->wcs->crval1 = muse_pfits_get_crval(header, 1);
757  lsf->wcs->crval2 = muse_pfits_get_crval(header, 2);
758  /* XXX check types and units of the WCS */
759  // muse_pfits_get_ctype(header, 1) "PARAM"
760  // muse_pfits_get_ctype(header, 2) "AWAV"
761  // muse_pfits_get_cunit(header, 1) "Angstrom"
762  // muse_pfits_get_cunit(header, 2) "Angstrom"
763  cpl_propertylist_delete(header);
764 
765  return lsf;
766 } /* muse_lsf_cube_load() */
767 
768 /*----------------------------------------------------------------------------*/
779 /*----------------------------------------------------------------------------*/
780 cpl_image *
782 {
783  cpl_ensure(aLsfCube, CPL_ERROR_NULL_INPUT, NULL);
784  cpl_image *img = NULL;
785  cpl_size wsum = 0;
786  cpl_size w[kMuseNumIFUs][kMuseSlicesPerCCD];
787  cpl_size ifu;
788  for (ifu = 0; ifu < kMuseNumIFUs; ifu++) {
789  cpl_size i_slice;
790  for (i_slice = 0; i_slice < kMuseSlicesPerCCD; i_slice++) {
791  w[ifu][i_slice] = (aPixtable == NULL)?1.0:0.0;
792  }
793  }
794 
795  if (aPixtable) {
796  cpl_size n_rows = muse_pixtable_get_nrow(aPixtable);
797  cpl_size i_row;
798  uint32_t *origin = (uint32_t *)cpl_table_get_data_int(aPixtable->table,
800  for (i_row = 0; i_row < n_rows; i_row++) {
801  int i_ifu = muse_pixtable_origin_get_ifu(origin[i_row]);
802  int i_slice = muse_pixtable_origin_get_slice(origin[i_row]);
803  w[i_ifu-1][i_slice-1]++;
804  }
805  }
806 
807  for (ifu = 0; ifu < kMuseNumIFUs; ifu++) {
808  if (aLsfCube[ifu] == NULL) {
809  continue;
810  }
811  cpl_size i_slice;
812  cpl_size n_slices = cpl_imagelist_get_size(aLsfCube[ifu]->img);
813  for (i_slice = 0; i_slice < n_slices; i_slice++) {
814  if (w[ifu][i_slice] > 0) {
815  cpl_image *m = cpl_imagelist_get(aLsfCube[ifu]->img, i_slice);
816  m = cpl_image_duplicate(m);
817  cpl_image_multiply_scalar(m, w[ifu][i_slice]);
818  wsum += w[ifu][i_slice];
819  if (img == NULL) {
820  img = m;
821  } else {
822  cpl_errorstate pre = cpl_errorstate_get();
823  cpl_error_code rc = cpl_image_add(img, m);
824  cpl_image_delete(m);
825  if (rc != CPL_ERROR_NONE) {
826  cpl_msg_warning(__func__, "Could not add cube of IFU %"
827  CPL_SIZE_FORMAT": %s",
828  ifu+1, cpl_error_get_message());
829  cpl_errorstate_set(pre);
830  break;
831  }
832  }
833  }
834  }
835  }
836  if ((img) && (wsum > 0)) {
837  cpl_image_divide_scalar(img, wsum);
838  return img;
839  } else {
840  cpl_image_delete(img);
841  return NULL;
842  }
843 } /* muse_lsf_average_cube_all() */
844 
845 /*----------------------------------------------------------------------------*/
858 /*----------------------------------------------------------------------------*/
859 muse_wcs *
861 {
862  cpl_ensure(aLsfCubes, CPL_ERROR_NULL_INPUT, NULL);
863  int ifu;
864  for (ifu = 0; ifu < kMuseNumIFUs; ifu++) {
865  if (aLsfCubes[ifu]) {
866  return aLsfCubes[ifu]->wcs;
867  }
868  }
869  return NULL;
870 } /* muse_lsf_cube_get_wcs_all() */
871 
872 /*----------------------------------------------------------------------------*/
883 /*----------------------------------------------------------------------------*/
884 cpl_error_code
885 muse_lsf_fold_rectangle(cpl_image *aLsfImage, const muse_wcs *aWCS,
886  double aBinWidth)
887 {
888  cpl_ensure_code(aLsfImage && aWCS, CPL_ERROR_NULL_INPUT);
889  cpl_ensure_code(aBinWidth > 0., CPL_ERROR_ILLEGAL_INPUT);
890 
891  cpl_size ncol_kernel = aBinWidth / aWCS->cd11;
892  ncol_kernel = ((ncol_kernel + 1) / 2) * 2 + 1; /* odd number */
893  double r = ncol_kernel - aBinWidth / aWCS->cd11;
894  cpl_matrix *kernel = cpl_matrix_new(1, ncol_kernel);
895  cpl_matrix_fill(kernel, 1.0);
896  cpl_matrix_set(kernel, 0, 0, 1 - r/2);
897  cpl_matrix_set(kernel, 0, ncol_kernel-1, 1 - r/2);
898  cpl_image *lsfImage0 = cpl_image_duplicate(aLsfImage);
899  cpl_image_filter(aLsfImage, lsfImage0, kernel, CPL_FILTER_LINEAR,
900  CPL_BORDER_FILTER);
901  cpl_matrix_delete(kernel);
902  cpl_image_delete(lsfImage0);
903 
904  return CPL_ERROR_NONE;
905 } /* muse_lsf_fold_rectangle() */
906 
907 /*----------------------------------------------------------------------------*/
921 /*----------------------------------------------------------------------------*/
922 cpl_error_code
923 muse_lsf_apply(const cpl_image *aLsfImage, const muse_wcs *aWCS,
924  cpl_array *aVal, double aLambda)
925 {
926  cpl_ensure_code(aLsfImage, CPL_ERROR_NULL_INPUT);
927  cpl_ensure_code(aWCS, CPL_ERROR_NULL_INPUT);
928  cpl_ensure_code(aVal, CPL_ERROR_NULL_INPUT);
929  cpl_size n_lsf = cpl_image_get_size_x(aLsfImage);
930  cpl_size n_lambda = cpl_image_get_size_y(aLsfImage);
931 
932  /* Find y position in image corresponding to line wavelength */
933  double lambda_pix = (aLambda - aWCS->crval2) / aWCS->cd22 + aWCS->crpix2;
934  if (lambda_pix < 1) {
935  lambda_pix = 1;
936  }
937  if (lambda_pix > n_lambda) {
938  lambda_pix = n_lambda;
939  }
940  cpl_size i_lambda = floor(lambda_pix);
941  lambda_pix -= i_lambda; /* lambda_pix has fraction of y position */
942 
943  /* Create vector containing the LSF by linear interpolation.
944  For speed reasons, this is a plain C array. */
945  cpl_array *lsf_lambda = cpl_array_new(n_lsf + 4, CPL_TYPE_DOUBLE);
946  cpl_array *lsf_values = cpl_array_new(n_lsf + 4, CPL_TYPE_DOUBLE);
947  cpl_size i;
948  for (i = 1; i <= n_lsf; i++) {
949  int res;
950  double z = cpl_image_get(aLsfImage, i, i_lambda, &res);
951  if (lambda_pix > 0) {
952  z = z * (1 - lambda_pix)
953  + cpl_image_get(aLsfImage, i, i_lambda+1, &res) * lambda_pix;
954  }
955  cpl_array_set(lsf_values, i+1, z);
956  cpl_array_set(lsf_lambda, i+1, aWCS->crval1 + (i - aWCS->crpix1) * aWCS->cd11);
957  }
958  // Set outer limits of LSF to zero to avoid invalid values in the fit
959  // +- 10000 A is used since the pixtable range will never be in this range
960  cpl_array_set(lsf_lambda, 0, -10000);
961  cpl_array_set(lsf_values, 0, 0);
962  cpl_array_set(lsf_lambda, 1, aWCS->crval1 - aWCS->crpix1 * aWCS->cd11);
963  cpl_array_set(lsf_values, 1, 0);
964  cpl_array_set(lsf_lambda, n_lsf+2, aWCS->crval1 + (n_lsf+1 - aWCS->crpix1) * aWCS->cd11);
965  cpl_array_set(lsf_values, n_lsf+2, 0);
966  cpl_array_set(lsf_lambda, n_lsf+3, 10000);
967  cpl_array_set(lsf_values, n_lsf+3, 0);
968 
969  // Correct the central position of the LSF function
970  cpl_array *v = cpl_array_duplicate(lsf_values);
971  cpl_array_multiply(v, lsf_lambda);
972  double offset = cpl_array_get_mean(v)/cpl_array_get_mean(lsf_values);
973  cpl_array_delete(v);
974  cpl_array_subtract_scalar (lsf_lambda, offset);
975 
976  // Re-normalize, just to be safe
977  double norm = cpl_array_get_mean(lsf_values) * (n_lsf + 4) * aWCS->cd11;
978  cpl_array_divide_scalar(lsf_values, norm);
979 
980  cpl_array *values = muse_cplarray_interpolate_linear(aVal, lsf_lambda,
981  lsf_values);
982 
983  // Copy the values back to the function argument
984  memcpy(cpl_array_get_data_double(aVal), cpl_array_get_data_double(values),
985  cpl_array_get_size(aVal) * sizeof(double));
986 
987  cpl_array_delete(values);
988  cpl_array_delete(lsf_lambda);
989  cpl_array_delete(lsf_values);
990  return CPL_ERROR_NONE;
991 } /* muse_lsf_apply() */
992 
993 /*----------------------------------------------------------------------------*/
1008 /*----------------------------------------------------------------------------*/
1009 cpl_error_code
1010 muse_lsf_apply_slice(muse_pixtable *aPixtable, double aWavelength,
1011  double aFlux, cpl_image *aLsfImage, muse_wcs *aLsfWCS)
1012 {
1013  cpl_propertylist *order = cpl_propertylist_new();
1014  cpl_propertylist_append_bool(order, MUSE_PIXTABLE_LAMBDA, CPL_FALSE);
1015  cpl_table_sort(aPixtable->table, order);
1016  cpl_propertylist_delete(order);
1017 
1018  cpl_array *lsf_data = muse_cpltable_extract_column(aPixtable->table, "lsf");
1019 
1020  cpl_array *lambda = NULL;
1021  if (cpl_table_get_column_type(aPixtable->table, MUSE_PIXTABLE_LAMBDA)
1022  == CPL_TYPE_DOUBLE) {
1023  lambda = muse_cpltable_extract_column(aPixtable->table,
1025  } else {
1026  cpl_table_cast_column(aPixtable->table, MUSE_PIXTABLE_LAMBDA,
1027  "lambda_double", CPL_TYPE_DOUBLE);
1028  lambda = muse_cpltable_extract_column(aPixtable->table, "lambda_double");
1029  }
1030 
1031  double l_min = aLsfWCS->crval1 + aLsfWCS->cd11 * (1 - aLsfWCS->crpix1),
1032  l_max = aLsfWCS->crval1
1033  + aLsfWCS->cd11 * (cpl_image_get_size_x(aLsfImage) - aLsfWCS->crpix1);
1034  cpl_size imin = muse_cplarray_find_sorted(lambda, aWavelength + l_min);
1035  cpl_size imax = muse_cplarray_find_sorted(lambda, aWavelength + l_max);
1036  cpl_array *l0 = cpl_array_extract(lambda, imin, imax-imin+1);
1037  cpl_array_subtract_scalar(l0, aWavelength);
1038  muse_lsf_apply(aLsfImage, aLsfWCS, l0, aWavelength);
1039  cpl_array_multiply_scalar(l0, aFlux);
1040  muse_cplarray_add_window(lsf_data, imin, l0);
1041  cpl_array_delete(l0);
1042  cpl_array_unwrap(lsf_data);
1043  cpl_array_unwrap(lambda);
1044  if (cpl_table_has_column(aPixtable->table, "lambda_double")) {
1045  cpl_table_erase_column(aPixtable->table, "lambda_double");
1046  }
1047 
1048  return CPL_ERROR_NONE;
1049 } /* muse_lsf_apply_slice() */
1050 
double crpix2
Definition: muse_wcs.h:106
Structure definition for a collection of muse_images.
muse_wcs * wcs
Common WCS information for each slice.
Definition: muse_lsf.h:55
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
unsigned short muse_pixtable_origin_get_slice(uint32_t aOrigin)
Get the slice number from the encoded 32bit origin number.
cpl_size muse_pixtable_extracted_get_size(muse_pixtable **aPixtables)
Get the size of an array of extracted pixel tables.
cpl_propertylist * header
Primary header used to save the LSF cube to disk.
Definition: muse_lsf.h:51
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
A structure containing a spatial two-axis WCS.
Definition: muse_wcs.h:105
double cd22
Definition: muse_wcs.h:108
muse_pixtable ** muse_pixtable_extracted_get_slices(muse_pixtable *aPixtable)
Extract one pixel table per IFU and slice.
cpl_size muse_pixtable_get_nrow(const muse_pixtable *aPixtable)
get the number of rows within the pixel table
cpl_image * muse_lsf_average_cube_all(muse_lsf_cube **aLsfCube, muse_pixtable *aPixtable)
Create an average image from all LSF cubes.
Data cube/stacked image list containing the LSF for one IFU.
Definition: muse_lsf.h:49
muse_lsf_cube * muse_lsf_cube_new(double aLsfHalfRange, cpl_size aNLsf, cpl_size aNLambda, const cpl_propertylist *aHeader)
Create a new LSF datacube.
Structure definition of MUSE three extension FITS file.
Definition: muse_image.h:40
cpl_error_code muse_lsf_cube_save(muse_lsf_cube *aLsfCube, const char *aFileName)
Save the LSF cube to disk.
cpl_table * table
The pixel table.
#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_error_code muse_lsf_apply_slice(muse_pixtable *aPixtable, double aWavelength, double aFlux, cpl_image *aLsfImage, muse_wcs *aLsfWCS)
Add line spread function to a MUSE slice of a pixtable.
cpl_table * muse_cpltable_new(const muse_cpltable_def *aDef, cpl_size aLength)
Create an empty table according to the specified definition.
muse_lsf_cube * muse_lsf_cube_load(const char *aFileName, unsigned char aIFU)
Load a LSF cube for one single IFU from disk.
const char * muse_wave_lines_get_lampname(cpl_table *aTable, const int aIdx)
Associate the ion listed in a linelist table row to a lamp name.
double muse_pfits_get_crpix(const cpl_propertylist *aHeaders, unsigned int aAxis)
find out the WCS reference point
Definition: muse_pfits.c:401
Structure definition of MUSE pixel table.
cpl_boolean muse_wave_lines_covered_by_data(double aLambda, muse_ins_mode aMode)
Check, if a given wavelength is covered by a given instrument mode.
#define MUSE_WCS_KEYS
regular expression for WCS properties
Definition: muse_wcs.h:48
muse_image * muse_imagelist_get(muse_imagelist *aList, unsigned int aIdx)
Get the muse_image of given list index.
cpl_array * muse_cpltable_extract_column(cpl_table *aTable, const char *aColumn)
Create an array from a section of a column.
muse_lsf_cube ** muse_lsf_cube_load_all(muse_processing *aProcessing)
Load all LSF cubes for all IFUs into an array.
cpl_array * muse_cplarray_interpolate_linear(const cpl_array *aTargetAbscissa, const cpl_array *aSourceAbscissa, const cpl_array *aSourceOrdinate)
Linear interpolation of a 1d array.
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.
cpl_error_code muse_lsf_apply(const cpl_image *aLsfImage, const muse_wcs *aWCS, cpl_array *aVal, double aLambda)
Apply the LSF to a number of data points of one slice.
muse_pixtable * muse_pixtable_create(muse_image *aImage, cpl_table *aTrace, cpl_table *aWave, cpl_table *aGeoTable)
Create the pixel table for one CCD.
cpl_error_code muse_cplarray_add_window(cpl_array *aDest, cpl_size aStart, const cpl_array *aArray)
Add the value of an array to a window of a table column.
char * muse_utils_header_get_lamp_names(cpl_propertylist *aHeader, char aSep)
Concatenate names of all active calibration lamps.
Definition: muse_utils.c:989
#define MUSE_PIXTABLE_ORIGIN
Definition: muse_pixtable.h:54
cpl_size muse_cpltable_find_sorted(const cpl_table *aTable, const char *aColumn, double aValue)
Find a row in a table.
unsigned short muse_pixtable_origin_get_ifu(uint32_t aOrigin)
Get the IFU number from the encoded 32bit origin number.
#define MUSE_PIXTABLE_STAT
Definition: muse_pixtable.h:50
void muse_lsf_cube_delete_all(muse_lsf_cube **aLsfCube)
Delete all LSF cubes.
const muse_cpltable_def muse_pixtable_def[]
MUSE pixel table definition.
muse_wcs * muse_lsf_cube_get_wcs_all(muse_lsf_cube **aLsfCubes)
Get the world coordinate representative of all LSF cubes.
cpl_frameset * inframes
#define MUSE_PIXTABLE_LAMBDA
Definition: muse_pixtable.h:53
muse_pixtable * muse_lsf_create_arcpixtable(muse_imagelist *aImages, cpl_table *aTrace, cpl_table *aWave, cpl_table *aArcLines, int aQuality, double aWindow)
Read images and combine the arc lines into one pixtable.
cpl_error_code muse_lsf_fold_rectangle(cpl_image *aLsfImage, const muse_wcs *aWCS, double aBinWidth)
Filter an LSF image with a rectangle to model spectrum binning.
void muse_lsf_cube_delete(muse_lsf_cube *aLsfCube)
Deallocate the memory for the LSF cube.
cpl_imagelist * img
Stacked image list for LSF; one per slice.
Definition: muse_lsf.h:53
double crval2
Definition: muse_wcs.h:107
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
void muse_pixtable_delete(muse_pixtable *aPixtable)
Deallocate memory associated to a pixel table object.
cpl_size muse_cplarray_find_sorted(const cpl_array *aArray, double aValue)
Find a row in an array.
muse_ins_mode muse_pfits_get_mode(const cpl_propertylist *aHeaders)
find out the observation mode
Definition: muse_pfits.c:1352
cpl_error_code muse_lsf_fit_slice(const muse_pixtable *aPixtable, cpl_image *aLsfImage, muse_wcs *aWCS, double aLsfRegressionWindow)
Compute the LSF for all wavelengths of one slice.
cpl_propertylist * header
The FITS header.