MUSE Pipeline Reference Manual  2.5.2
muse_cplwrappers.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-2015 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 #ifdef HAVE_READLINK
30 #define _BSD_SOURCE /* get readlink() from unistd.h */
31 #include <unistd.h> /* readlink(), has to be included before cpl.h */
32 #endif
33 #include <cpl.h>
34 #include <string.h>
35 #include <math.h>
36 
37 #include "muse_cplwrappers.h"
38 
39 /*----------------------------------------------------------------------------*
40  * Debugging Macros *
41  * Set these to 1 or higher for (lots of) debugging output *
42  *----------------------------------------------------------------------------*/
43 #define DEBUG_SQR 0 /* debugging in muse_cplvector_get_semiquartile() */
44 
45 /*----------------------------------------------------------------------------*/
55 /*----------------------------------------------------------------------------*/
56 
59 /*----------------------------------------------------------------------------*/
75 /*----------------------------------------------------------------------------*/
76 cpl_error_code
77 muse_cplimage_or(cpl_image *aTarget, const cpl_image *aImage, unsigned int mask)
78 {
79  cpl_ensure_code(aTarget && aImage, CPL_ERROR_NULL_INPUT);
80  cpl_ensure_code(cpl_image_get_type(aTarget) == CPL_TYPE_INT,
81  CPL_ERROR_INVALID_TYPE);
82  cpl_ensure_code(cpl_image_get_type(aImage) == CPL_TYPE_INT,
83  CPL_ERROR_INVALID_TYPE);
84  cpl_ensure_code(cpl_image_get_size_x(aTarget) == cpl_image_get_size_x(aImage),
85  CPL_ERROR_ILLEGAL_INPUT);
86  cpl_ensure_code(cpl_image_get_size_y(aTarget) == cpl_image_get_size_y(aImage),
87  CPL_ERROR_ILLEGAL_INPUT);
88 
89  int *target = cpl_image_get_data_int(aTarget);
90  const int *data = cpl_image_get_data_int_const(aImage);
91  cpl_size nData = cpl_image_get_size_x(aImage) * cpl_image_get_size_y(aImage);
92  cpl_size i;
93  for (i = 0; i < nData; i++, data++, target++) {
94  *target |= *data & mask;
95  }
96  return CPL_ERROR_NONE;
97 } /* muse_cplimage_or() */
98 
99 /*----------------------------------------------------------------------------*/
113 /*----------------------------------------------------------------------------*/
114 cpl_image *
115 muse_cplimage_concat_y(const cpl_image *aImage1, const cpl_image *aImage2)
116 {
117  cpl_ensure(aImage1 || aImage2, CPL_ERROR_NULL_INPUT, NULL);
118  if (aImage1 == NULL) {
119  return cpl_image_duplicate(aImage2);
120  }
121  if (aImage2 == NULL) {
122  return cpl_image_duplicate(aImage1);
123  }
124  cpl_type type = cpl_image_get_type(aImage1);
125  cpl_ensure(type == cpl_image_get_type(aImage2), CPL_ERROR_ILLEGAL_INPUT, NULL);
126  cpl_size xsize = cpl_image_get_size_x(aImage1);
127  cpl_ensure(xsize == cpl_image_get_size_x(aImage2), CPL_ERROR_ILLEGAL_INPUT, NULL);
128 
129  cpl_size ysize1 = cpl_image_get_size_y(aImage1);
130  cpl_size ysize2 = cpl_image_get_size_y(aImage2);
131  cpl_image *res = cpl_image_new(xsize, ysize1 + ysize2, type);
132  void *resdata = cpl_image_get_data(res);
133  const void *data1 = cpl_image_get_data_const(aImage1);
134  cpl_size size1 = xsize * ysize1 * cpl_type_get_sizeof(type);
135  const void *data2 = cpl_image_get_data_const(aImage2);
136  cpl_size size2 = xsize * ysize2 * cpl_type_get_sizeof(type);
137  memcpy(resdata, data1, size1);
138  memcpy((char *)resdata+size1, data2, size2);
139 
140  return res;
141 }
142 
143 /*----------------------------------------------------------------------------*/
157 /*----------------------------------------------------------------------------*/
158 cpl_image *
159 muse_cplimage_concat_x(const cpl_image *aImage1, const cpl_image *aImage2)
160 {
161  cpl_ensure(aImage1 || aImage2, CPL_ERROR_NULL_INPUT, NULL);
162  if (aImage1 == NULL) {
163  return cpl_image_duplicate(aImage2);
164  }
165  if (aImage2 == NULL) {
166  return cpl_image_duplicate(aImage1);
167  }
168  cpl_type type = cpl_image_get_type(aImage1);
169  cpl_ensure(type == cpl_image_get_type(aImage2), CPL_ERROR_ILLEGAL_INPUT, NULL);
170  cpl_size ysize = cpl_image_get_size_y(aImage1);
171  cpl_ensure(ysize == cpl_image_get_size_y(aImage2), CPL_ERROR_ILLEGAL_INPUT, NULL);
172 
173  cpl_size xsize1 = cpl_image_get_size_x(aImage1);
174  cpl_size xsize2 = cpl_image_get_size_x(aImage2);
175  cpl_image *res = cpl_image_new(xsize1 + xsize2, ysize, type);
176  void *resdata = cpl_image_get_data(res);
177  const void *data1 = cpl_image_get_data_const(aImage1);
178  cpl_size size1 = xsize1 * cpl_type_get_sizeof(type);
179  const void *data2 = cpl_image_get_data_const(aImage2);
180  cpl_size size2 = xsize2 * cpl_type_get_sizeof(type);
181  cpl_size size = (size1 + size2) * ysize;
182  cpl_size y, y3, y4; /* instead of y1 and y2 to circumvent warning */
183  for (y = 0, y3 = 0, y4 = 0; y < size; y+=size1+size2, y3+=size1, y4+=size2) {
184  memcpy((char *)resdata + y, (char *)data1 + y3, size1);
185  memcpy((char *)resdata + y + size1, (char *)data2 + y4, size2);
186  }
187  return res;
188 }
189 
190 /*----------------------------------------------------------------------------*/
201 /*----------------------------------------------------------------------------*/
202 cpl_image *
204  unsigned int aNX, unsigned int aNY)
205 {
206  cpl_ensure(aImage, CPL_ERROR_NULL_INPUT, NULL);
207  /* make sure here already that none is an even number */
208  cpl_ensure((aNX & 1) && (aNY & 1), CPL_ERROR_ILLEGAL_INPUT, NULL);
209 
210  /* create filtered image of the same size as input image */
211  cpl_image *filtered = cpl_image_new(cpl_image_get_size_x(aImage),
212  cpl_image_get_size_y(aImage),
213  CPL_TYPE_FLOAT);
214  /* create mask of the necessary size */
215  cpl_mask *mask = cpl_mask_new(aNX, aNY);
216  cpl_mask_not(mask);
217  cpl_errorstate prestate = cpl_errorstate_get();
218  cpl_image_filter_mask(filtered, aImage, mask, CPL_FILTER_MEDIAN,
219  CPL_BORDER_FILTER);
220  if (!cpl_errorstate_is_equal(prestate)) {
221  cpl_msg_error(__func__, "filtering failed: %s", cpl_error_get_message());
222  cpl_mask_delete(mask);
223  cpl_image_delete(filtered);
224  return NULL;
225  }
226  cpl_mask_delete(mask);
227 
228  /* now subtract the filtered image from the input image */
229  cpl_image *subtracted = cpl_image_subtract_create(aImage, filtered);
230  cpl_image_delete(filtered);
231 
232  return subtracted;
233 } /* muse_cplimage_filter_median_subtract() */
234 
235 /*----------------------------------------------------------------------------*/
256 /*----------------------------------------------------------------------------*/
257 cpl_vector *
258 muse_cplimage_slope_window(const cpl_image *aImage, const cpl_size *aWindow)
259 {
260  cpl_ensure(aImage && aWindow, CPL_ERROR_NULL_INPUT, NULL);
261  /* duplicate the input image to remove the bad pixel mask, if one exists */
262  cpl_image *image = cpl_image_duplicate(aImage);
263  cpl_image_accept_all(image);
264 
265  cpl_vector *slopes = cpl_vector_new(2); /* two elements: x- and y-slope */
266  unsigned char k; /* vector index, collapsing direction */
267  for (k = 0; k <= 1; k++) {
268  /* collapse by row (direction 0) or column (1) */
269  cpl_image *coll = cpl_image_collapse_window_create(image,
270  aWindow[0], aWindow[2],
271  aWindow[1], aWindow[3],
272  k);
273  if (!coll) {
274  cpl_image_delete(image);
275  cpl_vector_delete(slopes);
276  return NULL;
277  }
278  /* we need the average, not the sum! */
279  if (k == 0) {
280  cpl_image_divide_scalar(coll, aWindow[3] - aWindow[2] + 1);
281  } else {
282  cpl_image_divide_scalar(coll, aWindow[1] - aWindow[0] + 1);
283  }
284  int npx = k == 0 ? cpl_image_get_size_x(coll) : cpl_image_get_size_y(coll);
285  /* convert coordinates into matrices */
286  cpl_matrix *coords = cpl_matrix_new(1, npx);
287  cpl_vector *values = cpl_vector_new(npx);
288  float *data = cpl_image_get_data_float(coll);
289  int i;
290  for (i = 0; i < npx; i++) {
291  cpl_matrix_set(coords, 0, i, i + 1);
292  /* do it manually one-by-one, to use cpl_vector_wrap() *
293  * one would first need to cast the data to double */
294  cpl_vector_set(values, i, data[i]);
295  } /* for i (all pixels) */
296 
297  cpl_polynomial *fit = cpl_polynomial_new(1);
298  const cpl_boolean sym = CPL_FALSE;
299  const cpl_size mindeg = 0, maxdeg = 1;
300  cpl_error_code err = cpl_polynomial_fit(fit, coords, &sym, values, NULL,
301  CPL_FALSE, &mindeg, &maxdeg);
302  cpl_matrix_delete(coords);
303  cpl_vector_delete(values);
304  cpl_image_delete(coll);
305 
306  if (err != CPL_ERROR_NONE) {
307  cpl_msg_warning(__func__, "Could not fit %s slope: %s",
308  k == 0 ? "horizontal" : "vertical",
309  cpl_error_get_message());
310  cpl_polynomial_delete(fit);
311  cpl_vector_delete(slopes);
312  cpl_image_delete(image);
313  return NULL;
314  }
315 #if 0
316  printf("%s: fit (%s)\n", __func__, k == 0 ? "rows" : "cols");
317  cpl_polynomial_dump(fit, stdout);
318  fflush(stdout);
319 #endif
320  const cpl_size pows = { 1 };
321  cpl_vector_set(slopes, k, cpl_polynomial_get_coeff(fit, &pows));
322  cpl_polynomial_delete(fit);
323  } /* for k (collapsing direction) */
324  cpl_image_delete(image);
325 #if 0
326  printf("slopes vector:\n");
327  cpl_vector_dump(slopes, stdout);
328  fflush(stdout);
329 #endif
330 
331  return slopes;
332 } /* muse_cplimage_slope_window() */
333 
334 /*----------------------------------------------------------------------------*/
344 /*----------------------------------------------------------------------------*/
345 double
346 muse_cplimage_get_percentile(const cpl_image *aImage, double aFraction)
347 {
348  cpl_ensure(aImage != NULL, CPL_ERROR_NULL_INPUT, 0.0);
349 
350  cpl_array *a = muse_cplarray_new_from_image(aImage);
352  cpl_size n = cpl_array_get_size(a);
353  muse_cplarray_sort(a, TRUE);
354  if (aFraction < 0) {
355  aFraction = 0.;
356  }
357  if (aFraction > 1) {
358  aFraction = 1.;
359  }
360  /* array index of where the percentile is located */
361  cpl_size i = lround(n * aFraction) - 1;
362  if (i < 0) {
363  i = 0;
364  }
365  if (i >= n) {
366  i = n - 1;
367  }
368  double res = cpl_array_get(a, i, NULL);
369  cpl_array_delete(a);
370  return res;
371 }
372 
373 /*----------------------------------------------------------------------------*/
387 /*----------------------------------------------------------------------------*/
388 cpl_image *
389 muse_cplimagelist_collapse_or_create(const cpl_imagelist *imlist)
390 {
391  cpl_ensure(imlist, CPL_ERROR_NULL_INPUT, NULL);
392  int count = cpl_imagelist_get_size(imlist);
393  cpl_ensure(count > 0, CPL_ERROR_ILLEGAL_INPUT, NULL);
394  cpl_image *res = cpl_image_duplicate(cpl_imagelist_get_const(imlist, 0));
395  int i;
396  unsigned int mask = 0xffffffff;
397  for (i = 1; i < count; i++) {
398  int r = muse_cplimage_or(res, cpl_imagelist_get_const(imlist, i), mask);
399  if (r != CPL_ERROR_NONE) {
400  cpl_image_delete(res);
401  return NULL;
402  }
403  }
404  return res;
405 }
406 
407 /*----------------------------------------------------------------------------*/
424 /*----------------------------------------------------------------------------*/
425 cpl_mask *
426 muse_cplmask_adapt_to_image(const cpl_mask *aMask, const cpl_image *aImage)
427 {
428  cpl_ensure(aMask && aImage, CPL_ERROR_NULL_INPUT, NULL);
429 
430  /* find masked region */
431  enum corner { NONE = 0,
432  BOTTOMLEFT = 1, BOTTOMRIGHT = 2,
433  TOPRIGHT = 3, TOPLEFT = 4 };
434  const char *cnames[] = { "none",
435  "bottom left", "bottom right",
436  "top right", "top left" };
437  int nx = cpl_mask_get_size_x(aMask),
438  ny = cpl_mask_get_size_y(aMask),
439  nximage = cpl_image_get_size_x(aImage),
440  nyimage = cpl_image_get_size_y(aImage),
441  nmax = 0;
442  enum corner nmaxcorner = NONE;
443  int ncount = cpl_mask_count_window(aMask, 1, 1, nx/2, ny/2);
444  if (ncount > nmax) {
445  nmaxcorner = BOTTOMLEFT;
446  nmax = ncount;
447  }
448  ncount = cpl_mask_count_window(aMask, nx/2, 1, nx, ny/2);
449  if (ncount > nmax) {
450  nmaxcorner = BOTTOMRIGHT;
451  nmax = ncount;
452  }
453  ncount = cpl_mask_count_window(aMask, nx/2, ny/2, nx, ny);
454  if (ncount > nmax) {
455  nmaxcorner = TOPRIGHT;
456  nmax = ncount;
457  }
458  ncount = cpl_mask_count_window(aMask, 1, ny/2, nx/2, ny);
459  if (ncount > nmax) {
460  nmaxcorner = TOPLEFT;
461  nmax = ncount;
462  }
463  if (nmaxcorner == NONE) {
464  cpl_error_set_message(__func__, CPL_ERROR_DATA_NOT_FOUND, "No masked "
465  "quadrant found, cannot adapt %dx%d mask to %dx%d "
466  "image size!", nx, ny, nximage, nyimage);
467  return NULL;
468  }
469  cpl_msg_debug(__func__, "Adapting %dx%d mask in %s quadrant (%d masked pixels)"
470  " to %dx%d image", nx, ny, cnames[nmaxcorner], nmax,
471  nximage, nyimage);
472  /* extract masked quadrant */
473  cpl_mask *xmask;
474  switch (nmaxcorner) {
475  case BOTTOMLEFT:
476  xmask = cpl_mask_extract(aMask, 1, 1, nx/2, ny/2);
477  break;
478  case BOTTOMRIGHT:
479  xmask = cpl_mask_extract(aMask, nx/2, 1, nx, ny/2);
480  break;
481  case TOPRIGHT:
482  xmask = cpl_mask_extract(aMask, nx/2, ny/2, nx, ny);
483  break;
484  default: /* TOPLEFT */
485  xmask = cpl_mask_extract(aMask, 1, ny/2, nx/2, ny);
486  } /* switch */
487  /* track the extracted size */
488  nx = cpl_mask_get_size_x(xmask);
489  ny = cpl_mask_get_size_y(xmask);
490 
491  /* create new mask of the right size */
492  cpl_mask *outmask = cpl_mask_new(nximage, nyimage);
493  /* copy the extracted region into it, so that it aligns with the right corner */
494  cpl_error_code rc = CPL_ERROR_NONE;
495  switch (nmaxcorner) {
496  case BOTTOMLEFT:
497  rc = cpl_mask_copy(outmask, xmask, 1, 1);
498  break;
499  case BOTTOMRIGHT:
500  rc = cpl_mask_copy(outmask, xmask, nximage - nx + 1, 1);
501  break;
502  case TOPRIGHT:
503  rc = cpl_mask_copy(outmask, xmask, nximage - nx + 1, nyimage - ny + 1);
504  break;
505  default: /* TOPLEFT */
506  rc = cpl_mask_copy(outmask, xmask, 1, nyimage - ny + 1);
507  } /* switch */
508  cpl_mask_delete(xmask);
509  if (rc != CPL_ERROR_NONE) {
510  cpl_mask_delete(outmask);
511  cpl_error_set_message(__func__, rc, "Could not copy %dx%d quadrant with "
512  "masked region into new %dx%d mask", nx, ny,
513  nximage, nyimage);
514  return NULL;
515  }
516 
517  return outmask;
518 } /* muse_cplmask_adapt_to_image() */
519 
520 /*----------------------------------------------------------------------------*/
538 /*----------------------------------------------------------------------------*/
539 cpl_matrix *
540 muse_cplmatrix_multiply_create(const cpl_matrix *aMatrix1,
541  const cpl_matrix *aMatrix2)
542 {
543  cpl_ensure(aMatrix1 && aMatrix2, CPL_ERROR_NULL_INPUT, NULL);
544 
545  cpl_matrix *result = cpl_matrix_duplicate(aMatrix1);
546 
547  if (cpl_matrix_multiply(result, aMatrix2) != CPL_ERROR_NONE) {
548  cpl_error_set_where(__func__);
549  cpl_matrix_delete(result);
550  return NULL;
551  }
552  return result;
553 }
554 
555 /*----------------------------------------------------------------------------*/
571 /*----------------------------------------------------------------------------*/
572 cpl_array *
573 muse_cplmatrix_where(const cpl_matrix *aMatrix, double aValue,
575 {
576 
577  cpl_ensure(aMatrix, CPL_ERROR_NULL_INPUT, NULL);
578  cpl_ensure(aCondition, CPL_ERROR_NULL_INPUT, NULL);
579 
580  cpl_size i;
581  cpl_size count = 0;
582  cpl_size size = cpl_matrix_get_nrow(aMatrix) * cpl_matrix_get_ncol(aMatrix);
583 
584  const double *mdata = cpl_matrix_get_data_const(aMatrix);
585 
586  cpl_size *selection = cpl_malloc(size * sizeof *selection);
587  cpl_size *_selection = selection;
588 
589  for (i = 0; i < size; ++i) {
590  if (aCondition(mdata[i], aValue)) {
591  *_selection++ = i;
592  ++count;
593  }
594  }
595  cpl_array *where = cpl_array_new(count, CPL_TYPE_SIZE);
596  cpl_array_copy_data_cplsize(where, selection);
597  cpl_free(selection);
598 
599  return where;
600 
601 }
602 
603 /*----------------------------------------------------------------------------*/
623 /*----------------------------------------------------------------------------*/
624 cpl_matrix *
625 muse_cplmatrix_extract_selected(const cpl_matrix *aMatrix,
626  const cpl_array *aIndices)
627 {
628  cpl_ensure(aMatrix, CPL_ERROR_NULL_INPUT, NULL);
629  cpl_ensure(aIndices, CPL_ERROR_NULL_INPUT, NULL);
630  cpl_ensure(cpl_array_get_type(aIndices) == CPL_TYPE_SIZE,
631  CPL_ERROR_INVALID_TYPE, NULL);
632 
633  cpl_size maxpos = cpl_matrix_get_nrow(aMatrix) * cpl_matrix_get_ncol(aMatrix);
634  cpl_size sz = cpl_array_get_size(aIndices);
635  cpl_matrix *subset = cpl_matrix_new(1, sz);
636 
637  double *sdata = cpl_matrix_get_data(subset);
638  const double *mdata = cpl_matrix_get_data_const(aMatrix);
639  const cpl_size *idata = cpl_array_get_data_cplsize_const(aIndices);
640 
641  cpl_size i;
642  for (i = 0; i < sz; ++i) {
643  if ((idata[i] >= 0) && (idata[i] < maxpos)) {
644  *sdata++ = mdata[idata[i]];
645  }
646  }
647  return subset;
648 }
649 
650 /*----------------------------------------------------------------------------*/
659 /*----------------------------------------------------------------------------*/
660 double
661 muse_cplvector_get_adev_const(const cpl_vector *aVector, double aCenter)
662 {
663  cpl_ensure(aVector, CPL_ERROR_NULL_INPUT, 0.);
664  double mdev = 0;
665  cpl_size i, n = cpl_vector_get_size(aVector);
666  for (i = 0; i < n; i++) {
667  mdev += fabs(cpl_vector_get(aVector, i) - aCenter);
668  }
669  return mdev / (double)n; /* return normalized value */
670 } /* muse_cplvector_get_adev_const() */
671 
672 /*----------------------------------------------------------------------------*/
685 /*----------------------------------------------------------------------------*/
686 double
687 muse_cplvector_get_median_dev(cpl_vector *aVector, double *aMedian)
688 {
689  cpl_ensure(aVector, CPL_ERROR_NULL_INPUT, 0.);
690  double median = cpl_vector_get_median(aVector),
691  mdev = 0.;
692  cpl_size i, n = cpl_vector_get_size(aVector);
693  for (i = 0; i < n; i++) {
694  mdev += fabs(cpl_vector_get(aVector, i) - median);
695  }
696  if (aMedian) {
697  *aMedian = median;
698  }
699  return mdev / (double)n; /* return normalized value */
700 } /* muse_cplvector_get_median_dev() */
701 
702 /*----------------------------------------------------------------------------*/
716 /*----------------------------------------------------------------------------*/
717 double
719 {
720  double sqr = 0;
721  double median = cpl_vector_get_median_const(aVector);
722  cpl_vector *v = cpl_vector_duplicate(aVector), *v2;
723  int i, splitindex = 0;
724 
725  cpl_vector_sort(v, +1);
726 #if DEBUG_SQR
727  cpl_vector_dump(v, stdout);
728  fflush(stdout);
729  printf("median=%f%d\n", median);
730  fflush(stdout);
731 #endif
732  /* search for point to split the sorted vector, better just do it linearly */
733  splitindex = cpl_vector_find(v, median);
734 
735  /* copy upper half into new vector */
736  v2 = cpl_vector_new(cpl_vector_get_size(v) - splitindex - 1);
737 #if DEBUG_SQR
738  printf("Copying elements %d to %d\n", splitindex+1, cpl_vector_get_size(v)-1);
739 #endif
740  for (i = splitindex; i < cpl_vector_get_size(v); i++){
741 #if DEBUG_SQR
742  printf(" %d %f\n", i+1, cpl_vector_get(v, i));
743 #endif
744  cpl_vector_set(v2, i-splitindex, cpl_vector_get(v, i));
745  }
746 #if DEBUG_SQR
747  printf("\n");
748  fflush(stdout);
749 #endif
750  sqr = cpl_vector_get_median(v2); /* the upper median, non const OK */
751  cpl_vector_delete(v2);
752 
753  /* copy lower half into new vector */
754  v2 = cpl_vector_new(splitindex - 1);
755 #if DEBUG_SQR
756  printf("Copying elements %d to %d\n", 1, splitindex+1);
757 #endif
758  for (i = 0; i <= splitindex; i++) {
759 #if DEBUG_SQR
760  printf(" %d %f\n", i+1, cpl_vector_get(v, i));
761 #endif
762  cpl_vector_set(v2, i, cpl_vector_get(v, i));
763  }
764 #if DEBUG_SQR
765  printf("\n");
766  fflush(stdout);
767 #endif
768  sqr -= cpl_vector_get_median(v2); /* subtract the lower median, non const OK */
769  cpl_vector_delete(v2);
770 
771  return sqr/2.0; /* divide by two to get semiquartile range */
772 } /* muse_cplvector_get_semiquartile() */
773 
774 /*----------------------------------------------------------------------------*/
794 /*----------------------------------------------------------------------------*/
795 cpl_error_code
796 muse_cplvector_threshold(cpl_vector *aVec, double aLoCut, double aHiCut,
797  double aLoVal, double aHiVal)
798 {
799  cpl_ensure_code(aVec, CPL_ERROR_NULL_INPUT);
800  cpl_ensure_code(aLoCut <= aHiCut, CPL_ERROR_ILLEGAL_INPUT);
801 
802  double *data = cpl_vector_get_data(aVec);
803  int i, n = cpl_vector_get_size(aVec);
804  for (i = 0; i < n; i++) {
805  if (data[i] > aHiCut) {
806  data[i] = aHiVal;
807  } else if (data[i] < aLoCut) {
808  data[i] = aLoVal;
809  }
810  } /* for i (vector elements) */
811 
812  return CPL_ERROR_NONE;
813 }
814 
815 /*----------------------------------------------------------------------------*/
827 /*----------------------------------------------------------------------------*/
828 cpl_error_code
829 muse_cplvector_erase_element(cpl_vector *aVector, int aElement)
830 {
831  cpl_ensure_code(aVector, CPL_ERROR_NULL_INPUT);
832  int size = cpl_vector_get_size(aVector);
833  cpl_ensure_code(aElement >= 0 && aElement < size, CPL_ERROR_ILLEGAL_INPUT);
834 
835  if (aElement < size - 1) {
836  /* if it's not the last element, we need to move the remaining *
837  * elements so that they overwrite the one to be removed */
838  double *data = cpl_vector_get_data(aVector);
839  memmove(&data[aElement], &data[aElement+1],
840  (size-1 - aElement) * sizeof(double));
841  }
842 
843  /* resize the vector to account for the removed element */
844  return cpl_vector_set_size(aVector, size - 1);
845 } /* muse_cplvector_erase_element() */
846 
847 /*----------------------------------------------------------------------------*/
855 /*----------------------------------------------------------------------------*/
856 cpl_size
857 muse_cplvector_count_unique(const cpl_vector *aVector)
858 {
859  cpl_ensure(aVector, CPL_ERROR_NULL_INPUT, -1);
860  cpl_vector *sorted = cpl_vector_duplicate(aVector);
861  cpl_vector_sort(sorted, CPL_SORT_ASCENDING);
862  double *data = cpl_vector_get_data(sorted);
863  cpl_size i, n = cpl_vector_get_size(sorted),
864  nunique = 1; /* first element is always unique */
865  for (i = 1; i < n; i++) { /* start at 2nd element */
866  if (data[i] != data[i - 1]) {
867  nunique++;
868  }
869  } /* for i (all elements in sorted vector) */
870  cpl_vector_delete(sorted);
871  return nunique;
872 } /* muse_cplvector_count_unique() */
873 
874 /*----------------------------------------------------------------------------*/
882 /*----------------------------------------------------------------------------*/
883 cpl_vector *
884 muse_cplvector_get_unique(const cpl_vector *aVector)
885 {
886  cpl_ensure(aVector, CPL_ERROR_NULL_INPUT, NULL);
887  cpl_vector *sorted = cpl_vector_duplicate(aVector);
888  cpl_vector_sort(sorted, CPL_SORT_ASCENDING);
889  double *data = cpl_vector_get_data(sorted);
890  cpl_size i, n = cpl_vector_get_size(sorted),
891  iunique = 0;
892  cpl_vector *vunique = cpl_vector_new(n);
893  cpl_vector_set(vunique, iunique++, data[0]); /* set unique first element */
894  for (i = 1; i < n; i++) { /* start at 2nd element */
895  if (data[i] != data[i - 1]) {
896  cpl_vector_set(vunique, iunique++, data[i]);
897  }
898  } /* for i (all elements in sorted vector) */
899  cpl_vector_delete(sorted);
900  cpl_vector_set_size(vunique, iunique);
901  return vunique;
902 } /* muse_cplvector_get_unique() */
903 
904 /*----------------------------------------------------------------------------*/
914 /*----------------------------------------------------------------------------*/
915 cpl_table *
916 muse_cpltable_new(const muse_cpltable_def *aDef, cpl_size aLength)
917 {
918  cpl_ensure(aDef, CPL_ERROR_NULL_INPUT, NULL);
919  cpl_table *res = cpl_table_new(aLength);
920  for (; aDef->name != NULL; aDef++) {
921  cpl_error_code rc = CPL_ERROR_NONE;
922  if (aDef->type & CPL_TYPE_POINTER) {
923  rc = cpl_table_new_column_array(res, aDef->name, aDef->type, 2);
924  } else {
925  rc = cpl_table_new_column(res, aDef->name, aDef->type);
926  }
927  if (rc != CPL_ERROR_NONE) {
928  cpl_table_delete(res);
929  return NULL;
930  }
931  if (aDef->unit != NULL) {
932  if (cpl_table_set_column_unit(res, aDef->name,
933  aDef->unit) != CPL_ERROR_NONE) {
934  return NULL;
935  }
936  }
937  if (aDef->format != NULL) {
938  if (cpl_table_set_column_format(res, aDef->name,
939  aDef->format) != CPL_ERROR_NONE) {
940  return NULL;
941  }
942  }
943  }
944  return res;
945 }
946 
947 /*----------------------------------------------------------------------------*/
959 /*----------------------------------------------------------------------------*/
960 cpl_table *
961 muse_cpltable_load(const char *aFile, const char *aExtension,
962  const muse_cpltable_def aDefinition[])
963 {
964  int extension = cpl_fits_find_extension(aFile, aExtension);
965  if (extension <= 0) {
966  cpl_error_set_message(__func__, cpl_error_get_code(), "%s['%s']: "
967  "extension not found by EXTNAME", aFile, aExtension);
968  return NULL;
969  }
970  cpl_msg_debug(__func__, "Loading %s['%s'] from extension %d", aFile,
971  aExtension, extension);
972  cpl_table *tbl = cpl_table_load(aFile, extension, 1);
973  if (muse_cpltable_check(tbl, aDefinition) != CPL_ERROR_NONE) {
974  cpl_table_delete(tbl);
975  return NULL;
976  }
977  return tbl;
978 } /* muse_cpltable_load() */
979 
980 /*----------------------------------------------------------------------------*/
997 /*----------------------------------------------------------------------------*/
998 cpl_error_code
999 muse_cpltable_append_file(const cpl_table *aTable, const char *aFile,
1000  const char *aExtension,
1001  const muse_cpltable_def aDefinition[]) {
1002  cpl_ensure_code(aTable != NULL, CPL_ERROR_NULL_INPUT);
1003  cpl_ensure_code(aFile != NULL, CPL_ERROR_NULL_INPUT);
1004  cpl_ensure_code(aExtension != NULL, CPL_ERROR_NULL_INPUT);
1005  cpl_error_code r = muse_cpltable_check(aTable, aDefinition);
1006  if (r != CPL_ERROR_NONE) {
1007  cpl_msg_error(__func__, " %s['%s'] Table format error", aFile, aExtension);
1008  cpl_error_set(__func__, r);
1009  return r;
1010  }
1011  cpl_propertylist *props = cpl_propertylist_new();
1012  cpl_propertylist_update_string(props, "EXTNAME", aExtension);
1013  r = cpl_table_save(aTable, NULL, props, aFile, CPL_IO_EXTEND);
1014  cpl_propertylist_delete(props);
1015  if (r != CPL_ERROR_NONE) {
1016  cpl_msg_error(__func__, "%s[%s]: %s", aFile, aExtension,
1017  cpl_error_get_message());
1018  }
1019  return r;
1020 }
1021 
1022 
1023 /*----------------------------------------------------------------------------*/
1029 /*----------------------------------------------------------------------------*/
1030 cpl_error_code
1031 muse_cpltable_check(const cpl_table *aTable, const muse_cpltable_def *aDef)
1032 {
1033  if (aTable == NULL) {
1034  cpl_msg_error(__func__, "NULL table");
1035  cpl_error_set(__func__, CPL_ERROR_NULL_INPUT);
1036  return CPL_ERROR_NULL_INPUT;
1037  }
1038  if (aDef == NULL) {
1039  return CPL_ERROR_NONE;
1040  }
1041  cpl_error_code rc = CPL_ERROR_NONE;
1042  for (; aDef->name != NULL; aDef++) {
1043  if (!cpl_table_has_column(aTable, aDef->name)) {
1044  if (aDef->required) {
1045  rc = CPL_ERROR_ILLEGAL_INPUT;
1046  cpl_error_set_message(__func__, rc, "table column '%s' not found",
1047  aDef->name);
1048  }
1049  continue;
1050  }
1051  cpl_type coltype = cpl_table_get_column_type(aTable, aDef->name);
1052  if (((coltype | CPL_TYPE_POINTER) != (aDef->type | CPL_TYPE_POINTER)) ||
1053  ((coltype & CPL_TYPE_POINTER) && !(aDef->type & CPL_TYPE_POINTER))) {
1054  rc = CPL_ERROR_ILLEGAL_INPUT;
1055  cpl_error_set_message(__func__, rc,
1056  "table column '%s' format '%s' is not '%s'",
1057  aDef->name, cpl_type_get_name(coltype),
1058  cpl_type_get_name(aDef->type));
1059  }
1060  }
1061  return rc;
1062 } /* muse_cpltable_check() */
1063 
1064 /*----------------------------------------------------------------------------*/
1081 /*----------------------------------------------------------------------------*/
1082 cpl_array *
1083 muse_cpltable_extract_column(cpl_table *aTable, const char *aColumn)
1084 {
1085  cpl_ensure(aTable && aColumn, CPL_ERROR_NULL_INPUT, NULL);
1086  cpl_size nRows = cpl_table_get_nrow(aTable);
1087 
1088  cpl_type type = cpl_table_get_column_type(aTable, aColumn);
1089  if (nRows == 0) {
1090  return cpl_array_new(0, type);
1091  }
1092  if (type == CPL_TYPE_DOUBLE) {
1093  double *src = cpl_table_get_data_double(aTable, aColumn);
1094  return cpl_array_wrap_double(src, nRows);
1095  } else if (type == CPL_TYPE_FLOAT) {
1096  float *src = cpl_table_get_data_float(aTable, aColumn);
1097  return cpl_array_wrap_float(src, nRows);
1098  } else if (type == CPL_TYPE_INT) {
1099  int *src = cpl_table_get_data_int(aTable, aColumn);
1100  return cpl_array_wrap_int(src, nRows);
1101  } else {
1102  cpl_error_set(__func__, CPL_ERROR_ILLEGAL_INPUT);
1103  cpl_msg_error(__func__, "%s: %i - %s", cpl_error_get_message(), type,
1104  cpl_type_get_name(type));
1105  return NULL;
1106  }
1107 }
1108 
1109 /*----------------------------------------------------------------------------*/
1119 /*----------------------------------------------------------------------------*/
1120 cpl_error_code
1121 muse_cpltable_copy_array(cpl_table *aTable, const char *aColumn,
1122  const cpl_array *aArray)
1123 {
1124  cpl_ensure_code(aTable && aColumn && aArray, CPL_ERROR_NULL_INPUT);
1125  cpl_size n_rows = cpl_table_get_nrow(aTable);
1126  cpl_size i;
1127  for (i = 0; i < n_rows; i++) {
1128  int flag;
1129  double d = cpl_array_get(aArray, i, &flag);
1130  if (flag == 0) {
1131  cpl_table_set(aTable, aColumn, i, d);
1132  } else {
1133  cpl_table_set_invalid(aTable, aColumn, i);
1134  }
1135  }
1136  return CPL_ERROR_NONE;
1137 }
1138 
1139 /*----------------------------------------------------------------------------*/
1149 /*----------------------------------------------------------------------------*/
1150 cpl_array *
1151 muse_cpltable_get_array_copy(cpl_table *aTable, const char *aColumn,
1152  cpl_size aRow)
1153 {
1154  cpl_ensure(aTable && aColumn, CPL_ERROR_NULL_INPUT, NULL);
1155  if (cpl_table_get_column_type(aTable, aColumn) & CPL_TYPE_POINTER) {
1156  return cpl_array_duplicate(cpl_table_get_array(aTable, aColumn, aRow));
1157  } else {
1158  cpl_array *res
1159  = cpl_array_new(1, cpl_table_get_column_type(aTable, aColumn));
1160  int flag;
1161  cpl_array_set(res, 0, cpl_table_get(aTable, aColumn, aRow, &flag));
1162  if (flag) {
1163  cpl_array_delete(res);
1164  return NULL;
1165  } else {
1166  return res;
1167  }
1168  }
1169 }
1170 /*----------------------------------------------------------------------------*/
1184 /*----------------------------------------------------------------------------*/
1185 
1186 cpl_size
1187 muse_cpltable_find_sorted(const cpl_table *aTable, const char *aColumn,
1188  double aValue) {
1189  cpl_ensure(aTable && aColumn, CPL_ERROR_NULL_INPUT, 0);
1190  cpl_array *array = muse_cpltable_extract_column((cpl_table *)aTable, aColumn);
1191  cpl_size res = muse_cplarray_find_sorted(array, aValue);
1192  cpl_array_unwrap(array);
1193  return res;
1194 }
1195 
1196 /*----------------------------------------------------------------------------*/
1204 /*----------------------------------------------------------------------------*/
1205 cpl_array *
1206 muse_cplarray_new_from_image(const cpl_image *aImage) {
1207  cpl_size nx = cpl_image_get_size_x(aImage);
1208  cpl_size ny = cpl_image_get_size_y(aImage);
1209  cpl_array *array = cpl_array_new(nx*ny, cpl_image_get_type(aImage));
1210  cpl_size i = 0;
1211  cpl_size iy;
1212  for (iy = 1; iy <= ny; iy++) {
1213  int ix;
1214  for (ix = 1; ix <= nx; ix++, i++) {
1215  int rej;
1216  double d = cpl_image_get(aImage, ix, iy, &rej);
1217  cpl_array_set(array, i, d);
1218  if (rej) {
1219  cpl_array_set_invalid(array, i);
1220  }
1221  }
1222  }
1223  return array;
1224 }
1225 
1226 /*----------------------------------------------------------------------------*/
1239 /*----------------------------------------------------------------------------*/
1240 cpl_error_code
1241 muse_cplarray_poly1d(cpl_array *aArray, const cpl_array *aCoeff)
1242 {
1243  cpl_ensure_code(aArray && aCoeff, CPL_ERROR_NULL_INPUT);
1244  const cpl_size nrows = cpl_array_get_size(aArray);
1245  cpl_size order = cpl_array_get_size(aCoeff);
1246  if (order == 0) {
1247  cpl_array_fill_window(aArray, 0, nrows, 0.0);
1248  return CPL_ERROR_NONE;
1249  }
1250  order--;
1251  cpl_array *x = cpl_array_duplicate(aArray);
1252  cpl_array_fill_window(aArray, 0, nrows, cpl_array_get(aCoeff, order, NULL));
1253 
1254  int k;
1255  for (k = order-1; k >= 0; k--) {
1256  cpl_array_multiply(aArray, x);
1257  cpl_array_add_scalar(aArray, cpl_array_get(aCoeff, k, NULL));
1258  }
1259 
1260  cpl_array_delete(x);
1261 
1262  return CPL_ERROR_NONE;
1263 }
1264 
1265 /*----------------------------------------------------------------------------*/
1277 /*----------------------------------------------------------------------------*/
1278 double
1279 muse_cplarray_poly1d_double(double aDouble, const cpl_array *aCoeff)
1280 {
1281  cpl_ensure(aCoeff, CPL_ERROR_NULL_INPUT, NAN);
1282  cpl_size order = cpl_array_get_size(aCoeff);
1283  if (order == 0) {
1284  return 0.0;
1285  }
1286  order--;
1287  double res = cpl_array_get(aCoeff, order, NULL);
1288  int k;
1289  for (k = order-1; k >= 0; k--) {
1290  res = res * aDouble + cpl_array_get(aCoeff, k, NULL);
1291  }
1292  return res;
1293 }
1294 
1295 /*----------------------------------------------------------------------------*/
1304 /*----------------------------------------------------------------------------*/
1305 cpl_error_code
1306 muse_cplarray_dump_name(const cpl_array *aArray, const char *aName)
1307 {
1308  cpl_ensure_code(aArray && aName, CPL_ERROR_NULL_INPUT);
1309  cpl_size i, size = cpl_array_get_size(aArray);
1310  for (i = 0; i < size; i++) {
1311  printf("%s[%"CPL_SIZE_FORMAT"] = %g\n", aName, i,
1312  cpl_array_get(aArray, i, NULL));
1313  }
1314  return CPL_ERROR_NONE;
1315 }
1316 
1317 /*----------------------------------------------------------------------------*/
1323 /*----------------------------------------------------------------------------*/
1324 cpl_error_code
1326 {
1327  cpl_ensure_code(aArray != NULL, CPL_ERROR_NULL_INPUT);
1328  cpl_size n = cpl_array_get_size(aArray);
1329  cpl_size n_val = n - cpl_array_count_invalid(aArray);
1330 #if 0 /* DEBUG */
1331  cpl_msg_debug(__func__, "size = %li, %li valid", (long)n, (long)n_val);
1332 #endif
1333  if (n_val == n) {
1334  return CPL_ERROR_NONE;
1335  }
1336  cpl_size i;
1337  cpl_size idx = 0;
1338  for (i = 0; (i < n) && (idx < n_val); i++) {
1339  int rej;
1340  double d = cpl_array_get(aArray, i, &rej);
1341  if (!rej) {
1342  if (idx < i) {
1343  cpl_array_set(aArray, idx, d);
1344  }
1345  idx++;
1346  }
1347  }
1348  cpl_array_set_size(aArray, n_val);
1349  return CPL_ERROR_NONE;
1350 }
1351 
1352 /*---------------------------------------------------------------------------*/
1367 /*---------------------------------------------------------------------------*/
1368 cpl_size
1369 muse_cplarray_erase_outliers(cpl_array *aArray, const cpl_bivector *aHistogram,
1370  cpl_size aGap, double aLimit)
1371 {
1372  cpl_ensure(aArray && aHistogram, CPL_ERROR_NULL_INPUT, -1);
1373  /* test for numerical array */
1374  int err;
1375  double value = cpl_array_get(aArray, 0, &err);
1376  cpl_ensure(err >= 0, CPL_ERROR_ILLEGAL_INPUT, -2);
1377 
1378  /* start at the peak of the histogram */
1379  const double *hpos = cpl_bivector_get_x_data_const(aHistogram),
1380  *hval = cpl_bivector_get_y_data_const(aHistogram);
1381  cpl_size nhist = cpl_bivector_get_size(aHistogram);
1382  cpl_array *ahist = cpl_array_wrap_double((double *)hval, nhist);
1383  cpl_size imax;
1384  cpl_array_get_maxpos(ahist, &imax);
1385  cpl_array_unwrap(ahist);
1386 
1387  /* go to lower values in the histogram, search for the first gap */
1388  double loval = hpos[0],
1389  hival = hpos[nhist - 1];
1390  cpl_size i, nlow = 0;
1391  for (i = imax; i >= 0; i--) {
1392  if (hval[i] <= aLimit) {
1393  if (nlow == 0) { /* keep this as the initial low value */
1394  loval = hpos[i];
1395  }
1396  nlow++;
1397  if (nlow == aGap) { /* gap already wide enough */
1398  break;
1399  }
1400  } else if (nlow > 0) {
1401  nlow = 0; /* gap not wide enough after all */
1402  loval = hpos[0];
1403  }
1404  } /* for i */
1405  /* same search now to higher histogram values */
1406  for (i = imax; i < nhist; i++) {
1407  if (hval[i] <= aLimit) {
1408  if (nlow == 0) { /* keep this as the initial low value */
1409  hival = hpos[i];
1410  }
1411  nlow++;
1412  if (nlow == aGap) { /* gap already wide enough */
1413  break;
1414  }
1415  } else if (nlow > 0) {
1416  nlow = 0; /* gap not wide enough after all */
1417  hival = hpos[nhist - 1];
1418  }
1419  } /* for i */
1420  cpl_msg_debug(__func__, "Histogram gaps (%"CPL_SIZE_FORMAT" consecutive "
1421  "entries <= %f) at %f and %f", aGap, aLimit, loval, hival);
1422 
1423  /* now go through the array, and set values larger *
1424  * or smaller than these extremes to invalid */
1425  cpl_size idx, narray = cpl_array_get_size(aArray);
1426  for (idx = 0; idx < narray; idx++) {
1427  value = cpl_array_get(aArray, idx, NULL);
1428  if (value > hival || value < loval) {
1429  cpl_array_set_invalid(aArray, idx);
1430  }
1431  } /* for idx */
1432 
1433  /* finally count them and then remove all invalid ones */
1434  cpl_size nbad = cpl_array_count_invalid(aArray);
1436  return nbad;
1437 } /* muse_cplarray_erase_outliers() */
1438 
1439 
1440 /*----------------------------------------------------------------------------*/
1441 /* Helper functions for quicksort */
1442 /*----------------------------------------------------------------------------*/
1444 static int cmp_double_asc(const void *p1, const void *p2) {
1445  double d = (*(const double *)p1 - *(const double *)p2);
1446  return (d < 0)?-1:(d>0)?1:0;
1447 }
1449 static int cmp_double_desc(const void *p1, const void *p2) {
1450  double d = (*(const double *)p1 - *(const double *)p2);
1451  return (d < 0)?1:(d>0)?-1:0;
1452 }
1454 static int cmp_float_asc(const void *p1, const void *p2) {
1455  float d = (*(const float *)p1 - *(const float *)p2);
1456  return (d < 0)?-1:(d>0)?1:0;
1457 }
1459 static int cmp_float_desc(const void *p1, const void *p2) {
1460  float d = (*(const float *)p1 - *(const float *)p2);
1461  return (d < 0)?1:(d>0)?-1:0;
1462 }
1464 static int cmp_int_asc(const void *p1, const void *p2) {
1465  return (*(const int *)p1 - *(const int *)p2);
1466 }
1468 static int cmp_int_desc(const void *p1, const void *p2) {
1469  return (*(const int *)p2 - *(const int *)p1);
1470 }
1471 
1473 static int cmp_long_asc(const void *p1, const void *p2) {
1474  return (*(const long *)p1 - *(const long *)p2);
1475 }
1477 static int cmp_long_desc(const void *p1, const void *p2) {
1478  return (*(const long *)p2 - *(const long *)p1);
1479 }
1480 
1482 static int cmp_string_asc(const void *p1, const void *p2) {
1483  return strcmp(*(const char **)p1, *(const char **)p2);
1484 }
1486 static int cmp_string_desc(const void *p1, const void *p2) {
1487  return strcmp(*(const char **)p2, *(const char **)p1);
1488 }
1489 
1490 /*----------------------------------------------------------------------------*/
1500 /*----------------------------------------------------------------------------*/
1501 cpl_error_code
1502 muse_cplarray_sort(cpl_array *aArray, cpl_boolean aOrder)
1503 {
1504  cpl_ensure_code(aArray != NULL, CPL_ERROR_NULL_INPUT);
1505  cpl_ensure_code(!cpl_array_has_invalid(aArray), CPL_ERROR_NULL_INPUT);
1506 
1507  cpl_size n = cpl_array_get_size(aArray);
1508  if (cpl_array_get_type(aArray) == CPL_TYPE_DOUBLE) {
1509  double *d = cpl_array_get_data_double(aArray);
1510  qsort(d, n, sizeof(double), (aOrder)?cmp_double_asc:cmp_double_desc);
1511  return CPL_ERROR_NONE;
1512  } else if (cpl_array_get_type(aArray) == CPL_TYPE_FLOAT) {
1513  float *d = cpl_array_get_data_float(aArray);
1514  qsort(d, n, sizeof(float), (aOrder)?cmp_float_asc:cmp_float_desc);
1515  return CPL_ERROR_NONE;
1516  } else if (cpl_array_get_type(aArray) == CPL_TYPE_INT) {
1517  int *d = cpl_array_get_data_int(aArray);
1518  qsort(d, n, sizeof(int), (aOrder)?cmp_int_asc:cmp_int_desc);
1519  return CPL_ERROR_NONE;
1520  } else if (cpl_array_get_type(aArray) == CPL_TYPE_LONG) {
1521  long *d = cpl_array_get_data_long(aArray);
1522  qsort(d, n, sizeof(long), (aOrder)?cmp_long_asc:cmp_long_desc);
1523  return CPL_ERROR_NONE;
1524  } else if (cpl_array_get_type(aArray) == CPL_TYPE_STRING) {
1525  char **d = cpl_array_get_data_string(aArray);
1526  qsort(d, n, sizeof(char *), (aOrder)?cmp_string_asc:cmp_string_desc);
1527  return CPL_ERROR_NONE;
1528  } else {
1529  return CPL_ERROR_ILLEGAL_INPUT;
1530  }
1531 }
1532 
1533 /*---------------------------------------------------------------------------*/
1552 /*---------------------------------------------------------------------------*/
1553 cpl_bivector *
1554 muse_cplarray_histogram(const cpl_array *aArray, double aWidth,
1555  double aMin, double aMax)
1556 {
1557  cpl_ensure(aArray, CPL_ERROR_NULL_INPUT, NULL);
1558  /* test for numerical array */
1559  int err;
1560  double value = cpl_array_get(aArray, 0, &err);
1561  cpl_ensure(err >= 0, CPL_ERROR_INVALID_TYPE, NULL);
1562  if (!isnan(aMin) && !isnan(aMax) && aMin >= aMax) { /* inverse extremes */
1563  cpl_error_set(__func__, CPL_ERROR_ILLEGAL_INPUT);
1564  return NULL;
1565  }
1566  if (isnan(aMin)) {
1567  aMin = cpl_array_get_min(aArray);
1568  }
1569  if (isnan(aMax)) {
1570  aMax = cpl_array_get_max(aArray);
1571  }
1572  cpl_size hlen = lround((aMax - aMin) / aWidth) + 1;
1573  cpl_bivector *histogram = cpl_bivector_new(hlen);
1574 
1575  /* fill histogram positions */
1576  double *hpos = cpl_bivector_get_x_data(histogram);
1577  cpl_size i;
1578  for (i = 0; i < hlen; i++) {
1579  hpos[i] = i * aWidth + aMin;
1580  } /* for i */
1581 
1582  /* fill histogram values */
1583  double *hval = cpl_bivector_get_y_data(histogram);
1584  /* histogram has at least zero everywhere */
1585  cpl_vector_fill(cpl_bivector_get_y(histogram), 0.);
1586  cpl_size n = cpl_array_get_size(aArray);
1587  for (i = 0; i < n; i++) {
1588  value = cpl_array_get(aArray, i, &err);
1589  if (err) {
1590  continue;
1591  }
1592  /* find histogram index */
1593  cpl_size idx = lround((value - aMin) / aWidth);
1594  if (idx >= hlen || idx < 0) {
1595  continue;
1596  }
1597  /* add one to the histogram at the respective index */
1598  hval[idx] += 1;
1599  } /* for i */
1600 #if 0
1601  printf("histogram %f...%f / %f\n", aMin, aMax, aWidth);
1602  cpl_bivector_dump(histogram, stdout);
1603  fflush(stdout);
1604 #endif
1605  return histogram;
1606 } /* muse_cplarray_histogram() */
1607 
1608 /*----------------------------------------------------------------------------*/
1621 /*----------------------------------------------------------------------------*/
1622 cpl_size
1623 muse_cplarray_find_sorted(const cpl_array *aArray, double aValue)
1624 {
1625  cpl_ensure(aArray, CPL_ERROR_NULL_INPUT, 0);
1626  cpl_size min = 0;
1627  cpl_size max = cpl_array_get_size(aArray);
1628  cpl_type type = cpl_array_get_type(aArray);
1629  if (type == CPL_TYPE_DOUBLE) {
1630  const double *data = cpl_array_get_data_double_const(aArray);
1631  while (max - min > 1) {
1632  int i = (max + min)/2;
1633  if (data[i] > aValue) {
1634  max = i;
1635  } else {
1636  min = i;
1637  }
1638  }
1639  } else if (type == CPL_TYPE_FLOAT) {
1640  const float *data = cpl_array_get_data_float_const(aArray);
1641  while (max - min > 1) {
1642  int i = (max + min)/2;
1643  if (data[i] > aValue) {
1644  max = i;
1645  } else {
1646  min = i;
1647  }
1648  }
1649  } else if (type == CPL_TYPE_INT) {
1650  const int *data = cpl_array_get_data_int_const(aArray);
1651  while (max - min > 1) {
1652  int i = (max + min)/2;
1653  if (data[i] > aValue) {
1654  max = i;
1655  } else {
1656  min = i;
1657  }
1658  }
1659  } else {
1660  cpl_msg_error(__func__, "illegal type %i", type);
1661  cpl_error_set(__func__, CPL_ERROR_ILLEGAL_INPUT);
1662  return 0;
1663  }
1664  return min;
1665 }
1666 
1667 /*----------------------------------------------------------------------------*/
1682 /*----------------------------------------------------------------------------*/
1683 cpl_boolean
1684 muse_cplarray_has_duplicate(const cpl_array *aArray)
1685 {
1686  cpl_ensure(aArray, CPL_ERROR_NULL_INPUT, CPL_FALSE);
1687  cpl_type type = cpl_array_get_type(aArray);
1688  switch (type) {
1689  case CPL_TYPE_INT:
1690  case CPL_TYPE_LONG:
1691  case CPL_TYPE_LONG_LONG:
1692  case CPL_TYPE_SIZE:
1693  break;
1694  default:
1695  cpl_error_set(__func__, CPL_ERROR_UNSUPPORTED_MODE);
1696  return CPL_FALSE;
1697  }
1698 
1699  cpl_size idx, n = cpl_array_get_size(aArray);
1700  for (idx = 0; idx < n - 1; idx++) {
1701  int err;
1702  cpl_size v1 = cpl_array_get(aArray, idx, &err);
1703  if (err) { /* invalid somehow, skip this one */
1704  continue;
1705  }
1706  cpl_size idx2;
1707  for (idx2 = idx + 1; idx2 < n; idx2++) {
1708  cpl_size v2 = cpl_array_get(aArray, idx2, &err);
1709  if (err) { /* invalid somehow, skip this one */
1710  continue;
1711  }
1712  if (v2 == v1) {
1713 #if 0
1714  cpl_msg_debug(__func__, "entry[%"CPL_SIZE_FORMAT"] == entry[%"
1715  CPL_SIZE_FORMAT"] == %"CPL_SIZE_FORMAT, idx, idx2, v1);
1716 #endif
1717  return CPL_TRUE;
1718  }
1719  } /* for idx2 (array indices starting after idx) */
1720  } /* for idx (all array indices but the last) */
1721  return CPL_FALSE;
1722 } /* muse_cplarray_has_duplicate() */
1723 
1724 /*----------------------------------------------------------------------------*/
1737 /*----------------------------------------------------------------------------*/
1738 cpl_array *
1739 muse_cplarray_extract(cpl_array *aArray, cpl_size aStart, cpl_size aCount)
1740 {
1741  cpl_size nrows = cpl_array_get_size(aArray);
1742  if (aCount > nrows - aStart) {
1743  aCount = nrows - aStart;
1744  }
1745  cpl_type type = cpl_array_get_type(aArray);
1746  if (type == CPL_TYPE_DOUBLE) {
1747  return cpl_array_wrap_double(cpl_array_get_data_double(aArray) + aStart,
1748  aCount);
1749  } else if (type == CPL_TYPE_FLOAT) {
1750  return cpl_array_wrap_float(cpl_array_get_data_float(aArray) + aStart,
1751  aCount);
1752  } else if (type == CPL_TYPE_INT) {
1753  return cpl_array_wrap_int(cpl_array_get_data_int(aArray) + aStart,
1754  aCount);
1755  } else {
1756  cpl_error_set(__func__, CPL_ERROR_ILLEGAL_INPUT);
1757  return NULL;
1758  }
1759 }
1760 /*----------------------------------------------------------------------------*/
1774 /*----------------------------------------------------------------------------*/
1775 cpl_error_code
1776 muse_cplarray_add_window(cpl_array *aDest, cpl_size aStart,
1777  const cpl_array *aArray)
1778 {
1779  cpl_ensure_code(aDest && aArray, CPL_ERROR_NULL_INPUT);
1780  cpl_size count = cpl_array_get_size(aArray);
1781  cpl_array *destArray = muse_cplarray_extract(aDest, aStart, count);
1782  if (destArray == NULL) {
1783  return CPL_ERROR_ILLEGAL_INPUT;
1784  }
1785  cpl_array_add(destArray, aArray);
1786  cpl_array_unwrap(destArray);
1787 
1788  return CPL_ERROR_NONE;
1789 }
1790 
1791 /*----------------------------------------------------------------------------*/
1801 /*----------------------------------------------------------------------------*/
1802 cpl_array *
1803 muse_cplarray_diff(const cpl_array *aArray, int aOffset)
1804 {
1805  cpl_ensure(aArray, CPL_ERROR_NULL_INPUT, NULL);
1806  cpl_ensure(aOffset > 0, CPL_ERROR_ILLEGAL_INPUT, NULL);
1807  cpl_size nrows = cpl_array_get_size(aArray);
1808 
1809  cpl_array *a1 = cpl_array_extract(aArray, 0, nrows - aOffset);
1810  cpl_array *a2 = cpl_array_extract(aArray, aOffset, nrows - aOffset);
1811  if (a1 == NULL || a2 == NULL) {
1812  cpl_array_delete(a1);
1813  cpl_array_delete(a2);
1814  return NULL;
1815  }
1816  cpl_array_subtract(a2, a1);
1817  cpl_array_delete(a1);
1818  return a2;
1819 }
1820 
1821 /*----------------------------------------------------------------------------*/
1834 /*----------------------------------------------------------------------------*/
1835 cpl_error_code
1836 muse_cplarray_erf(cpl_array *aArray)
1837 {
1838  cpl_ensure_code(aArray, CPL_ERROR_NULL_INPUT);
1839  cpl_type type = cpl_array_get_type(aArray);
1840  cpl_size n = cpl_array_get_size(aArray);
1841  if (type == CPL_TYPE_DOUBLE) {
1842  double *d = cpl_array_get_data_double(aArray);
1843  cpl_size i;
1844  for (i = 0; i < n; i++, d++) {
1845  *d = erf(*d);
1846  }
1847  } else if (type == CPL_TYPE_FLOAT) {
1848  float *d = cpl_array_get_data_float(aArray);
1849  cpl_size i;
1850  for (i = 0; i < n; i++, d++) {
1851  *d = erf(*d);
1852  }
1853  } else {
1854  cpl_error_set(__func__, CPL_ERROR_ILLEGAL_INPUT);
1855  return CPL_ERROR_ILLEGAL_INPUT;
1856  }
1857  return CPL_ERROR_NONE;
1858 }
1859 
1860 /*----------------------------------------------------------------------------*/
1873 /*----------------------------------------------------------------------------*/
1874 cpl_error_code
1875 muse_cplarray_exp(cpl_array *aArray)
1876 {
1877  cpl_ensure_code(aArray, CPL_ERROR_NULL_INPUT);
1878  cpl_type type = cpl_array_get_type(aArray);
1879  cpl_size n = cpl_array_get_size(aArray);
1880  if (type == CPL_TYPE_DOUBLE) {
1881  double *d = cpl_array_get_data_double(aArray);
1882  cpl_size i;
1883  for (i = 0; i < n; i++, d++) {
1884  *d = exp(*d);
1885  }
1886  } else if (type == CPL_TYPE_FLOAT) {
1887  float *d = cpl_array_get_data_float(aArray);
1888  cpl_size i;
1889  for (i = 0; i < n; i++, d++) {
1890  *d = expf(*d);
1891  }
1892  } else {
1893  cpl_error_set(__func__, CPL_ERROR_ILLEGAL_INPUT);
1894  return CPL_ERROR_ILLEGAL_INPUT;
1895  }
1896  return CPL_ERROR_NONE;
1897 }
1898 
1899 /*----------------------------------------------------------------------------*/
1922 /*----------------------------------------------------------------------------*/
1923 cpl_array *
1924 muse_cplarray_interpolate_linear(const cpl_array *aTargetAbscissa,
1925  const cpl_array *aSourceAbscissa,
1926  const cpl_array *aSourceOrdinate)
1927 {
1928  cpl_ensure(aTargetAbscissa && aSourceAbscissa && aSourceOrdinate,
1929  CPL_ERROR_NULL_INPUT, NULL);
1930 
1931  double *targetX = cpl_array_get_data_double((cpl_array *)aTargetAbscissa);
1932  double *srcX = cpl_array_get_data_double((cpl_array *)aSourceAbscissa);
1933  double *srcY = cpl_array_get_data_double((cpl_array *)aSourceOrdinate);
1934  cpl_ensure(targetX && srcX && srcY, CPL_ERROR_ILLEGAL_INPUT, NULL);
1935 
1936  cpl_array *targetOrdinate = cpl_array_duplicate(aTargetAbscissa);
1937  double *targetY = cpl_array_get_data_double(targetOrdinate);
1938 
1939  cpl_size n_src = cpl_array_get_size(aSourceAbscissa);
1940  cpl_vector *srcX_vec = cpl_vector_wrap(n_src, srcX);
1941  cpl_vector *srcY_vec = cpl_vector_wrap(n_src, srcY);
1942  cpl_bivector *src_vec = cpl_bivector_wrap_vectors(srcX_vec, srcY_vec);
1943 
1944  cpl_size offset = (srcX[0] <= targetX[0])?0:
1945  muse_cplarray_find_sorted(aTargetAbscissa, srcX[0]) + 1;
1946  cpl_size n_target =
1947  muse_cplarray_find_sorted(aTargetAbscissa, srcX[n_src-1]) - offset + 1;
1948 
1949  cpl_vector *targetX_vec = cpl_vector_wrap(n_target, targetX + offset);
1950  cpl_vector *targetY_vec = cpl_vector_wrap(n_target, targetY + offset);
1951  cpl_bivector *target_vec = cpl_bivector_wrap_vectors(targetX_vec,
1952  targetY_vec);
1953  if (offset > 0) {
1954  cpl_array_fill_window_invalid(targetOrdinate, 0, offset);
1955  }
1956  if (offset + n_target < (unsigned)cpl_array_get_size(targetOrdinate)) {
1957  cpl_array_fill_window_invalid(targetOrdinate, offset + n_target,
1958  cpl_array_get_size(targetOrdinate)
1959  - (offset + n_target));
1960  }
1961  cpl_bivector_interpolate_linear(target_vec, src_vec);
1962  cpl_bivector_unwrap_vectors(target_vec);
1963  cpl_vector_unwrap(targetX_vec);
1964  cpl_vector_unwrap(targetY_vec);
1965  cpl_bivector_unwrap_vectors(src_vec);
1966  cpl_vector_unwrap(srcX_vec);
1967  cpl_vector_unwrap(srcY_vec);
1968 
1969  return targetOrdinate;
1970 }
1971 
1972 /*----------------------------------------------------------------------------*/
1991 /*----------------------------------------------------------------------------*/
1992 cpl_array *
1993 muse_cplarray_interpolate_table_linear(const cpl_array *aTargetAbscissa,
1994  const cpl_table *aSrcTable,
1995  const char *aSrcAbscissa,
1996  const char *aSrcOrdinate)
1997 {
1998  cpl_array *sabs = muse_cpltable_extract_column((cpl_table *)aSrcTable,
1999  aSrcAbscissa);
2000  cpl_array *sord = muse_cpltable_extract_column((cpl_table *)aSrcTable,
2001  aSrcOrdinate);
2002  cpl_array *ord = muse_cplarray_interpolate_linear(aTargetAbscissa, sabs, sord);
2003  cpl_array_unwrap(sabs);
2004  cpl_array_unwrap(sord);
2005  return ord;
2006 }
2007 
2008 /*---------------------------------------------------------------------------*/
2022 /*---------------------------------------------------------------------------*/
2023 cpl_array *
2024 muse_cplarray_new_from_delimited_string(const char *aString, const char *aDelim)
2025 {
2026  cpl_ensure(aString && aDelim, CPL_ERROR_NULL_INPUT, NULL);
2027  /* duplicate the string to be able to work on it */
2028  char *string = cpl_strdup(aString);
2029 
2030  /* loop to find delimiters and save sub-strings in array */
2031  char *prev = string, *next;
2032  cpl_array *out = cpl_array_new(0, CPL_TYPE_STRING);
2033  int ntok = 0;
2034  do {
2035  next = strstr(prev, aDelim);
2036  if (next) {
2037  *next = '\0'; /* terminate this token starting at |prev| */
2038  }
2039  if (strlen(prev)) { /* don't want to add non-empty strings */
2040  cpl_array_set_size(out, ++ntok);
2041  cpl_array_set_string(out, ntok - 1, prev);
2042  }
2043  prev = next + strlen(aDelim);
2044  } while (next);
2045  cpl_free(string);
2046 
2047 #if 0
2048  printf("Input string %s and delimiter %s resulted in output\n",
2049  aString, aDelim);
2050  cpl_array_dump(out, 0, cpl_array_get_size(out), stdout);
2051  fflush(stdout);
2052 #endif
2053  return out;
2054 } /* muse_cplarray_new_from_delimited_string() */
2055 
2056 /*---------------------------------------------------------------------------*/
2071 /*---------------------------------------------------------------------------*/
2072 cpl_array *
2073 muse_cplarray_string_to_double(const cpl_array *aArray)
2074 {
2075  cpl_ensure(aArray, CPL_ERROR_NULL_INPUT, NULL);
2076  cpl_ensure(cpl_array_get_type(aArray) == CPL_TYPE_STRING,
2077  CPL_ERROR_ILLEGAL_INPUT, NULL);
2078 
2079  cpl_size i, n = cpl_array_get_size(aArray);
2080  cpl_array *darray = cpl_array_new(n, CPL_TYPE_DOUBLE);
2081  for (i = 0; i < n; i++) {
2082  const char *string = cpl_array_get_string(aArray, i);
2083  if (!string) {
2084  continue;
2085  }
2086  cpl_array_set_double(darray, i, atof(string));
2087  } /* for i (array elements) */
2088  return darray;
2089 } /* muse_cplarray_string_to_double() */
2090 
2091 /*---------------------------------------------------------------------------*/
2105 /*---------------------------------------------------------------------------*/
2106 cpl_parameter *
2107 muse_cplparamerterlist_find_prefix(cpl_parameterlist *aParameters,
2108  const char *aPrefix, const char *aName)
2109 {
2110  char *fullname = cpl_sprintf("%s.%s", aPrefix, aName);
2111  cpl_parameter *p = cpl_parameterlist_find(aParameters, fullname);
2112  cpl_free(fullname);
2113  return p;
2114 }
2115 
2116 /*---------------------------------------------------------------------------*/
2141 /*---------------------------------------------------------------------------*/
2142 cpl_parameterlist *
2143 muse_cplparameterlist_from_propertylist(const cpl_propertylist *aHeader,
2144  int aRecNum)
2145 {
2146  cpl_ensure(aHeader, CPL_ERROR_NULL_INPUT, NULL);
2147  cpl_ensure(aRecNum > 0, CPL_ERROR_ILLEGAL_INPUT, NULL);
2148 
2149  /* check that the input header has a recipe name */
2150  char *kw = cpl_sprintf("ESO PRO REC%d ID", aRecNum);
2151  const char *recipe = cpl_propertylist_get_string(aHeader, kw);
2152  cpl_free(kw);
2153  cpl_ensure(recipe, CPL_ERROR_ILLEGAL_INPUT, NULL);
2154  /* check that the input header was written by the MUSE pipeline */
2155  kw = cpl_sprintf("ESO PRO REC%d PIPE ID", aRecNum);
2156  const char *pipeid = cpl_propertylist_get_string(aHeader, kw);
2157  cpl_free(kw);
2158  cpl_ensure(strstr(recipe, "muse_") && strstr(pipeid, "muse"),
2159  CPL_ERROR_INCOMPATIBLE_INPUT, NULL);
2160  char *context = cpl_sprintf("muse.%s", recipe);
2161 
2162  /* create the new parameter list to be filled from the header */
2163  cpl_parameterlist *parlist = cpl_parameterlist_new();
2164  int npar;
2165  for (npar = 1; npar < cpl_propertylist_get_size(aHeader); npar++) {
2166  char *kwname = cpl_sprintf("ESO PRO REC%d PARAM%d NAME", aRecNum, npar),
2167  *kwvalue = cpl_sprintf("ESO PRO REC%d PARAM%d VALUE", aRecNum, npar);
2168  if (!cpl_propertylist_has(aHeader, kwname) ||
2169  !cpl_propertylist_has(aHeader, kwvalue)) {
2170  cpl_free(kwname);
2171  cpl_free(kwvalue);
2172  break;
2173  }
2174  const cpl_property *prop = cpl_propertylist_get_property_const(aHeader,
2175  kwvalue);
2176  /* since they are all saved as strings, convert them to other types *
2177  * based on the first character and the presence of a dot */
2178  const char *value = cpl_property_get_string(prop);
2179  cpl_type type = CPL_TYPE_STRING;
2180  if (!strncmp(value, "true", 5) || !strncmp(value, "false", 6)) {
2181  type = CPL_TYPE_BOOL;
2182  } else if (!strchr(value, ',') && /* no comma-separator of multiple numbers */
2183  ((value[0] >= '0' && value[0] <= '9') || /* numerical type */
2184  value[0] == '-' || value[0] == '+')) {
2185  /* this might mis-identify a few doubles saved without dot as ints! */
2186  if (strchr(value, '.') || strchr(value, 'E')) {
2187  type = CPL_TYPE_DOUBLE;
2188  } else {
2189  type = CPL_TYPE_INT;
2190  } /* else */
2191  } /* else */
2192  char *parname = cpl_sprintf("muse.%s.%s", recipe,
2193  cpl_propertylist_get_string(aHeader, kwname));
2194  const char *comment = cpl_property_get_comment(prop),
2195  *comname = cpl_propertylist_get_comment(aHeader, kwname);
2196  char defstr[41] = "true"; /* string with the default value */
2197  if (comment) {
2198  sscanf(comment, "Default: %40s", defstr);
2199  }
2200  cpl_parameter *par = NULL;
2201  switch (type) {
2202  case CPL_TYPE_BOOL:
2203  par = cpl_parameter_new_value(parname, type, comname, context,
2204  !strncmp(defstr, "true", 5) ? CPL_TRUE : CPL_FALSE);
2205  if (!strncmp(value, "true", 5)) {
2206  cpl_parameter_set_bool(par, CPL_TRUE);
2207  } else {
2208  cpl_parameter_set_bool(par, CPL_FALSE);
2209  }
2210  break;
2211  case CPL_TYPE_INT:
2212  par = cpl_parameter_new_value(parname, type, comname, context, atoi(defstr));
2213  cpl_parameter_set_int(par, atoi(value));
2214  break;
2215  case CPL_TYPE_DOUBLE:
2216  par = cpl_parameter_new_value(parname, type, comname, context, atof(defstr));
2217  cpl_parameter_set_double(par, atof(value));
2218  break;
2219  case CPL_TYPE_STRING:
2220  par = cpl_parameter_new_value(parname, type, comname, context, defstr);
2221  cpl_parameter_set_string(par, value);
2222  break;
2223  default:
2224  /* cannot do anything */
2225  par = cpl_parameter_new_value(parname, type, comname, context, 0);
2226  cpl_msg_warning(__func__, "property of type %s (%d) found!",
2227  cpl_type_get_name(type), type);
2228  } /* switch */
2229  cpl_parameterlist_append(parlist, par);
2230  cpl_free(parname);
2231  cpl_free(kwname);
2232  cpl_free(kwvalue);
2233  } /* for npar */
2234  cpl_free(context);
2235  return parlist;
2236 } /* muse_cplparameterlist_from_propertylist() */
2237 
2238 /*---------------------------------------------------------------------------*/
2250 /*---------------------------------------------------------------------------*/
2251 cpl_parameterlist *
2252 muse_cplparameterlist_duplicate(const cpl_parameterlist *aPList)
2253 {
2254  cpl_ensure(aPList, CPL_ERROR_NULL_INPUT, NULL);
2255 
2256  cpl_parameterlist *list = cpl_parameterlist_new();
2257  const cpl_parameter *par = cpl_parameterlist_get_first_const(aPList);
2258  while (par) {
2259  cpl_parameterlist_append(list, cpl_parameter_duplicate(par));
2260  par = cpl_parameterlist_get_next_const(aPList);
2261  } /* while */
2262  return list;
2263 } /* muse_cplparameterlist_duplicate() */
2264 
2265 /*----------------------------------------------------------------------------*/
2283 /*----------------------------------------------------------------------------*/
2284 cpl_error_code
2285 muse_cplpropertylist_update_long_long(cpl_propertylist *aHeader,
2286  const char *aKeyword, cpl_size aValue)
2287 {
2288  cpl_ensure_code(aHeader && aKeyword, CPL_ERROR_NULL_INPUT);
2289  cpl_property *p = cpl_propertylist_get_property(aHeader, aKeyword);
2290  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
2291  cpl_error_code rc = CPL_ERROR_NONE;
2292  switch (cpl_property_get_type(p)) {
2293  case CPL_TYPE_LONG_LONG:
2294  rc = cpl_property_set_long_long(p, aValue);
2295  break;
2296  case CPL_TYPE_LONG:
2297  rc = cpl_property_set_long(p, aValue);
2298  break;
2299  default:
2300  rc = cpl_property_set_int(p, aValue);
2301  } /* switch */
2302  return rc;
2303 } /* muse_cplpropertylist_update_long_long() */
2304 
2305 /*----------------------------------------------------------------------------*/
2316 /*----------------------------------------------------------------------------*/
2317 cpl_error_code
2318 muse_cplframeset_erase_all(cpl_frameset *aFrames)
2319 {
2320  cpl_ensure_code(aFrames, CPL_ERROR_NULL_INPUT);
2321  cpl_error_code rc = CPL_ERROR_NONE;
2322  /* always get and erase the first frame until we are done */
2323  while (cpl_frameset_get_size(aFrames) > 0 && rc == CPL_ERROR_NONE) {
2324  cpl_frame *frame = cpl_frameset_get_position(aFrames, 0);
2325  rc = cpl_frameset_erase_frame(aFrames, frame);
2326  } /* while */
2327  return rc;
2328 } /* muse_cplframeset_erase_all() */
2329 
2330 /*----------------------------------------------------------------------------*/
2347 /*----------------------------------------------------------------------------*/
2348 cpl_error_code
2349 muse_cplframeset_erase_duplicate(cpl_frameset *aFrames)
2350 {
2351  cpl_ensure_code(aFrames, CPL_ERROR_NULL_INPUT);
2352 #if 0
2353  printf("\n\n\n%s input frameset (with duplicates):\n", __func__);
2354  cpl_frameset_dump(aFrames, stdout);
2355  printf("---------------------------------------------------------------------------\n");
2356  fflush(stdout);
2357 #endif
2358  cpl_error_code rc = CPL_ERROR_NONE;
2359  /* Loop through all frames but the last, and compare all frame properties *
2360  * to all following frames. Delete the frame if they are all the same. */
2361  cpl_size i;
2362  for (i = 0; i < cpl_frameset_get_size(aFrames) - 1; i++) {
2363  cpl_frame *fref = cpl_frameset_get_position(aFrames, i);
2364  cpl_size j;
2365  for (j = i + 1; j < cpl_frameset_get_size(aFrames); j++) {
2366  cpl_frame *fother = cpl_frameset_get_position(aFrames, j);
2367  cpl_boolean areequal = CPL_FALSE;
2368  cpl_errorstate state = cpl_errorstate_get();
2369  const char *fn1 = cpl_frame_get_filename(fref),
2370  *fn2 = cpl_frame_get_filename(fother);
2371  if (!cpl_errorstate_is_equal(state)) {
2372  cpl_errorstate_set(state);
2373  }
2374  if ((!fn1 && fn2) || (fn1 && !fn2)) {
2375  areequal = CPL_FALSE;
2376  } else if (!fn1 && !fn2) {
2377  areequal = CPL_TRUE;
2378  } else {
2379  areequal = !strcmp(fn1, fn2);
2380  }
2381  areequal = areequal
2382  && !strcmp(cpl_frame_get_tag(fref), cpl_frame_get_tag(fother));
2383  areequal = areequal
2384  && (cpl_frame_get_group(fref) == cpl_frame_get_group(fother));
2385  areequal = areequal
2386  && (cpl_frame_get_level(fref) == cpl_frame_get_level(fother));
2387  areequal = areequal
2388  && (cpl_frame_get_type(fref) == cpl_frame_get_type(fother));
2389  if (areequal) {
2390 #if 0
2391  printf("%ld/%ld are equal: %s/%s, %s/%s, %d/%d, %d/%d, %d/%d\n", i, j,
2392  fn1, fn2, tag1, tag2,
2393  cpl_frame_get_group(fref), cpl_frame_get_group(fother),
2394  cpl_frame_get_level(fref), cpl_frame_get_level(fother),
2395  cpl_frame_get_type(fref), cpl_frame_get_type(fother));
2396  fflush(stdout);
2397 #endif
2398  /* would really like to erase the other frame, *
2399  * but it's not possible to delete by position! */
2400  rc = cpl_frameset_erase_frame(aFrames, fref);
2401  i--; /* stay at the same reference position in the frameset */
2402  break;
2403  } /* if equal */
2404  } /* for j (all following frames) */
2405  } /* for i (all frames but the last) */
2406 #if 0
2407  printf("---------------------------------------------------------------------------\n");
2408  printf("%s input frameset (without duplicates):\n", __func__);
2409  cpl_frameset_dump(aFrames, stdout);
2410  printf("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n\n");
2411  fflush(stdout);
2412 #endif
2413  return rc;
2414 } /* muse_cplframeset_erase_duplicate() */
2415 
2416 /*----------------------------------------------------------------------------*/
2428 /*----------------------------------------------------------------------------*/
2429 void
2430 muse_cplerrorstate_dump_some(unsigned aCurrent, unsigned aFirst, unsigned aLast)
2431 {
2432  const cpl_boolean is_reverse = aFirst > aLast ? CPL_TRUE : CPL_FALSE;
2433  const char *revmsg = is_reverse ? " in reverse order" : "";
2434  const unsigned newest = is_reverse ? aFirst : aLast,
2435  nmax = labs((long int)aLast - (long int)aFirst) + 1;
2436  unsigned ndump = 20;
2437  if (getenv("MUSE_CPL_ERRORSTATE_NDUMP") &&
2438  atoi(getenv("MUSE_CPL_ERRORSTATE_NDUMP")) > 0) {
2439  ndump = atoi(getenv("MUSE_CPL_ERRORSTATE_NDUMP"));
2440  }
2441  ndump = nmax < ndump ? nmax : ndump;
2442 
2443  if (newest) { /* there are errors to dump */
2444  if (aCurrent == aLast - (ndump-1)) {
2445  cpl_msg_error(__func__, "Dumping the %u most recent error(s) out of a "
2446  "total of %u errors%s:", ndump, newest, revmsg);
2447  cpl_msg_indent_more();
2448  }
2449  if (aCurrent >= aLast - (ndump-1)) {
2450  cpl_msg_error(__func__, "[%u/%u] '%s' (%u) at %s", aCurrent, newest,
2451  cpl_error_get_message(), cpl_error_get_code(),
2452  cpl_error_get_where());
2453  }
2454  if (aCurrent == aLast) {
2455  cpl_msg_indent_less();
2456  }
2457  } else {
2458  cpl_msg_info(__func__, "No error(s) to dump");
2459  }
2460 } /* muse_cplerrorstate_dump_some() */
2461 
2462 
2463 /*----------------------------------------------------------------------------*/
2476 /*----------------------------------------------------------------------------*/
2478 #ifdef HAVE_READLINK
2479  char buffer[FILENAME_MAX] = "\0";
2480  int length = readlink("/proc/self/exe", buffer, sizeof(buffer) - 1);
2481  if (length != -1) {
2482  buffer[length] = '\0';
2483  }
2484  if (strstr(buffer, "esorex")) {
2485  return MUSE_CPLFRAMEWORK_ESOREX;
2486  } else if (strstr(buffer, "python")) {
2488  } else if (strstr(buffer, "jre")) {
2490  } else {
2492  }
2493 #else
2495 #endif
2496 }
2497 
cpl_error_code muse_cplarray_erase_invalid(cpl_array *aArray)
Erase all invalid values from an array.
cpl_type type
Column type (use CPL_TYPE_POINTER for array columns).
int(* muse_cplmatrix_element_compare_func)(double aValue1, double aValue2)
Matrix element comparison function type definition.
cpl_array * muse_cplarray_interpolate_table_linear(const cpl_array *aTargetAbscissa, const cpl_table *aSrcTable, const char *aSrcAbscissa, const char *aSrcOrdinate)
Linear interpolation of a 1d column.
const int required
Is column required?
cpl_error_code muse_cplarray_dump_name(const cpl_array *aArray, const char *aName)
Dump a numerical array to stdout with a name prefixed to each line.
cpl_image * muse_cplimage_filter_median_subtract(cpl_image *aImage, unsigned int aNX, unsigned int aNY)
Subtract a median-filtered version of the input image from itself.
cpl_array * muse_cplarray_extract(cpl_array *aArray, cpl_size aStart, cpl_size aCount)
Create an array from a section of another array.
muse_cplframework_type muse_cplframework(void)
Return the CPL framework the recipe is run under.
cpl_array * muse_cplarray_string_to_double(const cpl_array *aArray)
Convert a string array into an array of type double.
cpl_error_code muse_cplarray_sort(cpl_array *aArray, cpl_boolean aOrder)
Sort float, int or double array by quicksort.
const char * unit
Column unit, or NULL.
cpl_error_code muse_cplarray_poly1d(cpl_array *aArray, const cpl_array *aCoeff)
Apply a polynomial to an array.
double muse_cplvector_get_median_dev(cpl_vector *aVector, double *aMedian)
Compute the median and average absolute deviation against the median of a vector. ...
cpl_vector * muse_cplvector_get_unique(const cpl_vector *aVector)
Separate out all unique entries in a given vector into a new one.
double muse_cplvector_get_semiquartile(cpl_vector *aVector)
compute the semi-quartile range of a vector of elements
cpl_boolean muse_cplarray_has_duplicate(const cpl_array *aArray)
Check, if an array contains duplicate values.
cpl_image * muse_cplimage_concat_y(const cpl_image *aImage1, const cpl_image *aImage2)
Concatenate two images in y direction.
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.
cpl_table * muse_cpltable_load(const char *aFile, const char *aExtension, const muse_cpltable_def aDefinition[])
Load a table from disk (and check against definition).
cpl_matrix * muse_cplmatrix_extract_selected(const cpl_matrix *aMatrix, const cpl_array *aIndices)
Extract the elements given by the index array.
cpl_table * muse_cpltable_new(const muse_cpltable_def *aDef, cpl_size aLength)
Create an empty table according to the specified definition.
cpl_error_code muse_cplarray_exp(cpl_array *aArray)
Compute the exponential function of array elements.
cpl_error_code muse_cplimage_or(cpl_image *aTarget, const cpl_image *aImage, unsigned int mask)
Provide an &#39;OR&#39; operation of two integer images.
cpl_array * muse_cplarray_new_from_delimited_string(const char *aString, const char *aDelim)
Convert a delimited string into an array of strings.
cpl_array * muse_cpltable_get_array_copy(cpl_table *aTable, const char *aColumn, cpl_size aRow)
Return the copy of an array of a table cell.
cpl_array * muse_cpltable_extract_column(cpl_table *aTable, const char *aColumn)
Create an array from a section of a column.
cpl_error_code muse_cplvector_erase_element(cpl_vector *aVector, int aElement)
delete the given element from the input vector
const char * name
Column name.
const char * format
Default print format, or NULL.
cpl_array * muse_cplarray_new_from_image(const cpl_image *aImage)
Copy the image data into an array.
cpl_bivector * muse_cplarray_histogram(const cpl_array *aArray, double aWidth, double aMin, double aMax)
Create a histogram for a numerical array.
cpl_array * muse_cplarray_interpolate_linear(const cpl_array *aTargetAbscissa, const cpl_array *aSourceAbscissa, const cpl_array *aSourceOrdinate)
Linear interpolation of a 1d array.
double muse_cplimage_get_percentile(const cpl_image *aImage, double aFraction)
Get the percentile of an image.
void muse_cplerrorstate_dump_some(unsigned aCurrent, unsigned aFirst, unsigned aLast)
Dump some CPL errors.
cpl_vector * muse_cplimage_slope_window(const cpl_image *aImage, const cpl_size *aWindow)
Compute slopes of an image, both horizontally and vertically.
cpl_error_code muse_cplarray_erf(cpl_array *aArray)
Compute the error function of array elements.
cpl_error_code muse_cplarray_add_window(cpl_array *aDest, cpl_size aStart, const cpl_array *aArray)
Add the value of an array to a window of a table column.
cpl_error_code muse_cplpropertylist_update_long_long(cpl_propertylist *aHeader, const char *aKeyword, cpl_size aValue)
Update an integer-like property irrespective of the real type.
cpl_size muse_cpltable_find_sorted(const cpl_table *aTable, const char *aColumn, double aValue)
Find a row in a table.
cpl_image * muse_cplimage_concat_x(const cpl_image *aImage1, const cpl_image *aImage2)
Concatenate two images in x direction.
cpl_error_code muse_cpltable_copy_array(cpl_table *aTable, const char *aColumn, const cpl_array *aArray)
Copy an array into a table.
cpl_array * muse_cplarray_diff(const cpl_array *aArray, int aOffset)
Build the difference of any element and one of the next elements.
cpl_parameterlist * muse_cplparameterlist_duplicate(const cpl_parameterlist *aPList)
Duplicate a CPL parameter list.
cpl_error_code muse_cplframeset_erase_duplicate(cpl_frameset *aFrames)
Erase all duplicate frames from a frameset.
cpl_error_code muse_cplframeset_erase_all(cpl_frameset *aFrames)
Erase all frames in a frameset.
cpl_size muse_cplarray_erase_outliers(cpl_array *aArray, const cpl_bivector *aHistogram, cpl_size aGap, double aLimit)
Erase outliers from an array using histogram information.
cpl_matrix * muse_cplmatrix_multiply_create(const cpl_matrix *aMatrix1, const cpl_matrix *aMatrix2)
Compute the element-wise product of two matrices.
cpl_array * muse_cplmatrix_where(const cpl_matrix *aMatrix, double aValue, muse_cplmatrix_element_compare_func aCondition)
Select matrix elements according to a condition.
muse_cplframework_type
Type for the framework that called the recipe.
cpl_size muse_cplvector_count_unique(const cpl_vector *aVector)
Count the number of unique entries in a given vector.
Definition of a cpl table structure.
double muse_cplvector_get_adev_const(const cpl_vector *aVector, double aCenter)
Compute the average absolute deviation of a (constant) vector.
cpl_parameter * muse_cplparamerterlist_find_prefix(cpl_parameterlist *aParameters, const char *aPrefix, const char *aName)
Return the full recipe parameter belonging to prefix and shortname.
double muse_cplarray_poly1d_double(double aDouble, const cpl_array *aCoeff)
Apply a polynomial to a double value.
cpl_size muse_cplarray_find_sorted(const cpl_array *aArray, double aValue)
Find a row in an array.
cpl_error_code muse_cplvector_threshold(cpl_vector *aVec, double aLoCut, double aHiCut, double aLoVal, double aHiVal)
Threshold a vector to a given interval.
cpl_mask * muse_cplmask_adapt_to_image(const cpl_mask *aMask, const cpl_image *aImage)
Adapt mask with masked region in one quadrant to size of an image.
cpl_parameterlist * muse_cplparameterlist_from_propertylist(const cpl_propertylist *aHeader, int aRecNum)
Recreate a cpl_parameterlist from the RECi headers of an output MUSE product.
cpl_image * muse_cplimagelist_collapse_or_create(const cpl_imagelist *imlist)
Compute the OR of an image list to a single image.
cpl_error_code muse_cpltable_append_file(const cpl_table *aTable, const char *aFile, const char *aExtension, const muse_cpltable_def aDefinition[])
Save a table to disk (into a FITS extension)