29 from astro_metadata_translator
import fix_header
31 import lsst.daf.persistence
as dafPersist
32 from .
import ImageMapping, ExposureMapping, CalibrationMapping, DatasetMapping
33 import lsst.daf.base
as dafBase
34 import lsst.afw.geom
as afwGeom
35 import lsst.afw.image
as afwImage
36 import lsst.afw.table
as afwTable
37 from lsst.afw.fits
import readMetadata
38 import lsst.afw.cameraGeom
as afwCameraGeom
39 import lsst.log
as lsstLog
41 from .exposureIdInfo
import ExposureIdInfo
42 from .makeRawVisitInfo
import MakeRawVisitInfo
43 from .utils
import createInitialSkyWcs, InitialSkyWcsError
45 from ._instrument
import Instrument
47 __all__ = [
"CameraMapper",
"exposureFromImage"]
52 """CameraMapper is a base class for mappers that handle images from a
53 camera and products derived from them. This provides an abstraction layer
54 between the data on disk and the code.
56 Public methods: keys, queryMetadata, getDatasetTypes, map,
57 canStandardize, standardize
59 Mappers for specific data sources (e.g., CFHT Megacam, LSST
60 simulations, etc.) should inherit this class.
62 The CameraMapper manages datasets within a "root" directory. Note that
63 writing to a dataset present in the input root will hide the existing
64 dataset but not overwrite it. See #2160 for design discussion.
66 A camera is assumed to consist of one or more rafts, each composed of
67 multiple CCDs. Each CCD is in turn composed of one or more amplifiers
68 (amps). A camera is also assumed to have a camera geometry description
69 (CameraGeom object) as a policy file, a filter description (Filter class
70 static configuration) as another policy file.
72 Information from the camera geometry and defects are inserted into all
73 Exposure objects returned.
75 The mapper uses one or two registries to retrieve metadata about the
76 images. The first is a registry of all raw exposures. This must contain
77 the time of the observation. One or more tables (or the equivalent)
78 within the registry are used to look up data identifier components that
79 are not specified by the user (e.g. filter) and to return results for
80 metadata queries. The second is an optional registry of all calibration
81 data. This should contain validity start and end entries for each
82 calibration dataset in the same timescale as the observation time.
84 Subclasses will typically set MakeRawVisitInfoClass and optionally the
85 metadata translator class:
87 MakeRawVisitInfoClass: a class variable that points to a subclass of
88 MakeRawVisitInfo, a functor that creates an
89 lsst.afw.image.VisitInfo from the FITS metadata of a raw image.
91 translatorClass: The `~astro_metadata_translator.MetadataTranslator`
92 class to use for fixing metadata values. If it is not set an attempt
93 will be made to infer the class from ``MakeRawVisitInfoClass``, failing
94 that the metadata fixup will try to infer the translator class from the
97 Subclasses must provide the following methods:
99 _extractDetectorName(self, dataId): returns the detector name for a CCD
100 (e.g., "CFHT 21", "R:1,2 S:3,4") as used in the AFW CameraGeom class given
101 a dataset identifier referring to that CCD or a subcomponent of it.
103 _computeCcdExposureId(self, dataId): see below
105 _computeCoaddExposureId(self, dataId, singleFilter): see below
107 Subclasses may also need to override the following methods:
109 _transformId(self, dataId): transformation of a data identifier
110 from colloquial usage (e.g., "ccdname") to proper/actual usage
111 (e.g., "ccd"), including making suitable for path expansion (e.g. removing
112 commas). The default implementation does nothing. Note that this
113 method should not modify its input parameter.
115 getShortCcdName(self, ccdName): a static method that returns a shortened
116 name suitable for use as a filename. The default version converts spaces
119 _mapActualToPath(self, template, actualId): convert a template path to an
120 actual path, using the actual dataset identifier.
122 The mapper's behaviors are largely specified by the policy file.
123 See the MapperDictionary.paf for descriptions of the available items.
125 The 'exposures', 'calibrations', and 'datasets' subpolicies configure
126 mappings (see Mappings class).
128 Common default mappings for all subclasses can be specified in the
129 "policy/{images,exposures,calibrations,datasets}.yaml" files. This
130 provides a simple way to add a product to all camera mappers.
132 Functions to map (provide a path to the data given a dataset
133 identifier dictionary) and standardize (convert data into some standard
134 format or type) may be provided in the subclass as "map_{dataset type}"
135 and "std_{dataset type}", respectively.
137 If non-Exposure datasets cannot be retrieved using standard
138 daf_persistence methods alone, a "bypass_{dataset type}" function may be
139 provided in the subclass to return the dataset instead of using the
140 "datasets" subpolicy.
142 Implementations of map_camera and bypass_camera that should typically be
143 sufficient are provided in this base class.
149 Instead of auto-loading the camera at construction time, load it from
150 the calibration registry
154 policy : daf_persistence.Policy,
155 Policy with per-camera defaults already merged.
156 repositoryDir : string
157 Policy repository for the subclassing module (obtained with
158 getRepositoryPath() on the per-camera default dictionary).
159 root : string, optional
160 Path to the root directory for data.
161 registry : string, optional
162 Path to registry with data's metadata.
163 calibRoot : string, optional
164 Root directory for calibrations.
165 calibRegistry : string, optional
166 Path to registry with calibrations' metadata.
167 provided : list of string, optional
168 Keys provided by the mapper.
169 parentRegistry : Registry subclass, optional
170 Registry from a parent repository that may be used to look up
172 repositoryCfg : daf_persistence.RepositoryCfg or None, optional
173 The configuration information for the repository this mapper is
180 MakeRawVisitInfoClass = MakeRawVisitInfo
183 PupilFactoryClass = afwCameraGeom.PupilFactory
186 translatorClass =
None
190 _gen3instrument =
None
193 root=None, registry=None, calibRoot=None, calibRegistry=None,
194 provided=None, parentRegistry=None, repositoryCfg=None):
196 dafPersist.Mapper.__init__(self)
198 self.
log = lsstLog.Log.getLogger(
"CameraMapper")
203 self.
root = repositoryCfg.root
207 repoPolicy = repositoryCfg.policy
if repositoryCfg
else None
208 if repoPolicy
is not None:
209 policy.update(repoPolicy)
213 if 'levels' in policy:
214 levelsPolicy = policy[
'levels']
215 for key
in levelsPolicy.names(
True):
216 self.
levels[key] = set(levelsPolicy.asArray(key))
219 if 'defaultSubLevels' in policy:
225 root = dafPersist.LogicalLocation(root).locString()
227 self.
rootStorage = dafPersist.Storage.makeFromURI(uri=root)
235 if calibRoot
is not None:
236 calibRoot = dafPersist.Storage.absolutePath(root, calibRoot)
237 calibStorage = dafPersist.Storage.makeFromURI(uri=calibRoot,
240 calibRoot = policy.get(
'calibRoot',
None)
242 calibStorage = dafPersist.Storage.makeFromURI(uri=calibRoot,
244 if calibStorage
is None:
252 posixIfNoSql=(
not parentRegistry))
255 needCalibRegistry = policy.get(
'needCalibRegistry',
None)
256 if needCalibRegistry:
259 "calibRegistryPath", calibStorage,
263 "'needCalibRegistry' is true in Policy, but was unable to locate a repo at "
264 f
"calibRoot ivar:{calibRoot} or policy['calibRoot']:{policy.get('calibRoot', None)}")
284 raise ValueError(
'class variable packageName must not be None')
294 def _initMappings(self, policy, rootStorage=None, calibStorage=None, provided=None):
295 """Initialize mappings
297 For each of the dataset types that we want to be able to read, there
298 are methods that can be created to support them:
299 * map_<dataset> : determine the path for dataset
300 * std_<dataset> : standardize the retrieved dataset
301 * bypass_<dataset> : retrieve the dataset (bypassing the usual
303 * query_<dataset> : query the registry
305 Besides the dataset types explicitly listed in the policy, we create
306 additional, derived datasets for additional conveniences,
307 e.g., reading the header of an image, retrieving only the size of a
312 policy : `lsst.daf.persistence.Policy`
313 Policy with per-camera defaults already merged
314 rootStorage : `Storage subclass instance`
315 Interface to persisted repository data.
316 calibRoot : `Storage subclass instance`
317 Interface to persisted calib repository data
318 provided : `list` of `str`
319 Keys provided by the mapper
322 imgMappingPolicy = dafPersist.Policy(dafPersist.Policy.defaultPolicyFile(
323 "obs_base",
"ImageMappingDefaults.yaml",
"policy"))
324 expMappingPolicy = dafPersist.Policy(dafPersist.Policy.defaultPolicyFile(
325 "obs_base",
"ExposureMappingDefaults.yaml",
"policy"))
326 calMappingPolicy = dafPersist.Policy(dafPersist.Policy.defaultPolicyFile(
327 "obs_base",
"CalibrationMappingDefaults.yaml",
"policy"))
328 dsMappingPolicy = dafPersist.Policy()
332 (
"images", imgMappingPolicy, ImageMapping),
333 (
"exposures", expMappingPolicy, ExposureMapping),
334 (
"calibrations", calMappingPolicy, CalibrationMapping),
335 (
"datasets", dsMappingPolicy, DatasetMapping)
338 for name, defPolicy, cls
in mappingList:
340 datasets = policy[name]
343 defaultsPath = os.path.join(
getPackageDir(
"obs_base"),
"policy", name +
".yaml")
344 if os.path.exists(defaultsPath):
345 datasets.merge(dafPersist.Policy(defaultsPath))
348 setattr(self, name, mappings)
349 for datasetType
in datasets.names(
True):
350 subPolicy = datasets[datasetType]
351 subPolicy.merge(defPolicy)
353 if not hasattr(self,
"map_" + datasetType)
and 'composite' in subPolicy:
354 def compositeClosure(dataId, write=False, mapper=None, mapping=None,
355 subPolicy=subPolicy):
356 components = subPolicy.get(
'composite')
357 assembler = subPolicy[
'assembler']
if 'assembler' in subPolicy
else None
358 disassembler = subPolicy[
'disassembler']
if 'disassembler' in subPolicy
else None
359 python = subPolicy[
'python']
360 butlerComposite = dafPersist.ButlerComposite(assembler=assembler,
361 disassembler=disassembler,
365 for name, component
in components.items():
366 butlerComposite.add(id=name,
367 datasetType=component.get(
'datasetType'),
368 setter=component.get(
'setter',
None),
369 getter=component.get(
'getter',
None),
370 subset=component.get(
'subset',
False),
371 inputOnly=component.get(
'inputOnly',
False))
372 return butlerComposite
373 setattr(self,
"map_" + datasetType, compositeClosure)
378 if name ==
"calibrations":
380 provided=provided, dataRoot=rootStorage)
382 mapping =
cls(datasetType, subPolicy, self.
registry, rootStorage, provided=provided)
385 raise ValueError(f
"Duplicate mapping policy for dataset type {datasetType}")
386 self.
keyDict.update(mapping.keys())
387 mappings[datasetType] = mapping
388 self.
mappings[datasetType] = mapping
389 if not hasattr(self,
"map_" + datasetType):
390 def mapClosure(dataId, write=False, mapper=weakref.proxy(self), mapping=mapping):
391 return mapping.map(mapper, dataId, write)
392 setattr(self,
"map_" + datasetType, mapClosure)
393 if not hasattr(self,
"query_" + datasetType):
394 def queryClosure(format, dataId, mapping=mapping):
395 return mapping.lookup(format, dataId)
396 setattr(self,
"query_" + datasetType, queryClosure)
397 if hasattr(mapping,
"standardize")
and not hasattr(self,
"std_" + datasetType):
398 def stdClosure(item, dataId, mapper=weakref.proxy(self), mapping=mapping):
399 return mapping.standardize(mapper, item, dataId)
400 setattr(self,
"std_" + datasetType, stdClosure)
402 def setMethods(suffix, mapImpl=None, bypassImpl=None, queryImpl=None):
403 """Set convenience methods on CameraMapper"""
404 mapName =
"map_" + datasetType +
"_" + suffix
405 bypassName =
"bypass_" + datasetType +
"_" + suffix
406 queryName =
"query_" + datasetType +
"_" + suffix
407 if not hasattr(self, mapName):
408 setattr(self, mapName, mapImpl
or getattr(self,
"map_" + datasetType))
409 if not hasattr(self, bypassName):
410 if bypassImpl
is None and hasattr(self,
"bypass_" + datasetType):
411 bypassImpl = getattr(self,
"bypass_" + datasetType)
412 if bypassImpl
is not None:
413 setattr(self, bypassName, bypassImpl)
414 if not hasattr(self, queryName):
415 setattr(self, queryName, queryImpl
or getattr(self,
"query_" + datasetType))
418 setMethods(
"filename", bypassImpl=
lambda datasetType, pythonType, location, dataId:
419 [os.path.join(location.getStorage().root, p)
for p
in location.getLocations()])
421 if subPolicy[
"storage"] ==
"FitsStorage":
422 def getMetadata(datasetType, pythonType, location, dataId):
423 md = readMetadata(location.getLocationsWithRoot()[0])
427 setMethods(
"md", bypassImpl=getMetadata)
430 addName =
"add_" + datasetType
431 if not hasattr(self, addName):
434 if name ==
"exposures":
435 def getSkyWcs(datasetType, pythonType, location, dataId):
436 fitsReader = afwImage.ExposureFitsReader(location.getLocationsWithRoot()[0])
437 return fitsReader.readWcs()
439 setMethods(
"wcs", bypassImpl=getSkyWcs)
441 def getRawHeaderWcs(datasetType, pythonType, location, dataId):
442 """Create a SkyWcs from the un-modified raw
443 FITS WCS header keys."""
444 if datasetType[:3] !=
"raw":
445 raise dafPersist.NoResults(
"Can only get header WCS for raw exposures.",
447 return afwGeom.makeSkyWcs(readMetadata(location.getLocationsWithRoot()[0]))
449 setMethods(
"header_wcs", bypassImpl=getRawHeaderWcs)
451 def getPhotoCalib(datasetType, pythonType, location, dataId):
452 fitsReader = afwImage.ExposureFitsReader(location.getLocationsWithRoot()[0])
453 return fitsReader.readPhotoCalib()
455 setMethods(
"photoCalib", bypassImpl=getPhotoCalib)
457 def getVisitInfo(datasetType, pythonType, location, dataId):
458 fitsReader = afwImage.ExposureFitsReader(location.getLocationsWithRoot()[0])
459 return fitsReader.readVisitInfo()
461 setMethods(
"visitInfo", bypassImpl=getVisitInfo)
464 def getFilter(datasetType, pythonType, location, dataId):
465 fitsReader = afwImage.ExposureFitsReader(location.getLocationsWithRoot()[0])
466 return fitsReader.readFilter()
468 setMethods(
"filter", bypassImpl=getFilter)
471 def getFilterLabel(datasetType, pythonType, location, dataId):
472 fitsReader = afwImage.ExposureFitsReader(location.getLocationsWithRoot()[0])
473 return fitsReader.readFilterLabel()
475 setMethods(
"filterLabel", bypassImpl=getFilterLabel)
477 setMethods(
"detector",
478 mapImpl=
lambda dataId, write=
False:
479 dafPersist.ButlerLocation(
480 pythonType=
"lsst.afw.cameraGeom.CameraConfig",
482 storageName=
"Internal",
483 locationList=
"ignored",
488 bypassImpl=
lambda datasetType, pythonType, location, dataId:
492 def getBBox(datasetType, pythonType, location, dataId):
493 md = readMetadata(location.getLocationsWithRoot()[0], hdu=1)
495 return afwImage.bboxFromMetadata(md)
497 setMethods(
"bbox", bypassImpl=getBBox)
499 elif name ==
"images":
500 def getBBox(datasetType, pythonType, location, dataId):
501 md = readMetadata(location.getLocationsWithRoot()[0])
503 return afwImage.bboxFromMetadata(md)
504 setMethods(
"bbox", bypassImpl=getBBox)
506 if subPolicy[
"storage"] ==
"FitsCatalogStorage":
508 def getMetadata(datasetType, pythonType, location, dataId):
509 md = readMetadata(os.path.join(location.getStorage().root,
510 location.getLocations()[0]), hdu=1)
514 setMethods(
"md", bypassImpl=getMetadata)
517 if subPolicy[
"storage"] ==
"FitsStorage":
518 def mapSubClosure(dataId, write=False, mapper=weakref.proxy(self), mapping=mapping):
519 subId = dataId.copy()
521 loc = mapping.map(mapper, subId, write)
522 bbox = dataId[
'bbox']
523 llcX = bbox.getMinX()
524 llcY = bbox.getMinY()
525 width = bbox.getWidth()
526 height = bbox.getHeight()
527 loc.additionalData.set(
'llcX', llcX)
528 loc.additionalData.set(
'llcY', llcY)
529 loc.additionalData.set(
'width', width)
530 loc.additionalData.set(
'height', height)
531 if 'imageOrigin' in dataId:
532 loc.additionalData.set(
'imageOrigin',
533 dataId[
'imageOrigin'])
536 def querySubClosure(key, format, dataId, mapping=mapping):
537 subId = dataId.copy()
539 return mapping.lookup(format, subId)
540 setMethods(
"sub", mapImpl=mapSubClosure, queryImpl=querySubClosure)
542 if subPolicy[
"storage"] ==
"FitsCatalogStorage":
545 def getLen(datasetType, pythonType, location, dataId):
546 md = readMetadata(os.path.join(location.getStorage().root,
547 location.getLocations()[0]), hdu=1)
551 setMethods(
"len", bypassImpl=getLen)
554 if not datasetType.endswith(
"_schema")
and datasetType +
"_schema" not in datasets:
555 setMethods(
"schema", bypassImpl=
lambda datasetType, pythonType, location, dataId:
556 afwTable.Schema.readFits(os.path.join(location.getStorage().root,
557 location.getLocations()[0])))
559 def _computeCcdExposureId(self, dataId):
560 """Compute the 64-bit (long) identifier for a CCD exposure.
562 Subclasses must override
567 Data identifier with visit, ccd.
569 raise NotImplementedError()
571 def _computeCoaddExposureId(self, dataId, singleFilter):
572 """Compute the 64-bit (long) identifier for a coadd.
574 Subclasses must override
579 Data identifier with tract and patch.
580 singleFilter : `bool`
581 True means the desired ID is for a single-filter coadd, in which
582 case dataIdmust contain filter.
584 raise NotImplementedError()
586 def _search(self, path):
587 """Search for path in the associated repository's storage.
592 Path that describes an object in the repository associated with
594 Path may contain an HDU indicator, e.g. 'foo.fits[1]'. The
595 indicator will be stripped when searching and so will match
596 filenames without the HDU indicator, e.g. 'foo.fits'. The path
597 returned WILL contain the indicator though, e.g. ['foo.fits[1]'].
602 The path for this object in the repository. Will return None if the
603 object can't be found. If the input argument path contained an HDU
604 indicator, the returned path will also contain the HDU indicator.
609 """Rename any existing object with the given type and dataId.
611 The CameraMapper implementation saves objects in a sequence of e.g.:
617 All of the backups will be placed in the output repo, however, and will
618 not be removed if they are found elsewhere in the _parent chain. This
619 means that the same file will be stored twice if the previous version
620 was found in an input repo.
629 def firstElement(list):
630 """Get the first element in the list, or None if that can't be
633 return list[0]
if list
is not None and len(list)
else None
636 newLocation = self.map(datasetType, dataId, write=
True)
637 newPath = newLocation.getLocations()[0]
638 path = dafPersist.PosixStorage.search(self.
root, newPath, searchParents=
True)
639 path = firstElement(path)
641 while path
is not None:
643 oldPaths.append((n, path))
644 path = dafPersist.PosixStorage.search(self.
root,
"%s~%d" % (newPath, n), searchParents=
True)
645 path = firstElement(path)
646 for n, oldPath
in reversed(oldPaths):
647 self.
rootStorage.copyFile(oldPath,
"%s~%d" % (newPath, n))
650 """Return supported keys.
655 List of keys usable in a dataset identifier
660 """Return a dict of supported keys and their value types for a given
661 dataset type at a given level of the key hierarchy.
666 Dataset type or None for all dataset types.
667 level : `str` or None
668 Level or None for all levels or '' for the default level for the
674 Keys are strings usable in a dataset identifier, values are their
683 if datasetType
is None:
684 keyDict = copy.copy(self.
keyDict)
687 if level
is not None and level
in self.
levels:
688 keyDict = copy.copy(keyDict)
689 for lev
in self.
levels[level]:
704 """Return the name of the camera that this CameraMapper is for."""
706 className = className[className.find(
'.'):-1]
707 m = re.search(
r'(\w+)Mapper', className)
709 m = re.search(
r"class '[\w.]*?(\w+)'", className)
711 return name[:1].lower() + name[1:]
if name
else ''
715 """Return the name of the package containing this CameraMapper."""
717 raise ValueError(
'class variable packageName must not be None')
722 """Return the gen3 Instrument class equivalent for this gen2 Mapper.
727 A `~lsst.obs.base.Instrument` class.
730 raise NotImplementedError(
"Please provide a specific implementation for your instrument"
731 " to enable conversion of this gen2 repository to gen3")
736 raise ValueError(f
"Mapper {cls} has declared a gen3 instrument class of {cls._gen3instrument}"
737 " but that is not an lsst.obs.base.Instrument")
742 """Return the base directory of this package"""
746 """Map a camera dataset."""
748 raise RuntimeError(
"No camera dataset available.")
750 return dafPersist.ButlerLocation(
751 pythonType=
"lsst.afw.cameraGeom.CameraConfig",
753 storageName=
"ConfigStorage",
761 """Return the (preloaded) camera object.
764 raise RuntimeError(
"No camera dataset available.")
768 return dafPersist.ButlerLocation(
769 pythonType=
"lsst.obs.base.ExposureIdInfo",
771 storageName=
"Internal",
772 locationList=
"ignored",
779 """Hook to retrieve an lsst.obs.base.ExposureIdInfo for an exposure"""
780 expId = self.bypass_ccdExposureId(datasetType, pythonType, location, dataId)
781 expBits = self.bypass_ccdExposureId_bits(datasetType, pythonType, location, dataId)
785 """Disable standardization for bfKernel
787 bfKernel is a calibration product that is numpy array,
788 unlike other calibration products that are all images;
789 all calibration images are sent through _standardizeExposure
790 due to CalibrationMapping, but we don't want that to happen to bfKernel
795 """Standardize a raw dataset by converting it to an Exposure instead
798 trimmed=
False, setVisitInfo=
True)
801 """Map a sky policy."""
802 return dafPersist.ButlerLocation(
"lsst.pex.policy.Policy",
"Policy",
803 "Internal",
None,
None, self,
807 """Standardize a sky policy by returning the one we use."""
808 return self.skypolicy
816 def _setupRegistry(self, name, description, path, policy, policyKey, storage, searchParents=True,
818 """Set up a registry (usually SQLite3), trying a number of possible
826 Description of registry (for log messages)
830 Policy that contains the registry name, used if path is None.
832 Key in policy for registry path.
833 storage : Storage subclass
834 Repository Storage to look in.
835 searchParents : bool, optional
836 True if the search for a registry should follow any Butler v1
838 posixIfNoSql : bool, optional
839 If an sqlite registry is not found, will create a posix registry if
844 lsst.daf.persistence.Registry
847 if path
is None and policyKey
in policy:
848 path = dafPersist.LogicalLocation(policy[policyKey]).locString()
849 if os.path.isabs(path):
850 raise RuntimeError(
"Policy should not indicate an absolute path for registry.")
851 if not storage.exists(path):
852 newPath = storage.instanceSearch(path)
854 newPath = newPath[0]
if newPath
is not None and len(newPath)
else None
856 self.
log.warn(
"Unable to locate registry at policy path (also looked in root): %s",
860 self.
log.warn(
"Unable to locate registry at policy path: %s", path)
869 if path
and (path.startswith(root)):
870 path = path[len(root +
'/'):]
871 except AttributeError:
878 def search(filename, description):
879 """Search for file in storage
884 Filename to search for
886 Description of file, for error message.
890 path : `str` or `None`
891 Path to file, or None
893 result = storage.instanceSearch(filename)
896 self.
log.debug(
"Unable to locate %s: %s", description, filename)
901 path = search(
"%s.pgsql" % name,
"%s in root" % description)
903 path = search(
"%s.sqlite3" % name,
"%s in root" % description)
905 path = search(os.path.join(
".",
"%s.sqlite3" % name),
"%s in current dir" % description)
908 if not storage.exists(path):
909 newPath = storage.instanceSearch(path)
910 newPath = newPath[0]
if newPath
is not None and len(newPath)
else None
911 if newPath
is not None:
913 localFileObj = storage.getLocalFile(path)
914 self.
log.info(
"Loading %s registry from %s", description, localFileObj.name)
915 registry = dafPersist.Registry.create(localFileObj.name)
917 elif not registry
and posixIfNoSql:
919 self.
log.info(
"Loading Posix %s registry from %s", description, storage.root)
920 registry = dafPersist.PosixRegistry(storage.root)
926 def _transformId(self, dataId):
927 """Generate a standard ID dict from a camera-specific ID dict.
929 Canonical keys include:
930 - amp: amplifier name
931 - ccd: CCD name (in LSST this is a combination of raft and sensor)
932 The default implementation returns a copy of its input.
937 Dataset identifier; this must not be modified
942 Transformed dataset identifier.
947 def _mapActualToPath(self, template, actualId):
948 """Convert a template path to an actual path, using the actual data
949 identifier. This implementation is usually sufficient but can be
950 overridden by the subclass.
967 return template % transformedId
968 except Exception
as e:
969 raise RuntimeError(
"Failed to format %r with data %r: %s" % (template, transformedId, e))
973 """Convert a CCD name to a form useful as a filename
975 The default implementation converts spaces to underscores.
977 return ccdName.replace(
" ",
"_")
979 def _extractDetectorName(self, dataId):
980 """Extract the detector (CCD) name from the dataset identifier.
982 The name in question is the detector name used by lsst.afw.cameraGeom.
994 raise NotImplementedError(
"No _extractDetectorName() function specified")
996 def _setAmpDetector(self, item, dataId, trimmed=True):
997 """Set the detector object in an Exposure for an amplifier.
999 Defects are also added to the Exposure based on the detector object.
1003 item : `lsst.afw.image.Exposure`
1004 Exposure to set the detector in.
1008 Should detector be marked as trimmed? (ignored)
1011 return self.
_setCcdDetector(item=item, dataId=dataId, trimmed=trimmed)
1013 def _setCcdDetector(self, item, dataId, trimmed=True):
1014 """Set the detector object in an Exposure for a CCD.
1018 item : `lsst.afw.image.Exposure`
1019 Exposure to set the detector in.
1023 Should detector be marked as trimmed? (ignored)
1025 if item.getDetector()
is not None:
1029 detector = self.
camera[detectorName]
1030 item.setDetector(detector)
1033 def _resolveFilters(definitions, idFilter, filterLabel):
1034 """Identify the filter(s) consistent with partial filter information.
1038 definitions : `lsst.obs.base.FilterDefinitionCollection`
1039 The filter definitions in which to search for filters.
1040 idFilter : `str` or `None`
1041 The filter information provided in a data ID.
1042 filterLabel : `lsst.afw.image.FilterLabel` or `None`
1043 The filter information provided by an exposure; may be incomplete.
1047 filters : `set` [`lsst.obs.base.FilterDefinition`]
1048 The set of filters consistent with ``idFilter``
1049 and ``filterLabel``.
1054 matches = set(definitions)
1055 if idFilter
is not None:
1056 matches.intersection_update(definitions.findAll(idFilter))
1057 if filterLabel
is not None and filterLabel.hasPhysicalLabel():
1058 matches.intersection_update(definitions.findAll(filterLabel.physicalLabel))
1059 if filterLabel
is not None and filterLabel.hasBandLabel():
1060 matches.intersection_update(definitions.findAll(filterLabel.bandLabel))
1063 def _setFilter(self, mapping, item, dataId):
1064 """Set the filter information in an Exposure.
1066 The Exposure should already have had a filter loaded, but the reader
1067 (in ``afw``) had to act on incomplete information. This method
1068 cross-checks the filter against the data ID and the standard list
1073 mapping : `lsst.obs.base.Mapping`
1074 Where to get the data ID filter from.
1075 item : `lsst.afw.image.Exposure`
1076 Exposure to set the filter in.
1080 if not (isinstance(item, afwImage.ExposureU)
or isinstance(item, afwImage.ExposureI)
1081 or isinstance(item, afwImage.ExposureF)
or isinstance(item, afwImage.ExposureD)):
1087 except NotImplementedError:
1088 filterDefinitions =
None
1089 itemFilter = item.getFilterLabel()
1091 idFilter = mapping.need([
'filter'], dataId)[
'filter']
1092 except dafPersist.NoResults:
1095 if filterDefinitions
is not None:
1096 definitions = self.
_resolveFilters(filterDefinitions, idFilter, itemFilter)
1097 self.
log.debug(
"Matching filters for id=%r and label=%r are %s.",
1098 idFilter, itemFilter, definitions)
1099 if len(definitions) == 1:
1100 newLabel = list(definitions)[0].makeFilterLabel()
1101 if newLabel != itemFilter:
1102 item.setFilterLabel(newLabel)
1104 self.
log.warn(
"Multiple matches for filter %r with data ID %r.", itemFilter, idFilter)
1107 bands = {d.band
for d
in definitions}
1108 if len(bands) == 1
and itemFilter
is None:
1109 band = list(bands)[0]
1110 item.setFilterLabel(afwImage.FilterLabel(band=band))
1113 self.
log.warn(
"Cannot reconcile filter %r with data ID %r.", itemFilter, idFilter)
1115 if itemFilter
is None:
1118 idFilter = self.
filters[idFilter]
1122 with warnings.catch_warnings():
1123 warnings.filterwarnings(
"ignore", category=FutureWarning)
1124 item.setFilter(afwImage.Filter(idFilter))
1125 except pexExcept.NotFoundError:
1126 self.
log.warn(
"Filter %s not defined. Set to UNKNOWN.", idFilter)
1128 def _standardizeExposure(self, mapping, item, dataId, filter=True,
1129 trimmed=True, setVisitInfo=True):
1130 """Default standardization function for images.
1132 This sets the Detector from the camera geometry
1133 and optionally set the Filter. In both cases this saves
1134 having to persist some data in each exposure (or image).
1138 mapping : `lsst.obs.base.Mapping`
1139 Where to get the values from.
1140 item : image-like object
1141 Can be any of lsst.afw.image.Exposure,
1142 lsst.afw.image.DecoratedImage, lsst.afw.image.Image
1143 or lsst.afw.image.MaskedImage
1148 Set filter? Ignored if item is already an exposure
1150 Should detector be marked as trimmed?
1151 setVisitInfo : `bool`
1152 Should Exposure have its VisitInfo filled out from the metadata?
1156 `lsst.afw.image.Exposure`
1157 The standardized Exposure.
1161 setVisitInfo=setVisitInfo)
1162 except Exception
as e:
1163 self.
log.error(
"Could not turn item=%r into an exposure: %s" % (repr(item), e))
1166 if mapping.level.lower() ==
"amp":
1168 elif mapping.level.lower() ==
"ccd":
1174 if mapping.level.lower() !=
"amp" and exposure.getWcs()
is None and \
1175 (exposure.getInfo().getVisitInfo()
is not None or exposure.getMetadata().toDict()):
1183 def _createSkyWcsFromMetadata(self, exposure):
1184 """Create a SkyWcs from the FITS header metadata in an Exposure.
1188 exposure : `lsst.afw.image.Exposure`
1189 The exposure to get metadata from, and attach the SkyWcs to.
1191 metadata = exposure.getMetadata()
1194 wcs = afwGeom.makeSkyWcs(metadata, strip=
True)
1195 exposure.setWcs(wcs)
1196 except pexExcept.TypeError
as e:
1199 self.
log.debug(
"wcs set to None; missing information found in metadata to create a valid wcs:"
1203 exposure.setMetadata(metadata)
1205 def _createInitialSkyWcs(self, exposure):
1206 """Create a SkyWcs from the boresight and camera geometry.
1208 If the boresight or camera geometry do not support this method of
1209 WCS creation, this falls back on the header metadata-based version
1210 (typically a purely linear FITS crval/crpix/cdmatrix WCS).
1214 exposure : `lsst.afw.image.Exposure`
1215 The exposure to get data from, and attach the SkyWcs to.
1220 if exposure.getInfo().getVisitInfo()
is None:
1221 msg =
"No VisitInfo; cannot access boresight information. Defaulting to metadata-based SkyWcs."
1225 newSkyWcs =
createInitialSkyWcs(exposure.getInfo().getVisitInfo(), exposure.getDetector())
1226 exposure.setWcs(newSkyWcs)
1227 except InitialSkyWcsError
as e:
1228 msg =
"Cannot create SkyWcs using VisitInfo and Detector, using metadata-based SkyWcs: %s"
1229 self.
log.warn(msg, e)
1230 self.
log.debug(
"Exception was: %s", traceback.TracebackException.from_exception(e))
1231 if e.__context__
is not None:
1232 self.
log.debug(
"Root-cause Exception was: %s",
1233 traceback.TracebackException.from_exception(e.__context__))
1235 def _makeCamera(self, policy, repositoryDir):
1236 """Make a camera (instance of lsst.afw.cameraGeom.Camera) describing
1239 Also set self.cameraDataLocation, if relevant (else it can be left
1242 This implementation assumes that policy contains an entry "camera"
1243 that points to the subdirectory in this package of camera data;
1244 specifically, that subdirectory must contain:
1245 - a file named `camera.py` that contains persisted camera config
1246 - ampInfo table FITS files, as required by
1247 lsst.afw.cameraGeom.makeCameraFromPath
1251 policy : `lsst.daf.persistence.Policy`
1252 Policy with per-camera defaults already merged
1253 (PexPolicy only for backward compatibility).
1254 repositoryDir : `str`
1255 Policy repository for the subclassing module (obtained with
1256 getRepositoryPath() on the per-camera default dictionary).
1258 if 'camera' not in policy:
1259 raise RuntimeError(
"Cannot find 'camera' in policy; cannot construct a camera")
1260 cameraDataSubdir = policy[
'camera']
1262 os.path.join(repositoryDir, cameraDataSubdir,
"camera.py"))
1263 cameraConfig = afwCameraGeom.CameraConfig()
1266 return afwCameraGeom.makeCameraFromPath(
1267 cameraConfig=cameraConfig,
1268 ampInfoPath=ampInfoPath,
1274 """Get the registry used by this mapper.
1279 The registry used by this mapper for this mapper's repository.
1284 """Stuff image compression settings into a daf.base.PropertySet
1286 This goes into the ButlerLocation's "additionalData", which gets
1287 passed into the boost::persistence framework.
1292 Type of dataset for which to get the image compression settings.
1298 additionalData : `lsst.daf.base.PropertySet`
1299 Image compression settings.
1301 mapping = self.
mappings[datasetType]
1302 recipeName = mapping.recipe
1303 storageType = mapping.storage
1305 return dafBase.PropertySet()
1307 raise RuntimeError(
"Unrecognized write recipe for datasetType %s (storage type %s): %s" %
1308 (datasetType, storageType, recipeName))
1309 recipe = self.
_writeRecipes[storageType][recipeName].deepCopy()
1310 seed = hash(tuple(dataId.items())) % 2**31
1311 for plane
in (
"image",
"mask",
"variance"):
1312 if recipe.exists(plane +
".scaling.seed")
and recipe.getScalar(plane +
".scaling.seed") == 0:
1313 recipe.set(plane +
".scaling.seed", seed)
1316 def _initWriteRecipes(self):
1317 """Read the recipes for writing files
1319 These recipes are currently used for configuring FITS compression,
1320 but they could have wider uses for configuring different flavors
1321 of the storage types. A recipe is referred to by a symbolic name,
1322 which has associated settings. These settings are stored as a
1323 `PropertySet` so they can easily be passed down to the
1324 boost::persistence framework as the "additionalData" parameter.
1326 The list of recipes is written in YAML. A default recipe and
1327 some other convenient recipes are in obs_base/policy/writeRecipes.yaml
1328 and these may be overridden or supplemented by the individual obs_*
1329 packages' own policy/writeRecipes.yaml files.
1331 Recipes are grouped by the storage type. Currently, only the
1332 ``FitsStorage`` storage type uses recipes, which uses it to
1333 configure FITS image compression.
1335 Each ``FitsStorage`` recipe for FITS compression should define
1336 "image", "mask" and "variance" entries, each of which may contain
1337 "compression" and "scaling" entries. Defaults will be provided for
1338 any missing elements under "compression" and "scaling".
1340 The allowed entries under "compression" are:
1342 * algorithm (string): compression algorithm to use
1343 * rows (int): number of rows per tile (0 = entire dimension)
1344 * columns (int): number of columns per tile (0 = entire dimension)
1345 * quantizeLevel (float): cfitsio quantization level
1347 The allowed entries under "scaling" are:
1349 * algorithm (string): scaling algorithm to use
1350 * bitpix (int): bits per pixel (0,8,16,32,64,-32,-64)
1351 * fuzz (bool): fuzz the values when quantising floating-point values?
1352 * seed (long): seed for random number generator when fuzzing
1353 * maskPlanes (list of string): mask planes to ignore when doing
1355 * quantizeLevel: divisor of the standard deviation for STDEV_* scaling
1356 * quantizePad: number of stdev to allow on the low side (for
1357 STDEV_POSITIVE/NEGATIVE)
1358 * bscale: manually specified BSCALE (for MANUAL scaling)
1359 * bzero: manually specified BSCALE (for MANUAL scaling)
1361 A very simple example YAML recipe:
1367 algorithm: GZIP_SHUFFLE
1371 recipesFile = os.path.join(
getPackageDir(
"obs_base"),
"policy",
"writeRecipes.yaml")
1372 recipes = dafPersist.Policy(recipesFile)
1373 supplementsFile = os.path.join(self.
getPackageDir(),
"policy",
"writeRecipes.yaml")
1374 validationMenu = {
'FitsStorage': validateRecipeFitsStorage, }
1375 if os.path.exists(supplementsFile)
and supplementsFile != recipesFile:
1376 supplements = dafPersist.Policy(supplementsFile)
1378 for entry
in validationMenu:
1379 intersection = set(recipes[entry].names()).intersection(set(supplements.names()))
1381 raise RuntimeError(
"Recipes provided in %s section %s may not override those in %s: %s" %
1382 (supplementsFile, entry, recipesFile, intersection))
1383 recipes.update(supplements)
1386 for storageType
in recipes.names(
True):
1387 if "default" not in recipes[storageType]:
1388 raise RuntimeError(
"No 'default' recipe defined for storage type %s in %s" %
1389 (storageType, recipesFile))
1390 self.
_writeRecipes[storageType] = validationMenu[storageType](recipes[storageType])
1394 """Generate an Exposure from an image-like object
1396 If the image is a DecoratedImage then also set its WCS and metadata
1397 (Image and MaskedImage are missing the necessary metadata
1398 and Exposure already has those set)
1402 image : Image-like object
1403 Can be one of lsst.afw.image.DecoratedImage, Image, MaskedImage or
1408 `lsst.afw.image.Exposure`
1409 Exposure containing input image.
1411 translatorClass =
None
1412 if mapper
is not None:
1413 translatorClass = mapper.translatorClass
1416 if isinstance(image, afwImage.MaskedImage):
1417 exposure = afwImage.makeExposure(image)
1418 elif isinstance(image, afwImage.DecoratedImage):
1419 exposure = afwImage.makeExposure(afwImage.makeMaskedImage(image.getImage()))
1420 metadata = image.getMetadata()
1421 fix_header(metadata, translator_class=translatorClass)
1422 exposure.setMetadata(metadata)
1423 elif isinstance(image, afwImage.Exposure):
1425 metadata = exposure.getMetadata()
1426 fix_header(metadata, translator_class=translatorClass)
1428 exposure = afwImage.makeExposure(afwImage.makeMaskedImage(image))
1431 if setVisitInfo
and exposure.getInfo().getVisitInfo()
is None:
1432 if metadata
is not None:
1435 logger = lsstLog.Log.getLogger(
"CameraMapper")
1436 logger.warn(
"I can only set the VisitInfo if you provide a mapper")
1438 exposureId = mapper._computeCcdExposureId(dataId)
1439 visitInfo = mapper.makeRawVisitInfo(md=metadata, exposureId=exposureId)
1441 exposure.getInfo().setVisitInfo(visitInfo)
1447 """Validate recipes for FitsStorage
1449 The recipes are supplemented with default values where appropriate.
1451 TODO: replace this custom validation code with Cerberus (DM-11846)
1455 recipes : `lsst.daf.persistence.Policy`
1456 FitsStorage recipes to validate.
1460 validated : `lsst.daf.base.PropertySet`
1461 Validated FitsStorage recipe.
1466 If validation fails.
1470 compressionSchema = {
1471 "algorithm":
"NONE",
1474 "quantizeLevel": 0.0,
1477 "algorithm":
"NONE",
1479 "maskPlanes": [
"NO_DATA"],
1481 "quantizeLevel": 4.0,
1488 def checkUnrecognized(entry, allowed, description):
1489 """Check to see if the entry contains unrecognised keywords"""
1490 unrecognized = set(entry.keys()) - set(allowed)
1493 "Unrecognized entries when parsing image compression recipe %s: %s" %
1494 (description, unrecognized))
1497 for name
in recipes.names(
True):
1498 checkUnrecognized(recipes[name], [
"image",
"mask",
"variance"], name)
1499 rr = dafBase.PropertySet()
1500 validated[name] = rr
1501 for plane
in (
"image",
"mask",
"variance"):
1502 checkUnrecognized(recipes[name][plane], [
"compression",
"scaling"],
1503 name +
"->" + plane)
1505 for settings, schema
in ((
"compression", compressionSchema),
1506 (
"scaling", scalingSchema)):
1507 prefix = plane +
"." + settings
1508 if settings
not in recipes[name][plane]:
1510 rr.set(prefix +
"." + key, schema[key])
1512 entry = recipes[name][plane][settings]
1513 checkUnrecognized(entry, schema.keys(), name +
"->" + plane +
"->" + settings)
1515 value = type(schema[key])(entry[key])
if key
in entry
else schema[key]
1516 rr.set(prefix +
"." + key, value)