23 from lsst.utils import continueClass, TemplateMeta
24 from ._table
import BaseRecord, BaseCatalog
25 from ._schema
import Key
35 """Extract a dictionary of {<name>: <field-value>} in which the field names 36 match the given shell-style glob pattern(s). 38 Any number of glob patterns may be passed; the result will be the union of all 39 the result of each glob considered separately. 44 The result of a call to self.schema.extract(); this will be used 45 instead of doing any new matching, and allows the pattern matching 46 to be reused to extract values from multiple records. This 47 keyword is incompatible with any position arguments and the regex, 48 sub, and ordered keyword arguments. 50 If `True`, fields with named subfields (e.g. points) will be split 51 into separate items in the dict; instead of {"point": 52 lsst.geom.Point2I(2,3)}, for instance, you'd get {"point.x": 53 2, "point.y": 3}. Default is `False`. 54 regex : `str` or `re` pattern object 55 A regular expression to be used in addition to any glob patterns 56 passed as positional arguments. Note that this will be compared 57 with re.match, not re.search. 59 A replacement string (see `re.MatchObject.expand`) used to set the 60 dictionary keys of any fields matched by regex. 62 If `True`, a `collections.OrderedDict` will be returned instead of 63 a standard dict, with the order corresponding to the definition 64 order of the `Schema`. Default is `False`. 66 d = kwds.pop(
"items",
None)
67 split = kwds.pop(
"split",
False)
69 d = self.schema.
extract(*patterns, **kwds).copy()
72 "Unrecognized keyword arguments for extract: %s" %
", ".join(kwds.keys()))
74 for name, schemaItem
in list(d.items()):
76 if split
and key.HAS_NAMED_SUBFIELDS:
77 for subname, subkey
in zip(key.subfields, key.subkeys):
78 d[
"%s.%s" % (name, subname)] = self.get(subkey)
81 d[name] = self.get(schemaItem.key)
85 return "%s\n%s" % (
type(self), str(self))
91 self.
_columns = self._getColumnView()
94 def __getColumns(self):
95 if not hasattr(self,
"_columns")
or self.
_columns is None:
96 self.
_columns = self._getColumnView()
98 columns = property(__getColumns, doc=
"a column view of the catalog")
101 """Return the record at index key if key is an integer, 102 return a column if `key` is a string field name or Key, 103 or return a subset of the catalog if key is a slice 104 or boolean NumPy array. 106 if type(key)
is slice:
107 (start, stop, step) = (key.start, key.stop, key.step)
114 return self.subset(start, stop, step)
115 elif isinstance(key, np.ndarray):
116 if key.dtype == bool:
117 return self.subset(key)
118 raise RuntimeError(
"Unsupported array type for indexing non-contiguous Catalog: %s" %
120 elif isinstance(key, Key)
or isinstance(key, str):
121 if not self.isContiguous():
122 if isinstance(key, str):
123 key = self.schema[key].asKey()
124 array = self._getitem_(key)
130 array.flags.writeable =
False 134 return self._getitem_(key)
137 """If ``key`` is an integer, set ``catalog[key]`` to 138 ``value``. Otherwise select column ``key`` and set it to 142 if isinstance(key, Key)
or isinstance(key, str):
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. 176 Type of catalog to return. 177 deep : `bool`, optional 178 If `True`, clone the table and deep copy all records. 183 Copy of catalog with the requested type. 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). 200 def extend(self, iterable, deep=False, mapper=None):
201 """Append all records in the given iterable to the catalog. 206 Any Python iterable containing records. 207 deep : `bool`, optional 208 If `True`, the records will be deep-copied; ignored if 209 mapper is not `None` (that always implies `True`). 210 mapper : `lsst.afw.table.schemaMapper.SchemaMapper`, optional 211 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. 243 Table subclass to use; `None` implies `astropy.table.Table` 244 itself. Use `astropy.table.QTable` to get Quantity columns. 245 copy : bool, optional 246 If `True`, copy data from the LSST catalog to the astropy 247 table. Not copying is usually faster, but can keep memory 248 from being freed if columns are later removed from the 250 unviewable : `str`, optional 251 One of the following options (which is ignored if 252 copy=`True` ), indicating how to handle field types (`str` 253 and `Flag`) for which views cannot be constructed: 254 - 'copy' (default): copy only the unviewable fields. 255 - 'raise': raise ValueError if unviewable fields are present. 256 - 'skip': do not include unviewable fields in the Astropy Table. 260 cls : `astropy.table.Table` 261 Astropy view into the catalog. 266 Raised if the `unviewable` option is not a known value, or 267 if the option is 'raise' and an uncopyable field is found. 272 cls = astropy.table.Table
273 if unviewable
not in (
"copy",
"raise",
"skip"):
275 "'unviewable'=%r must be one of 'copy', 'raise', or 'skip'" % (unviewable,))
276 ps = self.getMetadata()
277 meta = ps.toOrderedDict()
if ps
is not None else None 279 items = self.schema.extract(
"*", ordered=
True)
280 for name, item
in items.items():
282 unit = item.field.getUnits()
or None 283 if key.getTypeString() ==
"String":
285 if unviewable ==
"raise":
286 raise ValueError(
"Cannot extract string " 287 "unless copy=True or unviewable='copy' or 'skip'.")
288 elif unviewable ==
"skip":
291 len(self), dtype=np.dtype((str, key.getSize())))
292 for i, record
in enumerate(self):
293 data[i] = record.get(key)
294 elif key.getTypeString() ==
"Flag":
296 if unviewable ==
"raise":
297 raise ValueError(
"Cannot extract packed bit columns " 298 "unless copy=True or unviewable='copy' or 'skip'.")
299 elif unviewable ==
"skip":
301 data = self.
columns.get_bool_array(key)
302 elif key.getTypeString() ==
"Angle":
307 elif "Array" in key.getTypeString()
and key.isVariableLength():
309 if unviewable ==
"raise":
310 raise ValueError(
"Cannot extract variable-length array fields unless unviewable='skip'.")
311 elif unviewable ==
"skip" or unviewable ==
"copy":
318 astropy.table.Column(
322 description=item.field.getDoc()
325 return cls(columns, meta=meta, copy=
False)
329 This custom dir is necessary due to the custom getattr below. 330 Without it, not all of the methods available are returned with dir. 333 def recursive_get_class_dir(cls):
335 Return a set containing the names of all methods 336 for a given class *and* all of its subclasses. 340 for subcls
in cls.__bases__:
341 result |= recursive_get_class_dir(subcls)
342 result |=
set(cls.__dict__.
keys())
344 return sorted(
set(dir(self.
columns)) |
set(dir(self.table)) |
345 recursive_get_class_dir(
type(self)) |
set(self.__dict__.
keys()))
351 if name ==
"_columns":
355 return getattr(self.table, name)
356 except AttributeError:
357 return getattr(self.
columns, name)
360 if self.isContiguous():
363 fields =
' '.join(x.field.getName()
for x
in self.schema)
364 string =
"Non-contiguous afw.Catalog of %d rows.\ncolumns: %s" % (len(self), fields)
368 return "%s\n%s" % (
type(self), self)
371 Catalog.register(
"Base", BaseCatalog)
def extract(self, patterns, kwds)
def __getattr__(self, name)
def copy(self, deep=False)
def __setitem__(self, key, value)
def extend(self, iterable, deep=False, mapper=None)
def insert(self, key, value)
daf::base::PropertySet * set
def asAstropy(self, cls=None, copy=False, unviewable="copy")
def __getitem__(self, key)
def __delitem__(self, key)
def cast(self, type_, deep=False)
daf::base::PropertyList * list