22 from __future__
import absolute_import, division, print_function
24 from future.utils
import with_metaclass
25 from past.types
import basestring
29 from lsst.utils
import continueClass, TemplateMeta
30 from .base
import BaseRecord, BaseCatalog
31 from ..schema
import Key
40 """Extract a dictionary of {<name>: <field-value>} in which the field names
41 match the given shell-style glob pattern(s).
43 Any number of glob patterns may be passed; the result will be the union of all
44 the result of each glob considered separately.
50 The result of a call to self.schema.extract(); this will be used
51 instead of doing any new matching, and allows the pattern matching
52 to be reused to extract values from multiple records. This
53 keyword is incompatible with any position arguments and the regex,
54 sub, and ordered keyword arguments.
57 If True, fields with named subfields (e.g. points) will be split
58 into separate items in the dict; instead of {"point":
59 lsst.afw.geom.Point2I(2,3)}, for instance, you'd get {"point.x":
60 2, "point.y": 3}. Default is False.
62 regex : `str` or `re` pattern object
63 A regular expression to be used in addition to any glob patterns
64 passed as positional arguments. Note that this will be compared
65 with re.match, not re.search.
68 A replacement string (see `re.MatchObject.expand`) used to set the
69 dictionary keys of any fields matched by regex.
72 If `True`, a `collections.OrderedDict` will be returned instead of
73 a standard dict, with the order corresponding to the definition
74 order of the `Schema`. `Default is False`.
76 d = kwds.pop(
"items",
None)
77 split = kwds.pop(
"split",
False)
79 d = self.schema.extract(*patterns, **kwds).copy()
82 "Unrecognized keyword arguments for extract: %s" %
", ".join(kwds.keys()))
84 for name, schemaItem
in list(d.items()):
86 if split
and key.HAS_NAMED_SUBFIELDS:
87 for subname, subkey
in zip(key.subfields, key.subkeys):
88 d[
"%s.%s" % (name, subname)] = self.get(subkey)
91 d[name] = self.get(schemaItem.key)
95 return '\n'.join(
"%s: %s"%(x.field.getName(), self.
extract(
"*")[x.field.getName()])
99 return "%s\n%s" % (type(self), str(self))
102 class Catalog(with_metaclass(TemplateMeta, object)):
105 self.
_columns = self._getColumnView()
108 def __getColumns(self):
109 if not hasattr(self,
"_columns")
or self.
_columns is None:
110 self.
_columns = self._getColumnView()
112 columns = property(__getColumns, doc=
"a column view of the catalog")
115 """Return the record at index key if key is an integer,
116 return a column if key is a string field name or Key,
117 or return a subset of the catalog if key is a slice
118 or boolean NumPy array.
120 if type(key)
is slice:
121 (start, stop, step) = (key.start, key.stop, key.step)
128 return self.subset(start, stop, step)
129 elif isinstance(key, np.ndarray):
130 return self.subset(key)
131 elif isinstance(key, Key)
or isinstance(key, basestring):
134 return self._getitem_(key)
138 If ``key`` is an integer, set ``catalog[key]`` to ``value``. Otherwise select column ``key``
139 and set it to ``value``.
142 if isinstance(key, Key)
or isinstance(key, basestring):
145 return self.set(key, value)
149 if isinstance(key, slice):
160 self._insert(key, value)
168 return self._addNew()
170 def cast(self, type_, deep=False):
171 """Return a copy of the catalog with the given type, optionally
172 cloning the table and deep-copying all records if deep==True.
175 table = self.table.clone()
176 table.preallocate(len(self))
180 copy.extend(self, deep=deep)
185 Copy a catalog (default is not a deep copy).
187 return self.
cast(type(self), deep)
189 def extend(self, iterable, deep=False, mapper=None):
190 """Append all records in the given iterable to the catalog.
193 iterable ------ any Python iterable containing records
194 deep ---------- if True, the records will be deep-copied; ignored
195 if mapper is not None (that always implies True).
196 mapper -------- a SchemaMapper object used to translate records
201 if type(deep).__name__ ==
"SchemaMapper":
204 if isinstance(iterable, type(self)):
205 if mapper
is not None:
206 self._extend(iterable, mapper)
208 self._extend(iterable, deep)
210 for record
in iterable:
211 if mapper
is not None:
212 self._append(self.table.copyRecord(record, mapper))
214 self._append(self.table.copyRecord(record))
220 return lsst.afw.fits.reduceToFits(self)
222 def asAstropy(self, cls=None, copy=False, unviewable="copy"):
223 """!Return an astropy.table.Table (or subclass thereof) view into this catalog.
225 @param[in] cls Table subclass to use; None implies astropy.table.Table itself.
226 Use astropy.table.QTable to get Quantity columns.
228 @param[in] copy Whether to copy data from the LSST catalog to the astropy table.
229 Not copying is usually faster, but can keep memory from being
230 freed if columns are later removed from the Astropy view.
232 @param[in] unviewable One of the following options, indicating how to handle field types
233 (string and Flag) for which views cannot be constructed:
234 - 'copy' (default): copy only the unviewable fields.
235 - 'raise': raise ValueError if unviewable fields are present.
236 - 'skip': do not include unviewable fields in the Astropy Table.
237 This option is ignored if copy=True.
241 cls = astropy.table.Table
242 if unviewable
not in (
"copy",
"raise",
"skip"):
244 "'unviewable'=%r must be one of 'copy', 'raise', or 'skip'" % (unviewable,))
245 ps = self.getMetadata()
246 meta = ps.toOrderedDict()
if ps
is not None else None
248 items = self.schema.extract(
"*", ordered=
True)
249 for name, item
in items.items():
251 unit = item.field.getUnits()
or None
252 if key.getTypeString() ==
"String":
254 if unviewable ==
"raise":
255 raise ValueError(
"Cannot extract string "
256 "unless copy=True or unviewable='copy' or 'skip'.")
257 elif unviewable ==
"skip":
260 len(self), dtype=np.dtype((str, key.getSize())))
261 for i, record
in enumerate(self):
262 data[i] = record.get(key)
263 elif key.getTypeString() ==
"Flag":
265 if unviewable ==
"raise":
266 raise ValueError(
"Cannot extract packed bit columns "
267 "unless copy=True or unviewable='copy' or 'skip'.")
268 elif unviewable ==
"skip":
270 data = self.columns.get_bool_array(key)
271 elif key.getTypeString() ==
"Angle":
272 data = self.columns.get(key)
276 elif "Array" in key.getTypeString()
and key.isVariableLength():
278 if unviewable ==
"raise":
279 raise ValueError(
"Cannot extract variable-length array fields unless unviewable='skip'.")
280 elif unviewable ==
"skip" or unviewable ==
"copy":
283 data = self.columns.get(key)
287 astropy.table.Column(
291 description=item.field.getDoc()
294 return cls(columns, meta=meta, copy=
False)
298 This custom dir is necessary due to the custom getattr below.
299 Without it, not all of the methods available are returned with dir.
302 def recursive_get_class_dir(cls):
304 Return a set containing the names of all methods
305 for a given class *and* all of its subclasses.
309 for subcls
in cls.__bases__:
310 result |= recursive_get_class_dir(subcls)
311 result |= set(cls.__dict__.keys())
313 return sorted(set(dir(self.
columns)) | set(dir(self.table)) |
314 recursive_get_class_dir(type(self)) | set(self.__dict__.keys()))
320 if name ==
"_columns":
324 return getattr(self.table, name)
325 except AttributeError:
326 return getattr(self.
columns, name)
329 if self.isContiguous():
332 fields =
' '.join(x.field.getName()
for x
in self.schema)
333 string =
"Non-contiguous afw.Catalog of %d rows.\ncolumns: %s" % (len(self), fields)
337 return "%s\n%s" % (type(self), self)
339 Catalog.register(
"Base", BaseCatalog)
def asAstropy
Return an astropy.table.Table (or subclass thereof) view into this catalog.