MUSE Pipeline Reference Manual  2.5.2
muse_pixtable.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-2016 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 <cpl.h>
30 #include <math.h>
31 #include <string.h>
32 
33 #include "muse_pixtable.h"
34 #include "muse_instrument.h"
35 
36 #include "muse_cplwrappers.h"
37 #include "muse_geo.h"
38 #include "muse_mask.h"
39 #include "muse_pfits.h"
40 #include "muse_quadrants.h"
41 #include "muse_quality.h"
42 #include "muse_postproc.h"
43 #include "muse_tracing.h"
44 #include "muse_wavecalib.h"
45 #include "muse_wcs.h"
46 #include "muse_utils.h"
47 
48 /*----------------------------------------------------------------------------*
49  * Debugging Macros *
50  * Set these to 1 or higher for (lots of) debugging output *
51  *----------------------------------------------------------------------------*/
52 #define CREATE_MINIMAL_PIXTABLE 0 /* create a very small pixel table */
53 #define PIXTABLE_CREATE_CCDSIZED 1 /* start with pixel table sized like input image */
54 #define DEBUG_PIXTABLE_CREATION 0 /* some table dumps in muse_pixtable_create() */
55 #define DEBUG_PIXTABLE_FEW_SLICES 0 /* when doing quick pixel table creation for *
56  * debugging, set this to a value below 48 */
57 #define PIXTABLE_MASK_PARALLEL 0 /* make muse_pixtable_and_selected_mask() *
58  * OpenMP-parallel (little gains) */
59 
60 /*----------------------------------------------------------------------------*/
98 /*----------------------------------------------------------------------------*/
99 
102 /* Let's use macros for the shift lengths we need */
103 #define MUSE_ORIGIN_SHIFT_XSLICE 24
104 #define MUSE_ORIGIN_SHIFT_YPIX 11
105 #define MUSE_ORIGIN_SHIFT_IFU 6
106 /* spacing between the left slice edge at the bottom of the slice *
107  * to the origin of the slice from where we could x positions within *
108  * the slice; this is to make sure that no pixel is left of the offset */
109 #define MUSE_ORIGIN_SLICE_SAFETY_OFFSET -20
110 
111 /* private functions without error checking */
113 static inline uint32_t
114 muse_pixtable_origin_encode_fast(unsigned int aX, unsigned int aY,
115  unsigned short aIFU,
116  unsigned short aSlice, unsigned int aOffset)
117 {
118  return ((aX - aOffset) << MUSE_ORIGIN_SHIFT_XSLICE)
119  | (aY << MUSE_ORIGIN_SHIFT_YPIX)
120  | (aIFU << MUSE_ORIGIN_SHIFT_IFU)
121  | aSlice;
122 }
123 
125 static inline unsigned int
126 muse_pixtable_origin_get_x_fast(uint32_t aOrigin, uint32_t aOffset)
127 {
128  return ((aOrigin >> MUSE_ORIGIN_SHIFT_XSLICE) & 0x7f) + aOffset;
129 }
130 
132 static inline unsigned int
133 muse_pixtable_origin_get_y_fast(uint32_t aOrigin)
134 {
135  return (aOrigin >> MUSE_ORIGIN_SHIFT_YPIX) & 0x1fff;
136 }
137 
139 static inline unsigned short
140 muse_pixtable_origin_get_ifu_fast(uint32_t aOrigin)
141 {
142  return (aOrigin >> MUSE_ORIGIN_SHIFT_IFU) & 0x1f;
143 }
144 
146 static inline unsigned short
147 muse_pixtable_origin_get_slice_fast(uint32_t aOrigin)
148 {
149  return aOrigin & 0x3f;
150 }
151 
152 /*---------------------------------------------------------------------------*/
168 /*---------------------------------------------------------------------------*/
169 uint32_t
170 muse_pixtable_origin_encode(unsigned int aX, unsigned int aY,
171  unsigned short aIFU,
172  unsigned short aSlice, unsigned int aOffset)
173  /* use the explicit 32bit return type so that *
174  * this also works on systems with other setups */
175 {
176  /* check for allowed values to fit into 32bit */
177  cpl_ensure(aX < 8192 && aX > 0 && aY < 8192 && aY > 0 &&
178  aIFU <= kMuseNumIFUs && aIFU >= 1 &&
179  aSlice <= kMuseSlicesPerCCD && aSlice >= 1 && aOffset < 8192,
180  CPL_ERROR_ILLEGAL_INPUT, 0);
181 
182 #if 0
183  cpl_msg_debug(__func__, "origin (%d, %d, %d, %d, %d) = 0x%x",
184  aX, aY, aIFU, aSlice, aOffset,
185  ((aX - aOffset) << MUSE_ORIGIN_SHIFT_XSLICE)
186  | (aY << MUSE_ORIGIN_SHIFT_YPIX)
187  | (aIFU << MUSE_ORIGIN_SHIFT_IFU)
188  | aSlice);
189 #endif
190 
191  /* do the bit-shifting "magic" */
192  return muse_pixtable_origin_encode_fast(aX, aY, aIFU, aSlice, aOffset);
193 } /* muse_pixtable_origin_encode() */
194 
195 /*---------------------------------------------------------------------------*/
213 /*---------------------------------------------------------------------------*/
214 unsigned int
215 muse_pixtable_origin_get_x(uint32_t aOrigin, muse_pixtable *aPixtable,
216  cpl_size aRow)
217 {
218  unsigned short slice = muse_pixtable_origin_get_slice_fast(aOrigin),
219  ifu = muse_pixtable_origin_get_ifu_fast(aOrigin);
220  cpl_errorstate prestate = cpl_errorstate_get();
221  unsigned int expnum = muse_pixtable_get_expnum(aPixtable, aRow);
222  if (!cpl_errorstate_is_equal(prestate)) {
223  cpl_errorstate_set(prestate);
224  }
225  unsigned int offset = muse_pixtable_origin_get_offset(aPixtable, expnum, ifu,
226  slice),
227  x = muse_pixtable_origin_get_x_fast(aOrigin, offset);
228 #if 0
229  if (x > 8191 || x < 1 || !cpl_errorstate_is_equal(prestate)) {
230  cpl_msg_error(__func__, "aOrigin=%#x x=%d (%d %d %d), %s",
231  aOrigin, x, slice, ifu, offset, cpl_error_get_message());
232  }
233 #endif
234  cpl_ensure(x <= 8191 && x >= 1 && cpl_errorstate_is_equal(prestate),
235  CPL_ERROR_ILLEGAL_OUTPUT, 0);
236  return x;
237 } /* muse_pixtable_origin_get_x() */
238 
239 /*---------------------------------------------------------------------------*/
247 /*---------------------------------------------------------------------------*/
248 unsigned int
249 muse_pixtable_origin_get_y(uint32_t aOrigin)
250 {
251  unsigned int y = muse_pixtable_origin_get_y_fast(aOrigin);
252 #if 0
253  if (y > 8191 || y < 1) {
254  cpl_msg_error(__func__, "aOrigin=%#x y=%d", aOrigin, y);
255  }
256 #endif
257  cpl_ensure(y <= 8191 && y >= 1, CPL_ERROR_ILLEGAL_OUTPUT, 0);
258  return y;
259 } /* muse_pixtable_origin_get_y() */
260 
261 /*---------------------------------------------------------------------------*/
269 /*---------------------------------------------------------------------------*/
270 unsigned short
272 {
273  unsigned short ifu = muse_pixtable_origin_get_ifu_fast(aOrigin);
274 #if 0
275  if (ifu > kMuseNumIFUs || ifu < 1) {
276  cpl_msg_error(__func__, "aOrigin=%#x ifu=%d", aOrigin, ifu);
277  }
278 #endif
279  cpl_ensure(ifu <= kMuseNumIFUs && ifu >= 1, CPL_ERROR_ILLEGAL_OUTPUT, 0);
280  return ifu;
281 } /* muse_pixtable_origin_get_ifu() */
282 
283 /*---------------------------------------------------------------------------*/
291 /*---------------------------------------------------------------------------*/
292 unsigned short
294 {
295  unsigned short slice = muse_pixtable_origin_get_slice_fast(aOrigin);
296 #if 0
297  if (slice > kMuseSlicesPerCCD || slice < 1) {
298  cpl_msg_error(__func__, "aOrigin=%#x slice=%d", aOrigin, slice);
299  }
300 #endif
301  cpl_ensure(slice <= kMuseSlicesPerCCD && slice >= 1,
302  CPL_ERROR_ILLEGAL_OUTPUT, 0);
303  return slice;
304 } /* muse_pixtable_origin_get_slice() */
305 
306 /*---------------------------------------------------------------------------*/
321 /*---------------------------------------------------------------------------*/
322 unsigned int
324  cpl_polynomial *aLTrace,
325  unsigned short aIFU, unsigned short aSlice)
326 {
327  cpl_ensure(aPixtable && aPixtable->header, CPL_ERROR_NULL_INPUT, 0);
328  cpl_errorstate prestate = cpl_errorstate_get();
329  unsigned int offset = floor(cpl_polynomial_eval_1d(aLTrace, 1, NULL))
330  + MUSE_ORIGIN_SLICE_SAFETY_OFFSET;
331  cpl_ensure(cpl_errorstate_is_equal(prestate), cpl_error_get_code(), 0);
332  /* use exposure number 0 here, this is set only later, *
333  * when merging pixel tables of different exposures */
334  char *keyword = cpl_sprintf(MUSE_HDR_PT_IFU_SLICE_OFFSET, 0, aIFU, aSlice);
335  cpl_propertylist_update_int(aPixtable->header, keyword, offset);
336  cpl_propertylist_set_comment(aPixtable->header, keyword,
337  MUSE_HDR_PT_IFU_SLICE_OFFSET_COMMENT);
338  cpl_free(keyword);
339  return offset;
340 } /* muse_pixtable_origin_set_offset() */
341 
342 /*---------------------------------------------------------------------------*/
356 /*---------------------------------------------------------------------------*/
357 unsigned int
358 muse_pixtable_origin_get_offset(muse_pixtable *aPixtable, unsigned int aExpNum,
359  unsigned short aIFU, unsigned short aSlice)
360 {
361  cpl_ensure(aPixtable && aPixtable->header, CPL_ERROR_NULL_INPUT, 0);
362  char *keyword = cpl_sprintf(MUSE_HDR_PT_IFU_SLICE_OFFSET, aExpNum, aIFU,
363  aSlice);
364  cpl_errorstate prestate = cpl_errorstate_get();
365  unsigned int offset = cpl_propertylist_get_int(aPixtable->header, keyword);
366  cpl_free(keyword);
367 #if 0
368  if (offset > 8191 || offset < 1) {
369  cpl_msg_error(__func__, "aIFU=%d aSlice=%d offset=%d",
370  aIFU, aSlice, offset);
371  }
372 #endif
373  cpl_ensure(offset <= 8191 && offset >= 1 && cpl_errorstate_is_equal(prestate),
374  CPL_ERROR_ILLEGAL_OUTPUT, 0);
375  return offset;
376 } /* muse_pixtable_origin_get_offset() */
377 
378 /*---------------------------------------------------------------------------*/
398 /*---------------------------------------------------------------------------*/
399 cpl_error_code
401  unsigned int aNum)
402 {
403  cpl_ensure_code(aOut && aOut->header, CPL_ERROR_NULL_INPUT);
404  cpl_propertylist *dest = aOut->header,
405  *from = aOut->header;
406  if (aFrom && aFrom->header) {
407  from = aFrom->header;
408  }
409  char keyword[KEYWORD_LENGTH];
410  unsigned short nifu, nslice;
411  for (nifu = 1; nifu <= kMuseNumIFUs; nifu++) {
412  for (nslice = 1; nslice <= kMuseSlicesPerCCD; nslice++) {
413  /* keyword to copy */
414  snprintf(keyword, KEYWORD_LENGTH, MUSE_HDR_PT_IFU_SLICE_OFFSET,
415  0, nifu, nslice);
416  cpl_errorstate prestate = cpl_errorstate_get();
417  unsigned int offset = cpl_propertylist_get_int(from, keyword);
418  if (!cpl_errorstate_is_equal(prestate)) {
419  /* this one was not set, skip to the next one */
420  cpl_errorstate_set(prestate);
421  continue;
422  }
423  /* erase old keyword */
424  cpl_propertylist_erase(from, keyword);
425  /* add new keyword */
426  snprintf(keyword, KEYWORD_LENGTH, MUSE_HDR_PT_IFU_SLICE_OFFSET,
427  aNum, nifu, nslice);
428  cpl_propertylist_update_int(dest, keyword, offset);
429  cpl_propertylist_set_comment(dest, keyword,
430  MUSE_HDR_PT_IFU_SLICE_OFFSET_COMMENT);
431  } /* for nslice */
432  } /* for nifu */
433 
434  return CPL_ERROR_NONE;
435 } /* muse_pixtable_origin_copy_offsets() */
436 
437 /*---------------------------------------------------------------------------*/
456 /*---------------------------------------------------------------------------*/
457 cpl_error_code
459  unsigned short **aX, unsigned short **aY,
460  unsigned char **aIFU, unsigned char **aSlice)
461 {
462  /* pixel table with origin column is needed */
463  cpl_ensure_code(aPixtable, CPL_ERROR_NULL_INPUT);
464  const uint32_t *origin
465  = (uint32_t *)cpl_table_get_data_int_const(aPixtable->table,
467  cpl_ensure_code(origin, CPL_ERROR_BAD_FILE_FORMAT);
468  cpl_ensure_code(aX && aIFU && aSlice, CPL_ERROR_NULL_INPUT);
469 
470  /* allocate the output buffers */
471  cpl_size nrow = muse_pixtable_get_nrow(aPixtable);
472  *aX = cpl_malloc(nrow * sizeof(unsigned short));
473  if (aY) {
474  *aY = cpl_malloc(nrow * sizeof(unsigned short));
475  }
476  *aIFU = cpl_malloc(nrow * sizeof(unsigned char));
477  *aSlice = cpl_malloc(nrow * sizeof(unsigned char));
478 
479  /* check how many exposures there are in this pixel table: *
480  * if there is only one (exposure number for first and last entry are
481  * identical, i.e. zero), then we do not need to recompute the exposure number
482  * at all, otherwise we need to do that for each new slice */
483  cpl_errorstate prestate = cpl_errorstate_get();
484  unsigned int expnum = muse_pixtable_get_expnum(aPixtable, 0),
485  expnumN = muse_pixtable_get_expnum(aPixtable, nrow - 1);
486  if (!cpl_errorstate_is_equal(prestate)) {
487  cpl_errorstate_set(prestate);
488  }
489  cpl_boolean multiexp = expnum != expnumN;
490 
491  /* how loop through the table and fill the buffers */
492  unsigned int offset = 0;
493  cpl_size i;
494  for (i = 0; i < nrow; i++) {
495  (*aIFU)[i] = muse_pixtable_origin_get_ifu_fast(origin[i]);
496  (*aSlice)[i] = muse_pixtable_origin_get_slice_fast(origin[i]);
497 
498  /* need to get the slice offset to get a proper X coordinate */
499  if ((i == 0) || (i > 0 && ((*aSlice)[i] != (*aSlice)[i-1]))) {
500  /* IFUs/exposures only change at slice boundaries */
501  if (multiexp && i > 0 && (*aIFU)[i] != (*aIFU)[i-1]) {
502  expnum = muse_pixtable_get_expnum(aPixtable, i);
503  }
504 
505  /* need to (re-)compute the slice offset */
506  offset = muse_pixtable_origin_get_offset(aPixtable, expnum, (*aIFU)[i],
507  (*aSlice)[i]);
508  } /* if new slice */
509 
510  (*aX)[i] = muse_pixtable_origin_get_x_fast(origin[i], offset);
511  if (aY) {
512  (*aY)[i]= muse_pixtable_origin_get_y_fast(origin[i]);
513  }
514  } /* for i (pixel table rows) */
515 
516  return CPL_ERROR_NONE;
517 } /* muse_pixtable_origin_decode_all() */
518 
519 /*---------------------------------------------------------------------------*/
534 /*---------------------------------------------------------------------------*/
535 unsigned int
536 muse_pixtable_get_expnum(muse_pixtable *aPixtable, cpl_size aRow)
537 {
538  cpl_ensure(aPixtable && aPixtable->header, CPL_ERROR_NULL_INPUT, 0);
539  cpl_ensure(aRow >= 0 && muse_pixtable_get_nrow(aPixtable) > aRow,
540  CPL_ERROR_ILLEGAL_INPUT, 0);
541 
542  char keyword[KEYWORD_LENGTH];
543  unsigned int exposure = 0;
544  cpl_size lo = 0, hi = 0;
545  do {
546  cpl_errorstate prestate = cpl_errorstate_get();
547  snprintf(keyword, KEYWORD_LENGTH, MUSE_HDR_PT_EXP_FST, ++exposure);
548  lo = cpl_propertylist_get_long_long(aPixtable->header, keyword);
549  snprintf(keyword, KEYWORD_LENGTH, MUSE_HDR_PT_EXP_LST, exposure);
550  hi = cpl_propertylist_get_long_long(aPixtable->header, keyword);
551  if (!cpl_errorstate_is_equal(prestate)) {
552  if (exposure == 1) {
553  /* no exposure headers in the table at all, so it's either the *
554  * only one or the table was sorted, destroying exposure info */
555  lo = hi = aRow;
556  exposure = 0; /* signify the problem to the caller */
557  }
558  cpl_errorstate_set(prestate);
559  break;
560  }
561  } while (hi < aRow);
562  cpl_ensure(lo <= aRow && hi >= aRow, CPL_ERROR_ILLEGAL_OUTPUT, 0);
563  return exposure;
564 } /* muse_pixtable_get_expnum */
565 
566 /*----------------------------------------------------------------------------*/
586 /*----------------------------------------------------------------------------*/
588  { MUSE_PIXTABLE_XPOS, CPL_TYPE_FLOAT, "pix", "%7.2f",
589  "relative x-pixel position in the output datacube", CPL_TRUE},
590  { MUSE_PIXTABLE_YPOS, CPL_TYPE_FLOAT, "pix", "%7.2f",
591  "relative y-pixel position in the output datacube", CPL_TRUE},
592  { MUSE_PIXTABLE_LAMBDA, CPL_TYPE_FLOAT, "Angstrom", "%8.2f",
593  "wavelength of this pixel", CPL_TRUE},
594  { MUSE_PIXTABLE_DATA, CPL_TYPE_FLOAT, "count", "%e",
595  "data value in this pixel", CPL_TRUE},
596  { MUSE_PIXTABLE_DQ, CPL_TYPE_INT, NULL, "%#x",
597  "Euro3D bad pixel status of this pixel", CPL_TRUE},
598  { MUSE_PIXTABLE_STAT, CPL_TYPE_FLOAT, "count**2", "%e",
599  "data variance of this pixel", CPL_TRUE},
600  { MUSE_PIXTABLE_ORIGIN, CPL_TYPE_INT, NULL, "0x%08x",
601  "encoded value of IFU and slice number, as well as x and y "
602  "position in the raw (trimmed) data", CPL_TRUE},
603  { NULL, 0, NULL, NULL, NULL, CPL_FALSE }
604 };
605 
606 /*---------------------------------------------------------------------------*/
652 /*---------------------------------------------------------------------------*/
654 muse_pixtable_create(muse_image *aImage, cpl_table *aTrace, cpl_table *aWave,
655  cpl_table *aGeoTable)
656 {
657  cpl_ensure(aImage && aWave && aTrace, CPL_ERROR_NULL_INPUT, NULL);
658  /* get and check IFU number */
659  unsigned char ifu = muse_utils_get_ifu(aImage->header);
660  cpl_ensure(ifu >= 1 && ifu <= kMuseNumIFUs, CPL_ERROR_DATA_NOT_FOUND, NULL);
661 
662  /* check that the input data is in count units */
663  if (!cpl_propertylist_has(aImage->header, "BUNIT")) {
664  char *msg = cpl_sprintf("Input data of IFU %hhu does not contain a data "
665  "unit (\"BUNIT\"), cannot proceed!", ifu);
666  cpl_msg_error(__func__, "%s", msg);
667  cpl_error_set_message(__func__, CPL_ERROR_INCOMPATIBLE_INPUT, "%s", msg);
668  cpl_free(msg);
669  return NULL;;
670  }
671  const char *unit = muse_pfits_get_bunit(aImage->header);
672  if (strncmp(unit, "count", 6)) {
673  char *msg = cpl_sprintf("Input data of IFU %hhu is not in \"count\" units "
674  "but in \"%s\", not suitable for a new pixel table!",
675  ifu, unit);
676  cpl_msg_error(__func__, "%s", msg);
677  cpl_error_set_message(__func__, CPL_ERROR_INCOMPATIBLE_INPUT, "%s", msg);
678  cpl_free(msg);
679  return NULL;
680  }
681 
682  /* create the output pixel table structure, and NULL out the components */
683  muse_pixtable *pt = cpl_calloc(1, sizeof(muse_pixtable));
684  /* compute initial table size */
685  int xsize = cpl_image_get_size_x(aImage->data),
686  ysize = cpl_image_get_size_y(aImage->data),
687 #if PIXTABLE_CREATE_CCDSIZED
688  /* There cannot be more pixels needed in the table than in the *
689  * input image, so with this we can remove the overflow check below. */
690  isize = xsize * ysize;
691 #else
692  /* It's very likely that no more pixels than these are needed. But then *
693  * we need to check for overflows below (and still cut it in the end). */
694  isize = ysize * kMuseSlicesPerCCD * kMuseSliceHiLikelyWidth;
695 #endif
696  pt->table = muse_cpltable_new(muse_pixtable_def, isize);
697 
698  /* copy the header from the input image to the pixel table, *
699  * but remove some keywords that could cause trouble */
700  pt->header = cpl_propertylist_duplicate(aImage->header);
701  cpl_propertylist_erase_regexp(pt->header,
702  "^SIMPLE$|^BITPIX$|^NAXIS|^EXTEND$|^XTENSION$|"
703  "^DATASUM$|^DATAMIN$|^DATAMAX$|^DATAMD5$|"
704  "^PCOUNT$|^GCOUNT$|^HDUVERS$|^BLANK$|"
705  "^BZERO$|^BSCALE$|^BUNIT$|^CHECKSUM$|^INHERIT$|"
706  MUSE_HDR_OVSC_REGEXP"|"MUSE_WCS_KEYS, 0);
707  cpl_propertylist_append_string(pt->header, MUSE_HDR_PT_TYPE,
708  aGeoTable ? MUSE_PIXTABLE_STRING_FULL
709  : MUSE_PIXTABLE_STRING_SIMPLE);
710  cpl_propertylist_set_comment(pt->header, MUSE_HDR_PT_TYPE,
711  aGeoTable ? MUSE_PIXTABLE_COMMENT_FULL
712  : MUSE_PIXTABLE_COMMENT_SIMPLE);
713 
714  /* make all table cells valid by filling them with zeros; this is a workaround *
715  * suggested by Carlo Izzo to be able to set the table cells using array *
716  * access instead of the slower and non-threadsafe cpl_table_set() function */
717  cpl_table_fill_column_window_float(pt->table, MUSE_PIXTABLE_XPOS, 0, isize, 0);
718  cpl_table_fill_column_window_float(pt->table, MUSE_PIXTABLE_YPOS, 0, isize, 0);
719  cpl_table_fill_column_window_float(pt->table, MUSE_PIXTABLE_LAMBDA, 0, isize, 0);
720  cpl_table_fill_column_window_float(pt->table, MUSE_PIXTABLE_DATA, 0, isize, 0);
721  cpl_table_fill_column_window_float(pt->table, MUSE_PIXTABLE_STAT, 0, isize, 0);
722  cpl_table_fill_column_window_int(pt->table, MUSE_PIXTABLE_DQ, 0, isize, 0);
723  cpl_table_fill_column_window_int(pt->table, MUSE_PIXTABLE_ORIGIN, 0, isize, 0);
724 
725  /* get columns as pointers */
726  float *cdata_xpos = cpl_table_get_data_float(pt->table, MUSE_PIXTABLE_XPOS),
727  *cdata_ypos = cpl_table_get_data_float(pt->table, MUSE_PIXTABLE_YPOS),
728  *cdata_lambda = cpl_table_get_data_float(pt->table, MUSE_PIXTABLE_LAMBDA),
729  *cdata_data = cpl_table_get_data_float(pt->table, MUSE_PIXTABLE_DATA),
730  *cdata_stat = cpl_table_get_data_float(pt->table, MUSE_PIXTABLE_STAT);
731  int *cdata_dq = cpl_table_get_data_int(pt->table, MUSE_PIXTABLE_DQ);
732  uint32_t *cdata_origin = (uint32_t *)cpl_table_get_data_int(pt->table,
734 
735  /* get input image buffers as pointers, too */
736  const float *pixdata = cpl_image_get_data_float_const(aImage->data),
737  *pixstat = cpl_image_get_data_float_const(aImage->stat);
738  const int *pixdq = cpl_image_get_data_int_const(aImage->dq);
739 
740  /* get columns of the wavecal table */
741  unsigned short wavexorder, waveyorder;
742  muse_wave_table_get_orders(aWave, &wavexorder, &waveyorder);
743  cpl_msg_info(__func__, "Creating pixel table for IFU %hhu, using order %d for "
744  "trace solution and orders %hu/%hu for wavelength solution", ifu,
745  muse_trace_table_get_order(aTrace), wavexorder, waveyorder);
746 
747  /* get position corresponding to the IFU number */
748  cpl_table *geopos = NULL;
749  double *slice_x = NULL, *slice_y = NULL, *slice_angle = NULL,
750  *slice_width = NULL;
751  if (aGeoTable) {
752  geopos = muse_geo_table_extract_ifu(aGeoTable, ifu);
753  slice_x = cpl_table_get_data_double(geopos, MUSE_GEOTABLE_X);
754  slice_y = cpl_table_get_data_double(geopos, MUSE_GEOTABLE_Y);
755  /* fail on missing x/y as they are critical */
756  if (!geopos || !slice_x || !slice_y) {
757  char *msg = !geopos
758  ? cpl_sprintf("Geometry table is missing data for IFU %hhu!", ifu)
759  : cpl_sprintf("Geometry table is missing column%s%s%s!",
760  !slice_x && !slice_y ? "s" : "",
761  slice_x ? "" : " \""MUSE_GEOTABLE_X"\"",
762  slice_y ? "" : " \""MUSE_GEOTABLE_Y"\"");
763  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_INPUT, "%s", msg);
764  cpl_msg_error(__func__, "%s", msg);
765  cpl_free(msg);
766  cpl_table_delete(geopos);
768  return NULL;
769  }
770  /* only output warnings for other missing columns, they *
771  * default to usable values below, ignore CPL errors */
772  cpl_errorstate prestate = cpl_errorstate_get();
773  slice_angle = cpl_table_get_data_double(geopos, MUSE_GEOTABLE_ANGLE);
774  slice_width = cpl_table_get_data_double(geopos, MUSE_GEOTABLE_WIDTH);
775  if (!cpl_errorstate_is_equal(prestate)) {
776  char *msg = cpl_sprintf("Geometry table is missing column%s%s%s!",
777  !slice_angle && !slice_width ? "s" : "",
778  slice_angle ? "" : " \""MUSE_GEOTABLE_ANGLE"\"",
779  slice_width ? "" : " \""MUSE_GEOTABLE_WIDTH"\"");
780  cpl_error_set_message(__func__, CPL_ERROR_BAD_FILE_FORMAT, "%s", msg);
781  cpl_msg_error(__func__, "%s", msg);
782  cpl_free(msg);
783  if (!getenv("MUSE_EXPERT_USER")) {
784  cpl_table_delete(geopos);
786  return NULL;
787  }
788  } /* if */
789  } /* if aGeoTable */
790 
791  /* this counts the current table row that is being entered */
792  cpl_size itablerow = 0;
793  /* time the operation for this IFU */
794  double cputime = cpl_test_get_cputime(),
795  walltime = cpl_test_get_walltime();
796  /* loop through all slices */
797  int islice;
798 #if DEBUG_PIXTABLE_FEW_SLICES > 0
799 # define SLICE_LIMIT DEBUG_PIXTABLE_FEW_SLICES
800 #else
801 # define SLICE_LIMIT kMuseSlicesPerCCD
802 #endif
803  for (islice = 0; islice < SLICE_LIMIT; islice++) {
804 #if DEBUG_PIXTABLE_CREATION /* check how many pixels extend over the nominal width */
805  cpl_msg_debug(__func__, "Starting to process slice %2d of IFU %2hhu",
806  islice + 1, ifu);
807 #endif
808 
809  /* fill the wavelength calibration polynomial for this slice */
810  cpl_polynomial *pwave = muse_wave_table_get_poly_for_slice(aWave, islice + 1);
811  /* vector for the position within the slice (for evaluation *
812  * of the wavelength solution in two dimensions */
813  cpl_vector *pos = cpl_vector_new(2);
814 
815  /* test evaluate the wavelength polynomial to see if it's valid */
816  cpl_vector_set(pos, 0, kMuseOutputYTop / 2);
817  cpl_vector_set(pos, 1, kMuseOutputYTop / 2);
818  double ltest = cpl_polynomial_eval(pwave, pos);
819  if (!pwave || !isnormal(ltest) || fabs(ltest) < DBL_EPSILON) {
820  char *msg = cpl_sprintf("Wavelength calibration polynomial for slice %d "
821  "of IFU %hhu is not well defined!", islice + 1,
822  ifu);
823  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_INPUT, "%s", msg);
824  cpl_msg_error(__func__, "%s", msg);
825  cpl_free(msg);
826  cpl_polynomial_delete(pwave);
827  cpl_vector_delete(pos);
828  if (getenv("MUSE_EXPERT_USER")) {
829  continue; /* go the next slice */
830  } else { /* give up completely */
831  cpl_table_delete(geopos);
833  return NULL;
834  }
835  } /* if bad wavecal polynomial */
836 
837  /* get the tracing polynomials for this slice */
838  cpl_polynomial **ptrace = muse_trace_table_get_polys_for_slice(aTrace,
839  islice + 1);
840  if (!ptrace) {
841  char *msg = cpl_sprintf("Tracing polynomials for slice %d of IFU %hhu are"
842  " not well defined!", islice + 1, ifu);
843  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_INPUT, "%s", msg);
844  cpl_msg_error(__func__, "%s", msg);
845  cpl_free(msg);
846  cpl_polynomial_delete(pwave);
847  cpl_vector_delete(pos);
848  if (getenv("MUSE_EXPERT_USER")) {
849  continue; /* go the next slice */
850  } else { /* give up completely */
851  cpl_table_delete(geopos);
853  return NULL;
854  }
855  } /* if no tracing polynomials */
856  unsigned offset = muse_pixtable_origin_set_offset(pt,
857  ptrace[MUSE_TRACE_LEFT],
858  ifu, islice + 1);
859 
860  /* within each slice, loop from bottom to top */
861  int j;
862  for (j = 1; j <= ysize; j++) {
863  /* compute slice center for this vertical position and set the *
864  * edge pixels of slice, so that we can loop over those pixels */
865  double x1 = cpl_polynomial_eval_1d(ptrace[MUSE_TRACE_LEFT], j, NULL),
866  x2 = cpl_polynomial_eval_1d(ptrace[MUSE_TRACE_RIGHT], j, NULL),
867  xcenter = (x1 + x2) / 2.,
868  width = x2 - x1;
869  if (!isnormal(x1) || !isnormal(x2) || x1 < 1 || x2 > xsize || x1 > x2) {
870  cpl_msg_warning(__func__, "slice %2d of IFU %hhu: faulty polynomial "
871  "detected at y=%d (borders: %f ... %f)", islice + 1,
872  ifu, j, x1, x2);
873  break; /* skip the rest of this slice */
874  }
875  /* include pixels that have more than half of them inside the slice */
876  int ileft = ceil(x1),
877  iright = floor(x2);
878  cpl_vector_set(pos, 1, j); /* vertical pos. for wavelength evaluation */
879 
880  /* now loop over all pixels of this slice horizontally */
881  int i;
882  for (i = ileft; i <= iright; i++) {
883  cpl_vector_set(pos, 0, i); /* horiz. pos. for wavelength evaluation */
884 
885  /* do the wavelength evaluation early on, to more quickly *
886  * recover from errors */
887  double lambda = cpl_polynomial_eval(pwave, pos);
888  if (lambda < 3000. || lambda > 11000. || !isfinite(lambda)) {
889  continue; /* skip this pixel */
890  }
891 
892  /* Relative horizontal pixel position within slice; has to be scaled *
893  * by the width of the slice on the CCD. Slice width is measured *
894  * horizontally, not along iso-lambda lines, the difference for *
895  * straight lines is below 0.015 pix (0.02%), and only slightly *
896  * larger for curved lines, so this simplification should not have a *
897  * negative effect on anything. We compute (xcenter - i) to account *
898  * for the reversed sky orientation within each slice. */
899  float dx = (xcenter - i) / width
900  * (slice_width ? slice_width[islice] : kMuseSliceNominalWidth);
901 #if DEBUG_PIXTABLE_CREATION /* check how many pixels extend over the nominal width */
902  if (fabs(dx) > 37.5) {
903  cpl_msg_debug(__func__, "%d - %f -> %f", i, xcenter, dx);
904  }
905 #endif
906 
907 #if CREATE_MINIMAL_PIXTABLE
908  /* if we need to create a very small pixel table for debugging */
909  if (lambda < 6495. || lambda > 6505. || fabs(dx) > 10.) {
910  continue;
911  }
912 #endif
913 
914  /* this pixel is set up to be inside the slice, write it to the table */
915  cpl_size irow = itablerow++; /* started at 0, so increment after assignment */
916 #if !PIXTABLE_CREATE_CCDSIZED /* overflow check, and possibly enlarge the table */
917  if (irow + 1 > (cpl_size)muse_pixtable_get_nrow(pt)) {
918 #if DEBUG_PIXTABLE_CREATION /* make sure that we are filling the right part */
919  printf("pixel table before enlargement:\n");
920  cpl_table_dump(pt->table, irow-5, 10, stdout);
921  fflush(stdout);
922 #endif
923  /* If the table is too small, we can as well add a lot more rows *
924  * right now, than adding them in small portions. If we add too many *
925  * this will only marginally decrease the speed of this procedure */
926  const cpl_size nr = 1000000;
927  cpl_msg_debug(__func__, "expand table to %"CPL_SIZE_FORMAT" rows "
928  "(add %"CPL_SIZE_FORMAT" lines)!", irow + nr, nr);
929  cpl_table_set_size(pt->table, irow + nr);
930 
931  /* again fill the new section of each column */
932  cpl_table_fill_column_window_float(pt->table, MUSE_PIXTABLE_XPOS, irow, nr, 0);
933  cpl_table_fill_column_window_float(pt->table, MUSE_PIXTABLE_YPOS, irow, nr, 0);
934  cpl_table_fill_column_window_float(pt->table, MUSE_PIXTABLE_LAMBDA, irow, nr, 0);
935  cpl_table_fill_column_window_float(pt->table, MUSE_PIXTABLE_DATA, irow, nr, 0);
936  cpl_table_fill_column_window_float(pt->table, MUSE_PIXTABLE_STAT, irow, nr, 0);
937  cpl_table_fill_column_window_int(pt->table, MUSE_PIXTABLE_DQ, irow, nr, 0);
938  cpl_table_fill_column_window_int(pt->table, MUSE_PIXTABLE_ORIGIN, irow, nr, 0);
939 
940  /* re-get columns as pointers, the memory location might have changed */
941  cdata_xpos = cpl_table_get_data_float(pt->table, MUSE_PIXTABLE_XPOS);
942  cdata_ypos = cpl_table_get_data_float(pt->table, MUSE_PIXTABLE_YPOS);
943  cdata_lambda = cpl_table_get_data_float(pt->table, MUSE_PIXTABLE_LAMBDA);
944  cdata_data = cpl_table_get_data_float(pt->table, MUSE_PIXTABLE_DATA);
945  cdata_stat = cpl_table_get_data_float(pt->table, MUSE_PIXTABLE_STAT);
946  cdata_dq = cpl_table_get_data_int(pt->table, MUSE_PIXTABLE_DQ);
947  cdata_origin = (uint32_t *)cpl_table_get_data_int(pt->table,
949 #if DEBUG_PIXTABLE_CREATION /* make sure that we have filled the right part */
950  printf("pixel table after filling new rows:\n");
951  cpl_table_dump(pt->table, irow-5, 10, stdout);
952  fflush(stdout);
953 #endif
954  } /* if new rows needed */
955 #endif /* !PIXTABLE_CREATE_CCDSIZED */
956 
957  /* Assign the coordinates (slice angle is in degrees). */
958  double angle = slice_angle ? slice_angle[islice] * CPL_MATH_RAD_DEG
959  : 0.;
960  cdata_xpos[irow] = aGeoTable
961  ? dx * cos(angle) + slice_x[islice]
962  : dx + islice * kMuseSliceHiLikelyWidth
963  + kMuseSliceHiLikelyWidth / 2.;
964  cdata_ypos[irow] = aGeoTable
965  ? dx * sin(angle) + slice_y[islice]
966  : 0.; /* no vertical position for simple case */
967 #if DEBUG_PIXTABLE_CREATION
968  if (!isfinite(cdata_xpos[irow]) ||
969  cdata_xpos[irow] < -200 || cdata_xpos[irow] > 4000) {
970  cpl_msg_debug(__func__, "weird data in x: %e %e",
971  cdata_xpos[irow], cdata_ypos[irow]);
972  }
973  if (!isfinite(cdata_ypos[irow]) ||
974  cdata_ypos[irow] < -200 || cdata_ypos[irow] > 200) {
975  cpl_msg_debug(__func__, "weird data in y: %e %e",
976  cdata_xpos[irow], cdata_ypos[irow]);
977  }
978 #endif
979  cdata_lambda[irow] = lambda;
980 
981  /* assign the data values */
982  cdata_data[irow] = pixdata[(i-1) + (j-1)*xsize];
983  cdata_dq[irow] = pixdq[(i-1) + (j-1)*xsize];
984  cdata_stat[irow] = pixstat[(i-1) + (j-1)*xsize];
985  /* assign origin and slice number */
986  cdata_origin[irow] = muse_pixtable_origin_encode_fast(i, j, ifu,
987  islice + 1,
988  offset);
989  } /* for i (horizontal pixels) */
990  } /* for j (vertical direction) */
991 
992  /* we are now done with this slice, clean up */
993  muse_trace_polys_delete(ptrace);
994  cpl_polynomial_delete(pwave);
995  cpl_vector_delete(pos);
996  } /* for islice */
997  cpl_table_delete(geopos);
998  cpl_msg_debug(__func__, "IFU %hhu took %gs (CPU time), %gs (wall-clock)",
999  ifu, cpl_test_get_cputime() - cputime,
1000  cpl_test_get_walltime() - walltime);
1001 
1002  /* itablerow is the last written to location (starting at zero), so add one */
1003  if (muse_pixtable_get_nrow(pt) > itablerow) {
1004  cpl_msg_debug(__func__, "Trimming pixel table of IFU %hhu to %"CPL_SIZE_FORMAT
1005  " of %"CPL_SIZE_FORMAT" rows", ifu, itablerow,
1007 #if DEBUG_PIXTABLE_CREATION /* make sure that we are trimming correctly */
1008  printf("end of used part of pixel table before trimming:\n");
1009  cpl_table_dump(pt->table, itablerow-5, 10, stdout);
1010  fflush(stdout);
1011 #endif
1012  cpl_table_set_size(pt->table, itablerow);
1013  }
1014  /* now that we are done creating it, we can also *
1015  * compute its extremes for the first time */
1017 #if DEBUG_PIXTABLE_CREATION
1018  printf("beginning of pixel table before returning:\n");
1019  cpl_table_dump(pt->table, 0, 5, stdout);
1020  fflush(stdout);
1021  printf("end of pixel table before returning:\n");
1022  cpl_table_dump(pt->table, muse_pixtable_get_nrow(pt)-5, 10, stdout);
1023  fflush(stdout);
1024 #endif
1025 
1026  return pt;
1027 } /* muse_pixtable_create() */
1028 
1029 /*---------------------------------------------------------------------------*/
1042 /*---------------------------------------------------------------------------*/
1043 muse_pixtable *
1045 {
1046  if (aPixtable == NULL) {
1047  return NULL;
1048  }
1049  muse_pixtable *pt = cpl_calloc(1, sizeof(muse_pixtable));
1050  pt->table = cpl_table_duplicate(aPixtable->table);
1051  pt->header = cpl_propertylist_duplicate(aPixtable->header);
1052  return pt;
1053 }
1054 
1055 /*---------------------------------------------------------------------------*/
1064 /*---------------------------------------------------------------------------*/
1065 void
1067 {
1068  /* if we already get NULL, we don't need to do anything */
1069  if (!aPixtable) {
1070  return;
1071  }
1072 
1073  /* delete the table portion */
1074  cpl_table_delete(aPixtable->table);
1075  aPixtable->table = NULL;
1076 
1077  /* delete the header portion */
1078  cpl_propertylist_delete(aPixtable->header);
1079  aPixtable->header = NULL;
1080 
1081  /* delete the flat-field spectrum */
1082  cpl_table_delete(aPixtable->ffspec);
1083  aPixtable->ffspec = NULL;
1084 
1085  cpl_free(aPixtable);
1086 } /* muse_pixtable_delete() */
1087 
1088 /*---------------------------------------------------------------------------*/
1113 /*---------------------------------------------------------------------------*/
1114 cpl_error_code
1116  cpl_table *aTrace, cpl_table *aWave, float aSampling)
1117 {
1118  cpl_ensure_code(aPixtable, CPL_ERROR_NULL_INPUT);
1119 
1120  /* discard a pre-existing flat-field spectrum */
1121  if (aPixtable->ffspec) {
1122  cpl_table_delete(aPixtable->ffspec);
1123  }
1124 
1125  /* create pixel table, without geometry table is fine */
1126  muse_pixtable *ptflat = muse_pixtable_create(aFF, aTrace, aWave, NULL);
1127  if (!ptflat) {
1128  return cpl_error_get_code();
1129  }
1130  aPixtable->ffspec = muse_resampling_spectrum(ptflat, aSampling);
1131  muse_pixtable_delete(ptflat);
1132  /* there does not seem to be a way to generate a muse_resampling_spectrum() *
1133  * failure other than with a NULL pixel table, so do not test for that */
1134 
1135  /* muse_resampling_spectrum() also creates variance and bad pixel *
1136  * spectra in extra columns which we do not need to carry around here */
1137  cpl_table_erase_column(aPixtable->ffspec, "stat");
1138  cpl_table_erase_column(aPixtable->ffspec, "dq");
1139 
1140  return CPL_ERROR_NONE;
1141 } /* muse_pixtable_append_ff() */
1142 
1143 /*---------------------------------------------------------------------------*/
1155 /*---------------------------------------------------------------------------*/
1156 static cpl_error_code
1157 muse_pixtable_save_ffspec(muse_pixtable *aPixtable, const char *aFilename)
1158 {
1159  cpl_ensure_code(aPixtable, CPL_ERROR_NULL_INPUT);
1160 
1161  /* if the flat-field spectrum does not exist, return early */
1162  if (!aPixtable->ffspec) {
1163  /* but warn, if the flag was set in the primary header *
1164  * (too late now to do anything about it) */
1165  return CPL_ERROR_NONE;
1166  }
1167 
1168  /* save the flat-field in a new file extension */
1169  cpl_propertylist *hext = cpl_propertylist_new();
1170  cpl_propertylist_append_string(hext, "EXTNAME", MUSE_PIXTABLE_FF_EXT);
1171  cpl_error_code rc = cpl_table_save(aPixtable->ffspec, NULL, hext, aFilename,
1172  CPL_IO_EXTEND);
1173  cpl_propertylist_delete(hext);
1174 
1175  return rc;
1176 } /* muse_pixtable_save_ffspec() */
1177 
1178 /*---------------------------------------------------------------------------*/
1199 /*---------------------------------------------------------------------------*/
1200 static cpl_error_code
1201 muse_pixtable_save_image(muse_pixtable *aPixtable, const char *aFilename)
1202 {
1203  const char *id = "muse_pixtable_save"; /* pretend to be in that function */
1204  cpl_ensure_code(aPixtable, CPL_ERROR_NULL_INPUT);
1205  cpl_size nrow = muse_pixtable_get_nrow(aPixtable);
1206  cpl_ensure_code(nrow > 0, CPL_ERROR_ILLEGAL_INPUT);
1207 
1208  cpl_errorstate state = cpl_errorstate_get();
1209  cpl_array *columns = cpl_table_get_column_names(aPixtable->table);
1210  int icol, ncol = cpl_array_get_size(columns);
1211  for (icol = 0; icol < ncol; icol++) {
1212  const char *colname = cpl_array_get_string(columns, icol);
1213  /* access data buffer and wrap as corresponding CPL image type */
1214  cpl_type type = cpl_table_get_column_type(aPixtable->table, colname);
1215  cpl_image *image = NULL;
1216  switch (type) {
1217  case CPL_TYPE_FLOAT: {
1218  float *data = cpl_table_get_data_float(aPixtable->table, colname);
1219  image = cpl_image_wrap_float(1, nrow, data);
1220  break;
1221  }
1222  case CPL_TYPE_INT: {
1223  int *data = cpl_table_get_data_int(aPixtable->table, colname);
1224  image = cpl_image_wrap_int(1, nrow, data);
1225  break;
1226  }
1227  default:
1228  cpl_error_set_message(id, CPL_ERROR_UNSUPPORTED_MODE, "type \"%s\" (of "
1229  "column %s) is not supported for MUSE pixel tables",
1230  cpl_type_get_name(type), colname);
1231  continue;
1232  } /* switch */
1233  /* now construct minimal extension header with EXTNAME and *
1234  * BUNIT and save the image with its internal data type */
1235  cpl_propertylist *hext = cpl_propertylist_new();
1236  cpl_propertylist_append_string(hext, "EXTNAME", colname);
1237  const char *unit = cpl_table_get_column_unit(aPixtable->table, colname);
1238  if (unit) {
1239  cpl_propertylist_append_string(hext, "BUNIT", unit);
1240  }
1241  cpl_image_save(image, aFilename, CPL_TYPE_UNSPECIFIED, hext, CPL_IO_EXTEND);
1242  cpl_image_unwrap(image);
1243  cpl_propertylist_delete(hext);
1244  } /* for icol (all table columns) */
1245  cpl_array_delete(columns);
1246 
1247  /* append the flat-field spectrum to the file (if it exists) */
1248  muse_pixtable_save_ffspec(aPixtable, aFilename);
1249 
1250  return cpl_errorstate_is_equal(state) ? CPL_ERROR_NONE : cpl_error_get_code();
1251 } /* muse_pixtable_save_image() */
1252 
1253 /*---------------------------------------------------------------------------*/
1274 /*---------------------------------------------------------------------------*/
1275 cpl_error_code
1276 muse_pixtable_save(muse_pixtable *aPixtable, const char *aFilename)
1277 {
1278  cpl_ensure_code(aPixtable, CPL_ERROR_NULL_INPUT);
1279 
1280  /* let CPL do the real work and propagate any errors and errorstates that *
1281  * it generates; the secondary header should be generated automatically *
1282  * from the table data we have set in muse_pixtable_create(). */
1283  /* save headers separately to keep WCS information */
1284  cpl_error_code rc = cpl_propertylist_save(aPixtable->header, aFilename,
1285  CPL_IO_CREATE);
1286  if (rc != CPL_ERROR_NONE) {
1287  cpl_error_set_message(__func__, rc, "could not save FITS header of pixel "
1288  "table \"%s\"", aFilename);
1289  return rc;
1290  }
1291  /* test if we need to save it as image */
1292  cpl_boolean astable = getenv("MUSE_PIXTABLE_SAVE_AS_TABLE")
1293  && atoi(getenv("MUSE_PIXTABLE_SAVE_AS_TABLE")) > 0;
1294  if (astable) {
1295  cpl_msg_debug(__func__, "Saving pixel table \"%s\" as binary table",
1296  aFilename);
1297  rc = cpl_table_save(aPixtable->table, NULL, NULL, aFilename, CPL_IO_EXTEND);
1298  /* append the flat-field spectrum to the file (if it exists) */
1299  muse_pixtable_save_ffspec(aPixtable, aFilename);
1300  } else {
1301  rc = muse_pixtable_save_image(aPixtable, aFilename);
1302  }
1303  return rc;
1304 } /* muse_pixtable_save() */
1305 
1306 /*---------------------------------------------------------------------------*/
1331 /*---------------------------------------------------------------------------*/
1332 static cpl_table *
1333 muse_pixtable_load_window_image(const char *aFilename,
1334  cpl_size aStart, cpl_size aNRows)
1335 {
1336  const char *id = "muse_pixtable_load"; /* pretend to be in that function */
1337  /* determine "image" window to read, the y-direction *
1338  * in the image is the dimension of the rows */
1339  cpl_size y1 = aStart + 1,
1340  y2 = aStart + aNRows;
1341  /* get header of "data" extension, and check/correct the size of the dataset */
1342  int ext = cpl_fits_find_extension(aFilename, MUSE_PIXTABLE_DATA);
1343  cpl_propertylist *hdata = cpl_propertylist_load(aFilename, ext);
1344  /* get NAXIS2 which contains contains the number of rows */
1345  cpl_size naxis2 = muse_pfits_get_naxis(hdata, 2);
1346  if (y2 > naxis2) {
1347  y2 = naxis2;
1348  }
1349  cpl_propertylist_delete(hdata);
1350 
1351  /* find and load all image extensions using their EXTNAMEs */
1352  cpl_size nrow = 0;
1353  cpl_table *table = cpl_table_new(nrow);
1354  int iext, next = cpl_fits_count_extensions(aFilename);
1355  for (iext = 1; iext <= next; iext++) {
1356  /* first check, that we are not loading the flat-field extension */
1357  cpl_propertylist *hext = cpl_propertylist_load(aFilename, iext);
1358  const char *colname = muse_pfits_get_extname(hext);
1359  if (!strncmp(colname, MUSE_PIXTABLE_FF_EXT, strlen(MUSE_PIXTABLE_FF_EXT) + 1)) {
1360  /* this will be loaded later */
1361  cpl_propertylist_delete(hext);
1362  continue;
1363  }
1364 
1365  /* now load the column from the image extension */
1366  cpl_errorstate ps = cpl_errorstate_get();
1367  cpl_image *column = cpl_image_load_window(aFilename, CPL_TYPE_UNSPECIFIED,
1368  0, iext, 1, y1, 1, y2);
1369  if (!column || !cpl_errorstate_is_equal(ps)) {
1370  cpl_image_delete(column);
1371  cpl_error_set_message(id, cpl_error_get_code(), "could not load extension"
1372  " %d of pixel table \"%s\"", iext, aFilename);
1373  cpl_propertylist_delete(hext);
1374  continue;
1375  }
1376  cpl_size nrows = cpl_image_get_size_x(column)
1377  * cpl_image_get_size_y(column);
1378  if (nrow < 1) {
1379  cpl_table_set_size(table, nrows);
1380  nrow = nrows;
1381  } else if (nrows != nrow) {
1382  cpl_error_set_message(id, CPL_ERROR_INCOMPATIBLE_INPUT, "size of column "
1383  "%s does not match", colname);
1384  cpl_propertylist_delete(hext);
1385  cpl_image_delete(column);
1386  continue;
1387  }
1388  cpl_type type = cpl_image_get_type(column);
1389  switch (type) {
1390  case CPL_TYPE_FLOAT:
1391  cpl_table_wrap_float(table, cpl_image_unwrap(column), colname);
1392  break;
1393  case CPL_TYPE_INT:
1394  cpl_table_wrap_int(table, cpl_image_unwrap(column), colname);
1395  break;
1396  default:
1397  cpl_error_set_message(id, CPL_ERROR_UNSUPPORTED_MODE, "type \"%s\" (of "
1398  "column %s) is not supported for MUSE pixel tables",
1399  cpl_type_get_name(type), colname);
1400  } /* switch */
1401  cpl_errorstate state = cpl_errorstate_get();
1402  const char *unit = muse_pfits_get_bunit(hext);
1403  if (!cpl_errorstate_is_equal(state)) {
1404  cpl_errorstate_set(state);
1405  }
1406  if (unit) {
1407  cpl_table_set_column_unit(table, colname, unit);
1408  }
1409  cpl_propertylist_delete(hext);
1410  } /* for iext (all FITS extensions) */
1411  return table;
1412 } /* muse_pixtable_load_window_image() */
1413 
1414 /*---------------------------------------------------------------------------*/
1429 /*---------------------------------------------------------------------------*/
1430 static cpl_error_code
1431 muse_pixtable_load_ffspec(const char *aFilename, muse_pixtable *aPixtable)
1432 {
1433  const char *id = "muse_pixtable_load"; /* pretend to be in that function */
1434  cpl_ensure_code(aFilename && aPixtable, CPL_ERROR_NULL_INPUT);
1435 
1436  int iext = cpl_fits_find_extension(aFilename, MUSE_PIXTABLE_FF_EXT);
1437  /* if the flat-field extension was not found, just quietly *
1438  * return -- or make some noise if the flag was set */
1439  if (iext <= 0) {
1440  return CPL_ERROR_NONE; /* quietly return */
1441  }
1442 
1443  cpl_errorstate es = cpl_errorstate_get();
1444  aPixtable->ffspec = cpl_table_load(aFilename, iext, 1);
1445  if (!cpl_errorstate_is_equal(es)) {
1446  cpl_msg_warning(id, "Pixel table flat-field spectrum extension %s "
1447  "exists in \"%s\", but cannot be loaded!",
1448  MUSE_PIXTABLE_FF_EXT, aFilename);
1449 
1450  /* clean up again, in case something (broken?) was loaded */
1451  cpl_table_delete(aPixtable->ffspec);
1452  aPixtable->ffspec = NULL;
1453  /* swallow the error code, since the missing flat-field only becomes *
1454  * critical, if this pixel table is later combined with others */
1455  cpl_errorstate_set(es);
1456  }
1457 
1458  return CPL_ERROR_NONE;
1459 } /* muse_pixtable_load_ffspec() */
1460 
1461 /*---------------------------------------------------------------------------*/
1486 /*---------------------------------------------------------------------------*/
1487 muse_pixtable *
1488 muse_pixtable_load_window(const char *aFilename,
1489  cpl_size aStart, cpl_size aNRows)
1490 {
1491  /* create the output pixel table structure, and NULL out the components */
1492  muse_pixtable *pt = cpl_calloc(1, sizeof(muse_pixtable));
1493 
1494  /* load the header and return with an error if something went wrong */
1495  cpl_errorstate prestate = cpl_errorstate_get();
1496  pt->header = cpl_propertylist_load(aFilename, 0);
1497  cpl_ensure(cpl_errorstate_is_equal(prestate) && pt->header,
1498  cpl_error_get_code(), NULL);
1500  cpl_msg_error(__func__, "unknown pixel table type found in \"%s\"", aFilename);
1502  return NULL;
1503  }
1504 
1505  /* determine the type of data (FITS binary table extension or *
1506  * FITS multi-extension images) by looking at the first extension */
1507  cpl_propertylist *hext = cpl_propertylist_load(aFilename, 1);
1508  cpl_boolean asimage = !strcmp(cpl_propertylist_get_string(hext, "XTENSION"),
1509  "IMAGE");
1510  cpl_propertylist_delete(hext);
1511 
1512  /* load the table itself and return an error if something went wrong */
1513  if (asimage) {
1514  cpl_msg_info(__func__, "Loading pixel table \"%s\" (image format)",
1515  aFilename);
1516  pt->table = muse_pixtable_load_window_image(aFilename, aStart, aNRows);
1517  } else {
1518  cpl_msg_info(__func__, "Loading pixel table \"%s\" (bintable format)",
1519  aFilename);
1520  pt->table = cpl_table_load_window(aFilename, 1, 0, NULL, aStart, aNRows);
1521  }
1522  if (!cpl_errorstate_is_equal(prestate) || !pt->table) {
1523  cpl_msg_error(__func__, "Failed to load table part of pixel table \"%s\"",
1524  aFilename);
1526  return NULL;
1527  }
1528  cpl_error_code rc = muse_cpltable_check(pt->table, muse_pixtable_def);
1529  if (rc != CPL_ERROR_NONE) {
1530  cpl_error_set_message(__func__, rc, "pixel table \"%s\" does not contain "
1531  "all expected columns", aFilename);
1532  }
1533 
1534  /* load the flat-field spectrum, if it exists; same for both cases */
1535  muse_pixtable_load_ffspec(aFilename, pt);
1536  return pt;
1537 } /* muse_pixtable_load_window() */
1538 
1539 /*---------------------------------------------------------------------------*/
1559 /*---------------------------------------------------------------------------*/
1560 muse_pixtable *
1561 muse_pixtable_load(const char *aFilename)
1562 {
1563  /* find out original table length from the header of the FITS binary table */
1564  cpl_errorstate prestate = cpl_errorstate_get();
1565  cpl_propertylist *theader = cpl_propertylist_load(aFilename, 1);
1566  cpl_ensure(cpl_errorstate_is_equal(prestate) && theader,
1567  cpl_error_get_code(), NULL);
1568  cpl_size nrow = cpl_propertylist_get_long_long(theader, "NAXIS2");
1569  cpl_propertylist_delete(theader);
1570 
1571  /* now that we know the full size, load all rows */
1572  muse_pixtable *pt = muse_pixtable_load_window(aFilename, 0, nrow);
1573  return pt;
1574 } /* muse_pixtable_load() */
1575 
1576 /*---------------------------------------------------------------------------*/
1593 /*---------------------------------------------------------------------------*/
1594 muse_pixtable *
1596  double aLambdaMin, double aLambdaMax)
1597 {
1598  muse_pixtable *pt = muse_pixtable_load(aFilename);
1599  if (!pt) {
1600  return NULL;
1601  }
1602  cpl_error_code rc = muse_pixtable_restrict_wavelength(pt, aLambdaMin,
1603  aLambdaMax);
1604  if (rc != CPL_ERROR_NONE) {
1606  return NULL;
1607  }
1608  if (muse_pixtable_get_nrow(pt) < 1) {
1609  cpl_msg_error(__func__, "Pixel table contains no entries after cutting to "
1610  "%.3f..%.3f Angstrom", aLambdaMin, aLambdaMax);
1611  cpl_error_set(__func__, CPL_ERROR_DATA_NOT_FOUND);
1613  return NULL;
1614  }
1615  return pt;
1616 } /* muse_pixtable_load_restricted_wavelength() */
1617 
1618 /*---------------------------------------------------------------------------*/
1665 /*---------------------------------------------------------------------------*/
1666 muse_pixtable *
1667 muse_pixtable_load_merge_channels(cpl_table *aExposureList,
1668  double aLambdaMin, double aLambdaMax)
1669 {
1670  cpl_ensure(aExposureList, CPL_ERROR_NULL_INPUT, NULL);
1671 
1672  muse_pixtable *pt = NULL; /* the big output pixel table */
1673  if (cpl_table_has_column(aExposureList, "00")) {
1674  const char *filename = cpl_table_get_string(aExposureList, "00", 0);
1675  if (filename) {
1676  pt = muse_pixtable_load_restricted_wavelength(filename, aLambdaMin,
1677  aLambdaMax);
1678  }
1679  if (pt) {
1680  return pt;
1681  }
1682  } /* if table with "00" column */
1683 
1684  /* create array to hold interpolation points for flat-field spectrum */
1685  cpl_array *lambdas = cpl_array_new((kMuseLambdaMaxX - kMuseLambdaMinX)
1686  / kMuseSpectralSamplingA + 1,
1687  CPL_TYPE_DOUBLE),
1688  *ffspec = NULL; /* for output average flat-field spectrum data */
1689  int j, nwl = cpl_array_get_size(lambdas);
1690  for (j = 0; j < nwl; j++) {
1691  cpl_array_set_double(lambdas, j, kMuseLambdaMinX
1692  + j * kMuseSpectralSamplingA);
1693  }
1694 
1695  cpl_boolean isfirst = CPL_TRUE;
1696  double fluxlref = 0, /* propagated from lamp flat */
1697  fluxsref = 0; /* propagated from sky flat */
1698  int i, nifu = 0, nflats = 0;
1699  for (i = 1; i <= kMuseNumIFUs; i++) {
1700  char *colname = cpl_sprintf("%02d", i);
1701  const char *filename = cpl_table_get_string(aExposureList, colname, 0);
1702  cpl_free(colname);
1703  if (!filename) {
1704  cpl_msg_warning(__func__, "Channel for IFU %02d is missing", i);
1705  continue;
1706  }
1708  aLambdaMin,
1709  aLambdaMax);
1710  if (!onept) {
1711  cpl_msg_error(__func__, "failed to load pixel table from \"%s\"",
1712  filename);
1713  cpl_array_delete(lambdas);
1714  return pt;
1715  }
1716  nifu++;
1717 
1718  /* if this is the first pixel table, use its data to create the big one */
1719  if (isfirst) {
1720  pt = onept;
1721  cpl_msg_debug(__func__, "loaded pixel table with %"CPL_SIZE_FORMAT" rows",
1723  isfirst = CPL_FALSE;
1724  cpl_errorstate prestate = cpl_errorstate_get();
1725  fluxsref = cpl_propertylist_get_double(pt->header, MUSE_HDR_FLAT_FLUX_SKY);
1726  fluxlref = cpl_propertylist_get_double(pt->header, MUSE_HDR_FLAT_FLUX_LAMP);
1727  if (fluxsref == 0. && fluxlref == 0. && !cpl_errorstate_is_equal(prestate)) {
1728  /* If the flat headers are both missing, this can only mean that *
1729  * the exposure was previously merged into the pixel table we just *
1730  * loaded. Then we can recover from the error and stop right here. */
1731  cpl_msg_debug(__func__, "\"%s\" was previously merged (got \"%s\" when"
1732  " asking for flat-field fluxes)", filename,
1733  cpl_error_get_message());
1734  cpl_errorstate_set(prestate);
1735  break;
1736  }
1737  if (fluxsref == 0. && fluxlref > 0. && !cpl_errorstate_is_equal(prestate)) {
1738  /* only the sky-flat level was missing, output a warning */
1739  cpl_msg_warning(__func__, "only found reference lamp-flat flux (%e) in "
1740  "\"%s\", flux levels may vary between IFUs!", fluxlref,
1741  filename);
1742  cpl_errorstate_set(prestate);
1743  } else {
1744  cpl_msg_debug(__func__, "reference flat fluxes sky: %e lamp: %e",
1745  fluxsref, fluxlref);
1746  }
1747  cpl_propertylist_erase(pt->header, MUSE_HDR_FLAT_FLUX_SKY);
1748  cpl_propertylist_erase(pt->header, MUSE_HDR_FLAT_FLUX_LAMP);
1749 
1750  /* for the first table, directly resample the flat-field spectrum */
1751  if (pt->ffspec) { /* check, to keep backward compatibility */
1752  ffspec = muse_cplarray_interpolate_table_linear(lambdas, pt->ffspec,
1753  "lambda", "data");
1754  /* delete the flat-field spectrum component, since *
1755  * this will be the flat-field corrected output table */
1756  cpl_table_delete(pt->ffspec);
1757  pt->ffspec = NULL;
1758  nflats++;
1759  }
1760  continue;
1761  } /* if isfirst */
1762 
1763  /* copy the offset headers to the output pixel table */
1764  muse_pixtable_origin_copy_offsets(pt, onept, 0);
1765 
1766  /* to fix the flux offset (using propagated flat-field fluxes) */
1767  cpl_errorstate state = cpl_errorstate_get();
1768  double fluxs = cpl_propertylist_get_double(onept->header,
1769  MUSE_HDR_FLAT_FLUX_SKY),
1770  fluxl = cpl_propertylist_get_double(onept->header,
1771  MUSE_HDR_FLAT_FLUX_LAMP),
1772  scale = 1.;
1773  if (fluxsref > 0. && fluxs > 0.) { /* prefer sky flat flux scaling */
1774  scale = fluxs / fluxsref;
1775  } else if (fluxlref > 0. && fluxl > 0.) {
1776  scale = fluxl / fluxlref;
1777  if (!cpl_errorstate_is_equal(state)) {
1778  cpl_msg_warning(__func__, "only found relative lamp-flat flux (%e) in "
1779  "\"%s\", flux levels may vary between IFUs!", fluxl,
1780  filename);
1781  cpl_errorstate_set(state);
1782  } /* if bad error state */
1783  } /* else: use lamp-flat values */
1784  muse_pixtable_flux_multiply(onept, 1. / scale); /* inverse of scale here */
1785 
1786  /* resample ff-spectrum onto the regular sampling, given *
1787  * by the lambda vector created at the beginning */
1788  if (onept->ffspec) { /* check, to keep backward compatibility */
1789  cpl_array *ffout = muse_cplarray_interpolate_table_linear(lambdas,
1790  onept->ffspec,
1791  "lambda", "data");
1792  if (ffspec) { /* if the first one had a flat-field spectrum */
1793  cpl_array_add(ffspec, ffout); /* add up to average the resulting spectrum */
1794  }
1795  cpl_array_delete(ffout);
1796  nflats++;
1797  } /* if ff-spectrum */
1798 
1799  /* append this pixel table to the big one */
1800  cpl_table_insert(pt->table, onept->table, muse_pixtable_get_nrow(pt));
1801  cpl_msg_debug(__func__, "big pixel table now has %"CPL_SIZE_FORMAT" entries,"
1802  " scale was %e (flat fluxes sky: %e lamp: %e)",
1803  muse_pixtable_get_nrow(pt), scale, fluxs, fluxl);
1804 
1805  /* the insertion duplicates the data, so we can delete it now */
1806  muse_pixtable_delete(onept);
1807  } /* for i (all IFUs) */
1808 
1809  /* If some but not all pixel tables came with the flat-field spectrum, *
1810  * we may get unforeseen results when doing flux calibration etc., so *
1811  * better fail completely! */
1812  if (nflats > 0 && nifu != nflats) {
1813  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_INPUT, "Only %d of %d "
1814  "pixel tables of this exposure came with a flat-field"
1815  " spectrum, cannot continue!", nflats, nifu);
1816  cpl_array_delete(lambdas);
1817  cpl_array_delete(ffspec);
1819  return NULL;
1820  } /* if nflats */
1821 
1822  if (ffspec) {
1823  /* we need the average flat-field spectrum, so *
1824  * divide by the number of IFUs that were combined */
1825  cpl_array_divide_scalar(ffspec, nflats);
1826  cpl_msg_debug(__func__, "Average of flat-field spectrum: %.4f",
1827  cpl_array_get_mean(ffspec));
1828 
1829  /* now correct the output pixel table by the averaged flat-field spectrum */
1830  muse_pixtable_spectrum_apply(pt, lambdas, ffspec,
1831  MUSE_PIXTABLE_OPERATION_MULTIPLY);
1832 
1833  /* mark the header as having gotten the correction */
1834  cpl_propertylist_update_int(pt->header, MUSE_HDR_PT_FFCORR, nflats);
1835  cpl_propertylist_set_comment(pt->header, MUSE_HDR_PT_FFCORR,
1836  MUSE_HDR_PT_FFCORR_COMMENT);
1837 
1838  /* still keep the (rather small) flat-field spectrum around, *
1839  * at least for debugging */
1840  pt->ffspec = cpl_table_new(cpl_array_get_size(lambdas));
1841  cpl_table_new_column(pt->ffspec, MUSE_PIXTABLE_FFLAMBDA, CPL_TYPE_DOUBLE);
1842  cpl_table_new_column(pt->ffspec, MUSE_PIXTABLE_FFDATA, CPL_TYPE_DOUBLE);
1845  cpl_array_delete(ffspec);
1846  /* everything before was done on a fixed grid to encompass *
1847  * all possible MUSE data, now we have to get rid of the invalid *
1848  * entries at the extreme ends of the flat-field spectrum */
1849  cpl_table_erase_invalid(pt->ffspec);
1850  } /* if ffspec */
1851  cpl_array_delete(lambdas);
1852 
1853  /* now that we merged all pixel tables, compute the full extent */
1855  if (!pt) {
1856  cpl_error_set_message(__func__, CPL_ERROR_FILE_NOT_FOUND,
1857  "None of the pixel tables could be loaded");
1858  return NULL; /* exit here to not crash below! */
1859  }
1860  /* data does not belong to any one IFU any more, so *
1861  * remove the EXTNAME header that contains CHAN%02d */
1862  cpl_propertylist_erase_regexp(pt->header, "^EXTNAME|"MUSE_HDR_PT_ILLUM_REGEXP,
1863  0);
1864  /* also remove chip-specific info that doesn't belong to the merged data */
1865  cpl_propertylist_erase_regexp(pt->header, "ESO DET (CHIP|OUT) ", 0);
1866  cpl_propertylist_erase_regexp(pt->header, "ESO DET2 ", 0);
1867  /* add the status header */
1868  cpl_propertylist_update_int(pt->header, MUSE_HDR_PT_MERGED, nifu);
1869  cpl_propertylist_set_comment(pt->header, MUSE_HDR_PT_MERGED,
1870  MUSE_HDR_PT_MERGED_COMMENT);
1871  return pt;
1872 } /* muse_pixtable_load_merge_channels() */
1873 
1874 /*---------------------------------------------------------------------------*/
1886 /*---------------------------------------------------------------------------*/
1887 int
1889 {
1890  cpl_ensure(aPixtable, CPL_ERROR_NULL_INPUT, MUSE_PIXTABLE_TYPE_UNKNOWN);
1891  const char *type = cpl_propertylist_get_string(aPixtable->header,
1893 #if 0
1894  cpl_msg_debug(__func__, "pixel table type \"%s\"", type);
1895 #endif
1896  if (!type) {
1898  }
1899  if (!strncmp(type, MUSE_PIXTABLE_STRING_FULL,
1900  strlen(MUSE_PIXTABLE_STRING_FULL) + 1)) {
1901  return MUSE_PIXTABLE_TYPE_FULL;
1902  } else if (!strncmp(type, MUSE_PIXTABLE_STRING_SIMPLE,
1903  strlen(MUSE_PIXTABLE_STRING_SIMPLE) + 1)) {
1905  }
1906 
1908 } /* muse_pixtable_get_type() */
1909 
1910 /*---------------------------------------------------------------------------*/
1919 /*---------------------------------------------------------------------------*/
1920 cpl_size
1922 {
1923  /* make sure that we are getting valid input */
1924  cpl_ensure(aPixtable, CPL_ERROR_NULL_INPUT, 0);
1925  cpl_ensure(aPixtable->table, CPL_ERROR_NULL_INPUT, 0);
1926 
1927  /* let CPL do the work */
1928  return cpl_table_get_nrow(aPixtable->table);
1929 } /* muse_pixtable_get_nrow() */
1930 
1931 /*---------------------------------------------------------------------------*/
1947 /*---------------------------------------------------------------------------*/
1948 cpl_error_code
1950 {
1951  /* make sure that we are getting valid input */
1952  cpl_ensure_code(aPixtable && aPixtable->table && aPixtable->header,
1953  CPL_ERROR_NULL_INPUT);
1954  cpl_ensure_code(muse_cpltable_check(aPixtable->table, muse_pixtable_def)
1955  == CPL_ERROR_NONE, CPL_ERROR_DATA_NOT_FOUND);
1956 
1957  if (muse_pixtable_get_nrow(aPixtable) == 0) {
1958  return CPL_ERROR_NONE;
1959  }
1960 
1961  float *cdata_xpos = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_XPOS),
1962  *cdata_ypos = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_YPOS),
1963  *cdata_lambda = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_LAMBDA);
1964  uint32_t *origin = (uint32_t *)cpl_table_get_data_int(aPixtable->table,
1966  /* set to extreme values for a start */
1967  float xlo = FLT_MAX, xhi = -FLT_MAX,
1968  ylo = FLT_MAX, yhi = -FLT_MAX,
1969  llo = FLT_MAX, lhi = -FLT_MAX;
1970  int ifulo = INT_MAX, ifuhi = 0,
1971  slicelo = INT_MAX, slicehi = 0;
1972  cpl_size i, nrow = muse_pixtable_get_nrow(aPixtable);
1973  for (i = 0; i < nrow; i++) {
1974  if (cdata_xpos[i] > xhi) xhi = cdata_xpos[i];
1975  if (cdata_xpos[i] < xlo) xlo = cdata_xpos[i];
1976  if (cdata_ypos[i] > yhi) yhi = cdata_ypos[i];
1977  if (cdata_ypos[i] < ylo) ylo = cdata_ypos[i];
1978  if (cdata_lambda[i] > lhi) lhi = cdata_lambda[i];
1979  if (cdata_lambda[i] < llo) llo = cdata_lambda[i];
1980  int ifu = muse_pixtable_origin_get_ifu_fast(origin[i]),
1981  slice = muse_pixtable_origin_get_slice_fast(origin[i]);
1982  if (ifu > ifuhi) ifuhi = ifu;
1983  if (ifu < ifulo) ifulo = ifu;
1984  if (slice > slicehi) slicehi = slice;
1985  if (slice < slicelo) slicelo = slice;
1986  } /* for i */
1987  char *dodebug = getenv("MUSE_DEBUG_PIXTABLE_LIMITS");
1988  if (dodebug && atoi(dodebug)) {
1989  cpl_msg_debug(__func__, "x: %f...%f, y: %f...%f, lambda: %f...%f, "
1990  "ifu: %d...%d, slice: %d...%d",
1991  xlo, xhi, ylo, yhi, llo, lhi, ifulo, ifuhi, slicelo, slicehi);
1992  }
1993  cpl_propertylist_erase_regexp(aPixtable->header, MUSE_HDR_PT_LIMITS_REGEXP, 0);
1994  double ptxoff = 0., /* zero by default ... */
1995  ptyoff = 0.; /* for pixel coordinates */
1997  ptxoff = muse_pfits_get_crval(aPixtable->header, 1);
1998  ptyoff = muse_pfits_get_crval(aPixtable->header, 2);
1999  }
2000  cpl_propertylist_append_float(aPixtable->header, MUSE_HDR_PT_XLO, xlo + ptxoff);
2001  cpl_propertylist_append_float(aPixtable->header, MUSE_HDR_PT_XHI, xhi + ptxoff);
2002  cpl_propertylist_append_float(aPixtable->header, MUSE_HDR_PT_YLO, ylo + ptyoff);
2003  cpl_propertylist_append_float(aPixtable->header, MUSE_HDR_PT_YHI, yhi + ptyoff);
2004  cpl_propertylist_append_float(aPixtable->header, MUSE_HDR_PT_LLO, llo);
2005  cpl_propertylist_append_float(aPixtable->header, MUSE_HDR_PT_LHI, lhi);
2006  cpl_propertylist_append_int(aPixtable->header, MUSE_HDR_PT_ILO, ifulo);
2007  cpl_propertylist_append_int(aPixtable->header, MUSE_HDR_PT_IHI, ifuhi);
2008  cpl_propertylist_append_int(aPixtable->header, MUSE_HDR_PT_SLO, slicelo);
2009  cpl_propertylist_append_int(aPixtable->header, MUSE_HDR_PT_SHI, slicehi);
2010 
2011  return CPL_ERROR_NONE;
2012 } /* muse_pixtable_compute_limits() */
2013 
2014 /*---------------------------------------------------------------------------*/
2029 /*---------------------------------------------------------------------------*/
2030 cpl_error_code
2031 muse_pixtable_flux_multiply(muse_pixtable *aPixtable, double aScale)
2032 {
2033  cpl_ensure_code(aPixtable && aPixtable->table, CPL_ERROR_NULL_INPUT);
2034  cpl_errorstate prestate = cpl_errorstate_get();
2035  cpl_table_multiply_scalar(aPixtable->table, MUSE_PIXTABLE_DATA, aScale);
2036  cpl_table_multiply_scalar(aPixtable->table, MUSE_PIXTABLE_STAT, aScale*aScale);
2037  cpl_error_code rc = CPL_ERROR_NONE;
2038  if (!cpl_errorstate_is_equal(prestate)) {
2039  rc = cpl_error_get_code();
2040  }
2041  return rc;
2042 } /* muse_pixtable_flux_multiply() */
2043 
2044 /*---------------------------------------------------------------------------*/
2077 /*---------------------------------------------------------------------------*/
2078 cpl_error_code
2080  const cpl_array *aLambdas, const cpl_array *aFlux,
2081  muse_pixtable_operation aOperation)
2082 {
2083  cpl_ensure_code(aPixtable && aPixtable->table, CPL_ERROR_NULL_INPUT);
2084  cpl_ensure_code(aLambdas && aFlux, CPL_ERROR_NULL_INPUT);
2085  cpl_ensure_code(cpl_array_get_size(aLambdas) > 0 &&
2086  cpl_array_get_size(aLambdas) == cpl_array_get_size(aFlux),
2087  CPL_ERROR_ILLEGAL_INPUT);
2088  cpl_ensure_code(cpl_array_get_type(aLambdas) == CPL_TYPE_DOUBLE &&
2089  cpl_array_get_type(aFlux) == CPL_TYPE_DOUBLE,
2090  CPL_ERROR_INCOMPATIBLE_INPUT);
2091 
2092  /* To apply a given spectrum, decompose the full pixel table into per-slice *
2093  * pixel tables, which can be sorted by wavelength. For these, we can then *
2094  * linearly interpolate the input spectrum onto the same wavelengths as in *
2095  * the sub-pixel table and then subtract that in the form on an array. *
2096  * This also has the advantage of being parallelizable. */
2097  muse_pixtable **slicepts = muse_pixtable_extracted_get_slices(aPixtable);
2098  cpl_size islice, nslices = muse_pixtable_extracted_get_size(slicepts);
2099 
2100  switch (aOperation) {
2101  case MUSE_PIXTABLE_OPERATION_SUBTRACT:
2102  cpl_msg_debug(__func__, "Subtracting spectrum from pixel table with %"
2103  CPL_SIZE_FORMAT" slices...", nslices);
2104  break;
2105  case MUSE_PIXTABLE_OPERATION_MULTIPLY:
2106  cpl_msg_debug(__func__, "Multiplying pixel table of %"CPL_SIZE_FORMAT
2107  " slices with spectrum...", nslices);
2108  break;
2109  case MUSE_PIXTABLE_OPERATION_DIVIDE:
2110  cpl_msg_debug(__func__, "Dividing pixel table of %"CPL_SIZE_FORMAT
2111  " slices with spectrum...", nslices);
2112  break;
2113  default:
2115  return cpl_error_set(__func__, CPL_ERROR_UNSUPPORTED_MODE);
2116  } /* switch */
2117 
2118  /* now loop through all extracted slices in parallel */
2119  #pragma omp parallel for default(none) \
2120  shared(aFlux, aLambdas, aOperation, nslices, slicepts)
2121  for (islice = 0; islice < nslices; islice++) {
2122  muse_pixtable *thispt = slicepts[islice]; /* one slice pixel table */
2123  cpl_propertylist *order = cpl_propertylist_new();
2124  cpl_propertylist_append_bool(order, MUSE_PIXTABLE_LAMBDA, CPL_FALSE);
2125  cpl_table_sort(thispt->table, order);
2126  cpl_propertylist_delete(order);
2127 
2128  /* get sorted wavelengths as double array (so *
2129  * that the interpolation function can be used!) */
2130  cpl_table_cast_column(thispt->table, MUSE_PIXTABLE_LAMBDA, "lbda_d",
2131  CPL_TYPE_DOUBLE);
2132  cpl_array *lambdapt = muse_cpltable_extract_column(thispt->table, "lbda_d");
2133  cpl_array *fint = muse_cplarray_interpolate_linear(lambdapt, aLambdas,
2134  aFlux);
2135 
2136  /* get relevant pixel table columns to apply the flat-field spectrum to */
2137  cpl_array *datapt = muse_cpltable_extract_column(thispt->table,
2139  *statpt = muse_cpltable_extract_column(thispt->table,
2141  /* apply the flat-field spectrum */
2142  if (aOperation == MUSE_PIXTABLE_OPERATION_SUBTRACT) {
2143  cpl_array_subtract(datapt, fint);
2144  } else if (aOperation == MUSE_PIXTABLE_OPERATION_DIVIDE) {
2145  cpl_array_divide(datapt, fint);
2146  /* divide the variance squared (i.e. twice) */
2147  cpl_array_divide(statpt, fint);
2148  cpl_array_divide(statpt, fint);
2149  } else { /* MUSE_PIXTABLE_OPERATION_MULTIPLY */
2150  cpl_array_multiply(datapt, fint);
2151  /* multiply to the variance squared (i.e. twice) */
2152  cpl_array_multiply(statpt, fint);
2153  cpl_array_multiply(statpt, fint);
2154  } /* if aOperation */
2155  cpl_array_delete(fint);
2156 
2157  cpl_array_unwrap(datapt);
2158  cpl_array_unwrap(statpt);
2159  cpl_array_unwrap(lambdapt);
2160  cpl_table_erase_column(thispt->table, "lbda_d");
2161  } /* for islice (all slice pixel tables) */
2163 
2164  return CPL_ERROR_NONE;
2165 } /* muse_pixtable_spectrum_apply() */
2166 
2167 /*---------------------------------------------------------------------------*/
2177 /*---------------------------------------------------------------------------*/
2178 static cpl_error_code
2180 {
2181  cpl_ensure_code(aPixtable && aPixtable->header && aPixtable->table,
2182  CPL_ERROR_NULL_INPUT);
2183  if (cpl_table_count_selected(aPixtable->table) < 1) {
2184  return CPL_ERROR_NONE; /* nothing to do */
2185  }
2186  cpl_array *sel = cpl_table_where_selected(aPixtable->table);
2187  cpl_size narray = cpl_array_get_size(sel),
2188  nselprev = 0, /* selected ones in previous exposures */
2189  ifst = 0, ilst = 0;
2190  const cpl_size *asel = cpl_array_get_data_cplsize_const(sel);
2191  unsigned int nexp = 0;
2192  do {
2193  /* get exposure range for (next) exposure */
2194  char *kwfst = cpl_sprintf(MUSE_HDR_PT_EXP_FST, ++nexp),
2195  *kwlst = cpl_sprintf(MUSE_HDR_PT_EXP_LST, nexp);
2196  if (!cpl_propertylist_has(aPixtable->header, kwfst) ||
2197  !cpl_propertylist_has(aPixtable->header, kwlst)) {
2198  cpl_free(kwfst);
2199  cpl_free(kwlst);
2200  break; /* nothing (more) to do */
2201  }
2202  ifst = cpl_propertylist_get_long_long(aPixtable->header, kwfst);
2203  ilst = cpl_propertylist_get_long_long(aPixtable->header, kwlst);
2204  /* count selected */
2205  cpl_size i, nsel = 0;
2206  for (i = 0; i < narray; i++) {
2207  if (asel[i] >= ifst && asel[i] <= ilst) {
2208  nsel++;
2209  } /* if in range of this exposure */
2210  } /* for i (all array entries) */
2211  cpl_size ifst2 = ifst - nselprev,
2212  ilst2 = ilst - nsel - nselprev;
2213  cpl_msg_debug(__func__, "exp %d old %"CPL_SIZE_FORMAT"..%"CPL_SIZE_FORMAT
2214  ", %"CPL_SIZE_FORMAT" selected (previous: %"CPL_SIZE_FORMAT
2215  "), new %"CPL_SIZE_FORMAT"..%"CPL_SIZE_FORMAT, nexp,
2216  ifst, ilst, nsel, nselprev, ifst2, ilst2);
2217  /* finally update the header entries */
2218  muse_cplpropertylist_update_long_long(aPixtable->header, kwfst, ifst2);
2219  muse_cplpropertylist_update_long_long(aPixtable->header, kwlst, ilst2);
2220  cpl_free(kwfst);
2221  cpl_free(kwlst);
2222  nselprev += nsel; /* add selected ones for previous exposures */
2223  } while (ilst >= ifst);
2224  cpl_array_delete(sel);
2225  return CPL_ERROR_NONE;
2226 } /* muse_pixtable_fix_exp_headers() */
2227 
2228 /*---------------------------------------------------------------------------*/
2246 /*---------------------------------------------------------------------------*/
2247 cpl_error_code
2249  double aHigh)
2250 {
2251  cpl_ensure_code(aPixtable && aPixtable->table && aPixtable->header,
2252  CPL_ERROR_NULL_INPUT);
2253  if (cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_LLO) > aLow &&
2254  cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_LHI) < aHigh) {
2255  /* no need to do anything */
2256  return CPL_ERROR_NONE;
2257  }
2258 #pragma omp critical(cpl_table_select)
2259  {
2260  cpl_table_unselect_all(aPixtable->table);
2261  cpl_table_or_selected_float(aPixtable->table, MUSE_PIXTABLE_LAMBDA,
2262  CPL_LESS_THAN, aLow);
2263  cpl_table_or_selected_float(aPixtable->table, MUSE_PIXTABLE_LAMBDA,
2264  CPL_GREATER_THAN, aHigh);
2265  muse_pixtable_fix_exp_headers(aPixtable);
2266  cpl_table_erase_selected(aPixtable->table);
2267  }
2268 
2269  /* do the same for the flat-field spectrum, if it exists, but leave a *
2270  * spectral resolution element more on each side, for interpolation */
2271 #pragma omp critical(cpl_table_select)
2272  if (aPixtable->ffspec) {
2273  cpl_table_unselect_all(aPixtable->ffspec);
2274  cpl_table_or_selected_double(aPixtable->ffspec, MUSE_PIXTABLE_FFLAMBDA,
2275  CPL_LESS_THAN,
2276  aLow - 2. * kMuseSpectralSamplingA);
2277  cpl_table_or_selected_double(aPixtable->ffspec, MUSE_PIXTABLE_FFLAMBDA,
2278  CPL_GREATER_THAN,
2279  aHigh + 2. * kMuseSpectralSamplingA);
2280  cpl_table_erase_selected(aPixtable->ffspec);
2281  }
2282 
2283  return muse_pixtable_compute_limits(aPixtable);
2284 } /* muse_pixtable_restrict_wavelength() */
2285 
2286 /*---------------------------------------------------------------------------*/
2297 /*---------------------------------------------------------------------------*/
2298 cpl_error_code
2299 muse_pixtable_restrict_xpos(muse_pixtable *aPixtable, double aLo, double aHi)
2300 {
2301  cpl_ensure_code(aPixtable && aPixtable->table && aPixtable->header,
2302  CPL_ERROR_NULL_INPUT);
2303  if (cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_XLO) > aLo &&
2304  cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_XHI) < aHi) {
2305  /* no need to do anything */
2306  return CPL_ERROR_NONE;
2307  }
2308  double ptxoff = 0.;
2310  /* need to use the real coordinate offset for celestial spherical */
2311  ptxoff = muse_pfits_get_crval(aPixtable->header, 1);
2312  }
2313 #pragma omp critical(cpl_table_select)
2314  {
2315  cpl_table_unselect_all(aPixtable->table);
2316  cpl_table_or_selected_float(aPixtable->table, MUSE_PIXTABLE_XPOS,
2317  CPL_LESS_THAN, aLo - ptxoff);
2318  cpl_table_or_selected_float(aPixtable->table, MUSE_PIXTABLE_XPOS,
2319  CPL_GREATER_THAN, aHi - ptxoff);
2320  muse_pixtable_fix_exp_headers(aPixtable);
2321  cpl_table_erase_selected(aPixtable->table);
2322  }
2323  return muse_pixtable_compute_limits(aPixtable);
2324 } /* muse_pixtable_restrict_xpos() */
2325 
2326 /*---------------------------------------------------------------------------*/
2337 /*---------------------------------------------------------------------------*/
2338 cpl_error_code
2339 muse_pixtable_restrict_ypos(muse_pixtable *aPixtable, double aLo, double aHi)
2340 {
2341  cpl_ensure_code(aPixtable && aPixtable->table && aPixtable->header,
2342  CPL_ERROR_NULL_INPUT);
2343  if (cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_YLO) > aLo &&
2344  cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_YHI) < aHi) {
2345  /* no need to do anything */
2346  return CPL_ERROR_NONE;
2347  }
2348  double ptyoff = 0.;
2350  /* need to use the real coordinate offset for celestial spherical */
2351  ptyoff = muse_pfits_get_crval(aPixtable->header, 2);
2352  }
2353 #pragma omp critical(cpl_table_select)
2354  {
2355  cpl_table_unselect_all(aPixtable->table);
2356  cpl_table_or_selected_float(aPixtable->table, MUSE_PIXTABLE_YPOS,
2357  CPL_LESS_THAN, aLo - ptyoff);
2358  cpl_table_or_selected_float(aPixtable->table, MUSE_PIXTABLE_YPOS,
2359  CPL_GREATER_THAN, aHi - ptyoff);
2360  muse_pixtable_fix_exp_headers(aPixtable);
2361  cpl_table_erase_selected(aPixtable->table);
2362  }
2363  return muse_pixtable_compute_limits(aPixtable);
2364 } /* muse_pixtable_restrict_ypos() */
2365 
2366 /*---------------------------------------------------------------------------*/
2380 /*---------------------------------------------------------------------------*/
2381 cpl_error_code
2382 muse_pixtable_erase_ifu_slice(muse_pixtable *aPixtable, unsigned char aIFU,
2383  unsigned short aSlice)
2384 {
2385  cpl_ensure_code(aPixtable, CPL_ERROR_NULL_INPUT);
2386  cpl_size nrow = muse_pixtable_get_nrow(aPixtable);
2387  cpl_ensure_code(nrow > 0, CPL_ERROR_DATA_NOT_FOUND);
2388 
2389  cpl_table_unselect_all(aPixtable->table);
2390  uint32_t *origin = (uint32_t *)cpl_table_get_data_int(aPixtable->table,
2392  cpl_size irow;
2393  for (irow = 0; irow < nrow; irow++) {
2394  unsigned char ifu = muse_pixtable_origin_get_ifu(origin[irow]);
2395  unsigned short slice = muse_pixtable_origin_get_slice(origin[irow]);
2396  if (ifu == aIFU && slice == aSlice) {
2397  cpl_table_select_row(aPixtable->table, irow);
2398  } /* if same IFU and slice */
2399  } /* for irow (all pixtable rows) */
2400  cpl_size nsel = cpl_table_count_selected(aPixtable->table);
2401  cpl_error_code rc = cpl_table_erase_selected(aPixtable->table);
2402  cpl_msg_debug(__func__, "Erased %"CPL_SIZE_FORMAT" rows from pixel table",
2403  nsel);
2404 
2405  muse_pixtable_fix_exp_headers(aPixtable);
2406  muse_pixtable_compute_limits(aPixtable);
2407  return rc;
2408 } /* muse_pixtable_erase_ifu_slice() */
2409 
2410 /*---------------------------------------------------------------------------*/
2432 /*---------------------------------------------------------------------------*/
2433 cpl_error_code
2435  const muse_mask *aMask,
2436  const cpl_propertylist *aWCS,
2437  const cpl_table *aOffsets)
2438 {
2439  cpl_ensure_code(aPixtable && aPixtable->table, CPL_ERROR_NULL_INPUT);
2440  cpl_ensure_code(aMask && aMask->mask && aMask->header, CPL_ERROR_NULL_INPUT);
2441 
2442  /* first create WCS object from input mask header for easy access */
2443  cpl_errorstate state = cpl_errorstate_get();
2444  muse_wcs *maskwcs = muse_wcs_new(aMask->header);
2445  if (!maskwcs || !cpl_errorstate_is_equal(state)) {
2446  cpl_msg_error(__func__, "Selecting pixel table rows using mask failed due "
2447  "to faulty WCS in mask header: %s", cpl_error_get_message());
2448  cpl_free(maskwcs);
2449  return cpl_error_get_code();
2450  }
2451 
2452  /* Check of which type the WCS is and which unit it has. This determines *
2453  * how we then need to process the pixel table data to be able to mask it. */
2454  const char *ctype1 = muse_pfits_get_ctype(aMask->header, 1),
2455  *ctype2 = muse_pfits_get_ctype(aMask->header, 2),
2456  *cunit1 = muse_pfits_get_cunit(aMask->header, 1),
2457  *cunit2 = muse_pfits_get_cunit(aMask->header, 2);
2458  maskwcs->iscelsph = (ctype1 && strlen(ctype1) >= 5 && ctype1[4] == '-')
2459  && (ctype2 && strlen(ctype2) >= 5 && ctype2[4] == '-');
2460  /* check that the possible celestial WCS is gnomonic */
2461  if (maskwcs->iscelsph && (!strstr(ctype1, "-TAN") || !strstr(ctype2, "-TAN"))) {
2462  cpl_msg_warning(__func__, "Cannot use mask WCS for pixel selection, "
2463  "unsupported celestial WCS (%s / %s)", ctype1, ctype2);
2464  return CPL_ERROR_UNSUPPORTED_MODE;
2465  }
2466  /* check that the unit is "deg" if the WCS is celestial */
2467  if (maskwcs->iscelsph && ((cunit1 && strncmp(cunit1, "deg", 4)) ||
2468  (cunit2 && strncmp(cunit2, "deg", 4)))) {
2469  cpl_msg_warning(__func__, "Cannot use mask WCS for pixel selection, "
2470  "celestial gnomonic WCS with unsupported units (%s / %s)",
2471  cunit1, cunit2);
2472  return CPL_ERROR_UNSUPPORTED_MODE;
2473  }
2474 
2475  /* If the mask comes with celestial WCS, we need to duplicate and *
2476  * project/position the pixel table before we can check, which pixels *
2477  * need to be selected. This is not necessary for linear WCS. */
2478  muse_pixtable *pt = aPixtable; /* non-celestial case */
2479  double ra = 0., dec = 0.;
2480  if (maskwcs->iscelsph) {
2481  pt = muse_pixtable_duplicate(aPixtable);
2482  if (aWCS) {
2483  muse_wcs_project_tan(pt, aWCS);
2484  } else {
2485  const char *mode = muse_pfits_get_insmode(pt->header);
2486  cpl_msg_warning(__func__, "Using default MUSE %cFM astrometry, pixel "
2487  "selection using mask will be inaccurate!", mode[0]);
2488  cpl_propertylist *wcs = muse_wcs_create_default(pt->header);
2489  muse_wcs_project_tan(pt, wcs);
2490  cpl_propertylist_delete(wcs);
2491  }
2492  muse_postproc_offsets_scale(pt, aOffsets, "single pixel table for masking");
2493  if (!aOffsets) {
2494  cpl_msg_warning(__func__, "Using mask with celestial WCS for pixel "
2495  "selection, but no %s was given. Results will likely "
2496  "be inaccurate!", MUSE_TAG_OFFSET_LIST);
2497  }
2498  ra = muse_pfits_get_ra(pt->header);
2499  dec = muse_pfits_get_dec(pt->header);
2500  muse_wcs_position_celestial(pt, ra, dec);
2501 
2502  /* convert to radians, for muse_wcs_pixel_from_celestial_fast() */
2503  maskwcs->crval1 /= CPL_MATH_DEG_RAD;
2504  maskwcs->crval2 /= CPL_MATH_DEG_RAD;
2505  } /* if celestial */
2506 
2507  /* Use x- and y-positions of the possibly transformed pixel table. */
2508  float *xpos = cpl_table_get_data_float(pt->table, MUSE_PIXTABLE_XPOS),
2509  *ypos = cpl_table_get_data_float(pt->table, MUSE_PIXTABLE_YPOS);
2510  cpl_size nx = cpl_mask_get_size_x(aMask->mask),
2511  ny = cpl_mask_get_size_y(aMask->mask);
2512  const cpl_binary *maskdata = cpl_mask_get_data_const(aMask->mask);
2513 
2514  cpl_size irow, nrows = cpl_table_get_nrow(aPixtable->table),
2515  nsel = cpl_table_count_selected(aPixtable->table),
2516  nenabled = cpl_mask_count(aMask->mask),
2517  narea = 0;
2518  cpl_msg_debug(__func__, "Mask contains %"CPL_SIZE_FORMAT" (%.2f %%) enabled "
2519  "pixels of %"CPL_SIZE_FORMAT" total [%s WCS, %s/%s, units "
2520  "%s/%s]", nenabled, 100.*nenabled/nx/ny, nx*ny,
2521  maskwcs->iscelsph ? "celestial (gnomonic)" : "linear",
2522  ctype1, ctype2, cunit1, cunit2);
2523 #if PIXTABLE_MASK_PARALLEL
2524  #pragma omp parallel for default(none) \
2525  shared(aPixtable, dec, maskdata, maskwcs, narea, nrows, nsel, nx, ny,\
2526  ra, xpos, ypos)
2527 #endif
2528  for (irow = 0; irow < nrows; irow++) {
2529  /* Compute pixel location in mask on possibly transformed pixel table. */
2530  double x, y;
2531  if (maskwcs->iscelsph) {
2532  /* Add RA/DEC zeropoints before the conversion and convert to radians; *
2533  * the crval were already converted to radians above. */
2535  (xpos[irow] + ra) * CPL_MATH_RAD_DEG,
2536  (ypos[irow] + dec) * CPL_MATH_RAD_DEG,
2537  &x, &y);
2538  } else { /* linear case */
2539  muse_wcs_pixel_from_projplane_fast(maskwcs, xpos[irow], ypos[irow], &x, &y);
2540  }
2541  int ix = lround(x),
2542  iy = lround(y);
2543  if ((ix < 1) || (ix > nx) || (iy < 1) || (iy > ny)) {
2544  continue;
2545  }
2546 #if PIXTABLE_MASK_PARALLEL
2547  #pragma omp atomic
2548 #endif
2549  narea++; /* at least this pixel is inside the mask area */
2550  /* Apply selection always on the original pixel table. */
2551  if (maskdata[(ix-1) + (iy-1) * nx] != CPL_BINARY_1) {
2552 #if PIXTABLE_MASK_PARALLEL
2553  #pragma omp critical
2554 #endif
2555  {
2556  cpl_table_unselect_row(aPixtable->table, irow);
2557  nsel--;
2558  }
2559  } /* if */
2560  } /* for all pixel table rows */
2561  if (maskwcs->iscelsph) {
2562  /* need to delete temporary pixel table again */
2564  }
2565  cpl_free(maskwcs);
2566  cpl_msg_debug(__func__, "Mask selected %"CPL_SIZE_FORMAT" (%.2f %%/%.2f %%) "
2567  "pixels of %"CPL_SIZE_FORMAT" total/%"CPL_SIZE_FORMAT" in mask "
2568  "area", nsel, 100.*nsel/nrows, 100.*nsel/narea, nrows, narea);
2569  return CPL_ERROR_NONE;
2570 } /* muse_pixtable_and_selected_mask() */
2571 
2572 /*---------------------------------------------------------------------------*/
2599 /*---------------------------------------------------------------------------*/
2600 cpl_error_code
2601 muse_pixtable_dump(muse_pixtable *aPixtable, cpl_size aStart, cpl_size aCount,
2602  unsigned char aDisplayHeader)
2603 {
2604  cpl_ensure_code(aPixtable && aPixtable->table && aPixtable->header,
2605  CPL_ERROR_NULL_INPUT);
2606  cpl_size nrows = muse_pixtable_get_nrow(aPixtable);
2607  cpl_ensure_code(aStart >= 0 && aStart < nrows && aCount >= 0,
2608  CPL_ERROR_ILLEGAL_INPUT);
2609  cpl_size last = aStart + aCount;
2610  if (last > nrows - 1) {
2611  last = nrows;
2612  }
2613  int haswcs = muse_pixtable_wcs_check(aPixtable);
2614  double ptxoff = 0., ptyoff = 0.;
2615  if (haswcs == MUSE_PIXTABLE_WCS_CELSPH) {
2616  /* need to use the real coordinate offset for celestial spherical */
2617  ptxoff = muse_pfits_get_crval(aPixtable->header, 1);
2618  ptyoff = muse_pfits_get_crval(aPixtable->header, 2);
2619  }
2620  /* for non-pixel coordinates, we will need different formats below */
2621  haswcs = (haswcs == MUSE_PIXTABLE_WCS_NATSPH ||
2622  haswcs == MUSE_PIXTABLE_WCS_CELSPH);
2623  float *cdata_xpos = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_XPOS),
2624  *cdata_ypos = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_YPOS),
2625  *cdata_lambda = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_LAMBDA),
2626  *cdata_data = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_DATA),
2627  *cdata_stat = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_STAT);
2628  cpl_errorstate es = cpl_errorstate_get();
2629  float *cdata_weight = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_WEIGHT);
2630  cpl_errorstate_set(es); /* ignore errors due to missing weight column */
2631  int *cdata_dq = cpl_table_get_data_int(aPixtable->table, MUSE_PIXTABLE_DQ);
2632  uint32_t *cdata_origin = (uint32_t *)cpl_table_get_data_int(aPixtable->table,
2634  cpl_ensure_code(cdata_xpos && cdata_ypos && cdata_lambda &&
2635  cdata_data && cdata_dq && cdata_stat,
2636  CPL_ERROR_BAD_FILE_FORMAT);
2637 
2638  /* print header */
2639  if (aDisplayHeader) {
2640  printf("# xpos ypos lambda data dq stat"
2641  " weight exposure IFU xCCD yCCD xRaw yRaw slice\n");
2642  }
2643  if (aDisplayHeader == 1) {
2644  printf("#%13s %13s %9s %11s flag %11s ---------- No No pix "
2645  " pix pix pix No\n# flux in [%s]\n# flux**2 in [%s]\n",
2646  cpl_table_get_column_unit(aPixtable->table, MUSE_PIXTABLE_XPOS),
2647  cpl_table_get_column_unit(aPixtable->table, MUSE_PIXTABLE_YPOS),
2648  cpl_table_get_column_unit(aPixtable->table, MUSE_PIXTABLE_LAMBDA),
2649  "(flux)", "(flux**2)",
2650  cpl_table_get_column_unit(aPixtable->table, MUSE_PIXTABLE_DATA),
2651  cpl_table_get_column_unit(aPixtable->table, MUSE_PIXTABLE_STAT));
2652  }
2653 
2654  cpl_size i;
2655  for (i = aStart; i < last; i++) {
2656  int x = muse_pixtable_origin_get_x(cdata_origin[i], aPixtable, i),
2657  y = muse_pixtable_origin_get_y_fast(cdata_origin[i]),
2658  xraw = x, yraw = y;
2659  muse_quadrants_coords_to_raw(NULL, &xraw, &yraw);
2660  if (haswcs) {
2661  printf("%14.7e %14.7e %9.3f ", cdata_xpos[i] + ptxoff, cdata_ypos[i] + ptyoff,
2662  cdata_lambda[i]);
2663  } else {
2664  printf("%14.8f %14.8f %9.3f ", cdata_xpos[i], cdata_ypos[i], cdata_lambda[i]);
2665  }
2666  printf("%12.5e 0x%08x %11.5e %10.4e %2d %2d %4d %4d %4d %4d %2d\n",
2667  cdata_data[i], cdata_dq[i], cdata_stat[i],
2668  cdata_weight ? cdata_weight[i] : 0.,
2669  muse_pixtable_get_expnum(aPixtable, i),
2670  cdata_origin ? muse_pixtable_origin_get_ifu_fast(cdata_origin[i])
2671  : 0,
2672  x, y, xraw, yraw,
2673  cdata_origin ? muse_pixtable_origin_get_slice_fast(cdata_origin[i])
2674  : 0);
2675  } /* for i (pixel table rows) */
2676 
2677  return CPL_ERROR_NONE;
2678 } /* muse_pixtable_dump() */
2679 
2680 /*---------------------------------------------------------------------------*/
2702 /*---------------------------------------------------------------------------*/
2705 {
2706  cpl_ensure(aPixtable, CPL_ERROR_NULL_INPUT, MUSE_PIXTABLE_WCS_UNKNOWN);
2707  const char *unitx = cpl_table_get_column_unit(aPixtable->table,
2709  *unity = cpl_table_get_column_unit(aPixtable->table,
2711  cpl_ensure(unitx, CPL_ERROR_DATA_NOT_FOUND, MUSE_PIXTABLE_WCS_UNKNOWN);
2712  cpl_ensure(unity, CPL_ERROR_DATA_NOT_FOUND, MUSE_PIXTABLE_WCS_UNKNOWN);
2713  /* should be equal in the first three characters */
2714  cpl_ensure(!strncmp(unitx, unity, 4), CPL_ERROR_INCOMPATIBLE_INPUT,
2716  if (!strncmp(unitx, "deg", 4)) {
2717  return MUSE_PIXTABLE_WCS_CELSPH;
2718  }
2719  if (!strncmp(unitx, "pix", 4)) {
2720  return MUSE_PIXTABLE_WCS_PIXEL;
2721  }
2722  if (!strncmp(unitx, "rad", 4)) {
2723  return MUSE_PIXTABLE_WCS_NATSPH;
2724  }
2725  cpl_error_set(__func__, CPL_ERROR_ILLEGAL_INPUT);
2727 } /* muse_pixtable_wcs_check() */
2728 
2729 /*---------------------------------------------------------------------------*/
2737 /*---------------------------------------------------------------------------*/
2738 cpl_boolean
2740 {
2741  cpl_ensure(aPixtable, CPL_ERROR_NULL_INPUT, CPL_FALSE);
2742  cpl_errorstate prestate = cpl_errorstate_get();
2743  cpl_boolean flag = cpl_propertylist_get_bool(aPixtable->header,
2745  cpl_errorstate_set(prestate);
2746  return flag;
2747 }
2748 
2749 /*---------------------------------------------------------------------------*/
2757 /*---------------------------------------------------------------------------*/
2758 cpl_boolean
2760 {
2761  cpl_ensure(aPixtable, CPL_ERROR_NULL_INPUT, CPL_FALSE);
2762  cpl_errorstate prestate = cpl_errorstate_get();
2763  cpl_boolean flag = cpl_propertylist_get_bool(aPixtable->header,
2765  cpl_errorstate_set(prestate);
2766  return flag;
2767 }
2768 
2769 /*---------------------------------------------------------------------------*/
2777 /*---------------------------------------------------------------------------*/
2778 cpl_boolean
2780 {
2781  cpl_ensure(aPixtable, CPL_ERROR_NULL_INPUT, CPL_FALSE);
2782  return cpl_propertylist_has(aPixtable->header, MUSE_HDR_PT_RVCORR);
2783 } /* muse_pixtable_is_rvcorr() */
2784 
2785 /*---------------------------------------------------------------------------*/
2794 /*---------------------------------------------------------------------------*/
2795 cpl_error_code
2796 muse_pixtable_reset_dq(muse_pixtable *aPixtable, unsigned int aDQ)
2797 {
2798  cpl_ensure_code(aPixtable, CPL_ERROR_NULL_INPUT);
2799 
2800  unsigned int *dq = (unsigned int *)cpl_table_get_data_int(aPixtable->table,
2802  inverse = ~aDQ; /* inverse bitmask to AND each row's DQ with */
2803  cpl_size i, nrow = muse_pixtable_get_nrow(aPixtable);
2804  #pragma omp parallel for default(none) /* as req. by Ralf */ \
2805  shared(dq, inverse, nrow)
2806  for (i = 0; i < nrow; i++) {
2807  dq[i] &= inverse;
2808  } /* for i (all table rows) */
2809  return CPL_ERROR_NONE;
2810 } /* muse_pixtable_reset_dq() */
2811 
2812 /*---------------------------------------------------------------------------*/
2829 /*---------------------------------------------------------------------------*/
2832 {
2833  cpl_ensure(aPixtable && aPixtable->header, CPL_ERROR_NULL_INPUT, NULL);
2834  unsigned int expnum = muse_pixtable_get_expnum(aPixtable, 0),
2835  explast = muse_pixtable_get_expnum(aPixtable,
2836  muse_pixtable_get_nrow(aPixtable) - 1);
2837  cpl_ensure(expnum == explast, CPL_ERROR_ILLEGAL_INPUT, NULL);
2838 
2839  /* data seems to be valid, we can create the output list */
2841 
2842  /* split the pixel table up into per-slice pixel tables to handle *
2843  * them separately (to get the x-range of each slice for the header) */
2845  /* variables for current image and current IFU */
2846  muse_image *image = NULL;
2847  unsigned short ifu = 0, /* we haven't found any IFU yet */
2848  ilist = 0; /* image index in the list */
2849  int ipt, npt = muse_pixtable_extracted_get_size(pts);
2850  for (ipt = 0; ipt < npt; ipt++) {
2851  float *cdata = cpl_table_get_data_float(pts[ipt]->table, MUSE_PIXTABLE_DATA),
2852  *cstat = cpl_table_get_data_float(pts[ipt]->table, MUSE_PIXTABLE_STAT);
2853  int *cdq = cpl_table_get_data_int(pts[ipt]->table, MUSE_PIXTABLE_DQ);
2854  uint32_t *corigin = (uint32_t *)cpl_table_get_data_int(pts[ipt]->table,
2856  /* if we got to the next (or first) IFU, create new output *
2857  * image of the size of a typical MUSE CCD copy the header *
2858  * from the pixel table but remove specific entries */
2859  if (ifu != muse_pixtable_origin_get_ifu_fast(corigin[0])) {
2860  image = muse_image_new();
2861  image->header = cpl_propertylist_duplicate(pts[ipt]->header);
2862  cpl_propertylist_erase_regexp(image->header, "^ESO DRS MUSE PIXTABLE", 0);
2863  image->data = cpl_image_new(kMuseOutputXRight, kMuseOutputYTop, CPL_TYPE_FLOAT);
2864  image->dq = cpl_image_new(kMuseOutputXRight, kMuseOutputYTop, CPL_TYPE_INT);
2865  /* fill DQ image with EURO3D_MISSDATA, upper value will be cast correctly */
2866  cpl_image_fill_noise_uniform(image->dq, EURO3D_MISSDATA, EURO3D_MISSDATA + 0.1);
2867  image->stat = cpl_image_new(kMuseOutputXRight, kMuseOutputYTop, CPL_TYPE_FLOAT);
2868  cpl_msg_debug(__func__, "new image (index %hu in list)", ilist);
2869  muse_imagelist_set(list, image, ilist++);
2870  } /* if ifu */
2871  if (!image) { /* it cannot really go wrong, but to be sure... */
2872  cpl_msg_error(__func__, "ipt = %d: no image!", ipt);
2873  continue;
2874  }
2875  float *idata = cpl_image_get_data_float(image->data),
2876  *istat = cpl_image_get_data_float(image->stat);
2877  int *idq = cpl_image_get_data_int(image->dq);
2878 
2879  ifu = muse_pixtable_origin_get_ifu_fast(corigin[0]);
2880  unsigned short slice = muse_pixtable_origin_get_slice_fast(corigin[0]);
2881  unsigned int xoff = muse_pixtable_origin_get_offset(pts[ipt], expnum, ifu,
2882  slice),
2883  x1 = INT_MAX, x2 = 0,
2884  irow, nrow = muse_pixtable_get_nrow(pts[ipt]);
2885  for (irow = 0; irow < nrow; irow++) {
2886  /* get coordinate indices from the origin column */
2887  unsigned int x = muse_pixtable_origin_get_x_fast(corigin[irow], xoff) - 1,
2888  y = muse_pixtable_origin_get_y_fast(corigin[irow]) - 1;
2889  idata[x + y*kMuseOutputXRight] = cdata[irow];
2890  idq[x + y*kMuseOutputXRight] = cdq[irow];
2891  istat[x + y*kMuseOutputXRight] = cstat[irow];
2892  if (x < x1) {
2893  x1 = x;
2894  }
2895  if (x > x2) {
2896  x2 = x;
2897  }
2898  } /* for irow */
2899  /* record the approximate horizontal center in the output header */
2900  char *keyword = cpl_sprintf("ESO DRS MUSE SLICE%hu CENTER", slice);
2901  cpl_propertylist_update_float(image->header, keyword, (x2 + x1) / 2. + 1.);
2902 #if 0
2903  cpl_msg_debug(__func__, "IFU %hu %s = %.1f", ifu, keyword,
2904  (x2 + x1) / 2. + 1.);
2905 #endif
2906  cpl_free(keyword);
2907  } /* for ipt */
2909 
2910  return list;
2911 } /* muse_pixtable_to_imagelist() */
2912 
2913 /*---------------------------------------------------------------------------*/
2939 /*---------------------------------------------------------------------------*/
2940 cpl_error_code
2942 {
2943  cpl_ensure_code(aPixtable && aPixtable->header && aList, CPL_ERROR_NULL_INPUT);
2944  unsigned int expnum = muse_pixtable_get_expnum(aPixtable, 0),
2945  explast = muse_pixtable_get_expnum(aPixtable,
2946  muse_pixtable_get_nrow(aPixtable) - 1);
2947  cpl_ensure_code(expnum == explast, CPL_ERROR_ILLEGAL_INPUT);
2948 
2949  /* split the pixel table up into per-slice pixel tables *
2950  * as in muse_pixtable_to_imagelist() and ensure that the *
2951  * number of IFUs matches the number of input images */
2953  if (muse_pixtable_extracted_get_size(pts) / kMuseSlicesPerCCD
2954  != muse_imagelist_get_size(aList)) {
2956  return cpl_error_set(__func__, CPL_ERROR_INCOMPATIBLE_INPUT);
2957  }
2958  /* variables for current image and current IFU */
2959  muse_image *image = NULL;
2960  unsigned short ifu = 0, /* we haven't worked with any IFU yet */
2961  ilist = 0; /* image index in the list */
2962  int ipt, npt = muse_pixtable_extracted_get_size(pts);
2963  for (ipt = 0; ipt < npt; ipt++) {
2964  float *cdata = cpl_table_get_data_float(pts[ipt]->table, MUSE_PIXTABLE_DATA),
2965  *cstat = cpl_table_get_data_float(pts[ipt]->table, MUSE_PIXTABLE_STAT);
2966  uint32_t *corigin = (uint32_t *)cpl_table_get_data_int(pts[ipt]->table,
2968  /* if we got to the next (or first) IFU, get an image from the list */
2969  if (ifu != muse_pixtable_origin_get_ifu_fast(corigin[0])) {
2970  image = muse_imagelist_get(aList, ilist++);
2971  } /* if ifu */
2972  if (!image) { /* it cannot really go wrong, but to be sure... */
2973  cpl_msg_error(__func__, "ipt = %d: no image!", ipt);
2974  continue;
2975  }
2976  float *idata = cpl_image_get_data_float(image->data),
2977  *istat = cpl_image_get_data_float(image->stat);
2978  ifu = muse_pixtable_origin_get_ifu_fast(corigin[0]);
2979  unsigned short slice = muse_pixtable_origin_get_slice_fast(corigin[0]);
2980  unsigned int xoff = muse_pixtable_origin_get_offset(pts[ipt], expnum, ifu,
2981  slice),
2982  irow, nrow = muse_pixtable_get_nrow(pts[ipt]);
2983  for (irow = 0; irow < nrow; irow++) {
2984  /* get coordinate indices from the origin column */
2985  unsigned int x = muse_pixtable_origin_get_x_fast(corigin[irow], xoff) - 1,
2986  y = muse_pixtable_origin_get_y_fast(corigin[irow]) - 1;
2987  cdata[irow] = idata[x + y*kMuseOutputXRight];
2988  cstat[irow] = istat[x + y*kMuseOutputXRight];
2989  } /* for irow */
2990  } /* for ipt */
2992 
2993  return CPL_ERROR_NONE;
2994 } /* muse_pixtable_from_imagelist() */
2995 
2996 /*---------------------------------------------------------------------------*/
3006 /*---------------------------------------------------------------------------*/
3007 muse_pixtable *
3009  double aHigh)
3010 {
3011  cpl_ensure(aPixtable && aPixtable->table && aPixtable->header,
3012  CPL_ERROR_NULL_INPUT, NULL);
3013  muse_pixtable *pt = cpl_calloc(1, sizeof(muse_pixtable));
3014  pt->header = cpl_propertylist_duplicate(aPixtable->header);
3015 
3016 #pragma omp critical(cpl_table_select)
3017  {
3018  cpl_table_select_all(aPixtable->table);
3019  cpl_table_and_selected_float(aPixtable->table, MUSE_PIXTABLE_LAMBDA,
3020  CPL_NOT_LESS_THAN, aLow);
3021  cpl_table_and_selected_float(aPixtable->table, MUSE_PIXTABLE_LAMBDA,
3022  CPL_NOT_GREATER_THAN, aHigh);
3023  pt->table = cpl_table_extract_selected(aPixtable->table);
3024  cpl_table_select_all(aPixtable->table);
3025  }
3026 
3028  return pt;
3029 } /* muse_pixtable_extract_wavelength() */
3030 
3031 /*---------------------------------------------------------------------------*/
3044 /*---------------------------------------------------------------------------*/
3045 muse_pixtable **
3047 {
3048  cpl_ensure(aPixtable, CPL_ERROR_NULL_INPUT, NULL);
3049  cpl_size n_rows = cpl_table_get_nrow(aPixtable->table);
3050  unsigned int ifu_slice_mask = (0x1f << MUSE_ORIGIN_SHIFT_IFU) | 0x3f;
3051  cpl_table_duplicate_column(aPixtable->table, "ifuslice",
3052  aPixtable->table, MUSE_PIXTABLE_ORIGIN);
3053  unsigned int *slicedata = (unsigned int *)
3054  cpl_table_get_data_int(aPixtable->table, "ifuslice");
3055  cpl_size i_row;
3056  unsigned int last_ifu_slice = 0;
3057  int is_sorted = CPL_TRUE;
3058  for (i_row = 0; i_row < n_rows; i_row++) {
3059  slicedata[i_row] &= ifu_slice_mask;
3060  if (is_sorted && slicedata[i_row] < last_ifu_slice) {
3061  is_sorted = CPL_FALSE;
3062  } else {
3063  last_ifu_slice = slicedata[i_row];
3064  }
3065  }
3066  if (!is_sorted) {
3067  cpl_propertylist *order = cpl_propertylist_new();
3068  cpl_propertylist_append_bool(order, "ifuslice", CPL_FALSE);
3069  cpl_propertylist_append_bool(order, MUSE_PIXTABLE_LAMBDA, CPL_FALSE);
3070  cpl_msg_debug(__func__, "sorting pixel table: quick sort, %"CPL_SIZE_FORMAT
3071  " entries", n_rows);
3072  cpl_table_sort(aPixtable->table, order);
3073  cpl_propertylist_delete(order);
3074  /* erase headers that depend on the order in the pixel table */
3075  cpl_propertylist_erase_regexp(aPixtable->header, MUSE_HDR_PT_EXP_REGEXP, 0);
3076  cpl_msg_debug(__func__, "pixel table sorted.");
3077  } /* if !sorted */
3078 
3079  i_row = 0;
3080  cpl_size n_col = cpl_table_get_ncol(aPixtable->table);
3081  cpl_array *colnames = cpl_table_get_column_names(aPixtable->table);
3082  muse_pixtable **slice_tables = cpl_calloc(1, sizeof(muse_pixtable *));
3083  cpl_size n_slices = 0;
3084  while (i_row < n_rows) {
3085  unsigned int ifu_slice = slicedata[i_row];
3086  cpl_size j_row;
3087  for (j_row = i_row+1; j_row < n_rows && slicedata[j_row] == ifu_slice;
3088  j_row++)
3089  ;
3090  cpl_size nrows_slice = j_row - i_row;
3091  muse_pixtable *slice_pixtable = cpl_calloc(1, sizeof(muse_pixtable));
3092  slice_pixtable->table = cpl_table_new(nrows_slice);
3093  cpl_size i_col;
3094  for (i_col = 0; i_col < n_col; i_col++) {
3095  const char *cname = cpl_array_get_string(colnames, i_col);
3096  if (strcmp(cname, "ifuslice") == 0)
3097  continue;
3098  cpl_type ctype = cpl_table_get_column_type(aPixtable->table, cname);
3099  if (ctype == CPL_TYPE_INT) {
3100  int *cdata = cpl_table_get_data_int(aPixtable->table, cname);
3101  cpl_table_wrap_int(slice_pixtable->table, cdata + i_row, cname);
3102  } else if (ctype == CPL_TYPE_FLOAT) {
3103  float *cdata = cpl_table_get_data_float(aPixtable->table, cname);
3104  cpl_table_wrap_float(slice_pixtable->table, cdata + i_row, cname);
3105  } else if (ctype == CPL_TYPE_DOUBLE) {
3106  double *cdata = cpl_table_get_data_double(aPixtable->table, cname);
3107  cpl_table_wrap_double(slice_pixtable->table, cdata + i_row, cname);
3108  } else if (ctype == CPL_TYPE_STRING) {
3109  char **cdata = cpl_table_get_data_string(aPixtable->table, cname);
3110  cpl_table_wrap_string(slice_pixtable->table, cdata + i_row, cname);
3111  }
3112  const char *unit = cpl_table_get_column_unit(aPixtable->table, cname);
3113  cpl_table_set_column_unit(slice_pixtable->table, cname, unit);
3114  } /* for i_col (all table columns) */
3115 
3116  slice_pixtable->header = cpl_propertylist_duplicate(aPixtable->header);
3117  muse_pixtable_compute_limits(slice_pixtable);
3118  slice_tables = cpl_realloc(slice_tables,
3119  (n_slices + 2) * sizeof(muse_pixtable *));
3120  slice_tables[n_slices] = slice_pixtable;
3121  n_slices++;
3122  slice_tables[n_slices] = NULL;
3123  i_row = j_row;
3124  } /* while (all full pixel table rows) */
3125  cpl_array_delete(colnames);
3126  cpl_table_erase_column(aPixtable->table, "ifuslice");
3127 
3128  return slice_tables;
3129 } /* muse_pixtable_extracted_get_slices() */
3130 
3131 /*---------------------------------------------------------------------------*/
3142 /*---------------------------------------------------------------------------*/
3143 cpl_size
3145 {
3146  cpl_ensure(aPixtables, CPL_ERROR_NULL_INPUT, -1);
3147  cpl_size n = 0;
3148  while (aPixtables[n] != NULL) {
3149  n++;
3150  }
3151  return n;
3152 } /* muse_pixtable_extracted_get_size() */
3153 
3154 /*---------------------------------------------------------------------------*/
3164 /*---------------------------------------------------------------------------*/
3165 void
3167 {
3168  if (!aPixtables) {
3169  return;
3170  }
3171  muse_pixtable **t;
3172  for (t = aPixtables; *t != NULL; t++) {
3173  cpl_array *colnames = cpl_table_get_column_names((*t)->table);
3174  cpl_size n_col = cpl_table_get_ncol((*t)->table);
3175  cpl_size i_col;
3176  for (i_col = 0; i_col < n_col; i_col++) {
3177  const char *cname = cpl_array_get_string(colnames, i_col);
3178  cpl_table_unwrap((*t)->table, cname);
3179  }
3180  cpl_array_delete(colnames);
3181  cpl_table_delete((*t)->table);
3182  cpl_propertylist_delete((*t)->header);
3183  cpl_free(*t);
3184  }
3185  cpl_free(aPixtables);
3186 } /* muse_pixtable_extracted_delete() */
3187 
#define MUSE_PIXTABLE_DQ
Definition: muse_pixtable.h:49
#define MUSE_PIXTABLE_XPOS
Definition: muse_pixtable.h:51
cpl_polynomial ** muse_trace_table_get_polys_for_slice(const cpl_table *aTable, const unsigned short aSlice)
construct polynomial from the trace table entry for the given slice
#define MUSE_PIXTABLE_FFDATA
Definition: muse_pixtable.h:62
muse_pixtable_wcs
State of the astrometric calibration of a MUSE pixel table.
unsigned int muse_pixtable_get_expnum(muse_pixtable *aPixtable, cpl_size aRow)
Get the exposure number of a given row in a pixel table.
cpl_array * muse_cplarray_interpolate_table_linear(const cpl_array *aTargetAbscissa, const cpl_table *aSrcTable, const char *aSrcAbscissa, const char *aSrcOrdinate)
Linear interpolation of a 1d column.
cpl_error_code muse_wave_table_get_orders(const cpl_table *aWave, unsigned short *aXOrder, unsigned short *aYOrder)
Determine the x- and y-order of the polynomial stored in a wavelength calibration table...
Structure definition for a collection of muse_images.
int muse_trace_table_get_order(const cpl_table *aTable)
determine order of tracing polynomial from table
#define MUSE_HDR_PT_EXP_FST
FITS header keyword defining the first row index for a given exposure.
Definition: muse_pixtable.h:94
void muse_pixtable_extracted_delete(muse_pixtable **aPixtables)
Delete a pixel table array.
cpl_polynomial * muse_wave_table_get_poly_for_slice(const cpl_table *aTable, const unsigned short aSlice)
Construct polynomial from the wavelength calibration table entry for the given slice.
const char * muse_pfits_get_extname(const cpl_propertylist *aHeaders)
find out the extension name
Definition: muse_pfits.c:205
const char * muse_pfits_get_insmode(const cpl_propertylist *aHeaders)
find out the observation mode
Definition: muse_pfits.c:1383
muse_pixtable * muse_pixtable_load(const char *aFilename)
Load the table itself and the FITS headers of a MUSE pixel table from a file.
unsigned short muse_pixtable_origin_get_slice(uint32_t aOrigin)
Get the slice number from the encoded 32bit origin number.
muse_pixtable * muse_pixtable_duplicate(muse_pixtable *aPixtable)
Make a copy of the pixtanle.
#define MUSE_HDR_PT_XLO
FITS header keyword contains the lower limit of the data in x-direction.
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
#define MUSE_PIXTABLE_FFLAMBDA
Definition: muse_pixtable.h:61
A structure containing a spatial two-axis WCS.
Definition: muse_wcs.h:105
unsigned int muse_pixtable_origin_set_offset(muse_pixtable *aPixtable, cpl_polynomial *aLTrace, unsigned short aIFU, unsigned short aSlice)
Set the slice offset from the pixel table header.
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
double muse_pfits_get_ra(const cpl_propertylist *aHeaders)
find out the right ascension
Definition: muse_pfits.c:267
cpl_size muse_pfits_get_naxis(const cpl_propertylist *aHeaders, unsigned int aAxis)
find out the size of a given axis
Definition: muse_pfits.c:242
#define MUSE_HDR_PT_FLUXCAL
muse_pixtable ** muse_pixtable_extracted_get_slices(muse_pixtable *aPixtable)
Extract one pixel table per IFU and slice.
void muse_postproc_offsets_scale(muse_pixtable *aPT, const cpl_table *aOffsets, const char *aPurpose)
Apply spatial offsets and flux scale to a pixel table (of a single exposure)
cpl_image * data
the data extension
Definition: muse_image.h:46
cpl_size muse_pixtable_get_nrow(const muse_pixtable *aPixtable)
get the number of rows within the pixel table
#define MUSE_HDR_PT_LHI
FITS header keyword contains the upper limit of the data in spectral direction.
#define MUSE_HDR_PT_ILO
FITS header keyword contains the lowest IFU number in the data.
int muse_pixtable_get_type(muse_pixtable *aPixtable)
Determine the type of pixel table.
#define MUSE_HDR_PT_EXP_LST
FITS header keyword defining the last row index for a given exposure.
Definition: muse_pixtable.h:99
cpl_error_code muse_pixtable_erase_ifu_slice(muse_pixtable *aPixtable, unsigned char aIFU, unsigned short aSlice)
Erase pixel table rows related to one slice of one IFU.
static void muse_wcs_pixel_from_projplane_fast(muse_wcs *aWCS, double aX, double aY, double *aXOut, double *aYOut)
Convert from projection plane coordinates to pixel coordinates.
Definition: muse_wcs.h:246
cpl_error_code muse_pixtable_dump(muse_pixtable *aPixtable, cpl_size aStart, cpl_size aCount, unsigned char aDisplayHeader)
Dump a MUSE pixel table to the screen, resolving the origin column.
cpl_image * stat
the statistics extension
Definition: muse_image.h:64
#define MUSE_HDR_PT_FFCORR
#define MUSE_HDR_PT_TYPE
Pixel table "type" stored in the FITS header.
Definition: muse_pixtable.h:84
const char * muse_pfits_get_bunit(const cpl_propertylist *aHeaders)
find out the unit string
Definition: muse_pfits.c:223
#define MUSE_HDR_PT_MERGED
Structure definition of MUSE three extension FITS file.
Definition: muse_image.h:40
cpl_table * table
The pixel table.
const char * muse_pfits_get_cunit(const cpl_propertylist *aHeaders, unsigned int aAxis)
find out the WCS axis unit string
Definition: muse_pfits.c:491
cpl_propertylist * header
the FITS header
Definition: muse_image.h:72
cpl_error_code muse_pixtable_origin_copy_offsets(muse_pixtable *aOut, muse_pixtable *aFrom, unsigned int aNum)
Copy MUSE_HDR_PT_IFU_SLICE_OFFSET keywords between pixel tables.
cpl_error_code muse_pixtable_origin_decode_all(muse_pixtable *aPixtable, unsigned short **aX, unsigned short **aY, unsigned char **aIFU, unsigned char **aSlice)
Fill arrays with decoded entries from the origin column.
cpl_error_code muse_pixtable_reset_dq(muse_pixtable *aPixtable, unsigned int aDQ)
Reset a given bad pixel status (DQ flag) for all pixels in the table.
cpl_error_code muse_cpltable_check(const cpl_table *aTable, const muse_cpltable_def *aDef)
Check whether the table contains the fields of the definition.
#define MUSE_PIXTABLE_DATA
Definition: muse_pixtable.h:48
unsigned int muse_imagelist_get_size(muse_imagelist *aList)
Return the number of stored images.
muse_imagelist * muse_pixtable_to_imagelist(muse_pixtable *aPixtable)
Project a pixel table with data from one IFU back onto its image.
void muse_trace_polys_delete(cpl_polynomial *aPolys[])
Delete the multi-polynomial array created in relation to tracing.
cpl_error_code muse_wcs_project_tan(muse_pixtable *aPixtable, const cpl_propertylist *aWCS)
Carry out a gnomonic projection of a pixel table into native spherical coordinates.
Definition: muse_wcs.c:1353
#define MUSE_HDR_PT_SHI
FITS header keyword contains the highest slice number in the data.
cpl_image * dq
the data quality extension
Definition: muse_image.h:56
cpl_error_code muse_pixtable_append_ff(muse_pixtable *aPixtable, muse_image *aFF, cpl_table *aTrace, cpl_table *aWave, float aSampling)
Create flat-field spectrum and append to pixel table.
cpl_error_code muse_pixtable_restrict_wavelength(muse_pixtable *aPixtable, double aLow, double aHigh)
Restrict a pixel table to a certain wavelength range.
cpl_table * muse_cpltable_new(const muse_cpltable_def *aDef, cpl_size aLength)
Create an empty table according to the specified definition.
cpl_boolean muse_pixtable_is_skysub(muse_pixtable *aPixtable)
Determine whether the pixel table is sky subtracted.
unsigned int muse_pixtable_origin_get_x(uint32_t aOrigin, muse_pixtable *aPixtable, cpl_size aRow)
Get the horizontal coordinate from the encoded 32bit origin number.
muse_wcs * muse_wcs_new(cpl_propertylist *aHeader)
Create a new WCS structure from a given FITS header.
Definition: muse_wcs.c:1897
#define MUSE_PIXTABLE_WEIGHT
Definition: muse_pixtable.h:57
Structure definition of MUSE pixel table.
#define MUSE_HDR_PT_IFU_SLICE_OFFSET
FITS header keyword for the horizontal slice offset on the CCD.
Definition: muse_pixtable.h:75
#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.
#define MUSE_PIXTABLE_FF_EXT
Definition: muse_pixtable.h:60
muse_pixtable_wcs muse_pixtable_wcs_check(muse_pixtable *aPixtable)
Check the state of the world coordinate system of a pixel table.
#define MUSE_HDR_PT_YLO
FITS header keyword contains the lower limit of the data in y-direction.
static void muse_wcs_pixel_from_celestial_fast(muse_wcs *aWCS, double aRA, double aDEC, double *aX, double *aY)
Convert from celestial spherical coordinates to pixel coordinates.
Definition: muse_wcs.h:177
cpl_propertylist * muse_wcs_create_default(const cpl_propertylist *aHeader)
Create FITS headers containing a default (relative) WCS.
Definition: muse_wcs.c:1184
#define MUSE_HDR_PT_SKYSUB
cpl_boolean muse_pixtable_is_fluxcal(muse_pixtable *aPixtable)
Determine whether the pixel table is flux calibrated.
#define MUSE_HDR_PT_ILLUM_REGEXP
cpl_table * ffspec
A flat-field spectrum.
cpl_array * muse_cplarray_interpolate_linear(const cpl_array *aTargetAbscissa, const cpl_array *aSourceAbscissa, const cpl_array *aSourceOrdinate)
Linear interpolation of a 1d array.
#define MUSE_HDR_PT_IHI
FITS header keyword contains the highest IFU number in the data.
unsigned int muse_pixtable_origin_get_offset(muse_pixtable *aPixtable, unsigned int aExpNum, unsigned short aIFU, unsigned short aSlice)
Get the slice offset from the pixel table header.
uint32_t muse_pixtable_origin_encode(unsigned int aX, unsigned int aY, unsigned short aIFU, unsigned short aSlice, unsigned int aOffset)
Encode the three CCD coordinates defining the origin of one MUSE pixel into a 32bit integer...
double muse_pfits_get_dec(const cpl_propertylist *aHeaders)
find out the declination
Definition: muse_pfits.c:285
cpl_error_code muse_pixtable_and_selected_mask(muse_pixtable *aPixtable, const muse_mask *aMask, const cpl_propertylist *aWCS, const cpl_table *aOffsets)
Select all pixels where the spatial positions are enabled in the given mask.
muse_pixtable * muse_pixtable_load_window(const char *aFilename, cpl_size aStart, cpl_size aNRows)
Load a range of rows from the table and all the FITS headers of a MUSE pixel table from a file...
muse_pixtable_operation
Type of operation to apply to a MUSE pixel table.
muse_pixtable * muse_pixtable_extract_wavelength(muse_pixtable *aPixtable, double aLow, double aHigh)
Create a new pixtable with values within the selected wavelengths.
muse_pixtable * muse_pixtable_create(muse_image *aImage, cpl_table *aTrace, cpl_table *aWave, cpl_table *aGeoTable)
Create the pixel table for one CCD.
muse_pixtable * muse_pixtable_load_restricted_wavelength(const char *aFilename, double aLambdaMin, double aLambdaMax)
Load a pixel table from file and cut down the wavelength range.
#define MUSE_PIXTABLE_ORIGIN
Definition: muse_pixtable.h:54
cpl_error_code muse_cplpropertylist_update_long_long(cpl_propertylist *aHeader, const char *aKeyword, cpl_size aValue)
Update an integer-like property irrespective of the real type.
#define MUSE_HDR_PT_LLO
FITS header keyword contains the lower limit of the data in spectral direction.
const char * muse_pfits_get_ctype(const cpl_propertylist *aHeaders, unsigned int aAxis)
find out the WCS axis type string
Definition: muse_pfits.c:469
cpl_error_code muse_pixtable_save(muse_pixtable *aPixtable, const char *aFilename)
Save a MUSE pixel table to a file on disk.
cpl_error_code muse_cpltable_copy_array(cpl_table *aTable, const char *aColumn, const cpl_array *aArray)
Copy an array into a table.
unsigned short muse_pixtable_origin_get_ifu(uint32_t aOrigin)
Get the IFU number from the encoded 32bit origin number.
muse_pixtable * muse_pixtable_load_merge_channels(cpl_table *aExposureList, double aLambdaMin, double aLambdaMax)
Load and merge the pixel tables of the 24 MUSE sub-fields.
cpl_error_code muse_pixtable_restrict_xpos(muse_pixtable *aPixtable, double aLo, double aHi)
Restrict a pixel table to a certain x coordinate range.
#define MUSE_PIXTABLE_STAT
Definition: muse_pixtable.h:50
cpl_error_code muse_pixtable_from_imagelist(muse_pixtable *aPixtable, muse_imagelist *aList)
Get pixel table values back from a per-IFU imagelist.
Handling of "mask" files.
Definition: muse_mask.h:43
muse_imagelist * muse_imagelist_new(void)
Create a new (empty) MUSE image list.
const muse_cpltable_def muse_pixtable_def[]
MUSE pixel table definition.
#define MUSE_PIXTABLE_LAMBDA
Definition: muse_pixtable.h:53
cpl_table * muse_geo_table_extract_ifu(const cpl_table *aTable, const unsigned char aIFU)
Extract the part of a geometry table dealing with a given IFU.
Definition: muse_geo.c:235
cpl_error_code muse_quadrants_coords_to_raw(cpl_propertylist *aHeader, int *aX, int *aY)
Convert coordinates of a trimmed image to raw-image coordinates.
cpl_boolean iscelsph
Definition: muse_wcs.h:112
#define MUSE_HDR_PT_SLO
FITS header keyword contains the lowest slice number in the data.
cpl_propertylist * header
the FITS header
Definition: muse_mask.h:56
cpl_error_code muse_pixtable_spectrum_apply(muse_pixtable *aPixtable, const cpl_array *aLambdas, const cpl_array *aFlux, muse_pixtable_operation aOperation)
Apply a spectrum given by two arrays with an operation to a pixel table.
#define MUSE_HDR_PT_RVCORR
Definition of a cpl table structure.
muse_image * muse_image_new(void)
Allocate memory for a new muse_image object.
Definition: muse_image.c:66
cpl_error_code muse_wcs_position_celestial(muse_pixtable *aPixtable, double aRA, double aDEC)
Convert native to celestial spherical coordinates in a pixel table.
Definition: muse_wcs.c:1493
double crval2
Definition: muse_wcs.h:107
cpl_table * muse_resampling_spectrum(muse_pixtable *aPixtable, double aBinwidth)
Resample the selected pixels of a pixel table into a spectrum.
unsigned int muse_pixtable_origin_get_y(uint32_t aOrigin)
Get the vertical coordinate from the encoded 32bit origin number.
cpl_mask * mask
The mask data.
Definition: muse_mask.h:49
#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_pixtable_restrict_ypos(muse_pixtable *aPixtable, double aLo, double aHi)
Restrict a pixel table to a certain y coordinate range.
#define MUSE_HDR_PT_YHI
FITS header keyword contains the upper limit of the data in y-direction.
cpl_error_code muse_imagelist_set(muse_imagelist *aList, muse_image *aImage, unsigned int aIdx)
Set the muse_image of given list index.
cpl_error_code muse_pixtable_compute_limits(muse_pixtable *aPixtable)
(Re-)Compute the limits of the coordinate columns of a pixel table.
static cpl_error_code muse_pixtable_fix_exp_headers(muse_pixtable *aPixtable)
Fix the exposure ranges in the header of a pixel table.
cpl_propertylist * header
The FITS header.
cpl_error_code muse_pixtable_flux_multiply(muse_pixtable *aPixtable, double aScale)
Scale the flux of a pixel table with correct treatment of variance.
#define MUSE_HDR_PT_XHI
FITS header keyword contains the upper limit of the data in x-ion.
cpl_boolean muse_pixtable_is_rvcorr(muse_pixtable *aPixtable)
Determine whether the pixel table is radial-velocity corrected.