SourceXtractorPlusPlus  0.18
SourceXtractor++, the next generation SExtractor
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
WCS.cpp
Go to the documentation of this file.
1 
17 /*
18  * WCS.cpp
19  *
20  * Created on: Nov 17, 2016
21  * Author: mschefer
22  */
23 
24 #include <mutex>
25 
26 #include <boost/algorithm/string/trim.hpp>
27 
28 #include <fitsio.h>
29 
30 #include <wcslib/wcs.h>
31 #include <wcslib/wcshdr.h>
32 #include <wcslib/wcsfix.h>
33 #include <wcslib/wcsprintf.h>
34 #include <wcslib/getwcstab.h>
35 #if 0
36 #include <wcslib/dis.h>
37 #endif
38 
40 #include "ElementsKernel/Logging.h"
41 
43 
44 namespace SourceXtractor {
45 
46 static auto logger = Elements::Logging::getLogger("WCS");
47 
48 decltype(&lincpy) safe_lincpy = &lincpy;
49 
53 static void wcsRaiseOnParseError(int ret_code) {
54  switch (ret_code) {
55  case WCSHDRERR_SUCCESS:
56  break;
57  case WCSHDRERR_MEMORY:
58  throw Elements::Exception() << "wcslib failed to allocate memory";
59  case WCSHDRERR_PARSER:
60  throw Elements::Exception() << "wcslib failed to parse the FITS headers";
61  default:
62  throw Elements::Exception() << "Unexpected error when parsing the FITS WCS header: "
63  << ret_code;
64  }
65 }
66 
67 static void wcsLogErr(wcserr *err) {
68  if (err) {
69  logger.error() << err->file << ":" << err->line_no << " " << err->function;
70  logger.error() << err->msg;
71  }
72 }
73 
77 static void wcsRaiseOnTransformError(wcsprm *wcs, int ret_code) {
78  if (ret_code != WCSERR_SUCCESS) {
79  wcsLogErr(wcs->err);
80  wcsLogErr(wcs->lin.err);
81 #if 0
82  if (wcs->lin.dispre) {
83  wcsLogErr(wcs->lin.dispre->err);
84  }
85  if (wcs->lin.disseq) {
86  wcsLogErr(wcs->lin.disseq->err);
87  }
88 #endif
89  linfree(&wcs->lin);
90  throw InvalidCoordinatesException() << wcs_errmsg[ret_code];
91  }
92 }
93 
97 static std::set<std::string> wcsExtractKeywords(const char *header, int number_of_records) {
98  std::set<std::string> result;
99  for (const char *p = header; *p != '\0' && number_of_records; --number_of_records, p += 80) {
100  size_t len = strcspn(p, "= ");
101  result.insert(std::string(p, len));
102  }
103  return result;
104 }
105 
109 static void wcsCheckHeaders(const wcsprm *wcs, const char *headers_str, int number_of_records) {
110  auto headers = wcsExtractKeywords(headers_str, number_of_records);
111 
112 #if 0
113  // SIP present, but not specified in CTYPE
114  // See https://github.com/astrorama/SourceXtractorPlusPlus/issues/254#issuecomment-765235869
115  if (wcs->lin.dispre) {
116  bool sip_used = false, sip_specified = false;
117  for (int i = 0; i < wcs->naxis; ++i) {
118  sip_used |= (strncmp(wcs->lin.dispre->dtype[i], "SIP", 3) == 0);
119  size_t ctype_len = strlen(wcs->ctype[i]);
120  sip_specified |= (strncmp(wcs->ctype[i] + ctype_len - 4, "-SIP", 4) == 0);
121  }
122  if (sip_used && !sip_specified) {
123  logger.warn() << "SIP coefficients present, but CTYPE has not the '-SIP' suffix";
124  logger.warn() << "SIP distortion will be applied, but this may not be desired";
125  logger.warn() << "To suppress this warning, explicitly add the '-SIP' suffix to the CTYPE,";
126  logger.warn() << "or remove the SIP distortion coefficients";
127  }
128  }
129 #endif
130 }
131 
135 static void wcsReportWarnings(const char *err_buffer) {
136  if (err_buffer[0]) {
137  logger.warn() << "WCS generated some errors in strict mode. This may be OK.";
138  logger.warn() << "Will run in relaxed mode.";
139  const char *eol;
140  do {
141  eol = strchr(err_buffer, '\n');
142  if (eol) {
143  logger.warn() << std::string(err_buffer, eol - err_buffer);
144  err_buffer = eol + 1;
145  }
146  else {
147  logger.warn() << std::string(err_buffer);
148  }
149  } while (eol);
150  }
151 }
152 
158 static int wrapped_lincpy(int alloc, const struct linprm *linsrc, struct linprm *lindst) {
159  static std::mutex lincpy_mutex;
160  std::lock_guard<std::mutex> lock(lincpy_mutex);
161 
162  return lincpy(alloc, linsrc, lindst);
163 }
164 
165 
166 WCS::WCS(const FitsImageSource& fits_image_source) : m_wcs(nullptr, nullptr) {
167  int number_of_records = 0;
168  auto fits_headers = fits_image_source.getFitsHeaders(number_of_records);
169 
170  init(&(*fits_headers)[0], number_of_records);
171 }
172 
173 WCS::WCS(const WCS& original) : m_wcs(nullptr, nullptr) {
174 
175  //FIXME Horrible hack: I couldn't figure out how to properly do a deep copy wcsprm so instead
176  // of making a copy, I use the ascii headers output from the original to recreate a new one
177 
178  int number_of_records;
179  char *raw_header;
180 
181  if (wcshdo(WCSHDO_none, original.m_wcs.get(), &number_of_records, &raw_header) != 0) {
182  throw Elements::Exception() << "Failed to get the FITS headers for the WCS coordinate system when copying WCS";
183  }
184 
185  init(raw_header, number_of_records);
186 
187  free(raw_header);
188 }
189 
190 
191 void WCS::init(char* headers, int number_of_records) {
192  wcserr_enable(1);
193 
194  int nreject = 0, nwcs = 0, nreject_strict = 0;
195  wcsprm* wcs;
196 
197  // Write warnings to a buffer
198  wcsprintf_set(nullptr);
199 
200 #if 0
201  // Do a first pass, in strict mode, and ignore the result.
202  // Log the reported errors as warnings
203  int ret = wcspih(headers, number_of_records, WCSHDR_strict, 2, &nreject_strict, &nwcs, &wcs);
205  wcsReportWarnings(wcsprintf_buf());
206 #endif
207 
208  // Do a second pass, in relaxed mode. We use the result.
209  int ret = wcspih(headers, number_of_records, WCSHDR_all, 0, &nreject, &nwcs, &wcs);
211  wcsset(wcs);
212 
213  // There are some things worth reporting about which WCS will not necessarily complain
214  wcsCheckHeaders(wcs, headers, number_of_records);
215 
216  m_wcs = decltype(m_wcs)(wcs, [nwcs](wcsprm* ptr) {
217  int nwcs_copy = nwcs;
218  wcsfree(ptr);
219  wcsvfree(&nwcs_copy, &ptr);
220  });
221 
222 #if 0
223  int wcsver[3];
224  wcslib_version(wcsver);
225  if (wcsver[0] < 5 || (wcsver[0] == 5 && wcsver[1] < 18)) {
226  logger.info() << "wcslib " << wcsver[0] << "." << wcsver[1]
227  << " is not fully thread safe, using wrapped lincpy call!";
229  }
230 #else
232 #endif
233 }
234 
235 
237 }
238 
240  // wcsprm is in/out, since its member lin is modified by wcsp2s
241  wcsprm wcs_copy = *m_wcs;
242  wcs_copy.lin.flag = -1;
243  safe_lincpy(true, &m_wcs->lin, &wcs_copy.lin);
244  linset(&wcs_copy.lin);
245 
246  // +1 as fits standard coordinates start at 1
247  double pc_array[2] {image_coordinate.m_x + 1, image_coordinate.m_y + 1};
248 
249  double ic_array[2] {0, 0};
250  double wc_array[2] {0, 0};
251  double phi, theta;
252 
253  int status = 0;
254  wcsp2s(&wcs_copy, 1, 1, pc_array, ic_array, &phi, &theta, wc_array, &status);
255  int ret_val = wcsp2s(&wcs_copy, 1, 1, pc_array, ic_array, &phi, &theta, wc_array, &status);
256  wcsRaiseOnTransformError(&wcs_copy, ret_val);
257  linfree(&wcs_copy.lin);
258 
259  return WorldCoordinate(wc_array[0], wc_array[1]);
260 }
261 
263  // wcsprm is in/out, since its member lin is modified by wcss2p
264  wcsprm wcs_copy = *m_wcs;
265  wcs_copy.lin.flag = -1;
266  safe_lincpy(true, &m_wcs->lin, &wcs_copy.lin);
267  linset(&wcs_copy.lin);
268 
269  double pc_array[2] {0, 0};
270  double ic_array[2] {0, 0};
271  double wc_array[2] {world_coordinate.m_alpha, world_coordinate.m_delta};
272  double phi, theta;
273 
274  int status = 0;
275  int ret_val = wcss2p(&wcs_copy, 1, 1, wc_array, &phi, &theta, ic_array, pc_array, &status);
276  wcsRaiseOnTransformError(&wcs_copy, ret_val);
277  linfree(&wcs_copy.lin);
278 
279  return ImageCoordinate(pc_array[0] - 1, pc_array[1] - 1); // -1 as fits standard coordinates start at 1
280 }
281 
283  int nkeyrec;
284  char *raw_header;
285 
286  if (wcshdo(WCSHDO_none, m_wcs.get(), &nkeyrec, &raw_header) != 0) {
287  throw Elements::Exception() << "Failed to get the FITS headers for the WCS coordinate system";
288  }
289 
291  for (int i = 0; i < nkeyrec; ++i) {
292  char *hptr = &raw_header[80 * i];
293  std::string key(hptr, hptr + 8);
294  boost::trim(key);
295  std::string value(hptr + 9, hptr + 72);
296  boost::trim(value);
297  if (!key.empty()) {
298  headers.emplace(std::make_pair(key, value));
299  }
300  }
301 
302  free(raw_header);
303  return headers;
304 }
305 
307  m_wcs->crpix[0] -= pc.m_x;
308  m_wcs->crpix[1] -= pc.m_y;
309 }
310 
311 
312 }
WCS(const FitsImageSource &fits_image_source)
Definition: WCS.cpp:166
T empty(T...args)
static auto logger
Definition: WCS.cpp:46
std::unique_ptr< std::vector< char > > getFitsHeaders(int &number_of_records) const
static void wcsCheckHeaders(const wcsprm *wcs, const char *headers_str, int number_of_records)
Definition: WCS.cpp:109
decltype(&lincpy) safe_lincpy
Definition: WCS.cpp:48
static void wcsRaiseOnParseError(int ret_code)
Definition: WCS.cpp:53
T free(T...args)
void init(char *headers, int number_of_records)
Definition: WCS.cpp:191
STL class.
WorldCoordinate imageToWorld(ImageCoordinate image_coordinate) const override
Definition: WCS.cpp:239
static std::set< std::string > wcsExtractKeywords(const char *header, int number_of_records)
Definition: WCS.cpp:97
static void wcsRaiseOnTransformError(wcsprm *wcs, int ret_code)
Definition: WCS.cpp:77
T strlen(T...args)
T strcspn(T...args)
T lock(T...args)
T make_pair(T...args)
std::map< std::string, std::string > getFitsHeaders() const override
Definition: WCS.cpp:282
A pixel coordinate made of two integers m_x and m_y.
std::unique_ptr< wcsprm, std::function< void(wcsprm *)> > m_wcs
Definition: WCS.h:54
virtual ~WCS()
Definition: WCS.cpp:236
static int wrapped_lincpy(int alloc, const struct linprm *linsrc, struct linprm *lindst)
Definition: WCS.cpp:158
T get(T...args)
void addOffset(PixelCoordinate pc)
Definition: WCS.cpp:306
T insert(T...args)
STL class.
static void wcsReportWarnings(const char *err_buffer)
Definition: WCS.cpp:135
T strncmp(T...args)
static void wcsLogErr(wcserr *err)
Definition: WCS.cpp:67
T emplace(T...args)
ImageCoordinate worldToImage(WorldCoordinate world_coordinate) const override
Definition: WCS.cpp:262
static Logging getLogger(const std::string &name="")
T strchr(T...args)