22 from __future__
import absolute_import, division, print_function
26 from future.utils
import with_metaclass
30 from lsst.utils
import continueClass, TemplateMeta
31 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 class Catalog(with_metaclass(TemplateMeta, object)):
96 self.
_columns = self._getColumnView()
99 def __getColumns(self):
100 if not hasattr(self,
"_columns")
or self.
_columns is None:
101 self.
_columns = self._getColumnView()
103 columns = property(__getColumns, doc=
"a column view of the catalog")
106 """Return the record at index key if key is an integer,
107 return a column if key is a string field name or Key,
108 or return a subset of the catalog if key is a slice
109 or boolean NumPy array.
111 if type(key)
is slice:
112 (start, stop, step) = (key.start, key.stop, key.step)
119 return self.subset(start, stop, step)
120 elif isinstance(key, np.ndarray):
121 return self.subset(key)
124 return self._getitem_(key)
132 If ``key`` is an integer, set ``catalog[key]`` to ``value``. Otherwise select column ``key``
133 and set it to ``value``.
138 return self.set(key, value)
145 if isinstance(key, slice):
156 self._insert(key, value)
164 return self._addNew()
166 def cast(self, type_, deep=False):
167 """Return a copy of the catalog with the given type, optionally
168 cloning the table and deep-copying all records if deep==True.
171 table = self.table.clone()
172 table.preallocate(len(self))
176 copy.extend(self, deep=deep)
181 Copy a catalog (default is not a deep copy).
183 return self.
cast(type(self), deep)
185 def extend(self, iterable, deep=False, mapper=None):
186 """Append all records in the given iterable to the catalog.
189 iterable ------ any Python iterable containing records
190 deep ---------- if True, the records will be deep-copied; ignored
191 if mapper is not None (that always implies True).
192 mapper -------- a SchemaMapper object used to translate records
197 if type(deep).__name__ ==
"SchemaMapper":
200 if isinstance(iterable, type(self)):
201 if mapper
is not None:
202 self._extend(iterable, mapper)
204 self._extend(iterable, deep)
206 for record
in iterable:
207 if mapper
is not None:
208 self._append(self.table.copyRecord(record, mapper))
210 self._append(self.table.copyRecord(record))
216 return lsst.afw.fits.reduceToFits(self)
218 def asAstropy(self, cls=None, copy=False, unviewable="copy"):
219 """!Return an astropy.table.Table (or subclass thereof) view into this catalog.
221 @param[in] cls Table subclass to use; None implies astropy.table.Table itself.
222 Use astropy.table.QTable to get Quantity columns.
224 @param[in] copy Whether to copy data from the LSST catalog to the astropy table.
225 Not copying is usually faster, but can keep memory from being
226 freed if columns are later removed from the Astropy view.
228 @param[in] unviewable One of the following options, indicating how to handle field types
229 (string and Flag) for which views cannot be constructed:
230 - 'copy' (default): copy only the unviewable fields.
231 - 'raise': raise ValueError if unviewable fields are present.
232 - 'skip': do not include unviewable fields in the Astropy Table.
233 This option is ignored if copy=True.
237 cls = astropy.table.Table
238 if unviewable
not in (
"copy",
"raise",
"skip"):
240 "'unviewable'=%r must be one of 'copy', 'raise', or 'skip'" % (unviewable,))
241 ps = self.getMetadata()
242 meta = ps.toOrderedDict()
if ps
is not None else None
244 items = self.schema.extract(
"*", ordered=
True)
245 for name, item
in items.items():
247 unit = item.field.getUnits()
or None
248 if key.getTypeString() ==
"String":
250 if unviewable ==
"raise":
251 raise ValueError(
"Cannot extract string "
252 "unless copy=True or unviewable='copy' or 'skip'.")
253 elif unviewable ==
"skip":
256 len(self), dtype=np.dtype((str, key.getSize())))
257 for i, record
in enumerate(self):
258 data[i] = record.get(key)
259 elif key.getTypeString() ==
"Flag":
261 if unviewable ==
"raise":
262 raise ValueError(
"Cannot extract packed bit columns "
263 "unless copy=True or unviewable='copy' or 'skip'.")
264 elif unviewable ==
"skip":
266 data = self.columns.get_bool_array(key)
267 elif key.getTypeString() ==
"Angle":
268 data = self.columns.get(key)
273 data = self.columns.get(key)
277 astropy.table.Column(
281 description=item.field.getDoc()
284 return cls(columns, meta=meta, copy=
False)
288 This custom dir is necessary due to the custom getattr below.
289 Without it, not all of the methods available are returned with dir.
292 def recursive_get_class_dir(cls):
294 Return a set containing the names of all methods
295 for a given class *and* all of its subclasses.
299 for subcls
in cls.__bases__:
300 result |= recursive_get_class_dir(subcls)
301 result |= set(cls.__dict__.keys())
303 return sorted(set(dir(self.
columns)) | set(dir(self.table)) |
304 recursive_get_class_dir(type(self)) | set(self.__dict__.keys()))
310 if name ==
"_columns":
314 return getattr(self.table, name)
315 except AttributeError:
316 return getattr(self.
columns, name)
319 Catalog.register(
"Base", BaseCatalog)
def asAstropy
Return an astropy.table.Table (or subclass thereof) view into this catalog.