lsst.afw  17.0.1-19-gee9b810f8+2
frameSetUtils.cc
Go to the documentation of this file.
1 /*
2  * LSST Data Management System
3  * Copyright 2017 LSST Corporation.
4  *
5  * This product includes software developed by the
6  * LSST Project (http://www.lsst.org/).
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the LSST License Statement and
19  * the GNU General Public License along with this program. If not,
20  * see <http://www.lsstcorp.org/LegalNotices/>.
21  */
22 
23 #include <algorithm>
24 #include <exception>
25 #include <memory>
26 #include <ostream>
27 #include <set>
28 #include <sstream>
29 #include <vector>
30 
31 #include "astshim.h"
32 
34 #include "lsst/afw/fits.h"
35 #include "lsst/geom/Angle.h"
36 #include "lsst/geom/Point.h"
37 #include "lsst/afw/geom/wcsUtils.h"
39 #include "lsst/afw/image/ImageBase.h" // for wcsNameForXY0
42 #include "lsst/pex/exceptions.h"
43 
44 namespace lsst {
45 namespace afw {
46 namespace geom {
47 namespace detail {
48 namespace {
49 
50 // destructively make a set of strings from a vector of strings
53 }
54 
55 /*
56  * Copy a FITS header card from a FitsChan to a PropertyList.
57  *
58  * Internal function for use by getPropertyListFromFitsChan.
59  *
60  * @param[in,out] metadata PropertyList to which to copy the value
61  * @param[in] name FITS header card name; used as the name for the new entry in `metadata`
62  * @param[in] foundValue Value and found flag returned by ast::FitsChan.getFits{X};
63  * foundValue.found must be true.
64  * @param[in] comment Card comment; if blank then no comment is written
65  *
66  * @throw lsst::pex::exceptions::LogicError if foundValue.found false.
67  */
68 template <typename T>
69 void setMetadataFromFoundValue(daf::base::PropertyList& metadata, std::string const& name,
70  ast::FoundValue<T> const& foundValue, std::string const& comment = "") {
71  if (!foundValue.found) {
72  throw LSST_EXCEPT(pex::exceptions::LogicError, "Bug! FitsChan card \"" + name + "\" not found");
73  }
74  if (comment.empty()) {
75  metadata.set(name, foundValue.value);
76  } else {
77  metadata.set(name, foundValue.value, comment);
78  }
79 }
80 
81 } // namespace
82 
84  // Exclude WCS A keywords because LSST uses them to store XY0
85  auto wcsANames = createTrivialWcsMetadata("A", lsst::geom::Point2I(0, 0))->names();
86  std::set<std::string> excludeNames(wcsANames.begin(), wcsANames.end());
87  // Ignore NAXIS1, NAXIS2 because if they are zero then AST will fail to read a WCS
88  // Ignore LTV1/2 because LSST adds it and this code should ignore it and not strip it
89  // Exclude comments and history to reduce clutter
90  std::set<std::string> moreNames{"NAXIS1", "NAXIS2", "LTV1", "LTV2", "COMMENT", "HISTORY"};
91  excludeNames.insert(moreNames.begin(), moreNames.end());
92 
93  // Replace RADECSYS with RADESYS if only the former is present
94  if (metadata.exists("RADECSYS") && !metadata.exists("RADESYS")) {
95  metadata.set("RADESYS", metadata.getAsString("RADECSYS"));
96  metadata.remove("RADECSYS");
97  }
98 
99  auto channel = getFitsChanFromPropertyList(metadata, excludeNames,
100  "Encoding=FITS-WCS, IWC=1, SipReplace=0, ReportLevel=3");
101  auto const initialNames = strip ? setFromVector(channel.getAllCardNames()) : std::set<std::string>();
103  try {
104  obj = channel.read();
105  } catch (std::runtime_error) {
106  throw LSST_EXCEPT(pex::exceptions::TypeError, "The metadata does not describe an AST object");
107  }
108 
110  if (!frameSet) {
112  "metadata describes a " + obj->getClassName() + ", not a FrameSet");
113  }
114  if (strip) {
115  auto const finalNames = setFromVector(channel.getAllCardNames());
116 
117  // FITS keywords that FitsChan stripped
118  std::set<std::string> namesChannelStripped;
119  std::set_difference(initialNames.begin(), initialNames.end(), finalNames.begin(), finalNames.end(),
120  std::inserter(namesChannelStripped, namesChannelStripped.begin()));
121 
122  // FITS keywords that FitsChan may strip that we want to keep in `metadata`
123  std::set<std::string> const namesToKeep = {"DATE-OBS", "MJD-OBS"};
124 
125  std::set<std::string> namesToStrip; // names to strip from metadata
126  std::set_difference(namesChannelStripped.begin(), namesChannelStripped.end(), namesToKeep.begin(),
127  namesToKeep.end(), std::inserter(namesToStrip, namesToStrip.begin()));
128  for (auto const& name : namesToStrip) {
129  metadata.remove(name);
130  }
131  }
132  return frameSet;
133 }
134 
136  // Record CRPIX in GRID coordinates
137  // so we can compute CRVAL after standardizing the SkyFrame to ICRS
138  // (that standardization is why we don't simply save CRVAL now)
139  std::vector<double> crpixGrid(2);
140  try {
141  crpixGrid[0] = metadata.getAsDouble("CRPIX1");
142  crpixGrid[1] = metadata.getAsDouble("CRPIX2");
144  // std::string used because e.what() returns a C string and two C strings cannot be added
146  e.what() + std::string("; cannot read metadata as a SkyWcs"));
147  }
148 
149  auto rawFrameSet = readFitsWcs(metadata, strip);
150  auto const initialBaseIndex = rawFrameSet->getBase();
151 
152  // Find the GRID frame
153  auto gridIndex = ast::FrameSet::NOFRAME;
154  if (rawFrameSet->findFrame(ast::Frame(2, "Domain=GRID"))) {
155  gridIndex = rawFrameSet->getCurrent();
156  } else {
157  // No appropriate GRID frame found; if the original base frame is of type Frame
158  // with 2 axes and a blank domain then use that, else give up
159  auto const baseFrame = rawFrameSet->getFrame(initialBaseIndex, false);
160  auto const baseClassName = rawFrameSet->getClassName();
161  if (baseFrame->getClassName() != "Frame") {
163  "The base frame is of type " + baseFrame->getClassName() +
164  "instead of Frame; cannot read metadata as a SkyWcs");
165  }
166  if (baseFrame->getNAxes() != 2) {
168  "The base frame has " + std::to_string(baseFrame->getNAxes()) +
169  " axes instead of 2; cannot read metadata as a SkyWcs");
170  }
171  if (baseFrame->getDomain() != "") {
173  "The base frame has domain \"" + baseFrame->getDomain() +
174  "\" instead of blank or GRID; cannot read metadata as a SkyWcs");
175  }
176  // Original base frame has a blank Domain, is of type Frame, and has 2 axes, so
177  // Set its domain to GRID, and set some other potentially useful attributes.
178  gridIndex = initialBaseIndex;
179  }
180 
181  // Find the IWC frame
182  if (!rawFrameSet->findFrame(ast::Frame(2, "Domain=IWC"))) {
183  throw LSST_EXCEPT(pex::exceptions::TypeError, "No IWC frame found; cannot read metadata as a SkyWcs");
184  }
185  auto const iwcIndex = rawFrameSet->getCurrent();
186  auto const iwcFrame = rawFrameSet->getFrame(iwcIndex);
187 
188  // Create a standard sky frame: ICRS with axis order RA, Dec
189 
190  // Create the a template for the standard sky frame
191  auto const stdSkyFrameTemplate = ast::SkyFrame("System=ICRS");
192 
193  // Locate a Frame in the target FrameSet that looks like the template
194  // and hence can be used as the original sky frame.
195  // We ignore the frame set returned by findFrame because that goes from pixels to sky,
196  // and using it would add an unwanted extra branch to our WCS; instead, later on,
197  // we compute a mapping from the old sky frame to the new sky frame and add that.
198  if (!rawFrameSet->findFrame(stdSkyFrameTemplate)) {
200  "Could not find a SkyFrame; cannot read metadata as a SkyWcs");
201  }
202  auto initialSkyIndex = rawFrameSet->getCurrent();
203 
204  // Compute a frame set that maps from the original sky frame to our desired sky frame template;
205  // this contains the mapping and sky frame we will insert into the frame set.
206  // (Temporarily set the base frame to the sky frame, because findFrame
207  // produces a mapping from base to the found frame).
208  rawFrameSet->setBase(initialSkyIndex);
209  auto stdSkyFrameSet = rawFrameSet->findFrame(stdSkyFrameTemplate);
210  if (!stdSkyFrameSet) {
212  "Bug: found a SkyFrame the first time, but not the second time");
213  }
214 
215  // Add the new mapping into rawFrameSet, connecting it to the original SkyFrame.
216  // Note: we use stdSkyFrameSet as the new frame (meaning stdSkyFrameSet's current frame),
217  // because, unlike stdSkyFrameTemplate, stdSkyFrameSet's current frame has inherited some
218  // potentially useful attributes from the old sky frame, such as epoch.
219  rawFrameSet->addFrame(initialSkyIndex, *stdSkyFrameSet->getMapping()->simplified(),
220  *stdSkyFrameSet->getFrame(ast::FrameSet::CURRENT));
221  auto const stdSkyIndex = rawFrameSet->getCurrent();
222  auto const stdSkyFrame = rawFrameSet->getFrame(stdSkyIndex, false);
223 
224  // Compute a mapping from PIXELS (0-based in parent coordinates)
225  // to GRID (1-based in local coordinates)
226  auto xy0 = getImageXY0FromMetadata(metadata, image::detail::wcsNameForXY0, strip);
227  std::vector<double> pixelToGridArray = {1.0 - xy0[0], 1.0 - xy0[1]}; // 1.0 for FITS vs LSST convention
228  auto pixelToGrid = ast::ShiftMap(pixelToGridArray);
229 
230  // Now construct the returned FrameDict
231  auto const gridToIwc = rawFrameSet->getMapping(gridIndex, iwcIndex)->simplified();
232  auto const pixelToIwc = pixelToGrid.then(*gridToIwc).simplified();
233  auto const iwcToStdSky = rawFrameSet->getMapping(iwcIndex, stdSkyIndex);
234 
235  auto frameDict = std::make_shared<ast::FrameDict>(ast::Frame(2, "Domain=PIXELS"), *pixelToIwc, *iwcFrame);
236  frameDict->addFrame("IWC", *iwcToStdSky, *stdSkyFrame);
237 
238  // Record CRVAL as SkyRef in the SkyFrame so it can easily be obtained later;
239  // set SkyRefIs = "Ignored" (the default) so SkyRef value is ignored instead of used as an offset
240  auto crpixPixels = pixelToGrid.applyInverse(crpixGrid);
241  auto crvalRad = frameDict->applyForward(crpixPixels);
242  auto skyFrame = std::dynamic_pointer_cast<ast::SkyFrame>(frameDict->getFrame("SKY", false));
243  if (!skyFrame) {
244  throw LSST_EXCEPT(pex::exceptions::LogicError, "SKY frame is not a SkyFrame");
245  }
246  skyFrame->setSkyRefIs("Ignored");
247  skyFrame->setSkyRef(crvalRad);
248 
249  return frameDict;
250 }
251 
253  int const numCards = fitsChan.getNCard();
254  auto metadata = std::make_shared<daf::base::PropertyList>();
255  for (int cardNum = 1; cardNum <= numCards; ++cardNum) {
256  fitsChan.setCard(cardNum);
257  auto const cardType = fitsChan.getCardType();
258  auto const cardName = fitsChan.getCardName();
259  auto const cardComment = fitsChan.getCardComm();
260  switch (cardType) {
261  case ast::CardType::FLOAT: {
262  auto foundValue = fitsChan.getFitsF();
263  setMetadataFromFoundValue(*metadata, cardName, foundValue, cardComment);
264  break;
265  }
266  case ast::CardType::INT: {
267  auto foundValue = fitsChan.getFitsI();
268  setMetadataFromFoundValue(*metadata, cardName, foundValue, cardComment);
269  break;
270  }
271  case ast::CardType::STRING: {
272  auto foundValue = fitsChan.getFitsS();
273  setMetadataFromFoundValue(*metadata, cardName, foundValue, cardComment);
274  break;
275  }
276  case ast::CardType::LOGICAL: {
277  auto foundValue = fitsChan.getFitsL();
278  setMetadataFromFoundValue(*metadata, cardName, foundValue, cardComment);
279  break;
280  }
281  case ast::CardType::UNDEF: {
282  if (cardComment.empty()) {
283  metadata->set(cardName, nullptr);
284  } else {
285  metadata->set(cardName, nullptr, cardComment);
286  }
287  break;
288  }
290  auto foundValue = fitsChan.getFitsCN();
291  setMetadataFromFoundValue(*metadata, cardName, foundValue, cardComment);
292  break;
293  }
295  // Drop HISTORY and COMMENT cards
296  break;
299  // PropertyList supports neither complex numbers nor cards with no value
301  os << "Card " << cardNum << " with name \"" << cardName << "\" has type "
302  << static_cast<int>(cardType) << ", which is not supported by PropertyList";
304  }
305  case ast::CardType::NOTYPE: {
306  // This should only occur if cardNum is invalid, and that should be impossible
308  os << "Bug! Card " << cardNum << " with name \"" << cardName
309  << "\" has type NOTYPE, which should not be possible";
311  }
312  }
313  }
314  return metadata;
315 }
316 
318  std::set<std::string> const& excludeNames,
319  std::string options) {
320  // Create FitsChan to receive each of the parameters
321  auto stream = ast::StringStream("");
322  auto fc = ast::FitsChan(stream, options);
323 
324  // Get the parameter names (in order if necessary)
325  daf::base::PropertyList const *pl = dynamic_cast<daf::base::PropertyList const *>(&metadata);
326  std::vector<std::string> allParamNames;
327  if (pl) {
328  allParamNames = pl->getOrderedNames();
329  } else {
330  allParamNames = metadata.paramNames(false);
331  }
332 
333  // Loop over the names and add them to the FitsChan if not excluded
334  for (auto const &fullName : allParamNames) {
335  if (excludeNames.count(fullName) == 0) {
336  std::size_t lastPeriod = fullName.rfind(char('.'));
337  auto name = (lastPeriod == std::string::npos) ? fullName : fullName.substr(lastPeriod + 1);
338  std::type_info const &type = metadata.typeOf(name);
339 
340  if (name.size() > 8) {
341  continue; // The name is too long for a FITS keyword; skip this item
342  }
343 
344  if (type == typeid(bool)) {
345  fc.setFitsL(name, metadata.get<bool>(name));
346  } else if (type == typeid(std::uint8_t)) {
347  fc.setFitsI(name, static_cast<int>(metadata.get<std::uint8_t>(name)));
348  } else if (type == typeid(int)) {
349  fc.setFitsI(name, metadata.get<int>(name));
350  } else if (type == typeid(double)) {
351  fc.setFitsF(name, metadata.get<double>(name));
352  } else if (type == typeid(float)) {
353  fc.setFitsF(name, static_cast<double>(metadata.get<float>(name)));
354  } else if (type == typeid(std::string)) {
355  std::string str = metadata.get<std::string>(name);
356  // No support for long strings yet so skip those
357  if (str.size() <= 68) {
358  fc.setFitsS(name, metadata.get<std::string>(name));
359  }
360  }
361  }
362  }
363  // Rewind the channel
364  fc.setCard(0);
365  return fc;
366 }
367 
368 } // namespace detail
369 } // namespace geom
370 } // namespace afw
371 } // namespace lsst
double getAsDouble(std::string const &name) const
FoundValue< std::string > getFitsCN(std::string const &name="", std::string defval="") const
virtual char const * what(void) const noexcept
T get(std::string const &name) const
CardType getCardType() const
T to_string(T... args)
std::string getCardComm() const
bool strip
Definition: fits.cc:883
T make_move_iterator(T... args)
T end(T... args)
std::shared_ptr< ast::FrameDict > readLsstSkyWcs(daf::base::PropertySet &metadata, bool strip=true)
Read an LSST celestial WCS FrameDict from a FITS header.
virtual void remove(std::string const &name)
std::vector< std::string > paramNames(bool topLevelOnly=true) const
std::string getCardName() const
static int constexpr CURRENT
int getNCard() const
void set(std::string const &name, T const &value)
STL class.
FoundValue< int > getFitsI(std::string const &name="", int defval=0) const
void setCard(int ind)
A base class for image defects.
ast::FitsChan getFitsChanFromPropertyList(daf::base::PropertySet &metadata, std::set< std::string > const &excludeNames={}, std::string options="")
Construct AST FitsChan from PropertyList.
FoundValue< std::string > getFitsS(std::string const &name="", std::string defval="") const
std::shared_ptr< daf::base::PropertyList > createTrivialWcsMetadata(std::string const &wcsName, lsst::geom::Point2I const &xy0)
Definition: wcsUtils.cc:51
static int constexpr NOFRAME
table::Key< table::Array< std::uint8_t > > frameSet
T str(T... args)
bool exists(std::string const &name) const
std::shared_ptr< daf::base::PropertyList > getPropertyListFromFitsChan(ast::FitsChan &fitsChan)
Copy values from an AST FitsChan into a PropertyList.
T dynamic_pointer_cast(T... args)
table::Key< int > type
Definition: Detector.cc:167
T count(T... args)
FoundValue< double > getFitsF(std::string const &name="", double defval=0) const
T insert(T... args)
T size(T... args)
STL class.
#define LSST_EXCEPT(type,...)
T begin(T... args)
lsst::geom::Point2I getImageXY0FromMetadata(daf::base::PropertySet &metadata, std::string const &wcsName, bool strip=false)
Definition: wcsUtils.cc:98
std::shared_ptr< ast::FrameSet > readFitsWcs(daf::base::PropertySet &metadata, bool strip=true)
Read a FITS convention WCS FrameSet from FITS metadata.
T substr(T... args)
std::string getAsString(std::string const &name) const
T inserter(T... args)
std::ostream * os
Definition: Schema.cc:746
std::vector< std::string > getOrderedNames() const
T set_difference(T... args)
std::string const wcsNameForXY0
Definition: ImageBase.h:71
std::type_info const & typeOf(std::string const &name) const
FoundValue< bool > getFitsL(std::string const &name="", bool defval=false) const