LSSTApplications  19.0.0-14-gb0260a2+72efe9b372,20.0.0+7927753e06,20.0.0+8829bf0056,20.0.0+995114c5d2,20.0.0+b6f4b2abd1,20.0.0+bddc4f4cbe,20.0.0-1-g253301a+8829bf0056,20.0.0-1-g2b7511a+0d71a2d77f,20.0.0-1-g5b95a8c+7461dd0434,20.0.0-12-g321c96ea+23efe4bbff,20.0.0-16-gfab17e72e+fdf35455f6,20.0.0-2-g0070d88+ba3ffc8f0b,20.0.0-2-g4dae9ad+ee58a624b3,20.0.0-2-g61b8584+5d3db074ba,20.0.0-2-gb780d76+d529cf1a41,20.0.0-2-ged6426c+226a441f5f,20.0.0-2-gf072044+8829bf0056,20.0.0-2-gf1f7952+ee58a624b3,20.0.0-20-geae50cf+e37fec0aee,20.0.0-25-g3dcad98+544a109665,20.0.0-25-g5eafb0f+ee58a624b3,20.0.0-27-g64178ef+f1f297b00a,20.0.0-3-g4cc78c6+e0676b0dc8,20.0.0-3-g8f21e14+4fd2c12c9a,20.0.0-3-gbd60e8c+187b78b4b8,20.0.0-3-gbecbe05+48431fa087,20.0.0-38-ge4adf513+a12e1f8e37,20.0.0-4-g97dc21a+544a109665,20.0.0-4-gb4befbc+087873070b,20.0.0-4-gf910f65+5d3db074ba,20.0.0-5-gdfe0fee+199202a608,20.0.0-5-gfbfe500+d529cf1a41,20.0.0-6-g64f541c+d529cf1a41,20.0.0-6-g9a5b7a1+a1cd37312e,20.0.0-68-ga3f3dda+5fca18c6a4,20.0.0-9-g4aef684+e18322736b,w.2020.45
LSSTDataManagementBasePackage
makeRawVisitInfo.py
Go to the documentation of this file.
1 # This file is part of obs_base.
2 #
3 # Developed for the LSST Data Management System.
4 # This product includes software developed by the LSST Project
5 # (https://www.lsst.org).
6 # See the COPYRIGHT file at the top-level directory of this distribution
7 # for details of code ownership.
8 #
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <https://www.gnu.org/licenses/>.
21 
22 import math
23 import numpy as np
24 
25 import astropy.coordinates
26 import astropy.time
27 import astropy.units
28 
29 from lsst.log import Log
30 from lsst.daf.base import DateTime
31 from lsst.geom import degrees
32 from lsst.afw.image import VisitInfo
33 
34 __all__ = ["MakeRawVisitInfo"]
35 
36 
37 PascalPerMillibar = 100.0
38 PascalPerMmHg = 133.322387415 # from Wikipedia; exact
39 PascalPerTorr = 101325.0/760.0 # from Wikipedia; exact
40 KelvinMinusCentigrade = 273.15 # from Wikipedia; exact
41 
42 # have these read at need, to avoid unexpected errors later
43 NaN = float("nan")
44 BadDate = DateTime()
45 
46 
48  """Base class functor to make a VisitInfo from the FITS header of a raw
49  image.
50 
51  A subclass will be wanted for each camera. Subclasses should override:
52 
53  - `setArgDict`, The override can call the base implementation,
54  which simply sets exposure time and date of observation
55  - `getDateAvg`
56 
57  The design philosophy is to make a best effort and log warnings of
58  problems, rather than raising exceptions, in order to extract as much
59  VisitInfo information as possible from a messy FITS header without the
60  user needing to add a lot of error handling.
61 
62  However, the methods that transform units are less forgiving; they assume
63  the user provides proper data types, since type errors in arguments to
64  those are almost certainly due to coding mistakes.
65 
66  Parameters
67  ----------
68  log : `lsst.log.Log` or None
69  Logger to use for messages.
70  (None to use ``Log.getLogger("MakeRawVisitInfo")``).
71  doStripHeader : `bool`, optional
72  Strip header keywords from the metadata as they are used?
73  """
74 
75  def __init__(self, log=None, doStripHeader=False):
76  if log is None:
77  log = Log.getLogger("MakeRawVisitInfo")
78  self.log = log
79  self.doStripHeader = doStripHeader
80 
81  def __call__(self, md, exposureId):
82  """Construct a VisitInfo and strip associated data from the metadata.
83 
84  Parameters
85  ----------
86  md : `lsst.daf.base.PropertyList` or `lsst.daf.base.PropertySet`
87  Metadata to pull from.
88  Items that are used are stripped from the metadata (except TIMESYS,
89  because it may apply to other keywords) if ``doStripHeader``.
90  exposureId : `int`
91  exposure ID
92 
93  Notes
94  -----
95  The basic implementation sets `date` and `exposureTime` using typical
96  values found in FITS files and logs a warning if neither can be set.
97  """
98  argDict = dict(exposureId=exposureId)
99  self.setArgDict(md, argDict)
100  for key in list(argDict.keys()): # use a copy because we may delete items
101  if argDict[key] is None:
102  self.log.warn("argDict[%s] is None; stripping", key)
103  del argDict[key]
104  return VisitInfo(**argDict)
105 
106  def setArgDict(self, md, argDict):
107  """Fill an argument dict with arguments for VisitInfo and pop
108  associated metadata
109 
110  Subclasses are expected to override this method, though the override
111  may wish to call this default implementation, which:
112 
113  - sets exposureTime from "EXPTIME"
114  - sets date by calling getDateAvg
115 
116  Parameters
117  ----------
118  md : `lsst.daf.base.PropertyList` or `PropertySet`
119  Metadata to pull from.
120  Items that are used are stripped from the metadata (except TIMESYS,
121  because it may apply to other keywords).
122  argdict : `dict`
123  dict of arguments
124 
125  Notes
126  -----
127  Subclasses should expand this or replace it.
128  """
129  argDict["exposureTime"] = self.popFloat(md, "EXPTIME")
130  argDict["date"] = self.getDateAvg(md=md, exposureTime=argDict["exposureTime"])
131 
132  def getDateAvg(self, md, exposureTime):
133  """Return date at the middle of the exposure.
134 
135  Parameters
136  ----------
137  md : `lsst.daf.base.PropertyList` or `PropertySet`
138  Metadata to pull from.
139  Items that are used are stripped from the metadata (except TIMESYS,
140  because it may apply to other keywords).
141  exposureTime : `float`
142  Exposure time (sec)
143 
144  Notes
145  -----
146  Subclasses must override. Here is a typical implementation::
147 
148  dateObs = self.popIsoDate(md, "DATE-OBS")
149  return self.offsetDate(dateObs, 0.5*exposureTime)
150  """
151  raise NotImplementedError()
152 
153  def getDarkTime(self, argDict):
154  """Get the darkTime from the DARKTIME keyword, else expTime, else NaN,
155 
156  If dark time is available then subclasses should call this method by
157  putting the following in their `__init__` method::
158 
159  argDict['darkTime'] = self.getDarkTime(argDict)
160 
161  Parameters
162  ----------
163  argdict : `dict`
164  Dict of arguments.
165 
166  Returns
167  -------
168  `float`
169  Dark time, as inferred from the metadata.
170  """
171  darkTime = argDict.get("darkTime", NaN)
172  if np.isfinite(darkTime):
173  return darkTime
174 
175  self.log.info("darkTime is NaN/Inf; using exposureTime")
176  exposureTime = argDict.get("exposureTime", NaN)
177  if not np.isfinite(exposureTime):
178  raise RuntimeError("Tried to substitute exposureTime for darkTime but it is not available")
179 
180  return exposureTime
181 
182  def offsetDate(self, date, offsetSec):
183  """Return a date offset by a specified number of seconds.
184 
185  date : `lsst.daf.base.DateTime`
186  Date baseline to offset from.
187  offsetSec : `float`
188  Offset, in seconds.
189 
190  Returns
191  -------
192  `lsst.daf.base.DateTime`
193  The offset date.
194  """
195  if not date.isValid():
196  self.log.warn("date is invalid; cannot offset it")
197  return date
198  if math.isnan(offsetSec):
199  self.log.warn("offsetSec is invalid; cannot offset date")
200  return date
201  dateNSec = date.nsecs(DateTime.TAI)
202  return DateTime(dateNSec + int(offsetSec*1.0e9), DateTime.TAI)
203 
204  def popItem(self, md, key, default=None):
205  """Return an item of metadata.
206 
207  The item is removed if ``doStripHeader`` is ``True``.
208 
209  Log a warning if the key is not found.
210 
211  Parameters
212  ----------
213  md : `lsst.daf.base.PropertyList` or `PropertySet`
214  Metadata to pull `key` from and (optionally) remove.
215  key : `str`
216  Metadata key to extract.
217  default : `object`
218  Value to return if key not found.
219 
220  Returns
221  -------
222  `object`
223  The value of the specified key, using whatever type
224  md.getScalar(key) returns.
225  """
226  try:
227  if not md.exists(key):
228  self.log.warn("Key=\"{}\" not in metadata".format(key))
229  return default
230  val = md.getScalar(key)
231  if self.doStripHeader:
232  md.remove(key)
233  return val
234  except Exception as e:
235  # this should never happen, but is a last ditch attempt to avoid
236  # exceptions
237  self.log.warn('Could not read key="{}" in metadata: {}'.format(key, e))
238  return default
239 
240  def popFloat(self, md, key):
241  """Pop a float with a default of NaN.
242 
243  Parameters
244  ----------
245  md : `lsst.daf.base.PropertyList` or `PropertySet`
246  Metadata to pull `key` from.
247  key : `str`
248  Key to read.
249 
250  Returns
251  -------
252  `float`
253  Value of the requested key as a float; float("nan") if the key is
254  not found.
255  """
256  val = self.popItem(md, key, default=NaN)
257  try:
258  return float(val)
259  except Exception as e:
260  self.log.warn("Could not interpret {} value {} as a float: {}".format(key, repr(val), e))
261  return NaN
262 
263  def popAngle(self, md, key, units=astropy.units.deg):
264  """Pop an lsst.afw.geom.Angle, whose metadata is in the specified
265  units, with a default of Nan
266 
267  The angle may be specified as a float or sexagesimal string with 1-3
268  fields.
269 
270  Parameters
271  ----------
272  md : `lsst.daf.base.PropertyList` or `PropertySet`
273  Metadata to pull `key` from.
274  key : `str`
275  Key to read from md.
276 
277  Returns
278  -------
279  `lsst.afw.geom.Angle`
280  Value of the requested key as an angle; Angle(NaN) if the key is
281  not found.
282  """
283  angleStr = self.popItem(md, key, default=None)
284  if angleStr is not None:
285  try:
286  return (astropy.coordinates.Angle(angleStr, unit=units).deg)*degrees
287  except Exception as e:
288  self.log.warn("Could not intepret {} value {} as an angle: {}".format(key, repr(angleStr), e))
289  return NaN*degrees
290 
291  def popIsoDate(self, md, key, timesys=None):
292  """Pop a FITS ISO date as an lsst.daf.base.DateTime
293 
294  Parameters
295  ----------
296  md : `lsst.daf.base.PropertyList` or `PropertySet`
297  Metadata to pull `key` from.
298  key : `str`
299  Date key to read from md.
300  timesys : `str`
301  Time system as a string (not case sensitive), e.g. "UTC" or None;
302  if None then look for TIMESYS (but do NOT pop it, since it may be
303  used for more than one date) and if not found, use UTC.
304 
305  Returns
306  -------
307  `lsst.daf.base.DateTime`
308  Value of the requested date; `DateTime()` if the key is not found.
309  """
310  isoDateStr = self.popItem(md=md, key=key)
311  if isoDateStr is not None:
312  try:
313  if timesys is None:
314  timesys = md.getScalar("TIMESYS") if md.exists("TIMESYS") else "UTC"
315  if isoDateStr.endswith("Z"): # illegal in FITS
316  isoDateStr = isoDateStr[0:-1]
317  astropyTime = astropy.time.Time(isoDateStr, scale=timesys.lower(), format="fits")
318  # DateTime uses nanosecond resolution, regardless of the
319  # resolution of the original date
320  astropyTime.precision = 9
321  # isot is ISO8601 format with "T" separating date and time and
322  # no time zone
323  return DateTime(astropyTime.tai.isot, DateTime.TAI)
324  except Exception as e:
325  self.log.warn("Could not parse {} = {} as an ISO date: {}".format(key, isoDateStr, e))
326  return BadDate
327 
328  def popMjdDate(self, md, key, timesys=None):
329  """Get a FITS MJD date as an ``lsst.daf.base.DateTime``.
330 
331  Parameters
332  ----------
333  md : `lsst.daf.base.PropertyList` or `PropertySet`
334  Metadata to pull `key` from.
335  key : `str`
336  Date key to read from md.
337  timesys : `str`
338  Time system as a string (not case sensitive), e.g. "UTC" or None;
339  if None then look for TIMESYS (but do NOT pop it, since it may be
340  used for more than one date) and if not found, use UTC.
341 
342  Returns
343  -------
344  `lsst.daf.base.DateTime`
345  Value of the requested date; `DateTime()` if the key is not found.
346  """
347  mjdDate = self.popFloat(md, key)
348  try:
349  if timesys is None:
350  timesys = md.getScalar("TIMESYS") if md.exists("TIMESYS") else "UTC"
351  astropyTime = astropy.time.Time(mjdDate, format="mjd", scale=timesys.lower())
352  # DateTime uses nanosecond resolution, regardless of the resolution
353  # of the original date
354  astropyTime.precision = 9
355  # isot is ISO8601 format with "T" separating date and time and no
356  # time zone
357  return DateTime(astropyTime.tai.isot, DateTime.TAI)
358  except Exception as e:
359  self.log.warn("Could not parse {} = {} as an MJD date: {}".format(key, mjdDate, e))
360  return BadDate
361 
362  @staticmethod
363  def eraFromLstAndLongitude(lst, longitude):
364  """
365  Return an approximate Earth Rotation Angle (afw:Angle) computed from
366  local sidereal time and longitude (both as afw:Angle; Longitude shares
367  the afw:Observatory covention: positive values are E of Greenwich).
368 
369  NOTE: if we properly compute ERA via UT1 a la DM-8053, we should remove
370  this method.
371  """
372  return lst - longitude
373 
374  @staticmethod
376  """Convert zenith distance to altitude (lsst.afw.geom.Angle)"""
377  return 90*degrees - zd
378 
379  @staticmethod
381  """Convert temperature from Kelvin to Centigrade"""
382  return tempK - KelvinMinusCentigrade
383 
384  @staticmethod
385  def pascalFromMBar(mbar):
386  """Convert pressure from millibars to Pascals
387  """
388  return mbar*PascalPerMillibar
389 
390  @staticmethod
391  def pascalFromMmHg(mmHg):
392  """Convert pressure from mm Hg to Pascals
393 
394  Notes
395  -----
396  Could use the following, but astropy.units.cds is not fully compatible
397  with Python 2 as of astropy 1.2.1 (see
398  https://github.com/astropy/astropy/issues/5350#issuecomment-248612824):
399  astropy.units.cds.mmHg.to(astropy.units.pascal, mmHg)
400  """
401  return mmHg*PascalPerMmHg
402 
403  @staticmethod
404  def pascalFromTorr(torr):
405  """Convert pressure from torr to Pascals
406  """
407  return torr*PascalPerTorr
408 
409  @staticmethod
410  def defaultMetadata(value, defaultValue, minimum=None, maximum=None):
411  """Return the value if it is not NaN and within min/max, otherwise
412  return defaultValue.
413 
414  Parameters
415  ----------
416  value : `float`
417  metadata value returned by popItem, popFloat, or popAngle
418  defaultValue : `float``
419  default value to use if the metadata value is invalid
420  minimum : `float`
421  Minimum possible valid value, optional
422  maximum : `float`
423  Maximum possible valid value, optional
424 
425  Returns
426  -------
427  `float`
428  The "validated" value.
429  """
430  if np.isnan(value):
431  retVal = defaultValue
432  else:
433  if minimum is not None and value < minimum:
434  retVal = defaultValue
435  elif maximum is not None and value > maximum:
436  retVal = defaultValue
437  else:
438  retVal = value
439  return retVal
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo
Definition: makeRawVisitInfo.py:47
lsst::afw::image
Backwards-compatibility support for depersisting the old Calib (FluxMag0/FluxMag0Err) objects.
Definition: imageAlgorithm.dox:1
lsst::log.log.logContinued.warn
def warn(fmt, *args)
Definition: logContinued.py:205
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.log
log
Definition: makeRawVisitInfo.py:78
lsst::log.log.logContinued.info
def info(fmt, *args)
Definition: logContinued.py:201
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.pascalFromMBar
def pascalFromMBar(mbar)
Definition: makeRawVisitInfo.py:385
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.doStripHeader
doStripHeader
Definition: makeRawVisitInfo.py:79
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.__call__
def __call__(self, md, exposureId)
Definition: makeRawVisitInfo.py:81
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.offsetDate
def offsetDate(self, date, offsetSec)
Definition: makeRawVisitInfo.py:182
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.altitudeFromZenithDistance
def altitudeFromZenithDistance(zd)
Definition: makeRawVisitInfo.py:375
lsst.pex.config.history.format
def format(config, name=None, writeSourceLine=True, prefix="", verbose=False)
Definition: history.py:174
lsst::daf::base::DateTime
Class for handling dates/times, including MJD, UTC, and TAI.
Definition: DateTime.h:64
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.popMjdDate
def popMjdDate(self, md, key, timesys=None)
Definition: makeRawVisitInfo.py:328
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.popFloat
def popFloat(self, md, key)
Definition: makeRawVisitInfo.py:240
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.eraFromLstAndLongitude
def eraFromLstAndLongitude(lst, longitude)
Definition: makeRawVisitInfo.py:363
lsst::afw::image::VisitInfo
Information about a single exposure of an imaging camera.
Definition: VisitInfo.h:68
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.getDarkTime
def getDarkTime(self, argDict)
Definition: makeRawVisitInfo.py:153
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.pascalFromMmHg
def pascalFromMmHg(mmHg)
Definition: makeRawVisitInfo.py:391
lsst::log
Definition: Log.h:706
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.defaultMetadata
def defaultMetadata(value, defaultValue, minimum=None, maximum=None)
Definition: makeRawVisitInfo.py:410
object
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.popItem
def popItem(self, md, key, default=None)
Definition: makeRawVisitInfo.py:204
lsst::geom
Definition: AffineTransform.h:36
lsst::daf::base
Definition: Utils.h:47
list
daf::base::PropertyList * list
Definition: fits.cc:913
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.pascalFromTorr
def pascalFromTorr(torr)
Definition: makeRawVisitInfo.py:404
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.__init__
def __init__(self, log=None, doStripHeader=False)
Definition: makeRawVisitInfo.py:75
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.getDateAvg
def getDateAvg(self, md, exposureTime)
Definition: makeRawVisitInfo.py:132
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.setArgDict
def setArgDict(self, md, argDict)
Definition: makeRawVisitInfo.py:106
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.centigradeFromKelvin
def centigradeFromKelvin(tempK)
Definition: makeRawVisitInfo.py:380
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.popIsoDate
def popIsoDate(self, md, key, timesys=None)
Definition: makeRawVisitInfo.py:291
lsst.obs.base.makeRawVisitInfo.MakeRawVisitInfo.popAngle
def popAngle(self, md, key, units=astropy.units.deg)
Definition: makeRawVisitInfo.py:263