28 from astro_metadata_translator
import fix_header
31 from .
import ImageMapping, ExposureMapping, CalibrationMapping, DatasetMapping
40 from .exposureIdInfo
import ExposureIdInfo
41 from .makeRawVisitInfo
import MakeRawVisitInfo
42 from .utils
import createInitialSkyWcs, InitialSkyWcsError
44 from ._instrument
import Instrument
46 __all__ = [
"CameraMapper",
"exposureFromImage"]
51 """CameraMapper is a base class for mappers that handle images from a
52 camera and products derived from them. This provides an abstraction layer
53 between the data on disk and the code.
55 Public methods: keys, queryMetadata, getDatasetTypes, map,
56 canStandardize, standardize
58 Mappers for specific data sources (e.g., CFHT Megacam, LSST
59 simulations, etc.) should inherit this class.
61 The CameraMapper manages datasets within a "root" directory. Note that
62 writing to a dataset present in the input root will hide the existing
63 dataset but not overwrite it. See #2160 for design discussion.
65 A camera is assumed to consist of one or more rafts, each composed of
66 multiple CCDs. Each CCD is in turn composed of one or more amplifiers
67 (amps). A camera is also assumed to have a camera geometry description
68 (CameraGeom object) as a policy file, a filter description (Filter class
69 static configuration) as another policy file.
71 Information from the camera geometry and defects are inserted into all
72 Exposure objects returned.
74 The mapper uses one or two registries to retrieve metadata about the
75 images. The first is a registry of all raw exposures. This must contain
76 the time of the observation. One or more tables (or the equivalent)
77 within the registry are used to look up data identifier components that
78 are not specified by the user (e.g. filter) and to return results for
79 metadata queries. The second is an optional registry of all calibration
80 data. This should contain validity start and end entries for each
81 calibration dataset in the same timescale as the observation time.
83 Subclasses will typically set MakeRawVisitInfoClass and optionally the
84 metadata translator class:
86 MakeRawVisitInfoClass: a class variable that points to a subclass of
87 MakeRawVisitInfo, a functor that creates an
88 lsst.afw.image.VisitInfo from the FITS metadata of a raw image.
90 translatorClass: The `~astro_metadata_translator.MetadataTranslator`
91 class to use for fixing metadata values. If it is not set an attempt
92 will be made to infer the class from ``MakeRawVisitInfoClass``, failing
93 that the metadata fixup will try to infer the translator class from the
96 Subclasses must provide the following methods:
98 _extractDetectorName(self, dataId): returns the detector name for a CCD
99 (e.g., "CFHT 21", "R:1,2 S:3,4") as used in the AFW CameraGeom class given
100 a dataset identifier referring to that CCD or a subcomponent of it.
102 _computeCcdExposureId(self, dataId): see below
104 _computeCoaddExposureId(self, dataId, singleFilter): see below
106 Subclasses may also need to override the following methods:
108 _transformId(self, dataId): transformation of a data identifier
109 from colloquial usage (e.g., "ccdname") to proper/actual usage
110 (e.g., "ccd"), including making suitable for path expansion (e.g. removing
111 commas). The default implementation does nothing. Note that this
112 method should not modify its input parameter.
114 getShortCcdName(self, ccdName): a static method that returns a shortened
115 name suitable for use as a filename. The default version converts spaces
118 _mapActualToPath(self, template, actualId): convert a template path to an
119 actual path, using the actual dataset identifier.
121 The mapper's behaviors are largely specified by the policy file.
122 See the MapperDictionary.paf for descriptions of the available items.
124 The 'exposures', 'calibrations', and 'datasets' subpolicies configure
125 mappings (see Mappings class).
127 Common default mappings for all subclasses can be specified in the
128 "policy/{images,exposures,calibrations,datasets}.yaml" files. This
129 provides a simple way to add a product to all camera mappers.
131 Functions to map (provide a path to the data given a dataset
132 identifier dictionary) and standardize (convert data into some standard
133 format or type) may be provided in the subclass as "map_{dataset type}"
134 and "std_{dataset type}", respectively.
136 If non-Exposure datasets cannot be retrieved using standard
137 daf_persistence methods alone, a "bypass_{dataset type}" function may be
138 provided in the subclass to return the dataset instead of using the
139 "datasets" subpolicy.
141 Implementations of map_camera and bypass_camera that should typically be
142 sufficient are provided in this base class.
148 Instead of auto-loading the camera at construction time, load it from
149 the calibration registry
153 policy : daf_persistence.Policy,
154 Policy with per-camera defaults already merged.
155 repositoryDir : string
156 Policy repository for the subclassing module (obtained with
157 getRepositoryPath() on the per-camera default dictionary).
158 root : string, optional
159 Path to the root directory for data.
160 registry : string, optional
161 Path to registry with data's metadata.
162 calibRoot : string, optional
163 Root directory for calibrations.
164 calibRegistry : string, optional
165 Path to registry with calibrations' metadata.
166 provided : list of string, optional
167 Keys provided by the mapper.
168 parentRegistry : Registry subclass, optional
169 Registry from a parent repository that may be used to look up
171 repositoryCfg : daf_persistence.RepositoryCfg or None, optional
172 The configuration information for the repository this mapper is
179 MakeRawVisitInfoClass = MakeRawVisitInfo
182 PupilFactoryClass = afwCameraGeom.PupilFactory
185 translatorClass =
None
189 _gen3instrument =
None
192 root=None, registry=None, calibRoot=None, calibRegistry=None,
193 provided=None, parentRegistry=None, repositoryCfg=None):
195 dafPersist.Mapper.__init__(self)
197 self.
log = lsstLog.Log.getLogger(
"CameraMapper")
202 self.
root = repositoryCfg.root
206 repoPolicy = repositoryCfg.policy
if repositoryCfg
else None
207 if repoPolicy
is not None:
208 policy.update(repoPolicy)
212 if 'levels' in policy:
213 levelsPolicy = policy[
'levels']
214 for key
in levelsPolicy.names(
True):
218 if 'defaultSubLevels' in policy:
226 self.
rootStorage = dafPersist.Storage.makeFromURI(uri=root)
234 if calibRoot
is not None:
235 calibRoot = dafPersist.Storage.absolutePath(root, calibRoot)
236 calibStorage = dafPersist.Storage.makeFromURI(uri=calibRoot,
239 calibRoot = policy.get(
'calibRoot',
None)
241 calibStorage = dafPersist.Storage.makeFromURI(uri=calibRoot,
243 if calibStorage
is None:
251 posixIfNoSql=(
not parentRegistry))
254 needCalibRegistry = policy.get(
'needCalibRegistry',
None)
255 if needCalibRegistry:
258 "calibRegistryPath", calibStorage,
262 "'needCalibRegistry' is true in Policy, but was unable to locate a repo at "
263 f
"calibRoot ivar:{calibRoot} or policy['calibRoot']:{policy.get('calibRoot', None)}")
283 raise ValueError(
'class variable packageName must not be None')
293 def _initMappings(self, policy, rootStorage=None, calibStorage=None, provided=None):
294 """Initialize mappings
296 For each of the dataset types that we want to be able to read, there
297 are methods that can be created to support them:
298 * map_<dataset> : determine the path for dataset
299 * std_<dataset> : standardize the retrieved dataset
300 * bypass_<dataset> : retrieve the dataset (bypassing the usual
302 * query_<dataset> : query the registry
304 Besides the dataset types explicitly listed in the policy, we create
305 additional, derived datasets for additional conveniences,
306 e.g., reading the header of an image, retrieving only the size of a
311 policy : `lsst.daf.persistence.Policy`
312 Policy with per-camera defaults already merged
313 rootStorage : `Storage subclass instance`
314 Interface to persisted repository data.
315 calibRoot : `Storage subclass instance`
316 Interface to persisted calib repository data
317 provided : `list` of `str`
318 Keys provided by the mapper
322 "obs_base",
"ImageMappingDefaults.yaml",
"policy"))
324 "obs_base",
"ExposureMappingDefaults.yaml",
"policy"))
326 "obs_base",
"CalibrationMappingDefaults.yaml",
"policy"))
331 (
"images", imgMappingPolicy, ImageMapping),
332 (
"exposures", expMappingPolicy, ExposureMapping),
333 (
"calibrations", calMappingPolicy, CalibrationMapping),
334 (
"datasets", dsMappingPolicy, DatasetMapping)
337 for name, defPolicy, cls
in mappingList:
339 datasets = policy[name]
342 defaultsPath = os.path.join(
getPackageDir(
"obs_base"),
"policy", name +
".yaml")
343 if os.path.exists(defaultsPath):
347 setattr(self, name, mappings)
348 for datasetType
in datasets.names(
True):
349 subPolicy = datasets[datasetType]
350 subPolicy.merge(defPolicy)
352 if not hasattr(self,
"map_" + datasetType)
and 'composite' in subPolicy:
353 def compositeClosure(dataId, write=False, mapper=None, mapping=None,
354 subPolicy=subPolicy):
355 components = subPolicy.get(
'composite')
356 assembler = subPolicy[
'assembler']
if 'assembler' in subPolicy
else None
357 disassembler = subPolicy[
'disassembler']
if 'disassembler' in subPolicy
else None
358 python = subPolicy[
'python']
360 disassembler=disassembler,
364 for name, component
in components.items():
365 butlerComposite.add(id=name,
366 datasetType=component.get(
'datasetType'),
367 setter=component.get(
'setter',
None),
368 getter=component.get(
'getter',
None),
369 subset=component.get(
'subset',
False),
370 inputOnly=component.get(
'inputOnly',
False))
371 return butlerComposite
372 setattr(self,
"map_" + datasetType, compositeClosure)
377 if name ==
"calibrations":
379 provided=provided, dataRoot=rootStorage)
381 mapping =
cls(datasetType, subPolicy, self.
registry, rootStorage, provided=provided)
384 raise ValueError(f
"Duplicate mapping policy for dataset type {datasetType}")
385 self.
keyDict.update(mapping.keys())
386 mappings[datasetType] = mapping
387 self.
mappings[datasetType] = mapping
388 if not hasattr(self,
"map_" + datasetType):
389 def mapClosure(dataId, write=False, mapper=weakref.proxy(self), mapping=mapping):
390 return mapping.map(mapper, dataId, write)
391 setattr(self,
"map_" + datasetType, mapClosure)
392 if not hasattr(self,
"query_" + datasetType):
393 def queryClosure(format, dataId, mapping=mapping):
394 return mapping.lookup(format, dataId)
395 setattr(self,
"query_" + datasetType, queryClosure)
396 if hasattr(mapping,
"standardize")
and not hasattr(self,
"std_" + datasetType):
397 def stdClosure(item, dataId, mapper=weakref.proxy(self), mapping=mapping):
398 return mapping.standardize(mapper, item, dataId)
399 setattr(self,
"std_" + datasetType, stdClosure)
401 def setMethods(suffix, mapImpl=None, bypassImpl=None, queryImpl=None):
402 """Set convenience methods on CameraMapper"""
403 mapName =
"map_" + datasetType +
"_" + suffix
404 bypassName =
"bypass_" + datasetType +
"_" + suffix
405 queryName =
"query_" + datasetType +
"_" + suffix
406 if not hasattr(self, mapName):
407 setattr(self, mapName, mapImpl
or getattr(self,
"map_" + datasetType))
408 if not hasattr(self, bypassName):
409 if bypassImpl
is None and hasattr(self,
"bypass_" + datasetType):
410 bypassImpl = getattr(self,
"bypass_" + datasetType)
411 if bypassImpl
is not None:
412 setattr(self, bypassName, bypassImpl)
413 if not hasattr(self, queryName):
414 setattr(self, queryName, queryImpl
or getattr(self,
"query_" + datasetType))
417 setMethods(
"filename", bypassImpl=
lambda datasetType, pythonType, location, dataId:
418 [os.path.join(location.getStorage().root, p)
for p
in location.getLocations()])
420 if subPolicy[
"storage"] ==
"FitsStorage":
421 def getMetadata(datasetType, pythonType, location, dataId):
426 setMethods(
"md", bypassImpl=getMetadata)
429 addName =
"add_" + datasetType
430 if not hasattr(self, addName):
433 if name ==
"exposures":
434 def getSkyWcs(datasetType, pythonType, location, dataId):
436 return fitsReader.readWcs()
438 setMethods(
"wcs", bypassImpl=getSkyWcs)
440 def getRawHeaderWcs(datasetType, pythonType, location, dataId):
441 """Create a SkyWcs from the un-modified raw
442 FITS WCS header keys."""
443 if datasetType[:3] !=
"raw":
448 setMethods(
"header_wcs", bypassImpl=getRawHeaderWcs)
450 def getPhotoCalib(datasetType, pythonType, location, dataId):
452 return fitsReader.readPhotoCalib()
454 setMethods(
"photoCalib", bypassImpl=getPhotoCalib)
456 def getVisitInfo(datasetType, pythonType, location, dataId):
458 return fitsReader.readVisitInfo()
460 setMethods(
"visitInfo", bypassImpl=getVisitInfo)
462 def getFilter(datasetType, pythonType, location, dataId):
464 return fitsReader.readFilter()
466 setMethods(
"filter", bypassImpl=getFilter)
468 setMethods(
"detector",
469 mapImpl=
lambda dataId, write=
False:
471 pythonType=
"lsst.afw.cameraGeom.CameraConfig",
473 storageName=
"Internal",
474 locationList=
"ignored",
479 bypassImpl=
lambda datasetType, pythonType, location, dataId:
483 def getBBox(datasetType, pythonType, location, dataId):
484 md =
readMetadata(location.getLocationsWithRoot()[0], hdu=1)
488 setMethods(
"bbox", bypassImpl=getBBox)
490 elif name ==
"images":
491 def getBBox(datasetType, pythonType, location, dataId):
495 setMethods(
"bbox", bypassImpl=getBBox)
497 if subPolicy[
"storage"] ==
"FitsCatalogStorage":
499 def getMetadata(datasetType, pythonType, location, dataId):
500 md =
readMetadata(os.path.join(location.getStorage().root,
501 location.getLocations()[0]), hdu=1)
505 setMethods(
"md", bypassImpl=getMetadata)
508 if subPolicy[
"storage"] ==
"FitsStorage":
509 def mapSubClosure(dataId, write=False, mapper=weakref.proxy(self), mapping=mapping):
510 subId = dataId.copy()
512 loc = mapping.map(mapper, subId, write)
513 bbox = dataId[
'bbox']
514 llcX = bbox.getMinX()
515 llcY = bbox.getMinY()
516 width = bbox.getWidth()
517 height = bbox.getHeight()
518 loc.additionalData.set(
'llcX', llcX)
519 loc.additionalData.set(
'llcY', llcY)
520 loc.additionalData.set(
'width', width)
521 loc.additionalData.set(
'height', height)
522 if 'imageOrigin' in dataId:
523 loc.additionalData.set(
'imageOrigin',
524 dataId[
'imageOrigin'])
527 def querySubClosure(key, format, dataId, mapping=mapping):
528 subId = dataId.copy()
530 return mapping.lookup(format, subId)
531 setMethods(
"sub", mapImpl=mapSubClosure, queryImpl=querySubClosure)
533 if subPolicy[
"storage"] ==
"FitsCatalogStorage":
536 def getLen(datasetType, pythonType, location, dataId):
537 md =
readMetadata(os.path.join(location.getStorage().root,
538 location.getLocations()[0]), hdu=1)
542 setMethods(
"len", bypassImpl=getLen)
545 if not datasetType.endswith(
"_schema")
and datasetType +
"_schema" not in datasets:
546 setMethods(
"schema", bypassImpl=
lambda datasetType, pythonType, location, dataId:
547 afwTable.Schema.readFits(os.path.join(location.getStorage().root,
548 location.getLocations()[0])))
550 def _computeCcdExposureId(self, dataId):
551 """Compute the 64-bit (long) identifier for a CCD exposure.
553 Subclasses must override
558 Data identifier with visit, ccd.
560 raise NotImplementedError()
562 def _computeCoaddExposureId(self, dataId, singleFilter):
563 """Compute the 64-bit (long) identifier for a coadd.
565 Subclasses must override
570 Data identifier with tract and patch.
571 singleFilter : `bool`
572 True means the desired ID is for a single-filter coadd, in which
573 case dataIdmust contain filter.
575 raise NotImplementedError()
577 def _search(self, path):
578 """Search for path in the associated repository's storage.
583 Path that describes an object in the repository associated with
585 Path may contain an HDU indicator, e.g. 'foo.fits[1]'. The
586 indicator will be stripped when searching and so will match
587 filenames without the HDU indicator, e.g. 'foo.fits'. The path
588 returned WILL contain the indicator though, e.g. ['foo.fits[1]'].
593 The path for this object in the repository. Will return None if the
594 object can't be found. If the input argument path contained an HDU
595 indicator, the returned path will also contain the HDU indicator.
600 """Rename any existing object with the given type and dataId.
602 The CameraMapper implementation saves objects in a sequence of e.g.:
608 All of the backups will be placed in the output repo, however, and will
609 not be removed if they are found elsewhere in the _parent chain. This
610 means that the same file will be stored twice if the previous version
611 was found in an input repo.
620 def firstElement(list):
621 """Get the first element in the list, or None if that can't be
624 return list[0]
if list
is not None and len(list)
else None
627 newLocation = self.
map(datasetType, dataId, write=
True)
628 newPath = newLocation.getLocations()[0]
629 path = dafPersist.PosixStorage.search(self.
root, newPath, searchParents=
True)
630 path = firstElement(path)
632 while path
is not None:
634 oldPaths.append((n, path))
635 path = dafPersist.PosixStorage.search(self.
root,
"%s~%d" % (newPath, n), searchParents=
True)
636 path = firstElement(path)
637 for n, oldPath
in reversed(oldPaths):
638 self.
rootStorage.copyFile(oldPath,
"%s~%d" % (newPath, n))
641 """Return supported keys.
646 List of keys usable in a dataset identifier
651 """Return a dict of supported keys and their value types for a given
652 dataset type at a given level of the key hierarchy.
657 Dataset type or None for all dataset types.
658 level : `str` or None
659 Level or None for all levels or '' for the default level for the
665 Keys are strings usable in a dataset identifier, values are their
674 if datasetType
is None:
675 keyDict = copy.copy(self.
keyDict)
678 if level
is not None and level
in self.
levels:
679 keyDict = copy.copy(keyDict)
680 for lev
in self.
levels[level]:
695 """Return the name of the camera that this CameraMapper is for."""
697 className = className[className.find(
'.'):-1]
698 m = re.search(
r'(\w+)Mapper', className)
700 m = re.search(
r"class '[\w.]*?(\w+)'", className)
702 return name[:1].lower() + name[1:]
if name
else ''
706 """Return the name of the package containing this CameraMapper."""
708 raise ValueError(
'class variable packageName must not be None')
713 """Return the gen3 Instrument class equivalent for this gen2 Mapper.
718 A `~lsst.obs.base.Instrument` class.
721 raise NotImplementedError(
"Please provide a specific implementation for your instrument"
722 " to enable conversion of this gen2 repository to gen3")
727 raise ValueError(f
"Mapper {cls} has declared a gen3 instrument class of {cls._gen3instrument}"
728 " but that is not an lsst.obs.base.Instrument")
733 """Return the base directory of this package"""
737 """Map a camera dataset."""
739 raise RuntimeError(
"No camera dataset available.")
742 pythonType=
"lsst.afw.cameraGeom.CameraConfig",
744 storageName=
"ConfigStorage",
752 """Return the (preloaded) camera object.
755 raise RuntimeError(
"No camera dataset available.")
760 pythonType=
"lsst.obs.base.ExposureIdInfo",
762 storageName=
"Internal",
763 locationList=
"ignored",
770 """Hook to retrieve an lsst.obs.base.ExposureIdInfo for an exposure"""
771 expId = self.bypass_ccdExposureId(datasetType, pythonType, location, dataId)
772 expBits = self.bypass_ccdExposureId_bits(datasetType, pythonType, location, dataId)
776 """Disable standardization for bfKernel
778 bfKernel is a calibration product that is numpy array,
779 unlike other calibration products that are all images;
780 all calibration images are sent through _standardizeExposure
781 due to CalibrationMapping, but we don't want that to happen to bfKernel
786 """Standardize a raw dataset by converting it to an Exposure instead
789 trimmed=
False, setVisitInfo=
True)
792 """Map a sky policy."""
794 "Internal",
None,
None, self,
798 """Standardize a sky policy by returning the one we use."""
799 return self.skypolicy
807 def _setupRegistry(self, name, description, path, policy, policyKey, storage, searchParents=True,
809 """Set up a registry (usually SQLite3), trying a number of possible
817 Description of registry (for log messages)
821 Policy that contains the registry name, used if path is None.
823 Key in policy for registry path.
824 storage : Storage subclass
825 Repository Storage to look in.
826 searchParents : bool, optional
827 True if the search for a registry should follow any Butler v1
829 posixIfNoSql : bool, optional
830 If an sqlite registry is not found, will create a posix registry if
835 lsst.daf.persistence.Registry
838 if path
is None and policyKey
in policy:
840 if os.path.isabs(path):
841 raise RuntimeError(
"Policy should not indicate an absolute path for registry.")
842 if not storage.exists(path):
843 newPath = storage.instanceSearch(path)
845 newPath = newPath[0]
if newPath
is not None and len(newPath)
else None
847 self.
log.
warn(
"Unable to locate registry at policy path (also looked in root): %s",
851 self.
log.
warn(
"Unable to locate registry at policy path: %s", path)
860 if path
and (path.startswith(root)):
861 path = path[len(root +
'/'):]
862 except AttributeError:
869 def search(filename, description):
870 """Search for file in storage
875 Filename to search for
877 Description of file, for error message.
881 path : `str` or `None`
882 Path to file, or None
884 result = storage.instanceSearch(filename)
887 self.
log.
debug(
"Unable to locate %s: %s", description, filename)
892 path = search(
"%s.pgsql" % name,
"%s in root" % description)
894 path = search(
"%s.sqlite3" % name,
"%s in root" % description)
896 path = search(os.path.join(
".",
"%s.sqlite3" % name),
"%s in current dir" % description)
899 if not storage.exists(path):
900 newPath = storage.instanceSearch(path)
901 newPath = newPath[0]
if newPath
is not None and len(newPath)
else None
902 if newPath
is not None:
904 localFileObj = storage.getLocalFile(path)
905 self.
log.
info(
"Loading %s registry from %s", description, localFileObj.name)
906 registry = dafPersist.Registry.create(localFileObj.name)
908 elif not registry
and posixIfNoSql:
910 self.
log.
info(
"Loading Posix %s registry from %s", description, storage.root)
917 def _transformId(self, dataId):
918 """Generate a standard ID dict from a camera-specific ID dict.
920 Canonical keys include:
921 - amp: amplifier name
922 - ccd: CCD name (in LSST this is a combination of raft and sensor)
923 The default implementation returns a copy of its input.
928 Dataset identifier; this must not be modified
933 Transformed dataset identifier.
938 def _mapActualToPath(self, template, actualId):
939 """Convert a template path to an actual path, using the actual data
940 identifier. This implementation is usually sufficient but can be
941 overridden by the subclass.
958 return template % transformedId
959 except Exception
as e:
960 raise RuntimeError(
"Failed to format %r with data %r: %s" % (template, transformedId, e))
964 """Convert a CCD name to a form useful as a filename
966 The default implementation converts spaces to underscores.
968 return ccdName.replace(
" ",
"_")
970 def _extractDetectorName(self, dataId):
971 """Extract the detector (CCD) name from the dataset identifier.
973 The name in question is the detector name used by lsst.afw.cameraGeom.
985 raise NotImplementedError(
"No _extractDetectorName() function specified")
987 def _setAmpDetector(self, item, dataId, trimmed=True):
988 """Set the detector object in an Exposure for an amplifier.
990 Defects are also added to the Exposure based on the detector object.
994 item : `lsst.afw.image.Exposure`
995 Exposure to set the detector in.
999 Should detector be marked as trimmed? (ignored)
1002 return self.
_setCcdDetector(item=item, dataId=dataId, trimmed=trimmed)
1004 def _setCcdDetector(self, item, dataId, trimmed=True):
1005 """Set the detector object in an Exposure for a CCD.
1009 item : `lsst.afw.image.Exposure`
1010 Exposure to set the detector in.
1014 Should detector be marked as trimmed? (ignored)
1016 if item.getDetector()
is not None:
1020 detector = self.
camera[detectorName]
1021 item.setDetector(detector)
1023 def _setFilter(self, mapping, item, dataId):
1024 """Set the filter object in an Exposure. If the Exposure had a FILTER
1025 keyword, this was already processed during load. But if it didn't,
1026 use the filter from the registry.
1030 mapping : `lsst.obs.base.Mapping`
1031 Where to get the filter from.
1032 item : `lsst.afw.image.Exposure`
1033 Exposure to set the filter in.
1038 if not (isinstance(item, afwImage.ExposureU)
or isinstance(item, afwImage.ExposureI)
1039 or isinstance(item, afwImage.ExposureF)
or isinstance(item, afwImage.ExposureD)):
1042 if item.getFilter().getId() != afwImage.Filter.UNKNOWN:
1045 actualId = mapping.need([
'filter'], dataId)
1046 filterName = actualId[
'filter']
1048 filterName = self.
filters[filterName]
1052 self.
log.
warn(
"Filter %s not defined. Set to UNKNOWN." % (filterName))
1054 def _standardizeExposure(self, mapping, item, dataId, filter=True,
1055 trimmed=True, setVisitInfo=True):
1056 """Default standardization function for images.
1058 This sets the Detector from the camera geometry
1059 and optionally set the Filter. In both cases this saves
1060 having to persist some data in each exposure (or image).
1064 mapping : `lsst.obs.base.Mapping`
1065 Where to get the values from.
1066 item : image-like object
1067 Can be any of lsst.afw.image.Exposure,
1068 lsst.afw.image.DecoratedImage, lsst.afw.image.Image
1069 or lsst.afw.image.MaskedImage
1074 Set filter? Ignored if item is already an exposure
1076 Should detector be marked as trimmed?
1077 setVisitInfo : `bool`
1078 Should Exposure have its VisitInfo filled out from the metadata?
1082 `lsst.afw.image.Exposure`
1083 The standardized Exposure.
1087 setVisitInfo=setVisitInfo)
1088 except Exception
as e:
1089 self.
log.
error(
"Could not turn item=%r into an exposure: %s" % (repr(item), e))
1092 if mapping.level.lower() ==
"amp":
1094 elif mapping.level.lower() ==
"ccd":
1100 if mapping.level.lower() !=
"amp" and exposure.getWcs()
is None and \
1101 (exposure.getInfo().getVisitInfo()
is not None or exposure.getMetadata().toDict()):
1109 def _createSkyWcsFromMetadata(self, exposure):
1110 """Create a SkyWcs from the FITS header metadata in an Exposure.
1114 exposure : `lsst.afw.image.Exposure`
1115 The exposure to get metadata from, and attach the SkyWcs to.
1117 metadata = exposure.getMetadata()
1121 exposure.setWcs(wcs)
1125 self.
log.
debug(
"wcs set to None; missing information found in metadata to create a valid wcs:"
1129 exposure.setMetadata(metadata)
1131 def _createInitialSkyWcs(self, exposure):
1132 """Create a SkyWcs from the boresight and camera geometry.
1134 If the boresight or camera geometry do not support this method of
1135 WCS creation, this falls back on the header metadata-based version
1136 (typically a purely linear FITS crval/crpix/cdmatrix WCS).
1140 exposure : `lsst.afw.image.Exposure`
1141 The exposure to get data from, and attach the SkyWcs to.
1146 if exposure.getInfo().getVisitInfo()
is None:
1147 msg =
"No VisitInfo; cannot access boresight information. Defaulting to metadata-based SkyWcs."
1151 newSkyWcs =
createInitialSkyWcs(exposure.getInfo().getVisitInfo(), exposure.getDetector())
1152 exposure.setWcs(newSkyWcs)
1153 except InitialSkyWcsError
as e:
1154 msg =
"Cannot create SkyWcs using VisitInfo and Detector, using metadata-based SkyWcs: %s"
1156 self.
log.
debug(
"Exception was: %s", traceback.TracebackException.from_exception(e))
1157 if e.__context__
is not None:
1158 self.
log.
debug(
"Root-cause Exception was: %s",
1159 traceback.TracebackException.from_exception(e.__context__))
1161 def _makeCamera(self, policy, repositoryDir):
1162 """Make a camera (instance of lsst.afw.cameraGeom.Camera) describing
1165 Also set self.cameraDataLocation, if relevant (else it can be left
1168 This implementation assumes that policy contains an entry "camera"
1169 that points to the subdirectory in this package of camera data;
1170 specifically, that subdirectory must contain:
1171 - a file named `camera.py` that contains persisted camera config
1172 - ampInfo table FITS files, as required by
1173 lsst.afw.cameraGeom.makeCameraFromPath
1177 policy : `lsst.daf.persistence.Policy`
1178 Policy with per-camera defaults already merged
1179 (PexPolicy only for backward compatibility).
1180 repositoryDir : `str`
1181 Policy repository for the subclassing module (obtained with
1182 getRepositoryPath() on the per-camera default dictionary).
1184 if 'camera' not in policy:
1185 raise RuntimeError(
"Cannot find 'camera' in policy; cannot construct a camera")
1186 cameraDataSubdir = policy[
'camera']
1188 os.path.join(repositoryDir, cameraDataSubdir,
"camera.py"))
1189 cameraConfig = afwCameraGeom.CameraConfig()
1192 return afwCameraGeom.makeCameraFromPath(
1193 cameraConfig=cameraConfig,
1194 ampInfoPath=ampInfoPath,
1200 """Get the registry used by this mapper.
1205 The registry used by this mapper for this mapper's repository.
1210 """Stuff image compression settings into a daf.base.PropertySet
1212 This goes into the ButlerLocation's "additionalData", which gets
1213 passed into the boost::persistence framework.
1218 Type of dataset for which to get the image compression settings.
1224 additionalData : `lsst.daf.base.PropertySet`
1225 Image compression settings.
1227 mapping = self.
mappings[datasetType]
1228 recipeName = mapping.recipe
1229 storageType = mapping.storage
1233 raise RuntimeError(
"Unrecognized write recipe for datasetType %s (storage type %s): %s" %
1234 (datasetType, storageType, recipeName))
1235 recipe = self.
_writeRecipes[storageType][recipeName].deepCopy()
1236 seed = hash(tuple(dataId.items())) % 2**31
1237 for plane
in (
"image",
"mask",
"variance"):
1238 if recipe.exists(plane +
".scaling.seed")
and recipe.getScalar(plane +
".scaling.seed") == 0:
1239 recipe.set(plane +
".scaling.seed", seed)
1242 def _initWriteRecipes(self):
1243 """Read the recipes for writing files
1245 These recipes are currently used for configuring FITS compression,
1246 but they could have wider uses for configuring different flavors
1247 of the storage types. A recipe is referred to by a symbolic name,
1248 which has associated settings. These settings are stored as a
1249 `PropertySet` so they can easily be passed down to the
1250 boost::persistence framework as the "additionalData" parameter.
1252 The list of recipes is written in YAML. A default recipe and
1253 some other convenient recipes are in obs_base/policy/writeRecipes.yaml
1254 and these may be overridden or supplemented by the individual obs_*
1255 packages' own policy/writeRecipes.yaml files.
1257 Recipes are grouped by the storage type. Currently, only the
1258 ``FitsStorage`` storage type uses recipes, which uses it to
1259 configure FITS image compression.
1261 Each ``FitsStorage`` recipe for FITS compression should define
1262 "image", "mask" and "variance" entries, each of which may contain
1263 "compression" and "scaling" entries. Defaults will be provided for
1264 any missing elements under "compression" and "scaling".
1266 The allowed entries under "compression" are:
1268 * algorithm (string): compression algorithm to use
1269 * rows (int): number of rows per tile (0 = entire dimension)
1270 * columns (int): number of columns per tile (0 = entire dimension)
1271 * quantizeLevel (float): cfitsio quantization level
1273 The allowed entries under "scaling" are:
1275 * algorithm (string): scaling algorithm to use
1276 * bitpix (int): bits per pixel (0,8,16,32,64,-32,-64)
1277 * fuzz (bool): fuzz the values when quantising floating-point values?
1278 * seed (long): seed for random number generator when fuzzing
1279 * maskPlanes (list of string): mask planes to ignore when doing
1281 * quantizeLevel: divisor of the standard deviation for STDEV_* scaling
1282 * quantizePad: number of stdev to allow on the low side (for
1283 STDEV_POSITIVE/NEGATIVE)
1284 * bscale: manually specified BSCALE (for MANUAL scaling)
1285 * bzero: manually specified BSCALE (for MANUAL scaling)
1287 A very simple example YAML recipe:
1293 algorithm: GZIP_SHUFFLE
1297 recipesFile = os.path.join(
getPackageDir(
"obs_base"),
"policy",
"writeRecipes.yaml")
1299 supplementsFile = os.path.join(self.
getPackageDir(),
"policy",
"writeRecipes.yaml")
1300 validationMenu = {
'FitsStorage': validateRecipeFitsStorage, }
1301 if os.path.exists(supplementsFile)
and supplementsFile != recipesFile:
1304 for entry
in validationMenu:
1305 intersection =
set(recipes[entry].names()).intersection(
set(supplements.names()))
1307 raise RuntimeError(
"Recipes provided in %s section %s may not override those in %s: %s" %
1308 (supplementsFile, entry, recipesFile, intersection))
1309 recipes.update(supplements)
1312 for storageType
in recipes.names(
True):
1313 if "default" not in recipes[storageType]:
1314 raise RuntimeError(
"No 'default' recipe defined for storage type %s in %s" %
1315 (storageType, recipesFile))
1316 self.
_writeRecipes[storageType] = validationMenu[storageType](recipes[storageType])
1320 """Generate an Exposure from an image-like object
1322 If the image is a DecoratedImage then also set its WCS and metadata
1323 (Image and MaskedImage are missing the necessary metadata
1324 and Exposure already has those set)
1328 image : Image-like object
1329 Can be one of lsst.afw.image.DecoratedImage, Image, MaskedImage or
1334 `lsst.afw.image.Exposure`
1335 Exposure containing input image.
1337 translatorClass =
None
1338 if mapper
is not None:
1339 translatorClass = mapper.translatorClass
1346 metadata = image.getMetadata()
1347 fix_header(metadata, translator_class=translatorClass)
1348 exposure.setMetadata(metadata)
1351 metadata = exposure.getMetadata()
1352 fix_header(metadata, translator_class=translatorClass)
1357 if setVisitInfo
and exposure.getInfo().getVisitInfo()
is None:
1358 if metadata
is not None:
1361 logger = lsstLog.Log.getLogger(
"CameraMapper")
1362 logger.warn(
"I can only set the VisitInfo if you provide a mapper")
1364 exposureId = mapper._computeCcdExposureId(dataId)
1365 visitInfo = mapper.makeRawVisitInfo(md=metadata, exposureId=exposureId)
1367 exposure.getInfo().setVisitInfo(visitInfo)
1373 """Validate recipes for FitsStorage
1375 The recipes are supplemented with default values where appropriate.
1377 TODO: replace this custom validation code with Cerberus (DM-11846)
1381 recipes : `lsst.daf.persistence.Policy`
1382 FitsStorage recipes to validate.
1386 validated : `lsst.daf.base.PropertySet`
1387 Validated FitsStorage recipe.
1392 If validation fails.
1396 compressionSchema = {
1397 "algorithm":
"NONE",
1400 "quantizeLevel": 0.0,
1403 "algorithm":
"NONE",
1405 "maskPlanes": [
"NO_DATA"],
1407 "quantizeLevel": 4.0,
1414 def checkUnrecognized(entry, allowed, description):
1415 """Check to see if the entry contains unrecognised keywords"""
1416 unrecognized =
set(entry.keys()) -
set(allowed)
1419 "Unrecognized entries when parsing image compression recipe %s: %s" %
1420 (description, unrecognized))
1423 for name
in recipes.names(
True):
1424 checkUnrecognized(recipes[name], [
"image",
"mask",
"variance"], name)
1426 validated[name] = rr
1427 for plane
in (
"image",
"mask",
"variance"):
1428 checkUnrecognized(recipes[name][plane], [
"compression",
"scaling"],
1429 name +
"->" + plane)
1431 for settings, schema
in ((
"compression", compressionSchema),
1432 (
"scaling", scalingSchema)):
1433 prefix = plane +
"." + settings
1434 if settings
not in recipes[name][plane]:
1436 rr.set(prefix +
"." + key, schema[key])
1438 entry = recipes[name][plane][settings]
1439 checkUnrecognized(entry, schema.keys(), name +
"->" + plane +
"->" + settings)
1441 value =
type(schema[key])(entry[key])
if key
in entry
else schema[key]
1442 rr.set(prefix +
"." + key, value)