22 from __future__
import absolute_import, division, print_function
24 from future.utils
import with_metaclass
28 from lsst.utils
import continueClass, TemplateMeta
29 from .base
import BaseRecord, BaseCatalog
38 """Extract a dictionary of {<name>: <field-value>} in which the field names
39 match the given shell-style glob pattern(s).
41 Any number of glob patterns may be passed; the result will be the union of all
42 the result of each glob considered separately.
48 The result of a call to self.schema.extract(); this will be used
49 instead of doing any new matching, and allows the pattern matching
50 to be reused to extract values from multiple records. This
51 keyword is incompatible with any position arguments and the regex,
52 sub, and ordered keyword arguments.
55 If True, fields with named subfields (e.g. points) will be split
56 into separate items in the dict; instead of {"point":
57 lsst.afw.geom.Point2I(2,3)}, for instance, you'd get {"point.x":
58 2, "point.y": 3}. Default is False.
60 regex : `str` or `re` pattern object
61 A regular expression to be used in addition to any glob patterns
62 passed as positional arguments. Note that this will be compared
63 with re.match, not re.search.
66 A replacement string (see `re.MatchObject.expand`) used to set the
67 dictionary keys of any fields matched by regex.
70 If `True`, a `collections.OrderedDict` will be returned instead of
71 a standard dict, with the order corresponding to the definition
72 order of the `Schema`. `Default is False`.
74 d = kwds.pop(
"items",
None)
75 split = kwds.pop(
"split",
False)
77 d = self.schema.extract(*patterns, **kwds).copy()
80 "Unrecognized keyword arguments for extract: %s" %
", ".join(kwds.keys()))
82 for name, schemaItem
in list(d.items()):
84 if split
and key.HAS_NAMED_SUBFIELDS:
85 for subname, subkey
in zip(key.subfields, key.subkeys):
86 d[
"%s.%s" % (name, subname)] = self.get(subkey)
89 d[name] = self.get(schemaItem.key)
93 return '\n'.join(
"%s: %s"%(x.field.getName(), self.
extract(
"*")[x.field.getName()])
97 return "%s\n%s" % (type(self), str(self))
100 class Catalog(with_metaclass(TemplateMeta, object)):
103 self.
_columns = self._getColumnView()
106 def __getColumns(self):
107 if not hasattr(self,
"_columns")
or self.
_columns is None:
108 self.
_columns = self._getColumnView()
110 columns = property(__getColumns, doc=
"a column view of the catalog")
113 """Return the record at index key if key is an integer,
114 return a column if key is a string field name or Key,
115 or return a subset of the catalog if key is a slice
116 or boolean NumPy array.
118 if type(key)
is slice:
119 (start, stop, step) = (key.start, key.stop, key.step)
126 return self.subset(start, stop, step)
127 elif isinstance(key, np.ndarray):
128 return self.subset(key)
131 return self._getitem_(key)
139 If ``key`` is an integer, set ``catalog[key]`` to ``value``. Otherwise select column ``key``
140 and set it to ``value``.
145 return self.set(key, value)
152 if isinstance(key, slice):
163 self._insert(key, value)
171 return self._addNew()
173 def cast(self, type_, deep=False):
174 """Return a copy of the catalog with the given type, optionally
175 cloning the table and deep-copying all records if deep==True.
178 table = self.table.clone()
179 table.preallocate(len(self))
183 copy.extend(self, deep=deep)
188 Copy a catalog (default is not a deep copy).
190 return self.
cast(type(self), deep)
192 def extend(self, iterable, deep=False, mapper=None):
193 """Append all records in the given iterable to the catalog.
196 iterable ------ any Python iterable containing records
197 deep ---------- if True, the records will be deep-copied; ignored
198 if mapper is not None (that always implies True).
199 mapper -------- a SchemaMapper object used to translate records
204 if type(deep).__name__ ==
"SchemaMapper":
207 if isinstance(iterable, type(self)):
208 if mapper
is not None:
209 self._extend(iterable, mapper)
211 self._extend(iterable, deep)
213 for record
in iterable:
214 if mapper
is not None:
215 self._append(self.table.copyRecord(record, mapper))
217 self._append(self.table.copyRecord(record))
223 return lsst.afw.fits.reduceToFits(self)
225 def asAstropy(self, cls=None, copy=False, unviewable="copy"):
226 """!Return an astropy.table.Table (or subclass thereof) view into this catalog.
228 @param[in] cls Table subclass to use; None implies astropy.table.Table itself.
229 Use astropy.table.QTable to get Quantity columns.
231 @param[in] copy Whether to copy data from the LSST catalog to the astropy table.
232 Not copying is usually faster, but can keep memory from being
233 freed if columns are later removed from the Astropy view.
235 @param[in] unviewable One of the following options, indicating how to handle field types
236 (string and Flag) for which views cannot be constructed:
237 - 'copy' (default): copy only the unviewable fields.
238 - 'raise': raise ValueError if unviewable fields are present.
239 - 'skip': do not include unviewable fields in the Astropy Table.
240 This option is ignored if copy=True.
244 cls = astropy.table.Table
245 if unviewable
not in (
"copy",
"raise",
"skip"):
247 "'unviewable'=%r must be one of 'copy', 'raise', or 'skip'" % (unviewable,))
248 ps = self.getMetadata()
249 meta = ps.toOrderedDict()
if ps
is not None else None
251 items = self.schema.extract(
"*", ordered=
True)
252 for name, item
in items.items():
254 unit = item.field.getUnits()
or None
255 if key.getTypeString() ==
"String":
257 if unviewable ==
"raise":
258 raise ValueError(
"Cannot extract string "
259 "unless copy=True or unviewable='copy' or 'skip'.")
260 elif unviewable ==
"skip":
263 len(self), dtype=np.dtype((str, key.getSize())))
264 for i, record
in enumerate(self):
265 data[i] = record.get(key)
266 elif key.getTypeString() ==
"Flag":
268 if unviewable ==
"raise":
269 raise ValueError(
"Cannot extract packed bit columns "
270 "unless copy=True or unviewable='copy' or 'skip'.")
271 elif unviewable ==
"skip":
273 data = self.columns.get_bool_array(key)
274 elif key.getTypeString() ==
"Angle":
275 data = self.columns.get(key)
279 elif "Array" in key.getTypeString()
and key.isVariableLength():
281 if unviewable ==
"raise":
282 raise ValueError(
"Cannot extract variable-length array fields unless unviewable='skip'.")
283 elif unviewable ==
"skip" or unviewable ==
"copy":
286 data = self.columns.get(key)
290 astropy.table.Column(
294 description=item.field.getDoc()
297 return cls(columns, meta=meta, copy=
False)
301 This custom dir is necessary due to the custom getattr below.
302 Without it, not all of the methods available are returned with dir.
305 def recursive_get_class_dir(cls):
307 Return a set containing the names of all methods
308 for a given class *and* all of its subclasses.
312 for subcls
in cls.__bases__:
313 result |= recursive_get_class_dir(subcls)
314 result |= set(cls.__dict__.keys())
316 return sorted(set(dir(self.
columns)) | set(dir(self.table)) |
317 recursive_get_class_dir(type(self)) | set(self.__dict__.keys()))
323 if name ==
"_columns":
327 return getattr(self.table, name)
328 except AttributeError:
329 return getattr(self.
columns, name)
332 if self.isContiguous():
335 fields =
' '.join(x.field.getName()
for x
in self.schema)
336 string =
"Non-contiguous afw.Catalog of %d rows.\ncolumns: %s" % (len(self), fields)
340 return "%s\n%s" % (type(self), self)
342 Catalog.register(
"Base", BaseCatalog)
def asAstropy
Return an astropy.table.Table (or subclass thereof) view into this catalog.