22 from __future__
import absolute_import, division, print_function
24 from future.utils
import with_metaclass
25 from past.types
import basestring
26 from builtins
import zip
30 from lsst.utils import continueClass, TemplateMeta
31 from .base
import BaseRecord, BaseCatalog
32 from ..schema
import Key
41 """Extract a dictionary of {<name>: <field-value>} in which the field names 42 match the given shell-style glob pattern(s). 44 Any number of glob patterns may be passed; the result will be the union of all 45 the result of each glob considered separately. 51 The result of a call to self.schema.extract(); this will be used 52 instead of doing any new matching, and allows the pattern matching 53 to be reused to extract values from multiple records. This 54 keyword is incompatible with any position arguments and the regex, 55 sub, and ordered keyword arguments. 58 If True, fields with named subfields (e.g. points) will be split 59 into separate items in the dict; instead of {"point": 60 lsst.afw.geom.Point2I(2,3)}, for instance, you'd get {"point.x": 61 2, "point.y": 3}. Default is False. 63 regex : `str` or `re` pattern object 64 A regular expression to be used in addition to any glob patterns 65 passed as positional arguments. Note that this will be compared 66 with re.match, not re.search. 69 A replacement string (see `re.MatchObject.expand`) used to set the 70 dictionary keys of any fields matched by regex. 73 If `True`, a `collections.OrderedDict` will be returned instead of 74 a standard dict, with the order corresponding to the definition 75 order of the `Schema`. `Default is False`. 77 d = kwds.pop(
"items",
None)
78 split = kwds.pop(
"split",
False)
80 d = self.schema.
extract(*patterns, **kwds).copy()
83 "Unrecognized keyword arguments for extract: %s" %
", ".join(kwds.keys()))
85 for name, schemaItem
in list(d.items()):
87 if split
and key.HAS_NAMED_SUBFIELDS:
88 for subname, subkey
in zip(key.subfields, key.subkeys):
89 d[
"%s.%s" % (name, subname)] = self.get(subkey)
92 d[name] = self.get(schemaItem.key)
96 return '\n'.join(
"%s: %s"%(x.field.getName(), self.
extract(
"*")[x.field.getName()])
100 return "%s\n%s" % (type(self), str(self))
103 class Catalog(with_metaclass(TemplateMeta, object)):
106 self.
_columns = self._getColumnView()
109 def __getColumns(self):
110 if not hasattr(self,
"_columns")
or self.
_columns is None:
111 self.
_columns = self._getColumnView()
113 columns = property(__getColumns, doc=
"a column view of the catalog")
116 """Return the record at index key if key is an integer, 117 return a column if key is a string field name or Key, 118 or return a subset of the catalog if key is a slice 119 or boolean NumPy array. 121 if type(key)
is slice:
122 (start, stop, step) = (key.start, key.stop, key.step)
129 return self.subset(start, stop, step)
130 elif isinstance(key, np.ndarray):
131 if key.dtype == bool:
132 return self.subset(key)
133 raise RuntimeError(
"Unsupported array type for indexing non-contiguous Catalog: %s" %
135 elif isinstance(key, Key)
or isinstance(key, basestring):
136 if not self.isContiguous():
137 if isinstance(key, basestring):
138 key = self.schema[key].asKey()
139 array = self._getitem_(key)
145 array.flags.writeable =
False 149 return self._getitem_(key)
153 If ``key`` is an integer, set ``catalog[key]`` to ``value``. Otherwise select column ``key`` 154 and set it to ``value``. 157 if isinstance(key, Key)
or isinstance(key, basestring):
160 return self.set(key, value)
164 if isinstance(key, slice):
175 self._insert(key, value)
183 return self._addNew()
185 def cast(self, type_, deep=False):
186 """Return a copy of the catalog with the given type, optionally 187 cloning the table and deep-copying all records if deep==True. 190 table = self.table.
clone()
191 table.preallocate(len(self))
195 copy.extend(self, deep=deep)
200 Copy a catalog (default is not a deep copy). 202 return self.
cast(type(self), deep)
204 def extend(self, iterable, deep=False, mapper=None):
205 """Append all records in the given iterable to the catalog. 208 iterable ------ any Python iterable containing records 209 deep ---------- if True, the records will be deep-copied; ignored 210 if mapper is not None (that always implies True). 211 mapper -------- a SchemaMapper object used to translate records 216 if type(deep).__name__ ==
"SchemaMapper":
219 if isinstance(iterable, type(self)):
220 if mapper
is not None:
221 self._extend(iterable, mapper)
223 self._extend(iterable, deep)
225 for record
in iterable:
226 if mapper
is not None:
227 self._append(self.table.copyRecord(record, mapper))
229 self._append(self.table.copyRecord(record))
235 return lsst.afw.fits.reduceToFits(self)
237 def asAstropy(self, cls=None, copy=False, unviewable="copy"):
238 """!Return an astropy.table.Table (or subclass thereof) view into this catalog. 240 @param[in] cls Table subclass to use; None implies astropy.table.Table itself. 241 Use astropy.table.QTable to get Quantity columns. 243 @param[in] copy Whether to copy data from the LSST catalog to the astropy table. 244 Not copying is usually faster, but can keep memory from being 245 freed if columns are later removed from the Astropy view. 247 @param[in] unviewable One of the following options, indicating how to handle field types 248 (string and Flag) for which views cannot be constructed: 249 - 'copy' (default): copy only the unviewable fields. 250 - 'raise': raise ValueError if unviewable fields are present. 251 - 'skip': do not include unviewable fields in the Astropy Table. 252 This option is ignored if copy=True. 256 cls = astropy.table.Table
257 if unviewable
not in (
"copy",
"raise",
"skip"):
259 "'unviewable'=%r must be one of 'copy', 'raise', or 'skip'" % (unviewable,))
260 ps = self.getMetadata()
261 meta = ps.toOrderedDict()
if ps
is not None else None 263 items = self.schema.extract(
"*", ordered=
True)
264 for name, item
in items.items():
266 unit = item.field.getUnits()
or None 267 if key.getTypeString() ==
"String":
269 if unviewable ==
"raise":
270 raise ValueError(
"Cannot extract string " 271 "unless copy=True or unviewable='copy' or 'skip'.")
272 elif unviewable ==
"skip":
275 len(self), dtype=np.dtype((str, key.getSize())))
276 for i, record
in enumerate(self):
277 data[i] = record.get(key)
278 elif key.getTypeString() ==
"Flag":
280 if unviewable ==
"raise":
281 raise ValueError(
"Cannot extract packed bit columns " 282 "unless copy=True or unviewable='copy' or 'skip'.")
283 elif unviewable ==
"skip":
285 data = self.
columns.get_bool_array(key)
286 elif key.getTypeString() ==
"Angle":
291 elif "Array" in key.getTypeString()
and key.isVariableLength():
293 if unviewable ==
"raise":
294 raise ValueError(
"Cannot extract variable-length array fields unless unviewable='skip'.")
295 elif unviewable ==
"skip" or unviewable ==
"copy":
302 astropy.table.Column(
306 description=item.field.getDoc()
309 return cls(columns, meta=meta, copy=
False)
313 This custom dir is necessary due to the custom getattr below. 314 Without it, not all of the methods available are returned with dir. 317 def recursive_get_class_dir(cls):
319 Return a set containing the names of all methods 320 for a given class *and* all of its subclasses. 324 for subcls
in cls.__bases__:
325 result |= recursive_get_class_dir(subcls)
326 result |= set(cls.__dict__.keys())
328 return sorted(set(dir(self.
columns)) | set(dir(self.table)) |
329 recursive_get_class_dir(type(self)) | set(self.__dict__.keys()))
335 if name ==
"_columns":
339 return getattr(self.table, name)
340 except AttributeError:
341 return getattr(self.
columns, name)
344 if self.isContiguous():
347 fields =
' '.join(x.field.getName()
for x
in self.schema)
348 string =
"Non-contiguous afw.Catalog of %d rows.\ncolumns: %s" % (len(self), fields)
352 return "%s\n%s" % (type(self), self)
354 Catalog.register(
"Base", BaseCatalog)
def extract(self, patterns, kwds)
def copy(self, deep=False)
def __setitem__(self, key, value)
def __delitem__(self, key)
def asAstropy(self, cls=None, copy=False, unviewable="copy")
Return an astropy.table.Table (or subclass thereof) view into this catalog.
def insert(self, key, value)
def __getattr__(self, name)
def extend(self, iterable, deep=False, mapper=None)
def cast(self, type_, deep=False)
def __getitem__(self, key)