23 from builtins
import str
29 import lsst.daf.persistence
as dafPersist
30 from .
import ImageMapping, ExposureMapping, CalibrationMapping, DatasetMapping
31 import lsst.afw.geom
as afwGeom
32 import lsst.afw.image
as afwImage
33 import lsst.afw.table
as afwTable
34 import lsst.afw.cameraGeom
as afwCameraGeom
35 import lsst.log
as lsstLog
36 import lsst.pex.policy
as pexPolicy
37 from .exposureIdInfo
import ExposureIdInfo
38 from .makeRawVisitInfo
import MakeRawVisitInfo
39 from lsst.utils
import getPackageDir
41 """This module defines the CameraMapper base class."""
46 """CameraMapper is a base class for mappers that handle images from a
47 camera and products derived from them. This provides an abstraction layer
48 between the data on disk and the code.
50 Public methods: keys, queryMetadata, getDatasetTypes, map,
51 canStandardize, standardize
53 Mappers for specific data sources (e.g., CFHT Megacam, LSST
54 simulations, etc.) should inherit this class.
56 The CameraMapper manages datasets within a "root" directory. Note that
57 writing to a dataset present in the input root will hide the existing
58 dataset but not overwrite it. See #2160 for design discussion.
60 A camera is assumed to consist of one or more rafts, each composed of
61 multiple CCDs. Each CCD is in turn composed of one or more amplifiers
62 (amps). A camera is also assumed to have a camera geometry description
63 (CameraGeom object) as a policy file, a filter description (Filter class
64 static configuration) as another policy file, and an optional defects
65 description directory.
67 Information from the camera geometry and defects are inserted into all
68 Exposure objects returned.
70 The mapper uses one or two registries to retrieve metadata about the
71 images. The first is a registry of all raw exposures. This must contain
72 the time of the observation. One or more tables (or the equivalent)
73 within the registry are used to look up data identifier components that
74 are not specified by the user (e.g. filter) and to return results for
75 metadata queries. The second is an optional registry of all calibration
76 data. This should contain validity start and end entries for each
77 calibration dataset in the same timescale as the observation time.
79 Subclasses will typically set MakeRawVisitInfoClass:
81 MakeRawVisitInfoClass: a class variable that points to a subclass of
82 MakeRawVisitInfo, a functor that creates an
83 lsst.afw.image.VisitInfo from the FITS metadata of a raw image.
85 Subclasses must provide the following methods:
87 _extractDetectorName(self, dataId): returns the detector name for a CCD
88 (e.g., "CFHT 21", "R:1,2 S:3,4") as used in the AFW CameraGeom class given
89 a dataset identifier referring to that CCD or a subcomponent of it.
91 _computeCcdExposureId(self, dataId): see below
93 _computeCoaddExposureId(self, dataId, singleFilter): see below
95 Subclasses may also need to override the following methods:
97 _transformId(self, dataId): transformation of a data identifier
98 from colloquial usage (e.g., "ccdname") to proper/actual usage (e.g., "ccd"),
99 including making suitable for path expansion (e.g. removing commas).
100 The default implementation does nothing. Note that this
101 method should not modify its input parameter.
103 getShortCcdName(self, ccdName): a static method that returns a shortened name
104 suitable for use as a filename. The default version converts spaces to underscores.
106 _getCcdKeyVal(self, dataId): return a CCD key and value
107 by which to look up defects in the defects registry.
108 The default value returns ("ccd", detector name)
110 _mapActualToPath(self, template, actualId): convert a template path to an
111 actual path, using the actual dataset identifier.
113 The mapper's behaviors are largely specified by the policy file.
114 See the MapperDictionary.paf for descriptions of the available items.
116 The 'exposures', 'calibrations', and 'datasets' subpolicies configure
117 mappings (see Mappings class).
119 Common default mappings for all subclasses can be specified in the
120 "policy/{images,exposures,calibrations,datasets}.yaml" files. This provides
121 a simple way to add a product to all camera mappers.
123 Functions to map (provide a path to the data given a dataset
124 identifier dictionary) and standardize (convert data into some standard
125 format or type) may be provided in the subclass as "map_{dataset type}"
126 and "std_{dataset type}", respectively.
128 If non-Exposure datasets cannot be retrieved using standard
129 daf_persistence methods alone, a "bypass_{dataset type}" function may be
130 provided in the subclass to return the dataset instead of using the
131 "datasets" subpolicy.
133 Implementations of map_camera and bypass_camera that should typically be
134 sufficient are provided in this base class.
137 * Handle defects the same was as all other calibration products, using the calibration registry
138 * Instead of auto-loading the camera at construction time, load it from the calibration registry
139 * Rewrite defects as AFW tables so we don't need pyfits to unpersist them; then remove all mention
140 of pyfits from this package.
146 MakeRawVisitInfoClass = MakeRawVisitInfo
149 PupilFactoryClass = afwCameraGeom.PupilFactory
151 def __init__(self, policy, repositoryDir,
152 root=
None, registry=
None, calibRoot=
None, calibRegistry=
None,
153 provided=
None, parentRegistry=
None, repositoryCfg=
None):
154 """Initialize the CameraMapper.
158 policy : daf_persistence.Policy,
159 Can also be pexPolicy.Policy, only for backward compatibility.
160 Policy with per-camera defaults already merged.
161 repositoryDir : string
162 Policy repository for the subclassing module (obtained with
163 getRepositoryPath() on the per-camera default dictionary).
164 root : string, optional
165 Path to the root directory for data.
166 registry : string, optional
167 Path to registry with data's metadata.
168 calibRoot : string, optional
169 Root directory for calibrations.
170 calibRegistry : string, optional
171 Path to registry with calibrations' metadata.
172 provided : list of string, optional
173 Keys provided by the mapper.
174 parentRegistry : Registry subclass, optional
175 Registry from a parent repository that may be used to look up
177 repositoryCfg : daf_persistence.RepositoryCfg or None, optional
178 The configuration information for the repository this mapper is
182 dafPersist.Mapper.__init__(self)
184 self.
log = lsstLog.Log.getLogger(
"CameraMapper")
189 self.
root = repositoryCfg.root
192 if isinstance(policy, pexPolicy.Policy):
193 policy = dafPersist.Policy(policy)
195 repoPolicy = repositoryCfg.policy
if repositoryCfg
else None
196 if repoPolicy
is not None:
197 policy.update(repoPolicy)
199 defaultPolicyFile = dafPersist.Policy.defaultPolicyFile(
"obs_base",
200 "MapperDictionary.paf",
202 dictPolicy = dafPersist.Policy(defaultPolicyFile)
203 policy.merge(dictPolicy)
207 if 'levels' in policy:
208 levelsPolicy = policy[
'levels']
209 for key
in levelsPolicy.names(
True):
210 self.
levels[key] = set(levelsPolicy.asArray(key))
213 if 'defaultSubLevels' in policy:
219 root = dafPersist.LogicalLocation(root).locString()
227 if calibRoot
is not None and dafPersist.Storage.storageExists(uri=calibRoot):
228 calibStorage = dafPersist.Storage.makeFromURI(uri=calibRoot)
229 elif 'calibRoot' in policy:
230 calibRoot = policy[
'calibRoot']
231 calibRoot = dafPersist.LogicalLocation(calibRoot).locString()
232 if dafPersist.Storage.exists(uri=calibRoot):
233 calibStorage = dafPersist.Storage.makeFromURI(uri=calibRoot)
234 if calibStorage
is None:
241 searchParents=
False, posixIfNoSql=(
not parentRegistry))
244 needCalibRegistry = policy.get(
'needCalibRegistry',
None)
245 if needCalibRegistry:
248 "calibRegistryPath", calibStorage)
251 "'needCalibRegistry' is true in Policy, but was unable to locate a repo at " +
252 "calibRoot ivar:%s or policy['calibRoot']:%s" %
253 (calibRoot, policy.get(
'calibRoot',
None)))
269 if 'defects' in policy:
270 self.
defectPath = os.path.join(repositoryDir, policy[
'defects'])
271 defectRegistryLocation = os.path.join(self.
defectPath,
"defectRegistry.sqlite3")
272 self.
defectRegistry = dafPersist.Registry.create(defectRegistryLocation)
283 raise ValueError(
'class variable packageName must not be None')
287 def _initMappings(self, policy, rootStorage=None, calibStorage=None, provided=None):
288 """Initialize mappings
290 For each of the dataset types that we want to be able to read, there are
291 methods that can be created to support them:
292 * map_<dataset> : determine the path for dataset
293 * std_<dataset> : standardize the retrieved dataset
294 * bypass_<dataset> : retrieve the dataset (bypassing the usual retrieval machinery)
295 * query_<dataset> : query the registry
297 Besides the dataset types explicitly listed in the policy, we create
298 additional, derived datasets for additional conveniences, e.g., reading
299 the header of an image, retrieving only the size of a catalog.
301 @param policy (Policy) Policy with per-camera defaults already merged
302 @param rootStorage (Storage subclass instance) Interface to persisted repository data
303 @param calibRoot (Storage subclass instance) Interface to persisted calib repository data
304 @param provided (list of strings) Keys provided by the mapper
307 imgMappingPolicy = dafPersist.Policy(dafPersist.Policy.defaultPolicyFile(
308 "obs_base",
"ImageMappingDictionary.paf",
"policy"))
309 expMappingPolicy = dafPersist.Policy(dafPersist.Policy.defaultPolicyFile(
310 "obs_base",
"ExposureMappingDictionary.paf",
"policy"))
311 calMappingPolicy = dafPersist.Policy(dafPersist.Policy.defaultPolicyFile(
312 "obs_base",
"CalibrationMappingDictionary.paf",
"policy"))
313 dsMappingPolicy = dafPersist.Policy(dafPersist.Policy.defaultPolicyFile(
314 "obs_base",
"DatasetMappingDictionary.paf",
"policy"))
318 (
"images", imgMappingPolicy, ImageMapping),
319 (
"exposures", expMappingPolicy, ExposureMapping),
320 (
"calibrations", calMappingPolicy, CalibrationMapping),
321 (
"datasets", dsMappingPolicy, DatasetMapping)
324 for name, defPolicy, cls
in mappingList:
326 datasets = policy[name]
329 defaultsPath = os.path.join(getPackageDir(
"obs_base"),
"policy", name +
".yaml")
330 if os.path.exists(defaultsPath):
331 datasets.merge(dafPersist.Policy(defaultsPath))
334 setattr(self, name, mappings)
335 for datasetType
in datasets.names(
True):
336 subPolicy = datasets[datasetType]
337 subPolicy.merge(defPolicy)
339 if not hasattr(self,
"map_" + datasetType)
and 'composite' in subPolicy:
340 def compositeClosure(dataId, write=False, mapper=None, mapping=None, subPolicy=subPolicy):
341 components = subPolicy.get(
'composite')
342 assembler = subPolicy[
'assembler']
if 'assembler' in subPolicy
else None
343 disassembler = subPolicy[
'disassembler']
if 'disassembler' in subPolicy
else None
344 python = subPolicy[
'python']
345 butlerComposite = dafPersist.ButlerComposite(assembler=assembler,
346 disassembler=disassembler,
350 for name, component
in components.items():
351 butlerComposite.add(id=name,
352 datasetType=component.get(
'datasetType'),
353 setter=component.get(
'setter',
None),
354 getter=component.get(
'getter',
None),
355 subset=component.get(
'subset',
False),
356 inputOnly=component.get(
'inputOnly',
False))
357 return butlerComposite
358 setattr(self,
"map_" + datasetType, compositeClosure)
362 if name ==
"calibrations":
366 mapping = cls(datasetType, subPolicy, self.
registry, rootStorage, provided=provided)
367 self.keyDict.update(mapping.keys())
368 mappings[datasetType] = mapping
369 self.
mappings[datasetType] = mapping
370 if not hasattr(self,
"map_" + datasetType):
371 def mapClosure(dataId, write=False, mapper=weakref.proxy(self), mapping=mapping):
372 return mapping.map(mapper, dataId, write)
373 setattr(self,
"map_" + datasetType, mapClosure)
374 if not hasattr(self,
"query_" + datasetType):
375 def queryClosure(format, dataId, mapping=mapping):
376 return mapping.lookup(format, dataId)
377 setattr(self,
"query_" + datasetType, queryClosure)
378 if hasattr(mapping,
"standardize")
and not hasattr(self,
"std_" + datasetType):
379 def stdClosure(item, dataId, mapper=weakref.proxy(self), mapping=mapping):
380 return mapping.standardize(mapper, item, dataId)
381 setattr(self,
"std_" + datasetType, stdClosure)
383 def setMethods(suffix, mapImpl=None, bypassImpl=None, queryImpl=None):
384 """Set convenience methods on CameraMapper"""
385 mapName =
"map_" + datasetType +
"_" + suffix
386 bypassName =
"bypass_" + datasetType +
"_" + suffix
387 queryName =
"query_" + datasetType +
"_" + suffix
388 if not hasattr(self, mapName):
389 setattr(self, mapName, mapImpl
or getattr(self,
"map_" + datasetType))
390 if not hasattr(self, bypassName):
391 if bypassImpl
is None and hasattr(self,
"bypass_" + datasetType):
392 bypassImpl = getattr(self,
"bypass_" + datasetType)
393 if bypassImpl
is not None:
394 setattr(self, bypassName, bypassImpl)
395 if not hasattr(self, queryName):
396 setattr(self, queryName, queryImpl
or getattr(self,
"query_" + datasetType))
399 setMethods(
"filename", bypassImpl=
lambda datasetType, pythonType, location, dataId:
400 [os.path.join(location.getStorage().root, p)
for p
in location.getLocations()])
403 if subPolicy[
"storage"] ==
"FitsStorage":
404 setMethods(
"md", bypassImpl=
lambda datasetType, pythonType, location, dataId:
405 afwImage.readMetadata(location.getLocationsWithRoot()[0]))
406 if name ==
"exposures":
407 setMethods(
"wcs", bypassImpl=
lambda datasetType, pythonType, location, dataId:
409 afwImage.readMetadata(location.getLocationsWithRoot()[0])))
410 setMethods(
"calib", bypassImpl=
lambda datasetType, pythonType, location, dataId:
412 afwImage.readMetadata(location.getLocationsWithRoot()[0])))
413 setMethods(
"visitInfo",
414 bypassImpl=
lambda datasetType, pythonType, location, dataId:
416 afwImage.readMetadata(location.getLocationsWithRoot()[0])))
417 if subPolicy[
"storage"] ==
"FitsCatalogStorage":
418 setMethods(
"md", bypassImpl=
lambda datasetType, pythonType, location, dataId:
419 afwImage.readMetadata(os.path.join(location.getStorage().root,
420 location.getLocations()[0]), hdu=1))
423 if subPolicy[
"storage"] ==
"FitsStorage":
424 def mapSubClosure(dataId, write=False, mapper=weakref.proxy(self), mapping=mapping):
425 subId = dataId.copy()
427 loc = mapping.map(mapper, subId, write)
428 bbox = dataId[
'bbox']
429 llcX = bbox.getMinX()
430 llcY = bbox.getMinY()
431 width = bbox.getWidth()
432 height = bbox.getHeight()
433 loc.additionalData.set(
'llcX', llcX)
434 loc.additionalData.set(
'llcY', llcY)
435 loc.additionalData.set(
'width', width)
436 loc.additionalData.set(
'height', height)
437 if 'imageOrigin' in dataId:
438 loc.additionalData.set(
'imageOrigin',
439 dataId[
'imageOrigin'])
441 def querySubClosure(key, format, dataId, mapping=mapping):
442 subId = dataId.copy()
444 return mapping.lookup(format, subId)
445 setMethods(
"sub", mapImpl=mapSubClosure, queryImpl=querySubClosure)
447 if subPolicy[
"storage"] ==
"FitsCatalogStorage":
449 setMethods(
"len", bypassImpl=
lambda datasetType, pythonType, location, dataId:
450 afwImage.readMetadata(os.path.join(location.getStorage().root,
451 location.getLocations()[0]),
452 hdu=1).get(
"NAXIS2"))
455 if not datasetType.endswith(
"_schema")
and datasetType +
"_schema" not in datasets:
456 setMethods(
"schema", bypassImpl=
lambda datasetType, pythonType, location, dataId:
457 afwTable.Schema.readFits(os.path.join(location.getStorage().root,
458 location.getLocations()[0])))
460 def _computeCcdExposureId(self, dataId):
461 """Compute the 64-bit (long) identifier for a CCD exposure.
463 Subclasses must override
465 @param dataId (dict) Data identifier with visit, ccd
467 raise NotImplementedError()
469 def _computeCoaddExposureId(self, dataId, singleFilter):
470 """Compute the 64-bit (long) identifier for a coadd.
472 Subclasses must override
474 @param dataId (dict) Data identifier with tract and patch.
475 @param singleFilter (bool) True means the desired ID is for a single-
476 filter coadd, in which case dataId
479 raise NotImplementedError()
481 def _search(self, path):
482 """Search for path in the associated repository's storage.
487 Path that describes an object in the repository associated with
489 Path may contain an HDU indicator, e.g. 'foo.fits[1]'. The
490 indicator will be stripped when searching and so will match
491 filenames without the HDU indicator, e.g. 'foo.fits'. The path
492 returned WILL contain the indicator though, e.g. ['foo.fits[1]'].
497 The path for this object in the repository. Will return None if the
498 object can't be found. If the input argument path contained an HDU
499 indicator, the returned path will also contain the HDU indicator.
502 return dafPersist.Storage.search(self.
root, path)
505 """Rename any existing object with the given type and dataId.
507 The CameraMapper implementation saves objects in a sequence of e.g.:
511 All of the backups will be placed in the output repo, however, and will
512 not be removed if they are found elsewhere in the _parent chain. This
513 means that the same file will be stored twice if the previous version was
514 found in an input repo.
523 def firstElement(list):
524 """Get the first element in the list, or None if that can't be done.
526 return list[0]
if list
is not None and len(list)
else None
529 newLocation = self.map(datasetType, dataId, write=
True)
530 newPath = newLocation.getLocations()[0]
531 path = dafPersist.PosixStorage.search(self.
root, newPath, searchParents=
True)
532 path = firstElement(path)
534 while path
is not None:
536 oldPaths.append((n, path))
537 path = dafPersist.PosixStorage.search(self.
root,
"%s~%d" % (newPath, n), searchParents=
True)
538 path = firstElement(path)
539 for n, oldPath
in reversed(oldPaths):
540 self.rootStorage.copyFile(oldPath,
"%s~%d" % (newPath, n))
543 """Return supported keys.
544 @return (iterable) List of keys usable in a dataset identifier"""
545 return iter(self.keyDict.keys())
548 """Return a dict of supported keys and their value types for a given dataset
549 type at a given level of the key hierarchy.
551 @param datasetType (str) dataset type or None for all dataset types
552 @param level (str) level or None for all levels or '' for the default level for the camera
553 @return (dict) dict keys are strings usable in a dataset identifier; values are their value types"""
559 if datasetType
is None:
560 keyDict = copy.copy(self.
keyDict)
563 if level
is not None and level
in self.
levels:
564 keyDict = copy.copy(keyDict)
565 for l
in self.
levels[level]:
580 """Return the name of the camera that this CameraMapper is for."""
582 className = className[className.find(
'.'):-1]
583 m = re.search(
r'(\w+)Mapper', className)
585 m = re.search(
r"class '[\w.]*?(\w+)'", className)
587 return name[:1].lower() + name[1:]
if name
else ''
591 """Return the name of the package containing this CameraMapper."""
592 if cls.packageName
is None:
593 raise ValueError(
'class variable packageName must not be None')
594 return cls.packageName
597 """Map a camera dataset."""
599 raise RuntimeError(
"No camera dataset available.")
601 return dafPersist.ButlerLocation(
602 pythonType=
"lsst.afw.cameraGeom.CameraConfig",
604 storageName=
"ConfigStorage",
612 """Return the (preloaded) camera object.
615 raise RuntimeError(
"No camera dataset available.")
619 """Map defects dataset.
621 @return a very minimal ButlerLocation containing just the locationList field
622 (just enough information that bypass_defects can use it).
625 if defectFitsPath
is None:
626 raise RuntimeError(
"No defects available for dataId=%s" % (dataId,))
628 return dafPersist.ButlerLocation(
None,
None,
None, defectFitsPath,
633 """Return a defect based on the butler location returned by map_defects
635 @param[in] butlerLocation: a ButlerLocation with locationList = path to defects FITS file
636 @param[in] dataId: the usual data ID; "ccd" must be set
638 Note: the name "bypass_XXX" means the butler makes no attempt to convert the ButlerLocation
639 into an object, which is what we want for now, since that conversion is a bit tricky.
642 defectsFitsPath = butlerLocation.locationList[0]
643 with pyfits.open(defectsFitsPath)
as hduList:
644 for hdu
in hduList[1:]:
645 if hdu.header[
"name"] != detectorName:
649 for data
in hdu.data:
650 bbox = afwGeom.Box2I(
651 afwGeom.Point2I(int(data[
'x0']), int(data[
'y0'])),
652 afwGeom.Extent2I(int(data[
'width']), int(data[
'height'])),
654 defectList.append(afwImage.DefectBase(bbox))
657 raise RuntimeError(
"No defects for ccd %s in %s" % (detectorName, defectsFitsPath))
660 return dafPersist.ButlerLocation(
661 pythonType=
"lsst.obs.base.ExposureIdInfo",
663 storageName=
"Internal",
664 locationList=
"ignored",
671 """Hook to retrieve an lsst.obs.base.ExposureIdInfo for an exposure"""
672 expId = self.bypass_ccdExposureId(datasetType, pythonType, location, dataId)
673 expBits = self.bypass_ccdExposureId_bits(datasetType, pythonType, location, dataId)
674 return ExposureIdInfo(expId=expId, expBits=expBits)
677 """Disable standardization for bfKernel
679 bfKernel is a calibration product that is numpy array,
680 unlike other calibration products that are all images;
681 all calibration images are sent through _standardizeExposure
682 due to CalibrationMapping, but we don't want that to happen to bfKernel
687 """Standardize a raw dataset by converting it to an Exposure instead of an Image"""
690 md = exposure.getMetadata()
692 exposure.getInfo().setVisitInfo(visitInfo)
697 """Map a sky policy."""
698 return dafPersist.ButlerLocation(
"lsst.pex.policy.Policy",
"Policy",
699 "Internal",
None,
None, self,
703 """Standardize a sky policy by returning the one we use."""
712 def _getCcdKeyVal(self, dataId):
713 """Return CCD key and value used to look a defect in the defect registry
715 The default implementation simply returns ("ccd", full detector name)
719 def _setupRegistry(self, name, path, policy, policyKey, storage, searchParents=True,
721 """Set up a registry (usually SQLite3), trying a number of possible
731 Policy that contains the registry name, used if path is None.
733 Key in policy for registry path.
734 storage : Storage subclass
735 Repository Storage to look in.
736 searchParents : bool, optional
737 True if the search for a registry should follow any Butler v1
739 posixIfNoSql : bool, optional
740 If an sqlite registry is not found, will create a posix registry if
745 lsst.daf.persistence.Registry
748 if path
is None and policyKey
in policy:
749 path = dafPersist.LogicalLocation(policy[policyKey]).locString()
750 if os.path.isabs(path):
751 raise RuntimeError(
"Policy should not indicate an absolute path for registry.")
752 if not storage.exists(path):
753 newPath = storage.instanceSearch(path)
755 newPath = newPath[0]
if newPath
is not None and len(newPath)
else None
757 self.log.warn(
"Unable to locate registry at policy path (also looked in root): %s",
761 self.log.warn(
"Unable to locate registry at policy path: %s", path)
768 if path
and (path.startswith(root)):
769 path = path[len(root +
'/'):]
775 path =
"%s.sqlite3" % name
776 newPath = storage.instanceSearch(path)
777 newPath = newPath[0]
if newPath
is not None and len(newPath)
else None
779 self.log.info(
"Unable to locate %s registry in root: %s", name, path)
782 path = os.path.join(
".",
"%s.sqlite3" % name)
783 newPath = storage.instanceSearch(path)
784 newPath = newPath[0]
if newPath
is not None and len(newPath)
else None
786 self.log.info(
"Unable to locate %s registry in current dir: %s", name, path)
789 if not storage.exists(path):
790 newPath = storage.instanceSearch(path)
791 newPath = newPath[0]
if newPath
is not None and len(newPath)
else None
792 if newPath
is not None:
794 self.log.debug(
"Loading %s registry from %s", name, path)
795 registry = dafPersist.Registry.create(storage.getLocalFile(path))
796 elif not registry
and posixIfNoSql:
797 self.log.info(
"Loading Posix registry from %s", storage.root)
798 registry = dafPersist.PosixRegistry(storage.root)
802 def _transformId(self, dataId):
803 """Generate a standard ID dict from a camera-specific ID dict.
805 Canonical keys include:
806 - amp: amplifier name
807 - ccd: CCD name (in LSST this is a combination of raft and sensor)
808 The default implementation returns a copy of its input.
810 @param dataId[in] (dict) Dataset identifier; this must not be modified
811 @return (dict) Transformed dataset identifier"""
815 def _mapActualToPath(self, template, actualId):
816 """Convert a template path to an actual path, using the actual data
817 identifier. This implementation is usually sufficient but can be
818 overridden by the subclass.
819 @param template (string) Template path
820 @param actualId (dict) Dataset identifier
821 @return (string) Pathname"""
825 return template % transformedId
826 except Exception
as e:
827 raise RuntimeError(
"Failed to format %r with data %r: %s" % (template, transformedId, e))
831 """Convert a CCD name to a form useful as a filename
833 The default implementation converts spaces to underscores.
835 return ccdName.replace(
" ",
"_")
837 def _extractDetectorName(self, dataId):
838 """Extract the detector (CCD) name from the dataset identifier.
840 The name in question is the detector name used by lsst.afw.cameraGeom.
842 @param dataId (dict) Dataset identifier
843 @return (string) Detector name
845 raise NotImplementedError(
"No _extractDetectorName() function specified")
847 def _extractAmpId(self, dataId):
848 """Extract the amplifier identifer from a dataset identifier.
850 @warning this is deprecated; DO NOT USE IT
852 amplifier identifier has two parts: the detector name for the CCD
853 containing the amplifier and index of the amplifier in the detector.
854 @param dataId (dict) Dataset identifer
855 @return (tuple) Amplifier identifier"""
858 return (trDataId[
"ccd"], int(trDataId[
'amp']))
860 def _setAmpDetector(self, item, dataId, trimmed=True):
861 """Set the detector object in an Exposure for an amplifier.
862 Defects are also added to the Exposure based on the detector object.
863 @param[in,out] item (lsst.afw.image.Exposure)
864 @param dataId (dict) Dataset identifier
865 @param trimmed (bool) Should detector be marked as trimmed? (ignored)"""
869 def _setCcdDetector(self, item, dataId, trimmed=True):
870 """Set the detector object in an Exposure for a CCD.
871 @param[in,out] item (lsst.afw.image.Exposure)
872 @param dataId (dict) Dataset identifier
873 @param trimmed (bool) Should detector be marked as trimmed? (ignored)"""
876 detector = self.
camera[detectorName]
877 item.setDetector(detector)
879 def _setFilter(self, mapping, item, dataId):
880 """Set the filter object in an Exposure. If the Exposure had a FILTER
881 keyword, this was already processed during load. But if it didn't,
882 use the filter from the registry.
883 @param mapping (lsst.obs.base.Mapping)
884 @param[in,out] item (lsst.afw.image.Exposure)
885 @param dataId (dict) Dataset identifier"""
887 if not (isinstance(item, afwImage.ExposureU)
or isinstance(item, afwImage.ExposureI)
or
888 isinstance(item, afwImage.ExposureF)
or isinstance(item, afwImage.ExposureD)):
891 actualId = mapping.need([
'filter'], dataId)
892 filterName = actualId[
'filter']
894 filterName = self.
filters[filterName]
895 item.setFilter(afwImage.Filter(filterName))
898 def _standardizeExposure(self, mapping, item, dataId, filter=True,
900 """Default standardization function for images.
902 This sets the Detector from the camera geometry
903 and optionally set the Fiter. In both cases this saves
904 having to persist some data in each exposure (or image).
906 @param mapping (lsst.obs.base.Mapping)
907 @param[in,out] item image-like object; any of lsst.afw.image.Exposure,
908 lsst.afw.image.DecoratedImage, lsst.afw.image.Image
909 or lsst.afw.image.MaskedImage
910 @param dataId (dict) Dataset identifier
911 @param filter (bool) Set filter? Ignored if item is already an exposure
912 @param trimmed (bool) Should detector be marked as trimmed?
913 @return (lsst.afw.image.Exposure) the standardized Exposure"""
914 if not hasattr(item,
"getMaskedImage"):
917 except Exception
as e:
918 self.log.error(
"Could not turn item=%r into an exposure: %s" % (repr(item), e))
921 if mapping.level.lower() ==
"amp":
923 elif mapping.level.lower() ==
"ccd":
931 def _defectLookup(self, dataId):
932 """Find the defects for a given CCD.
933 @param dataId (dict) Dataset identifier
934 @return (string) path to the defects file or None if not available"""
938 raise RuntimeError(
"No registry for defect lookup")
942 dataIdForLookup = {
'visit': dataId[
'visit']}
944 rows = self.registry.lookup((
'taiObs'), (
'raw_visit'), dataIdForLookup)
947 assert len(rows) == 1
951 rows = self.defectRegistry.executeQuery((
"path",), (
"defect",),
953 (
"DATETIME(?)",
"DATETIME(validStart)",
"DATETIME(validEnd)"),
955 if not rows
or len(rows) == 0:
958 return os.path.join(self.
defectPath, rows[0][0])
960 raise RuntimeError(
"Querying for defects (%s, %s) returns %d files: %s" %
961 (ccdVal, taiObs, len(rows),
", ".join([_[0]
for _
in rows])))
963 def _makeCamera(self, policy, repositoryDir):
964 """Make a camera (instance of lsst.afw.cameraGeom.Camera) describing the camera geometry
966 Also set self.cameraDataLocation, if relevant (else it can be left None).
968 This implementation assumes that policy contains an entry "camera" that points to the
969 subdirectory in this package of camera data; specifically, that subdirectory must contain:
970 - a file named `camera.py` that contains persisted camera config
971 - ampInfo table FITS files, as required by lsst.afw.cameraGeom.makeCameraFromPath
973 @param policy (daf_persistence.Policy, or pexPolicy.Policy (only for backward compatibility))
974 Policy with per-camera defaults already merged
975 @param repositoryDir (string) Policy repository for the subclassing
976 module (obtained with getRepositoryPath() on the
977 per-camera default dictionary)
979 if isinstance(policy, pexPolicy.Policy):
980 policy = dafPersist.Policy(pexPolicy=policy)
981 if 'camera' not in policy:
982 raise RuntimeError(
"Cannot find 'camera' in policy; cannot construct a camera")
983 cameraDataSubdir = policy[
'camera']
985 os.path.join(repositoryDir, cameraDataSubdir,
"camera.py"))
986 cameraConfig = afwCameraGeom.CameraConfig()
989 return afwCameraGeom.makeCameraFromPath(
990 cameraConfig=cameraConfig,
991 ampInfoPath=ampInfoPath,
997 """Get the registry used by this mapper.
1002 The registry used by this mapper for this mapper's repository.
1007 """Generate an Exposure from an image-like object
1009 If the image is a DecoratedImage then also set its WCS and metadata
1010 (Image and MaskedImage are missing the necessary metadata
1011 and Exposure already has those set)
1013 @param[in] image Image-like object (lsst.afw.image.DecoratedImage, Image, MaskedImage or Exposure)
1014 @return (lsst.afw.image.Exposure) Exposure containing input image
1016 if hasattr(image,
"getVariance"):
1018 exposure = afwImage.makeExposure(image)
1019 elif hasattr(image,
"getImage"):
1021 exposure = afwImage.makeExposure(afwImage.makeMaskedImage(image.getImage()))
1022 metadata = image.getMetadata()
1023 wcs = afwImage.makeWcs(metadata,
True)
1024 exposure.setWcs(wcs)
1025 exposure.setMetadata(metadata)
1026 elif hasattr(image,
"getMaskedImage"):
1031 exposure = afwImage.makeExposure(afwImage.makeMaskedImage(image))
def _computeCcdExposureId
def _getCcdKeyVal
Utility functions.