29 from deprecated.sphinx
import deprecated
31 from astro_metadata_translator
import fix_header
33 from .
import ImageMapping, ExposureMapping, CalibrationMapping, DatasetMapping
42 from .exposureIdInfo
import ExposureIdInfo
43 from .makeRawVisitInfo
import MakeRawVisitInfo
44 from .utils
import createInitialSkyWcs, InitialSkyWcsError
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 188 def __init__(self, policy, repositoryDir,
189 root=None, registry=None, calibRoot=None, calibRegistry=None,
190 provided=None, parentRegistry=None, repositoryCfg=None):
192 dafPersist.Mapper.__init__(self)
194 self.
log = lsstLog.Log.getLogger(
"CameraMapper")
199 self.
root = repositoryCfg.root
203 repoPolicy = repositoryCfg.policy
if repositoryCfg
else None 204 if repoPolicy
is not None:
205 policy.update(repoPolicy)
209 if 'levels' in policy:
210 levelsPolicy = policy[
'levels']
211 for key
in levelsPolicy.names(
True):
212 self.
levels[key] =
set(levelsPolicy.asArray(key))
215 if 'defaultSubLevels' in policy:
231 if calibRoot
is not None:
232 calibRoot = dafPersist.Storage.absolutePath(root, calibRoot)
233 calibStorage = dafPersist.Storage.makeFromURI(uri=calibRoot,
236 calibRoot = policy.get(
'calibRoot',
None)
238 calibStorage = dafPersist.Storage.makeFromURI(uri=calibRoot,
240 if calibStorage
is None:
248 posixIfNoSql=(
not parentRegistry))
251 needCalibRegistry = policy.get(
'needCalibRegistry',
None)
252 if needCalibRegistry:
255 "calibRegistryPath", calibStorage,
259 "'needCalibRegistry' is true in Policy, but was unable to locate a repo at " +
260 "calibRoot ivar:%s or policy['calibRoot']:%s" %
261 (calibRoot, policy.get(
'calibRoot',
None)))
281 raise ValueError(
'class variable packageName must not be None')
291 def _initMappings(self, policy, rootStorage=None, calibStorage=None, provided=None):
292 """Initialize mappings 294 For each of the dataset types that we want to be able to read, there 295 are methods that can be created to support them: 296 * map_<dataset> : determine the path for dataset 297 * std_<dataset> : standardize the retrieved dataset 298 * bypass_<dataset> : retrieve the dataset (bypassing the usual 300 * query_<dataset> : query the registry 302 Besides the dataset types explicitly listed in the policy, we create 303 additional, derived datasets for additional conveniences, 304 e.g., reading the header of an image, retrieving only the size of a 309 policy : `lsst.daf.persistence.Policy` 310 Policy with per-camera defaults already merged 311 rootStorage : `Storage subclass instance` 312 Interface to persisted repository data. 313 calibRoot : `Storage subclass instance` 314 Interface to persisted calib repository data 315 provided : `list` of `str` 316 Keys provided by the mapper 320 "obs_base",
"ImageMappingDefaults.yaml",
"policy"))
322 "obs_base",
"ExposureMappingDefaults.yaml",
"policy"))
324 "obs_base",
"CalibrationMappingDefaults.yaml",
"policy"))
329 (
"images", imgMappingPolicy, ImageMapping),
330 (
"exposures", expMappingPolicy, ExposureMapping),
331 (
"calibrations", calMappingPolicy, CalibrationMapping),
332 (
"datasets", dsMappingPolicy, DatasetMapping)
335 for name, defPolicy, cls
in mappingList:
337 datasets = policy[name]
340 defaultsPath = os.path.join(
getPackageDir(
"obs_base"),
"policy", name +
".yaml")
341 if os.path.exists(defaultsPath):
345 setattr(self, name, mappings)
346 for datasetType
in datasets.names(
True):
347 subPolicy = datasets[datasetType]
348 subPolicy.merge(defPolicy)
350 if not hasattr(self,
"map_" + datasetType)
and 'composite' in subPolicy:
351 def compositeClosure(dataId, write=False, mapper=None, mapping=None,
352 subPolicy=subPolicy):
353 components = subPolicy.get(
'composite')
354 assembler = subPolicy[
'assembler']
if 'assembler' in subPolicy
else None 355 disassembler = subPolicy[
'disassembler']
if 'disassembler' in subPolicy
else None 356 python = subPolicy[
'python']
358 disassembler=disassembler,
362 for name, component
in components.items():
363 butlerComposite.add(id=name,
364 datasetType=component.get(
'datasetType'),
365 setter=component.get(
'setter',
None),
366 getter=component.get(
'getter',
None),
367 subset=component.get(
'subset',
False),
368 inputOnly=component.get(
'inputOnly',
False))
369 return butlerComposite
370 setattr(self,
"map_" + datasetType, compositeClosure)
374 if name ==
"calibrations":
376 provided=provided, dataRoot=rootStorage)
378 mapping =
cls(datasetType, subPolicy, self.
registry, rootStorage, provided=provided)
381 raise ValueError(f
"Duplicate mapping policy for dataset type {datasetType}")
382 self.
keyDict.update(mapping.keys())
383 mappings[datasetType] = mapping
384 self.
mappings[datasetType] = mapping
385 if not hasattr(self,
"map_" + datasetType):
386 def mapClosure(dataId, write=False, mapper=weakref.proxy(self), mapping=mapping):
387 return mapping.map(mapper, dataId, write)
388 setattr(self,
"map_" + datasetType, mapClosure)
389 if not hasattr(self,
"query_" + datasetType):
390 def queryClosure(format, dataId, mapping=mapping):
391 return mapping.lookup(format, dataId)
392 setattr(self,
"query_" + datasetType, queryClosure)
393 if hasattr(mapping,
"standardize")
and not hasattr(self,
"std_" + datasetType):
394 def stdClosure(item, dataId, mapper=weakref.proxy(self), mapping=mapping):
395 return mapping.standardize(mapper, item, dataId)
396 setattr(self,
"std_" + datasetType, stdClosure)
398 def setMethods(suffix, mapImpl=None, bypassImpl=None, queryImpl=None):
399 """Set convenience methods on CameraMapper""" 400 mapName =
"map_" + datasetType +
"_" + suffix
401 bypassName =
"bypass_" + datasetType +
"_" + suffix
402 queryName =
"query_" + datasetType +
"_" + suffix
403 if not hasattr(self, mapName):
404 setattr(self, mapName, mapImpl
or getattr(self,
"map_" + datasetType))
405 if not hasattr(self, bypassName):
406 if bypassImpl
is None and hasattr(self,
"bypass_" + datasetType):
407 bypassImpl = getattr(self,
"bypass_" + datasetType)
408 if bypassImpl
is not None:
409 setattr(self, bypassName, bypassImpl)
410 if not hasattr(self, queryName):
411 setattr(self, queryName, queryImpl
or getattr(self,
"query_" + datasetType))
414 setMethods(
"filename", bypassImpl=
lambda datasetType, pythonType, location, dataId:
415 [os.path.join(location.getStorage().root, p)
for p
in location.getLocations()])
417 if subPolicy[
"storage"] ==
"FitsStorage":
418 def getMetadata(datasetType, pythonType, location, dataId):
423 setMethods(
"md", bypassImpl=getMetadata)
426 addName =
"add_" + datasetType
427 if not hasattr(self, addName):
430 if name ==
"exposures":
431 def getSkyWcs(datasetType, pythonType, location, dataId):
433 return fitsReader.readWcs()
435 setMethods(
"wcs", bypassImpl=getSkyWcs)
437 def getRawHeaderWcs(datasetType, pythonType, location, dataId):
438 """Create a SkyWcs from the un-modified raw FITS WCS header keys.""" 439 if datasetType[:3] !=
"raw":
444 setMethods(
"header_wcs", bypassImpl=getRawHeaderWcs)
446 def getPhotoCalib(datasetType, pythonType, location, dataId):
448 return fitsReader.readPhotoCalib()
450 setMethods(
"photoCalib", bypassImpl=getPhotoCalib)
452 def getVisitInfo(datasetType, pythonType, location, dataId):
454 return fitsReader.readVisitInfo()
456 setMethods(
"visitInfo", bypassImpl=getVisitInfo)
458 def getFilter(datasetType, pythonType, location, dataId):
460 return fitsReader.readFilter()
462 setMethods(
"filter", bypassImpl=getFilter)
464 setMethods(
"detector",
465 mapImpl=
lambda dataId, write=
False:
467 pythonType=
"lsst.afw.cameraGeom.CameraConfig",
469 storageName=
"Internal",
470 locationList=
"ignored",
475 bypassImpl=
lambda datasetType, pythonType, location, dataId:
479 def getBBox(datasetType, pythonType, location, dataId):
480 md =
readMetadata(location.getLocationsWithRoot()[0], hdu=1)
484 setMethods(
"bbox", bypassImpl=getBBox)
486 elif name ==
"images":
487 def getBBox(datasetType, pythonType, location, dataId):
491 setMethods(
"bbox", bypassImpl=getBBox)
493 if subPolicy[
"storage"] ==
"FitsCatalogStorage":
495 def getMetadata(datasetType, pythonType, location, dataId):
496 md =
readMetadata(os.path.join(location.getStorage().root,
497 location.getLocations()[0]), hdu=1)
501 setMethods(
"md", bypassImpl=getMetadata)
504 if subPolicy[
"storage"] ==
"FitsStorage":
505 def mapSubClosure(dataId, write=False, mapper=weakref.proxy(self), mapping=mapping):
506 subId = dataId.copy()
508 loc = mapping.map(mapper, subId, write)
509 bbox = dataId[
'bbox']
510 llcX = bbox.getMinX()
511 llcY = bbox.getMinY()
512 width = bbox.getWidth()
513 height = bbox.getHeight()
514 loc.additionalData.set(
'llcX', llcX)
515 loc.additionalData.set(
'llcY', llcY)
516 loc.additionalData.set(
'width', width)
517 loc.additionalData.set(
'height', height)
518 if 'imageOrigin' in dataId:
519 loc.additionalData.set(
'imageOrigin',
520 dataId[
'imageOrigin'])
523 def querySubClosure(key, format, dataId, mapping=mapping):
524 subId = dataId.copy()
526 return mapping.lookup(format, subId)
527 setMethods(
"sub", mapImpl=mapSubClosure, queryImpl=querySubClosure)
529 if subPolicy[
"storage"] ==
"FitsCatalogStorage":
532 def getLen(datasetType, pythonType, location, dataId):
533 md =
readMetadata(os.path.join(location.getStorage().root,
534 location.getLocations()[0]), hdu=1)
538 setMethods(
"len", bypassImpl=getLen)
541 if not datasetType.endswith(
"_schema")
and datasetType +
"_schema" not in datasets:
542 setMethods(
"schema", bypassImpl=
lambda datasetType, pythonType, location, dataId:
543 afwTable.Schema.readFits(os.path.join(location.getStorage().root,
544 location.getLocations()[0])))
546 def _computeCcdExposureId(self, dataId):
547 """Compute the 64-bit (long) identifier for a CCD exposure. 549 Subclasses must override 554 Data identifier with visit, ccd. 556 raise NotImplementedError()
558 def _computeCoaddExposureId(self, dataId, singleFilter):
559 """Compute the 64-bit (long) identifier for a coadd. 561 Subclasses must override 566 Data identifier with tract and patch. 567 singleFilter : `bool` 568 True means the desired ID is for a single-filter coadd, in which 569 case dataIdmust contain filter. 571 raise NotImplementedError()
573 def _search(self, path):
574 """Search for path in the associated repository's storage. 579 Path that describes an object in the repository associated with 581 Path may contain an HDU indicator, e.g. 'foo.fits[1]'. The 582 indicator will be stripped when searching and so will match 583 filenames without the HDU indicator, e.g. 'foo.fits'. The path 584 returned WILL contain the indicator though, e.g. ['foo.fits[1]']. 589 The path for this object in the repository. Will return None if the 590 object can't be found. If the input argument path contained an HDU 591 indicator, the returned path will also contain the HDU indicator. 596 """Rename any existing object with the given type and dataId. 598 The CameraMapper implementation saves objects in a sequence of e.g.: 604 All of the backups will be placed in the output repo, however, and will 605 not be removed if they are found elsewhere in the _parent chain. This 606 means that the same file will be stored twice if the previous version 607 was found in an input repo. 616 def firstElement(list):
617 """Get the first element in the list, or None if that can't be 620 return list[0]
if list
is not None and len(list)
else None 623 newLocation = self.
map(datasetType, dataId, write=
True)
624 newPath = newLocation.getLocations()[0]
625 path = dafPersist.PosixStorage.search(self.
root, newPath, searchParents=
True)
626 path = firstElement(path)
628 while path
is not None:
630 oldPaths.append((n, path))
631 path = dafPersist.PosixStorage.search(self.
root,
"%s~%d" % (newPath, n), searchParents=
True)
632 path = firstElement(path)
633 for n, oldPath
in reversed(oldPaths):
634 self.
rootStorage.copyFile(oldPath,
"%s~%d" % (newPath, n))
637 """Return supported keys. 642 List of keys usable in a dataset identifier 647 """Return a dict of supported keys and their value types for a given 648 dataset type at a given level of the key hierarchy. 653 Dataset type or None for all dataset types. 654 level : `str` or None 655 Level or None for all levels or '' for the default level for the 661 Keys are strings usable in a dataset identifier, values are their 669 if datasetType
is None:
670 keyDict = copy.copy(self.
keyDict)
673 if level
is not None and level
in self.
levels:
674 keyDict = copy.copy(keyDict)
675 for l
in self.
levels[level]:
690 """Return the name of the camera that this CameraMapper is for.""" 692 className = className[className.find(
'.'):-1]
693 m = re.search(
r'(\w+)Mapper', className)
695 m = re.search(
r"class '[\w.]*?(\w+)'", className)
697 return name[:1].lower() + name[1:]
if name
else '' 701 """Return the name of the package containing this CameraMapper.""" 703 raise ValueError(
'class variable packageName must not be None')
708 """Return the base directory of this package""" 712 """Map a camera dataset.""" 714 raise RuntimeError(
"No camera dataset available.")
717 pythonType=
"lsst.afw.cameraGeom.CameraConfig",
719 storageName=
"ConfigStorage",
727 """Return the (preloaded) camera object. 730 raise RuntimeError(
"No camera dataset available.")
735 pythonType=
"lsst.obs.base.ExposureIdInfo",
737 storageName=
"Internal",
738 locationList=
"ignored",
745 """Hook to retrieve an lsst.obs.base.ExposureIdInfo for an exposure""" 746 expId = self.bypass_ccdExposureId(datasetType, pythonType, location, dataId)
747 expBits = self.bypass_ccdExposureId_bits(datasetType, pythonType, location, dataId)
751 """Disable standardization for bfKernel 753 bfKernel is a calibration product that is numpy array, 754 unlike other calibration products that are all images; 755 all calibration images are sent through _standardizeExposure 756 due to CalibrationMapping, but we don't want that to happen to bfKernel 761 """Standardize a raw dataset by converting it to an Exposure instead 764 trimmed=
False, setVisitInfo=
True)
767 """Map a sky policy.""" 769 "Internal",
None,
None, self,
773 """Standardize a sky policy by returning the one we use.""" 774 return self.skypolicy
782 def _setupRegistry(self, name, description, path, policy, policyKey, storage, searchParents=True,
784 """Set up a registry (usually SQLite3), trying a number of possible 792 Description of registry (for log messages) 796 Policy that contains the registry name, used if path is None. 798 Key in policy for registry path. 799 storage : Storage subclass 800 Repository Storage to look in. 801 searchParents : bool, optional 802 True if the search for a registry should follow any Butler v1 804 posixIfNoSql : bool, optional 805 If an sqlite registry is not found, will create a posix registry if 810 lsst.daf.persistence.Registry 813 if path
is None and policyKey
in policy:
815 if os.path.isabs(path):
816 raise RuntimeError(
"Policy should not indicate an absolute path for registry.")
817 if not storage.exists(path):
818 newPath = storage.instanceSearch(path)
820 newPath = newPath[0]
if newPath
is not None and len(newPath)
else None 822 self.
log.
warn(
"Unable to locate registry at policy path (also looked in root): %s",
826 self.
log.
warn(
"Unable to locate registry at policy path: %s", path)
834 if path
and (path.startswith(root)):
835 path = path[len(root +
'/'):]
836 except AttributeError:
842 def search(filename, description):
843 """Search for file in storage 848 Filename to search for 850 Description of file, for error message. 854 path : `str` or `None` 855 Path to file, or None 857 result = storage.instanceSearch(filename)
860 self.
log.
debug(
"Unable to locate %s: %s", description, filename)
865 path = search(
"%s.pgsql" % name,
"%s in root" % description)
867 path = search(
"%s.sqlite3" % name,
"%s in root" % description)
869 path = search(os.path.join(
".",
"%s.sqlite3" % name),
"%s in current dir" % description)
872 if not storage.exists(path):
873 newPath = storage.instanceSearch(path)
874 newPath = newPath[0]
if newPath
is not None and len(newPath)
else None 875 if newPath
is not None:
877 localFileObj = storage.getLocalFile(path)
878 self.
log.
info(
"Loading %s registry from %s", description, localFileObj.name)
879 registry = dafPersist.Registry.create(localFileObj.name)
881 elif not registry
and posixIfNoSql:
883 self.
log.
info(
"Loading Posix %s registry from %s", description, storage.root)
890 def _transformId(self, dataId):
891 """Generate a standard ID dict from a camera-specific ID dict. 893 Canonical keys include: 894 - amp: amplifier name 895 - ccd: CCD name (in LSST this is a combination of raft and sensor) 896 The default implementation returns a copy of its input. 901 Dataset identifier; this must not be modified 906 Transformed dataset identifier. 911 def _mapActualToPath(self, template, actualId):
912 """Convert a template path to an actual path, using the actual data 913 identifier. This implementation is usually sufficient but can be 914 overridden by the subclass. 931 return template % transformedId
932 except Exception
as e:
933 raise RuntimeError(
"Failed to format %r with data %r: %s" % (template, transformedId, e))
937 """Convert a CCD name to a form useful as a filename 939 The default implementation converts spaces to underscores. 941 return ccdName.replace(
" ",
"_")
943 def _extractDetectorName(self, dataId):
944 """Extract the detector (CCD) name from the dataset identifier. 946 The name in question is the detector name used by lsst.afw.cameraGeom. 958 raise NotImplementedError(
"No _extractDetectorName() function specified")
960 @deprecated(
"This method is no longer used for ISR (will be removed after v11)", category=FutureWarning)
961 def _extractAmpId(self, dataId):
962 """Extract the amplifier identifer from a dataset identifier. 964 .. note:: Deprecated in 11_0 966 amplifier identifier has two parts: the detector name for the CCD 967 containing the amplifier and index of the amplifier in the detector. 981 return (trDataId[
"ccd"], int(trDataId[
'amp']))
983 def _setAmpDetector(self, item, dataId, trimmed=True):
984 """Set the detector object in an Exposure for an amplifier. 986 Defects are also added to the Exposure based on the detector object. 990 item : `lsst.afw.image.Exposure` 991 Exposure to set the detector in. 995 Should detector be marked as trimmed? (ignored) 1000 def _setCcdDetector(self, item, dataId, trimmed=True):
1001 """Set the detector object in an Exposure for a CCD. 1005 item : `lsst.afw.image.Exposure` 1006 Exposure to set the detector in. 1010 Should detector be marked as trimmed? (ignored) 1012 if item.getDetector()
is not None:
1016 detector = self.
camera[detectorName]
1017 item.setDetector(detector)
1019 def _setFilter(self, mapping, item, dataId):
1020 """Set the filter object in an Exposure. If the Exposure had a FILTER 1021 keyword, this was already processed during load. But if it didn't, 1022 use the filter from the registry. 1026 mapping : `lsst.obs.base.Mapping` 1027 Where to get the filter from. 1028 item : `lsst.afw.image.Exposure` 1029 Exposure to set the filter in. 1034 if not (isinstance(item, afwImage.ExposureU)
or isinstance(item, afwImage.ExposureI)
or 1035 isinstance(item, afwImage.ExposureF)
or isinstance(item, afwImage.ExposureD)):
1038 if item.getFilter().getId() != afwImage.Filter.UNKNOWN:
1041 actualId = mapping.need([
'filter'], dataId)
1042 filterName = actualId[
'filter']
1044 filterName = self.
filters[filterName]
1048 self.
log.
warn(
"Filter %s not defined. Set to UNKNOWN." % (filterName))
1050 def _standardizeExposure(self, mapping, item, dataId, filter=True,
1051 trimmed=True, setVisitInfo=True):
1052 """Default standardization function for images. 1054 This sets the Detector from the camera geometry 1055 and optionally set the Filter. In both cases this saves 1056 having to persist some data in each exposure (or image). 1060 mapping : `lsst.obs.base.Mapping` 1061 Where to get the values from. 1062 item : image-like object 1063 Can be any of lsst.afw.image.Exposure, 1064 lsst.afw.image.DecoratedImage, lsst.afw.image.Image 1065 or lsst.afw.image.MaskedImage 1070 Set filter? Ignored if item is already an exposure 1072 Should detector be marked as trimmed? 1073 setVisitInfo : `bool` 1074 Should Exposure have its VisitInfo filled out from the metadata? 1078 `lsst.afw.image.Exposure` 1079 The standardized Exposure. 1083 setVisitInfo=setVisitInfo)
1084 except Exception
as e:
1085 self.
log.
error(
"Could not turn item=%r into an exposure: %s" % (repr(item), e))
1088 if mapping.level.lower() ==
"amp":
1090 elif mapping.level.lower() ==
"ccd":
1096 if mapping.level.lower() !=
"amp" and exposure.getWcs()
is None and \
1097 (exposure.getInfo().getVisitInfo()
is not None or exposure.getMetadata().toDict()):
1105 def _createSkyWcsFromMetadata(self, exposure):
1106 """Create a SkyWcs from the FITS header metadata in an Exposure. 1110 exposure : `lsst.afw.image.Exposure` 1111 The exposure to get metadata from, and attach the SkyWcs to. 1113 metadata = exposure.getMetadata()
1116 exposure.setWcs(wcs)
1119 self.
log.
debug(
"wcs set to None; missing information found in metadata to create a valid wcs:" 1122 exposure.setMetadata(metadata)
1124 def _createInitialSkyWcs(self, exposure):
1125 """Create a SkyWcs from the boresight and camera geometry. 1127 If the boresight or camera geometry do not support this method of 1128 WCS creation, this falls back on the header metadata-based version 1129 (typically a purely linear FITS crval/crpix/cdmatrix WCS). 1133 exposure : `lsst.afw.image.Exposure` 1134 The exposure to get data from, and attach the SkyWcs to. 1139 if exposure.getInfo().getVisitInfo()
is None:
1140 msg =
"No VisitInfo; cannot access boresight information. Defaulting to metadata-based SkyWcs." 1144 newSkyWcs =
createInitialSkyWcs(exposure.getInfo().getVisitInfo(), exposure.getDetector())
1145 exposure.setWcs(newSkyWcs)
1146 except InitialSkyWcsError
as e:
1147 msg =
"Cannot create SkyWcs using VisitInfo and Detector, using metadata-based SkyWcs: %s" 1149 self.
log.
debug(
"Exception was: %s", traceback.TracebackException.from_exception(e))
1150 if e.__context__
is not None:
1151 self.
log.
debug(
"Root-cause Exception was: %s",
1152 traceback.TracebackException.from_exception(e.__context__))
1154 def _makeCamera(self, policy, repositoryDir):
1155 """Make a camera (instance of lsst.afw.cameraGeom.Camera) describing 1158 Also set self.cameraDataLocation, if relevant (else it can be left 1161 This implementation assumes that policy contains an entry "camera" 1162 that points to the subdirectory in this package of camera data; 1163 specifically, that subdirectory must contain: 1164 - a file named `camera.py` that contains persisted camera config 1165 - ampInfo table FITS files, as required by 1166 lsst.afw.cameraGeom.makeCameraFromPath 1170 policy : `lsst.daf.persistence.Policy` 1171 Policy with per-camera defaults already merged 1172 (PexPolicy only for backward compatibility). 1173 repositoryDir : `str` 1174 Policy repository for the subclassing module (obtained with 1175 getRepositoryPath() on the per-camera default dictionary). 1177 if 'camera' not in policy:
1178 raise RuntimeError(
"Cannot find 'camera' in policy; cannot construct a camera")
1179 cameraDataSubdir = policy[
'camera']
1181 os.path.join(repositoryDir, cameraDataSubdir,
"camera.py"))
1182 cameraConfig = afwCameraGeom.CameraConfig()
1185 return afwCameraGeom.makeCameraFromPath(
1186 cameraConfig=cameraConfig,
1187 ampInfoPath=ampInfoPath,
1193 """Get the registry used by this mapper. 1198 The registry used by this mapper for this mapper's repository. 1203 """Stuff image compression settings into a daf.base.PropertySet 1205 This goes into the ButlerLocation's "additionalData", which gets 1206 passed into the boost::persistence framework. 1211 Type of dataset for which to get the image compression settings. 1217 additionalData : `lsst.daf.base.PropertySet` 1218 Image compression settings. 1220 mapping = self.
mappings[datasetType]
1221 recipeName = mapping.recipe
1222 storageType = mapping.storage
1226 raise RuntimeError(
"Unrecognized write recipe for datasetType %s (storage type %s): %s" %
1227 (datasetType, storageType, recipeName))
1228 recipe = self.
_writeRecipes[storageType][recipeName].deepCopy()
1229 seed = hash(tuple(dataId.items())) % 2**31
1230 for plane
in (
"image",
"mask",
"variance"):
1231 if recipe.exists(plane +
".scaling.seed")
and recipe.getScalar(plane +
".scaling.seed") == 0:
1232 recipe.set(plane +
".scaling.seed", seed)
1235 def _initWriteRecipes(self):
1236 """Read the recipes for writing files 1238 These recipes are currently used for configuring FITS compression, 1239 but they could have wider uses for configuring different flavors 1240 of the storage types. A recipe is referred to by a symbolic name, 1241 which has associated settings. These settings are stored as a 1242 `PropertySet` so they can easily be passed down to the 1243 boost::persistence framework as the "additionalData" parameter. 1245 The list of recipes is written in YAML. A default recipe and 1246 some other convenient recipes are in obs_base/policy/writeRecipes.yaml 1247 and these may be overridden or supplemented by the individual obs_* 1248 packages' own policy/writeRecipes.yaml files. 1250 Recipes are grouped by the storage type. Currently, only the 1251 ``FitsStorage`` storage type uses recipes, which uses it to 1252 configure FITS image compression. 1254 Each ``FitsStorage`` recipe for FITS compression should define 1255 "image", "mask" and "variance" entries, each of which may contain 1256 "compression" and "scaling" entries. Defaults will be provided for 1257 any missing elements under "compression" and "scaling". 1259 The allowed entries under "compression" are: 1261 * algorithm (string): compression algorithm to use 1262 * rows (int): number of rows per tile (0 = entire dimension) 1263 * columns (int): number of columns per tile (0 = entire dimension) 1264 * quantizeLevel (float): cfitsio quantization level 1266 The allowed entries under "scaling" are: 1268 * algorithm (string): scaling algorithm to use 1269 * bitpix (int): bits per pixel (0,8,16,32,64,-32,-64) 1270 * fuzz (bool): fuzz the values when quantising floating-point values? 1271 * seed (long): seed for random number generator when fuzzing 1272 * maskPlanes (list of string): mask planes to ignore when doing 1274 * quantizeLevel: divisor of the standard deviation for STDEV_* scaling 1275 * quantizePad: number of stdev to allow on the low side (for 1276 STDEV_POSITIVE/NEGATIVE) 1277 * bscale: manually specified BSCALE (for MANUAL scaling) 1278 * bzero: manually specified BSCALE (for MANUAL scaling) 1280 A very simple example YAML recipe: 1286 algorithm: GZIP_SHUFFLE 1290 recipesFile = os.path.join(
getPackageDir(
"obs_base"),
"policy",
"writeRecipes.yaml")
1292 supplementsFile = os.path.join(self.
getPackageDir(),
"policy",
"writeRecipes.yaml")
1293 validationMenu = {
'FitsStorage': validateRecipeFitsStorage, }
1294 if os.path.exists(supplementsFile)
and supplementsFile != recipesFile:
1297 for entry
in validationMenu:
1298 intersection =
set(recipes[entry].names()).intersection(
set(supplements.names()))
1300 raise RuntimeError(
"Recipes provided in %s section %s may not override those in %s: %s" %
1301 (supplementsFile, entry, recipesFile, intersection))
1302 recipes.update(supplements)
1305 for storageType
in recipes.names(
True):
1306 if "default" not in recipes[storageType]:
1307 raise RuntimeError(
"No 'default' recipe defined for storage type %s in %s" %
1308 (storageType, recipesFile))
1309 self.
_writeRecipes[storageType] = validationMenu[storageType](recipes[storageType])
1313 """Generate an Exposure from an image-like object 1315 If the image is a DecoratedImage then also set its WCS and metadata 1316 (Image and MaskedImage are missing the necessary metadata 1317 and Exposure already has those set) 1321 image : Image-like object 1322 Can be one of lsst.afw.image.DecoratedImage, Image, MaskedImage or 1327 `lsst.afw.image.Exposure` 1328 Exposure containing input image. 1335 metadata = image.getMetadata()
1336 exposure.setMetadata(metadata)
1339 metadata = exposure.getMetadata()
1344 if setVisitInfo
and exposure.getInfo().getVisitInfo()
is None:
1345 if metadata
is not None:
1348 logger = lsstLog.Log.getLogger(
"CameraMapper")
1349 logger.warn(
"I can only set the VisitInfo if you provide a mapper")
1351 exposureId = mapper._computeCcdExposureId(dataId)
1352 visitInfo = mapper.makeRawVisitInfo(md=metadata, exposureId=exposureId)
1354 exposure.getInfo().setVisitInfo(visitInfo)
1360 """Validate recipes for FitsStorage 1362 The recipes are supplemented with default values where appropriate. 1364 TODO: replace this custom validation code with Cerberus (DM-11846) 1368 recipes : `lsst.daf.persistence.Policy` 1369 FitsStorage recipes to validate. 1373 validated : `lsst.daf.base.PropertySet` 1374 Validated FitsStorage recipe. 1379 If validation fails. 1383 compressionSchema = {
1384 "algorithm":
"NONE",
1387 "quantizeLevel": 0.0,
1390 "algorithm":
"NONE",
1392 "maskPlanes": [
"NO_DATA"],
1394 "quantizeLevel": 4.0,
1401 def checkUnrecognized(entry, allowed, description):
1402 """Check to see if the entry contains unrecognised keywords""" 1403 unrecognized =
set(entry.keys()) -
set(allowed)
1406 "Unrecognized entries when parsing image compression recipe %s: %s" %
1407 (description, unrecognized))
1410 for name
in recipes.names(
True):
1411 checkUnrecognized(recipes[name], [
"image",
"mask",
"variance"], name)
1413 validated[name] = rr
1414 for plane
in (
"image",
"mask",
"variance"):
1415 checkUnrecognized(recipes[name][plane], [
"compression",
"scaling"],
1416 name +
"->" + plane)
1418 for settings, schema
in ((
"compression", compressionSchema),
1419 (
"scaling", scalingSchema)):
1420 prefix = plane +
"." + settings
1421 if settings
not in recipes[name][plane]:
1423 rr.set(prefix +
"." + key, schema[key])
1425 entry = recipes[name][plane][settings]
1426 checkUnrecognized(entry, schema.keys(), name +
"->" + plane +
"->" + settings)
1428 value =
type(schema[key])(entry[key])
if key
in entry
else schema[key]
1429 rr.set(prefix +
"." + key, value)
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)
Class for logical location of a persisted Persistable instance.
def _extractDetectorName(self, dataId)
def _setFilter(self, mapping, item, dataId)
A class to contain the data, WCS, and other information needed to describe an image of the sky...
def _createInitialSkyWcs(self, exposure)
def _setCcdDetector(self, item, dataId, trimmed=True)
daf::base::PropertySet * set
def std_bfKernel(self, item, dataId)
def getKeys(self, datasetType, level)
MaskedImage< ImagePixelT, MaskPixelT, VariancePixelT > * makeMaskedImage(typename std::shared_ptr< Image< ImagePixelT >> image, typename std::shared_ptr< Mask< MaskPixelT >> mask=Mask< MaskPixelT >(), typename std::shared_ptr< Image< VariancePixelT >> variance=Image< VariancePixelT >())
A function to return a MaskedImage of the correct type (cf.
std::shared_ptr< Exposure< ImagePixelT, MaskPixelT, VariancePixelT > > makeExposure(MaskedImage< ImagePixelT, MaskPixelT, VariancePixelT > &mimage, std::shared_ptr< geom::SkyWcs const > wcs=std::shared_ptr< geom::SkyWcs const >())
A function to return an Exposure of the correct type (cf.
def getImageCompressionSettings(self, datasetType, dataId)
def _createSkyWcsFromMetadata(self, exposure)
Reports attempts to access elements using an invalid key.
def createInitialSkyWcs(visitInfo, detector, flipX=False)
def map_camera(self, dataId, write=False)
def map(self, datasetType, dataId, write=False)
A class to manipulate images, masks, and variance as a single object.
def std_raw(self, item, dataId)
def backup(self, datasetType, dataId)
def _setupRegistry(self, name, description, path, policy, policyKey, storage, searchParents=True, posixIfNoSql=True)
Utility functions.
def map_skypolicy(self, dataId)
Holds an integer identifier for an LSST filter.
def std_skypolicy(self, item, dataId)
def bypass_camera(self, datasetType, pythonType, butlerLocation, dataId)
def _initMappings(self, policy, rootStorage=None, calibStorage=None, provided=None)
std::shared_ptr< SkyWcs > makeSkyWcs(TransformPoint2ToPoint2 const &pixelsToFieldAngle, lsst::geom::Angle const &orientation, bool flipX, lsst::geom::SpherePoint const &boresight, std::string const &projection="TAN")
Construct a FITS SkyWcs from camera geometry.
def getDefaultSubLevel(self, level)
Class for storing generic metadata.
def _transformId(self, dataId)
A FITS reader class for Exposures and their components.
def getDefaultLevel(self)
def __init__(self, policy, repositoryDir, root=None, registry=None, calibRoot=None, calibRegistry=None, provided=None, parentRegistry=None, repositoryCfg=None)
Backwards-compatibility support for depersisting the old Calib (FluxMag0/FluxMag0Err) objects...
Reports errors from accepting an object of an unexpected or inappropriate type.
def bypass_expIdInfo(self, datasetType, pythonType, location, dataId)
def exposureFromImage(image, dataId=None, mapper=None, logger=None, setVisitInfo=True)
def _initWriteRecipes(self)
def getShortCcdName(ccdName)
lsst::geom::Box2I bboxFromMetadata(daf::base::PropertySet &metadata)
Determine the image bounding box from its metadata (FITS header)
A container for an Image and its associated metadata.