lsst.afw  16.0-43-gaa65a4573+1
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  std::string hdr = fits::makeLimitedFitsHeader(metadata, excludeNames);
100  ast::StringStream stream(hdr);
101  ast::FitsChan channel(stream, "Encoding=FITS-WCS, IWC=1, SipReplace=0");
102  auto const initialNames = strip ? setFromVector(channel.getAllCardNames()) : std::set<std::string>();
104  try {
105  obj = channel.read();
106  } catch (std::runtime_error) {
107  throw LSST_EXCEPT(pex::exceptions::TypeError, "The metadata does not describe an AST object");
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  }
282  auto foundValue = fitsChan.getFitsCN();
283  setMetadataFromFoundValue(*metadata, cardName, foundValue, cardComment);
284  break;
285  }
287  // Drop HISTORY and COMMENT cards
288  break;
291  case ast::CardType::UNDEF: {
292  // PropertyList supports neither complex numbers nor cards with no value
294  os << "Card " << cardNum << " with name \"" << cardName << "\" has type "
295  << static_cast<int>(cardType) << ", which is not supported by PropertyList";
297  }
298  case ast::CardType::NOTYPE: {
299  // This should only occur if cardNum is invalid, and that should be impossible
301  os << "Bug! Card " << cardNum << " with name \"" << cardName
302  << "\" has type NOTYPE, which should not be possible";
304  }
305  }
306  }
307  return metadata;
308 }
309 
310 } // namespace detail
311 } // namespace geom
312 } // namespace afw
313 } // 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
CardType getCardType() const
T to_string(T... args)
std::string getCardComm() const
std::vector< std::string > getAllCardNames()
bool strip
Definition: fits.cc:817
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::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.
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)
FoundValue< double > getFitsF(std::string const &name="", double defval=0) const
T insert(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.
std::string getAsString(std::string const &name) const
T inserter(T... args)
std::ostream * os
Definition: Schema.cc:737
T set_difference(T... args)
std::shared_ptr< Object > read()
std::string const wcsNameForXY0
Definition: ImageBase.h:71
std::string makeLimitedFitsHeader(lsst::daf::base::PropertySet const &metadata, std::set< std::string > const &excludeNames={})
Format a PropertySet into an FITS header string in a simplistic fashion.
Definition: fits.cc:422
FoundValue< bool > getFitsL(std::string const &name="", bool defval=false) const