Coverage for python/lsst/daf/persistence/butler.py : 79%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
#!/usr/bin/env python
# # LSST Data Management System # Copyright 2008-2015 LSST Corporation. # # This product includes software developed by the # LSST Project (http://www.lsst.org/). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the LSST License Statement and # the GNU General Public License along with this program. If not, # see <http://www.lsstcorp.org/LegalNotices/>. #
# -*- python -*-
Storage, Policy, NoResults, Repository, DataId, RepositoryCfg, \ RepositoryArgs, listify, setify, sequencify, doImport, ButlerComposite, genericAssembler, \ genericDisassembler, PosixStorage, ParentsMismatch
"Butler.__init__ will prevent Butler from passing " + "parentRegistry or repositoryCfg information to " + "the mapper, which is done only at init time. " + "It is better to pass a importable string or " + "class object.")
"""Represents a Butler configuration.
.. warning::
cfg is 'wet paint' and very likely to change. Use of it in production code other than via the 'old butler' API is strongly discouraged. """
super().__init__({'repoCfg': repoCfg, 'cls': cls})
"""Container object for repository data used by Butler
Parameters ---------- args : RepositoryArgs The arguments that are used to find or create the RepositoryCfg. role : string "input", "output", or "parent", indicating why Butler loaded this repository. * input: the Repository was passed as a Butler input. * output: the Repository was passed as a Butler output. * parent: the Repository was specified in the RepositoryCfg parents list of a readable repository.
Attributes ---------- cfg: RepositoryCfg The configuration for the Repository.
_cfgOrigin : string "new", "existing", or "nested". Indicates the origin of the repository and its RepositoryCfg: * new: it was created by this instance of Butler, and this instance of Butler will generate the RepositoryCfg file. * existing: it was found (via the root or cfgRoot argument) * nested: the full RepositoryCfg was nested in another RepositoryCfg's parents list (this can happen if parameters of an input specified by RepositoryArgs or dict does not entirely match an existing RepositoryCfg).
cfgRoot : string Path or URI to the location of the RepositoryCfg file.
repo : lsst.daf.persistence.Repository The Repository class instance.
parentRepoDatas : list of RepoData The parents of this Repository, as indicated this Repository's RepositoryCfg. If this is a new Repository then these are the inputs to this Butler (and will be saved in the RepositoryCfg). These RepoData objects are not owned by this RepoData, these are references to peer RepoData objects in the Butler's RepoDataContainer.
isV1Repository : bool True if this is an Old Butler repository. In this case the repository does not have a RepositoryCfg file. It may have a _mapper file and may have a _parent symlink. It will never be treated as a "new" repository, i.e. even though there is not a RepositoryCfg file, one will not be generated. If False, this is a New Butler repository and is specified by RepositoryCfg file.
tags : set These are values that may be used to restrict the search of input repositories. Details are available in the RepositoryArgs and DataId classes.
role : string "input", "output", or "parent", indicating why Butler loaded this repository. * input: the Repository was passed as a Butler input. * output: the Repository was passed as a Butler output. * parent: the Repository was specified in the RepositoryCfg parents list of a readable repository.
_repoArgs : RepositoryArgs Contains the arguments that were used to specify this Repository. """
def repoArgs(self):
def repoData(self):
"repoArgs={}" "cfg={!r}," "cfgOrigin={}," "cfgRoot={}," + "repo={}," "parentRepoDatas={}," + "isV1Repository={}," "role={}," + "parentRegistry={})").format( self.__class__.__name__, id(self), self.repoArgs, self.cfg, self.cfgOrigin, self.cfgRoot, self.repo, [id(p) for p in self.parentRepoDatas], self.isV1Repository, self.role, self.parentRegistry)
"""Set information about the cfg into the RepoData
Parameters ---------- cfg : RepositoryCfg The RepositoryCfg for the repo. origin : string 'new', 'existing', or 'nested' root : string URI or absolute path to the location of the RepositoryCfg.yaml file.
Returns ------- None """ raise RuntimeError("Invalid value for origin:{}".format(origin))
def cfgOrigin(self):
def isNewRepository(self):
def role(self):
def role(self, val): raise RuntimeError("Invalid value for role: {}".format(val))
"""Get the parents & grandparents etc of this repo data, in depth-first search order.
Duplicate entries will be removed in cases where the same parent appears more than once in the parent graph.
Parameters ---------- context : set, optional Users should typically omit context and accept the default argument. Context is used to keep a set of known RepoDatas when calling this function recursively, for duplicate elimination.
Returns ------- list of RepoData A list of the parents & grandparents etc of a given repo data, in depth-first search order. """ if context is None: context = set() parents = [] if id(self) in context: return parents context.add(id(self)) for parent in self.parentRepoDatas: parents.append(parent) parents += parent.getParentRepoDatas(context) return parents
"""Container object for RepoData instances owned by a Butler instance.
Parameters ---------- repoDataList : list of RepoData repoData - RepoData instance to add """
"""Get a list of RepoData that are used to as inputs to the Butler. The list is created lazily as needed, and cached.
Returns ------- A list of RepoData with readable repositories, in the order to be used when searching. """ raise RuntimeError("Inputs not yet initialized.")
"""Get a list of RepoData that are used to as outputs to the Butler. The list is created lazily as needed, and cached.
Returns ------- A list of RepoData with writable repositories, in the order to be use when searching. """ raise RuntimeError("Outputs not yet initialized.")
"""Get a list of all RepoData that are used to as by the Butler. The list is created lazily as needed, and cached.
Returns ------- A list of RepoData with writable repositories, in the order to be use when searching. """
self.__class__.__name__, self._inputs, self._outputs, self._all)
"""Build the inputs and outputs lists based on the order of self.all()."""
"""Add a repoData and each of its parents (depth first) to a list"""
raise RuntimeError("Lookup lists are already built.")
"""Butler provides a generic mechanism for persisting and retrieving data using mappers.
A Butler manages a collection of datasets known as a repository. Each dataset has a type representing its intended usage and a location. Note that the dataset type is not the same as the C++ or Python type of the object containing the data. For example, an ExposureF object might be used to hold the data for a raw image, a post-ISR image, a calibrated science image, or a difference image. These would all be different dataset types.
A Butler can produce a collection of possible values for a key (or tuples of values for multiple keys) if given a partial data identifier. It can check for the existence of a file containing a dataset given its type and data identifier. The Butler can then retrieve the dataset. Similarly, it can persist an object to an appropriate location when given its associated data identifier.
Note that the Butler has two more advanced features when retrieving a data set. First, the retrieval is lazy. Input does not occur until the data set is actually accessed. This allows datasets to be retrieved and placed on a clipboard prospectively with little cost, even if the algorithm of a stage ends up not using them. Second, the Butler will call a standardization hook upon retrieval of the dataset. This function, contained in the input mapper object, must perform any necessary manipulations to force the retrieved object to conform to standards, including translating metadata.
Public methods:
__init__(self, root, mapper=None, **mapperArgs)
defineAlias(self, alias, datasetType)
getKeys(self, datasetType=None, level=None)
queryMetadata(self, datasetType, format=None, dataId={}, **rest)
datasetExists(self, datasetType, dataId={}, **rest)
get(self, datasetType, dataId={}, immediate=False, **rest)
put(self, obj, datasetType, dataId={}, **rest)
subset(self, datasetType, level=None, dataId={}, **rest)
dataRef(self, datasetType, level=None, dataId={}, **rest)
Initialization:
The preferred method of initialization is to use the `inputs` and `outputs` __init__ parameters. These are described in the parameters section, below.
For backward compatibility: this initialization method signature can take a posix root path, and optionally a mapper class instance or class type that will be instantiated using the mapperArgs input argument. However, for this to work in a backward compatible way it creates a single repository that is used as both an input and an output repository. This is NOT preferred, and will likely break any provenance system we have in place.
Parameters ---------- root : string .. note:: Deprecated in 12_0 `root` will be removed in TBD, it is replaced by `inputs` and `outputs` for multiple-repository support. A file system path. Will only work with a PosixRepository. mapper : string or instance .. note:: Deprecated in 12_0 `mapper` will be removed in TBD, it is replaced by `inputs` and `outputs` for multiple-repository support. Provides a mapper to be used with Butler. mapperArgs : dict .. note:: Deprecated in 12_0 `mapperArgs` will be removed in TBD, it is replaced by `inputs` and `outputs` for multiple-repository support. Provides arguments to be passed to the mapper if the mapper input argument is a class type to be instantiated by Butler. inputs : RepositoryArgs, dict, or string Can be a single item or a list. Provides arguments to load an existing repository (or repositories). String is assumed to be a URI and is used as the cfgRoot (URI to the location of the cfg file). (Local file system URI does not have to start with 'file://' and in this way can be a relative path). The `RepositoryArgs` class can be used to provide more parameters with which to initialize a repository (such as `mapper`, `mapperArgs`, `tags`, etc. See the `RepositoryArgs` documentation for more details). A dict may be used as shorthand for a `RepositoryArgs` class instance. The dict keys must match parameters to the `RepositoryArgs.__init__` function. outputs : RepositoryArgs, dict, or string Provides arguments to load one or more existing repositories or create new ones. The different types are handled the same as for `inputs`.
The Butler init sequence loads all of the input and output repositories. This creates the object hierarchy to read from and write to them. Each repository can have 0 or more parents, which also get loaded as inputs. This becomes a DAG of repositories. Ultimately, Butler creates a list of these Repositories in the order that they are used.
Initialization Sequence =======================
During initialization Butler creates a Repository class instance & support structure for each object passed to `inputs` and `outputs` as well as the parent repositories recorded in the `RepositoryCfg` of each existing readable repository.
This process is complex. It is explained below to shed some light on the intent of each step.
1. Input Argument Standardization ---------------------------------
In `Butler._processInputArguments` the input arguments are verified to be legal (and a RuntimeError is raised if not), and they are converted into an expected format that is used for the rest of the Butler init sequence. See the docstring for `_processInputArguments`.
2. Create RepoData Objects --------------------------
Butler uses an object, called `RepoData`, to keep track of information about each repository; each repository is contained in a single `RepoData`. The attributes are explained in its docstring.
After `_processInputArguments`, a RepoData is instantiated and put in a list for each repository in `outputs` and `inputs`. This list of RepoData, the `repoDataList`, now represents all the output and input repositories (but not parent repositories) that this Butler instance will use.
3. Get `RepositoryCfg`s -----------------------
`Butler._getCfgs` gets the `RepositoryCfg` for each repository the `repoDataList`. The behavior is described in the docstring.
4. Add Parents --------------
`Butler._addParents` then considers the parents list in the `RepositoryCfg` of each `RepoData` in the `repoDataList` and inserts new `RepoData` objects for each parent not represented in the proper location in the `repoDataList`. Ultimately a flat list is built to represent the DAG of readable repositories represented in depth-first order.
5. Set and Verify Parents of Outputs ------------------------------------
To be able to load parent repositories when output repositories are used as inputs, the input repositories are recorded as parents in the `RepositoryCfg` file of new output repositories. When an output repository already exists, for consistency the Butler's inputs must match the list of parents specified the already- existing output repository's `RepositoryCfg` file.
In `Butler._setAndVerifyParentsLists`, the list of parents is recorded in the `RepositoryCfg` of new repositories. For existing repositories the list of parents is compared with the `RepositoryCfg`'s parents list, and if they do not match a `RuntimeError` is raised.
6. Set the Default Mapper -------------------------
If all the input repositories use the same mapper then we can assume that mapper to be the "default mapper". If there are new output repositories whose `RepositoryArgs` do not specify a mapper and there is a default mapper then the new output repository will be set to use that default mapper.
This is handled in `Butler._setDefaultMapper`.
7. Cache References to Parent RepoDatas ---------------------------------------
In `Butler._connectParentRepoDatas`, in each `RepoData` in `repoDataList`, a list of `RepoData` object references is built that matches the parents specified in that `RepoData`'s `RepositoryCfg`.
This list is used later to find things in that repository's parents, without considering peer repository's parents. (e.g. finding the registry of a parent)
8. Set Tags -----------
Tags are described at https://ldm-463.lsst.io/v/draft/#tagging
In `Butler._setRepoDataTags`, for each `RepoData`, the tags specified by its `RepositoryArgs` are recorded in a set, and added to the tags set in each of its parents, for ease of lookup when mapping.
9. Find Parent Registry and Instantiate RepoData ------------------------------------------------
At this point there is enough information to instantiate the `Repository` instances. There is one final step before instantiating the Repository, which is to try to get a parent registry that can be used by the child repository. The criteria for "can be used" is spelled out in `Butler._setParentRegistry`. However, to get the registry from the parent, the parent must be instantiated. The `repoDataList`, in depth-first search order, is built so that the most-dependent repositories are first, and the least dependent repositories are last. So the `repoDataList` is reversed and the Repositories are instantiated in that order; for each RepoData a parent registry is searched for, and then the Repository is instantiated with whatever registry could be found."""
'mapperArgs': mapperArgs}
# Always use an empty Persistence policy until we can get rid of it
root=root, mapper=mapper, inputs=inputs, outputs=outputs, **mapperArgs)
# convert the RepoArgs into RepoData
# this repository may have already been initialized by its children, in which case there is # nothing more to do.
"""Process, verify, and standardize the input arguments. * Inputs can not be for Old Butler (root, mapper, mapperArgs) AND New Butler (inputs, outputs) `root`, `mapper`, and `mapperArgs` are Old Butler init API. `inputs` and `outputs` are New Butler init API. Old Butler and New Butler init API may not be mixed, Butler may be initialized with only the Old arguments or the New arguments. * Verify that if there is a readable output that there is exactly one output. (This restriction is in place because all readable repositories must be parents of writable repositories, and for consistency the DAG of readable repositories must always be the same. Keeping the list of parents becomes very complicated in the presence of multiple readable output repositories. It is better to only write to output repositories, and then create a new Butler instance and use the outputs as inputs, and write to new output repositories.) * Make a copy of inputs & outputs so they may be modified without changing the passed-in arguments. * Convert any input/output values that are URI strings to RepositoryArgs. * Listify inputs & outputs. * Set default RW mode on inputs & outputs as needed.
Parameters ---------- Same as Butler.__init__
Returns ------- (list of RepositoryArgs, list of RepositoryArgs) First item is a list to use as inputs. Second item is a list to use as outputs.
Raises ------ RuntimeError If Old Butler and New Butler arguments are both used this will raise. If an output is readable there is more than one output this will raise. """ # inputs and outputs may be modified, do not change the external value.
mapper=mapper, mapperArgs=mapperArgs or None) 'Butler version 1 API (root, mapper, **mapperArgs) may ' + 'not be used with version 2 API (inputs, outputs)')
# make sure inputs and outputs are lists, and if list items are a string convert it RepositoryArgs. if not isinstance(args, RepositoryArgs) else args for args in inputs] if not isinstance(args, RepositoryArgs) else args for args in outputs] # Set the default value of inputs & outputs, verify the required values ('r' for inputs, 'w' for # outputs) and remove the 'w' from inputs if needed. # check for class instances in args.mapper (not allowed) not inspect.isclass(args.mapper)): # if the output is readable, there must be only one output: raise RuntimeError("Butler does not support multiple output repositories if any of the " "outputs are readable.")
# Handle the case where the output is readable and is also passed in as one of the inputs by removing # the input. This supports a legacy use case in pipe_tasks where the input is also passed as the # output, to the command line parser. o.root == inputArgs.root and o.mapper == inputArgs.mapper and o.mapperArgs == inputArgs.mapperArgs and o.tags == inputArgs.tags and o.policy == inputArgs.policy): self.log.debug(("Input repositoryArgs {} is also listed in outputs as readable; " + "throwing away the input.").format(inputArgs)) return True
def _getParentVal(repoData): """Get the value of this repoData as it should appear in the parents list of other repositories""" else:
def _getParents(ofRepoData, repoInfo): """Create a parents list of repoData from inputs and (readable) outputs.""" parents = [] # get the parents list of repoData: for repoData in repoInfo: if repoData is ofRepoData: continue if 'r' not in repoData.repoArgs.mode: continue parents.append(Butler._getParentVal(repoData)) return parents
def _getOldButlerRepositoryCfg(repositoryArgs): return None
"""Try to get a repository from the location described by cfgRoot.
Parameters ---------- repositoryArgs : RepositoryArgs or string Provides arguments to load an existing repository (or repositories). String is assumed to be a URI and is used as the cfgRoot (URI to the location of the cfg file).
Returned -------- (RepositoryCfg or None, bool) The RepositoryCfg, or None if one cannot be found, and True if the RepositoryCfg was created by reading an Old Butler repository, or False if it is a New Butler Repository. """
"""Get or make a RepositoryCfg for each RepoData, and add the cfg to the RepoData. If the cfg exists, compare values. If values match then use the cfg as an "existing" cfg. If the values do not match, use the cfg as a "nested" cfg. If the cfg does not exist, the RepositoryArgs must be for a writable repository.
Parameters ---------- repoDataList : list of RepoData The RepoData that are output and inputs of this Butler
Raises ------ RuntimeError If the passed-in RepositoryArgs indicate an existing repository but other cfg parameters in those RepositoryArgs don't match the existing repository's cfg a RuntimeError will be raised. """ """Test if there are any values in an RepositoryArgs that conflict with the values in a cfg""" return False return False return False
"No cfg found for read-only input repository at {}".format(repoData.repoArgs.cfgRoot)) origin='new', root=repoData.repoArgs.cfgRoot, isV1Repository=isOldButlerRepository) else:
# This is a hack fix for an issue introduced by DM-11284; Old Butler parent repositories used # to be stored as a path to the repository in the parents list and it was changed so that the # whole RepositoryCfg, that described the Old Butler repository (including the mapperArgs that # were used with it), was recorded as a "nested" repository cfg. That checkin did not account # for the fact that there were repositoryCfg.yaml files in the world with only the path to # Old Butler repositories in the parents list. "found in the parents list of a New Butler repositoryCfg: {} " "with a repositoryCfg that includes the child repository's " "mapperArgs: {}. This affects the instantiated RepositoryCfg " "but does not change the persisted child repositoryCfg.yaml file." ).format(parent, cfg, parentCfg))
# if it's an output repository, the RepositoryArgs must match the existing cfg. raise RuntimeError(("The RepositoryArgs and RepositoryCfg must match for writable " + "repositories, RepositoryCfg:{}, RepositoryArgs:{}").format( cfg, repoData.repoArgs)) isV1Repository=isOldButlerRepository) else: # if it's an input repository, the cfg can overwrite the in-repo cfg. isV1Repository=isOldButlerRepository) else: repoData.setCfg(cfg=cfg, origin='nested', root=None, isV1Repository=isOldButlerRepository)
"""For each repoData in the input list, see if its parents are the next items in the list, and if not add the parent, so that the repoDataList includes parents and is in order to operate depth-first 0..n.
Parameters ---------- repoDataList : list of RepoData The RepoData for the Butler outputs + inputs.
Raises ------ RuntimeError Raised if a RepositoryCfg can not be found at a location where a parent repository should be. """ repoDataIdx += 1 continue # if there are no parents then there's nothing to do. else: repoDataList[parentIdxInRepoDataList].cfg == repoParentCfg): isV1Repository=isOldButlerRepository)
"""Make a list of all the input repositories of this Butler, these are the parents of the outputs. For new output repositories, set the parents in the RepositoryCfg. For existing output repositories verify that the RepositoryCfg's parents match the parents list.
Parameters ---------- repoDataList : list of RepoData All the RepoDatas loaded by this butler, in search order.
Raises ------ RuntimeError If an existing output repository is loaded and its parents do not match the parents of this Butler an error will be raised. """ """make a parents list for repo in `ofRepoData` that is comprised of inputs and readable outputs (not parents-of-parents) of this butler""" raise RuntimeError("If an output is readable it must be the only output.") # and if this is the only output, this should have continued in # "if repoData is ofRepoData" continue
# if repoData is new, add the parent RepositoryCfgs to it. "writable cfg:{} (ParentMismatch exception: {}").format( parents, repoData.cfg.parents, e))
"""Establish a default mapper if there is one and assign it to outputs that do not have a mapper assigned.
If all inputs have the same mapper it will be used as the default mapper.
Parameters ---------- repoDataList : list of RepoData All the RepoDatas loaded by this butler, in search order.
Raises ------ RuntimeError If a default mapper can not be established and there is an output that does not have a mapper. """ ("No default mapper could be established from inputs:{} and no mapper specified " + "for outputs:{}").format(inputs, needyOutputs))
"""For each RepoData in repoDataList, find its parent in the repoDataList and cache a reference to it.
Parameters ---------- repoDataList : list of RepoData All the RepoDatas loaded by this butler, in search order.
Raises ------ RuntimeError When a parent is listed in the parents list but not found in the repoDataList. This is not expected to ever happen and would indicate an internal Butler error. """ raise RuntimeError( "Could not find a parent matching {} to add to {}".format(parent, repoData))
def _getParentRepoData(parent, repoDataList): """get a parent RepoData from a cfg from a list of RepoData
Parameters ---------- parent : string or RepositoryCfg cfgRoot of a repo or a cfg that describes the repo repoDataList : list of RepoData list to search in
Returns ------- RepoData or None A RepoData if one can be found, else None """ repoData = None for otherRepoData in repoDataList: if isinstance(parent, RepositoryCfg): if otherRepoData.cfg == parent: repoData = otherRepoData break elif otherRepoData.cfg.root == parent: repoData = otherRepoData break return repoData
"""Set the tags from each repoArgs into all its parent repoArgs so that they can be included in tagged searches."""
"""Convert Old Butler RepositoryArgs (root, mapper, mapperArgs) to New Butler RepositoryArgs (inputs, outputs)
Parameters ---------- root : string Posix path to repository root mapper : class, class instance, or string Instantiated class, a class object to be instantiated, or a string that refers to a class that can be imported & used as the mapper. mapperArgs : dict RepositoryArgs & their values used when instantiating the mapper.
Returns ------- tuple (inputs, outputs) - values to be used for inputs and outputs in Butler.__init__ """ not inspect.isclass(mapper)): if hasattr(mapper, 'root'): # in legacy repositories, the mapper may be given the root directly. root = mapper.root else: # in the past root="None" could be used to mean root='.' root = '.' root=root, mapper=mapper, mapperArgs=mapperArgs)
self.datasetTypeAliasDict, self._repos, self.persistence)
"""Get the default mapper. Currently this means if all the repositories use exactly the same mapper, that mapper may be considered the default.
This definition may be changing; mappers may be able to exclude themselves as candidates for default, and they may nominate a different mapper instead. Also, we may not want to look at *all* the repositories, but only a depth-first search on each of the input & output repositories, and use the first-found mapper for each of those. TBD.
Parameters ---------- inputs : TYPE Description
Returns ------- Mapper class or None Returns the class type of the default mapper, or None if a default mapper can not be determined. """
# if the mapper is: # * a string, import it. # * a class instance, get its class type # * a class, do nothing; use it mapper = mapper.__class__ # If no mapper has been found, note the first found mapper. # Then, if a mapper has been found and each next mapper matches it, # continue looking for mappers. # If a mapper has been found and another non-matching mapper is # found then we have no default, return None.
for repoData in self._repos.all().values(): if repoData.cfg.mapper is None and (repoData.isNewRepository or repoData.isV1Repository): if defaultMapper is None: raise RuntimeError( "No mapper specified for %s and no default mapper could be determined." % repoData.args) repoData.cfg.mapper = defaultMapper
def getMapperClass(root): """posix-only; gets the mapper class at the path specified by root (if a file _mapper can be found at that location or in a parent location.
As we abstract the storage and support different types of storage locations this method will be moved entirely into Butler Access, or made more dynamic, and the API will very likely change.""" return Storage.getMapperClass(root)
"""Register an alias that will be substituted in datasetTypes.
Parameters ---------- alias - string The alias keyword. It may start with @ or not. It may not contain @ except as the first character. datasetType - string The string that will be substituted when @alias is passed into datasetType. It may not contain '@' """ # verify formatting of alias: # it can have '@' as the first character (if not it's okay, we will add it) or not at all.
# verify that datasetType does not contain '@' raise RuntimeError("Badly formatted type string: %s" % (datasetType))
# verify that the alias keyword does not start with another alias keyword, # and vice versa
"""Get the valid data id keys at or above the given level of hierarchy for the dataset type or the entire collection if None. The dict values are the basic Python types corresponding to the keys (int, float, string).
Parameters ---------- datasetType - string The type of dataset to get keys for, entire collection if None. level - string The hierarchy level to descend to. None if it should not be restricted. Use an empty string if the mapper should lookup the default level. tags - any, or list of any Any object that can be tested to be the same as the tag in a dataId passed into butler input functions. Applies only to input repositories: If tag is specified by the dataId then the repo will only be read from used if the tag in the dataId matches a tag used for that repository.
Returns ------- Returns a dict. The dict keys are the valid data id keys at or above the given level of hierarchy for the dataset type or the entire collection if None. The dict values are the basic Python types corresponding to the keys (int, float, string). """
# An empty dict is a valid "found" condition for keys. The only value for keys that should # cause the search to continue is None
"""Returns the valid values for one or more keys when given a partial input collection data id.
Parameters ---------- datasetType - string The type of dataset to inquire about. format - str, tuple Key or tuple of keys to be returned. dataId - DataId, dict The partial data id. **rest - Keyword arguments for the partial data id.
Returns ------- A list of valid values or tuples of valid values as specified by the format. """
except TypeError: ret.append(x)
"""Determines if a dataset file exists.
Parameters ---------- datasetType - string The type of dataset to inquire about. dataId - DataId, dict The data id of the dataset. write - bool If True, look only in locations where the dataset could be written, and return True only if it is present in all of them. **rest keyword arguments for the data id.
Returns ------- exists - bool True if the dataset exists or is non-file-based. """
return False
# If the location is a ButlerComposite (as opposed to a ButlerLocation), # verify the component objects exist. for name, componentInfo in location.componentInfo.items(): if componentInfo.subset: subset = self.subset(datasetType=componentInfo.datasetType, dataId=location.dataId) exists = all([obj.datasetExists() for obj in subset]) else: exists = self.datasetExists(componentInfo.datasetType, location.dataId) if exists is False: return False else:
"""Get one or more ButlerLocations and/or ButlercComposites.
Parameters ---------- datasetType : string The datasetType that is being searched for. The datasetType may be followed by a dot and a component name (component names are specified in the policy). IE datasetType.componentName
dataId : dict or DataId class instance The dataId
write : bool True if this is a search to write an object. False if it is a search to read an object. This affects what type (an object or a container) is returned.
Returns ------- If write is False, will return either a single object or None. If write is True, will return a list (which may be empty) """ # enforce dataId & repository tags when reading: except NoResults: continue if not isinstance(location, ButlerComposite): raise RuntimeError("The location for a dotted datasetType must be a composite.") # replace the first component name with the datasetType components[0] = location.componentInfo[components[0]].datasetType # join components back into a dot-delimited string datasetType = '.'.join(components) location = self._locate(datasetType, dataId, write) # if a component location is not found, we can not continue with this repo, move to next repo. if location is None: break # if reading, only one location is desired. # If there is a bypass function for this dataset type, we can't test to see if the object # exists in storage, because the bypass function may not actually use the location # according to the template. Instead, execute the bypass function and include its results # in the bypass attribute of the location. The bypass function may fail for any reason, # the most common case being that a file does not exist. If it raises an exception # indicating such, we ignore the bypass function and proceed as though it does not exist. "bypass function for Dataset type:{} Data ID:{} at " "location {}".format(datasetType, dataId, location)) # If a location was found but the location does not exist, keep looking in input # repositories (the registry may have had enough data for a lookup even thought the object # exists in a different repository.) location.repository.exists(location)): else:
def _getBypassFunc(location, dataId):
"""Retrieves a dataset given an input collection data id.
Parameters ---------- datasetType - string The type of dataset to retrieve. dataId - dict The data id. immediate - bool If False use a proxy for delayed loading. **rest keyword arguments for the data id.
Returns ------- An object retrieved from the dataset (or a proxy for one). """
raise NoResults("No locations for get:", datasetType, dataId)
# this type loader block should get moved into a helper someplace, and duplications removed. else: innerCallback = callback
def callback(): return location.mapper.standardize(location.datasetType, innerCallback(), dataId)
"""Persists a dataset given an output collection data id.
Parameters ---------- obj - The object to persist. datasetType - string The type of dataset to persist. dataId - dict The data id. doBackup - bool If True, rename existing instead of overwriting. WARNING: Setting doBackup=True is not safe for parallel processing, as it may be subject to race conditions. **rest Keyword arguments for the data id. """
disassembler = location.disassembler if location.disassembler else genericDisassembler disassembler(obj=obj, dataId=location.dataId, componentInfo=location.componentInfo) for name, info in location.componentInfo.items(): if not info.inputOnly: self.put(info.obj, info.datasetType, location.dataId, doBackup=doBackup) else: location.getRepository().backup(location.datasetType, dataId)
"""Return complete dataIds for a dataset type that match a partial (or empty) dataId.
Given a partial (or empty) dataId specified in dataId and **rest, find all datasets that match the dataId. Optionally restrict the results to a given level specified by a dataId key (e.g. visit or sensor or amp for a camera). Return an iterable collection of complete dataIds as ButlerDataRefs. Datasets with the resulting dataIds may not exist; that needs to be tested with datasetExists().
Parameters ---------- datasetType - string The type of dataset collection to subset level - string The level of dataId at which to subset. Use an empty string if the mapper should look up the default level. dataId - dict The data id. **rest Keyword arguments for the data id.
Returns ------- subset - ButlerSubset Collection of ButlerDataRefs for datasets matching the data id.
Examples ----------- To print the full dataIds for all r-band measurements in a source catalog (note that the subset call is equivalent to: `butler.subset('src', dataId={'filter':'r'})`):
>>> subset = butler.subset('src', filter='r') >>> for data_ref in subset: print(data_ref.dataId) """
# Currently expected behavior of subset is that if specified level is None then the mapper's default # level should be used. Convention for level within Butler is that an empty string is used to indicate # 'get default'.
"""Returns a single ButlerDataRef.
Given a complete dataId specified in dataId and **rest, find the unique dataset at the given level specified by a dataId key (e.g. visit or sensor or amp for a camera) and return a ButlerDataRef.
Parameters ---------- datasetType - string The type of dataset collection to reference level - string The level of dataId at which to reference dataId - dict The data id. **rest Keyword arguments for the data id.
Returns ------- dataRef - ButlerDataRef ButlerDataRef for dataset matching the data id """
raise RuntimeError("No unique dataset for: Dataset type:%s Level:%s Data ID:%s Keywords:%s" % (str(datasetType), str(level), str(dataId), str(rest)))
"""Return the URI for a dataset
.. warning:: This is intended only for debugging. The URI should never be used for anything other than printing.
.. note:: In the event there are multiple URIs for read, we return only the first.
.. note:: getUri() does not currently support composite datasets.
Parameters ---------- datasetType : `str` The dataset type of interest. dataId : `dict`, optional The data identifier. write : `bool`, optional Return the URI for writing? rest : `dict`, optional Keyword arguments for the data id.
Returns ------- uri : `str` URI for dataset. """ raise NoResults("No locations for getUri: ", datasetType, dataId)
# Follow the write path # Return the first valid write location. for name, info in location.componentInfo.items(): if not info.inputOnly: return self.getUri(info.datasetType, location.dataId, write=True) else: # fall back to raise raise NoResults("No locations for getUri(write=True): ", datasetType, dataId) else: # Follow the read path, only return the first valid read
"""Unpersist an object using data inside a ButlerLocation or ButlerComposite object.
Parameters ---------- location : ButlerLocation or ButlerComposite A ButlerLocation or ButlerComposite instance populated with data needed to read the object.
Returns ------- object An instance of the object specified by the location. """
for name, componentInfo in location.componentInfo.items(): if componentInfo.subset: subset = self.subset(datasetType=componentInfo.datasetType, dataId=location.dataId) componentInfo.obj = [obj.get() for obj in subset] else: obj = self.get(componentInfo.datasetType, location.dataId, immediate=True) componentInfo.obj = obj assembler = location.assembler or genericAssembler results = assembler(dataId=location.dataId, componentInfo=location.componentInfo, cls=location.python) return results else:
"""Replaces all the known alias keywords in the given string with the alias value.
Parameters ---------- datasetType - string A datasetType string to search & replace on
Returns ------- datasetType - string The de-aliased string """ # if all aliases have been replaced, bail out
# If an alias specifier can not be resolved then throw.
|