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 "%s\n%s" % (type(self), str(self))
99 class Catalog(with_metaclass(TemplateMeta, object)):
102 self.
_columns = self._getColumnView()
105 def __getColumns(self):
106 if not hasattr(self,
"_columns")
or self.
_columns is None:
107 self.
_columns = self._getColumnView()
109 columns = property(__getColumns, doc=
"a column view of the catalog")
112 """Return the record at index key if key is an integer, 113 return a column if key is a string field name or Key, 114 or return a subset of the catalog if key is a slice 115 or boolean NumPy array. 117 if type(key)
is slice:
118 (start, stop, step) = (key.start, key.stop, key.step)
125 return self.subset(start, stop, step)
126 elif isinstance(key, np.ndarray):
127 if key.dtype == bool:
128 return self.subset(key)
129 raise RuntimeError(
"Unsupported array type for indexing non-contiguous Catalog: %s" %
131 elif isinstance(key, Key)
or isinstance(key, basestring):
132 if not self.isContiguous():
133 if isinstance(key, basestring):
134 key = self.schema[key].asKey()
135 array = self._getitem_(key)
141 array.flags.writeable =
False 145 return self._getitem_(key)
149 If ``key`` is an integer, set ``catalog[key]`` to ``value``. Otherwise select column ``key`` 150 and set it to ``value``. 153 if isinstance(key, Key)
or isinstance(key, basestring):
156 return self.set(key, value)
160 if isinstance(key, slice):
171 self._insert(key, value)
179 return self._addNew()
181 def cast(self, type_, deep=False):
182 """Return a copy of the catalog with the given type, optionally 183 cloning the table and deep-copying all records if deep==True. 186 table = self.table.
clone()
187 table.preallocate(len(self))
191 copy.extend(self, deep=deep)
196 Copy a catalog (default is not a deep copy). 198 return self.
cast(type(self), deep)
200 def extend(self, iterable, deep=False, mapper=None):
201 """Append all records in the given iterable to the catalog. 204 iterable ------ any Python iterable containing records 205 deep ---------- if True, the records will be deep-copied; ignored 206 if mapper is not None (that always implies True). 207 mapper -------- a SchemaMapper object used to translate records 212 if type(deep).__name__ ==
"SchemaMapper":
215 if isinstance(iterable, type(self)):
216 if mapper
is not None:
217 self._extend(iterable, mapper)
219 self._extend(iterable, deep)
221 for record
in iterable:
222 if mapper
is not None:
223 self._append(self.table.copyRecord(record, mapper))
225 self._append(self.table.copyRecord(record))
231 return lsst.afw.fits.reduceToFits(self)
233 def asAstropy(self, cls=None, copy=False, unviewable="copy"):
234 """!Return an astropy.table.Table (or subclass thereof) view into this catalog. 236 @param[in] cls Table subclass to use; None implies astropy.table.Table itself. 237 Use astropy.table.QTable to get Quantity columns. 239 @param[in] copy Whether to copy data from the LSST catalog to the astropy table. 240 Not copying is usually faster, but can keep memory from being 241 freed if columns are later removed from the Astropy view. 243 @param[in] unviewable One of the following options, indicating how to handle field types 244 (string and Flag) for which views cannot be constructed: 245 - 'copy' (default): copy only the unviewable fields. 246 - 'raise': raise ValueError if unviewable fields are present. 247 - 'skip': do not include unviewable fields in the Astropy Table. 248 This option is ignored if copy=True. 252 cls = astropy.table.Table
253 if unviewable
not in (
"copy",
"raise",
"skip"):
255 "'unviewable'=%r must be one of 'copy', 'raise', or 'skip'" % (unviewable,))
256 ps = self.getMetadata()
257 meta = ps.toOrderedDict()
if ps
is not None else None 259 items = self.schema.extract(
"*", ordered=
True)
260 for name, item
in items.items():
262 unit = item.field.getUnits()
or None 263 if key.getTypeString() ==
"String":
265 if unviewable ==
"raise":
266 raise ValueError(
"Cannot extract string " 267 "unless copy=True or unviewable='copy' or 'skip'.")
268 elif unviewable ==
"skip":
271 len(self), dtype=np.dtype((str, key.getSize())))
272 for i, record
in enumerate(self):
273 data[i] = record.get(key)
274 elif key.getTypeString() ==
"Flag":
276 if unviewable ==
"raise":
277 raise ValueError(
"Cannot extract packed bit columns " 278 "unless copy=True or unviewable='copy' or 'skip'.")
279 elif unviewable ==
"skip":
281 data = self.
columns.get_bool_array(key)
282 elif key.getTypeString() ==
"Angle":
287 elif "Array" in key.getTypeString()
and key.isVariableLength():
289 if unviewable ==
"raise":
290 raise ValueError(
"Cannot extract variable-length array fields unless unviewable='skip'.")
291 elif unviewable ==
"skip" or unviewable ==
"copy":
298 astropy.table.Column(
302 description=item.field.getDoc()
305 return cls(columns, meta=meta, copy=
False)
309 This custom dir is necessary due to the custom getattr below. 310 Without it, not all of the methods available are returned with dir. 313 def recursive_get_class_dir(cls):
315 Return a set containing the names of all methods 316 for a given class *and* all of its subclasses. 320 for subcls
in cls.__bases__:
321 result |= recursive_get_class_dir(subcls)
322 result |=
set(cls.__dict__.keys())
324 return sorted(
set(dir(self.
columns)) |
set(dir(self.table)) |
325 recursive_get_class_dir(type(self)) |
set(self.__dict__.keys()))
331 if name ==
"_columns":
335 return getattr(self.table, name)
336 except AttributeError:
337 return getattr(self.
columns, name)
340 if self.isContiguous():
343 fields =
' '.join(x.field.getName()
for x
in self.schema)
344 string =
"Non-contiguous afw.Catalog of %d rows.\ncolumns: %s" % (len(self), fields)
348 return "%s\n%s" % (type(self), self)
351 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)
daf::base::PropertyList * list
def cast(self, type_, deep=False)
def __getitem__(self, key)
daf::base::PropertySet * set