MUSE Pipeline Reference Manual  2.5.2
muse_exp_align.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) 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 #include <errno.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <strings.h>
33 #include <math.h>
34 #include <cpl.h>
35 #include <muse.h>
36 #include "muse_exp_align_z.h"
37 
38 
39 typedef struct muse_indexpair muse_indexpair;
40 
41 struct muse_indexpair {
42  cpl_size first;
43  cpl_size second;
44 };
45 
46 typedef void (*muse_free_func)(void *);
47 
48 
49 /* Conversion factor degree to arcsecond */
50 static const double deg2as = 3600.;
51 
52 
53 /*---------------------------------------------------------------------------*
54  * Functions code *
55  *---------------------------------------------------------------------------*/
56 
57 static void
58 muse_vfree(void **array, cpl_size size, muse_free_func deallocator)
59 {
60  if (array) {
61  cpl_size idx;
62  for (idx = 0; idx < size; ++idx) {
63  if (deallocator) {
64  deallocator(array[idx]);
65  }
66  }
67  cpl_free(array);
68  }
69  return;
70 }
71 
72 static int
73 _muse_condition_less_than(double aValue1, double aValue2)
74 {
75  return (aValue1 < aValue2) ? TRUE : FALSE;
76 }
77 
78 /*----------------------------------------------------------------------------*/
92 /*----------------------------------------------------------------------------*/
93 static cpl_error_code
94 muse_utils_replace_nan(muse_image *aImage, float aValue)
95 {
96  cpl_ensure(aImage, CPL_ERROR_NULL_INPUT, CPL_ERROR_NULL_INPUT);
97  cpl_ensure(aImage->data, CPL_ERROR_ILLEGAL_INPUT, CPL_ERROR_ILLEGAL_INPUT);
98 
99  cpl_size npixel = cpl_image_get_size_x(aImage->data) *
100  cpl_image_get_size_y(aImage->data);
101 
102  float *data = cpl_image_get_data_float(aImage->data);
103  if (cpl_error_get_code() == CPL_ERROR_TYPE_MISMATCH) {
104  cpl_error_set_message(__func__, CPL_ERROR_TYPE_MISMATCH,
105  "MUSE image data buffer has invalid type!");
106  return CPL_ERROR_TYPE_MISMATCH;
107  }
108 
109  cpl_size ipixel;
110  for (ipixel = 0; ipixel < npixel; ++ipixel) {
111  if (isnan(data[ipixel])) {
112  data[ipixel] = aValue;
113  }
114  }
115 
116  if (aImage->stat) {
117  npixel = cpl_image_get_size_x(aImage->stat) *
118  cpl_image_get_size_y(aImage->stat);
119 
120  data = cpl_image_get_data_float(aImage->stat);
121  if (cpl_error_get_code() == CPL_ERROR_TYPE_MISMATCH) {
122  cpl_error_set_message(__func__, CPL_ERROR_TYPE_MISMATCH,
123  "MUSE image data buffer has invalid type!");
124  return CPL_ERROR_TYPE_MISMATCH;
125  }
126 
127  for (ipixel = 0; ipixel < npixel; ++ipixel) {
128  if (isnan(data[ipixel])) {
129  data[ipixel] = aValue;
130  }
131  }
132  }
133 
134  return CPL_ERROR_NONE;
135 }
136 
137 
138 /* XXX: Moved to muse_utils, kept here disabled until final place is found */
139 #if 0
140 /*----------------------------------------------------------------------------*/
156 /*----------------------------------------------------------------------------*/
157 static muse_image *
158 muse_fov_load(const char *aFilename)
159 {
160  muse_image *image = muse_image_new();
161 
162  image->header = cpl_propertylist_load(aFilename, 0);
163  if (!image->header) {
164  cpl_error_set_message(__func__, cpl_error_get_code(), "Loading primary FITS "
165  "header of \"%s\" did not succeed", aFilename);
166  muse_image_delete(image);
167  return NULL;
168  }
169 
170  /* assuming an IMAGE_FOV input, start by searching for the DATA extension */
171  int extension = cpl_fits_find_extension(aFilename, EXTNAME_DATA);
172  cpl_propertylist *hdata = cpl_propertylist_load(aFilename, extension);
173  while (muse_pfits_get_naxis(hdata, 0) != 2) {
174  /* Not an image, this means we were given a cube, possibly *
175  * with image extensions; search for the first of those. */
176  cpl_msg_debug(__func__, "Skipping extension %d [%s]", extension,
177  muse_pfits_get_extname(hdata));
178  cpl_propertylist_delete(hdata);
179  extension++;
180  hdata = cpl_propertylist_load(aFilename, extension);
181  } /* while */
182  cpl_msg_debug(__func__, "Taking extension %d [%s]", extension,
183  muse_pfits_get_extname(hdata));
184  /* keep the extension name, to check if we loaded *
185  * from an IMAGE_FOV or from a cube extension */
186  char *extname = cpl_strdup(muse_pfits_get_extname(hdata));
187  image->data = cpl_image_load(aFilename, CPL_TYPE_FLOAT, 0, extension);
188  if (!image->data) {
189  cpl_error_set_message(__func__, MUSE_ERROR_READ_DATA, "Could not load "
190  "extension %s from \"%s\"", extname, aFilename);
191  muse_image_delete(image);
192  cpl_free(extname);
193  return NULL;
194  }
195 
196  if (cpl_propertylist_has(hdata, "BUNIT")) {
197  cpl_propertylist_append_string(image->header, "BUNIT",
198  muse_pfits_get_bunit(hdata));
199  cpl_propertylist_set_comment(image->header, "BUNIT",
200  cpl_propertylist_get_comment(hdata, "BUNIT"));
201  } else {
202  cpl_msg_warning(__func__, "No BUNIT given in extension %d [%s] of \"%s\"!",
203  extension, extname, aFilename);
204  }
205 
206  if (!cpl_propertylist_has(hdata, "CUNIT1") ||
207  !cpl_propertylist_has(hdata, "CUNIT2")) {
208  cpl_msg_warning(__func__, "No WCS found in extension %d [%s] of \"%s\"!",
209  extension, extname, aFilename);
210  }
211 
212  /* Merge WCS keywords and ESO hierarchical keywords from the data *
213  * extension into the image header */
214  cpl_propertylist_erase_regexp(hdata, "(^ESO |" MUSE_WCS_KEYS ")", 1);
215  cpl_propertylist_append(image->header, hdata);
216  cpl_propertylist_delete(hdata);
217 
218  /* Load STAT extension if it is found and contains data, ignore it *
219  * otherwise */
220  if (extname && !strncmp(extname, EXTNAME_DATA, strlen(EXTNAME_DATA)+1)) {
221  /* if this is an IMAGE_FOV, then a STAT extension might be there */
222  extension = cpl_fits_find_extension(aFilename, EXTNAME_STAT);
223  } else {
224  /* otherwise we might have an extension <filtername>_STAT */
225  char *statname = cpl_sprintf("%s_STAT", extname);
226  extension = cpl_fits_find_extension(aFilename, statname);
227  cpl_free(statname);
228  }
229  if (extension > 0) {
230  cpl_errorstate status = cpl_errorstate_get();
231  image->stat = cpl_image_load(aFilename, CPL_TYPE_INT, 0, extension);
232  if (!cpl_errorstate_is_equal(status)) {
233  if (cpl_error_get_code() == CPL_ERROR_DATA_NOT_FOUND) {
234  cpl_errorstate_set(status);
235  cpl_msg_debug(__func__, "Ignoring empty extension %s in \"%s\"",
236  EXTNAME_STAT, aFilename);
237  } else {
238  cpl_error_set_message(__func__, MUSE_ERROR_READ_STAT, "Could not load "
239  "extension %s from \"%s\"", EXTNAME_STAT, aFilename);
240  muse_image_delete(image);
241  cpl_free(extname);
242  return NULL;
243  }
244  }
245  }
246 
247  /* If present load the DQ extension and encode flagged pixels in the *
248  * image data (and possibly the statistics as NaNs. */
249  if (extname && !strncmp(extname, EXTNAME_DATA, strlen(EXTNAME_DATA)+1)) {
250  /* if this is an IMAGE_FOV, then a DQ extension might be there */
251  extension = cpl_fits_find_extension(aFilename, EXTNAME_DQ);
252  } else {
253  /* otherwise we might have an extension <filtername>_DQ */
254  char *dqname = cpl_sprintf("%s_DQ", extname);
255  extension = cpl_fits_find_extension(aFilename, dqname);
256  cpl_free(dqname);
257  }
258  if (extension > 0) {
259  cpl_errorstate status = cpl_errorstate_get();
260  image->dq = cpl_image_load(aFilename, CPL_TYPE_INT, 0, extension);
261  if (!cpl_errorstate_is_equal(status)) {
262  cpl_errorstate_set(status);
263  cpl_error_set_message(__func__, MUSE_ERROR_READ_DQ, "Could not load "
264  "extension %s from \"%s\"", EXTNAME_DQ, aFilename);
265  muse_image_delete(image);
266  cpl_free(extname);
267  return NULL;
268  }
269  muse_image_dq_to_nan(image);
270  }
271 
272  cpl_free(extname);
273  return image;
274 }
275 #endif
276 
277 /* XXX: Maybe there is a better name for this function */
278 /*----------------------------------------------------------------------------*/
284 /*----------------------------------------------------------------------------*/
285 static muse_imagelist *
286 muse_processing_fov_load_all(muse_processing *aProcessing)
287 {
288  cpl_ensure(aProcessing, CPL_ERROR_NULL_INPUT, NULL);
289  cpl_size nframes = cpl_frameset_get_size(aProcessing->inframes);
290  cpl_ensure(nframes, CPL_ERROR_DATA_NOT_FOUND, NULL);
291 
292  muse_imagelist *fovimages = muse_imagelist_new();
293 
294  cpl_size iexposure = 0;
295  cpl_size iframe;
296  for (iframe = 0; iframe < nframes; ++iframe) {
297  const cpl_frame *frame = cpl_frameset_get_position(aProcessing->inframes,
298  iframe);
299  const char *tag = cpl_frame_get_tag(frame);
300 
301  if (muse_processing_check_intags(aProcessing, tag, strlen(tag))) {
302  const char *filename = cpl_frame_get_filename(frame);
303 
304  cpl_msg_debug(__func__, "Loading FOV image '%s' as exposure %"
305  CPL_SIZE_FORMAT, filename, iexposure + 1);
306 
307  muse_image *image = muse_fov_load(filename);
308  if (!image) {
309  cpl_msg_error(__func__, "Could not load FOV image '%s'", filename);
310  muse_imagelist_delete(fovimages);
311  return NULL;
312  }
313 
314  muse_imagelist_set(fovimages, image, iexposure);
315  muse_processing_append_used(aProcessing, (cpl_frame *)frame,
316  CPL_FRAME_GROUP_RAW, 1);
317  ++iexposure;
318  }
319  }
320  return fovimages;
321 }
322 
323 /*----------------------------------------------------------------------------*/
330 /*----------------------------------------------------------------------------*/
331 static cpl_boolean
332 muse_align_check_detection_params(muse_exp_align_params_t *aParams)
333 {
334  if (aParams->bkgignore < 0.) {
335  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_INPUT,
336  "Fraction of image pixel to ignore for the "
337  "background estimation must be greater than"
338  "or equal to zero!");
339  return CPL_FALSE;
340  }
341  if (aParams->bkgfraction <= 0.) {
342  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_INPUT,
343  "Fraction of image pixels to use for the "
344  "background estimation must be greater "
345  "than zero!");
346  return CPL_FALSE;
347  }
348  if (aParams->fwhm < 0.5) {
349  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_INPUT,
350  "FWHM must be greater than 0.5 pixels!");
351  return CPL_FALSE;
352  }
353  if (aParams->srcmax <= aParams->srcmin) {
354  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_INPUT,
355  "Maximum number of sources must be grater than the "
356  "minimum number of sources!");
357  return CPL_FALSE;
358  }
359  if (aParams->roundmax < aParams->roundmin) {
360  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_INPUT,
361  "Upper limit of the point-source roundness must be "
362  "greater than the lower limit!");
363  return CPL_FALSE;
364  }
365  if (aParams->sharpmin <= 0.) {
366  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_INPUT,
367  "Low limit of the point-source sharpness must be "
368  "greater than zero!");
369  return CPL_FALSE;
370  }
371  if (aParams->sharpmax < aParams->sharpmin) {
372  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_INPUT,
373  "Upper limit of the point-source sharpness must be "
374  "greater than the lower limit!");
375  return CPL_FALSE;
376  }
377  return CPL_TRUE;
378 }
379 
380 /*----------------------------------------------------------------------------*/
388 /*----------------------------------------------------------------------------*/
389 static cpl_array *
390 muse_align_parse_valuelist(const char *aValuelist)
391 {
392  cpl_ensure(aValuelist, CPL_ERROR_NULL_INPUT, NULL);
393  if (strlen(aValuelist) == 0) {
394  cpl_error_set_message(__func__, CPL_ERROR_DATA_NOT_FOUND,
395  "List of values is empty!");
396  return NULL;
397  }
398 
399  cpl_array *strings = muse_cplarray_new_from_delimited_string(aValuelist, ",");
400  cpl_size nvalues = cpl_array_get_size(strings);
401 
402  cpl_array *values = cpl_array_new(nvalues, CPL_TYPE_DOUBLE);
403  cpl_size ivalue;
404  for (ivalue = 0; ivalue < nvalues; ++ivalue) {
405  const char *svalue = cpl_array_get_string(strings, ivalue);
406  if ((strncasecmp(svalue, "inf", 3) == 0) ||
407  (strncasecmp(svalue, "nan", 3) == 0)) {
408  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_INPUT,
409  "Illegal value \"%s\" encountered!", svalue);
410  cpl_array_delete(values);
411  cpl_array_delete(strings);
412  return NULL;
413  }
414  else {
415  char *last = NULL;
416  double value = strtod(svalue, &last);
417  if( (errno == ERANGE) || ((value == 0.) && (last == svalue))) {
418  cpl_error_set_message(__func__, CPL_ERROR_TYPE_MISMATCH,
419  "Could not convert \"%s\" to a decimal number!", svalue);
420  cpl_array_delete(values);
421  cpl_array_delete(strings);
422  return NULL;
423  }
424  cpl_array_set_double(values, ivalue, value);
425  }
426  }
427  cpl_array_delete(strings);
428  return values;
429 }
430 
431 /*----------------------------------------------------------------------------*/
440 /*----------------------------------------------------------------------------*/
441 static int
442 muse_align_celestial_from_pixel(cpl_table *aTable,
443  cpl_propertylist *aWCSHeader)
444 {
445  muse_wcs *wcs = muse_wcs_new(aWCSHeader);
446 
447  const char *unit1 = muse_pfits_get_cunit(aWCSHeader, 1);
448  const char *unit2 = muse_pfits_get_cunit(aWCSHeader, 2);
449 
450  if (unit1 && unit2) {
451  if ((strncmp(unit1, unit2, 4) == 0) && (strncmp(unit1, "deg", 3) == 0)) {
452  wcs->iscelsph = CPL_TRUE;
453  }
454  } else {
455  return -1;
456  }
457 
458  cpl_errorstate status = cpl_errorstate_get();
459 
460  cpl_table_new_column(aTable, "RA", CPL_TYPE_DOUBLE);
461  cpl_table_new_column(aTable, "DEC", CPL_TYPE_DOUBLE);
462 
463  cpl_size irow;
464  for (irow = 0; irow < cpl_table_get_nrow(aTable); ++irow) {
465  double x = cpl_table_get_double(aTable, "X", irow, NULL);
466  double y = cpl_table_get_double(aTable, "Y", irow, NULL);
467  double ra;
468  double dec;
469  muse_wcs_celestial_from_pixel_fast(wcs, x, y, &ra, &dec);
470 
471  cpl_table_set_double(aTable, "RA", irow, ra);
472  cpl_table_set_double(aTable, "DEC", irow, dec);
473  }
474  cpl_free(wcs);
475 
476  if (!cpl_errorstate_is_equal(status)) {
477  return -1;
478  }
479  return 0;
480 }
481 
482 /* XXX: Keep the conditional until the SVD code has been fully verified. *
483  * Once this is done, completely replace the old code with the SVD *
484  * version. */
485 #define USE_SVD_SOLVER
486 #ifdef USE_SVD_SOLVER
487 
488 #if CPL_VERSION_CODE < 459008
489 #define cpl_matrix_solve_svd muse_cplmatrix_solve_svd
490 
491 /*
492  * The following implementation of one-sided Jacobi orthogonalization
493  * to compute the SVD of a MxN matrix, with M >= N is based on the
494  * implementation found in the GNU Scientific Library (GSL).
495  */
496 
497 /*----------------------------------------------------------------------------*/
531 /*----------------------------------------------------------------------------*/
532 static cpl_error_code
533 muse_cplmatrix_decomp_sv_jacobi(cpl_matrix *U, cpl_vector *S, cpl_matrix *V)
534 {
535  cpl_ensure_code((U != NULL) && (V != NULL) && (S != NULL),
536  CPL_ERROR_NULL_INPUT);
537  cpl_ensure_code(cpl_matrix_get_nrow(U) >= cpl_matrix_get_ncol(U),
538  CPL_ERROR_ILLEGAL_INPUT);
539  cpl_ensure_code(cpl_matrix_get_nrow(V) == cpl_matrix_get_ncol(V),
540  CPL_ERROR_ILLEGAL_INPUT);
541  cpl_ensure_code(cpl_matrix_get_nrow(V) == cpl_matrix_get_ncol(U),
542  CPL_ERROR_INCOMPATIBLE_INPUT);
543  cpl_ensure_code(cpl_vector_get_size(S) == cpl_matrix_get_ncol(U),
544  CPL_ERROR_INCOMPATIBLE_INPUT);
545 
546  const cpl_size m = cpl_matrix_get_nrow(U);
547  const cpl_size n = cpl_matrix_get_ncol(U);
548 
549  /* Initialize the rotation counter and the sweep counter. *
550  * Use a minimum number of 12 sweeps. */
551  cpl_size count = 1;
552  cpl_size sweep = 0;
553  cpl_size sweepmax = CPL_MAX(5 * n, 12);
554 
555  double tolerance = 10. * m * DBL_EPSILON;
556 
557  /* Fill V with the identity matrix. */
558  cpl_matrix_fill(V, 0.);
559  cpl_matrix_fill_diagonal(V, 1., 0);
560 
561  /* Store the column error estimates in S, for use during the *
562  * orthogonalization. */
563 
564  cpl_size i;
565  cpl_size j;
566  cpl_vector *cv1 = cpl_vector_new(m);
567  double *const _cv1 = cpl_vector_get_data(cv1);
568 
569  for (j = 0; j < n; ++j) {
570  for (i = 0; i < m; ++i) {
571  _cv1[i] = cpl_matrix_get(U, i, j);
572  }
573 
574  double s = sqrt(cpl_vector_product(cv1, cv1));
575  cpl_vector_set(S, j, DBL_EPSILON * s);
576  }
577 
578  /* Orthogonalization of U by plane rotations. */
579  cpl_vector *cv2 = cpl_vector_new(m);
580  double *const _cv2 = cpl_vector_get_data(cv2);
581 
582  while ((count > 0) && (sweep <= sweepmax)) {
583 
584  /* Initialize the rotation counter. */
585  count = n * (n - 1) / 2;
586 
587  for (j = 0; j < n - 1; ++j) {
588  cpl_size k;
589  for (k = j + 1; k < n; ++k) {
590  for (i = 0; i < m; ++i) {
591  _cv1[i] = cpl_matrix_get(U, i, j);
592  }
593  for (i = 0; i < m; ++i) {
594  _cv2[i] = cpl_matrix_get(U, i, k);
595  }
596 
597  /* Compute the (j, k) submatrix elements of Ut*U. The *
598  * non-diagonal element c is scaled by 2. */
599  double a = sqrt(cpl_vector_product(cv1, cv1));
600  double b = sqrt(cpl_vector_product(cv2, cv2));
601  double c = 2. * cpl_vector_product(cv1, cv2);
602 
603  /* Test whether columns j, k are orthogonal, or dominant errors. */
604  double abserr_a = cpl_vector_get(S, j);
605  double abserr_b = cpl_vector_get(S, k);
606  cpl_boolean orthogonal = (fabs(c) <= tolerance * a * b);
607  cpl_boolean sorted = (a >= b);
608  cpl_boolean noisy_a = (a < abserr_a);
609  cpl_boolean noisy_b = (b < abserr_b);
610 
611  if (sorted && (orthogonal || noisy_a || noisy_b)) {
612  --count;
613  continue;
614  }
615 
616  /* Compute the Jacobi rotation which diagonalizes the (j, k) *
617  * submatrix. */
618  double q = a * a - b * b;
619  double v = sqrt(c * c + q * q);
620  double cs; /* cos(theta) */
621  double sn; /* sin(theta) */
622 
623  if (v == 0. || !sorted) {
624  cs = 0.;
625  sn = 1.;
626  } else {
627  cs = sqrt((v + q) / (2. * v));
628  sn = c / (2. * v * cs);
629  }
630 
631  /* Update the columns j and k of U and V */
632  for (i = 0; i < m; ++i) {
633  const double u_ij = cpl_matrix_get(U, i, j);
634  const double u_ik = cpl_matrix_get(U, i, k);
635  cpl_matrix_set(U, i, j, u_ij * cs + u_ik * sn);
636  cpl_matrix_set(U, i, k, -u_ij * sn + u_ik * cs);
637  }
638 
639  for (i = 0; i < n; ++i) {
640  const double v_ij = cpl_matrix_get(V, i, j);
641  const double v_ik = cpl_matrix_get(V, i, k);
642  cpl_matrix_set(V, i, j, v_ij * cs + v_ik * sn);
643  cpl_matrix_set(V, i, k, -v_ij * sn + v_ik * cs);
644  }
645 
646  cpl_vector_set(S, j, fabs(cs) * abserr_a +
647  fabs(sn) * abserr_b);
648  cpl_vector_set(S, k, fabs(sn) * abserr_a +
649  fabs(cs) * abserr_b);
650  }
651  }
652  ++sweep;
653 
654  }
655  cpl_vector_delete(cv2);
656 
657  /* Compute singular values. */
658  double prev_norm = -1.;
659  for (j = 0; j < n; ++j) {
660  for (i = 0; i < m; ++i) {
661  _cv1[i] = cpl_matrix_get(U, i, j);
662  }
663 
664  double norm = sqrt(cpl_vector_product(cv1, cv1));
665 
666  /* Determine if the singular value is zero, according to the *
667  * criteria used in the main loop above (i.e. comparison with *
668  * norm of previous column). */
669  if ((norm == 0.) || (prev_norm == 0.) ||
670  ((j > 0) && (norm <= tolerance * prev_norm))) {
671  cpl_vector_set(S, j, 0.); /* singular */
672  cpl_matrix_fill_column(U, 0., j); /* annihilate column */
673  prev_norm = 0.;
674  } else {
675  cpl_vector_set(S, j, norm); /* non-singular */
676 
677  /* Normalize the column vector of U */
678  for (i = 0; i < m; ++i) {
679  cpl_matrix_set(U, i, j, _cv1[i] / norm);
680  }
681  prev_norm = norm;
682  }
683  }
684  cpl_vector_delete(cv1);
685 
686  if (count > 0) {
687  return CPL_ERROR_CONTINUE;
688  }
689  return CPL_ERROR_NONE;
690 }
691 
692 /*----------------------------------------------------------------------------*/
701 /*----------------------------------------------------------------------------*/
702 static cpl_matrix *
703 muse_cplmatrix_solve_svd(const cpl_matrix *coeff, const cpl_matrix *rhs)
704 {
705  cpl_ensure((coeff != NULL) && (rhs != NULL), CPL_ERROR_NULL_INPUT, NULL);
706  cpl_ensure(cpl_matrix_get_nrow(coeff) == cpl_matrix_get_nrow(rhs),
707  CPL_ERROR_INCOMPATIBLE_INPUT, NULL);
708  cpl_ensure(cpl_matrix_get_ncol(rhs) == 1, CPL_ERROR_ILLEGAL_INPUT, NULL);
709 
710  /* Compute the SVD factorization of the coefficient matrix */
711  cpl_matrix *U = cpl_matrix_duplicate(coeff);
712  cpl_size nc = cpl_matrix_get_ncol(U);
713 
714  cpl_matrix *V = cpl_matrix_new(nc, nc);
715  cpl_vector *S = cpl_vector_new(nc);
716 
717  cpl_error_code status = muse_cplmatrix_decomp_sv_jacobi(U, S, V);
718  if (status != CPL_ERROR_NONE) {
719  cpl_vector_delete(S);
720  cpl_matrix_delete(V);
721  cpl_matrix_delete(U);
722  cpl_error_set_where(cpl_func);
723  return NULL;
724  }
725 
726  /* Solve the linear system */
727  cpl_matrix *Ut = cpl_matrix_transpose_create(U);
728  cpl_matrix *w = cpl_matrix_product_create(Ut, rhs);
729  cpl_matrix_delete(Ut);
730 
731  const double *_s = cpl_vector_get_data_const(S);
732  double *_w = cpl_matrix_get_data(w);
733  cpl_size ic;
734 
735  for (ic = 0; ic < nc; ++ic) {
736  double s = _s[ic];
737  if (s != 0.) {
738  s = 1. / s;
739  }
740  _w[ic] *= s;
741  }
742 
743  cpl_matrix *solution = cpl_matrix_product_create(V, w);
744  cpl_matrix_delete(w);
745  cpl_vector_delete(S);
746  cpl_matrix_delete(V);
747  cpl_matrix_delete(U);
748  return solution;
749 }
750 
751 #endif
752 
753 #endif
754 
755 /*----------------------------------------------------------------------------*/
764 /*----------------------------------------------------------------------------*/
765 static cpl_matrix *
766 muse_cplmatrix_solve_least_square(const cpl_matrix *aMatrix1,
767  const cpl_matrix *aMatrix2)
768 {
769  cpl_ensure(aMatrix1 && aMatrix2, CPL_ERROR_NULL_INPUT, NULL);
770 
771  cpl_size nc = cpl_matrix_get_ncol(aMatrix1);
772  cpl_size nr = cpl_matrix_get_nrow(aMatrix1);
773  cpl_ensure(cpl_matrix_get_nrow(aMatrix2) == nr,
774  CPL_ERROR_INCOMPATIBLE_INPUT, NULL);
775 
776  cpl_matrix *result = NULL;
777  cpl_errorstate status = cpl_errorstate_get();
778 
779 #ifndef USE_SVD_SOLVER
780  if (nr == nc) {
781  result = cpl_matrix_solve(aMatrix1, aMatrix2);
782  } else {
783  /* Handle over- and under-determined systems */
784  if (nr > nc) {
785  result = cpl_matrix_solve_normal(aMatrix1, aMatrix2);
786  } else {
787  cpl_matrix *mt = cpl_matrix_transpose_create(aMatrix1);
788  cpl_matrix *mgram = cpl_matrix_product_create(aMatrix1, mt);
789  cpl_matrix *mw = cpl_matrix_solve(mgram, aMatrix2);
790 
791  result = cpl_matrix_product_create(mt, mw);
792  cpl_matrix_delete(mw);
793  cpl_matrix_delete(mgram);
794  cpl_matrix_delete(mt);
795  }
796  }
797 #else
798  if (nr >= nc) {
799  result = cpl_matrix_solve_svd(aMatrix1, aMatrix2);
800  } else {
801  cpl_matrix *mt = cpl_matrix_transpose_create(aMatrix1);
802  cpl_matrix *mgram = cpl_matrix_product_create(aMatrix1, mt);
803  cpl_matrix *mw = cpl_matrix_solve(mgram, aMatrix2);
804 
805  result = cpl_matrix_product_create(mt, mw);
806  cpl_matrix_delete(mw);
807  cpl_matrix_delete(mgram);
808  cpl_matrix_delete(mt);
809  }
810 #endif
811 
812  if (status != cpl_errorstate_get()) {
813  cpl_matrix_delete(result);
814  result = NULL;
815  }
816  return result;
817 }
818 
819 /*----------------------------------------------------------------------------*/
829 /*----------------------------------------------------------------------------*/
830 static cpl_error_code
831 muse_cplmatrix_cosine(cpl_matrix *aMatrix)
832 {
833  cpl_ensure(aMatrix, CPL_ERROR_NULL_INPUT, CPL_ERROR_NULL_INPUT);
834 
835  cpl_size size = cpl_matrix_get_nrow(aMatrix) * cpl_matrix_get_ncol(aMatrix);
836  double *mdata = cpl_matrix_get_data(aMatrix);
837 
838  cpl_size i;
839  for (i = 0; i < size; ++i) {
840  mdata[i] = cos(mdata[i]);
841  }
842  return CPL_ERROR_NONE;
843 }
844 
845 /*----------------------------------------------------------------------------*/
861 /*----------------------------------------------------------------------------*/
862 static cpl_error_code
863 muse_align_estimate_background(muse_image *aImage,
864  double aMinFraction, double aFraction,
865  double *bkgValue, double *bkgError)
866 {
867 
868  cpl_ensure(aImage, CPL_ERROR_NULL_INPUT, CPL_ERROR_NULL_INPUT);
869  cpl_ensure((aImage->data && aImage->header),
870  CPL_ERROR_ILLEGAL_INPUT, CPL_ERROR_ILLEGAL_INPUT);
871 
872  muse_image *image = muse_image_new();
873 
874  image->data = cpl_image_duplicate(aImage->data);
875  image->header = cpl_propertylist_duplicate(aImage->header);
876 
877 
878  /* A FOV image may have pixels set to NaN, which should be ignored *
879  * for estimating the background. Also set an empty DQ image so *
880  * that muse_sky_create_skymask() does not raise an error. */
881  cpl_image_reject_value(image->data, CPL_VALUE_NOTFINITE);
882  image->dq = cpl_image_new(cpl_image_get_size_x(image->data),
883  cpl_image_get_size_y(image->data),
884  CPL_TYPE_INT);
885  muse_mask *mask = muse_sky_create_skymask(image, aMinFraction, aFraction,
886  "ESO QC EXPALIGN BKG");
887  if (!mask) {
888  cpl_error_set_message(__func__, CPL_ERROR_ILLEGAL_OUTPUT,
889  "Creating background mask failed!");
890  return CPL_ERROR_ILLEGAL_OUTPUT;
891  }
892 
893  cpl_mask_not(mask->mask); /* invert mask to reject non-sky pixels */
894  cpl_image_reject_from_mask(image->data, mask->mask);
895  muse_mask_delete(mask);
896 
897  double bkg_sigma = 0.;
898  double bkg = cpl_image_get_mad(image->data, &bkg_sigma);
899 
900  muse_image_delete(image);
901 
902  *bkgValue = bkg;
903  *bkgError = bkg_sigma;
904 
905  return CPL_ERROR_NONE;
906 }
907 
908 /*----------------------------------------------------------------------------*/
924 /*----------------------------------------------------------------------------*/
925 static cpl_matrix *
926 muse_align_compute_distances(const cpl_matrix *aDeltaRA, const cpl_matrix *aDeltaDEC,
927  const cpl_matrix *aMeanDEC, const double *aOffsetRA,
928  const double *aOffsetDEC)
929 {
930 
931  cpl_errorstate status = cpl_errorstate_get();
932 
933  /* XXX: Cannot use cpl_matrix_power() here, since it chokes on negative *
934  * elements, however it should not if the exponent is integer! */
935 
936  cpl_matrix *dDEC;
937  if (aOffsetDEC) {
938  cpl_matrix *tmp = cpl_matrix_duplicate(aDeltaDEC);
939  cpl_matrix_subtract_scalar(tmp, *aOffsetDEC);
940 
941  dDEC = muse_cplmatrix_multiply_create(tmp, tmp);
942  cpl_matrix_delete(tmp);
943  } else {
944  dDEC = muse_cplmatrix_multiply_create(aDeltaDEC, aDeltaDEC);
945  }
946 
947  cpl_matrix *dec = cpl_matrix_duplicate(aMeanDEC);
948  muse_cplmatrix_cosine(dec);
949 
950  cpl_matrix *dRA;
951  if (aOffsetRA) {
952  dRA = cpl_matrix_duplicate(aDeltaRA);
953  cpl_matrix_subtract_scalar(dRA, *aOffsetRA);
954  cpl_matrix_multiply(dRA, dec);
955  } else {
956  dRA = muse_cplmatrix_multiply_create(aDeltaRA, dec);
957  }
958  cpl_matrix_delete(dec);
959 
960  cpl_matrix *distance = muse_cplmatrix_multiply_create(dRA, dRA);
961  cpl_matrix_delete(dRA);
962 
963  cpl_matrix_add(distance, dDEC);
964  cpl_matrix_power(distance, 0.5);
965  cpl_matrix_delete(dDEC);
966 
967  if (status != cpl_errorstate_get()) {
968  cpl_matrix_delete(distance);
969  return NULL;
970  }
971 
972  return distance;
973 }
974 
975 /*----------------------------------------------------------------------------*/
995 /*----------------------------------------------------------------------------*/
996 static cpl_size
997 muse_align_estimate_offsets(double *aOffsetRA, double *aOffsetDEC, double *aWeight,
998  const cpl_matrix *aDeltaRA, const cpl_matrix *aDeltaDEC,
999  const cpl_matrix *aMeanDEC, double aRadius, int aNbins)
1000 {
1001  cpl_ensure((aOffsetRA && aOffsetDEC) && aWeight, CPL_ERROR_NULL_INPUT, 0);
1002  cpl_ensure((aDeltaRA && aDeltaDEC) && aMeanDEC, CPL_ERROR_NULL_INPUT, 0);
1003  cpl_ensure(cpl_matrix_get_nrow(aDeltaRA) == cpl_matrix_get_nrow(aDeltaDEC),
1004  CPL_ERROR_INCOMPATIBLE_INPUT, 0);
1005  cpl_ensure(cpl_matrix_get_nrow(aDeltaRA) == cpl_matrix_get_nrow(aMeanDEC),
1006  CPL_ERROR_INCOMPATIBLE_INPUT, 0);
1007  cpl_ensure(aRadius > 0., CPL_ERROR_ILLEGAL_INPUT, 0);
1008  cpl_ensure(aNbins > 0, CPL_ERROR_ILLEGAL_INPUT, 0);
1009 
1010  cpl_matrix *distance = muse_align_compute_distances(aDeltaRA, aDeltaDEC,
1011  aMeanDEC, NULL, NULL);
1012  if (cpl_matrix_get_min(distance) >= aRadius) {
1013  cpl_matrix_delete(distance);
1014  *aOffsetRA = 0.;
1015  *aOffsetDEC = 0.;
1016  *aWeight = 1.;
1017  return 0;
1018  }
1019 
1020  cpl_array *selection = muse_cplmatrix_where(distance, aRadius,
1021  _muse_condition_less_than);
1022  cpl_matrix_delete(distance);
1023  cpl_matrix *dRA = muse_cplmatrix_extract_selected(aDeltaRA, selection);
1024  cpl_matrix *dDEC = muse_cplmatrix_extract_selected(aDeltaDEC, selection);
1025  cpl_array_delete(selection);
1026 
1027  /* Search box from -aRadius to aRadius for both axes. */
1028  double bstep = 2. * aRadius / (double)aNbins;
1029 
1030  /* Note: Despite of the previous selection of positions which have *
1031  * distances smaller than the search radius the bin index of the right *
1032  * ascension may become invalid and must be restricted to valid range. *
1033  * The reason is that in the following the difference in right ascension *
1034  * is directly compared to the search radius, while in the selection of *
1035  * positions this difference is corrected by the cosine of the mean *
1036  * declination (cf. muse_align_compute_distances()), and thus differences *
1037  * in right ascension which are larger than the search radius may still *
1038  * be accepted by the distance criterion! *
1039  * To play it save also the index along the y-axis is validated. */
1040 
1041  cpl_matrix *bins = cpl_matrix_new(1, aNbins);
1042  cpl_size ibin;
1043  for (ibin = 0; ibin < aNbins; ++ibin) {
1044  cpl_matrix_set(bins, 0, ibin, -aRadius + ibin * bstep);
1045  }
1046  cpl_matrix *histogram = cpl_matrix_new(aNbins, aNbins);
1047  double *hdata = cpl_matrix_get_data(histogram);
1048  cpl_size npos = cpl_matrix_get_ncol(dRA);
1049  cpl_size nmatch = 0;
1050  cpl_size ipos;
1051  for (ipos = 0; ipos < npos; ++ipos) {
1052  cpl_size ix = (cpl_size)((cpl_matrix_get(dRA, 0, ipos) + aRadius) / bstep);
1053  cpl_size iy = (cpl_size)((cpl_matrix_get(dDEC, 0, ipos) + aRadius) / bstep);
1054  if (((ix >= 0) && (ix < aNbins)) && ((iy >= 0) && (iy < aNbins))) {
1055  hdata[iy * aNbins + ix] += 1.;
1056  ++nmatch;
1057  }
1058  }
1059  cpl_matrix_delete(dRA);
1060  cpl_matrix_delete(dDEC);
1061 
1062  if (nmatch == 0) {
1063  cpl_matrix_delete(histogram);
1064  cpl_matrix_delete(bins);
1065  return 0;
1066  }
1067 
1068  cpl_size row;
1069  cpl_size column;
1070  cpl_matrix_get_maxpos(histogram, &row, &column);
1071 
1072  *aOffsetRA = cpl_matrix_get(bins, 0, column) + 0.5 * bstep;
1073  *aOffsetDEC = cpl_matrix_get(bins, 0, row) + 0.5 * bstep;
1074  *aWeight = cpl_matrix_get_max(histogram);
1075  cpl_matrix_delete(histogram);
1076  cpl_matrix_delete(bins);
1077 
1078  return nmatch;
1079 }
1080 
1081 /*----------------------------------------------------------------------------*/
1101 /*----------------------------------------------------------------------------*/
1102 static cpl_size
1103 muse_align_update_offsets(double *aOffsetRA, double *aOffsetDEC, double *aWeight,
1104  const cpl_matrix *aDeltaRA, const cpl_matrix *aDeltaDEC,
1105  const cpl_matrix *aMeanDEC, double aRadius)
1106 {
1107  cpl_ensure((aOffsetRA && aOffsetDEC) && aWeight, CPL_ERROR_NULL_INPUT,
1108  CPL_FALSE);
1109  cpl_ensure((aDeltaRA && aDeltaDEC) && aMeanDEC, CPL_ERROR_NULL_INPUT,
1110  CPL_FALSE);
1111  cpl_ensure(cpl_matrix_get_nrow(aDeltaRA) == cpl_matrix_get_nrow(aDeltaDEC),
1112  CPL_ERROR_INCOMPATIBLE_INPUT, CPL_FALSE);
1113  cpl_ensure(cpl_matrix_get_nrow(aDeltaRA) == cpl_matrix_get_nrow(aMeanDEC),
1114  CPL_ERROR_INCOMPATIBLE_INPUT, CPL_FALSE);
1115  cpl_ensure(aRadius > 0., CPL_ERROR_ILLEGAL_INPUT, CPL_FALSE);
1116 
1117  cpl_matrix *distance = muse_align_compute_distances(aDeltaRA, aDeltaDEC,
1118  aMeanDEC, aOffsetRA, aOffsetDEC);
1119  if (cpl_matrix_get_min(distance) >= aRadius) {
1120  cpl_matrix_delete(distance);
1121  *aOffsetRA = 0.;
1122  *aOffsetDEC = 0.;
1123  *aWeight = 1.;
1124  return 0;
1125  }
1126 
1127  cpl_array *selection = muse_cplmatrix_where(distance, aRadius,
1128  _muse_condition_less_than);
1129  cpl_matrix_delete(distance);
1130  cpl_matrix *dRA = muse_cplmatrix_extract_selected(aDeltaRA, selection);
1131  cpl_matrix *dDEC = muse_cplmatrix_extract_selected(aDeltaDEC, selection);
1132  cpl_array_delete(selection);
1133 
1134  cpl_size nselected = cpl_matrix_get_ncol(dRA);
1135  double variance = 2. * aRadius * aRadius;
1136  if (nselected > 1) {
1137  double sdevRA = cpl_matrix_get_stdev(dRA);
1138  double sdevDEC = cpl_matrix_get_stdev(dDEC);
1139  double _variance = sdevRA * sdevRA + sdevDEC * sdevDEC;
1140  if (_variance > nselected / DBL_MAX) {
1141  variance = _variance;
1142  }
1143  }
1144 
1145  *aOffsetRA = cpl_matrix_get_median(dRA);
1146  *aOffsetDEC = cpl_matrix_get_median(dDEC);
1147  *aWeight = nselected / variance;
1148 
1149  cpl_matrix_delete(dRA);
1150  cpl_matrix_delete(dDEC);
1151 
1152  return nselected;
1153 }
1154 
1155 /*----------------------------------------------------------------------------*/
1171 /*----------------------------------------------------------------------------*/
1172 static cpl_table *
1173 muse_align_compute_field_offsets(muse_imagelist *aImagelist,
1174  muse_table **aCataloglist,
1175  const cpl_array *aFieldId,
1176  const cpl_array *aSearchradius,
1177  int aNbins, cpl_boolean aWeight,
1178  cpl_propertylist *aHeader)
1179 {
1180  cpl_ensure(aImagelist && aCataloglist && aFieldId,
1181  CPL_ERROR_NULL_INPUT, NULL);
1182  cpl_ensure(aSearchradius, CPL_ERROR_NULL_INPUT, NULL);
1183  cpl_ensure(cpl_array_get_size(aFieldId) == muse_imagelist_get_size(aImagelist),
1184  CPL_ERROR_ILLEGAL_INPUT, NULL);
1185  cpl_ensure(aNbins > 1, CPL_ERROR_ILLEGAL_INPUT, NULL);
1186 
1187  cpl_size nfields = muse_imagelist_get_size(aImagelist);
1188  cpl_ensure(nfields >= 2, CPL_ERROR_DATA_NOT_FOUND, NULL);
1189 
1190  /* Create a list of all possible pairings of the input fields *
1191  * number of combinations: nfields choose 2 */
1192  cpl_size npairs = nfields * (nfields - 1) / 2;
1193 
1194  muse_indexpair *combinations = cpl_calloc(npairs, sizeof *combinations);
1195  cpl_size ipair = 0;
1196  cpl_size ifield;
1197  for (ifield = 0; ifield < nfields; ++ifield) {
1198  cpl_size jfield;
1199  for (jfield = ifield + 1; jfield < nfields; ++jfield) {
1200  combinations[ipair].first = ifield;
1201  combinations[ipair].second = jfield;
1202  ++ipair;
1203  }
1204  }
1205 
1206  /* record number of detections in each image as QC parameter */
1207  for (ifield = 0; ifield < nfields; ++ifield) {
1208  cpl_size kfield = cpl_array_get_cplsize(aFieldId, ifield, NULL);
1209  char *kw = cpl_sprintf(QC_ALIGN_NDETi, (int)kfield + 1);
1210  cpl_propertylist_append_int(aHeader, kw,
1211  cpl_table_get_nrow(aCataloglist[ifield]->table));
1212  cpl_free(kw);
1213  }
1214 
1215  /* prepare the data structure to record the number of matching *
1216  * objects found in each of the other fields to, eventually, *
1217  * compute the median number of matching detections for each *
1218  * field. */
1219  cpl_array **aoverlaps = cpl_calloc(nfields, sizeof(cpl_array *));
1220  for (ifield = 0; ifield < nfields; ++ifield) {
1221  aoverlaps[ifield] = cpl_array_new(nfields, CPL_TYPE_INT);
1222  }
1223 
1224  /* search for correlations */
1225  cpl_matrix *ra_offsets = NULL;
1226  cpl_matrix *dec_offsets = NULL;
1227  cpl_size *has_neighbors = cpl_malloc(nfields * sizeof *has_neighbors);
1228  cpl_size isearch;
1229  for (isearch = 0; isearch < cpl_array_get_size(aSearchradius); ++isearch) {
1230  double radius = cpl_array_get_double(aSearchradius, isearch, NULL);
1231 
1232  /* Clear the number of matching detections. Note that this resets all *
1233  * elements to valid. To exclude the elements which should not be taken *
1234  * into account in the final median computation they are invalidated. *
1235  * This must at least be done for the "diagonal" elements of this *
1236  * matrix like structure which would refer to the number of matching *
1237  * detections a field has with itself, since these are never computed. */
1238  for (ifield = 0; ifield < nfields; ++ifield) {
1239  cpl_array_fill_window_int(aoverlaps[ifield], 0, nfields, 0);
1240  /* XXX: To include combinations with zero matches in the median *
1241  * statistic, use the alternative invalidation scheme */
1242 #if 0
1243  cpl_array_set_invalid(aoverlaps[ifield], ifield);
1244 #else
1245  cpl_array_fill_window_invalid(aoverlaps[ifield], 0, nfields);
1246 #endif
1247  }
1248 
1249  /* The linear system consists of one row for each pair of fields, and *
1250  * the closure relation */
1251  cpl_matrix *weights = cpl_matrix_new(npairs + 1, nfields);
1252  cpl_matrix *offsets_ra = cpl_matrix_new(npairs + 1, 1);
1253  cpl_matrix *offsets_dec = cpl_matrix_new(npairs + 1, 1);
1254 
1255  cpl_matrix_fill_row(weights, 1., 0);
1256  cpl_size kpairs = 0;
1257 
1258  memset(has_neighbors, 0, nfields * sizeof *has_neighbors);
1259 
1260  for (ipair = 0; ipair < npairs; ++ipair) {
1261  /* Compute the distance between any 2 stars in the 2 fields */
1262  const cpl_table *catalog1 = aCataloglist[combinations[ipair].first]->table;
1263  const cpl_table *catalog2 = aCataloglist[combinations[ipair].second]->table;
1264 
1265  cpl_size nstars1 = cpl_table_get_nrow(catalog1);
1266  cpl_size nstars2 = cpl_table_get_nrow(catalog2);
1267 
1268  const double *ra1 = cpl_table_get_data_double_const(catalog1, "RA");
1269  const double *ra2 = cpl_table_get_data_double_const(catalog2, "RA");
1270  const double *dec1 = cpl_table_get_data_double_const(catalog1, "DEC");
1271  const double *dec2 = cpl_table_get_data_double_const(catalog2, "DEC");
1272 
1273  cpl_matrix *delta_ra = cpl_matrix_new(nstars1, nstars2);
1274  cpl_matrix *delta_dec = cpl_matrix_new(nstars1, nstars2);
1275  cpl_matrix *dec_mean = cpl_matrix_new(nstars1, nstars2);
1276 
1277  cpl_size irow;
1278  for (irow = 0; irow < nstars1; ++irow) {
1279  cpl_size icol;
1280  for (icol = 0; icol < nstars2; ++icol) {
1281  cpl_matrix_set(delta_ra, irow, icol, (ra1[irow] - ra2[icol]) * deg2as);
1282  cpl_matrix_set(delta_dec, irow, icol, (dec1[irow] - dec2[icol]) * deg2as);
1283  cpl_matrix_set(dec_mean, irow, icol,
1284  0.5 *(dec1[irow] + dec2[icol]) * CPL_MATH_RAD_DEG);
1285  }
1286  }
1287 
1288  double offset_ra = 0.;
1289  double offset_dec = 0.;
1290  double weight = 1.;
1291  cpl_size noverlap = 0;
1292  if (isearch == 0) {
1293  noverlap = muse_align_estimate_offsets(&offset_ra, &offset_dec, &weight,
1294  delta_ra, delta_dec, dec_mean,
1295  radius, aNbins);
1296  } else {
1297  offset_ra = cpl_matrix_get(ra_offsets, combinations[ipair].first, 0) -
1298  cpl_matrix_get(ra_offsets, combinations[ipair].second, 0);
1299  offset_dec = cpl_matrix_get(dec_offsets, combinations[ipair].first, 0) -
1300  cpl_matrix_get(dec_offsets, combinations[ipair].second, 0);
1301 
1302  noverlap = muse_align_update_offsets(&offset_ra, &offset_dec, &weight,
1303  delta_ra, delta_dec, dec_mean,
1304  radius);
1305  }
1306  cpl_matrix_delete(dec_mean);
1307  cpl_matrix_delete(delta_ra);
1308  cpl_matrix_delete(delta_dec);
1309 
1310  if (noverlap > 0) {
1311  if (!aWeight) {
1312  weight = 1.;
1313  }
1314 
1315  ++kpairs;
1316  cpl_matrix_set(offsets_ra, kpairs, 0, weight * offset_ra);
1317  cpl_matrix_set(offsets_dec, kpairs, 0, weight * offset_dec);
1318  cpl_matrix_set(weights, kpairs, combinations[ipair].first, weight);
1319  cpl_matrix_set(weights, kpairs, combinations[ipair].second, -weight);
1320  has_neighbors[combinations[ipair].first] += 1;
1321  has_neighbors[combinations[ipair].second] += 1;
1322 
1323  /* record the number of overlaps for later median computation */
1324  cpl_array_set_int(aoverlaps[combinations[ipair].first],
1325  combinations[ipair].second, noverlap);
1326  cpl_array_set_int(aoverlaps[combinations[ipair].second],
1327  combinations[ipair].first, noverlap);
1328  } /* if noverlap positive */
1329  } /* for ipair */
1330 
1331  /* Replace the solution from the previous iteration */
1332  cpl_matrix_delete(ra_offsets);
1333  cpl_matrix_delete(dec_offsets);
1334 
1335  /* If there is no field with overlapping neighbors there is no *
1336  * correction to the field coordinates, i.e. all offsets are 0. */
1337  if (!kpairs) {
1338  cpl_matrix_delete(offsets_dec);
1339  cpl_matrix_delete(offsets_ra);
1340  cpl_matrix_delete(weights);
1341 
1342  cpl_msg_warning(__func__, "No overlapping fields of view were found "
1343  "for search radius %.4f!", radius);
1344 
1345  ra_offsets = cpl_matrix_new(nfields, 1);
1346  dec_offsets = cpl_matrix_new(nfields, 1);
1347 
1348  } else {
1349  /* Use only the valid part of the matrices when solving the linear system */
1350  cpl_matrix *_weights = cpl_matrix_wrap(kpairs + 1, nfields,
1351  cpl_matrix_get_data(weights));
1352  cpl_matrix *_offsets_ra = cpl_matrix_wrap(kpairs + 1, 1,
1353  cpl_matrix_get_data(offsets_ra));
1354  cpl_matrix *_offsets_dec = cpl_matrix_wrap(kpairs + 1, 1,
1355  cpl_matrix_get_data(offsets_dec));
1356 
1357  ra_offsets = muse_cplmatrix_solve_least_square(_weights, _offsets_ra);
1358  dec_offsets = muse_cplmatrix_solve_least_square(_weights, _offsets_dec);
1359 
1360  cpl_matrix_unwrap(_offsets_dec);
1361  cpl_matrix_unwrap(_offsets_ra);
1362  cpl_matrix_unwrap(_weights);
1363 
1364  cpl_matrix_delete(offsets_dec);
1365  cpl_matrix_delete(offsets_ra);
1366  cpl_matrix_delete(weights);
1367  }
1368  } /* for isearch */
1369  cpl_free(combinations);
1370 
1371  /* Build the results table from the matrices, and add observation start *
1372  * from the image header as observation identifier. For isolated fields, *
1373  * i.e.fields which do not overlap with any other, the pointing *
1374  * corrections are forced to 0. For fields which have an offset could be *
1375  * computed it is converted to degrees. */
1376  cpl_table *offsets = muse_cpltable_new(muse_offset_list_def,
1377  muse_imagelist_get_size(aImagelist));
1378  cpl_size minmatch = LLONG_MAX,
1379  nomatch = 0;
1380  for (ifield = 0; ifield < nfields; ++ifield) {
1381  muse_image *fov = muse_imagelist_get(aImagelist, ifield);
1382  cpl_size field_id = cpl_array_get_cplsize(aFieldId, ifield, NULL);
1383  const char *timestamp = muse_pfits_get_dateobs(fov->header);
1384  double mjd = muse_pfits_get_mjdobs(fov->header);
1385  cpl_table_set_string(offsets, MUSE_OFFSETS_DATEOBS, ifield, timestamp);
1386  cpl_table_set_double(offsets, MUSE_OFFSETS_MJDOBS, ifield, mjd);
1387 
1388  if (has_neighbors[ifield]) {
1389  double ra_offset = cpl_matrix_get(ra_offsets, ifield, 0);
1390  double dec_offset = cpl_matrix_get(dec_offsets, ifield, 0);
1391  cpl_table_set_double(offsets, MUSE_OFFSETS_DRA, ifield, ra_offset / deg2as);
1392  cpl_table_set_double(offsets, MUSE_OFFSETS_DDEC, ifield, dec_offset / deg2as);
1393  /* record QC parameter */
1394  int nmedian = cpl_array_get_median(aoverlaps[ifield]);
1395  char *kw = cpl_sprintf(QC_ALIGN_NMATCHi, (int)field_id + 1);
1396  cpl_propertylist_append_int(aHeader, kw, nmedian);
1397  cpl_free(kw);
1398  if (nmedian < minmatch) {
1399  minmatch = nmedian;
1400  }
1401  } else {
1402  cpl_table_set_double(offsets, MUSE_OFFSETS_DRA, ifield, 0.);
1403  cpl_table_set_double(offsets, MUSE_OFFSETS_DDEC, ifield, 0.);
1404  char *kw = cpl_sprintf(QC_ALIGN_NMATCHi, (int)field_id + 1);
1405  cpl_propertylist_append_int(aHeader, kw, 0);
1406  cpl_free(kw);
1407  nomatch++;
1408  }
1409  } /* for ifield */
1410  cpl_propertylist_append_int(aHeader, QC_ALIGN_NMATCH_MIN, minmatch);
1411  cpl_propertylist_append_int(aHeader, QC_ALIGN_NOMATCH, nomatch);
1412  muse_vfree((void **)aoverlaps, nfields, (muse_free_func)cpl_array_delete);
1413  cpl_free(has_neighbors);
1414  cpl_matrix_delete(dec_offsets);
1415  cpl_matrix_delete(ra_offsets);
1416 
1417  /* Force the offset of the first field of view to be zero and *
1418  * invalidate the flux scaling column, so that by no scaling *
1419  * occurs during the exposure combination. */
1420  double ra_shift = cpl_table_get(offsets, MUSE_OFFSETS_DRA, 0, NULL);
1421  double dec_shift = cpl_table_get(offsets, MUSE_OFFSETS_DDEC, 0, NULL);
1422  cpl_table_subtract_scalar(offsets, MUSE_OFFSETS_DRA, ra_shift);
1423  cpl_table_subtract_scalar(offsets, MUSE_OFFSETS_DDEC, dec_shift);
1424  cpl_table_set_column_invalid(offsets, MUSE_OFFSETS_FSCALE, 0, nfields);
1425 
1426  /* Extra QC parameters: offset statistics, in arcsec */
1427  double qcmin = cpl_table_get_column_min(offsets, MUSE_OFFSETS_DRA) * 3600.;
1428  double qcmax = cpl_table_get_column_max(offsets, MUSE_OFFSETS_DRA) * 3600.;
1429  double qcmean = cpl_table_get_column_mean(offsets, MUSE_OFFSETS_DRA) * 3600.;
1430  double qcsdev = cpl_table_get_column_stdev(offsets, MUSE_OFFSETS_DRA) * 3600.;
1431 
1432  cpl_propertylist_append_float(aHeader, QC_ALIGN_DRA_MIN, qcmin);
1433  cpl_propertylist_append_float(aHeader, QC_ALIGN_DRA_MAX, qcmax);
1434  cpl_propertylist_append_float(aHeader, QC_ALIGN_DRA_MEAN, qcmean);
1435  cpl_propertylist_append_float(aHeader, QC_ALIGN_DRA_STDEV, qcsdev);
1436 
1437  qcmin = cpl_table_get_column_min(offsets, MUSE_OFFSETS_DDEC) * 3600.;
1438  qcmax = cpl_table_get_column_max(offsets, MUSE_OFFSETS_DDEC) * 3600.;
1439  qcmean = cpl_table_get_column_mean(offsets, MUSE_OFFSETS_DDEC) * 3600.;
1440  qcsdev = cpl_table_get_column_stdev(offsets, MUSE_OFFSETS_DDEC) * 3600.;
1441 
1442  cpl_propertylist_append_float(aHeader, QC_ALIGN_DDEC_MIN, qcmin);
1443  cpl_propertylist_append_float(aHeader, QC_ALIGN_DDEC_MAX, qcmax);
1444  cpl_propertylist_append_float(aHeader, QC_ALIGN_DDEC_MEAN, qcmean);
1445  cpl_propertylist_append_float(aHeader, QC_ALIGN_DDEC_STDEV, qcsdev);
1446 
1447  return offsets;
1448 }
1449 
1450 /*----------------------------------------------------------------------------*/
1459 /*----------------------------------------------------------------------------*/
1460 int
1461 muse_exp_align_compute(muse_processing *aProcessing,
1462  muse_exp_align_params_t *aParams)
1463 {
1464 
1465  cpl_size nexposures = cpl_frameset_count_tags(aProcessing->inframes,
1466  MUSE_TAG_IMAGE_FOV);
1467  if (nexposures < 2) {
1468  cpl_msg_error(__func__, "This recipe requires at least 2 input FOV "
1469  "images!");
1470  return -1;
1471  }
1472 
1473  /* Validate input parameters */
1474  cpl_msg_debug(__func__, "Validating source detection parameters");
1475  if (!muse_align_check_detection_params(aParams)) {
1476  cpl_error_set_where(__func__);
1477  return -1;
1478  }
1479 
1480  /* Load and validate all fov input images */
1481  cpl_msg_info(__func__, "Loading FOV images");
1482 
1483  muse_imagelist *fovimages = muse_processing_fov_load_all(aProcessing);
1484  if (!fovimages) {
1485  cpl_msg_error(__func__, "Could not load FOV input images!");
1486  return -1;
1487  }
1488  nexposures = (cpl_size)muse_imagelist_get_size(fovimages);
1489 
1490  cpl_size iexposure;
1491  for (iexposure = 0; iexposure < nexposures; ++iexposure) {
1492  const muse_image *fov = muse_imagelist_get(fovimages, iexposure);
1493  cpl_errorstate es = cpl_errorstate_get();
1494  double mjdobs = muse_pfits_get_mjdobs(fov->header);
1495 
1496  if (!cpl_errorstate_is_equal(es) &&
1497  cpl_error_get_code() == CPL_ERROR_DATA_NOT_FOUND) {
1498  cpl_msg_error(__func__, "Missing \"MJD-OBS\" in FOV image %"
1499  CPL_SIZE_FORMAT, iexposure + 1);
1500  muse_imagelist_delete(fovimages);
1501  return -1;
1502  } else {
1503  cpl_size jexposure;
1504  for (jexposure = iexposure + 1; jexposure < nexposures; ++jexposure) {
1505  const muse_image *_fov = muse_imagelist_get(fovimages, jexposure);
1506  double _mjdobs = muse_pfits_get_mjdobs(_fov->header);
1507  if (_mjdobs == mjdobs) {
1508  cpl_msg_warning(__func__, "Found FOV images with non-unique "
1509  "\"MJD-OBS\" value (image %" CPL_SIZE_FORMAT
1510  " and %" CPL_SIZE_FORMAT ")!", iexposure + 1,
1511  jexposure + 1);
1512  }
1513  }
1514  }
1515  } /* for iexposure */
1516 
1517  cpl_msg_info(__func__, "Computing pointing corrections for %" CPL_SIZE_FORMAT
1518  " FOV images", nexposures);
1519 
1520  /* Cleanup NaN values which are possibly present in the input images to *
1521  * flag bad pixel. Replace them with an appropriate numerical value */
1522  for (iexposure = 0; iexposure < nexposures; ++iexposure) {
1523  muse_image *image = muse_imagelist_get(fovimages, iexposure);
1524  cpl_image_reject_value(image->data, CPL_VALUE_NOTFINITE);
1525  muse_utils_replace_nan(image, 0.);
1526  }
1527 
1528  /* For each FOV input image run the source detection and collect *
1529  * the created source lists */
1530  int nobjects[2] = {aParams->srcmin, aParams->srcmax};
1531 
1532  double roundness[2] = {aParams->roundmin, aParams->roundmax};
1533  double sharpness[2] = {aParams->sharpmin, aParams->sharpmax};
1534 
1535  muse_table **srclists = cpl_calloc(nexposures, sizeof *srclists);
1536 
1537  for (iexposure = 0; iexposure < nexposures; ++iexposure) {
1538  cpl_msg_debug(__func__, "Detecting sources on image %" CPL_SIZE_FORMAT
1539  " of %" CPL_SIZE_FORMAT, iexposure + 1, nexposures);
1540 
1541  muse_image *fov = muse_imagelist_get(fovimages, iexposure);
1542 
1543  srclists[iexposure] = muse_table_new();
1544 
1545  /* Estimate FOV sky background for use as detection threshold */
1546  double bkg_sigma = 0.;
1547  double bkg = 0.;
1548  double threshold = aParams->threshold;
1549 
1550  muse_align_estimate_background(fov, aParams->bkgignore,
1551  aParams->bkgfraction, &bkg, &bkg_sigma);
1552 
1553  cpl_msg_info(__func__, "Median background level computed from sky mask: "
1554  "%.6f +/- %.6f (MAD)", bkg, bkg_sigma);
1555 
1556  if (aParams->threshold <= 0.) {
1557  threshold = bkg + fabs(threshold) * bkg_sigma;
1558  }
1559 
1560  cpl_boolean iterate = CPL_TRUE;
1561  int iteration = 0;
1562  cpl_size ndetections = 0;
1563  cpl_table *detections;
1564  cpl_image *image = cpl_image_cast(fov->data, CPL_TYPE_DOUBLE);
1565 
1566  /* If the image does not have an even number of pixels along the *
1567  * any axis discard the last column and row respectively. */
1568 
1569  /* XXX: The size limit along the x- and y-axis corresponds to *
1570  * minimum convolution box size of muse_find_stars(). This *
1571  * check should better be done in muse_find_stars() itself! */
1572  cpl_size nx = cpl_image_get_size_x(image);
1573  cpl_size ny = cpl_image_get_size_y(image);
1574 
1575  if ((nx < 6) || (ny < 6)) {
1576  cpl_image_delete(image);
1577  muse_vfree((void **)srclists, nexposures, (muse_free_func)muse_table_delete);
1578  muse_imagelist_delete(fovimages);
1579  cpl_msg_error(__func__, "Image %" CPL_SIZE_FORMAT " of %"
1580  CPL_SIZE_FORMAT "is too small!", iexposure + 1, nexposures);
1581  return -1;
1582  }
1583 
1584  if ((nx % 2 != 0) || (ny % 2 != 0)) {
1585  cpl_msg_debug(__func__, "Trimming image %" CPL_SIZE_FORMAT " to an "
1586  "even number of pixels along the axes.", iexposure + 1);
1587  if (nx % 2 != 0) {
1588  --nx;
1589  }
1590  if (ny % 2 != 0) {
1591  --ny;
1592  }
1593  cpl_image *_image = cpl_image_extract(image, 1, 1, nx, ny);
1594  if (!_image) {
1595  cpl_image_delete(image);
1596  muse_vfree((void **)srclists, nexposures, (muse_free_func)muse_table_delete);
1597  muse_imagelist_delete(fovimages);
1598  cpl_msg_error(__func__, "Trimming image %" CPL_SIZE_FORMAT " failed",
1599  iexposure + 1);
1600  return -1;
1601  }
1602  cpl_image_delete(image);
1603  image = _image;
1604  } /* if odd image dimension(s) */
1605 
1606  while (iterate) {
1607  cpl_errorstate status = cpl_errorstate_get();
1608 
1609  cpl_msg_info(__func__, "Searching for sources using pixel value %.6f "
1610  "as detection threshold", threshold);
1611 
1612  detections = muse_find_stars(image, threshold, aParams->fwhm,
1613  roundness, sharpness);
1614 
1615  if (!detections) {
1616  if (cpl_error_get_code() == CPL_ERROR_DATA_NOT_FOUND) {
1617  cpl_errorstate_set(status);
1618  ndetections = 0;
1619  } else {
1620  cpl_image_delete(image);
1621  muse_vfree((void **)srclists, nexposures, (muse_free_func)muse_table_delete);
1622  muse_imagelist_delete(fovimages);
1623  cpl_msg_error(__func__, "Source detection failed on image %"
1624  CPL_SIZE_FORMAT " of %" CPL_SIZE_FORMAT, iexposure + 1,
1625  nexposures);
1626  return -1;
1627  }
1628  } else {
1629  ndetections = cpl_table_get_nrow(detections);
1630  }
1631 
1632  if ((ndetections > 0) &&
1633  ((ndetections >= nobjects[0]) && (ndetections <= nobjects[1]))) {
1634  iterate = CPL_FALSE;
1635  } else {
1636  cpl_table_delete(detections);
1637  detections = NULL;
1638  if (++iteration < aParams->iterations) {
1639  if (ndetections > nobjects[1]) {
1640  threshold += aParams->step;
1641  } else {
1642  threshold -= aParams->step;
1643  if (threshold <= 0.) {
1644  iterate = CPL_FALSE;
1645  }
1646  }
1647  } else {
1648  iterate = CPL_FALSE;
1649  }
1650  }
1651  } /* while iterate */
1652  cpl_image_delete(image);
1653 
1654  if (!detections) {
1655  if (ndetections == 0) {
1656  cpl_msg_warning(__func__, "No point-sources were detected in image %"
1657  CPL_SIZE_FORMAT, iexposure + 1);
1658  } else if (ndetections < nobjects[0]) {
1659  cpl_msg_warning(__func__, "Too few (%" CPL_SIZE_FORMAT ") point-sources "
1660  "were detected in image %" CPL_SIZE_FORMAT, ndetections,
1661  iexposure + 1);
1662  } else if (ndetections > nobjects[1]) {
1663  cpl_msg_warning(__func__, "Too many (%" CPL_SIZE_FORMAT ") point-sources "
1664  "were detected in image %" CPL_SIZE_FORMAT, ndetections,
1665  iexposure + 1);
1666  } else {
1667  cpl_msg_warning(__func__, "Invalid number (%" CPL_SIZE_FORMAT ") of "
1668  "point-sources were detected in image %" CPL_SIZE_FORMAT,
1669  ndetections, iexposure + 1);
1670  }
1671  srclists[iexposure]->table = muse_cpltable_new(muse_source_list_def, 0);
1672  } else {
1673  cpl_msg_info(__func__, "%" CPL_SIZE_FORMAT " point-sources detected in "
1674  "image %" CPL_SIZE_FORMAT, ndetections, iexposure + 1);
1675 
1676  /* Compute right ascension and declination from the pixel coordinates of *
1677  * each detected point-source using the WCS information of each exposure */
1678  if (muse_align_celestial_from_pixel(detections, fov->header)) {
1679  muse_vfree((void **)srclists, nexposures, (muse_free_func)muse_table_delete);
1680  muse_imagelist_delete(fovimages);
1681  cpl_msg_error(__func__, "Computing WCS coordinates from pixel positions "
1682  "failed for image %" CPL_SIZE_FORMAT " of %"
1683  CPL_SIZE_FORMAT, iexposure + 1, nexposures);
1684  return -1;
1685  }
1686 
1687  cpl_size nsources = cpl_table_get_nrow(detections);
1688  cpl_table *srclist = muse_cpltable_new(muse_source_list_def, nsources);
1689 
1690  cpl_size isource;
1691  for (isource = 0; isource < nsources; ++isource) {
1692  double value = 0.;
1693  int invalid = 0;
1694 
1695  cpl_table_set_int(srclist, MUSE_SRCLIST_ID, isource, isource + 1);
1696 
1697  value = cpl_table_get_double(detections, MUSE_SRCLIST_X,
1698  isource, &invalid);
1699  cpl_table_set_double(srclist, MUSE_SRCLIST_X, isource, value);
1700  value = cpl_table_get_double(detections, MUSE_SRCLIST_Y,
1701  isource, &invalid);
1702  cpl_table_set_double(srclist, MUSE_SRCLIST_Y, isource, value);
1703  value = cpl_table_get_double(detections, MUSE_SRCLIST_FLUX,
1704  isource, &invalid);
1705  cpl_table_set_double(srclist, MUSE_SRCLIST_FLUX, isource, value);
1706  value = cpl_table_get_double(detections, MUSE_SRCLIST_SHARPNESS,
1707  isource, &invalid);
1708  cpl_table_set_double(srclist, MUSE_SRCLIST_SHARPNESS, isource, value);
1709  value = cpl_table_get_double(detections, MUSE_SRCLIST_ROUNDNESS,
1710  isource, &invalid);
1711  cpl_table_set_double(srclist, MUSE_SRCLIST_ROUNDNESS, isource, value);
1712  value = cpl_table_get_double(detections, MUSE_SRCLIST_RA,
1713  isource, &invalid);
1714  cpl_table_set_double(srclist, MUSE_SRCLIST_RA, isource, value);
1715  cpl_table_set_double(srclist, MUSE_SRCLIST_RACORR, isource, value);
1716  value = cpl_table_get_double(detections, MUSE_SRCLIST_DEC,
1717  isource, &invalid);
1718  cpl_table_set_double(srclist, MUSE_SRCLIST_DEC, isource, value);
1719  cpl_table_set_double(srclist, MUSE_SRCLIST_DECCORR, isource, value);
1720 
1721  }
1722 
1723  srclists[iexposure]->table = srclist;
1724  cpl_table_delete(detections);
1725  }
1726 
1727  srclists[iexposure]->header = cpl_propertylist_duplicate(fov->header);
1728 
1729  cpl_propertylist_erase_regexp(srclists[iexposure]->header, "^ESO QC.*",
1730  CPL_FALSE);
1731 
1732  cpl_propertylist_update_int(srclists[iexposure]->header,
1733  QC_ALIGN_NDET, ndetections);
1734  cpl_propertylist_update_float(srclists[iexposure]->header,
1735  QC_ALIGN_BKG_MEDIAN, bkg);
1736  cpl_propertylist_update_float(srclists[iexposure]->header,
1737  QC_ALIGN_BKG_MAD, bkg_sigma);
1738  cpl_propertylist_update_float(srclists[iexposure]->header,
1739  QC_ALIGN_THRESHOLD, threshold);
1740 
1741  } /* for iexposure */
1742 
1743 
1744  /* Compute exposure offsets */
1745  cpl_array *radii = muse_align_parse_valuelist(aParams->rsearch);
1746  if (!radii) {
1747  muse_vfree((void **)srclists, nexposures, (muse_free_func)muse_table_delete);
1748  muse_imagelist_delete(fovimages);
1749  cpl_msg_error(__func__, "Cannot compute field offsets! No valid search "
1750  "radius was given!");
1751  return -1;
1752  }
1753 
1754  /* XXX: Dealing with subsets of the input fields should be better *
1755  * integrated into the code structure, possibly done by *
1756  * muse_align_compute_field_offsets(). */
1757 
1758  /* Before the field offsets are calculated the fields and the source *
1759  * list with no detected sources have to be filtered out. They will *
1760  * be added again later when the final offset table is prepared. *
1761  * Their corresponding field offsets will be forced to zero. */
1762 
1763  muse_imagelist *_fovimages = muse_imagelist_new();
1764  muse_table **_srclists = cpl_calloc(nexposures, sizeof *_srclists);
1765  cpl_array *field_id = cpl_array_new(nexposures, CPL_TYPE_SIZE);
1766  cpl_propertylist *header = cpl_propertylist_new();
1767 
1768  cpl_size kexposures = 0;
1769  for (iexposure = 0; iexposure < nexposures; ++iexposure) {
1770  if (cpl_table_get_nrow(srclists[iexposure]->table) > 0) {
1771  muse_imagelist_set(_fovimages, muse_imagelist_get(fovimages, iexposure),
1772  kexposures);
1773  _srclists[kexposures] = srclists[iexposure];
1774  cpl_array_set(field_id, kexposures, iexposure);
1775  ++kexposures;
1776  } else {
1777  char *kw = cpl_sprintf(QC_ALIGN_NDETi, (int)iexposure + 1);
1778  cpl_propertylist_append_int(header, kw, 0);
1779  cpl_free(kw);
1780 
1781  kw = cpl_sprintf(QC_ALIGN_NMATCHi, (int)iexposure + 1);
1782  cpl_propertylist_append_int(header, kw, 0);
1783  cpl_free(kw);
1784 
1785  cpl_msg_warning(__func__, "No sources are available for image % "
1786  CPL_SIZE_FORMAT ". This field will be ignored and no "
1787  "coordinate offsets will be calculated!", iexposure + 1);
1788  }
1789  }
1790  _srclists = cpl_realloc(_srclists, kexposures * sizeof *_srclists);
1791  muse_cplarray_erase_invalid(field_id);
1792 
1793  if (kexposures < 2) {
1794  cpl_propertylist_delete(header);
1795  cpl_array_delete(field_id);
1796  muse_vfree((void **)_srclists, kexposures, (muse_free_func)muse_table_delete);
1797  muse_imagelist_delete(_fovimages);
1798  muse_vfree((void **)srclists, nexposures, (muse_free_func)muse_table_delete);
1799  muse_imagelist_delete(fovimages);
1800  cpl_msg_error(__func__, "Cannot compute field offsets! Source positions "
1801  "are only available for %" CPL_SIZE_FORMAT " out of %"
1802  CPL_SIZE_FORMAT " fields!", kexposures, nexposures);
1803  return -1;
1804  }
1805 
1806  cpl_msg_info(__func__, "Calculating field offsets...");
1807  cpl_table *offsets = muse_align_compute_field_offsets(_fovimages, _srclists,
1808  field_id, radii,
1809  aParams->nbins,
1810  aParams->weight,
1811  header);
1812 
1813  /* XXX: Update the number of fields without matches only after *
1814  * calling muse_align_compute_field_offsets(). Otherwise *
1815  * this value would be overwritten. */
1816 
1817  int nomatch = cpl_propertylist_get_int(header, QC_ALIGN_NOMATCH) +
1818  nexposures - kexposures;
1819  cpl_propertylist_update_int(header, QC_ALIGN_NOMATCH, nomatch);
1820 
1821 
1822  /* When cleaning up the filtered image list and the list of source lists *
1823  * just clean up the container, as the actual data is managed by their *
1824  * full versions. The filtered data structures just served as a view for *
1825  * the computation of the offsets. */
1826 
1827  cpl_free(_srclists);
1828  iexposure = muse_imagelist_get_size(_fovimages);
1829  while (iexposure) {
1830  (void)muse_imagelist_unset(_fovimages, 0);
1831  --iexposure;
1832  }
1833  muse_imagelist_delete(_fovimages);
1834 
1835  cpl_array_delete(radii);
1836  if (!offsets) {
1837  cpl_propertylist_delete(header);
1838  cpl_array_delete(field_id);
1839  muse_vfree((void **)srclists, nexposures, (muse_free_func)muse_table_delete);
1840  muse_imagelist_delete(fovimages);
1841  cpl_msg_error(__func__, "Could not compute FOV offsets for %"
1842  CPL_SIZE_FORMAT " images", nexposures);
1843  return -1;
1844  }
1845 
1846  /* Finalize the source list product, and add columns with the corrected *
1847  * source positions to the source lists. */
1848  for (iexposure = 0; iexposure < cpl_array_get_size(field_id); ++iexposure) {
1849  int invalid[2] = {0, 0};
1850  double shift_ra = cpl_table_get_double(offsets, MUSE_OFFSETS_DRA,
1851  iexposure, &invalid[0]);
1852  double shift_dec = cpl_table_get_double(offsets, MUSE_OFFSETS_DDEC,
1853  iexposure, &invalid[1]);
1854 
1855  cpl_size ifield = cpl_array_get(field_id, iexposure, NULL);
1856 
1857  if (invalid[0] || invalid[1]) {
1858  cpl_msg_warning(__func__, "Invalid field offsets found for field %"
1859  CPL_SIZE_FORMAT ". No Correction will not be applied to "
1860  "the position of the detected sources.", ifield);
1861  }
1862  else {
1863  cpl_table_subtract_scalar(srclists[ifield]->table, MUSE_SRCLIST_RACORR,
1864  shift_ra);
1865  cpl_table_subtract_scalar(srclists[ifield]->table, MUSE_SRCLIST_DECCORR,
1866  shift_dec);
1867  }
1868  }
1869 
1870  cpl_array_delete(field_id);
1871 
1872  /* Write offset table product to file */
1873  cpl_error_code rc = muse_processing_save_table(aProcessing, -1, offsets,
1874  header, MUSE_TAG_OFFSET_LIST,
1876  cpl_propertylist_delete(header);
1877  cpl_table_delete(offsets);
1878 
1879  /* Save source list products to file. Note that in order to get the *
1880  * header information from FOV image associated to the source list *
1881  * product it has to be saved using CPL calls directly. */
1882  for (iexposure = 0; iexposure < nexposures; ++iexposure) {
1883  muse_processing_save_table(aProcessing, -1, srclists[iexposure]->table,
1884  srclists[iexposure]->header,
1885  "SOURCE_LIST", MUSE_TABLE_TYPE_CPL);
1886 
1887  }
1888  muse_vfree((void **)srclists, nexposures, (muse_free_func)muse_table_delete);
1889  muse_imagelist_delete(fovimages);
1890 
1891  if (rc != CPL_ERROR_NONE) {
1892  return -1;
1893  }
1894 
1895  return 0;
1896 } /* muse_exp_align_compute() */
cpl_error_code muse_cplarray_erase_invalid(cpl_array *aArray)
Erase all invalid values from an array.
int srcmin
Minimum number of sources which must be found.
Structure definition for a collection of muse_images.
int weight
Use weighting.
void muse_image_delete(muse_image *aImage)
Deallocate memory associated to a muse_image object.
Definition: muse_image.c:85
const char * muse_pfits_get_extname(const cpl_propertylist *aHeaders)
find out the extension name
Definition: muse_pfits.c:205
double fwhm
FWHM in pixels of the convolution filter.
A structure containing a spatial two-axis WCS.
Definition: muse_wcs.h:105
cpl_size muse_pfits_get_naxis(const cpl_propertylist *aHeaders, unsigned int aAxis)
find out the size of a given axis
Definition: muse_pfits.c:242
cpl_image * data
the data extension
Definition: muse_image.h:46
void muse_mask_delete(muse_mask *aMask)
Deallocate memory associated to a muse_mask object.
Definition: muse_mask.c:78
double roundmax
Upper limit of the allowed point-source roundness.
cpl_image * stat
the statistics extension
Definition: muse_image.h:64
const char * muse_pfits_get_dateobs(const cpl_propertylist *aHeaders)
find out the date of observations
Definition: muse_pfits.c:364
const muse_cpltable_def muse_offset_list_def[]
void muse_imagelist_delete(muse_imagelist *aList)
Free the memory of the MUSE image list.
muse_image * muse_fov_load(const char *aFilename)
Load a FOV image into a MUSE image.
Definition: muse_utils.c:2864
const char * muse_pfits_get_bunit(const cpl_propertylist *aHeaders)
find out the unit string
Definition: muse_pfits.c:223
muse_table * muse_table_new(void)
Allocate memory for a new muse_table object.
Definition: muse_table.c:63
Structure definition of MUSE three extension FITS file.
Definition: muse_image.h:40
const char * muse_pfits_get_cunit(const cpl_propertylist *aHeaders, unsigned int aAxis)
find out the WCS axis unit string
Definition: muse_pfits.c:491
cpl_propertylist * header
the FITS header
Definition: muse_image.h:72
cpl_boolean muse_processing_check_intags(muse_processing *aProcessing, const char *aTag, int aNChars)
Check that a tag is part of the input tags of a processing structure.
double step
Increment/decrement of the threshold value in subsequent iterations.
unsigned int muse_imagelist_get_size(muse_imagelist *aList)
Return the number of stored images.
cpl_matrix * muse_cplmatrix_extract_selected(const cpl_matrix *aMatrix, const cpl_array *aIndices)
Extract the elements given by the index array.
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 bkgfraction
Fraction of the image (without the ignored part) to be considered as background.
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.
double sharpmax
Upper limit of the allowed point-source sharpness.
Structure to hold the parameters of the muse_exp_align recipe.
int srcmax
Maximum number of sources which may be found.
#define MUSE_WCS_KEYS
regular expression for WCS properties
Definition: muse_wcs.h:48
muse_image * muse_imagelist_get(muse_imagelist *aList, unsigned int aIdx)
Get the muse_image of given list index.
double threshold
Initial intensity threshold for detecting point sources. If the value is negative or zero the thresho...
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
int nbins
Number of bins to use for 2D histogram on the first iteration of the offset computation.
cpl_table * table
The table.
Definition: muse_table.h:49
double bkgignore
Fraction of the image to be ignored.
void muse_processing_append_used(muse_processing *aProcessing, cpl_frame *aFrame, cpl_frame_group aGroup, int aDuplicate)
Add a frame to the set of used frames.
Structure to store a table together with a property list.
Definition: muse_table.h:43
void muse_table_delete(muse_table *aTable)
Deallocate memory associated to a muse_table object.
Definition: muse_table.c:80
cpl_propertylist * header
the header
Definition: muse_table.h:56
const char * rsearch
Search radius (in arcsec) for each iteration of the offset computation.
const muse_cpltable_def muse_source_list_def[]
double muse_pfits_get_mjdobs(const cpl_propertylist *aHeaders)
find out the Julian Date of the observation
Definition: muse_pfits.c:346
Handling of "mask" files.
Definition: muse_mask.h:43
double roundmin
Lower limit of the allowed point-source roundness.
muse_imagelist * muse_imagelist_new(void)
Create a new (empty) MUSE image list.
cpl_matrix * muse_cplmatrix_multiply_create(const cpl_matrix *aMatrix1, const cpl_matrix *aMatrix2)
Compute the element-wise product of two matrices.
cpl_frameset * inframes
cpl_array * muse_cplmatrix_where(const cpl_matrix *aMatrix, double aValue, muse_cplmatrix_element_compare_func aCondition)
Select matrix elements according to a condition.
cpl_table * muse_find_stars(const cpl_image *aImage, double aHmin, double aFwhm, const double *aRoundLimits, const double *aSharpLimits)
Find positive brightness perturbations (i.e stars) in an image.
muse_mask * muse_sky_create_skymask(muse_image *, double, double, const char *)
Select spaxels to be considered as sky.
cpl_boolean iscelsph
Definition: muse_wcs.h:112
cpl_error_code muse_processing_save_table(muse_processing *aProcessing, int aIFU, void *aTable, cpl_propertylist *aHeader, const char *aTag, muse_table_type aType)
Save a computed table to disk.
muse_image * muse_image_new(void)
Allocate memory for a new muse_image object.
Definition: muse_image.c:66
cpl_mask * mask
The mask data.
Definition: muse_mask.h:49
cpl_error_code muse_imagelist_set(muse_imagelist *aList, muse_image *aImage, unsigned int aIdx)
Set the muse_image of given list index.
muse_image * muse_imagelist_unset(muse_imagelist *aList, unsigned int aIdx)
Unset the muse_image at given list index from the list.
cpl_error_code muse_image_dq_to_nan(muse_image *aImage)
Convert pixels flagged in the DQ extension to NANs in DATA (and STAT, if present).
Definition: muse_image.c:904
double sharpmin
Lower limit of the allowed point-source sharpness.