MUSE Pipeline Reference Manual  2.5.2
muse_resampling.c
1 /* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set sw=2 sts=2 et cin: */
3 /*
4  * This file is part of the MUSE Instrument Pipeline
5  * Copyright (C) 2005-2018 European Southern Observatory
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20  */
21 
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25 
26 /*----------------------------------------------------------------------------*
27  * Includes *
28  *----------------------------------------------------------------------------*/
29 #include <cpl.h>
30 #include <math.h>
31 #include <string.h>
32 #ifndef _OPENMP
33 #define omp_get_max_threads() 1
34 #else
35 #include <omp.h>
36 #endif
37 
38 #include "muse_resampling.h"
39 #include "muse_instrument.h"
40 
41 #include "muse_astro.h"
42 #include "muse_cplwrappers.h"
43 #include "muse_dar.h"
44 #include "muse_dfs.h"
45 #include "muse_flux.h"
46 #include "muse_pfits.h"
47 #include "muse_pixgrid.h"
48 #include "muse_pixtable.h"
49 #include "muse_quality.h"
50 #include "muse_utils.h"
51 #include "muse_wcs.h"
52 #include "muse_data_format_z.h"
53 
54 /*----------------------------------------------------------------------------*/
58 /*----------------------------------------------------------------------------*/
59 
62 /*----------------------------------------------------------------------------*
63  * Resampling, collapsing, and saving in 3D *
64  *----------------------------------------------------------------------------*/
65 
66 /*---------------------------------------------------------------------------*/
79 /*---------------------------------------------------------------------------*/
82 {
83  cpl_ensure(aMethod <= MUSE_RESAMPLE_NONE, CPL_ERROR_ILLEGAL_INPUT, NULL);
84  muse_resampling_params *params = cpl_calloc(1, sizeof(muse_resampling_params));
85  params->method = aMethod;
86  /* leave crtype zero == MUSE_RESAMPLING_CRSTATS_IRAF by default */
87  /* leave crsigma zero, to not do CR rejection by default */
88  params->ld = 1;
89  params->pfx = 0.6;
90  params->pfy = 0.6;
91  params->pfl = 0.6;
92  params->rc = 1.25;
93  /* dx, dy, and dlambda, and wcs stay zero to trigger defaults */
94  /* leave tlambda zero == MUSE_RESAMPLING_DISP_AWAV by default */
95  return params;
96 } /* muse_resampling_params_new() */
97 
98 /*---------------------------------------------------------------------------*/
115 /*---------------------------------------------------------------------------*/
116 cpl_error_code
118  const char *aString)
119 {
120  cpl_ensure_code(aParams && aString, CPL_ERROR_NULL_INPUT);
121  cpl_array *pf = muse_cplarray_new_from_delimited_string(aString, ",");
122  int npf = cpl_array_get_size(pf);
123  cpl_error_code rc = CPL_ERROR_NONE;
124  switch (npf) {
125  case 1:
126  aParams->pfx = aParams->pfy = aParams->pfl = atof(cpl_array_get_string(pf, 0));
127  break;
128  case 2:
129  aParams->pfx = aParams->pfy = atof(cpl_array_get_string(pf, 0));
130  aParams->pfl = atof(cpl_array_get_string(pf, 1));
131  break;
132  case 3:
133  aParams->pfx = atof(cpl_array_get_string(pf, 0));
134  aParams->pfy = atof(cpl_array_get_string(pf, 1));
135  aParams->pfl = atof(cpl_array_get_string(pf, 2));
136  break;
137  default:
138  cpl_msg_warning(__func__, "%d instead of 1-3 values (\"%s\") were given as "
139  "pixfrac, values remain unchanged (%.2f, %.2f, %.2f)!",
140  npf, aString, aParams->pfx, aParams->pfy, aParams->pfl);
141  rc = CPL_ERROR_ILLEGAL_INPUT;
142  } /* switch */
143  cpl_array_delete(pf);
144  return rc;
145 } /* muse_resampling_params_set_pixfrac() */
146 
147 /*---------------------------------------------------------------------------*/
166 /*---------------------------------------------------------------------------*/
167 cpl_error_code
169  const cpl_propertylist *aWCS)
170 {
171  cpl_ensure_code(aParams, CPL_ERROR_NULL_INPUT);
172  if (!aWCS) {
174  cpl_wcs_delete(aParams->wcs);
175  aParams->wcs = NULL;
176  return CPL_ERROR_NONE;
177  }
178  /* first make sure it wasn't set to rubbish elsewhere */
180  if (cpl_propertylist_has(aWCS, "CTYPE3")) {
181  if (!strncmp(muse_pfits_get_ctype(aWCS, 3), "AWAV-LOG", 9)) {
183  } else if (!strncmp(muse_pfits_get_ctype(aWCS, 3), "WAVE", 5)) {
185  } else if (!strncmp(muse_pfits_get_ctype(aWCS, 3), "WAVE-LOG", 9)) {
187  } else {
188  /* MUSE_RESAMPLING_DISP_AWAV, do nothing */
189  }
190  } /* if CTYPE3 given */
191  cpl_errorstate state = cpl_errorstate_get();
192  cpl_error_code rc = CPL_ERROR_NONE;
193  aParams->wcs = cpl_wcs_new_from_propertylist(aWCS);
194  if (!cpl_errorstate_is_equal(state)) {
195  cpl_wcs_delete(aParams->wcs);
196  aParams->wcs = NULL;
197  rc = cpl_error_get_code();
198  }
199 #if 0
200  printf("CDi_j matrix:\n");
201  cpl_matrix_dump(cpl_wcs_get_cd(aParams->wcs), stdout);
202  fflush(stdout);
203 #endif
204  return rc;
205 } /* muse_resampling_params_set_wcs() */
206 
207 /*---------------------------------------------------------------------------*/
215 /*---------------------------------------------------------------------------*/
216 void
218 {
219  if (!aParams) {
220  return;
221  }
222  cpl_wcs_delete(aParams->wcs);
223  cpl_free(aParams);
224 } /* muse_resampling_params_delete() */
225 
226 /*---------------------------------------------------------------------------*/
237 /*---------------------------------------------------------------------------*/
238 static inline double
239 muse_resampling_weight_function_linear(double r)
240 {
241  return r == 0 ? FLT_MAX : 1. / r;
242 }
243 
244 /*---------------------------------------------------------------------------*/
255 /*---------------------------------------------------------------------------*/
256 static inline double
257 muse_resampling_weight_function_quadratic(double r2)
258 {
259  return r2 == 0 ? FLT_MAX : 1. / r2;
260 }
261 
262 /*---------------------------------------------------------------------------*/
275 /*---------------------------------------------------------------------------*/
276 static inline double
277 muse_resampling_weight_function_renka(double r, double r_c)
278 {
279  if (r == 0) {
280  return FLT_MAX;
281  } else if (r >= r_c) {
282  return DBL_MIN;
283  } else {
284  double p = (r_c - r) / (r_c * r);
285  return p*p;
286  }
287 }
288 
289 /*---------------------------------------------------------------------------*/
296 /*---------------------------------------------------------------------------*/
297 static inline double
298 muse_resampling_weight_function_sinc(double r)
299 {
300  return fabs(r) < DBL_EPSILON ? 1. : sin(CPL_MATH_PI * r) / (CPL_MATH_PI * r);
301 }
302 
303 /*---------------------------------------------------------------------------*/
313 /*---------------------------------------------------------------------------*/
314 static inline double
315 muse_resampling_weight_function_lanczos(double dx, double dy, double dz, unsigned int n)
316 {
317  return (fabs(dx) >= n || fabs(dy) >= n || fabs(dz) > n) ? 0.
318  : muse_resampling_weight_function_sinc(dx) * muse_resampling_weight_function_sinc(dx / n)
319  * muse_resampling_weight_function_sinc(dy) * muse_resampling_weight_function_sinc(dy / n)
320  * muse_resampling_weight_function_sinc(dz) * muse_resampling_weight_function_sinc(dz / n);
321 }
322 
323 /*---------------------------------------------------------------------------*/
342 /*---------------------------------------------------------------------------*/
343 static inline double
344 muse_resampling_weight_function_drizzle(double xin, double yin, double zin,
345  double xout, double yout, double zout,
346  double dx, double dy, double dz)
347 {
348  /* compute the three terms in the numerator: if the offset *
349  * plus the output halfsize is less than the input halfsize, *
350  * then that side is fully contained in the input pixel */
351  double x = (dx + xout / 2.) <= xin / 2. ? xout : (xin + xout) / 2. - dx,
352  y = (dy + yout / 2.) <= yin / 2. ? yout : (yin + yout) / 2. - dy,
353  z = (dz + zout / 2.) <= zin / 2. ? zout : (zin + zout) / 2. - dz;
354  /* any negative value means that the input pixel is completely *
355  * outside the target voxel, so it doesn't contribute */
356  if (x <= 0 || y <= 0 || z <= 0) {
357  return 0.;
358  }
359  /* any value > input size means this dimension of the input pixel *
360  * is completely inside the target voxel, so that's the limit! */
361  return (x > xin ? xin : x) * (y > yin ? yin : y) * (z > zin ? zin : z)
362  / (xin * yin * zin);
363 } /* muse_resampling_weight_function_drizzle() */
364 
365 /*---------------------------------------------------------------------------*/
381 /*---------------------------------------------------------------------------*/
382 static cpl_error_code
383 muse_resampling_cube_nearest(muse_datacube *aCube, muse_pixtable *aPixtable,
384  muse_pixgrid *aGrid)
385 {
386  cpl_ensure_code(aCube && aPixtable && aGrid, CPL_ERROR_NULL_INPUT);
387  double ptxoff = 0., /* zero by default ... */
388  ptyoff = 0., /* for pixel coordinates */
389  crval3 = muse_pfits_get_crval(aCube->header, 3),
390  crpix3 = muse_pfits_get_crpix(aCube->header, 3),
391  cd33 = muse_pfits_get_cd(aCube->header, 3, 3);
392  const char *ctype3 = muse_pfits_get_ctype(aCube->header, 3);
393  muse_wcs *wcs = muse_wcs_new(aCube->header);
395  cpl_boolean loglambda = ctype3 && (!strncmp(ctype3, "AWAV-LOG", 9) ||
396  !strncmp(ctype3, "WAVE-LOG", 9));
397  float *xpos = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_XPOS),
398  *ypos = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_YPOS),
399  *lbda = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_LAMBDA),
400  *data = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_DATA),
401  *stat = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_STAT);
402  int *dq = cpl_table_get_data_int(aPixtable->table, MUSE_PIXTABLE_DQ);
403 
404  /* If our data was astrometrically calibrated, we need to scale the *
405  * data units to the pixel size in all three dimensions so that the *
406  * radius computation works again. *
407  * Otherwise dx~5.6e-5deg won't contribute to the weighting at all. */
408  double xnorm = 1., ynorm = 1., znorm = 1. / kMuseSpectralSamplingA;
409  if (wcs->iscelsph) {
410  muse_wcs_get_scales(aPixtable->header, &xnorm, &ynorm);
411  xnorm = 1. / xnorm;
412  ynorm = 1. / ynorm;
413  /* need to use the real coordinate offset for celestial spherical */
414  ptxoff = muse_pfits_get_crval(aPixtable->header, 1);
415  ptyoff = muse_pfits_get_crval(aPixtable->header, 2);
416  }
417 
418 #ifdef ESO_ENABLE_DEBUG
419  int debug = 0;
420  if (getenv("MUSE_DEBUG_NEAREST")) {
421  debug = atoi(getenv("MUSE_DEBUG_NEAREST"));
422  }
423 #endif
424 
425  int l;
426 #ifdef ESO_ENABLE_DEBUG
427  #pragma omp parallel for default(none) /* as req. by Ralf */ \
428  shared(aCube, aGrid, cd33, crpix3, crval3, data, debug, dq, lbda, \
429  loglambda, ptxoff, ptyoff, stat, stdout, wcs, xnorm, xpos, \
430  ynorm, ypos, znorm)
431 #else
432  #pragma omp parallel for default(none) /* as req. by Ralf */ \
433  shared(aCube, aGrid, cd33, crpix3, crval3, data, dq, lbda, \
434  loglambda, ptxoff, ptyoff, stat, stdout, wcs, xnorm, xpos, \
435  ynorm, ypos, znorm)
436 #endif
437  for (l = 0; l < aGrid->nz; l++) {
438  float *pdata = cpl_image_get_data_float(cpl_imagelist_get(aCube->data, l)),
439  *pstat = cpl_image_get_data_float(cpl_imagelist_get(aCube->stat, l));
440  int *pdq = cpl_image_get_data_int(cpl_imagelist_get(aCube->dq, l));
441  /* wavelength of center of current grid cell (l is index starting at 0) */
442  double lambda = (l + 1. - crpix3) * cd33 + crval3;
443  if (loglambda) {
444  lambda = crval3 * exp((l + 1. - crpix3) * cd33 / crval3);
445  }
446 
447  int i;
448  for (i = 0; i < aGrid->nx; i++) {
449  int j;
450  for (j = 0; j < aGrid->ny; j++) {
451  cpl_size idx = muse_pixgrid_get_index(aGrid, i, j, l, CPL_FALSE),
452  n_rows = muse_pixgrid_get_count(aGrid, idx);
453  const cpl_size *rows = muse_pixgrid_get_rows(aGrid, idx);
454 
455  /* x and y position of center of current grid cell (i, j start at 0) */
456  double x, y;
457  if (wcs->iscelsph) {
458  muse_wcs_celestial_from_pixel_fast(wcs, i + 1, j + 1, &x, &y);
459  } else {
460  muse_wcs_projplane_from_pixel_fast(wcs, i + 1, j + 1, &x, &y);
461  }
462 
463  if (n_rows == 1) {
464  /* if there is only one pixel in the cell, just use it */
465  pdata[i + j * aGrid->nx] = data[rows[0]];
466  pstat[i + j * aGrid->nx] = stat[rows[0]];
467  pdq[i + j * aGrid->nx] = dq[rows[0]];
468 
469 #ifdef ESO_ENABLE_DEBUG
470  if (debug) {
471  printf("only: %f,%f\n", data[rows[0]], stat[rows[0]]);
472  fflush(stdout);
473  }
474 #endif
475  } else if (n_rows >= 2) {
476  /* loop through all available values and take the closest one */
477  cpl_size n, nbest = -1;
478  double dbest = FLT_MAX; /* some unlikely large value to start with*/
479  for (n = 0; n < n_rows; n++) {
480  /* the differences for the cell center and the current pixel */
481  double dx = fabs(x - xpos[rows[n]] + ptxoff) * xnorm,
482  dy = fabs(y - ypos[rows[n]] + ptyoff) * ynorm,
483  dlambda = fabs(lambda - lbda[rows[n]]) * znorm,
484  dthis = sqrt(dx*dx + dy*dy + dlambda*dlambda);
485  if (wcs->iscelsph) {
486  /* Not strictly necessary for NN, but still scale the RA *
487  * distance properly, see muse_resampling_cube_weighted(). */
488  dx *= cos(y * CPL_MATH_RAD_DEG);
489  }
490 #ifdef ESO_ENABLE_DEBUG
491  if (debug) {
492  printf("%f %f %f, %f %f %f, d: %f %f %f -> %f best: %f (%f,%f)\n",
493  x, y, lambda, xpos[rows[n]] + ptxoff, ypos[rows[n]] + ptyoff,
494  lbda[rows[n]], dx, dy, dlambda, dthis, dbest, data[rows[n]],
495  stat[rows[n]]);
496  }
497 #endif
498  if (dthis < dbest) {
499  nbest = n;
500  dbest = dthis;
501  }
502  }
503  pdata[i + j * aGrid->nx] = data[rows[nbest]];
504  pstat[i + j * aGrid->nx] = stat[rows[nbest]];
505  pdq[i + j * aGrid->nx] = dq[rows[nbest]];
506 #ifdef ESO_ENABLE_DEBUG
507  if (debug) {
508  printf("closest: %f,%f\n", data[rows[nbest]], stat[rows[nbest]]);
509  fflush(stdout);
510  }
511 #endif
512  } else {
513  /* npix == 0: do nothing, pixel stays zero */
514  pdq[i + j * aGrid->nx] = EURO3D_MISSDATA;
515  }
516  } /* for j (y direction) */
517  } /* for i (x direction) */
518  } /* for l (wavelength planes) */
519  cpl_free(wcs);
520 
521  return CPL_ERROR_NONE;
522 } /* muse_resampling_cube_nearest() */
523 
524 /*---------------------------------------------------------------------------*/
545 /*---------------------------------------------------------------------------*/
546 static cpl_error_code
547 muse_resampling_cube_weighted(muse_datacube *aCube, muse_pixtable *aPixtable,
548  muse_pixgrid *aGrid,
549  muse_resampling_params *aParams)
550 {
551  cpl_ensure_code(aCube && aPixtable && aGrid && aParams,
552  CPL_ERROR_NULL_INPUT);
553  double ptxoff = 0., /* zero by default ... */
554  ptyoff = 0., /* for pixel coordinates */
555  crval3 = muse_pfits_get_crval(aCube->header, 3),
556  crpix3 = muse_pfits_get_crpix(aCube->header, 3),
557  cd33 = muse_pfits_get_cd(aCube->header, 3, 3);
558  const char *ctype3 = muse_pfits_get_ctype(aCube->header, 3);
559  muse_wcs *wcs = muse_wcs_new(aCube->header);
561  cpl_boolean loglambda = ctype3 && (!strncmp(ctype3, "AWAV-LOG", 9) ||
562  !strncmp(ctype3, "WAVE-LOG", 9));
563  cpl_errorstate prestate = cpl_errorstate_get();
564  float *xpos = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_XPOS),
565  *ypos = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_YPOS),
566  *lbda = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_LAMBDA),
567  *data = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_DATA),
568  *stat = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_STAT),
569  *wght = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_WEIGHT);
570  if (!cpl_errorstate_is_equal(prestate)) {
571  cpl_errorstate_set(prestate); /* recover from missing weight column */
572  }
573  int *dq = cpl_table_get_data_int(aPixtable->table, MUSE_PIXTABLE_DQ);
574 
575  /* If our data was astrometrically calibrated, we need to scale the *
576  * data units to the pixel size in all three dimensions so that the *
577  * radius computation works again. *
578  * Otherwise dx~5.6e-5deg won't contribute to the weighting at all. */
579  double xnorm = 1., ynorm = 1., znorm = 1. / kMuseSpectralSamplingA;
580  if (wcs->iscelsph) {
581  muse_wcs_get_scales(aPixtable->header, &xnorm, &ynorm);
582  xnorm = 1. / xnorm;
583  ynorm = 1. / ynorm;
584  /* need to use the real coordinate offset for celestial spherical */
585  ptxoff = muse_pfits_get_crval(aPixtable->header, 1);
586  ptyoff = muse_pfits_get_crval(aPixtable->header, 2);
587  }
588  /* precomputed factor for output voxel size calculation in *
589  * wavelength direction, only needed for log-lambda axis */
590  double zoutefac = exp(1.5 * cd33 / crval3) - exp(0.5 * cd33 / crval3);
591  /* scale the input critical radius by the voxel radius */
592  double renka_rc = aParams->rc /* XXX beware of rotation! */
593  * sqrt((wcs->cd11*xnorm)*(wcs->cd11*xnorm) + (wcs->cd22*ynorm)*(wcs->cd22*ynorm)
594  + (cd33*znorm)*(cd33*znorm));
595  /* loop distance (to take into account surrounding pixels) verification */
596  int ld = aParams->ld;
597  if (ld <= 0) {
598  ld = 1;
599  cpl_msg_info(__func__, "Overriding loop distance ld=%d", ld);
600  }
601 
602  /* pixel sizes in all three directions, scaled by pixfrac, and *
603  * output pixel sizes (absolute values), as needed for drizzle */
604  double xsz = aParams->pfx / xnorm,
605  ysz = aParams->pfy / ynorm,
606  zsz = aParams->pfl / znorm,
607  xout = fabs(wcs->cd11), yout = fabs(wcs->cd22), zout = fabs(cd33);
608 
609 #ifdef ESO_ENABLE_DEBUG
610  int debug = 0, debugx = 0, debugy = 0, debugz = 0;
611  if (getenv("MUSE_DEBUG_WEIGHTED")) {
612  debug = atoi(getenv("MUSE_DEBUG_WEIGHTED"));
613  }
614  if (debug & 2) { /* need coordinates */
615  if (getenv("MUSE_DEBUG_WEIGHTED_X")) {
616  debugx = atoi(getenv("MUSE_DEBUG_WEIGHTED_X"));
617  if (debugx < 1 || debugx > aGrid->nx) {
618  debugx = 0;
619  }
620  }
621  if (getenv("MUSE_DEBUG_WEIGHTED_Y")) {
622  debugy = atoi(getenv("MUSE_DEBUG_WEIGHTED_Y"));
623  if (debugy < 1 || debugy > aGrid->ny) {
624  debugy = 0;
625  }
626  }
627  if (getenv("MUSE_DEBUG_WEIGHTED_Z")) {
628  debugz = atoi(getenv("MUSE_DEBUG_WEIGHTED_Z"));
629  if (debugz < 1 || debugz > aGrid->nz) {
630  debugz = 0;
631  }
632  }
633  }
634  if (debug & 8) {
635  printf("parameters:\n cd=%e %e %e\n"
636  " corrected crpix3=%e\n norm=%e %e %e\n",
637  wcs->cd11, wcs->cd22, cd33, crpix3, xnorm, ynorm, znorm);
638  if (aParams->method == MUSE_RESAMPLE_WEIGHTED_DRIZZLE) {
639  printf(" drop sizes %e %e %e (pixfrac %f,%f,%f)\n"
640  " output sizes %e %e %e\n",
641  xsz, ysz, zsz, aParams->pfx, aParams->pfy, aParams->pfl,
642  xout, yout, zout);
643  } else {
644  printf(" resulting renka_rc: %e %e %e / %e %e %e --> %e\n",
645  pow(wcs->cd11, 2), pow(wcs->cd22, 2), cd33*cd33,
646  pow(wcs->cd11*xnorm, 2), pow(wcs->cd22*ynorm, 2),
647  pow(cd33*znorm, 2), renka_rc);
648  }
649  fflush(stdout);
650  }
651 #endif
652  cpl_imagelist *wcube = NULL;
653  if (getenv("MUSE_DEBUG_WEIGHT_CUBE")) { /* create a weight cube */
654  cpl_msg_debug(__func__, "Weighted resampling: creating weight cube");
655  wcube = cpl_imagelist_new();
656  int i;
657  for (i = 0; i < aGrid->nz; i++) {
658  cpl_image *image = cpl_image_new(aGrid->nx, aGrid->ny,
659  CPL_TYPE_FLOAT);
660  cpl_imagelist_set(wcube, image, i);
661  } /* for i (all wavelength planes) */
662  } /* if weight cube */
663 
664  if (getenv("MUSE_DEBUG_WEIGHTED_GRID")) {
665  char *fn = getenv("MUSE_DEBUG_WEIGHTED_GRID");
666  FILE *grid = fopen(fn, "w");
667  if (grid) {
668  cpl_msg_info(__func__, "Writing grid to \"%s\"", fn);
669  fprintf(grid, "# i j l x y lambda\n");
670  int l;
671  for (l = 0; l < aGrid->nz; l++) {
672  double lambda = (l + 1. - crpix3) * cd33 + crval3;
673  int i;
674  for (i = 0; i < aGrid->nx; i++) {
675  int j;
676  for (j = 0; j < aGrid->ny; j++) {
677  /* x and y position of center of current grid cell (i, j start at 0) */
678  double x, y;
679  if (wcs->iscelsph) {
680  muse_wcs_celestial_from_pixel_fast(wcs, i + 1, j + 1, &x, &y);
681  } else {
682  muse_wcs_projplane_from_pixel_fast(wcs, i + 1, j + 1, &x, &y);
683  }
684  fprintf(grid, "%03d %03d %04d %.10f %.10f %8.3f\n", i+1, j+1, l+1,
685  x, y, lambda);
686  } /* for j (y direction) */
687  } /* for i (x direction) */
688  } /* for l (wavelength planes) */
689  fclose(grid);
690  } else {
691  cpl_msg_warning(__func__, "Writing grid to \"%s\" failed!", fn);
692  }
693  } /* if grid output */
694 
695  int l;
696 #ifdef ESO_ENABLE_DEBUG
697  #pragma omp parallel for default(none) /* as req. by Ralf */ \
698  shared(aCube, aParams, aGrid, aPixtable, cd33, crpix3, crval3, data, \
699  debug, debugx, debugy, debugz, dq, lbda, ld, loglambda, \
700  ptxoff, ptyoff, renka_rc, stat, stdout, wcs, wcube, wght, \
701  xnorm, xout, xpos, xsz, ynorm, yout, ypos, ysz, znorm, zout, \
702  zoutefac, zsz)
703 #else
704  #pragma omp parallel for default(none) /* as req. by Ralf */ \
705  shared(aCube, aParams, aGrid, aPixtable, cd33, crpix3, crval3, data, \
706  dq, lbda, ld, loglambda, ptxoff, ptyoff, renka_rc, stat, \
707  stdout, wcs, wcube, wght, xnorm, xout, xpos, xsz, ynorm, yout,\
708  ypos, ysz, znorm, zout, zoutefac, zsz)
709 #endif
710  for (l = 0; l < aGrid->nz; l++) {
711  float *pdata = cpl_image_get_data_float(cpl_imagelist_get(aCube->data, l)),
712  *pstat = cpl_image_get_data_float(cpl_imagelist_get(aCube->stat, l));
713  int *pdq = cpl_image_get_data_int(cpl_imagelist_get(aCube->dq, l));
714  /* wavelength of center of current grid cell (l is index starting at 0) */
715  double lambda = (l + 1. - crpix3) * cd33 + crval3;
716  double zout2 = zout; /* correct the output pixel size for log-lambda */
717  if (loglambda) {
718  lambda = crval3 * exp((l + 1. - crpix3) * cd33 / crval3);
719  zout2 = crval3 * exp((l - crpix3) * cd33 / crval3) * zoutefac;
720  }
721  float *pwcube = NULL;
722  if (wcube) { /* weight cube */
723  pwcube = cpl_image_get_data_float(cpl_imagelist_get(wcube, l));
724  } /* if weight cube */
725 
726  int i;
727  for (i = 0; i < aGrid->nx; i++) {
728  int j;
729  for (j = 0; j < aGrid->ny; j++) {
730  /* x and y position of center of current grid cell (i, j start at 0) */
731  double x, y;
732  if (wcs->iscelsph) {
733  muse_wcs_celestial_from_pixel_fast(wcs, i + 1, j + 1, &x, &y);
734  } else {
735  muse_wcs_projplane_from_pixel_fast(wcs, i + 1, j + 1, &x, &y);
736  }
737  double sumdata = 0, sumstat = 0, sumweight = 0;
738  int npoints = 0;
739 #ifdef ESO_ENABLE_DEBUG
740  cpl_size *pointlist = NULL;
741  double *pointweights = NULL;
742  int npointlist = 0;
743  if (debug & 2 && i+1 == debugx && j+1 == debugy && l+1 == debugz) {
744  pointlist = cpl_calloc(100, sizeof(cpl_size));
745  pointweights = cpl_malloc(100 * sizeof(double));
746  npointlist = 100;
747  }
748 #endif
749 #ifdef ESO_ENABLE_DEBUG
750  if (debug & 1) {
751  printf("cell %d %d %d:\n", i, j, l);
752  }
753 #endif
754  /* loop through surrounding cells and their contained pixels */
755  int i2;
756  for (i2 = i - ld; i2 <= i + ld; i2++) {
757  int j2;
758  for (j2 = j - ld; j2 <= j + ld; j2++) {
759  int l2;
760  for (l2 = l - ld; l2 <= l + ld; l2++) {
761  cpl_size idx2 = muse_pixgrid_get_index(aGrid, i2, j2, l2, CPL_FALSE),
762  n_rows2 = muse_pixgrid_get_count(aGrid, idx2);
763 #ifdef ESO_ENABLE_DEBUG
764  if (debug & 8 && n_rows2 < 1) {
765  printf("%d %d %d / %d %d %d (%"CPL_SIZE_FORMAT"): no rows!\n",
766  i+1, j+1, l+1, i2+1, j2+1, l2+1, idx2);
767  }
768 #endif
769  const cpl_size *rows2 = muse_pixgrid_get_rows(aGrid, idx2);
770  cpl_size n;
771  for (n = 0; n < n_rows2; n++) {
772  if (dq[rows2[n]]) { /* exclude all bad pixels */
773 #ifdef ESO_ENABLE_DEBUG
774  if (debug & 8) {
775  printf("%d %d %d / %d %d %d (%"CPL_SIZE_FORMAT", "
776  "%"CPL_SIZE_FORMAT"): bad!\n",
777  i+1, j+1, l+1, i2+1, j2+1, l2+1, idx2, n);
778  fflush(stdout);
779  }
780 #endif
781  continue;
782  }
783 
784  double dx = fabs(x - (xpos[rows2[n]] + ptxoff)),
785  dy = fabs(y - (ypos[rows2[n]] + ptyoff)),
786  dlambda = fabs(lambda - lbda[rows2[n]]),
787  r2 = 0;
788  if (wcs->iscelsph) {
789  /* Since the distances of RA in degrees get larger the *
790  * closer we get to the celestial pole, we have to *
791  * compensate for that by multiplying the distance in *
792  * RA by cos(delta), to make it comparable to the *
793  * distances in pixels for the differnt kernels below. */
794  dx *= cos(y * CPL_MATH_RAD_DEG);
795  }
796  if (aParams->method != MUSE_RESAMPLE_WEIGHTED_DRIZZLE) {
797  dx *= xnorm;
798  dy *= ynorm;
799  dlambda *= znorm;
800  r2 = dx*dx + dy*dy + dlambda*dlambda;
801  }
802  double weight = 0.;
803  if (aParams->method == MUSE_RESAMPLE_WEIGHTED_RENKA) {
804  weight = muse_resampling_weight_function_renka(sqrt(r2), renka_rc);
805  } else if (aParams->method == MUSE_RESAMPLE_WEIGHTED_DRIZZLE) {
806  weight = muse_resampling_weight_function_drizzle(xsz, ysz, zsz,
807  xout, yout, zout2,
808  dx, dy, dlambda);
809  } else if (aParams->method == MUSE_RESAMPLE_WEIGHTED_LINEAR) {
810  weight = muse_resampling_weight_function_linear(sqrt(r2));
811  } else if (aParams->method == MUSE_RESAMPLE_WEIGHTED_QUADRATIC) {
812  weight = muse_resampling_weight_function_quadratic(r2);
813  } else if (aParams->method == MUSE_RESAMPLE_WEIGHTED_LANCZOS) {
814  weight = muse_resampling_weight_function_lanczos(dx, dy, dlambda, ld);
815  }
816 
817  if (wght) { /* the pixel table does contain weights */
818  /* apply it on top of the weight computed here */
819  weight *= wght[rows2[n]];
820  }
821 #ifdef ESO_ENABLE_DEBUG
822  if (debug & 8) {
823  printf("%d %d %d / %d %d %d (%"CPL_SIZE_FORMAT", %"CPL_SIZE_FORMAT"):"
824  " x %e %e %e %e y %e %e %e %e l %e %e %e %e --> %e %e %e\n",
825  i+1, j+1, l+1, i2+1, j2+1, l2+1, idx2, n,
826  x, xpos[rows2[n]]+ptxoff, fabs(x - (xpos[rows2[n]]+ptxoff)), dx,
827  y, ypos[rows2[n]]+ptyoff, fabs(y - (ypos[rows2[n]]+ptyoff)), dy,
828  lambda, lbda[rows2[n]], fabs(lambda - lbda[rows2[n]]), dlambda,
829  r2, sqrt(r2), weight);
830  fflush(stdout);
831  }
832 #endif
833  sumweight += weight;
834  sumdata += data[rows2[n]] * weight;
835  sumstat += stat[rows2[n]] * weight*weight;
836  npoints++;
837 #ifdef ESO_ENABLE_DEBUG
838  if (debug & 2 && i+1 == debugx && j+1 == debugy && l+1 == debugz) {
839  if (npoints > npointlist) {
840  pointlist = cpl_realloc(pointlist,
841  (npointlist + 100) * sizeof(cpl_size));
842  memset(pointlist + npointlist, 0, 100 * sizeof(cpl_size));
843  pointweights = cpl_realloc(pointweights,
844  (npointlist + 100) * sizeof(double));
845  npointlist += 100;
846  }
847  /* store row number instead of index, because we cannot be zero: */
848  pointlist[npoints-1] = rows2[n] + 1;
849  pointweights[npoints-1] = weight;
850  }
851 
852  if (debug & 4) {
853  cpl_size idx = muse_pixgrid_get_index(aGrid, i, j, l, CPL_FALSE),
854  count = muse_pixgrid_get_count(aGrid, idx);
855  if (count) {
856  printf(" pixel %4d,%4d,%4d (%8"CPL_SIZE_FORMAT"): "
857  "%2"CPL_SIZE_FORMAT" %2"CPL_SIZE_FORMAT" %f %f %f, "
858  " %e -> %e ==> %e %e (%d)\n", i+1, j+1, l+1, idx,
859  n, count, dx, dy, dlambda,
860  data[muse_pixgrid_get_rows(aGrid, idx)[n]],
861  weight, sumweight, sumdata, npoints);
862  }
863  }
864 #endif
865  } /* for n (all pixels in grid cell) */
866  } /* for l2 (lambda direction) */
867  } /* for j2 (y direction) */
868  } /* for i2 (x direction) */
869 
870 #ifdef ESO_ENABLE_DEBUG
871  if (debug & 2 && i+1 == debugx && j+1 == debugy && l+1 == debugz) {
872  printf("cell center (%d, %d, %d): %14.7e %14.7e %9.3f\npixelnumber "
873  "weight ", debugx, debugy, debugz, x, y, lambda);
874  muse_pixtable_dump(aPixtable, 0, 0, 2);
875  int m = -1;
876  while (++m < npointlist && pointlist[m] != 0) {
877  /* access row using row index again instead of stored row number: */
878  printf("%12"CPL_SIZE_FORMAT" %8.5f ", pointlist[m] - 1,
879  pointweights[m]);
880  muse_pixtable_dump(aPixtable, pointlist[m] - 1, 1, 0);
881  }
882  printf("sums: %g %g %g --> %g %g\n", sumdata, sumstat, sumweight,
883  sumdata / sumweight, sumstat / pow(sumweight, 2));
884  cpl_free(pointlist);
885  cpl_free(pointweights);
886  }
887 
888  if (debug & 1 && npoints) {
889  printf(" sumdata: %e %e (%d)", sumdata, sumweight, npoints);
890  }
891 #endif
892 
893  /* if no points were found, we cannot divide by the summed weight *
894  * and don't need to set the output pixel value (it's 0 already), *
895  * only set the relevant Euro3D bad pixel flag */
896  if (!npoints || !isnormal(sumweight)) {
897  pdq[i + j * aGrid->nx] = EURO3D_MISSDATA;
898 #ifdef ESO_ENABLE_DEBUG
899  if (debug & 1) {
900  printf(" -> no points or weird weight\n");
901  }
902 #endif
903  continue;
904  }
905 
906  /* divide results by weight of summed pixels */
907  sumdata /= sumweight;
908  sumstat /= sumweight*sumweight;
909 #ifdef ESO_ENABLE_DEBUG
910  if (debug & 1) {
911  printf(" -> %e (%e)\n", sumdata, sumstat);
912  }
913  if (debug) {
914  fflush(stdout); /* flush the output in any debug case */
915  }
916 #endif
917  pdata[i + j * aGrid->nx] = sumdata;
918  pstat[i + j * aGrid->nx] = sumstat;
919  pdq[i + j * aGrid->nx] = EURO3D_GOODPIXEL; /* now we can mark it as good */
920  if (pwcube) {
921  pwcube[i + j * aGrid->nx] = sumweight;
922  } /* if weight cube */
923  } /* for j (y direction) */
924  } /* for i (x direction) */
925  } /* for l (wavelength planes) */
926  cpl_free(wcs);
927 
928  if (wcube) { /* weight cube */
929  const char *fn = getenv("MUSE_DEBUG_WEIGHT_CUBE");
930  cpl_error_code rc = cpl_imagelist_save(wcube, fn, CPL_TYPE_UNSPECIFIED,
931  NULL, CPL_IO_CREATE);
932  if (rc != CPL_ERROR_NONE) {
933  cpl_msg_warning(__func__, "Failure to save weight cube as \"%s\": %s", fn,
934  cpl_error_get_message());
935  } else {
936  cpl_msg_info(__func__, "Saved weight cube as \"%s\"", fn);
937  }
938  cpl_imagelist_delete(wcube);
939  } /* if weight cube */
940 
941  return CPL_ERROR_NONE;
942 } /* muse_resampling_cube_weighted() */
943 
944 /*---------------------------------------------------------------------------*/
954 /*---------------------------------------------------------------------------*/
955 static cpl_error_code
956 muse_resampling_check_deltas(muse_pixtable *aPixtable,
957  muse_resampling_params *aParams)
958 {
959  cpl_ensure_code(aPixtable && aParams, CPL_ERROR_NULL_INPUT);
960  const char func[] = "muse_resampling_cube"; /* pretend to be in that fct... */
961 
962  /* wavelength direction */
963  if (aParams->dlambda == 0.0) {
964  aParams->dlambda = kMuseSpectralSamplingA;
965  if (aParams->tlambda == MUSE_RESAMPLING_DISP_AWAV_LOG ||
967  aParams->dlambda /= 1.6; /* XXX seems to be a reasonable value... */
968  }
969  }
970 
972  /* if pixel table in pixel units, take a shortcut */
973  if (aParams->dx == 0.0) {
974  aParams->dx = 1.0;
975  }
976  if (aParams->dy == 0.0) {
977  aParams->dy = 1.0;
978  }
979  cpl_msg_debug(func, "steps from parameters: %.2f pix, %.2f pix, %.3f Angstrom",
980  aParams->dx, aParams->dy, aParams->dlambda);
981  return CPL_ERROR_NONE;
982  }
983  if (aParams->dx == 0.0) {
984  aParams->dx = kMuseSpaxelSizeX_WFM / 3600.;
985  if (muse_pfits_get_mode(aPixtable->header) == MUSE_MODE_NFM_AO_N) {
986  aParams->dx = kMuseSpaxelSizeX_NFM / 3600.;
987  }
988  } else {
989  /* convert from arcsec to degrees */
990  aParams->dx /= 3600.;
991  }
992  if (aParams->dy == 0.0) {
993  aParams->dy = kMuseSpaxelSizeY_WFM / 3600.;
994  if (muse_pfits_get_mode(aPixtable->header) == MUSE_MODE_NFM_AO_N) {
995  aParams->dy = kMuseSpaxelSizeY_NFM / 3600.;
996  }
997  } else {
998  /* anything else should be interpreted as arcsec, but we need deg */
999  aParams->dy /= 3600.;
1000  }
1001  cpl_msg_debug(func, "steps from parameters: %f arcsec, %f arcsec, %.3f Angstrom",
1002  aParams->dx * 3600., aParams->dy * 3600., aParams->dlambda);
1003  return CPL_ERROR_NONE;
1004 } /* muse_resampling_check_deltas() */
1005 
1006 /*---------------------------------------------------------------------------*/
1020 /*---------------------------------------------------------------------------*/
1021 static cpl_error_code
1022 muse_resampling_compute_size(muse_pixtable *aPixtable,
1023  muse_resampling_params *aParams,
1024  int *aX, int *aY, int *aZ)
1025 {
1026  cpl_ensure_code(aPixtable && aParams && aX && aY && aZ, CPL_ERROR_NULL_INPUT);
1027  const char func[] = "muse_resampling_cube"; /* pretend to be in that fct... */
1028  double x1, y1, x2, y2;
1029  float xmin = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_XLO),
1030  xmax = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_XHI),
1031  ymin = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_YLO),
1032  ymax = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_YHI);
1033  muse_pixtable_wcs wcstype = muse_pixtable_wcs_check(aPixtable);
1034  if (wcstype == MUSE_PIXTABLE_WCS_CELSPH) {
1035  muse_wcs_projplane_from_celestial(aPixtable->header, xmin, ymin, &x1, &y1);
1036  muse_wcs_projplane_from_celestial(aPixtable->header, xmax, ymax, &x2, &y2);
1037  } else {
1038  muse_wcs_projplane_from_pixel(aPixtable->header, xmin, ymin, &x1, &y1);
1039  muse_wcs_projplane_from_pixel(aPixtable->header, xmax, ymax, &x2, &y2);
1040  }
1041  *aX = lround(fabs(x2 - x1) / aParams->dx) + 1;
1042  *aY = lround(fabs(y2 - y1) / aParams->dy) + 1;
1043  float lmin = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_LLO),
1044  lmax = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_LHI);
1045  *aZ = (int)ceil((lmax - lmin) / aParams->dlambda) + 1;
1046  if (aParams->tlambda == MUSE_RESAMPLING_DISP_AWAV_LOG ||
1047  aParams->tlambda == MUSE_RESAMPLING_DISP_WAVE_LOG) {
1048  *aZ = (int)ceil(lmin / aParams->dlambda * log(lmax / lmin)) + 1;
1049  }
1050  cpl_msg_info(func, "Output cube size %d x %d x %d (fit to data)",
1051  *aX, *aY, *aZ);
1052  return CPL_ERROR_NONE;
1053 } /* muse_resampling_compute_size() */
1054 
1055 /*---------------------------------------------------------------------------*/
1065 /*---------------------------------------------------------------------------*/
1066 static void
1067 muse_resampling_override_size_int(int *aV, const char *aKeyword, int aValue)
1068 {
1069  if (aValue <= 0 || !aV) {
1070  return;
1071  }
1072  const char func[] = "muse_resampling_cube"; /* pretend to be in that fct... */
1073  cpl_msg_info(func, "Overriding %s=%d (was %d)", aKeyword, aValue, *aV);
1074  *aV = aValue;
1075 } /* muse_resampling_override_size_int() */
1076 
1077 /*---------------------------------------------------------------------------*/
1091 /*---------------------------------------------------------------------------*/
1092 static cpl_error_code
1093 muse_resampling_override_size(int *aX, int *aY, int *aZ,
1094  muse_resampling_params *aParams)
1095 {
1096  cpl_ensure_code(aX && aY && aZ && aParams, CPL_ERROR_NULL_INPUT);
1097  if (!aParams->wcs) { /* quietly return */
1098  return CPL_ERROR_NONE;
1099  }
1100  const char func[] = "muse_resampling_cube"; /* pretend to be in that fct... */
1101  /* cube size overrides */
1102  const cpl_array *dims = cpl_wcs_get_image_dims(aParams->wcs);
1103  if (!dims) {
1104  cpl_msg_debug(func, "No dimensions to override were specified");
1105  return CPL_ERROR_NONE;
1106  }
1107  muse_resampling_override_size_int(aX, "NAXIS1", cpl_array_get_int(dims, 0, NULL));
1108  muse_resampling_override_size_int(aY, "NAXIS2", cpl_array_get_int(dims, 1, NULL));
1109  if (cpl_wcs_get_image_naxis(aParams->wcs) >= 3) {
1110  muse_resampling_override_size_int(aZ, "NAXIS3",
1111  cpl_array_get_int(dims, 2, NULL));
1112  }
1113  return CPL_ERROR_NONE;
1114 } /* muse_resampling_override_size() */
1115 
1116 /*---------------------------------------------------------------------------*/
1127 /*---------------------------------------------------------------------------*/
1128 static void
1129 muse_resampling_override_wcs_double(muse_datacube *aCube, const char *aKeyword,
1130  double aValue, int aError)
1131 {
1132  if (aError || !aCube) {
1133  cpl_msg_debug("double", "%s=%#g (%d)", aKeyword, aValue, aError);
1134  return;
1135  }
1136  const char func[] = "muse_resampling_cube"; /* pretend to be in that fct... */
1137  double old = cpl_propertylist_has(aCube->header, aKeyword)
1138  ? cpl_propertylist_get_double(aCube->header, aKeyword) : NAN;
1139  cpl_msg_info(func, "Overriding %s=%#g (was %#g)", aKeyword, aValue, old);
1140  cpl_propertylist_update_double(aCube->header, aKeyword, aValue);
1141  /* Leave the marked that something was overridden, will *
1142  * be evaluated and removed in muse_pixgrid_create()! */
1143  cpl_propertylist_update_bool(aCube->header, "MUSE_RESAMPLING_WCS_OVERRIDDEN",
1144  CPL_TRUE);
1145 } /* muse_resampling_override_wcs_double() */
1146 
1147 /*---------------------------------------------------------------------------*/
1159 /*---------------------------------------------------------------------------*/
1160 static cpl_error_code
1161 muse_resampling_override_wcs(muse_datacube *aCube,
1162  muse_resampling_params *aParams)
1163 {
1164  cpl_ensure_code(aCube && aCube->header && aParams, CPL_ERROR_NULL_INPUT);
1165  if (!aParams->wcs) { /* quietly return */
1166  return CPL_ERROR_NONE;
1167  }
1168  const char func[] = "muse_resampling_cube"; /* pretend to be in that fct... */
1169  const cpl_array *crval = cpl_wcs_get_crval(aParams->wcs),
1170  *crpix = cpl_wcs_get_crpix(aParams->wcs);
1171  const cpl_matrix *cd = cpl_wcs_get_cd(aParams->wcs);
1172  int err = 0;
1173  /* spatial axes overrides */
1174  if (crval) {
1175  muse_resampling_override_wcs_double(aCube, "CRVAL1", cpl_array_get_double(crval, 0, &err), err);
1176  muse_resampling_override_wcs_double(aCube, "CRVAL2", cpl_array_get_double(crval, 1, &err), err);
1177  } else {
1178  cpl_msg_debug(func, "No CRVALj to override were specified");
1179  }
1180  if (crpix) {
1181  muse_resampling_override_wcs_double(aCube, "CRPIX1", cpl_array_get_double(crpix, 0, &err), err);
1182  muse_resampling_override_wcs_double(aCube, "CRPIX2", cpl_array_get_double(crpix, 1, &err), err);
1183  } else {
1184  cpl_msg_debug(func, "No CRPIXi to override were specified");
1185  }
1186  if (cd) {
1187  int naxes = cpl_matrix_get_ncol(cd); /* nrow should be the same */
1188  if (cpl_matrix_get_determinant(cd) == 0.) {
1189  cpl_msg_warning(func, "det(CDi_j) = 0, not overriding CDi_j!");
1190  cd = NULL; /* don't override dispersion direction, either */
1191  } else if (naxes > 2 && (cpl_matrix_get(cd, 0, 2) != 0. ||
1192  cpl_matrix_get(cd, 2, 0) != 0. ||
1193  cpl_matrix_get(cd, 2, 1) != 0. ||
1194  cpl_matrix_get(cd, 1, 2) != 0.)) {
1195  cpl_msg_warning(func, "Axis 3 (dispersion) is not cleanly separated from "
1196  "axes 1 and 2, not overriding CDi_j!");
1197  cd = NULL; /* don't override dispersion direction, either */
1198  } else {
1199  cpl_errorstate es = cpl_errorstate_get();
1200  muse_resampling_override_wcs_double(aCube, "CD1_1", cpl_matrix_get(cd, 0, 0),
1201  !cpl_errorstate_is_equal(es));
1202  es = cpl_errorstate_get();
1203  muse_resampling_override_wcs_double(aCube, "CD1_2", cpl_matrix_get(cd, 0, 1),
1204  !cpl_errorstate_is_equal(es));
1205  es = cpl_errorstate_get();
1206  muse_resampling_override_wcs_double(aCube, "CD2_1", cpl_matrix_get(cd, 1, 0),
1207  !cpl_errorstate_is_equal(es));
1208  es = cpl_errorstate_get();
1209  muse_resampling_override_wcs_double(aCube, "CD2_2", cpl_matrix_get(cd, 1, 1),
1210  !cpl_errorstate_is_equal(es));
1211  }
1212  } else {
1213  cpl_msg_debug(func, "No CDi_j to override were specified");
1214  }
1215  /* wavelength axis overrides; apparently, values originally in Angstrom *
1216  * values are here in meters (no way to check this here, since we cannot *
1217  * access aParams->wcs->wcsptr!), so need to convert them back */
1218  if (cpl_array_get_size(crval) > 2) {
1219  if (crval) {
1220  muse_resampling_override_wcs_double(aCube, "CRVAL3",
1221  cpl_array_get_double(crval, 2, &err) * 1e10, err);
1222  }
1223  if (crpix) {
1224  muse_resampling_override_wcs_double(aCube, "CRPIX3", cpl_array_get_double(crpix, 2, &err), err);
1225  }
1226  if (cd) {
1227  cpl_errorstate es = cpl_errorstate_get();
1228  muse_resampling_override_wcs_double(aCube, "CD3_3", cpl_matrix_get(cd, 2, 2) * 1e10,
1229  !cpl_errorstate_is_equal(es));
1230  }
1231  } /* if 3D */
1232  return CPL_ERROR_NONE;
1233 } /* muse_resampling_override_wcs() */
1234 
1235 /*---------------------------------------------------------------------------*/
1245 /*---------------------------------------------------------------------------*/
1246 static cpl_error_code
1247 muse_resampling_fit_data_to_grid(muse_datacube *aCube, muse_pixtable *aPixtable)
1248 {
1249  cpl_ensure_code(aCube && aPixtable, CPL_ERROR_NULL_INPUT);
1250  const char func[] = "muse_resampling_cube"; /* pretend to be in that fct... */
1251  /* Check if we need to move the spatial zeropoint to fit into the *
1252  * computed grid at all. This is only the case, if the grid was *
1253  * computed automatically, not overridden. */
1254  if (cpl_propertylist_has(aCube->header, "MUSE_RESAMPLING_WCS_OVERRIDDEN") &&
1255  cpl_propertylist_get_bool(aCube->header, "MUSE_RESAMPLING_WCS_OVERRIDDEN")) {
1256  cpl_msg_debug(func, "Output WCS was forced, won't update CRPIX[12]!");
1257  cpl_propertylist_erase(aCube->header, "MUSE_RESAMPLING_WCS_OVERRIDDEN");
1258  return CPL_ERROR_NONE;
1259  }
1260  /* do determine offset of coordinate to the first (1,1) pixel */
1261  double xoff1, yoff1, xoff2, yoff2;
1262  float xlo = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_XLO),
1263  xhi = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_XHI),
1264  ylo = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_YLO),
1265  yhi = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_YHI);
1266  muse_pixtable_wcs wcstype = muse_pixtable_wcs_check(aPixtable);
1267  if (wcstype == MUSE_PIXTABLE_WCS_CELSPH) {
1268  muse_wcs_pixel_from_celestial(aCube->header, xlo, ylo, &xoff1, &yoff1);
1269  muse_wcs_pixel_from_celestial(aCube->header, xhi, yhi, &xoff2, &yoff2);
1270  } else {
1271  muse_wcs_pixel_from_projplane(aCube->header, xlo, ylo, &xoff1, &yoff1);
1272  muse_wcs_pixel_from_projplane(aCube->header, xhi, yhi, &xoff2, &yoff2);
1273  }
1274  /* the actual minimum offset we need depends on the axis-direction, *
1275  * i.e. the sign of CDi_j, so we take the minimum of the result here */
1276  double xoff = fmin(xoff1, xoff2) - 1,
1277  yoff = fmin(yoff1, yoff2) - 1;
1278  if (xoff != 0. || yoff != 0.) {
1279  double crpix1 = muse_pfits_get_crpix(aCube->header, 1),
1280  crpix2 = muse_pfits_get_crpix(aCube->header, 2);
1281  cpl_msg_debug(func, "Updating CRPIX[12]=%#g,%#g (were %#g,%#g)",
1282  crpix1 - xoff, crpix2 - yoff, crpix1, crpix2);
1283  crpix1 -= xoff;
1284  crpix2 -= yoff;
1285  cpl_propertylist_update_double(aCube->header, "CRPIX1", crpix1);
1286  cpl_propertylist_update_double(aCube->header, "CRPIX2", crpix2);
1287  } /* if offsets */
1288  return CPL_ERROR_NONE;
1289 } /* muse_resampling_fit_data_to_grid() */
1290 
1291 /* corresponds to muse_resampling_crstats_type, *
1292  * keep in sync with those values! */
1293 const char *crtypestring[] = {
1294  "IRAF-like",
1295  "average",
1296  "median"
1297 };
1298 
1299 #if _OPENMP >= 201107 /* OpenMP v3.1 needed for "omp atomic read" */
1300 #define OMPATOMICREAD _Pragma("omp atomic read")
1301 #else
1302 /* OpenMP before 3.1 cannot make atomic assignements, so for *
1303  * compilers before GCC 4.7 we keep the risk of a data race */
1304 #define OMPATOMICREAD
1305 #endif
1306 
1307 #define MUSE_RESAMPLING_CRREJECT_COMPUTE_STATS_START \
1308  cpl_size idx = muse_pixgrid_get_index(aGrid, i2, j2, l2, CPL_FALSE), \
1309  nrow = muse_pixgrid_get_count(aGrid, idx), \
1310  irow; \
1311  const cpl_size *rows = muse_pixgrid_get_rows(aGrid, idx); \
1312  for (irow = 0; irow < nrow; irow++) { \
1313  uint32_t dqrow; \
1314  OMPATOMICREAD /* one atomic access to avoid race */ \
1315  dqrow = dq[rows[irow]]; \
1316  if (muse_quality_is_usable(dqrow, badinclude)) { \
1317  /* do nothing */ \
1318  } else if (dqrow) { \
1319  continue; /* exclude all other bad pixels */ \
1320  }
1321 #define MUSE_RESAMPLING_CRREJECT_COMPUTE_STATS_DEBUG \
1322  if (debug & 4 && i+1 == debugx && j+1 == debugy && l+1 == debugz) { \
1323  printf("%s: data / stat (%"CPL_SIZE_FORMAT") = %e / %e\n", \
1324  __func__, npixels+1, data[rows[irow]], stat[rows[irow]]); \
1325  }
1326 #define MUSE_RESAMPLING_CRREJECT_COMPUTE_STATS_END \
1327  if (aType == MUSE_RESAMPLING_CRSTATS_IRAF) { \
1328  /* add the point from the pixel table to the vector */ \
1329  level += data[rows[irow]]; \
1330  dev += stat[rows[irow]]; \
1331  } else { \
1332  /* add the point to the npixels'th column of the image */ \
1333  if (npixels >= sxsize) { \
1334  /* is there no cpl_image_resize()?! */ \
1335  sxsize += MUSE_CRREJECT_MAX_NPIX; \
1336  cpl_image *tmp = cpl_image_new(sxsize, 2, CPL_TYPE_DOUBLE); \
1337  cpl_image_copy(tmp, sdata, 1, 1); \
1338  cpl_image_delete(sdata); \
1339  sdata = tmp; \
1340  vdata = cpl_image_get_data_double(sdata); \
1341  } \
1342  vdata[npixels] = data[rows[irow]]; \
1343  vdata[npixels + sxsize] = stat[rows[irow]]; \
1344  } \
1345  /* increase the index for all methods */ \
1346  npixels++; \
1347  } /* for irow (all pixels in grid cell) */
1348 
1349 /*---------------------------------------------------------------------------*/
1372 /*---------------------------------------------------------------------------*/
1373 static void
1374 muse_resampling_crreject(muse_pixtable *aPixtable, muse_pixgrid *aGrid,
1375  muse_resampling_crstats_type aType, double aSigma)
1376 {
1377  const char *id = "muse_resampling_cube"; /* pretend to be in that function */
1378  if (aType > MUSE_RESAMPLING_CRSTATS_MEDIAN) {
1379  cpl_msg_warning(id, "Unknown type (%u) for cosmic-ray rejection statistics,"
1380  " resetting to \"%s\"", aType,
1381  crtypestring[MUSE_RESAMPLING_CRSTATS_MEDIAN]);
1383  }
1384  cpl_msg_info(id, "Using %s statistics (%.3f sigma level) for cosmic-ray"
1385  " rejection", crtypestring[aType], aSigma);
1386 
1387 #ifdef ESO_ENABLE_DEBUG
1388  int debug = 0, debugx = 0, debugy = 0, debugz = 0;
1389  if (getenv("MUSE_DEBUG_CRREJECT")) {
1390  debug = atoi(getenv("MUSE_DEBUG_CRREJECT"));
1391  }
1392  if (debug & 2) { /* need coordinates */
1393  if (getenv("MUSE_DEBUG_CRREJECT_X")) {
1394  debugx = atoi(getenv("MUSE_DEBUG_CRREJECT_X"));
1395  if (debugx < 1 || debugx > aGrid->nx) {
1396  debugx = 0;
1397  }
1398  }
1399  if (getenv("MUSE_DEBUG_CRREJECT_Y")) {
1400  debugy = atoi(getenv("MUSE_DEBUG_CRREJECT_Y"));
1401  if (debugy < 1 || debugy > aGrid->ny) {
1402  debugy = 0;
1403  }
1404  }
1405  if (getenv("MUSE_DEBUG_CRREJECT_Z")) {
1406  debugz = atoi(getenv("MUSE_DEBUG_CRREJECT_Z"));
1407  if (debugz < 1 || debugz > aGrid->nz) {
1408  debugz = 0;
1409  }
1410  }
1411  }
1412 #endif
1413 
1414  enum dirtype {
1415  DIR_X = 0,
1416  DIR_Y = 1,
1417  DIR_NONE = 2
1418  };
1419  enum dirtype dir = DIR_NONE;
1420  /* XXX also exclude multiple exposures with different POSANG! */
1421  cpl_boolean haswcs = muse_pixtable_wcs_check(aPixtable) == MUSE_PIXTABLE_WCS_CELSPH;
1422  double posang = muse_astro_posangle(aPixtable->header);
1423  const double palimit = 5.;
1424  if (!haswcs || (fabs(posang) < palimit || fabs(fabs(posang) - 180.) < palimit ||
1425  fabs(fabs(posang) - 360.) < palimit)) {
1426  cpl_msg_debug(id, "CR rejection: posang = %f deg --> DIR_X "
1427  "(%s / %s / %s / %s)", posang, haswcs ? "yes": "no",
1428  fabs(posang) < palimit ? "true" : "false",
1429  fabs(fabs(posang) - 180.) < palimit ? "true" : "false",
1430  fabs(fabs(posang) - 360.) < palimit ? "true" : "false");
1431  dir = DIR_X;
1432  } else if (fabs(fabs(posang) - 90.) < palimit ||
1433  fabs(fabs(posang) - 270.) < palimit) {
1434  cpl_msg_debug(id, "CR rejection: posang = %f deg --> DIR_Y "
1435  "(%s / %s / %s)", posang, haswcs ? "yes": "no",
1436  fabs(fabs(posang) - 90.) < palimit ? "true" : "false",
1437  fabs(fabs(posang) - 270.) < palimit ? "true" : "false");
1438  dir = DIR_Y;
1439  } else {
1440  cpl_msg_debug(id, "CR rejection: posang = %f deg --> DIR_NONE "
1441  "(%s / %s / %s / %s / %s / %s)", posang, haswcs ? "yes": "no",
1442  fabs(posang) < palimit ? "true" : "false",
1443  fabs(fabs(posang) - 90.) < palimit ? "true" : "false",
1444  fabs(fabs(posang) - 180.) < palimit ? "true" : "false",
1445  fabs(fabs(posang) - 270.) < palimit ? "true" : "false",
1446  fabs(fabs(posang) - 360.) < palimit ? "true" : "false");
1447  }
1448 
1449  /* pointer access to the relevant pixel table columns */
1450  float *data = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_DATA),
1451  *stat = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_STAT);
1452  int *dq = cpl_table_get_data_int(aPixtable->table, MUSE_PIXTABLE_DQ);
1453 
1454  /* when computing surrounding statistics, include these types of bad pixels */
1455  uint32_t badinclude = EURO3D_COSMICRAY;
1456  int l;
1457 #ifdef ESO_ENABLE_DEBUG
1458  #pragma omp parallel for default(none) /* as req. by Ralf */ \
1459  shared(aGrid, aPixtable, aSigma, badinclude, aType, crtypestring, \
1460  data, debug, debugx, debugy, debugz, dir, dq, id, stat, stdout)
1461 #else
1462  #pragma omp parallel for default(none) /* as req. by Ralf */ \
1463  shared(aGrid, aSigma, aType, badinclude, crtypestring, data, dir, \
1464  dq, id, stat)
1465 #endif
1466  for (l = 0; l < aGrid->nz; l++) {
1467 #define MUSE_CRREJECT_MAX_NPIX 1000 /* XXX compute size dynamically somehow */
1468  int sxsize = MUSE_CRREJECT_MAX_NPIX;
1469  cpl_image *sdata = NULL;
1470  double *vdata = NULL;
1471  if (aType > MUSE_RESAMPLING_CRSTATS_IRAF) {
1472  /* create image for statistics computations */
1473  /* XXX would memset'ting the buffer not be faster? */
1474  sdata = cpl_image_new(sxsize, 2, CPL_TYPE_DOUBLE);
1475  vdata = cpl_image_get_data_double(sdata);
1476  }
1477 
1478  int i;
1479  for (i = 0; i < aGrid->nx; i++) {
1480  int j;
1481  for (j = 0; j < aGrid->ny; j++) {
1482  /* in the IRAF-like case, compute local statistics, i.e. set *
1483  * the variables to zero (mean, and stdev from the variance) */
1484  double level = 0., dev = 0;
1485  /* loop through surrounding cells: compute local statistics */
1486 #define CR_LD 1 /* loop distance for CR rejection statistics */
1487  cpl_size npixels = 0; /* count pixels again, without bad ones */
1488  int i2, j2, l2;
1489  if (dir == DIR_Y) {
1490  for (i2 = i - CR_LD; i2 <= i + CR_LD; i2++) {
1491  int nwidth = CR_LD;
1492  if (i2 == i) {
1493  nwidth = 0; /* don't use neighbors in the same slice */
1494  }
1495  for (j2 = j - nwidth; j2 <= j + nwidth; j2++) {
1496  for (l2 = l - nwidth; l2 <= l + nwidth; l2++) {
1497  MUSE_RESAMPLING_CRREJECT_COMPUTE_STATS_START
1498 #ifdef ESO_ENABLE_DEBUG
1499  MUSE_RESAMPLING_CRREJECT_COMPUTE_STATS_DEBUG
1500 #endif
1501  MUSE_RESAMPLING_CRREJECT_COMPUTE_STATS_END
1502  } /* for l2 (wavelength/z direction) */
1503  } /* for i2 (x direction) */
1504  } /* for j2 (y direction) */
1505  } else {
1506  for (j2 = j - CR_LD; j2 <= j + CR_LD; j2++) {
1507  int nwidth = CR_LD;
1508  if (dir == DIR_X && j2 == j) {
1509  nwidth = 0; /* don't use neighbors in the same slice */
1510  }
1511  for (i2 = i - nwidth; i2 <= i + nwidth; i2++) {
1512  for (l2 = l - nwidth; l2 <= l + nwidth; l2++) {
1513  MUSE_RESAMPLING_CRREJECT_COMPUTE_STATS_START
1514 #ifdef ESO_ENABLE_DEBUG
1515  MUSE_RESAMPLING_CRREJECT_COMPUTE_STATS_DEBUG
1516 #endif
1517  MUSE_RESAMPLING_CRREJECT_COMPUTE_STATS_END
1518  } /* for l2 (wavelength/z direction) */
1519  } /* for i2 (x direction) */
1520  } /* for j2 (y direction) */
1521  } /* else */
1522  /* need at least 3 values to do something sensible */
1523  if (npixels < 3) {
1524  continue;
1525  }
1526  if (aType == MUSE_RESAMPLING_CRSTATS_IRAF) {
1527  level /= npixels; /* local mean value */
1528  dev = sqrt(dev) / npixels; /* local mean sigma value */
1529  } else {
1530  unsigned sflags;
1531  if (aType == MUSE_RESAMPLING_CRSTATS_MEDIAN) {
1532  sflags = CPL_STATS_MEDIAN | CPL_STATS_MAD;
1533  } else {
1534  sflags = CPL_STATS_MEAN | CPL_STATS_STDEV;
1535  }
1536  cpl_stats *sstats = cpl_stats_new_from_image_window(sdata, sflags,
1537  1, 1, npixels, 1);
1538  if (aType == MUSE_RESAMPLING_CRSTATS_MEDIAN) {
1539  level = cpl_stats_get_median(sstats); /* local median value */
1540  dev = cpl_stats_get_mad(sstats); /* local MAD */
1541  } else {
1542  level = cpl_stats_get_mean(sstats); /* local mean value */
1543  dev = cpl_stats_get_stdev(sstats); /* local standard deviation */
1544  }
1545  cpl_stats_delete(sstats);
1546  } /* else (not IRAF) */
1547  double limit = level + aSigma * dev;
1548 #ifdef ESO_ENABLE_DEBUG
1549  if (debug & 2 && i+1 == debugx && j+1 == debugy && l+1 == debugz) {
1550  if (aType == MUSE_RESAMPLING_CRSTATS_IRAF) {
1551  printf("%s: %03d,%03d,%04d: %.3f+/-%.3f (stats), %.3f (limit) (%"
1552  CPL_SIZE_FORMAT" values)\n", __func__, i+1, j+1, l+1, level,
1553  dev, limit, npixels);
1554  } else {
1555  cpl_stats *ssdata = cpl_stats_new_from_image_window(sdata, CPL_STATS_ALL,
1556  1, 1, npixels, 1),
1557  *ssstat = cpl_stats_new_from_image_window(sdata, CPL_STATS_ALL,
1558  1, 2, npixels, 2);
1559  printf("%s: %03d,%03d,%04d: %e +/- %e (%s), %e (limit) (%"CPL_SIZE_FORMAT
1560  " values); data stats:\n", __func__, i+1, j+1, l+1,
1561  level, dev, crtypestring[aType], limit, npixels);
1562  cpl_stats_dump(ssdata, CPL_STATS_ALL, stdout);
1563  printf("%s: variance stats:\n", __func__);
1564  cpl_stats_dump(ssstat, CPL_STATS_ALL, stdout);
1565  fflush(stdout);
1566  cpl_stats_delete(ssdata);
1567  cpl_stats_delete(ssstat);
1568  }
1569  }
1570 #endif
1571 
1572  /* loop through pixels in the central cell: mark cosmic rays */
1573  cpl_size idx = muse_pixgrid_get_index(aGrid, i, j, l, CPL_FALSE),
1574  nrow = muse_pixgrid_get_count(aGrid, idx),
1575  irow;
1576  const cpl_size *rows = muse_pixgrid_get_rows(aGrid, idx);
1577  for (irow = 0; irow < nrow; irow++) {
1578  if (data[rows[irow]] > limit) {
1579  #pragma omp atomic
1580  dq[rows[irow]] |= EURO3D_COSMICRAY;
1581 #ifdef ESO_ENABLE_DEBUG
1582  if (debug & 1 && i+1 == debugx && j+1 == debugy && l+1 == debugz) {
1583  printf("%s: %03d,%03d,%04d: rejected row %"CPL_SIZE_FORMAT" (%"
1584  CPL_SIZE_FORMAT" of %"CPL_SIZE_FORMAT" in this gridcell):\t",
1585  __func__, i+1, j+1, l+1, rows[irow], irow+1, nrow);
1586  muse_pixtable_dump(aPixtable, rows[irow], 1, 0);
1587  }
1588 #endif
1589  }
1590  } /* for irow (all pixels in grid cell) */
1591 #ifdef ESO_ENABLE_DEBUG
1592  if (debug) {
1593  fflush(stdout);
1594  }
1595 #endif
1596  } /* for j (y direction) */
1597  } /* for i (x direction) */
1598  cpl_image_delete(sdata);
1599  } /* for l (wavelength planes) */
1600 } /* muse_resampling_crreject() */
1601 
1602 /*---------------------------------------------------------------------------*/
1625 /*---------------------------------------------------------------------------*/
1628  muse_resampling_params *aParams)
1629 {
1630  cpl_ensure(aParams, CPL_ERROR_NULL_INPUT, NULL);
1631  cpl_ensure(aParams->method < MUSE_RESAMPLE_NONE, CPL_ERROR_ILLEGAL_INPUT, NULL);
1632  /* all other error checking is already done in muse_resampling_cube() */
1633 
1634  /* call the existing resampling routine for datacubes */
1635  muse_datacube *cube = muse_resampling_cube(aPixtable, aParams, NULL);
1636  if (!cube) {
1637  return NULL;
1638  }
1639 
1640  /* create Euro3D object, copy header and set typical Euro3D primary headers */
1641  muse_euro3dcube *e3d = cpl_calloc(1, sizeof(muse_euro3dcube));
1642  e3d->header = cpl_propertylist_duplicate(cube->header);
1643  cpl_propertylist_erase_regexp(e3d->header,
1644  "^SIMPLE$|^BITPIX$|^NAXIS|^EURO3D$|^E3D_",
1645  0);
1646  cpl_propertylist_append_char(e3d->header, "EURO3D", 'T');
1647  cpl_propertylist_set_comment(e3d->header, "EURO3D",
1648  "file conforms to Euro3D standard");
1649  /* E3D_VERS is supposed to be a string! */
1650  cpl_propertylist_append_string(e3d->header, "E3D_VERS", "1.0");
1651  cpl_propertylist_set_comment(e3d->header, "E3D_VERS",
1652  "version number of the Euro3D format");
1653  cpl_errorstate prestate = cpl_errorstate_get();
1654  double darlambdaref = cpl_propertylist_get_double(e3d->header,
1656  if (!cpl_errorstate_is_equal(prestate)) {
1657  darlambdaref = -1.; /* set to negative value to be sure on error */
1658  cpl_errorstate_set(prestate);
1659  }
1660  if (darlambdaref > 0.) {
1661  cpl_propertylist_append_char(e3d->header, "E3D_ADC", 'T');
1662  cpl_propertylist_set_comment(e3d->header, "E3D_ADC",
1663  "data was corrected for atmospheric dispersion");
1664  } else {
1665  cpl_propertylist_append_char(e3d->header, "E3D_ADC", 'F');
1666  cpl_propertylist_set_comment(e3d->header, "E3D_ADC",
1667  "data not corrected for atmospheric dispersion");
1668  }
1669 
1670  /* fill WCS info in data header */
1671  e3d->hdata = cpl_propertylist_new();
1672  cpl_propertylist_append_string(e3d->hdata, "EXTNAME", "E3D_DATA");
1673  cpl_propertylist_set_comment(e3d->hdata, "EXTNAME",
1674  "This is the Euro3D data table extension");
1675  cpl_propertylist_append_string(e3d->hdata, "CTYPES",
1676  muse_pfits_get_ctype(e3d->header, 3));
1677  cpl_propertylist_set_comment(e3d->hdata, "CTYPES",
1678  cpl_propertylist_get_comment(e3d->header, "CTYPE3"));
1679  cpl_propertylist_append_string(e3d->hdata, "CUNITS",
1680  muse_pfits_get_cunit(e3d->header, 3));
1681  cpl_propertylist_set_comment(e3d->hdata, "CUNITS",
1682  cpl_propertylist_get_comment(e3d->header, "CUNIT3"));
1683  cpl_propertylist_append_double(e3d->hdata, "CRVALS",
1684  muse_pfits_get_crval(e3d->header, 3));
1685  cpl_propertylist_set_comment(e3d->hdata, "CRVALS",
1686  cpl_propertylist_get_comment(e3d->header, "CRVAL3"));
1687  cpl_propertylist_append_double(e3d->hdata, "CDELTS",
1688  muse_pfits_get_cd(e3d->header, 3, 3));
1689  cpl_propertylist_set_comment(e3d->hdata, "CDELTS",
1690  cpl_propertylist_get_comment(e3d->header, "CD3_3"));
1691  /* remove WCS for spatial axis from main header */
1692  cpl_propertylist_erase_regexp(e3d->header, "^C...*3$|^CD3_.$", 0);
1693 
1694  /* create and fill Euro3D table structure */
1695  int nx = cpl_image_get_size_x(cpl_imagelist_get(cube->data, 0)),
1696  ny = cpl_image_get_size_y(cpl_imagelist_get(cube->data, 0)),
1697  nz = cpl_imagelist_get_size(cube->data);
1699  /* set array columns to initial (expected) depth */
1700  /* XXX this is very expensive for big tables, we should make *
1701  * muse_cpltable_new() take an extra argument for the depth */
1702  cpl_table_set_column_depth(e3d->dtable, "DATA_SPE", nz);
1703  cpl_table_set_column_depth(e3d->dtable, "QUAL_SPE", nz);
1704  cpl_table_set_column_depth(e3d->dtable, "STAT_SPE", nz);
1705  /* set column units depending on data unit type in the pixel table */
1706  cpl_table_set_column_unit(e3d->dtable, "DATA_SPE",
1707  cpl_table_get_column_unit(aPixtable->table,
1709  cpl_table_set_column_unit(e3d->dtable, "STAT_SPE",
1710  cpl_table_get_column_unit(aPixtable->table,
1712  /* set column save types as needed */
1713  cpl_table_set_column_savetype(e3d->dtable, "SELECTED", CPL_TYPE_BOOL);
1714 
1715  muse_wcs *wcs = muse_wcs_new(cube->header);
1717  if (wcs->iscelsph) { /* if not, then the preset unit of "pix" is valid */
1718  cpl_table_set_column_unit(e3d->dtable, "XPOS", "deg");
1719  cpl_table_set_column_unit(e3d->dtable, "YPOS", "deg");
1720  }
1721 
1722  /* Loop over all spaxels in the cube and transfer the data */
1723  unsigned euro3d_ignore = EURO3D_OUTSDRANGE | EURO3D_MISSDATA;
1724  cpl_vector *vusable = cpl_vector_new(nx * ny); /* for statistics */
1725  int i, itable = 0;
1726  for (i = 1; i <= nx; i++) {
1727  int j;
1728  for (j = 1; j <= ny; j++) {
1729  cpl_array *adata = cpl_array_new(nz, CPL_TYPE_FLOAT),
1730  *adq = cpl_array_new(nz, CPL_TYPE_INT),
1731  *astat = cpl_array_new(nz, CPL_TYPE_FLOAT);
1732  /* WCS coordinates */
1733  double x, y;
1734  if (wcs->iscelsph) {
1735  muse_wcs_celestial_from_pixel_fast(wcs, i, j, &x, &y);
1736  } else {
1737  muse_wcs_projplane_from_pixel_fast(wcs, i, j, &x, &y);
1738  }
1739 
1740  int l, nusable = 0, nstart = -1; /* numbers needed for Euro3D format */
1741  for (l = 0; l < nz; l++) {
1742  int err;
1743  unsigned dq = cpl_image_get(cpl_imagelist_get(cube->dq, l), i, j, &err);
1744  /* check if we can ignore this as bad pixel at the start */
1745  if (nstart < 0 && (dq & euro3d_ignore)) {
1746  continue;
1747  }
1748  cpl_array_set_int(adq, nusable, dq);
1749  cpl_array_set_float(adata, nusable,
1750  cpl_image_get(cpl_imagelist_get(cube->data, l),
1751  i, j, &err));
1752  /* take the square root so that we get errors and not variances */
1753  cpl_array_set_float(astat, nusable,
1754  sqrt(cpl_image_get(cpl_imagelist_get(cube->stat, l),
1755  i, j, &err)));
1756  nusable++;
1757  if (nstart < 0) {
1758  nstart = l + 1;
1759  }
1760  } /* for l (z / wavelengths) */
1761 
1762  cpl_table_set_int(e3d->dtable, "SPEC_ID", itable, itable + 1);
1763  cpl_table_set_int(e3d->dtable, "SPEC_LEN", itable, nusable);
1764  cpl_table_set_int(e3d->dtable, "SPEC_STA", itable, nstart);
1765  cpl_table_set_double(e3d->dtable, "XPOS", itable, x);
1766  cpl_table_set_double(e3d->dtable, "YPOS", itable, y);
1767  /* not sure what to use for SPAX_ID, just leave it unset for now */
1768  /*cpl_table_set_string(e3d->dtable, "SPAX_ID", itable, ""); */
1769  cpl_table_set_array(e3d->dtable, "DATA_SPE", itable, adata);
1770  cpl_table_set_array(e3d->dtable, "QUAL_SPE", itable, adq);
1771  cpl_table_set_array(e3d->dtable, "STAT_SPE", itable, astat);
1772 
1773  cpl_array_delete(adata);
1774  cpl_array_delete(adq);
1775  cpl_array_delete(astat);
1776 
1777  cpl_vector_set(vusable, itable, nusable);
1778  if (nstart != -1 && nusable > 0) {
1779  /* good spectrum, unselect to not remove it below */
1780  cpl_table_unselect_row(e3d->dtable, itable);
1781  }
1782  itable++; /* move to next table row */
1783  } /* for j (y spaxels) */
1784  } /* for i (x spaxels) */
1785  cpl_free(wcs);
1786 
1787  cpl_vector_set_size(vusable, itable);
1788  int maxusable = cpl_vector_get_max(vusable);
1789 #if 0
1790  cpl_msg_debug(__func__, "filled %d of %d spaxels, usable are "
1791  "%f..%f(%f)+/-%f..%d pixels per spectrum", itable, nx * ny,
1792  cpl_vector_get_min(vusable), cpl_vector_get_mean(vusable),
1793  cpl_vector_get_median(vusable), cpl_vector_get_stdev(vusable),
1794  maxusable);
1795 #endif
1796  cpl_msg_debug(__func__, "filled %"CPL_SIZE_FORMAT" of %d spaxels, usable "
1797  "are max. %d of %d pixels per spectrum%s",
1798  itable - cpl_table_count_selected(e3d->dtable), nx * ny,
1799  maxusable, nz, maxusable == nz ? "" : ", cutting table");
1800  if (maxusable != nz) {
1801  /* set array columns to real depth (maximum usable spectral pixels found) */
1802  cpl_table_set_column_depth(e3d->dtable, "DATA_SPE", maxusable);
1803  cpl_table_set_column_depth(e3d->dtable, "QUAL_SPE", maxusable);
1804  cpl_table_set_column_depth(e3d->dtable, "STAT_SPE", maxusable);
1805  }
1806  /* resize table to number of used spaxels */
1807  cpl_table_erase_selected(e3d->dtable); /* erase empty spectra */
1808  cpl_vector_delete(vusable);
1809 
1810  /* fill columns that are the same for all spaxels */
1811  /* by default, all spectra are supposed to be selected */
1812  cpl_table_fill_column_window_int(e3d->dtable, "SELECTED", 0, itable,
1813  1 /* TRUE */);
1814  /* assume that we only used one resolution element */
1815  cpl_table_fill_column_window_int(e3d->dtable, "NSPAX", 0, itable, 1);
1816  /* we have only one group for MUSE */
1817  cpl_table_fill_column_window_int(e3d->dtable, "GROUP_N", 0, itable, 1);
1818 
1819  /* done converting the data, free the datacube */
1820  muse_datacube_delete(cube);
1821 
1822  /* fill info in group table */
1823  e3d->hgroup = cpl_propertylist_new();
1824  cpl_propertylist_append_string(e3d->hgroup, "EXTNAME", "E3D_GRP");
1825  cpl_propertylist_set_comment(e3d->hgroup, "EXTNAME",
1826  "This is the Euro3D group table extension");
1827  e3d->gtable = muse_cpltable_new(muse_euro3dcube_e3d_grp_def, 1); /* single group */
1828  cpl_table_set_int(e3d->gtable, "GROUP_N", 0, 1);
1829  cpl_table_set_string(e3d->gtable, "G_SHAPE", 0, "R"/*ECTANG" ULAR*/);
1830  cpl_table_set_float(e3d->gtable, "G_SIZE1", 0, aParams->dx);
1831  cpl_table_set_float(e3d->gtable, "G_ANGLE", 0, 0.);
1832  cpl_table_set_float(e3d->gtable, "G_SIZE2", 0, aParams->dy);
1833  if (darlambdaref > 0.) {
1834  /* set all properties to NaN as required by the Euro3D specs */
1835  cpl_table_set_float(e3d->gtable, "G_POSWAV", 0, NAN);
1836  cpl_table_set_float(e3d->gtable, "G_AIRMAS", 0, NAN);
1837  cpl_table_set_float(e3d->gtable, "G_PARANG", 0, NAN);
1838  cpl_table_set_float(e3d->gtable, "G_PRESSU", 0, NAN);
1839  cpl_table_set_float(e3d->gtable, "G_TEMPER", 0, NAN);
1840  cpl_table_set_float(e3d->gtable, "G_HUMID", 0, NAN);
1841  } else {
1842  /* because we then don't know any better, use the central MUSE wavelength */
1843  cpl_table_set_float(e3d->gtable, "G_POSWAV", 0,
1844  (kMuseNominalLambdaMin + kMuseNominalLambdaMax) / 2.);
1845  cpl_table_set_float(e3d->gtable, "G_AIRMAS", 0,
1846  muse_astro_airmass(e3d->header));
1847  cpl_table_set_float(e3d->gtable, "G_PARANG", 0,
1848  muse_astro_parangle(e3d->header));
1849  cpl_table_set_float(e3d->gtable, "G_PRESSU", 0,
1851  + muse_pfits_get_pres_start(e3d->header)) / 2.);
1852  cpl_table_set_float(e3d->gtable, "G_TEMPER", 0,
1853  muse_pfits_get_temp(e3d->header) + 273.15);
1854  cpl_table_set_float(e3d->gtable, "G_HUMID", 0,
1855  muse_pfits_get_rhum(e3d->header));
1856  }
1857 
1858  return e3d;
1859 } /* muse_resampling_euro3d() */
1860 
1861 /*---------------------------------------------------------------------------*/
1914 /*---------------------------------------------------------------------------*/
1915 muse_datacube *
1917  muse_pixgrid **aGrid)
1918 {
1919  cpl_ensure(aPixtable && aParams, CPL_ERROR_NULL_INPUT, NULL);
1920  cpl_ensure(muse_pixtable_get_type(aPixtable) == MUSE_PIXTABLE_TYPE_FULL,
1921  CPL_ERROR_ILLEGAL_INPUT, NULL);
1922  muse_pixtable_wcs wcstype = muse_pixtable_wcs_check(aPixtable);
1923  cpl_ensure(wcstype == MUSE_PIXTABLE_WCS_CELSPH ||
1924  wcstype == MUSE_PIXTABLE_WCS_PIXEL, CPL_ERROR_UNSUPPORTED_MODE,
1925  NULL);
1926 
1927  /* compute or set the size of the output grid depending on *
1928  * the inputs and the data available in the pixel table */
1929  muse_resampling_check_deltas(aPixtable, aParams);
1930  /* compute output sizes; wavelength is different in that it is *
1931  * more useful to contain partly empty areas within the field *
1932  * for the extreme ends, so use ceil() */
1933  int xsize = 0, ysize = 0, zsize = 0;
1934  muse_resampling_compute_size(aPixtable, aParams, &xsize, &ysize, &zsize);
1935  muse_resampling_override_size(&xsize, &ysize, &zsize, aParams);
1936  cpl_ensure(xsize > 0 && ysize > 0 && zsize > 0, CPL_ERROR_ILLEGAL_OUTPUT,
1937  NULL);
1938 
1939  double time = cpl_test_get_walltime();
1940 
1941  /* create the structure for the output datacube */
1942  muse_datacube *cube = cpl_calloc(1, sizeof(muse_datacube));
1943 
1944  /* copy and clean up incoming FITS headers */
1945  cube->header = cpl_propertylist_duplicate(aPixtable->header);
1946  cpl_propertylist_erase_regexp(cube->header,
1947  "^SIMPLE$|^BITPIX$|^NAXIS|^EXTEND$|^XTENSION$|"
1948  "^DATASUM$|^DATAMIN$|^DATAMAX$|^DATAMD5$|"
1949  "^PCOUNT$|^GCOUNT$|^HDUVERS$|^BLANK$|"
1950  "^BZERO$|^BSCALE$|^CHECKSUM$|^INHERIT$|"
1951  "^EXTNAME$|"MUSE_WCS_KEYS"|"MUSE_HDR_PT_REGEXP,
1952  0);
1953  /* set data unit depending on data unit type in the pixel table */
1954  cpl_propertylist_update_string(cube->header, "BUNIT",
1955  cpl_table_get_column_unit(aPixtable->table,
1957  /* set NAXIS for later handling of the WCS */
1958  cpl_propertylist_update_int(cube->header, "NAXIS", 3);
1959  cpl_propertylist_update_int(cube->header, "NAXIS1", xsize);
1960  cpl_propertylist_update_int(cube->header, "NAXIS2", ysize);
1961  cpl_propertylist_update_int(cube->header, "NAXIS3", zsize);
1962  /* if pixel table was astrometrically calibrated, use its WCS headers *
1963  * Axis 1: x or RA, axis 2: y or DEC, axis 3: lambda */
1964  if (wcstype == MUSE_PIXTABLE_WCS_CELSPH) {
1965  cpl_propertylist_copy_property_regexp(cube->header, aPixtable->header,
1966  MUSE_WCS_KEYS, 0);
1967  cpl_propertylist_update_double(cube->header, "CD1_1", -aParams->dx);
1968  cpl_propertylist_update_double(cube->header, "CD2_2", aParams->dy);
1969  cpl_propertylist_update_double(cube->header, "CD1_2", 0.);
1970  cpl_propertylist_update_double(cube->header, "CD2_1", 0.);
1971  /* correct CRPIX by the central pixel coordinate */
1972  cpl_propertylist_update_double(cube->header, "CRPIX1",
1973  muse_pfits_get_crpix(cube->header, 1)
1974  + (1. + xsize) / 2.);
1975  cpl_propertylist_update_double(cube->header, "CRPIX2",
1976  muse_pfits_get_crpix(cube->header, 2)
1977  + (1. + ysize) / 2.);
1978  /* the pixel table had WCSAXES=2 which should not be propagated to the cube! */
1979  cpl_propertylist_erase(cube->header, "WCSAXES");
1980  } else {
1981  /* add basic WCS headers that are also required by the functions below. */
1982  cpl_propertylist_append_double(cube->header, "CRPIX1", 1.);
1983  cpl_propertylist_append_double(cube->header, "CRVAL1",
1984  cpl_propertylist_get_float(aPixtable->header,
1985  MUSE_HDR_PT_XLO));
1986  /* for linear axes CTYPE doesn't matter, as long as it's not in 4-3 form, *
1987  * see Greisen & Calabretta 2002 A&A 395, 1061 */
1988  cpl_propertylist_append_string(cube->header, "CTYPE1", "PIXEL");
1989  cpl_propertylist_append_string(cube->header, "CUNIT1", "pixel");
1990  cpl_propertylist_append_double(cube->header, "CD1_1", aParams->dx);
1991  cpl_propertylist_append_double(cube->header, "CRPIX2", 1.);
1992  cpl_propertylist_append_double(cube->header, "CRVAL2",
1993  cpl_propertylist_get_float(aPixtable->header,
1994  MUSE_HDR_PT_YLO));
1995  cpl_propertylist_append_string(cube->header, "CTYPE2", "PIXEL");
1996  cpl_propertylist_append_string(cube->header, "CUNIT2", "pixel");
1997  cpl_propertylist_append_double(cube->header, "CD2_2", aParams->dy);
1998  /* fill in empty cross-terms of the CDi_j matrix */
1999  cpl_propertylist_append_double(cube->header, "CD1_2", 0.);
2000  cpl_propertylist_append_double(cube->header, "CD2_1", 0.);
2001  }
2002  switch (aParams->tlambda) {
2004  cpl_propertylist_append_string(cube->header, "CTYPE3", "AWAV");
2005  break;
2007  cpl_propertylist_append_string(cube->header, "CTYPE3", "AWAV-LOG");
2008  break;
2010  cpl_propertylist_append_string(cube->header, "CTYPE3", "WAVE");
2011  break;
2013  cpl_propertylist_append_string(cube->header, "CTYPE3", "WAVE-LOG");
2014  break;
2015  default:
2016  cpl_propertylist_append_string(cube->header, "CTYPE3", "UNKNOWN");
2017  } /* switch */
2018  cpl_propertylist_append_string(cube->header, "CUNIT3", "Angstrom");
2019  cpl_propertylist_append_double(cube->header, "CD3_3", aParams->dlambda);
2020  cpl_propertylist_append_double(cube->header, "CRPIX3", 1.);
2021  cpl_propertylist_append_double(cube->header, "CRVAL3",
2022  cpl_propertylist_get_float(aPixtable->header,
2023  MUSE_HDR_PT_LLO));
2024  /* fill in empty cross-terms of the CDi_j matrix */
2025  cpl_propertylist_append_double(cube->header, "CD1_3", 0.);
2026  cpl_propertylist_append_double(cube->header, "CD2_3", 0.);
2027  cpl_propertylist_append_double(cube->header, "CD3_1", 0.);
2028  cpl_propertylist_append_double(cube->header, "CD3_2", 0.);
2029  /* transfer flat-spectrum correction status */
2030  if (cpl_propertylist_has(aPixtable->header, MUSE_HDR_PT_FFCORR)) {
2031  cpl_propertylist_append_bool(cube->header, MUSE_HDR_FLUX_FFCORR, CPL_TRUE);
2032  cpl_propertylist_set_comment(cube->header, MUSE_HDR_FLUX_FFCORR,
2033  MUSE_HDR_FLUX_FFCORR_C);
2034  }
2035  /* after everything has been transferred from the pixel table headers, *
2036  * see if we want to override anything from an OUTPUT_WCS setup */
2037  muse_resampling_override_wcs(cube, aParams);
2038  /* check, if we need to move the zeropoint to fit the data into the grid */
2039  muse_resampling_fit_data_to_grid(cube, aPixtable);
2040 
2041  if (aParams->method < MUSE_RESAMPLE_NONE) {
2042  /* fill the cube for the data */
2043  cube->data = cpl_imagelist_new();
2044  cube->dq = cpl_imagelist_new();
2045  cube->stat = cpl_imagelist_new();
2046  int i;
2047  for (i = 0; i < zsize; i++) {
2048  cpl_image *image = cpl_image_new(xsize, ysize, CPL_TYPE_FLOAT);
2049  /* set as last image in the list to extend the list size by one */
2050  cpl_imagelist_set(cube->data, image, i);
2051  /* can use the same (empty) image for the variance for now */
2052  cpl_imagelist_set(cube->stat, cpl_image_duplicate(image), i);
2053 
2054  /* the other two are part of their lists now, we can reuse *
2055  * the variable without leaking */
2056  image = cpl_image_new(xsize, ysize, CPL_TYPE_INT);
2057  /* pre-fill with Euro3D status for outside data range */
2058  cpl_image_add_scalar(image, EURO3D_OUTSDRANGE);
2059  cpl_imagelist_set(cube->dq, image, i);
2060  } /* for i (all wavelength planes) */
2061  } /* if method not MUSE_RESAMPLE_NONE */
2062 
2063  muse_utils_memory_dump("muse_resampling_cube() before pixgrid");
2064  /* convert the pixel table into a pixel grid */
2065  muse_pixgrid *grid = muse_pixgrid_create(aPixtable, cube->header,
2066  xsize, ysize, zsize);
2067  if (!grid) {
2068  muse_datacube_delete(cube);
2069  cpl_error_set_message(__func__, CPL_ERROR_DATA_NOT_FOUND, "Could not create"
2070  " pixel grid!");
2071  if (aGrid) {
2072  *aGrid = NULL;
2073  }
2074  return NULL;
2075  } /* if not grid */
2076 
2077  if (aParams->crsigma > 0) {
2078  muse_resampling_crreject(aPixtable, grid, aParams->crtype,
2079  aParams->crsigma);
2080  }
2081  muse_utils_memory_dump("muse_resampling_cube() after pixgrid and crreject");
2082 
2083  double timeinit = cpl_test_get_walltime(),
2084  cpuinit = cpl_test_get_cputime();
2085 
2086  /* do the resampling */
2087  cpl_error_code rc = CPL_ERROR_NONE;
2088  switch (aParams->method) {
2089  case MUSE_RESAMPLE_NEAREST:
2090  cpl_msg_info(__func__, "Starting resampling, using method \"nearest\"");
2091  rc = muse_resampling_cube_nearest(cube, aPixtable, grid);
2092  break;
2094  cpl_msg_info(__func__, "Starting resampling, using method \"renka\" "
2095  "(critical radius rc=%f, loop distance ld=%d)", aParams->rc,
2096  aParams->ld);
2097  rc = muse_resampling_cube_weighted(cube, aPixtable, grid, aParams);
2098  break;
2102  cpl_msg_info(__func__, "Starting resampling, using method \"%s\" (loop "
2103  "distance ld=%d)",
2105  ? "linear"
2107  ? "quadratic"
2108  : "lanczos"),
2109  aParams->ld);
2110  rc = muse_resampling_cube_weighted(cube, aPixtable, grid, aParams);
2111  break;
2113  cpl_msg_info(__func__, "Starting resampling, using method \"drizzle\" "
2114  "(pixfrac f=%.3f,%.3f,%.3f, loop distance ld=%d)",
2115  aParams->pfx, aParams->pfy, aParams->pfl, aParams->ld);
2116  rc = muse_resampling_cube_weighted(cube, aPixtable, grid, aParams);
2117  break;
2118  case MUSE_RESAMPLE_NONE:
2119  cpl_msg_debug(__func__, "Method %d (no resampling)", aParams->method);
2120  break;
2121  default:
2122  cpl_msg_error(__func__, "Don't know this resampling method: %d",
2123  aParams->method);
2124  cpl_error_set(__func__, CPL_ERROR_UNSUPPORTED_MODE);
2125  rc = CPL_ERROR_UNSUPPORTED_MODE;
2126  }
2127  muse_utils_memory_dump("muse_resampling_cube() after resampling");
2128 
2129  double timefini = cpl_test_get_walltime(),
2130  cpufini = cpl_test_get_cputime();
2131 
2132  /* now that we have resampled we can either remove the pixel grid or save it */
2133  if (aGrid) {
2134  *aGrid = grid;
2135  } else {
2136  muse_pixgrid_delete(grid);
2137  }
2138 
2139  cpl_msg_debug(__func__, "resampling took %.3fs (wall-clock) and %.3fs "
2140  "(%.3fs CPU, %d CPUs) for muse_resampling_cube*() alone",
2141  timefini - time, timefini - timeinit, cpufini - cpuinit,
2142  omp_get_max_threads());
2143  if (rc != CPL_ERROR_NONE) {
2144  cpl_msg_error(__func__, "resampling failed: %s", cpl_error_get_message());
2145  muse_datacube_delete(cube);
2146  return NULL;
2147  }
2148 
2149  muse_utils_memory_dump("muse_resampling_cube() end");
2150  return cube;
2151 } /* muse_resampling_cube() */
2152 
2153 /*---------------------------------------------------------------------------*/
2183 /*---------------------------------------------------------------------------*/
2184 muse_image *
2186  muse_datacube *aCube, const muse_table *aFilter,
2187  muse_resampling_params *aParams)
2188 {
2189  cpl_ensure(aPixtable && aPixtable->table && aGrid && aParams &&
2190  aCube && aCube->header, CPL_ERROR_NULL_INPUT, NULL);
2191  cpl_ensure(aParams->method < MUSE_RESAMPLE_NONE &&
2192  aParams->method > MUSE_RESAMPLE_NEAREST, CPL_ERROR_ILLEGAL_INPUT,
2193  NULL);
2194 
2195  muse_wcs *wcs = muse_wcs_new(aCube->header);
2197  cpl_errorstate prestate = cpl_errorstate_get();
2198  float *xpos = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_XPOS),
2199  *ypos = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_YPOS),
2200  *lbda = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_LAMBDA),
2201  *data = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_DATA),
2202  *stat = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_STAT),
2203  *wght = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_WEIGHT);
2204  if (!cpl_errorstate_is_equal(prestate)) {
2205  cpl_errorstate_set(prestate); /* recover from missing weight column */
2206  }
2207  int *dq = cpl_table_get_data_int(aPixtable->table, MUSE_PIXTABLE_DQ);
2208 
2209  /* If our data was astrometrically calibrated, we need to scale the *
2210  * data units to the pixel size in all three dimensions so that the *
2211  * radius computation works again. *
2212  * Otherwise dx~5.6e-5deg won't contribute to the weighting at all. */
2213  double xnorm = 1., ynorm = 1.,
2214  ptxoff = 0., /* zero by default ... */
2215  ptyoff = 0.; /* for pixel coordinates */
2216  if (wcs->iscelsph) {
2217  muse_wcs_get_scales(aPixtable->header, &xnorm, &ynorm);
2218  xnorm = 1. / xnorm;
2219  ynorm = 1. / ynorm;
2220  /* need to use the real coordinate offset for celestial spherical */
2221  ptxoff = muse_pfits_get_crval(aPixtable->header, 1);
2222  ptyoff = muse_pfits_get_crval(aPixtable->header, 2);
2223  }
2224  /* scale the input critical radius by the voxel radius */
2225  double renka_rc = aParams->rc /* XXX beware of rotation! */
2226  * sqrt(pow(wcs->cd11*xnorm, 2) + pow(wcs->cd22*xnorm, 2));
2227  /* loop distance (to take into account surrounding pixels) verification */
2228  int ld = aParams->ld;
2229  if (ld <= 0) {
2230  ld = 1;
2231  cpl_msg_info(__func__, "Overriding loop distance ld=%d", ld);
2232  }
2233  /* pixel sizes in the spatial directions, scaled by pixfrac, and *
2234  * output pixel sizes (absolute values), as needed for drizzle */
2235  double xsz = aParams->pfx / xnorm,
2236  ysz = aParams->pfy / ynorm,
2237  xout = fabs(wcs->cd11), yout = fabs(wcs->cd22);
2238 
2239  muse_image *image = muse_image_new();
2240  image->data = cpl_image_new(aGrid->nx, aGrid->ny, CPL_TYPE_FLOAT);
2241  image->dq = cpl_image_new(aGrid->nx, aGrid->ny, CPL_TYPE_INT);
2242  image->stat = cpl_image_new(aGrid->nx, aGrid->ny, CPL_TYPE_FLOAT);
2243  image->header = cpl_propertylist_duplicate(aCube->header);
2244  cpl_propertylist_erase_regexp(image->header, "^C...*3$|^CD3_.$", 0);
2245  float *pdata = cpl_image_get_data_float(image->data),
2246  *pstat = cpl_image_get_data_float(image->stat);
2247  int *pdq = cpl_image_get_data_int(image->dq);
2248 
2249  /* check if we need to use the variance for weighting */
2250  cpl_boolean usevariance = CPL_FALSE;
2251  if (getenv("MUSE_COLLAPSE_USE_VARIANCE") &&
2252  atoi(getenv("MUSE_COLLAPSE_USE_VARIANCE")) > 0) {
2253  usevariance = CPL_TRUE;
2254  }
2255 
2256  /* find filter range and coverage fraction */
2257  cpl_table *filter = aFilter && aFilter->table ? aFilter->table : NULL;
2258  double lmin, lmax;
2259  if (filter) {
2260  const double *flbda = cpl_table_get_data_double_const(filter, "lambda"),
2261  *fresp = cpl_table_get_data_double_const(filter, "throughput");
2262  int l = 0, nl = cpl_table_get_nrow(filter);
2263  while (l < nl && fabs(fresp[l]) < DBL_EPSILON) {
2264  lmin = flbda[l++];
2265  }
2266  l = nl - 1;
2267  while (l > 0 && fabs(fresp[l]) < DBL_EPSILON) {
2268  lmax = flbda[l--];
2269  }
2270  cpl_msg_debug(__func__, "filter wavelength range %.1f..%.1fA", lmin, lmax);
2271  /* compute filter coverage and propagate filter properties */
2272  double ffraction = muse_utils_filter_fraction(aFilter, lmin, lmax);
2273  muse_utils_filter_copy_properties(image->header, aFilter, ffraction);
2274  } else {
2275  lmin = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_LLO);
2276  lmax = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_LHI);
2277  cpl_msg_debug(__func__, "full wavelength range %.1f..%.1fA", lmin, lmax);
2278  }
2279 
2280  int i;
2281  #pragma omp parallel for default(none) /* as req. by Ralf */ \
2282  shared(aParams, aGrid, data, dq, filter, lbda, ld, lmax, lmin, pdata,\
2283  pdq, pstat, ptxoff, ptyoff, renka_rc, stat, usevariance, wcs, \
2284  wght, xnorm, xout, xpos, xsz, ynorm, yout, ypos, ysz)
2285  for (i = 0; i < aGrid->nx; i++) {
2286  int j;
2287  for (j = 0; j < aGrid->ny; j++) {
2288  /* x and y position of center of current grid cell (i, j start at 0) */
2289  double x, y;
2290  if (wcs->iscelsph) {
2291  muse_wcs_celestial_from_pixel_fast(wcs, i + 1, j + 1, &x, &y);
2292  } else {
2293  muse_wcs_projplane_from_pixel_fast(wcs, i + 1, j + 1, &x, &y);
2294  }
2295  double sumdata = 0, sumstat = 0, sumweight = 0;
2296  cpl_size npoints = 0;
2297 
2298  /* loop through surrounding cells and their contained pixels */
2299  int i2;
2300  for (i2 = i - ld; i2 <= i + ld; i2++) {
2301  int j2;
2302  for (j2 = j - ld; j2 <= j + ld; j2++) {
2303  /* loop over full wavelength range! */
2304  int l2;
2305  for (l2 = 0; l2 < aGrid->nz; l2++) {
2306  cpl_size idx2 = muse_pixgrid_get_index(aGrid, i2, j2, l2, CPL_FALSE),
2307  n, n_rows2 = muse_pixgrid_get_count(aGrid, idx2);
2308  const cpl_size *rows2 = muse_pixgrid_get_rows(aGrid, idx2);
2309  for (n = 0; n < n_rows2; n++) {
2310  if (dq[rows2[n]]) { /* exclude all bad pixels */
2311  continue;
2312  }
2313  if (usevariance && !isnormal(stat[rows2[n]])) {
2314  continue; /* weighting by inv. variance doesn`t work with extremes */
2315  }
2316  if (lbda[rows2[n]] > lmax || lbda[rows2[n]] < lmin) {
2317  continue; /* exclude pixels outside the filter range */
2318  }
2319 
2320  double dx = fabs(x - (xpos[rows2[n]] + ptxoff)),
2321  dy = fabs(y - (ypos[rows2[n]] + ptyoff)),
2322  r2 = 0;
2323  if (wcs->iscelsph) {
2324  /* Make the RA distance comparable to pixel *
2325  * sizes, see muse_resampling_cube_weighted(). */
2326  dx *= cos(y * CPL_MATH_RAD_DEG);
2327  }
2328  if (aParams->method != MUSE_RESAMPLE_WEIGHTED_DRIZZLE) {
2329  dx *= xnorm;
2330  dy *= ynorm;
2331  r2 = dx*dx + dy*dy;
2332  }
2333  double weight = 0.;
2334  if (aParams->method == MUSE_RESAMPLE_WEIGHTED_RENKA) {
2335  weight = muse_resampling_weight_function_renka(sqrt(r2), renka_rc);
2336  } else if (aParams->method == MUSE_RESAMPLE_WEIGHTED_DRIZZLE) {
2337  weight = muse_resampling_weight_function_drizzle(xsz, ysz, 1.,
2338  xout, yout, 1.,
2339  dx, dy, 0.);
2340  } else if (aParams->method == MUSE_RESAMPLE_WEIGHTED_LINEAR) {
2341  weight = muse_resampling_weight_function_linear(sqrt(r2));
2342  } else if (aParams->method == MUSE_RESAMPLE_WEIGHTED_QUADRATIC) {
2343  weight = muse_resampling_weight_function_quadratic(r2);
2344  } else if (aParams->method == MUSE_RESAMPLE_WEIGHTED_LANCZOS) {
2345  weight = muse_resampling_weight_function_lanczos(dx, dy, 0., ld);
2346  }
2347 
2348  if (wght) { /* the pixel table does contain weights */
2349  /* apply it on top of the weight computed here */
2350  weight *= wght[rows2[n]];
2351  }
2352  /* apply the filter curve on top of the weights, if a filter *
2353  * was given; otherwise the weight stays unchanged */
2354  if (filter) {
2355  weight *= muse_flux_response_interpolate(filter, lbda[rows2[n]],
2356  NULL, MUSE_FLUX_RESP_FILTER);
2357  }
2358  if (usevariance) { /* weight by inverse variance */
2359  weight /= stat[rows2[n]];
2360  }
2361  sumweight += weight;
2362  sumdata += data[rows2[n]] * weight;
2363  sumstat += stat[rows2[n]] * weight*weight;
2364  npoints++;
2365  } /* for n (all pixels in grid cell) */
2366  } /* for l2 (lambda direction) */
2367  } /* for j2 (y direction) */
2368  } /* for i2 (x direction) */
2369 
2370  /* if no points were found, we cannot divide by the summed weight *
2371  * and don't need to set the output pixel value (it's 0 already), *
2372  * only set the relevant Euro3D bad pixel flag */
2373  if (!npoints || !isnormal(sumweight)) {
2374  pdq[i + j * aGrid->nx] = EURO3D_MISSDATA;
2375  continue;
2376  }
2377 
2378  /* divide results by weight of summed pixels */
2379  sumdata /= sumweight;
2380  sumstat /= sumweight*sumweight;
2381  pdata[i + j * aGrid->nx] = sumdata;
2382  pstat[i + j * aGrid->nx] = sumstat;
2383  pdq[i + j * aGrid->nx] = EURO3D_GOODPIXEL; /* now we can mark it as good */
2384  } /* for j (y direction) */
2385  } /* for i (x direction) */
2386  cpl_free(wcs);
2387 
2388  return image;
2389 } /* muse_resampling_collapse_pixgrid() */
2390 
2391 
2392 /*----------------------------------------------------------------------------*
2393  * Resampling and collapsing in 2D *
2394  *----------------------------------------------------------------------------*/
2395 
2396 /*---------------------------------------------------------------------------*/
2412 /*---------------------------------------------------------------------------*/
2413 static cpl_error_code
2414 muse_resampling_image_nearest(muse_image *aImage, muse_pixtable *aPixtable,
2415  muse_pixgrid *aGrid)
2416 {
2417  cpl_ensure_code(aImage && aPixtable && aGrid, CPL_ERROR_NULL_INPUT);
2418  aImage->data = cpl_image_new(aGrid->nx, aGrid->nz,
2419  CPL_TYPE_FLOAT);
2420 
2421  double crval2 = muse_pfits_get_crval(aImage->header, 2),
2422  cd22 = muse_pfits_get_cd(aImage->header, 2, 2);
2423  /* get all (relevant) table columns for easy pointer access */
2424  float *lbda = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_LAMBDA),
2425  *data = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_DATA);
2426  int *dq = cpl_table_get_data_int(aPixtable->table, MUSE_PIXTABLE_DQ);
2427  float *imagedata = cpl_image_get_data_float(aImage->data);
2428 
2429 #ifdef ESO_ENABLE_DEBUG
2430  int debug = 0;
2431  if (getenv("MUSE_DEBUG_NEAREST")) {
2432  debug = atoi(getenv("MUSE_DEBUG_NEAREST"));
2433  }
2434 #endif
2435 
2436  int i;
2437  for (i = 0; i < aGrid->nx; i++) {
2438  int j;
2439  for (j = 0; j < aGrid->nz; j++) {
2440  cpl_size idx = muse_pixgrid_get_index(aGrid, i, 0, j, CPL_FALSE),
2441  n_rows = muse_pixgrid_get_count(aGrid, idx);
2442  const cpl_size *rows = muse_pixgrid_get_rows(aGrid, idx);
2443  if (n_rows == 1 && !dq[rows[0]]) {
2444  /* if there is only one (good) pixel in the cell, just use it */
2445  imagedata[i + j * aGrid->nx] = data[rows[0]];
2446 #ifdef ESO_ENABLE_DEBUG
2447  if (debug) {
2448  printf("only: %f\n", data[rows[0]]);
2449  fflush(stdout);
2450  }
2451 #endif
2452  } else if (n_rows >= 2) {
2453  /* loop through all available values and take the closest one */
2454  cpl_size n, nbest = -1;
2455  double dbest = FLT_MAX; /* some unlikely large value to start with*/
2456  for (n = 0; n < n_rows; n++) {
2457  if (dq[rows[n]]) { /* exclude all bad pixels */
2458  continue;
2459  }
2460  /* the differences for the cell center and the current pixel; *
2461  * for simplicitly, just compare the difference in lambda */
2462  double dlambda = fabs(j * cd22 + crval2 - lbda[rows[n]]);
2463 #ifdef ESO_ENABLE_DEBUG
2464  if (debug) {
2465  printf("%f, %f, d: %f best: %f (%f)\n",
2466  j * cd22 + crval2, lbda[rows[n]],
2467  dlambda, dbest, data[rows[n]]);
2468  }
2469 #endif
2470  if (dlambda < dbest) {
2471  nbest = n;
2472  dbest = dlambda;
2473  }
2474  }
2475  imagedata[i + j * aGrid->nx] = data[rows[nbest]];
2476 #ifdef ESO_ENABLE_DEBUG
2477  if (debug) {
2478  printf("closest: %f\n", data[rows[nbest]]);
2479  fflush(stdout);
2480  }
2481 #endif
2482  } else {
2483  /* npix == 0: do nothing, pixel stays zero */
2484  }
2485  } /* for j (y direction = wavelength planes) */
2486  } /* for i (x direction) */
2487 
2488  return CPL_ERROR_NONE;
2489 } /* muse_resampling_image_nearest() */
2490 
2491 /*---------------------------------------------------------------------------*/
2508 /*---------------------------------------------------------------------------*/
2509 static cpl_error_code
2510 muse_resampling_image_weighted(muse_image *aImage, muse_pixtable *aPixtable,
2511  muse_pixgrid *aGrid)
2512 {
2513  cpl_ensure_code(aImage && aPixtable && aGrid, CPL_ERROR_NULL_INPUT);
2514  aImage->data = cpl_image_new(aGrid->nx, aGrid->nz,
2515  CPL_TYPE_FLOAT);
2516 
2517  double crval2 = muse_pfits_get_crval(aImage->header, 2),
2518  cd22 = muse_pfits_get_cd(aImage->header, 2, 2);
2519  /* get all (relevant) table columns for easy pointer access */
2520  float *lbda = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_LAMBDA),
2521  *data = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_DATA);
2522  int *dq = cpl_table_get_data_int(aPixtable->table, MUSE_PIXTABLE_DQ);
2523  float *imagedata = cpl_image_get_data_float(aImage->data);
2524 
2525 #ifdef ESO_ENABLE_DEBUG
2526  int debug = 0, debugx = 0, debugz = 0;
2527  if (getenv("MUSE_DEBUG_WEIGHTED")) {
2528  debug = atoi(getenv("MUSE_DEBUG_WEIGHTED"));
2529  }
2530  if (debug & 128) { /* need coordinates */
2531  if (getenv("MUSE_DEBUG_WEIGHTED_X")) {
2532  debugx = atoi(getenv("MUSE_DEBUG_WEIGHTED_X"));
2533  if (debugx < 1 || debugx > aGrid->nx) {
2534  debugx = 0;
2535  }
2536  }
2537  if (getenv("MUSE_DEBUG_WEIGHTED_Z")) {
2538  debugz = atoi(getenv("MUSE_DEBUG_WEIGHTED_Z"));
2539  if (debugz < 1 || debugz > aGrid->nz) {
2540  debugz = 0;
2541  }
2542  }
2543  }
2544 #endif
2545 
2546  int ld = 1; /* loop distance, to take into account surrounding pixels */
2547  /* Renka critical radius; only 1.25 to 1.5 makes sense in *
2548  * this 1D interpolation, hardcode to 1.25 for the moment */
2549  double renka_rc = 1.25;
2550  /* scale critical radius by the scale factor in wavelength */
2551  renka_rc *= cd22;
2552 
2553  int i;
2554  for (i = 0; i < aGrid->nx; i++) {
2555  int j;
2556  for (j = 0; j < aGrid->nz; j++) {
2557  double sumdata = 0, sumweight = 0,
2558  lambda = j * cd22 + crval2;
2559  int npoints = 0;
2560 #ifdef ESO_ENABLE_DEBUG
2561 #define MAX_NPIX_2D 50 /* allow for quite a few pixels */
2562  int *pointlist = NULL;
2563  double *pointweights = NULL;
2564  if (debug & 128 && i+1 == debugx && j+1 == debugz) {
2565  pointlist = cpl_calloc(MAX_NPIX_2D, sizeof(int));
2566  pointweights = cpl_malloc(MAX_NPIX_2D * sizeof(double));
2567  }
2568 #endif
2569 
2570  /* go through this and the surrounding cells and their contained pixels */
2571  int j2;
2572  for (j2 = j - ld; j2 <= j + ld; j2++) {
2573  cpl_size idx = muse_pixgrid_get_index(aGrid, i, 0, j2, CPL_FALSE),
2574  n, n_rows = muse_pixgrid_get_count(aGrid, idx);
2575  const cpl_size *rows = muse_pixgrid_get_rows(aGrid, idx);
2576  for (n = 0; n < n_rows; n++) {
2577  if (dq[rows[n]]) { /* exclude all bad pixels */
2578  continue;
2579  }
2580  double dlambda = fabs(lambda - lbda[rows[n]]),
2581  weight = muse_resampling_weight_function_renka(dlambda,
2582  renka_rc);
2583  sumweight += weight;
2584  sumdata += data[rows[n]] * weight;
2585  npoints++;
2586 #ifdef ESO_ENABLE_DEBUG
2587  if (debug & 128 && i+1 == debugx && j+1 == debugz &&
2588  npoints-1 < MAX_NPIX_2D) {
2589  /* store row number instead of index, because we cannot be zero: */
2590  pointlist[npoints-1] = rows[n] + 1;
2591  pointweights[npoints-1] = weight;
2592  }
2593 
2594  if (debug & 256) {
2595  printf(" pixel %4d,%4d (%8"CPL_SIZE_FORMAT"): %2"CPL_SIZE_FORMAT
2596  " %2"CPL_SIZE_FORMAT" %f, %f -> %f ==> %f %f (%d)\n",
2597  i, j2, idx, n, muse_pixgrid_get_count(aGrid, idx), dlambda,
2598  data[muse_pixgrid_get_rows(aGrid, idx)[n]],
2599  weight, sumweight, sumdata, npoints);
2600  }
2601 #endif
2602  } /* for n (all pixels in grid cell) */
2603  } /* for j2 (x direction) */
2604 
2605 #ifdef ESO_ENABLE_DEBUG
2606  if (debug & 128 && i+1 == debugx && j+1 == debugz) {
2607  printf("pixelnumber weight ");
2608  muse_pixtable_dump(aPixtable, 0, 0, 2);
2609  int m = -1;
2610  while (++m < MAX_NPIX_2D && pointlist[m] != 0) {
2611  /* access row using index again: */
2612  printf("%12d %8.5f ", pointlist[m] - 1, pointweights[m]);
2613  muse_pixtable_dump(aPixtable, pointlist[m] - 1, 1, 0);
2614  }
2615  fflush(stdout);
2616  cpl_free(pointlist);
2617  cpl_free(pointweights);
2618  }
2619  if (debug) {
2620  fflush(stdout); /* flush the output in any debug case */
2621  }
2622 #endif
2623  /* if no points were found, we cannot divide by the summed weight *
2624  * and don't need to set the output pixel value (it's 0 already) */
2625  if (!npoints) {
2626  continue;
2627  }
2628  /* divide results by weight of summed pixels */
2629  imagedata[i + j * aGrid->nx] = sumdata / sumweight;
2630  } /* for j (y direction = wavelength planes) */
2631  } /* for i (x direction) */
2632 
2633  return CPL_ERROR_NONE;
2634 } /* muse_resampling_image_weighted() */
2635 
2636 /*---------------------------------------------------------------------------*/
2653 /*---------------------------------------------------------------------------*/
2654 static muse_image *
2655 muse_resampling_image_selected(muse_pixtable *aPixtable,
2656  muse_resampling_type aMethod,
2657  double aDX, double aLambdaMin,
2658  double aLambdaMax, double aDLambda)
2659 {
2660  double dlambda = aDLambda;
2661  float xmin = 0.;
2662  muse_pixgrid *grid = muse_pixgrid_2d_create(aPixtable->table, aDX,
2663  aLambdaMin, aLambdaMax,
2664  dlambda, &xmin);
2665 
2666  /* create output image and add FITS header to it (we already need *
2667  * CRVAL2 and CD2_2 in the sub-functions called from here) */
2668  muse_image *image = muse_image_new();
2669  image->header = cpl_propertylist_new();
2670  const char *unit = cpl_table_get_column_unit(aPixtable->table, "data");
2671  cpl_propertylist_append_string(image->header, "BUNIT", unit);
2672  /* copy input header and append the necessary WCS keywords *
2673  * WCSAXES must preceed all other keywords, but defaults to NAXIS, *
2674  * so we can ignore this here for simplicity */
2675  cpl_propertylist_copy_property_regexp(image->header, aPixtable->header,
2676  MUSE_HDR_PT_REGEXP"|"MUSE_WCS_KEYS, 1);
2677  cpl_propertylist_append_double(image->header, "CRPIX1", 1.);
2678  cpl_propertylist_append_double(image->header, "CRPIX2", 1.);
2679  cpl_propertylist_append_double(image->header, "CRVAL1", 1.);
2680  cpl_propertylist_append_double(image->header, "CRVAL2", aLambdaMin);
2681  cpl_propertylist_append_double(image->header, "CD1_1", 1.);
2682  cpl_propertylist_append_double(image->header, "CD2_2", dlambda);
2683  /* units verified using FITS standard v3.0 */
2684  cpl_propertylist_append_string(image->header, "CUNIT1", "pixel");
2685  cpl_propertylist_append_string(image->header, "CUNIT2", "Angstrom");
2686  /* for linear axes CTYPE doesn't matter, as long as it's not in 4-3 form, *
2687  * see Greisen & Calabretta 2002 A&A 395, 1061 */
2688  cpl_propertylist_append_string(image->header, "CTYPE1", "PIXEL");
2689  /* although DS9 seems to like "LAMBDA" better, the type (for the wavelength *
2690  * direction) was verified using Greisen et al. 2006 A&A 446, 747 */
2691  cpl_propertylist_append_string(image->header, "CTYPE2", "AWAV");
2692  /* fill in empty cross-terms of the CDi_j matrix */
2693  cpl_propertylist_append_double(image->header, "CD1_2", 0.);
2694  cpl_propertylist_append_double(image->header, "CD2_1", 0.);
2695 
2696  /* do the resampling */
2697  cpl_error_code rc = CPL_ERROR_NONE;
2698  switch (aMethod) {
2699  case MUSE_RESAMPLE_NEAREST:
2700  rc = muse_resampling_image_nearest(image, aPixtable, grid);
2701  break;
2702  default: /* MUSE_RESAMPLE_WEIGHTED_RENKA */
2703  /* the caller is responsible for checking for other methods */
2704  rc = muse_resampling_image_weighted(image, aPixtable, grid);
2705  }
2706 
2707  muse_pixgrid_delete(grid);
2708  if (rc != CPL_ERROR_NONE) {
2709  cpl_msg_error(__func__, "resampling failed: %s", cpl_error_get_message());
2710  muse_image_delete(image);
2711  return NULL;
2712  }
2713 
2714  return image;
2715 } /* muse_resampling_image_selected() */
2716 
2717 /*---------------------------------------------------------------------------*/
2757 /*---------------------------------------------------------------------------*/
2758 muse_image *
2760  double aDX, double aDLambda)
2761 {
2762  cpl_ensure(aPixtable, CPL_ERROR_NULL_INPUT, NULL);
2763  if (aDLambda == 0.0) {
2764  aDLambda = kMuseSpectralSamplingA;
2765  }
2766  muse_pixtable_wcs wcstype = muse_pixtable_wcs_check(aPixtable);
2767  cpl_ensure(wcstype == MUSE_PIXTABLE_WCS_CELSPH ||
2768  wcstype == MUSE_PIXTABLE_WCS_PIXEL, CPL_ERROR_UNSUPPORTED_MODE,
2769  NULL);
2770 
2771  /* check method and give info message */
2772  switch (aMethod) {
2773  case MUSE_RESAMPLE_NEAREST:
2774  cpl_msg_info(__func__, "Using nearest neighbor sampling (%d) along "
2775  "wavelengths.", aMethod);
2776  break;
2778  cpl_msg_info(__func__, "Using renka-weighted interpolation (%d) along "
2779  "wavelengths.", aMethod);
2780  break;
2781  default:
2782  cpl_msg_error(__func__, "Don't know this resampling method: %d", aMethod);
2783  cpl_error_set(__func__, CPL_ERROR_UNSUPPORTED_MODE);
2784  return NULL;
2785  }
2786 
2787  /* compute the size of the output grid depending on the inputs and the *
2788  * data available in the pixel table */
2789  float lmin = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_LLO),
2790  lmax = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_LHI);
2791 
2793  /* Pretend that we are dealing with only one slice. *
2794  * We can do that because the pixel table was created in such *
2795  * a way that no slice overlaps in x-direction with another. */
2796  return muse_resampling_image_selected(aPixtable, aMethod,
2797  aDX == 0.0 ? 1. : aDX,
2798  lmin, lmax, aDLambda);
2799  }
2800 
2801  /* For pixel tables with full geometry information, resample each *
2802  * slice of each IFU into an image one by one and stack them next *
2803  * to each other (horizontally) in a large output image. */
2804  muse_pixtable **slice_pixtable = muse_pixtable_extracted_get_slices(aPixtable);
2805  int n_slices = muse_pixtable_extracted_get_size(slice_pixtable);
2806 
2807  double dx = aDX;
2808  if (dx == 0.0) {
2810  dx = 1.0;
2811  } else {
2812  double xsc, ysc;
2813  muse_wcs_get_scales(aPixtable->header, &xsc, &ysc);
2814  /* XXX need such an extra 1.2 factor to get good results: */
2815  dx = 1.20 * xsc;
2816  }
2817  }
2818  cpl_msg_debug(__func__, "Resampling %d slices to a 2D image, using bins of"
2819  " %e %s x %.3f Angstrom", n_slices, dx,
2820  cpl_table_get_column_unit(aPixtable->table, MUSE_PIXTABLE_XPOS),
2821  aDLambda);
2822 
2823  /* build one stacked image per slice */
2824  muse_image *slice_image[n_slices];
2825  int i_slice;
2826  #pragma omp parallel for default(none) /* as req. by Ralf */ \
2827  shared(aDLambda, aMethod, dx, lmax, lmin, n_slices, \
2828  slice_image, slice_pixtable)
2829  for (i_slice = 0; i_slice < n_slices; i_slice++) {
2830 #if 0
2831  cpl_msg_debug(__func__, "slice pixel table %d", i_slice + 1);
2832 #endif
2833  muse_pixtable *pt = slice_pixtable[i_slice];
2834  if (muse_pixtable_get_nrow(pt) < 1) {
2835  slice_image[i_slice] = NULL;
2836  continue;
2837  }
2838  slice_image[i_slice] = muse_resampling_image_selected(pt, aMethod, dx,
2839  lmin, lmax, aDLambda);
2840  } /* for i_slice */
2841 
2842  /* concatenate all images into one large output image */
2843  muse_image *image = muse_image_new();
2844  for (i_slice = 0; i_slice < n_slices; i_slice++) {
2845  muse_image *slice = slice_image[i_slice];
2846 #if 0
2847  cpl_msg_debug(__func__, "slice %d: %ldx%ld", i_slice + 1,
2848  cpl_image_get_size_x(slice->data), cpl_image_get_size_y(slice->data));
2849 #endif
2850  if (slice == NULL) {
2851  continue;
2852  }
2853  if (!image->header) {
2854  /* use FITS header from the first slice */
2855  image->header = cpl_propertylist_duplicate(slice->header);
2856  }
2857  cpl_image *data = muse_cplimage_concat_x(image->data, slice->data);
2858  cpl_image_delete(image->data);
2859  image->data = data;
2860  if (slice->dq) {
2861  cpl_image *dq = muse_cplimage_concat_x(image->dq, slice->dq);
2862  cpl_image_delete(image->dq);
2863  image->dq = dq;
2864  }
2865  if (slice->stat) {
2866  cpl_image *stat = muse_cplimage_concat_x(image->stat, slice->stat);
2867  cpl_image_delete(image->stat);
2868  image->stat = stat;
2869  }
2870  muse_image_delete(slice);
2871  slice_image[i_slice] = NULL;
2872  } /* for i_slice */
2873  muse_pixtable_extracted_delete(slice_pixtable);
2874 
2875  /* transfer flat-spectrum correction status */
2876  if (cpl_propertylist_has(aPixtable->header, MUSE_HDR_PT_FFCORR)) {
2877  cpl_propertylist_append_bool(image->header, MUSE_HDR_FLUX_FFCORR, CPL_TRUE);
2878  cpl_propertylist_set_comment(image->header, MUSE_HDR_FLUX_FFCORR,
2879  MUSE_HDR_FLUX_FFCORR_C);
2880  }
2881 
2882  return image;
2883 } /* muse_resampling_image() */
2884 
2885 /*---------------------------------------------------------------------------*/
2901 /*---------------------------------------------------------------------------*/
2902 cpl_table *
2903 muse_resampling_spectrum(muse_pixtable *aPixtable, double aBinwidth)
2904 {
2905  cpl_ensure(aPixtable && aPixtable->header && aPixtable->table,
2906  CPL_ERROR_NULL_INPUT, NULL);
2907  cpl_ensure(muse_cpltable_check(aPixtable->table, muse_pixtable_def)
2908  == CPL_ERROR_NONE, CPL_ERROR_ILLEGAL_INPUT, NULL);
2909 
2910  /* determine spectral range */
2911  double lmin = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_LLO);
2912  double lmax = cpl_propertylist_get_float(aPixtable->header, MUSE_HDR_PT_LHI);
2913  cpl_size lsize = floor((lmax - lmin) / aBinwidth) + 2;
2914 
2915  /* create the empty spectral table */
2916  cpl_table *spectrum = muse_cpltable_new(muse_dataspectrum_def, lsize);
2917  cpl_table_fill_column_window(spectrum, "lambda", 0, lsize, 0);
2918  cpl_table_fill_column_window(spectrum, "data", 0, lsize, 0);
2919  cpl_table_fill_column_window(spectrum, "stat", 0, lsize, 0);
2920  cpl_table_fill_column_window(spectrum, "dq", 0, lsize, 0);
2921  double *spec_data = cpl_table_get_data_double(spectrum, "data");
2922  double *spec_stat = cpl_table_get_data_double(spectrum, "stat");
2923  double *spec_lbda = cpl_table_get_data_double(spectrum, "lambda");
2924  /* inherit spectral data units from the pixel table */
2925  cpl_table_set_column_unit(spectrum, "data",
2926  cpl_table_get_column_unit(aPixtable->table,
2928  cpl_table_set_column_unit(spectrum, "stat",
2929  cpl_table_get_column_unit(aPixtable->table,
2931 
2932  /* add a temporary column for the integrated weight of each bin */
2933  cpl_table_new_column(spectrum, "weight", CPL_TYPE_DOUBLE);
2934  cpl_table_fill_column_window(spectrum, "weight", 0, lsize, 0);
2935  double *spec_weight = cpl_table_get_data_double(spectrum, "weight");
2936 
2937  /* accessors for the pixel table */
2938  float *lbda = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_LAMBDA);
2939  float *data = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_DATA);
2940  float *stat = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_STAT);
2941  float *wght = NULL;
2942  if (cpl_table_has_column(aPixtable->table, MUSE_PIXTABLE_WEIGHT)) {
2943  wght = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_WEIGHT);
2944  }
2945  int *dq = cpl_table_get_data_int(aPixtable->table, MUSE_PIXTABLE_DQ);
2946 
2947  /* loop through all selected pixel table rows and sort them *
2948  * into the output bins, assigning them linear weights */
2949  cpl_array *asel = cpl_table_where_selected(aPixtable->table);
2950  const cpl_size *sel = cpl_array_get_data_cplsize_const(asel);
2951  cpl_size isel, nsel = cpl_array_get_size(asel);
2952  for (isel = 0; isel < nsel; isel++) {
2953  cpl_size i_row = sel[isel];
2954  if ((dq[i_row] != EURO3D_GOODPIXEL)) {
2955  continue;
2956  }
2957  // We ignore "inf" and "nan" values here.
2958  // See http://urania1.univ-lyon1.fr/mpdaf/ticket/374
2959  if (! isfinite(data[i_row])) {
2960  continue;
2961  }
2962  /* compute target bins and weights */
2963  double l = (lbda[i_row] - lmin) / aBinwidth;
2964  if (l < 0) l = 0;
2965  cpl_size il = floor(l);
2966  l -= il;
2967  double w0 = 1-l;
2968  double w1 = l;
2969  if (wght) {
2970  w0 *= wght[i_row];
2971  w1 *= wght[i_row];
2972  }
2973  /* weight the data in the two involved bins */
2974  spec_data[il] += w0 * data[i_row];
2975  spec_data[il+1] += w1 * data[i_row];
2976  spec_stat[il] += w0 * stat[i_row];
2977  spec_stat[il+1] += w1 * stat[i_row];
2978  spec_weight[il] += w0;
2979  spec_weight[il+1] += w1;
2980  } /* for isel (selected pixel table rows) */
2981  cpl_array_delete(asel);
2982 
2983  /* assign wavelengths and erase empty spectral bins */
2984  cpl_size ispec;
2985  for (ispec = 0; ispec < lsize; ispec++) {
2986  if (spec_weight[ispec] > 0) {
2987  spec_lbda[ispec] = ispec * aBinwidth + lmin;
2988  cpl_table_unselect_row(spectrum, ispec);
2989  }
2990  } /* for ispec (all spectrum points) */
2991  cpl_table_erase_selected(spectrum);
2992 
2993  /* apply the weights and delete the temporary weight column */
2994  cpl_table_divide_columns(spectrum, "data", "weight");
2995  cpl_table_divide_columns(spectrum, "stat", "weight");
2996  cpl_table_erase_column(spectrum, "weight");
2997  return spectrum;
2998 } /* muse_resampling_spectrum() */
2999 
3000 /*---------------------------------------------------------------------------*/
3031 /*---------------------------------------------------------------------------*/
3032 cpl_table *
3034  float aLo, float aHi, unsigned char aIter)
3035 {
3036  cpl_ensure(aPixtable && aPixtable->header && aPixtable->table,
3037  CPL_ERROR_NULL_INPUT, NULL);
3038  cpl_ensure(muse_cpltable_check(aPixtable->table, muse_pixtable_def)
3039  == CPL_ERROR_NONE, CPL_ERROR_ILLEGAL_INPUT, NULL);
3040 
3041  /* initial resampling */
3042  cpl_table *spectrum = muse_resampling_spectrum(aPixtable, aBinwidth);
3043  if (aIter == 0) {
3044  return spectrum;
3045  }
3046 
3047  /* create easy accessors for the pixel table */
3048  float *lbda = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_LAMBDA),
3049  *data = cpl_table_get_data_float(aPixtable->table, MUSE_PIXTABLE_DATA);
3050  int *dq = cpl_table_get_data_int(aPixtable->table, MUSE_PIXTABLE_DQ);
3051  /* get row selection of the pixel table */
3052  cpl_array *asel = cpl_table_where_selected(aPixtable->table);
3053  const cpl_size *sel = cpl_array_get_data_cplsize_const(asel);
3054  cpl_size isel, nsel = cpl_array_get_size(asel);
3055 
3056  /* now iterate the spectrum creation */
3057  cpl_size nhi = 0, nlo = 0; /* sum up rejections of all iterations */
3058  unsigned char i;
3059  for (i = 1; i <= aIter; i++) {
3060  cpl_size ispec, nbins = cpl_table_get_nrow(spectrum);
3061  double *sdata = cpl_table_get_data_double(spectrum, "data"),
3062  *sstat = cpl_table_get_data_double(spectrum, "stat"),
3063  *sstddev = cpl_malloc(nbins * sizeof(double));
3064  /* compute standard deviation from the variance of the spectrum */
3065  for (ispec = 0; ispec < nbins; ispec++) {
3066  sstddev[ispec] = sqrt(sstat[ispec]);
3067  }
3068 
3069  /* loop through all selected pixel table rows */
3070  for (isel = 0; isel < nsel; isel++) {
3071  cpl_size irow = sel[isel];
3072  if ((dq[irow] != EURO3D_GOODPIXEL)) {
3073  continue;
3074  }
3075  double l = lbda[irow];
3076  ispec = muse_cpltable_find_sorted(spectrum, "lambda", l);
3077  /* search for the right wavelength */
3078  if ((ispec < nbins - 1) && (sdata[ispec] < sdata[ispec + 1])) {
3079  ispec++;
3080  }
3081  /* flag the pixel if it's outside given high... */
3082  if (aHi > 0. && data[irow] > sdata[ispec] + aHi * sstddev[ispec]) {
3083  dq[irow] = EURO3D_OUTLIER;
3084  nhi++;
3085  }
3086  /* or low boundaries */
3087  if (aLo > 0. && data[irow] < sdata[ispec] - aLo * sstddev[ispec]) {
3088  dq[irow] = EURO3D_OUTLIER;
3089  nlo++;
3090  }
3091  } /* for isel (all selected pixel table rows) */
3092  cpl_free(sstddev);
3093 
3094  /* give some output, only in debug-level (because otherwise *
3095  * users would not understand where the message comes from) */
3096  cpl_msg_debug(__func__, "%"CPL_SIZE_FORMAT" of %"CPL_SIZE_FORMAT" pixels "
3097  "are outliers (%"CPL_SIZE_FORMAT" low and %"CPL_SIZE_FORMAT
3098  " high, after %hhu iteration%s)", nlo + nhi, nsel, nlo, nhi,
3099  i, i == 1 ? "" : "s");
3100 
3101  cpl_table_delete(spectrum);
3102  spectrum = muse_resampling_spectrum(aPixtable, aBinwidth);
3103  } /* for i (all iterations) */
3104  cpl_array_delete(asel);
3105 
3106  /* reinstate the original pixel table flags */
3107  muse_pixtable_reset_dq(aPixtable, EURO3D_OUTLIER);
3108 
3109  return spectrum;
3110 } /* muse_resampling_spectrum_iterate() */
3111 
#define MUSE_PIXTABLE_DQ
Definition: muse_pixtable.h:49
#define MUSE_PIXTABLE_XPOS
Definition: muse_pixtable.h:51
muse_image * muse_resampling_collapse_pixgrid(muse_pixtable *aPixtable, muse_pixgrid *aGrid, muse_datacube *aCube, const muse_table *aFilter, muse_resampling_params *aParams)
Integrate a pixel table / pixel grid along the wavelength direction.
muse_pixtable_wcs
State of the astrometric calibration of a MUSE pixel table.
Structure definition of a MUSE datacube.
Definition: muse_datacube.h:48
muse_image * muse_resampling_image(muse_pixtable *aPixtable, muse_resampling_type aMethod, double aDX, double aDLambda)
Resample a pixel table onto a two-dimensional regular grid.
cpl_error_code muse_wcs_get_scales(cpl_propertylist *aHeader, double *aXScale, double *aYScale)
Compute the spatial scales (in degrees) from the FITS header WCS.
Definition: muse_wcs.c:1852
cpl_error_code muse_wcs_pixel_from_projplane(cpl_propertylist *aHeader, double aX, double aY, double *aXOut, double *aYOut)
Convert from projection plane coordinates to pixel coordinates.
Definition: muse_wcs.c:1766
void muse_image_delete(muse_image *aImage)
Deallocate memory associated to a muse_image object.
Definition: muse_image.c:85
void muse_pixtable_extracted_delete(muse_pixtable **aPixtables)
Delete a pixel table array.
double muse_pfits_get_cd(const cpl_propertylist *aHeaders, unsigned int aAxisI, unsigned int aAxisJ)
find out the WCS coordinate at the reference point
Definition: muse_pfits.c:446
muse_pixgrid * muse_pixgrid_2d_create(cpl_table *aTable, double aDX, double aZMin, double aZMax, double aDZ, float *aXMin)
Convert selected rows of a pixel table into 2D pixel grid, linking the grid points to entries (=rows)...
Definition: muse_pixgrid.c:507
#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_rhum(const cpl_propertylist *aHeaders)
find out the relavtive humidity (in %)
Definition: muse_pfits.c:1024
double muse_pfits_get_crval(const cpl_propertylist *aHeaders, unsigned int aAxis)
find out the WCS coordinate at the reference point
Definition: muse_pfits.c:423
A structure containing a spatial two-axis WCS.
Definition: muse_wcs.h:105
cpl_table * muse_resampling_spectrum_iterate(muse_pixtable *aPixtable, double aBinwidth, float aLo, float aHi, unsigned char aIter)
Iteratively resample selected pixels of a pixel table into spectrum.
double cd22
Definition: muse_wcs.h:108
cpl_error_code muse_resampling_params_set_wcs(muse_resampling_params *aParams, const cpl_propertylist *aWCS)
Set an output WCS (and wavelength scale) in the resampling parameters.
muse_pixgrid * muse_pixgrid_create(muse_pixtable *aPixtable, cpl_propertylist *aHeader, cpl_size aXSize, cpl_size aYSize, cpl_size aZSize)
Convert selected rows of a pixel table into pixel grid, linking the grid points to entries (=rows) in...
Definition: muse_pixgrid.c:237
muse_pixtable ** muse_pixtable_extracted_get_slices(muse_pixtable *aPixtable)
Extract one pixel table per IFU and slice.
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.
int muse_pixtable_get_type(muse_pixtable *aPixtable)
Determine the type of pixel table.
const muse_cpltable_def muse_dataspectrum_def[]
cpl_error_code muse_utils_filter_copy_properties(cpl_propertylist *aHeader, const muse_table *aFilter, double aFraction)
Add/propagate filter properties to header of collapsed image.
Definition: muse_utils.c:934
void muse_utils_memory_dump(const char *aMarker)
Display the current memory usage of the given program.
Definition: muse_utils.c:2702
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.
muse_datacube * muse_resampling_cube(muse_pixtable *aPixtable, muse_resampling_params *aParams, muse_pixgrid **aGrid)
Resample a pixel table onto a regular grid structure representing a FITS NAXIS=3 datacube.
double muse_pfits_get_pres_start(const cpl_propertylist *aHeaders)
find out the ambient pressure at start of exposure (in mbar)
Definition: muse_pfits.c:1042
cpl_image * stat
the statistics extension
Definition: muse_image.h:64
cpl_error_code muse_wcs_projplane_from_celestial(cpl_propertylist *aHeader, double aRA, double aDEC, double *aX, double *aY)
Convert from celestial spherical coordinates to projection plane coordinates.
Definition: muse_wcs.c:1685
void muse_datacube_delete(muse_datacube *aCube)
Deallocate memory associated to a muse_datacube object.
cpl_propertylist * hgroup
the group FITS header
#define MUSE_HDR_PT_FFCORR
cpl_propertylist * header
the primary FITS header
The pixel grid.
Definition: muse_pixgrid.h:65
double muse_astro_parangle(const cpl_propertylist *aHeader)
Properly average parallactic angle values of one exposure.
Definition: muse_astro.c:449
Structure definition of MUSE three extension FITS file.
Definition: muse_image.h:40
cpl_table * table
The pixel table.
cpl_propertylist * header
the FITS header
Definition: muse_image.h:72
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_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
muse_resampling_crstats_type crtype
cpl_image * dq
the data quality extension
Definition: muse_image.h:56
cpl_table * muse_cpltable_new(const muse_cpltable_def *aDef, cpl_size aLength)
Create an empty table according to the specified definition.
double muse_pfits_get_crpix(const cpl_propertylist *aHeaders, unsigned int aAxis)
find out the WCS reference point
Definition: muse_pfits.c:401
void muse_pixgrid_delete(muse_pixgrid *aGrid)
Delete a pixel grid and remove its memory.
Definition: muse_pixgrid.c:575
double muse_flux_response_interpolate(const cpl_table *aResponse, double aLambda, double *aError, muse_flux_interpolation_type aType)
Compute linearly interpolated response of some kind at given wavelength.
Definition: muse_flux.c:338
muse_wcs * muse_wcs_new(cpl_propertylist *aHeader)
Create a new WCS structure from a given FITS header.
Definition: muse_wcs.c:1897
cpl_array * muse_cplarray_new_from_delimited_string(const char *aString, const char *aDelim)
Convert a delimited string into an array of strings.
#define MUSE_PIXTABLE_WEIGHT
Definition: muse_pixtable.h:57
Structure definition of MUSE pixel table.
static const cpl_size * muse_pixgrid_get_rows(muse_pixgrid *aGrid, cpl_size aIndex)
Return a pointer to the rows stored in one pixel.
Definition: muse_pixgrid.h:171
#define MUSE_WCS_KEYS
regular expression for WCS properties
Definition: muse_wcs.h:48
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_celestial_from_pixel_fast(muse_wcs *aWCS, double aX, double aY, double *aRA, double *aDEC)
Convert from pixel coordinates to celestial spherical coordinates.
Definition: muse_wcs.h:138
muse_resampling_crstats_type
Cosmic ray rejection statistics type.
muse_resampling_params * muse_resampling_params_new(muse_resampling_type aMethod)
Create the resampling parameters structure.
cpl_error_code muse_wcs_projplane_from_pixel(cpl_propertylist *aHeader, double aX, double aY, double *aXOut, double *aYOut)
Convert from pixel coordinates to projection plane coordinates.
Definition: muse_wcs.c:1733
cpl_table * table
The table.
Definition: muse_table.h:49
cpl_imagelist * data
the cube containing the actual data values
Definition: muse_datacube.h:76
cpl_error_code muse_wcs_pixel_from_celestial(cpl_propertylist *aHeader, double aRA, double aDEC, double *aX, double *aY)
Convert from celestial spherical coordinates to pixel coordinates.
Definition: muse_wcs.c:1630
Structure definition of a Euro3D datacube.
Definition: muse_datacube.h:97
Structure to store a table together with a property list.
Definition: muse_table.h:43
double muse_utils_filter_fraction(const muse_table *aFilter, double aLambda1, double aLambda2)
Compute fraction of filter area covered by the data range.
Definition: muse_utils.c:893
cpl_imagelist * dq
the optional cube containing the bad pixel status
Definition: muse_datacube.h:81
muse_resampling_dispersion_type tlambda
#define MUSE_HDR_PT_LLO
FITS header keyword contains the lower limit of the data in spectral direction.
cpl_size muse_cpltable_find_sorted(const cpl_table *aTable, const char *aColumn, double aValue)
Find a row in a table.
cpl_table * dtable
the table containing the actual Euro3D data
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_image * muse_cplimage_concat_x(const cpl_image *aImage1, const cpl_image *aImage2)
Concatenate two images in x direction.
cpl_error_code muse_resampling_params_set_pixfrac(muse_resampling_params *aParams, const char *aString)
Set resampling pixfrac given a string that can contain up to three floating-point values...
cpl_propertylist * hdata
the data FITS header
cpl_table * gtable
the table containing the Euro3D groups
cpl_propertylist * header
the FITS header
Definition: muse_datacube.h:57
const muse_cpltable_def muse_euro3dcube_e3d_data_def[]
double muse_astro_posangle(const cpl_propertylist *aHeader)
Derive the position angle of an observation from information in a FITS header.
Definition: muse_astro.c:413
#define MUSE_PIXTABLE_STAT
Definition: muse_pixtable.h:50
const muse_cpltable_def muse_pixtable_def[]
MUSE pixel table definition.
#define MUSE_PIXTABLE_LAMBDA
Definition: muse_pixtable.h:53
static cpl_size muse_pixgrid_get_index(muse_pixgrid *aGrid, cpl_size aX, cpl_size aY, cpl_size aZ, cpl_boolean aAllowOutside)
Get the grid index determined from all three coordinates.
Definition: muse_pixgrid.h:100
static void muse_wcs_projplane_from_pixel_fast(muse_wcs *aWCS, double aX, double aY, double *aXOut, double *aYOut)
Convert from pixel coordinates to projection plane coordinates.
Definition: muse_wcs.h:217
cpl_boolean iscelsph
Definition: muse_wcs.h:112
#define MUSE_HDR_PT_DAR_NAME
muse_resampling_type
Resampling types.
double muse_pfits_get_temp(const cpl_propertylist *aHeaders)
find out the ambient temperature (in degrees Celsius)
Definition: muse_pfits.c:1006
muse_euro3dcube * muse_resampling_euro3d(muse_pixtable *aPixtable, muse_resampling_params *aParams)
Resample a pixel table onto a regular grid structure representing a Euro3D format file...
Resampling parameters.
void muse_resampling_params_delete(muse_resampling_params *aParams)
Delete a resampling parameters structure.
muse_resampling_type method
muse_image * muse_image_new(void)
Allocate memory for a new muse_image object.
Definition: muse_image.c:66
cpl_table * muse_resampling_spectrum(muse_pixtable *aPixtable, double aBinwidth)
Resample the selected pixels of a pixel table into a spectrum.
#define MUSE_PIXTABLE_YPOS
Definition: muse_pixtable.h:52
#define MUSE_HDR_PT_YHI
FITS header keyword contains the upper limit of the data in y-direction.
static cpl_size muse_pixgrid_get_count(muse_pixgrid *aGrid, cpl_size aIndex)
Return the number of rows stored in one pixel.
Definition: muse_pixgrid.h:140
const muse_cpltable_def muse_euro3dcube_e3d_grp_def[]
muse_ins_mode muse_pfits_get_mode(const cpl_propertylist *aHeaders)
find out the observation mode
Definition: muse_pfits.c:1352
double muse_astro_airmass(cpl_propertylist *aHeader)
Derive the effective airmass of an observation from information in a FITS header. ...
Definition: muse_astro.c:331
cpl_imagelist * stat
the cube containing the data variance
Definition: muse_datacube.h:86
cpl_propertylist * header
The FITS header.
#define MUSE_HDR_PT_XHI
FITS header keyword contains the upper limit of the data in x-ion.