lsst.afw  15.0-25-gacd707fca
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/afw/geom/Angle.h"
36 #include "lsst/afw/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", 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) {
108  "The metadata does not describe an AST object");
109  }
111  if (!frameSet) {
113  "metadata describes a " + obj->getClassName() + ", not a FrameSet");
114  }
115  if (strip) {
116  auto const finalNames = setFromVector(channel.getAllCardNames());
117 
118  // FITS keywords that FitsChan stripped
119  std::set<std::string> namesChannelStripped;
120  std::set_difference(initialNames.begin(), initialNames.end(), finalNames.begin(), finalNames.end(),
121  std::inserter(namesChannelStripped, namesChannelStripped.begin()));
122 
123  // FITS keywords that FitsChan may strip that we want to keep in `metadata`
124  std::set<std::string> const namesToKeep = {"DATE-OBS", "MJD-OBS"};
125 
126  std::set<std::string> namesToStrip; // names to strip from metadata
127  std::set_difference(namesChannelStripped.begin(), namesChannelStripped.end(), namesToKeep.begin(),
128  namesToKeep.end(), std::inserter(namesToStrip, namesToStrip.begin()));
129  for (auto const& name : namesToStrip) {
130  metadata.remove(name);
131  }
132  }
133  return frameSet;
134 }
135 
137  // Record CRPIX in GRID coordinates
138  // so we can compute CRVAL after standardizing the SkyFrame to ICRS
139  // (that standardization is why we don't simply save CRVAL now)
140  std::vector<double> crpixGrid(2);
141  try {
142  crpixGrid[0] = metadata.getAsDouble("CRPIX1");
143  crpixGrid[1] = metadata.getAsDouble("CRPIX2");
145  // std::string used because e.what() returns a C string and two C strings cannot be added
147  e.what() + std::string("; cannot read metadata as a SkyWcs"));
148  }
149 
150  auto rawFrameSet = readFitsWcs(metadata, strip);
151  auto const initialBaseIndex = rawFrameSet->getBase();
152 
153  // Find the GRID frame
154  auto gridIndex = ast::FrameSet::NOFRAME;
155  if (rawFrameSet->findFrame(ast::Frame(2, "Domain=GRID"))) {
156  gridIndex = rawFrameSet->getCurrent();
157  } else {
158  // No appropriate GRID frame found; if the original base frame is of type Frame
159  // with 2 axes and a blank domain then use that, else give up
160  auto const baseFrame = rawFrameSet->getFrame(initialBaseIndex, false);
161  auto const baseClassName = rawFrameSet->getClassName();
162  if (baseFrame->getClassName() != "Frame") {
164  "The base frame is of type " + baseFrame->getClassName() +
165  "instead of Frame; cannot read metadata as a SkyWcs");
166  }
167  if (baseFrame->getNAxes() != 2) {
169  "The base frame has " + std::to_string(baseFrame->getNAxes()) +
170  " axes instead of 2; cannot read metadata as a SkyWcs");
171  }
172  if (baseFrame->getDomain() != "") {
174  "The base frame has domain \"" + baseFrame->getDomain() +
175  "\" instead of blank or GRID; cannot read metadata as a SkyWcs");
176  }
177  // Original base frame has a blank Domain, is of type Frame, and has 2 axes, so
178  // Set its domain to GRID, and set some other potentially useful attributes.
179  gridIndex = initialBaseIndex;
180  }
181 
182  // Find the IWC frame
183  if (!rawFrameSet->findFrame(ast::Frame(2, "Domain=IWC"))) {
185  "No IWC frame found; cannot read metadata as a SkyWcs");
186  }
187  auto const iwcIndex = rawFrameSet->getCurrent();
188  auto const iwcFrame = rawFrameSet->getFrame(iwcIndex);
189 
190  // Create a standard sky frame: ICRS with axis order RA, Dec
191 
192  // Create the a template for the standard sky frame
193  auto const stdSkyFrameTemplate = ast::SkyFrame("System=ICRS");
194 
195  // Locate a Frame in the target FrameSet that looks like the template
196  // and hence can be used as the original sky frame.
197  // We ignore the frame set returned by findFrame because that goes from pixels to sky,
198  // and using it would add an unwanted extra branch to our WCS; instead, later on,
199  // we compute a mapping from the old sky frame to the new sky frame and add that.
200  if (!rawFrameSet->findFrame(stdSkyFrameTemplate)) {
202  "Could not find a SkyFrame; cannot read metadata as a SkyWcs");
203  }
204  auto initialSkyIndex = rawFrameSet->getCurrent();
205 
206  // Compute a frame set that maps from the original sky frame to our desired sky frame template;
207  // this contains the mapping and sky frame we will insert into the frame set.
208  // (Temporarily set the base frame to the sky frame, because findFrame
209  // produces a mapping from base to the found frame).
210  rawFrameSet->setBase(initialSkyIndex);
211  auto stdSkyFrameSet = rawFrameSet->findFrame(stdSkyFrameTemplate);
212  if (!stdSkyFrameSet) {
214  "Bug: found a SkyFrame the first time, but not the second time");
215  }
216 
217  // Add the new mapping into rawFrameSet, connecting it to the original SkyFrame.
218  // Note: we use stdSkyFrameSet as the new frame (meaning stdSkyFrameSet's current frame),
219  // because, unlike stdSkyFrameTemplate, stdSkyFrameSet's current frame has inherited some
220  // potentially useful attributes from the old sky frame, such as epoch.
221  rawFrameSet->addFrame(initialSkyIndex, *stdSkyFrameSet->getMapping()->simplify(),
222  *stdSkyFrameSet->getFrame(ast::FrameSet::CURRENT));
223  auto const stdSkyIndex = rawFrameSet->getCurrent();
224  auto const stdSkyFrame = rawFrameSet->getFrame(stdSkyIndex, false);
225 
226  // Compute a mapping from PIXELS (0-based in parent coordinates)
227  // to GRID (1-based in local coordinates)
228  auto xy0 = getImageXY0FromMetadata(metadata, image::detail::wcsNameForXY0, strip);
229  std::vector<double> pixelToGridArray = {1.0 - xy0[0], 1.0 - xy0[1]}; // 1.0 for FITS vs LSST convention
230  auto pixelToGrid = ast::ShiftMap(pixelToGridArray);
231 
232  // Now construct the returned FrameDict
233  auto const gridToIwc = rawFrameSet->getMapping(gridIndex, iwcIndex)->simplify();
234  auto const pixelToIwc = pixelToGrid.then(*gridToIwc).simplify();
235  auto const iwcToStdSky = rawFrameSet->getMapping(iwcIndex, stdSkyIndex);
236 
237  auto frameDict = std::make_shared<ast::FrameDict>(ast::Frame(2, "Domain=PIXELS"), *pixelToIwc, *iwcFrame);
238  frameDict->addFrame("IWC", *iwcToStdSky, *stdSkyFrame);
239 
240  // Record CRVAL as SkyRef in the SkyFrame so it can easily be obtained later;
241  // set SkyRefIs = "Ignored" (the default) so SkyRef value is ignored instead of used as an offset
242  auto crpixPixels = pixelToGrid.applyInverse(crpixGrid);
243  auto crvalRad = frameDict->applyForward(crpixPixels);
244  auto skyFrame = std::dynamic_pointer_cast<ast::SkyFrame>(frameDict->getFrame("SKY", false));
245  if (!skyFrame) {
246  throw LSST_EXCEPT(pex::exceptions::LogicError, "SKY frame is not a SkyFrame");
247  }
248  skyFrame->setSkyRefIs("Ignored");
249  skyFrame->setSkyRef(crvalRad);
250 
251  return frameDict;
252 }
253 
255  int const numCards = fitsChan.getNCard();
256  auto metadata = std::make_shared<daf::base::PropertyList>();
257  for (int cardNum = 1; cardNum <= numCards; ++cardNum) {
258  fitsChan.setCard(cardNum);
259  auto const cardType = fitsChan.getCardType();
260  auto const cardName = fitsChan.getCardName();
261  auto const cardComment = fitsChan.getCardComm();
262  switch (cardType) {
263  case ast::CardType::FLOAT: {
264  auto foundValue = fitsChan.getFitsF();
265  setMetadataFromFoundValue(*metadata, cardName, foundValue, cardComment);
266  break;
267  }
268  case ast::CardType::INT: {
269  auto foundValue = fitsChan.getFitsI();
270  setMetadataFromFoundValue(*metadata, cardName, foundValue, cardComment);
271  break;
272  }
273  case ast::CardType::STRING: {
274  auto foundValue = fitsChan.getFitsS();
275  setMetadataFromFoundValue(*metadata, cardName, foundValue, cardComment);
276  break;
277  }
278  case ast::CardType::LOGICAL: {
279  auto foundValue = fitsChan.getFitsL();
280  setMetadataFromFoundValue(*metadata, cardName, foundValue, cardComment);
281  break;
282  }
284  auto foundValue = fitsChan.getFitsCN();
285  setMetadataFromFoundValue(*metadata, cardName, foundValue, cardComment);
286  break;
287  }
289  // Drop HISTORY and COMMENT cards
290  break;
293  case ast::CardType::UNDEF: {
294  // PropertyList supports neither complex numbers nor cards with no value
296  os << "Card " << cardNum << " with name \"" << cardName << "\" has type "
297  << static_cast<int>(cardType) << ", which is not supported by PropertyList";
299  }
300  case ast::CardType::NOTYPE: {
301  // This should only occur if cardNum is invalid, and that should be impossible
303  os << "Bug! Card " << cardNum << " with name \"" << cardName
304  << "\" has type NOTYPE, which should not be possible";
306  }
307  }
308  }
309  return metadata;
310 }
311 
312 } // namespace detail
313 } // namespace geom
314 } // namespace afw
315 } // namespace lsst
double getAsDouble(std::string const &name) const
FoundValue< std::string > getFitsCN(std::string const &name="", std::string defval="") const
virtual void remove(std::string const &name)
virtual char const * what(void) const noexcept
CardType getCardType() const
std::shared_ptr< daf::base::PropertyList > createTrivialWcsMetadata(std::string const &wcsName, geom::Point2I const &xy0)
Definition: wcsUtils.cc:51
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)
geom::Point2I getImageXY0FromMetadata(daf::base::PropertySet &metadata, std::string const &wcsName, bool strip=false)
Definition: wcsUtils.cc:98
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.
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
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)
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
Point< int, 2 > Point2I
Definition: Point.h:301
T inserter(T... args)
std::ostream * os
Definition: Schema.cc:736
T set_difference(T... args)
std::shared_ptr< Object > read()
std::string const wcsNameForXY0
Definition: ImageBase.h:74
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:421
FoundValue< bool > getFitsL(std::string const &name="", bool defval=false) const