lsst.afw  14.0-56-gfbf220870
ExposureFormatter.cc
Go to the documentation of this file.
1 // -*- lsst-c++ -*-
2 
3 /*
4  * LSST Data Management System
5  * Copyright 2008, 2009, 2010 LSST Corporation.
6  *
7  * This product includes software developed by the
8  * LSST Project (http://www.lsst.org/).
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the LSST License Statement and
21  * the GNU General Public License along with this program. If not,
22  * see <http://www.lsstcorp.org/LegalNotices/>.
23  */
24 
25 /*
26  * Implementation of ExposureFormatter class
27  */
28 
29 #ifndef __GNUC__
30 #define __attribute__(x) /*NOTHING*/
31 #endif
32 static char const* SVNid __attribute__((unused)) = "$Id$";
33 
34 #include <cstdint>
35 #include <iostream>
36 #include <string>
37 
38 #include "boost/serialization/shared_ptr.hpp"
39 #include <boost/archive/binary_iarchive.hpp>
40 #include <boost/archive/binary_oarchive.hpp>
41 #include <boost/archive/text_iarchive.hpp>
42 #include <boost/archive/text_oarchive.hpp>
43 
44 #include "lsst/daf/base.h"
45 #include "lsst/pex/exceptions.h"
46 #include "lsst/daf/persistence.h"
47 #include "lsst/log/Log.h"
52 
53 // #include "lsst/afw/image/LSSTFitsResource.h"
54 
55 namespace {
56 LOG_LOGGER _log = LOG_GET("afw.ExposureFormatter");
57 }
58 
59 namespace lsst {
60 namespace afw {
61 namespace formatters {
62 
63 namespace dafBase = lsst::daf::base;
65 
66 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
68 public:
69  static std::string name();
70 };
71 
72 template <>
74  static std::string name = "ExposureU";
75  return name;
76 }
77 template <>
79  static std::string name = "ExposureI";
80  return name;
81 }
82 template <>
84  static std::string name = "ExposureF";
85  return name;
86 }
87 template <>
89  static std::string name = "ExposureD";
90  return name;
91 }
92 template <>
94  static std::string name = "ExposureL";
95  return name;
96 }
97 
98 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
103 
104 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
107  : daf::persistence::Formatter(typeid(this)), _policy(policy) {}
108 
109 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
111 
118 static std::string lookupFilterName(dafPersist::DbStorage* db, int filterId) {
119  db->setTableForQuery("Filter");
120  db->outColumn("filterName");
121  db->condParam<int>("id", filterId);
122  db->setQueryWhere("filterId = :id");
123  db->query();
124  if (!db->next() || db->columnIsNull(0)) {
126  (boost::format("Unable to get name for filter id: %d") % filterId).str());
127  }
128  std::string filterName = db->getColumnByPos<std::string>(0);
129  if (db->next()) {
131  (boost::format("Multiple names for filter id: %d") % filterId).str());
132  }
133  db->finishQuery();
134  return filterName;
135 }
136 
146 template <typename T>
147 static void setColumn(dafPersist::DbStorage* db, std::string const& colName,
148  std::shared_ptr<daf::base::PropertySet> source, std::string const& propName) {
149  if (!source->exists(propName)) {
150  db->setColumnToNull(colName);
151  } else {
152  db->setColumn<T>(colName, source->get<T>(propName));
153  }
154 }
155 
160 template <typename T1, typename T2>
161 static void setColumn(dafPersist::DbStorage* db,
162  std::string const& colName,
164  std::string const& propName
165  ) {
166  if (!source->exists(propName)) {
167  db->setColumnToNull(colName);
168  } else {
169  db->setColumn<T1>(colName, static_cast<T1>(source->get<T2>(propName)));
170  }
171 }
172 
173 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
177  LOGL_DEBUG(_log, "ExposureFormatter write start");
179  dynamic_cast<image::Exposure<ImagePixelT, MaskPixelT, VariancePixelT> const*>(persistable);
180  if (ip == 0) {
181  throw LSST_EXCEPT(pex::exceptions::RuntimeError, "Persisting non-Exposure");
182  }
183  // TODO: Replace this with something better in DM-10776
185  if (boost) {
186  LOGL_DEBUG(_log, "ExposureFormatter write BoostStorage");
187  boost->getOArchive() & *ip;
188  LOGL_DEBUG(_log, "ExposureFormatter write end");
189  return;
190  }
192  if (fits) {
193  LOGL_DEBUG(_log, "ExposureFormatter write FitsStorage");
194 
195  fits::ImageWriteOptions imageOptions, maskOptions, varianceOptions;
196  if (additionalData) {
197  try {
198  imageOptions = fits::ImageWriteOptions(*additionalData->getAsPropertySetPtr("image"));
199  maskOptions = fits::ImageWriteOptions(*additionalData->getAsPropertySetPtr("mask"));
200  varianceOptions = fits::ImageWriteOptions(*additionalData->getAsPropertySetPtr("variance"));
201  } catch (std::exception const& exc) {
202  LOGLS_WARN(_log, "Unable to construct Exposure write options (" << exc.what() <<
203  "); writing with default options");
204  }
205  }
206 
207  ip->writeFits(fits->getPath(), imageOptions, maskOptions, varianceOptions);
208  LOGL_DEBUG(_log, "ExposureFormatter write end");
209  return;
210  }
211  auto db = dynamic_cast<dafPersist::DbStorage*>(storage.get());
212  if (db) {
213  LOGL_DEBUG(_log, "ExposureFormatter write DbStorage");
214 
215  // Get the Wcs headers.
216  std::shared_ptr<daf::base::PropertySet> wcsProps = ip->getWcs()->getFitsMetadata();
217 
218  // Get the image headers.
220  if (!dp) {
222  "Unable to retrieve metadata from MaskedImage's Image");
223  }
224 
225  // Select a table to insert into based on the itemName.
226  std::string itemName = additionalData->get<std::string>("itemName");
227  std::string tableName = itemName;
228  if (_policy->exists(itemName)) {
229  std::shared_ptr<pex::policy::Policy> itemPolicy = _policy->getPolicy(itemName);
230  if (itemPolicy->exists("TableName")) {
231  tableName = itemPolicy->getString("TableName");
232  }
233  }
234  if (tableName != "Raw_Amp_Exposure" && tableName != "Science_Amp_Exposure") {
236  "Unknown table name for persisting Exposure to DbStorage: " + tableName +
237  "for item " + itemName);
238  }
239  db->setTableForInsert(tableName);
240 
241  // Set the identifier columns.
242 
243  int ampId = extractAmpId(additionalData);
244  // int ccdId = extractCcdId(additionalData);
245  int64_t fpaExposureId = extractFpaExposureId(dp);
246  int64_t ccdExposureId = extractCcdExposureId(dp);
247  int64_t ampExposureId = extractAmpExposureId(dp);
248 
249  if (tableName == "Raw_Amp_Exposure") {
250  db->setColumn<long long>("rawAmpExposureId", ampExposureId);
251  db->setColumn<long long>("rawCCDExposureId", ccdExposureId);
252  db->setColumn<long long>("rawFPAExposureId", fpaExposureId);
253  } else { // Science_Amp_Exposure
254  db->setColumn<long long>("scienceAmpExposureId", ampExposureId);
255  db->setColumn<long long>("scienceCCDExposureId", ccdExposureId);
256  db->setColumn<long long>("scienceFPAExposureId", fpaExposureId);
257  db->setColumn<long long>("rawAmpExposureId", ampExposureId);
258  // @todo Check that rawCCDExposureId == scienceCCDExposureId --
259  // KTL -- 2008-01-25
260  }
261 
262  db->setColumn<int>("ampId", ampId);
263 
264  // Set the URL column with the location of the FITS file.
265  setColumn<std::string>(db, "url", additionalData, "StorageLocation.FitsStorage");
266 
267  // Set the Wcs information columns.
268  setColumn<std::string>(db, "ctype1", wcsProps, "CTYPE1");
269  setColumn<std::string>(db, "ctype2", wcsProps, "CTYPE2");
270  setColumn<float, double>(db, "crpix1", wcsProps, "CRPIX1");
271  setColumn<float, double>(db, "crpix2", wcsProps, "CRPIX2");
272  setColumn<double>(db, "crval1", wcsProps, "CRVAL1");
273  setColumn<double>(db, "crval2", wcsProps, "CRVAL2");
274  if (tableName == "Raw_Amp_Exposure") {
275  setColumn<double>(db, "cd11", wcsProps, "CD1_1");
276  setColumn<double>(db, "cd21", wcsProps, "CD2_1");
277  setColumn<double>(db, "cd12", wcsProps, "CD1_2");
278  setColumn<double>(db, "cd22", wcsProps, "CD2_2");
279  } else {
280  setColumn<double>(db, "cd1_1", wcsProps, "CD1_1");
281  setColumn<double>(db, "cd2_1", wcsProps, "CD2_1");
282  setColumn<double>(db, "cd1_2", wcsProps, "CD1_2");
283  setColumn<double>(db, "cd2_2", wcsProps, "CD2_2");
284  }
285 
286  if (tableName == "Science_Amp_Exposure") {
287  // Set calibration data columns.
288  setColumn<float, double>(db, "photoFlam", dp, "PHOTFLAM");
289  setColumn<float, double>(db, "photoZP", dp, "PHOTZP");
290  }
291 
292  // Phew! Insert the row now.
293  db->insertRow();
294 
295  LOGL_DEBUG(_log, "ExposureFormatter write end");
296  return;
297  }
298  throw LSST_EXCEPT(pex::exceptions::RuntimeError, "Unrecognized FormatterStorage for Exposure");
299 }
300 
301 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
305  LOGL_DEBUG(_log, "ExposureFormatter read start");
306  // TODO: Replace this with something better in DM-10776
308  if (boost) {
309  LOGL_DEBUG(_log, "ExposureFormatter read BoostStorage");
312  boost->getIArchive() & *ip;
313  LOGL_DEBUG(_log, "ExposureFormatter read end");
314  return ip;
315  }
317  if (fits) {
318  LOGL_DEBUG(_log, "ExposureFormatter read FitsStorage");
320  if (additionalData->exists("llcX")) {
321  int llcX = additionalData->get<int>("llcX");
322  int llcY = additionalData->get<int>("llcY");
323  int width = additionalData->get<int>("width");
324  int height = additionalData->get<int>("height");
325  box = geom::Box2I(geom::Point2I(llcX, llcY), geom::Extent2I(width, height));
326  }
328  if (additionalData->exists("imageOrigin")) {
329  std::string originStr = additionalData->get<std::string>("imageOrigin");
330  if (originStr == "LOCAL") {
331  origin = image::LOCAL;
332  } else if (originStr == "PARENT") {
333  origin = image::PARENT;
334  } else {
336  (boost::format("Unknown ImageOrigin type %s specified in additional"
337  "data for retrieving Exposure from fits") %
338  originStr
339 
340  ).str());
341  }
342  }
344  new image::Exposure<ImagePixelT, MaskPixelT, VariancePixelT>(fits->getPath(), box, origin);
345  LOGL_DEBUG(_log, "ExposureFormatter read end");
346  return ip;
347  }
348  auto db = dynamic_cast<dafPersist::DbStorage*>(storage.get());
349  if (db) {
350  LOGL_DEBUG(_log, "ExposureFormatter read DbStorage");
351 
352  // Select a table to retrieve from based on the itemName.
353  std::string itemName = additionalData->get<std::string>("itemName");
354  std::string tableName = itemName;
355  if (_policy->exists(itemName)) {
356  std::shared_ptr<pex::policy::Policy> itemPolicy = _policy->getPolicy(itemName);
357  if (itemPolicy->exists("TableName")) {
358  tableName = itemPolicy->getString("TableName");
359  }
360  }
361  if (tableName != "Raw_Amp_Exposure" && tableName != "Science_Amp_Exposure") {
363  "Unknown table name for retrieving Exposure from DbStorage: " + tableName +
364  " for item " + itemName);
365  }
366  db->setTableForQuery(tableName);
367 
368  // Set the identifier column tests.
369  db->condParam<int64_t>("id", additionalData->getAsInt64("ampExposureId"));
370  if (tableName == "Raw_Amp_Exposure") {
371  db->setQueryWhere("rawAmpExposureId = :id");
372  } else { // Science_Amp_Exposure
373  db->setQueryWhere("scienceAmpExposureId = :id");
374  }
375 
376  db->outColumn("url");
377 
378  if (tableName == "Science_Amp_Exposure") {
379  // Set the Wcs information columns.
380  db->outColumn("ctype1");
381  db->outColumn("ctype2");
382  db->outColumn("crpix1");
383  db->outColumn("crpix2");
384  db->outColumn("crval1");
385  db->outColumn("crval2");
386  db->outColumn("cd11");
387  db->outColumn("cd21");
388  db->outColumn("cd12");
389  db->outColumn("cd22");
390 
391  // Set calibration data columns.
392  db->outColumn("photoFlam");
393  db->outColumn("photoZP");
394  }
395 
396  // Phew! Run the query.
397  db->query();
398  if (!db->next()) {
399  throw LSST_EXCEPT(pex::exceptions::RuntimeError, "Unable to retrieve row");
400  }
401  // ...
402  if (db->next()) {
403  throw LSST_EXCEPT(pex::exceptions::RuntimeError, "Non-unique Exposure retrieved");
404  }
405  db->finishQuery();
406 
407  // @todo Should really have FITS be a separate FormatterStorage.
408  // - KTL - 2007-11-29
409 
410  // Restore image from FITS...
413  db->getColumnByPos<std::string>(0));
415 
416  // Look up the filter name given the ID.
417  int filterId = db->getColumnByPos<int>(1);
418  std::string filterName = lookupFilterName(db, filterId);
419  dp->set("FILTER", filterName);
420 
421  // Set the image headers.
422  // Set the Wcs headers in ip->_wcs.
423 
424  // @todo Need to implement overwriting of FITS metadata PropertySet
425  // with values from database. - KTL - 2007-12-18
426 
427  LOGL_DEBUG(_log, "ExposureFormatter read end");
428  return ip;
429  }
430  throw LSST_EXCEPT(pex::exceptions::RuntimeError, "Unrecognized FormatterStorage for Exposure");
431 }
432 
433 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
438  // - KTL - 2007-11-29
439  throw LSST_EXCEPT(pex::exceptions::RuntimeError, "Unexpected call to update for Exposure");
440 }
441 
442 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
443 template <class Archive>
445  Archive& ar, unsigned int const, dafBase::Persistable* persistable) {
446  LOGL_DEBUG(_log, "ExposureFormatter delegateSerialize start");
449  if (ip == 0) {
450  throw LSST_EXCEPT(pex::exceptions::RuntimeError, "Serializing non-Exposure");
451  }
453  ar& * ip->getMetadata() & ip->_maskedImage; // & wcs; // TODO: replace this with what?
454  LOGL_DEBUG(_log, "ExposureFormatter delegateSerialize end");
455 }
456 
457 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT>
463 }
464 
466 #define INSTANTIATE(I, M, V) \
467  template class ExposureFormatter<I, M, V>; \
468  template void ExposureFormatter<I, M, V>::delegateSerialize<boost::archive::text_oarchive>( \
469  boost::archive::text_oarchive&, unsigned int const, dafBase::Persistable*); \
470  template void ExposureFormatter<I, M, V>::delegateSerialize<boost::archive::text_iarchive>( \
471  boost::archive::text_iarchive&, unsigned int const, dafBase::Persistable*); \
472  template void ExposureFormatter<I, M, V>::delegateSerialize<boost::archive::binary_oarchive>( \
473  boost::archive::binary_oarchive&, unsigned int const, dafBase::Persistable*); \
474  template void ExposureFormatter<I, M, V>::delegateSerialize<boost::archive::binary_iarchive>( \
475  boost::archive::binary_iarchive&, unsigned int const, dafBase::Persistable*);
476 
483 }
484 }
485 } // end afw::formatters
#define LOGLS_WARN(logger, message)
virtual void outColumn(std::string const &columnName, bool isExpr=false)
void setColumn(std::string const &columnName, T const &value)
A class to contain the data, WCS, and other information needed to describe an image of the sky...
Definition: Exposure.h:76
Options for writing an image to FITS.
Definition: fits.h:220
virtual void setQueryWhere(std::string const &whereClause)
int extractAmpId(std::shared_ptr< lsst::daf::base::PropertySet const > const &properties)
Definition: Utils.cc:110
int64_t extractCcdExposureId(std::shared_ptr< lsst::daf::base::PropertySet const > const &properties)
Definition: Utils.cc:124
#define LOGL_DEBUG(logger, message...)
void condParam(std::string const &paramName, T const &value)
An integer coordinate rectangle.
Definition: Box.h:55
STL class.
int64_t extractFpaExposureId(std::shared_ptr< lsst::daf::base::PropertySet const > const &properties)
Definition: Utils.cc:82
#define __attribute__(x)
Class implementing persistence and retrieval for Exposures.
int64_t extractAmpExposureId(std::shared_ptr< lsst::daf::base::PropertySet const > const &properties)
Definition: Utils.cc:135
A base class for image defects.
T what(T... args)
std::shared_ptr< lsst::daf::base::PropertySet > getMetadata() const
Return flexible metadata.
Definition: Exposure.h:221
virtual void update(lsst::daf::base::Persistable *persistable, std::shared_ptr< lsst::daf::persistence::FormatterStorage > storage, std::shared_ptr< lsst::daf::base::PropertySet > additionalData)
#define INSTANTIATE(FROMSYS, TOSYS)
Definition: Detector.cc:156
T dynamic_pointer_cast(T... args)
STL class.
T get(T... args)
static void delegateSerialize(Archive &ar, unsigned int const version, lsst::daf::base::Persistable *persistable)
virtual void setTableForQuery(std::string const &tableName, bool isExpr=false)
#define LSST_EXCEPT(type,...)
T const & getColumnByPos(int pos)
virtual lsst::daf::base::Persistable * read(std::shared_ptr< lsst::daf::persistence::FormatterStorage > storage, std::shared_ptr< lsst::daf::base::PropertySet > additionalData)
std::shared_ptr< geom::SkyWcs const > getWcs() const
Definition: Exposure.h:212
static std::shared_ptr< lsst::daf::persistence::Formatter > createInstance(std::shared_ptr< lsst::pex::policy::Policy > policy)
void writeFits(std::string const &fileName) const
Write an Exposure to a regular multi-extension FITS file.
Definition: Exposure.cc:151
ExposureFormatter(ExposureFormatter const &)=default
#define LOG_GET(logger)
virtual void setTableForInsert(std::string const &tableName)
float VariancePixel
default type for MaskedImage variance images
virtual void setColumnToNull(std::string const &columnName)
virtual void write(lsst::daf::base::Persistable const *persistable, std::shared_ptr< lsst::daf::persistence::FormatterStorage > storage, std::shared_ptr< lsst::daf::base::PropertySet > additionalData)