lsst.obs.base  18.1.0-13-gcf63ac1
cameraMapper.py
Go to the documentation of this file.
1 #
2 # LSST Data Management System
3 # Copyright 2008, 2009, 2010 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 import copy
24 import os
25 import re
26 import traceback
27 import weakref
28 
29 from astro_metadata_translator import fix_header
30 import lsst.daf.persistence as dafPersist
31 from . import ImageMapping, ExposureMapping, CalibrationMapping, DatasetMapping
32 import lsst.daf.base as dafBase
33 import lsst.afw.geom as afwGeom
34 import lsst.afw.image as afwImage
35 import lsst.afw.table as afwTable
36 from lsst.afw.fits import readMetadata
37 import lsst.afw.cameraGeom as afwCameraGeom
38 import lsst.log as lsstLog
39 import lsst.pex.exceptions as pexExcept
40 from .exposureIdInfo import ExposureIdInfo
41 from .makeRawVisitInfo import MakeRawVisitInfo
42 from .utils import createInitialSkyWcs, InitialSkyWcsError
43 from lsst.utils import getPackageDir
44 
45 __all__ = ["CameraMapper", "exposureFromImage"]
46 
47 
48 class CameraMapper(dafPersist.Mapper):
49 
50  """CameraMapper is a base class for mappers that handle images from a
51  camera and products derived from them. This provides an abstraction layer
52  between the data on disk and the code.
53 
54  Public methods: keys, queryMetadata, getDatasetTypes, map,
55  canStandardize, standardize
56 
57  Mappers for specific data sources (e.g., CFHT Megacam, LSST
58  simulations, etc.) should inherit this class.
59 
60  The CameraMapper manages datasets within a "root" directory. Note that
61  writing to a dataset present in the input root will hide the existing
62  dataset but not overwrite it. See #2160 for design discussion.
63 
64  A camera is assumed to consist of one or more rafts, each composed of
65  multiple CCDs. Each CCD is in turn composed of one or more amplifiers
66  (amps). A camera is also assumed to have a camera geometry description
67  (CameraGeom object) as a policy file, a filter description (Filter class
68  static configuration) as another policy file.
69 
70  Information from the camera geometry and defects are inserted into all
71  Exposure objects returned.
72 
73  The mapper uses one or two registries to retrieve metadata about the
74  images. The first is a registry of all raw exposures. This must contain
75  the time of the observation. One or more tables (or the equivalent)
76  within the registry are used to look up data identifier components that
77  are not specified by the user (e.g. filter) and to return results for
78  metadata queries. The second is an optional registry of all calibration
79  data. This should contain validity start and end entries for each
80  calibration dataset in the same timescale as the observation time.
81 
82  Subclasses will typically set MakeRawVisitInfoClass and optionally the
83  metadata translator class:
84 
85  MakeRawVisitInfoClass: a class variable that points to a subclass of
86  MakeRawVisitInfo, a functor that creates an
87  lsst.afw.image.VisitInfo from the FITS metadata of a raw image.
88 
89  translatorClass: The `~astro_metadata_translator.MetadataTranslator`
90  class to use for fixing metadata values. If it is not set an attempt
91  will be made to infer the class from ``MakeRawVisitInfoClass``, failing
92  that the metadata fixup will try to infer the translator class from the
93  header itself.
94 
95  Subclasses must provide the following methods:
96 
97  _extractDetectorName(self, dataId): returns the detector name for a CCD
98  (e.g., "CFHT 21", "R:1,2 S:3,4") as used in the AFW CameraGeom class given
99  a dataset identifier referring to that CCD or a subcomponent of it.
100 
101  _computeCcdExposureId(self, dataId): see below
102 
103  _computeCoaddExposureId(self, dataId, singleFilter): see below
104 
105  Subclasses may also need to override the following methods:
106 
107  _transformId(self, dataId): transformation of a data identifier
108  from colloquial usage (e.g., "ccdname") to proper/actual usage
109  (e.g., "ccd"), including making suitable for path expansion (e.g. removing
110  commas). The default implementation does nothing. Note that this
111  method should not modify its input parameter.
112 
113  getShortCcdName(self, ccdName): a static method that returns a shortened
114  name suitable for use as a filename. The default version converts spaces
115  to underscores.
116 
117  _mapActualToPath(self, template, actualId): convert a template path to an
118  actual path, using the actual dataset identifier.
119 
120  The mapper's behaviors are largely specified by the policy file.
121  See the MapperDictionary.paf for descriptions of the available items.
122 
123  The 'exposures', 'calibrations', and 'datasets' subpolicies configure
124  mappings (see Mappings class).
125 
126  Common default mappings for all subclasses can be specified in the
127  "policy/{images,exposures,calibrations,datasets}.yaml" files. This
128  provides a simple way to add a product to all camera mappers.
129 
130  Functions to map (provide a path to the data given a dataset
131  identifier dictionary) and standardize (convert data into some standard
132  format or type) may be provided in the subclass as "map_{dataset type}"
133  and "std_{dataset type}", respectively.
134 
135  If non-Exposure datasets cannot be retrieved using standard
136  daf_persistence methods alone, a "bypass_{dataset type}" function may be
137  provided in the subclass to return the dataset instead of using the
138  "datasets" subpolicy.
139 
140  Implementations of map_camera and bypass_camera that should typically be
141  sufficient are provided in this base class.
142 
143  Notes
144  -----
145  .. todo::
146 
147  Instead of auto-loading the camera at construction time, load it from
148  the calibration registry
149 
150  Parameters
151  ----------
152  policy : daf_persistence.Policy,
153  Policy with per-camera defaults already merged.
154  repositoryDir : string
155  Policy repository for the subclassing module (obtained with
156  getRepositoryPath() on the per-camera default dictionary).
157  root : string, optional
158  Path to the root directory for data.
159  registry : string, optional
160  Path to registry with data's metadata.
161  calibRoot : string, optional
162  Root directory for calibrations.
163  calibRegistry : string, optional
164  Path to registry with calibrations' metadata.
165  provided : list of string, optional
166  Keys provided by the mapper.
167  parentRegistry : Registry subclass, optional
168  Registry from a parent repository that may be used to look up
169  data's metadata.
170  repositoryCfg : daf_persistence.RepositoryCfg or None, optional
171  The configuration information for the repository this mapper is
172  being used with.
173  """
174  packageName = None
175 
176  # a class or subclass of MakeRawVisitInfo, a functor that makes an
177  # lsst.afw.image.VisitInfo from the FITS metadata of a raw image
178  MakeRawVisitInfoClass = MakeRawVisitInfo
179 
180  # a class or subclass of PupilFactory
181  PupilFactoryClass = afwCameraGeom.PupilFactory
182 
183  # Class to use for metadata translations
184  translatorClass = None
185 
186  def __init__(self, policy, repositoryDir,
187  root=None, registry=None, calibRoot=None, calibRegistry=None,
188  provided=None, parentRegistry=None, repositoryCfg=None):
189 
190  dafPersist.Mapper.__init__(self)
191 
192  self.log = lsstLog.Log.getLogger("CameraMapper")
193 
194  if root:
195  self.root = root
196  elif repositoryCfg:
197  self.root = repositoryCfg.root
198  else:
199  self.root = None
200 
201  repoPolicy = repositoryCfg.policy if repositoryCfg else None
202  if repoPolicy is not None:
203  policy.update(repoPolicy)
204 
205  # Levels
206  self.levels = dict()
207  if 'levels' in policy:
208  levelsPolicy = policy['levels']
209  for key in levelsPolicy.names(True):
210  self.levels[key] = set(levelsPolicy.asArray(key))
211  self.defaultLevel = policy['defaultLevel']
212  self.defaultSubLevels = dict()
213  if 'defaultSubLevels' in policy:
214  self.defaultSubLevels = policy['defaultSubLevels']
215 
216  # Root directories
217  if root is None:
218  root = "."
219  root = dafPersist.LogicalLocation(root).locString()
220 
221  self.rootStorage = dafPersist.Storage.makeFromURI(uri=root)
222 
223  # If the calibRoot is passed in, use that. If not and it's indicated in
224  # the policy, use that. And otherwise, the calibs are in the regular
225  # root.
226  # If the location indicated by the calib root does not exist, do not
227  # create it.
228  calibStorage = None
229  if calibRoot is not None:
230  calibRoot = dafPersist.Storage.absolutePath(root, calibRoot)
231  calibStorage = dafPersist.Storage.makeFromURI(uri=calibRoot,
232  create=False)
233  else:
234  calibRoot = policy.get('calibRoot', None)
235  if calibRoot:
236  calibStorage = dafPersist.Storage.makeFromURI(uri=calibRoot,
237  create=False)
238  if calibStorage is None:
239  calibStorage = self.rootStorage
240 
241  self.root = root
242 
243  # Registries
244  self.registry = self._setupRegistry("registry", "exposure", registry, policy, "registryPath",
245  self.rootStorage, searchParents=False,
246  posixIfNoSql=(not parentRegistry))
247  if not self.registry:
248  self.registry = parentRegistry
249  needCalibRegistry = policy.get('needCalibRegistry', None)
250  if needCalibRegistry:
251  if calibStorage:
252  self.calibRegistry = self._setupRegistry("calibRegistry", "calib", calibRegistry, policy,
253  "calibRegistryPath", calibStorage,
254  posixIfNoSql=False) # NB never use posix for calibs
255  else:
256  raise RuntimeError(
257  "'needCalibRegistry' is true in Policy, but was unable to locate a repo at " +
258  "calibRoot ivar:%s or policy['calibRoot']:%s" %
259  (calibRoot, policy.get('calibRoot', None)))
260  else:
261  self.calibRegistry = None
262 
263  # Dict of valid keys and their value types
264  self.keyDict = dict()
265 
266  self._initMappings(policy, self.rootStorage, calibStorage, provided=None)
267  self._initWriteRecipes()
268 
269  # Camera geometry
270  self.cameraDataLocation = None # path to camera geometry config file
271  self.camera = self._makeCamera(policy=policy, repositoryDir=repositoryDir)
272 
273  # Filter translation table
274  self.filters = None
275 
276  # verify that the class variable packageName is set before attempting
277  # to instantiate an instance
278  if self.packageName is None:
279  raise ValueError('class variable packageName must not be None')
280 
282 
283  # Assign a metadata translator if one has not been defined by
284  # subclass. We can sometimes infer one from the RawVisitInfo
285  # class.
286  if self.translatorClass is None and hasattr(self.makeRawVisitInfo, "metadataTranslator"):
287  self.translatorClass = self.makeRawVisitInfo.metadataTranslator
288 
289  def _initMappings(self, policy, rootStorage=None, calibStorage=None, provided=None):
290  """Initialize mappings
291 
292  For each of the dataset types that we want to be able to read, there
293  are methods that can be created to support them:
294  * map_<dataset> : determine the path for dataset
295  * std_<dataset> : standardize the retrieved dataset
296  * bypass_<dataset> : retrieve the dataset (bypassing the usual
297  retrieval machinery)
298  * query_<dataset> : query the registry
299 
300  Besides the dataset types explicitly listed in the policy, we create
301  additional, derived datasets for additional conveniences,
302  e.g., reading the header of an image, retrieving only the size of a
303  catalog.
304 
305  Parameters
306  ----------
307  policy : `lsst.daf.persistence.Policy`
308  Policy with per-camera defaults already merged
309  rootStorage : `Storage subclass instance`
310  Interface to persisted repository data.
311  calibRoot : `Storage subclass instance`
312  Interface to persisted calib repository data
313  provided : `list` of `str`
314  Keys provided by the mapper
315  """
316  # Sub-dictionaries (for exposure/calibration/dataset types)
317  imgMappingPolicy = dafPersist.Policy(dafPersist.Policy.defaultPolicyFile(
318  "obs_base", "ImageMappingDefaults.yaml", "policy"))
319  expMappingPolicy = dafPersist.Policy(dafPersist.Policy.defaultPolicyFile(
320  "obs_base", "ExposureMappingDefaults.yaml", "policy"))
321  calMappingPolicy = dafPersist.Policy(dafPersist.Policy.defaultPolicyFile(
322  "obs_base", "CalibrationMappingDefaults.yaml", "policy"))
323  dsMappingPolicy = dafPersist.Policy()
324 
325  # Mappings
326  mappingList = (
327  ("images", imgMappingPolicy, ImageMapping),
328  ("exposures", expMappingPolicy, ExposureMapping),
329  ("calibrations", calMappingPolicy, CalibrationMapping),
330  ("datasets", dsMappingPolicy, DatasetMapping)
331  )
332  self.mappings = dict()
333  for name, defPolicy, cls in mappingList:
334  if name in policy:
335  datasets = policy[name]
336 
337  # Centrally-defined datasets
338  defaultsPath = os.path.join(getPackageDir("obs_base"), "policy", name + ".yaml")
339  if os.path.exists(defaultsPath):
340  datasets.merge(dafPersist.Policy(defaultsPath))
341 
342  mappings = dict()
343  setattr(self, name, mappings)
344  for datasetType in datasets.names(True):
345  subPolicy = datasets[datasetType]
346  subPolicy.merge(defPolicy)
347 
348  if not hasattr(self, "map_" + datasetType) and 'composite' in subPolicy:
349  def compositeClosure(dataId, write=False, mapper=None, mapping=None,
350  subPolicy=subPolicy):
351  components = subPolicy.get('composite')
352  assembler = subPolicy['assembler'] if 'assembler' in subPolicy else None
353  disassembler = subPolicy['disassembler'] if 'disassembler' in subPolicy else None
354  python = subPolicy['python']
355  butlerComposite = dafPersist.ButlerComposite(assembler=assembler,
356  disassembler=disassembler,
357  python=python,
358  dataId=dataId,
359  mapper=self)
360  for name, component in components.items():
361  butlerComposite.add(id=name,
362  datasetType=component.get('datasetType'),
363  setter=component.get('setter', None),
364  getter=component.get('getter', None),
365  subset=component.get('subset', False),
366  inputOnly=component.get('inputOnly', False))
367  return butlerComposite
368  setattr(self, "map_" + datasetType, compositeClosure)
369  # for now at least, don't set up any other handling for this dataset type.
370  continue
371 
372  if name == "calibrations":
373  mapping = cls(datasetType, subPolicy, self.registry, self.calibRegistry, calibStorage,
374  provided=provided, dataRoot=rootStorage)
375  else:
376  mapping = cls(datasetType, subPolicy, self.registry, rootStorage, provided=provided)
377 
378  if datasetType in self.mappings:
379  raise ValueError(f"Duplicate mapping policy for dataset type {datasetType}")
380  self.keyDict.update(mapping.keys())
381  mappings[datasetType] = mapping
382  self.mappings[datasetType] = mapping
383  if not hasattr(self, "map_" + datasetType):
384  def mapClosure(dataId, write=False, mapper=weakref.proxy(self), mapping=mapping):
385  return mapping.map(mapper, dataId, write)
386  setattr(self, "map_" + datasetType, mapClosure)
387  if not hasattr(self, "query_" + datasetType):
388  def queryClosure(format, dataId, mapping=mapping):
389  return mapping.lookup(format, dataId)
390  setattr(self, "query_" + datasetType, queryClosure)
391  if hasattr(mapping, "standardize") and not hasattr(self, "std_" + datasetType):
392  def stdClosure(item, dataId, mapper=weakref.proxy(self), mapping=mapping):
393  return mapping.standardize(mapper, item, dataId)
394  setattr(self, "std_" + datasetType, stdClosure)
395 
396  def setMethods(suffix, mapImpl=None, bypassImpl=None, queryImpl=None):
397  """Set convenience methods on CameraMapper"""
398  mapName = "map_" + datasetType + "_" + suffix
399  bypassName = "bypass_" + datasetType + "_" + suffix
400  queryName = "query_" + datasetType + "_" + suffix
401  if not hasattr(self, mapName):
402  setattr(self, mapName, mapImpl or getattr(self, "map_" + datasetType))
403  if not hasattr(self, bypassName):
404  if bypassImpl is None and hasattr(self, "bypass_" + datasetType):
405  bypassImpl = getattr(self, "bypass_" + datasetType)
406  if bypassImpl is not None:
407  setattr(self, bypassName, bypassImpl)
408  if not hasattr(self, queryName):
409  setattr(self, queryName, queryImpl or getattr(self, "query_" + datasetType))
410 
411  # Filename of dataset
412  setMethods("filename", bypassImpl=lambda datasetType, pythonType, location, dataId:
413  [os.path.join(location.getStorage().root, p) for p in location.getLocations()])
414  # Metadata from FITS file
415  if subPolicy["storage"] == "FitsStorage": # a FITS image
416  def getMetadata(datasetType, pythonType, location, dataId):
417  md = readMetadata(location.getLocationsWithRoot()[0])
418  fix_header(md, translator_class=self.translatorClass)
419  return md
420 
421  setMethods("md", bypassImpl=getMetadata)
422 
423  # Add support for configuring FITS compression
424  addName = "add_" + datasetType
425  if not hasattr(self, addName):
426  setattr(self, addName, self.getImageCompressionSettings)
427 
428  if name == "exposures":
429  def getSkyWcs(datasetType, pythonType, location, dataId):
430  fitsReader = afwImage.ExposureFitsReader(location.getLocationsWithRoot()[0])
431  return fitsReader.readWcs()
432 
433  setMethods("wcs", bypassImpl=getSkyWcs)
434 
435  def getPhotoCalib(datasetType, pythonType, location, dataId):
436  fitsReader = afwImage.ExposureFitsReader(location.getLocationsWithRoot()[0])
437  return fitsReader.readPhotoCalib()
438 
439  setMethods("photoCalib", bypassImpl=getPhotoCalib)
440 
441  def getVisitInfo(datasetType, pythonType, location, dataId):
442  fitsReader = afwImage.ExposureFitsReader(location.getLocationsWithRoot()[0])
443  return fitsReader.readVisitInfo()
444 
445  setMethods("visitInfo", bypassImpl=getVisitInfo)
446 
447  def getFilter(datasetType, pythonType, location, dataId):
448  fitsReader = afwImage.ExposureFitsReader(location.getLocationsWithRoot()[0])
449  return fitsReader.readFilter()
450 
451  setMethods("filter", bypassImpl=getFilter)
452 
453  setMethods("detector",
454  mapImpl=lambda dataId, write=False:
455  dafPersist.ButlerLocation(
456  pythonType="lsst.afw.cameraGeom.CameraConfig",
457  cppType="Config",
458  storageName="Internal",
459  locationList="ignored",
460  dataId=dataId,
461  mapper=self,
462  storage=None,
463  ),
464  bypassImpl=lambda datasetType, pythonType, location, dataId:
465  self.camera[self._extractDetectorName(dataId)]
466  )
467 
468  def getBBox(datasetType, pythonType, location, dataId):
469  md = readMetadata(location.getLocationsWithRoot()[0], hdu=1)
470  fix_header(md, translator_class=self.translatorClass)
471  return afwImage.bboxFromMetadata(md)
472 
473  setMethods("bbox", bypassImpl=getBBox)
474 
475  elif name == "images":
476  def getBBox(datasetType, pythonType, location, dataId):
477  md = readMetadata(location.getLocationsWithRoot()[0])
478  fix_header(md, translator_class=self.translatorClass)
479  return afwImage.bboxFromMetadata(md)
480  setMethods("bbox", bypassImpl=getBBox)
481 
482  if subPolicy["storage"] == "FitsCatalogStorage": # a FITS catalog
483 
484  def getMetadata(datasetType, pythonType, location, dataId):
485  md = readMetadata(os.path.join(location.getStorage().root,
486  location.getLocations()[0]), hdu=1)
487  fix_header(md, translator_class=self.translatorClass)
488  return md
489 
490  setMethods("md", bypassImpl=getMetadata)
491 
492  # Sub-images
493  if subPolicy["storage"] == "FitsStorage":
494  def mapSubClosure(dataId, write=False, mapper=weakref.proxy(self), mapping=mapping):
495  subId = dataId.copy()
496  del subId['bbox']
497  loc = mapping.map(mapper, subId, write)
498  bbox = dataId['bbox']
499  llcX = bbox.getMinX()
500  llcY = bbox.getMinY()
501  width = bbox.getWidth()
502  height = bbox.getHeight()
503  loc.additionalData.set('llcX', llcX)
504  loc.additionalData.set('llcY', llcY)
505  loc.additionalData.set('width', width)
506  loc.additionalData.set('height', height)
507  if 'imageOrigin' in dataId:
508  loc.additionalData.set('imageOrigin',
509  dataId['imageOrigin'])
510  return loc
511 
512  def querySubClosure(key, format, dataId, mapping=mapping):
513  subId = dataId.copy()
514  del subId['bbox']
515  return mapping.lookup(format, subId)
516  setMethods("sub", mapImpl=mapSubClosure, queryImpl=querySubClosure)
517 
518  if subPolicy["storage"] == "FitsCatalogStorage":
519  # Length of catalog
520 
521  def getLen(datasetType, pythonType, location, dataId):
522  md = readMetadata(os.path.join(location.getStorage().root,
523  location.getLocations()[0]), hdu=1)
524  fix_header(md, translator_class=self.translatorClass)
525  return md["NAXIS2"]
526 
527  setMethods("len", bypassImpl=getLen)
528 
529  # Schema of catalog
530  if not datasetType.endswith("_schema") and datasetType + "_schema" not in datasets:
531  setMethods("schema", bypassImpl=lambda datasetType, pythonType, location, dataId:
532  afwTable.Schema.readFits(os.path.join(location.getStorage().root,
533  location.getLocations()[0])))
534 
535  def _computeCcdExposureId(self, dataId):
536  """Compute the 64-bit (long) identifier for a CCD exposure.
537 
538  Subclasses must override
539 
540  Parameters
541  ----------
542  dataId : `dict`
543  Data identifier with visit, ccd.
544  """
545  raise NotImplementedError()
546 
547  def _computeCoaddExposureId(self, dataId, singleFilter):
548  """Compute the 64-bit (long) identifier for a coadd.
549 
550  Subclasses must override
551 
552  Parameters
553  ----------
554  dataId : `dict`
555  Data identifier with tract and patch.
556  singleFilter : `bool`
557  True means the desired ID is for a single-filter coadd, in which
558  case dataIdmust contain filter.
559  """
560  raise NotImplementedError()
561 
562  def _search(self, path):
563  """Search for path in the associated repository's storage.
564 
565  Parameters
566  ----------
567  path : string
568  Path that describes an object in the repository associated with
569  this mapper.
570  Path may contain an HDU indicator, e.g. 'foo.fits[1]'. The
571  indicator will be stripped when searching and so will match
572  filenames without the HDU indicator, e.g. 'foo.fits'. The path
573  returned WILL contain the indicator though, e.g. ['foo.fits[1]'].
574 
575  Returns
576  -------
577  string
578  The path for this object in the repository. Will return None if the
579  object can't be found. If the input argument path contained an HDU
580  indicator, the returned path will also contain the HDU indicator.
581  """
582  return self.rootStorage.search(path)
583 
584  def backup(self, datasetType, dataId):
585  """Rename any existing object with the given type and dataId.
586 
587  The CameraMapper implementation saves objects in a sequence of e.g.:
588 
589  - foo.fits
590  - foo.fits~1
591  - foo.fits~2
592 
593  All of the backups will be placed in the output repo, however, and will
594  not be removed if they are found elsewhere in the _parent chain. This
595  means that the same file will be stored twice if the previous version
596  was found in an input repo.
597  """
598 
599  # Calling PosixStorage directly is not the long term solution in this
600  # function, this is work-in-progress on epic DM-6225. The plan is for
601  # parentSearch to be changed to 'search', and search only the storage
602  # associated with this mapper. All searching of parents will be handled
603  # by traversing the container of repositories in Butler.
604 
605  def firstElement(list):
606  """Get the first element in the list, or None if that can't be
607  done.
608  """
609  return list[0] if list is not None and len(list) else None
610 
611  n = 0
612  newLocation = self.map(datasetType, dataId, write=True)
613  newPath = newLocation.getLocations()[0]
614  path = dafPersist.PosixStorage.search(self.root, newPath, searchParents=True)
615  path = firstElement(path)
616  oldPaths = []
617  while path is not None:
618  n += 1
619  oldPaths.append((n, path))
620  path = dafPersist.PosixStorage.search(self.root, "%s~%d" % (newPath, n), searchParents=True)
621  path = firstElement(path)
622  for n, oldPath in reversed(oldPaths):
623  self.rootStorage.copyFile(oldPath, "%s~%d" % (newPath, n))
624 
625  def keys(self):
626  """Return supported keys.
627 
628  Returns
629  -------
630  iterable
631  List of keys usable in a dataset identifier
632  """
633  return iter(self.keyDict.keys())
634 
635  def getKeys(self, datasetType, level):
636  """Return a dict of supported keys and their value types for a given
637  dataset type at a given level of the key hierarchy.
638 
639  Parameters
640  ----------
641  datasetType : `str`
642  Dataset type or None for all dataset types.
643  level : `str` or None
644  Level or None for all levels or '' for the default level for the
645  camera.
646 
647  Returns
648  -------
649  `dict`
650  Keys are strings usable in a dataset identifier, values are their
651  value types.
652  """
653 
654  # not sure if this is how we want to do this. what if None was intended?
655  if level == '':
656  level = self.getDefaultLevel()
657 
658  if datasetType is None:
659  keyDict = copy.copy(self.keyDict)
660  else:
661  keyDict = self.mappings[datasetType].keys()
662  if level is not None and level in self.levels:
663  keyDict = copy.copy(keyDict)
664  for l in self.levels[level]:
665  if l in keyDict:
666  del keyDict[l]
667  return keyDict
668 
669  def getDefaultLevel(self):
670  return self.defaultLevel
671 
672  def getDefaultSubLevel(self, level):
673  if level in self.defaultSubLevels:
674  return self.defaultSubLevels[level]
675  return None
676 
677  @classmethod
678  def getCameraName(cls):
679  """Return the name of the camera that this CameraMapper is for."""
680  className = str(cls)
681  className = className[className.find('.'):-1]
682  m = re.search(r'(\w+)Mapper', className)
683  if m is None:
684  m = re.search(r"class '[\w.]*?(\w+)'", className)
685  name = m.group(1)
686  return name[:1].lower() + name[1:] if name else ''
687 
688  @classmethod
689  def getPackageName(cls):
690  """Return the name of the package containing this CameraMapper."""
691  if cls.packageName is None:
692  raise ValueError('class variable packageName must not be None')
693  return cls.packageName
694 
695  @classmethod
696  def getPackageDir(cls):
697  """Return the base directory of this package"""
698  return getPackageDir(cls.getPackageName())
699 
700  def map_camera(self, dataId, write=False):
701  """Map a camera dataset."""
702  if self.camera is None:
703  raise RuntimeError("No camera dataset available.")
704  actualId = self._transformId(dataId)
705  return dafPersist.ButlerLocation(
706  pythonType="lsst.afw.cameraGeom.CameraConfig",
707  cppType="Config",
708  storageName="ConfigStorage",
709  locationList=self.cameraDataLocation or "ignored",
710  dataId=actualId,
711  mapper=self,
712  storage=self.rootStorage
713  )
714 
715  def bypass_camera(self, datasetType, pythonType, butlerLocation, dataId):
716  """Return the (preloaded) camera object.
717  """
718  if self.camera is None:
719  raise RuntimeError("No camera dataset available.")
720  return self.camera
721 
722  def map_expIdInfo(self, dataId, write=False):
723  return dafPersist.ButlerLocation(
724  pythonType="lsst.obs.base.ExposureIdInfo",
725  cppType=None,
726  storageName="Internal",
727  locationList="ignored",
728  dataId=dataId,
729  mapper=self,
730  storage=self.rootStorage
731  )
732 
733  def bypass_expIdInfo(self, datasetType, pythonType, location, dataId):
734  """Hook to retrieve an lsst.obs.base.ExposureIdInfo for an exposure"""
735  expId = self.bypass_ccdExposureId(datasetType, pythonType, location, dataId)
736  expBits = self.bypass_ccdExposureId_bits(datasetType, pythonType, location, dataId)
737  return ExposureIdInfo(expId=expId, expBits=expBits)
738 
739  def std_bfKernel(self, item, dataId):
740  """Disable standardization for bfKernel
741 
742  bfKernel is a calibration product that is numpy array,
743  unlike other calibration products that are all images;
744  all calibration images are sent through _standardizeExposure
745  due to CalibrationMapping, but we don't want that to happen to bfKernel
746  """
747  return item
748 
749  def std_raw(self, item, dataId):
750  """Standardize a raw dataset by converting it to an Exposure instead
751  of an Image"""
752  return self._standardizeExposure(self.exposures['raw'], item, dataId,
753  trimmed=False, setVisitInfo=True)
754 
755  def map_skypolicy(self, dataId):
756  """Map a sky policy."""
757  return dafPersist.ButlerLocation("lsst.pex.policy.Policy", "Policy",
758  "Internal", None, None, self,
759  storage=self.rootStorage)
760 
761  def std_skypolicy(self, item, dataId):
762  """Standardize a sky policy by returning the one we use."""
763  return self.skypolicy
764 
765 
770 
771  def _setupRegistry(self, name, description, path, policy, policyKey, storage, searchParents=True,
772  posixIfNoSql=True):
773  """Set up a registry (usually SQLite3), trying a number of possible
774  paths.
775 
776  Parameters
777  ----------
778  name : string
779  Name of registry.
780  description: `str`
781  Description of registry (for log messages)
782  path : string
783  Path for registry.
784  policy : string
785  Policy that contains the registry name, used if path is None.
786  policyKey : string
787  Key in policy for registry path.
788  storage : Storage subclass
789  Repository Storage to look in.
790  searchParents : bool, optional
791  True if the search for a registry should follow any Butler v1
792  _parent symlinks.
793  posixIfNoSql : bool, optional
794  If an sqlite registry is not found, will create a posix registry if
795  this is True.
796 
797  Returns
798  -------
799  lsst.daf.persistence.Registry
800  Registry object
801  """
802  if path is None and policyKey in policy:
803  path = dafPersist.LogicalLocation(policy[policyKey]).locString()
804  if os.path.isabs(path):
805  raise RuntimeError("Policy should not indicate an absolute path for registry.")
806  if not storage.exists(path):
807  newPath = storage.instanceSearch(path)
808 
809  newPath = newPath[0] if newPath is not None and len(newPath) else None
810  if newPath is None:
811  self.log.warn("Unable to locate registry at policy path (also looked in root): %s",
812  path)
813  path = newPath
814  else:
815  self.log.warn("Unable to locate registry at policy path: %s", path)
816  path = None
817 
818  # Old Butler API was to indicate the registry WITH the repo folder, New Butler expects the registry to
819  # be in the repo folder. To support Old API, check to see if path starts with root, and if so, strip
820  # root from path. Currently only works with PosixStorage
821  try:
822  root = storage.root
823  if path and (path.startswith(root)):
824  path = path[len(root + '/'):]
825  except AttributeError:
826  pass
827 
828  # determine if there is an sqlite registry and if not, try the posix registry.
829  registry = None
830 
831  def search(filename, description):
832  """Search for file in storage
833 
834  Parameters
835  ----------
836  filename : `str`
837  Filename to search for
838  description : `str`
839  Description of file, for error message.
840 
841  Returns
842  -------
843  path : `str` or `None`
844  Path to file, or None
845  """
846  result = storage.instanceSearch(filename)
847  if result:
848  return result[0]
849  self.log.debug("Unable to locate %s: %s", description, filename)
850  return None
851 
852  # Search for a suitable registry database
853  if path is None:
854  path = search("%s.pgsql" % name, "%s in root" % description)
855  if path is None:
856  path = search("%s.sqlite3" % name, "%s in root" % description)
857  if path is None:
858  path = search(os.path.join(".", "%s.sqlite3" % name), "%s in current dir" % description)
859 
860  if path is not None:
861  if not storage.exists(path):
862  newPath = storage.instanceSearch(path)
863  newPath = newPath[0] if newPath is not None and len(newPath) else None
864  if newPath is not None:
865  path = newPath
866  localFileObj = storage.getLocalFile(path)
867  self.log.info("Loading %s registry from %s", description, localFileObj.name)
868  registry = dafPersist.Registry.create(localFileObj.name)
869  localFileObj.close()
870  elif not registry and posixIfNoSql:
871  try:
872  self.log.info("Loading Posix %s registry from %s", description, storage.root)
873  registry = dafPersist.PosixRegistry(storage.root)
874  except Exception:
875  registry = None
876 
877  return registry
878 
879  def _transformId(self, dataId):
880  """Generate a standard ID dict from a camera-specific ID dict.
881 
882  Canonical keys include:
883  - amp: amplifier name
884  - ccd: CCD name (in LSST this is a combination of raft and sensor)
885  The default implementation returns a copy of its input.
886 
887  Parameters
888  ----------
889  dataId : `dict`
890  Dataset identifier; this must not be modified
891 
892  Returns
893  -------
894  `dict`
895  Transformed dataset identifier.
896  """
897 
898  return dataId.copy()
899 
900  def _mapActualToPath(self, template, actualId):
901  """Convert a template path to an actual path, using the actual data
902  identifier. This implementation is usually sufficient but can be
903  overridden by the subclass.
904 
905  Parameters
906  ----------
907  template : `str`
908  Template path
909  actualId : `dict`
910  Dataset identifier
911 
912  Returns
913  -------
914  `str`
915  Pathname
916  """
917 
918  try:
919  transformedId = self._transformId(actualId)
920  return template % transformedId
921  except Exception as e:
922  raise RuntimeError("Failed to format %r with data %r: %s" % (template, transformedId, e))
923 
924  @staticmethod
925  def getShortCcdName(ccdName):
926  """Convert a CCD name to a form useful as a filename
927 
928  The default implementation converts spaces to underscores.
929  """
930  return ccdName.replace(" ", "_")
931 
932  def _extractDetectorName(self, dataId):
933  """Extract the detector (CCD) name from the dataset identifier.
934 
935  The name in question is the detector name used by lsst.afw.cameraGeom.
936 
937  Parameters
938  ----------
939  dataId : `dict`
940  Dataset identifier.
941 
942  Returns
943  -------
944  `str`
945  Detector name
946  """
947  raise NotImplementedError("No _extractDetectorName() function specified")
948 
949  def _extractAmpId(self, dataId):
950  """Extract the amplifier identifer from a dataset identifier.
951 
952  .. note:: Deprecated in 11_0
953 
954  amplifier identifier has two parts: the detector name for the CCD
955  containing the amplifier and index of the amplifier in the detector.
956 
957  Parameters
958  ----------
959  dataId : `dict`
960  Dataset identifer
961 
962  Returns
963  -------
964  `tuple`
965  Amplifier identifier
966  """
967 
968  trDataId = self._transformId(dataId)
969  return (trDataId["ccd"], int(trDataId['amp']))
970 
971  def _setAmpDetector(self, item, dataId, trimmed=True):
972  """Set the detector object in an Exposure for an amplifier.
973 
974  Defects are also added to the Exposure based on the detector object.
975 
976  Parameters
977  ----------
978  item : `lsst.afw.image.Exposure`
979  Exposure to set the detector in.
980  dataId : `dict`
981  Dataset identifier
982  trimmed : `bool`
983  Should detector be marked as trimmed? (ignored)
984  """
985 
986  return self._setCcdDetector(item=item, dataId=dataId, trimmed=trimmed)
987 
988  def _setCcdDetector(self, item, dataId, trimmed=True):
989  """Set the detector object in an Exposure for a CCD.
990 
991  Parameters
992  ----------
993  item : `lsst.afw.image.Exposure`
994  Exposure to set the detector in.
995  dataId : `dict`
996  Dataset identifier
997  trimmed : `bool`
998  Should detector be marked as trimmed? (ignored)
999  """
1000  if item.getDetector() is not None:
1001  return
1002 
1003  detectorName = self._extractDetectorName(dataId)
1004  detector = self.camera[detectorName]
1005  item.setDetector(detector)
1006 
1007  def _setFilter(self, mapping, item, dataId):
1008  """Set the filter object in an Exposure. If the Exposure had a FILTER
1009  keyword, this was already processed during load. But if it didn't,
1010  use the filter from the registry.
1011 
1012  Parameters
1013  ----------
1014  mapping : `lsst.obs.base.Mapping`
1015  Where to get the filter from.
1016  item : `lsst.afw.image.Exposure`
1017  Exposure to set the filter in.
1018  dataId : `dict`
1019  Dataset identifier.
1020  """
1021 
1022  if not (isinstance(item, afwImage.ExposureU) or isinstance(item, afwImage.ExposureI) or
1023  isinstance(item, afwImage.ExposureF) or isinstance(item, afwImage.ExposureD)):
1024  return
1025 
1026  if item.getFilter().getId() != afwImage.Filter.UNKNOWN:
1027  return
1028 
1029  actualId = mapping.need(['filter'], dataId)
1030  filterName = actualId['filter']
1031  if self.filters is not None and filterName in self.filters:
1032  filterName = self.filters[filterName]
1033  item.setFilter(afwImage.Filter(filterName))
1034 
1035  def _standardizeExposure(self, mapping, item, dataId, filter=True,
1036  trimmed=True, setVisitInfo=True):
1037  """Default standardization function for images.
1038 
1039  This sets the Detector from the camera geometry
1040  and optionally set the Filter. In both cases this saves
1041  having to persist some data in each exposure (or image).
1042 
1043  Parameters
1044  ----------
1045  mapping : `lsst.obs.base.Mapping`
1046  Where to get the values from.
1047  item : image-like object
1048  Can be any of lsst.afw.image.Exposure,
1049  lsst.afw.image.DecoratedImage, lsst.afw.image.Image
1050  or lsst.afw.image.MaskedImage
1051 
1052  dataId : `dict`
1053  Dataset identifier
1054  filter : `bool`
1055  Set filter? Ignored if item is already an exposure
1056  trimmed : `bool`
1057  Should detector be marked as trimmed?
1058  setVisitInfo : `bool`
1059  Should Exposure have its VisitInfo filled out from the metadata?
1060 
1061  Returns
1062  -------
1063  `lsst.afw.image.Exposure`
1064  The standardized Exposure.
1065  """
1066  try:
1067  exposure = exposureFromImage(item, dataId, mapper=self, logger=self.log,
1068  setVisitInfo=setVisitInfo)
1069  except Exception as e:
1070  self.log.error("Could not turn item=%r into an exposure: %s" % (repr(item), e))
1071  raise
1072 
1073  if mapping.level.lower() == "amp":
1074  self._setAmpDetector(exposure, dataId, trimmed)
1075  elif mapping.level.lower() == "ccd":
1076  self._setCcdDetector(exposure, dataId, trimmed)
1077 
1078  # We can only create a WCS if it doesn't already have one and
1079  # we have either a VisitInfo or exposure metadata.
1080  if exposure.getWcs() is None and \
1081  (exposure.getInfo().getVisitInfo() is not None or exposure.getMetadata().toDict() != {}):
1082  self._createInitialSkyWcs(exposure)
1083 
1084  if filter:
1085  self._setFilter(mapping, exposure, dataId)
1086 
1087  return exposure
1088 
1089  def _createSkyWcsFromMetadata(self, exposure):
1090  """Create a SkyWcs from the FITS header metadata in an Exposure.
1091 
1092  Parameters
1093  ----------
1094  exposure : `lsst.afw.image.Exposure`
1095  The exposure to get metadata from, and attach the SkyWcs to.
1096  """
1097  metadata = exposure.getMetadata()
1098  try:
1099  wcs = afwGeom.makeSkyWcs(metadata, strip=True)
1100  exposure.setWcs(wcs)
1101  except pexExcept.TypeError as e:
1102  # See DM-14372 for why this is debug and not warn (e.g. calib files without wcs metadata).
1103  self.log.debug("wcs set to None; missing information found in metadata to create a valid wcs:"
1104  " %s", e.args[0])
1105  # ensure any WCS values stripped from the metadata are removed in the exposure
1106  exposure.setMetadata(metadata)
1107 
1108  def _createInitialSkyWcs(self, exposure):
1109  """Create a SkyWcs from the boresight and camera geometry.
1110 
1111  If the boresight or camera geometry do not support this method of
1112  WCS creation, this falls back on the header metadata-based version
1113  (typically a purely linear FITS crval/crpix/cdmatrix WCS).
1114 
1115  Parameters
1116  ----------
1117  exposure : `lsst.afw.image.Exposure`
1118  The exposure to get data from, and attach the SkyWcs to.
1119  """
1120  # Always use try to use metadata first, to strip WCS keys from it.
1121  self._createSkyWcsFromMetadata(exposure)
1122 
1123  if exposure.getInfo().getVisitInfo() is None:
1124  msg = "No VisitInfo; cannot access boresight information. Defaulting to metadata-based SkyWcs."
1125  self.log.warn(msg)
1126  return
1127  try:
1128  newSkyWcs = createInitialSkyWcs(exposure.getInfo().getVisitInfo(), exposure.getDetector())
1129  exposure.setWcs(newSkyWcs)
1130  except InitialSkyWcsError as e:
1131  msg = "Cannot create SkyWcs using VisitInfo and Detector, using metadata-based SkyWcs: %s"
1132  self.log.warn(msg, e)
1133  self.log.debug("Exception was: %s", traceback.TracebackException.from_exception(e))
1134  if e.__context__ is not None:
1135  self.log.debug("Root-cause Exception was: %s",
1136  traceback.TracebackException.from_exception(e.__context__))
1137 
1138  def _makeCamera(self, policy, repositoryDir):
1139  """Make a camera (instance of lsst.afw.cameraGeom.Camera) describing
1140  the camera geometry
1141 
1142  Also set self.cameraDataLocation, if relevant (else it can be left
1143  None).
1144 
1145  This implementation assumes that policy contains an entry "camera"
1146  that points to the subdirectory in this package of camera data;
1147  specifically, that subdirectory must contain:
1148  - a file named `camera.py` that contains persisted camera config
1149  - ampInfo table FITS files, as required by
1150  lsst.afw.cameraGeom.makeCameraFromPath
1151 
1152  Parameters
1153  ----------
1154  policy : `lsst.daf.persistence.Policy`
1155  Policy with per-camera defaults already merged
1156  (PexPolicy only for backward compatibility).
1157  repositoryDir : `str`
1158  Policy repository for the subclassing module (obtained with
1159  getRepositoryPath() on the per-camera default dictionary).
1160  """
1161  if 'camera' not in policy:
1162  raise RuntimeError("Cannot find 'camera' in policy; cannot construct a camera")
1163  cameraDataSubdir = policy['camera']
1164  self.cameraDataLocation = os.path.normpath(
1165  os.path.join(repositoryDir, cameraDataSubdir, "camera.py"))
1166  cameraConfig = afwCameraGeom.CameraConfig()
1167  cameraConfig.load(self.cameraDataLocation)
1168  ampInfoPath = os.path.dirname(self.cameraDataLocation)
1169  return afwCameraGeom.makeCameraFromPath(
1170  cameraConfig=cameraConfig,
1171  ampInfoPath=ampInfoPath,
1172  shortNameFunc=self.getShortCcdName,
1173  pupilFactoryClass=self.PupilFactoryClass
1174  )
1175 
1176  def getRegistry(self):
1177  """Get the registry used by this mapper.
1178 
1179  Returns
1180  -------
1181  Registry or None
1182  The registry used by this mapper for this mapper's repository.
1183  """
1184  return self.registry
1185 
1186  def getImageCompressionSettings(self, datasetType, dataId):
1187  """Stuff image compression settings into a daf.base.PropertySet
1188 
1189  This goes into the ButlerLocation's "additionalData", which gets
1190  passed into the boost::persistence framework.
1191 
1192  Parameters
1193  ----------
1194  datasetType : `str`
1195  Type of dataset for which to get the image compression settings.
1196  dataId : `dict`
1197  Dataset identifier.
1198 
1199  Returns
1200  -------
1201  additionalData : `lsst.daf.base.PropertySet`
1202  Image compression settings.
1203  """
1204  mapping = self.mappings[datasetType]
1205  recipeName = mapping.recipe
1206  storageType = mapping.storage
1207  if storageType not in self._writeRecipes:
1208  return dafBase.PropertySet()
1209  if recipeName not in self._writeRecipes[storageType]:
1210  raise RuntimeError("Unrecognized write recipe for datasetType %s (storage type %s): %s" %
1211  (datasetType, storageType, recipeName))
1212  recipe = self._writeRecipes[storageType][recipeName].deepCopy()
1213  seed = hash(tuple(dataId.items())) % 2**31
1214  for plane in ("image", "mask", "variance"):
1215  if recipe.exists(plane + ".scaling.seed") and recipe.getScalar(plane + ".scaling.seed") == 0:
1216  recipe.set(plane + ".scaling.seed", seed)
1217  return recipe
1218 
1219  def _initWriteRecipes(self):
1220  """Read the recipes for writing files
1221 
1222  These recipes are currently used for configuring FITS compression,
1223  but they could have wider uses for configuring different flavors
1224  of the storage types. A recipe is referred to by a symbolic name,
1225  which has associated settings. These settings are stored as a
1226  `PropertySet` so they can easily be passed down to the
1227  boost::persistence framework as the "additionalData" parameter.
1228 
1229  The list of recipes is written in YAML. A default recipe and
1230  some other convenient recipes are in obs_base/policy/writeRecipes.yaml
1231  and these may be overridden or supplemented by the individual obs_*
1232  packages' own policy/writeRecipes.yaml files.
1233 
1234  Recipes are grouped by the storage type. Currently, only the
1235  ``FitsStorage`` storage type uses recipes, which uses it to
1236  configure FITS image compression.
1237 
1238  Each ``FitsStorage`` recipe for FITS compression should define
1239  "image", "mask" and "variance" entries, each of which may contain
1240  "compression" and "scaling" entries. Defaults will be provided for
1241  any missing elements under "compression" and "scaling".
1242 
1243  The allowed entries under "compression" are:
1244 
1245  * algorithm (string): compression algorithm to use
1246  * rows (int): number of rows per tile (0 = entire dimension)
1247  * columns (int): number of columns per tile (0 = entire dimension)
1248  * quantizeLevel (float): cfitsio quantization level
1249 
1250  The allowed entries under "scaling" are:
1251 
1252  * algorithm (string): scaling algorithm to use
1253  * bitpix (int): bits per pixel (0,8,16,32,64,-32,-64)
1254  * fuzz (bool): fuzz the values when quantising floating-point values?
1255  * seed (long): seed for random number generator when fuzzing
1256  * maskPlanes (list of string): mask planes to ignore when doing
1257  statistics
1258  * quantizeLevel: divisor of the standard deviation for STDEV_* scaling
1259  * quantizePad: number of stdev to allow on the low side (for
1260  STDEV_POSITIVE/NEGATIVE)
1261  * bscale: manually specified BSCALE (for MANUAL scaling)
1262  * bzero: manually specified BSCALE (for MANUAL scaling)
1263 
1264  A very simple example YAML recipe:
1265 
1266  FitsStorage:
1267  default:
1268  image: &default
1269  compression:
1270  algorithm: GZIP_SHUFFLE
1271  mask: *default
1272  variance: *default
1273  """
1274  recipesFile = os.path.join(getPackageDir("obs_base"), "policy", "writeRecipes.yaml")
1275  recipes = dafPersist.Policy(recipesFile)
1276  supplementsFile = os.path.join(self.getPackageDir(), "policy", "writeRecipes.yaml")
1277  validationMenu = {'FitsStorage': validateRecipeFitsStorage, }
1278  if os.path.exists(supplementsFile) and supplementsFile != recipesFile:
1279  supplements = dafPersist.Policy(supplementsFile)
1280  # Don't allow overrides, only supplements
1281  for entry in validationMenu:
1282  intersection = set(recipes[entry].names()).intersection(set(supplements.names()))
1283  if intersection:
1284  raise RuntimeError("Recipes provided in %s section %s may not override those in %s: %s" %
1285  (supplementsFile, entry, recipesFile, intersection))
1286  recipes.update(supplements)
1287 
1288  self._writeRecipes = {}
1289  for storageType in recipes.names(True):
1290  if "default" not in recipes[storageType]:
1291  raise RuntimeError("No 'default' recipe defined for storage type %s in %s" %
1292  (storageType, recipesFile))
1293  self._writeRecipes[storageType] = validationMenu[storageType](recipes[storageType])
1294 
1295 
1296 def exposureFromImage(image, dataId=None, mapper=None, logger=None, setVisitInfo=True):
1297  """Generate an Exposure from an image-like object
1298 
1299  If the image is a DecoratedImage then also set its WCS and metadata
1300  (Image and MaskedImage are missing the necessary metadata
1301  and Exposure already has those set)
1302 
1303  Parameters
1304  ----------
1305  image : Image-like object
1306  Can be one of lsst.afw.image.DecoratedImage, Image, MaskedImage or
1307  Exposure.
1308 
1309  Returns
1310  -------
1311  `lsst.afw.image.Exposure`
1312  Exposure containing input image.
1313  """
1314  metadata = None
1315  if isinstance(image, afwImage.MaskedImage):
1316  exposure = afwImage.makeExposure(image)
1317  elif isinstance(image, afwImage.DecoratedImage):
1318  exposure = afwImage.makeExposure(afwImage.makeMaskedImage(image.getImage()))
1319  metadata = image.getMetadata()
1320  exposure.setMetadata(metadata)
1321  elif isinstance(image, afwImage.Exposure):
1322  exposure = image
1323  metadata = exposure.getMetadata()
1324  else: # Image
1325  exposure = afwImage.makeExposure(afwImage.makeMaskedImage(image))
1326 
1327  # set VisitInfo if we can
1328  if setVisitInfo and exposure.getInfo().getVisitInfo() is None:
1329  if metadata is not None:
1330  if mapper is None:
1331  if not logger:
1332  logger = lsstLog.Log.getLogger("CameraMapper")
1333  logger.warn("I can only set the VisitInfo if you provide a mapper")
1334  else:
1335  exposureId = mapper._computeCcdExposureId(dataId)
1336  visitInfo = mapper.makeRawVisitInfo(md=metadata, exposureId=exposureId)
1337 
1338  exposure.getInfo().setVisitInfo(visitInfo)
1339 
1340  return exposure
1341 
1342 
1344  """Validate recipes for FitsStorage
1345 
1346  The recipes are supplemented with default values where appropriate.
1347 
1348  TODO: replace this custom validation code with Cerberus (DM-11846)
1349 
1350  Parameters
1351  ----------
1352  recipes : `lsst.daf.persistence.Policy`
1353  FitsStorage recipes to validate.
1354 
1355  Returns
1356  -------
1357  validated : `lsst.daf.base.PropertySet`
1358  Validated FitsStorage recipe.
1359 
1360  Raises
1361  ------
1362  `RuntimeError`
1363  If validation fails.
1364  """
1365  # Schemas define what should be there, and the default values (and by the default
1366  # value, the expected type).
1367  compressionSchema = {
1368  "algorithm": "NONE",
1369  "rows": 1,
1370  "columns": 0,
1371  "quantizeLevel": 0.0,
1372  }
1373  scalingSchema = {
1374  "algorithm": "NONE",
1375  "bitpix": 0,
1376  "maskPlanes": ["NO_DATA"],
1377  "seed": 0,
1378  "quantizeLevel": 4.0,
1379  "quantizePad": 5.0,
1380  "fuzz": True,
1381  "bscale": 1.0,
1382  "bzero": 0.0,
1383  }
1384 
1385  def checkUnrecognized(entry, allowed, description):
1386  """Check to see if the entry contains unrecognised keywords"""
1387  unrecognized = set(entry.keys()) - set(allowed)
1388  if unrecognized:
1389  raise RuntimeError(
1390  "Unrecognized entries when parsing image compression recipe %s: %s" %
1391  (description, unrecognized))
1392 
1393  validated = {}
1394  for name in recipes.names(True):
1395  checkUnrecognized(recipes[name], ["image", "mask", "variance"], name)
1396  rr = dafBase.PropertySet()
1397  validated[name] = rr
1398  for plane in ("image", "mask", "variance"):
1399  checkUnrecognized(recipes[name][plane], ["compression", "scaling"],
1400  name + "->" + plane)
1401 
1402  for settings, schema in (("compression", compressionSchema),
1403  ("scaling", scalingSchema)):
1404  prefix = plane + "." + settings
1405  if settings not in recipes[name][plane]:
1406  for key in schema:
1407  rr.set(prefix + "." + key, schema[key])
1408  continue
1409  entry = recipes[name][plane][settings]
1410  checkUnrecognized(entry, schema.keys(), name + "->" + plane + "->" + settings)
1411  for key in schema:
1412  value = type(schema[key])(entry[key]) if key in entry else schema[key]
1413  rr.set(prefix + "." + key, value)
1414  return validated
def _makeCamera(self, policy, repositoryDir)
def map_expIdInfo(self, dataId, write=False)
def _setAmpDetector(self, item, dataId, trimmed=True)
def validateRecipeFitsStorage(recipes)
def _standardizeExposure(self, mapping, item, dataId, filter=True, trimmed=True, setVisitInfo=True)
def _setFilter(self, mapping, item, dataId)
def _setCcdDetector(self, item, dataId, trimmed=True)
def std_bfKernel(self, item, dataId)
def getKeys(self, datasetType, level)
def getImageCompressionSettings(self, datasetType, dataId)
def _createSkyWcsFromMetadata(self, exposure)
def createInitialSkyWcs(visitInfo, detector, flipX=False)
Definition: utils.py:43
def map_camera(self, dataId, write=False)
def backup(self, datasetType, dataId)
def _setupRegistry(self, name, description, path, policy, policyKey, storage, searchParents=True, posixIfNoSql=True)
Utility functions.
def std_skypolicy(self, item, dataId)
def bypass_camera(self, datasetType, pythonType, butlerLocation, dataId)
def _initMappings(self, policy, rootStorage=None, calibStorage=None, provided=None)
def __init__(self, policy, repositoryDir, root=None, registry=None, calibRoot=None, calibRegistry=None, provided=None, parentRegistry=None, repositoryCfg=None)
def bypass_expIdInfo(self, datasetType, pythonType, location, dataId)
def exposureFromImage(image, dataId=None, mapper=None, logger=None, setVisitInfo=True)