lsst.afw  14.0-34-g2d9284d60+1
baseContinued.py
Go to the documentation of this file.
1 #
2 # LSST Data Management System
3 # Copyright 2017 LSST/AURA.
4 #
5 # This product includes software developed by the
6 # LSST Project (http://www.lsst.org/).
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the LSST License Statement and
19 # the GNU General Public License along with this program. If not,
20 # see <http://www.lsstcorp.org/LegalNotices/>.
21 #
22 from __future__ import absolute_import, division, print_function
23 
24 from future.utils import with_metaclass
25 from past.types import basestring
26 from builtins import zip
27 
28 import numpy as np
29 
30 from lsst.utils import continueClass, TemplateMeta
31 from .base import BaseRecord, BaseCatalog
32 from ..schema import Key
33 
34 __all__ = ["Catalog"]
35 
36 
37 @continueClass
38 class BaseRecord:
39 
40  def extract(self, *patterns, **kwds):
41  """Extract a dictionary of {<name>: <field-value>} in which the field names
42  match the given shell-style glob pattern(s).
43 
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.
46 
47  Parameters
48  ----------
49 
50  items : `dict`
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.
56 
57  split : `bool`
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.
62 
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.
67 
68  sub : `str`
69  A replacement string (see `re.MatchObject.expand`) used to set the
70  dictionary keys of any fields matched by regex.
71 
72  ordered : `bool`
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`.
76  """
77  d = kwds.pop("items", None)
78  split = kwds.pop("split", False)
79  if d is None:
80  d = self.schema.extract(*patterns, **kwds).copy()
81  elif kwds:
82  raise ValueError(
83  "Unrecognized keyword arguments for extract: %s" % ", ".join(kwds.keys()))
84  # must use list because we might be adding/deleting elements
85  for name, schemaItem in list(d.items()):
86  key = schemaItem.key
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)
90  del d[name]
91  else:
92  d[name] = self.get(schemaItem.key)
93  return d
94 
95  def __str__(self):
96  return '\n'.join("%s: %s"%(x.field.getName(), self.extract("*")[x.field.getName()])
97  for x in self.schema)
98 
99  def __repr__(self):
100  return "%s\n%s" % (type(self), str(self))
101 
102 
103 class Catalog(with_metaclass(TemplateMeta, object)):
104 
105  def getColumnView(self):
106  self._columns = self._getColumnView()
107  return self._columns
108 
109  def __getColumns(self):
110  if not hasattr(self, "_columns") or self._columns is None:
111  self._columns = self._getColumnView()
112  return self._columns
113  columns = property(__getColumns, doc="a column view of the catalog")
114 
115  def __getitem__(self, key):
116  """Return the record at index key if key is an integer,
117  return a column if key is a string field name or Key,
118  or return a subset of the catalog if key is a slice
119  or boolean NumPy array.
120  """
121  if type(key) is slice:
122  (start, stop, step) = (key.start, key.stop, key.step)
123  if step is None:
124  step = 1
125  if start is None:
126  start = 0
127  if stop is None:
128  stop = len(self)
129  return self.subset(start, stop, step)
130  elif isinstance(key, np.ndarray):
131  if key.dtype == bool:
132  return self.subset(key)
133  raise RuntimeError("Unsupported array type for indexing non-contiguous Catalog: %s" %
134  (key.dtype,))
135  elif isinstance(key, Key) or isinstance(key, basestring):
136  if not self.isContiguous():
137  if isinstance(key, basestring):
138  key = self.schema[key].asKey()
139  array = self._getitem_(key)
140  # This array doesn't share memory with the Catalog, so don't let it be modified by
141  # the user who thinks that the Catalog itself is being modified.
142  # Just be aware that this array can only be passed down to C++ as an ndarray::Array<T const>
143  # instead of an ordinary ndarray::Array<T>. If pybind isn't letting it down into C++,
144  # you may have left off the 'const' in the definition.
145  array.flags.writeable = False
146  return array
147  return self.columns[key]
148  else:
149  return self._getitem_(key)
150 
151  def __setitem__(self, key, value):
152  """
153  If ``key`` is an integer, set ``catalog[key]`` to ``value``. Otherwise select column ``key``
154  and set it to ``value``.
155  """
156  self._columns = None
157  if isinstance(key, Key) or isinstance(key, basestring):
158  self.columns[key] = value
159  else:
160  return self.set(key, value)
161 
162  def __delitem__(self, key):
163  self._columns = None
164  if isinstance(key, slice):
165  self._delslice_(key)
166  else:
167  self._delitem_(key)
168 
169  def append(self, record):
170  self._columns = None
171  self._append(record)
172 
173  def insert(self, key, value):
174  self._columns = None
175  self._insert(key, value)
176 
177  def clear(self):
178  self._columns = None
179  self._clear()
180 
181  def addNew(self):
182  self._columns = None
183  return self._addNew()
184 
185  def cast(self, type_, deep=False):
186  """Return a copy of the catalog with the given type, optionally
187  cloning the table and deep-copying all records if deep==True.
188  """
189  if deep:
190  table = self.table.clone()
191  table.preallocate(len(self))
192  else:
193  table = self.table
194  copy = type_(table)
195  copy.extend(self, deep=deep)
196  return copy
197 
198  def copy(self, deep=False):
199  """
200  Copy a catalog (default is not a deep copy).
201  """
202  return self.cast(type(self), deep)
203 
204  def extend(self, iterable, deep=False, mapper=None):
205  """Append all records in the given iterable to the catalog.
206 
207  Arguments:
208  iterable ------ any Python iterable containing records
209  deep ---------- if True, the records will be deep-copied; ignored
210  if mapper is not None (that always implies True).
211  mapper -------- a SchemaMapper object used to translate records
212  """
213  self._columns = None
214  # We can't use isinstance here, because the SchemaMapper symbol isn't available
215  # when this code is part of a subclass of Catalog in another package.
216  if type(deep).__name__ == "SchemaMapper":
217  mapper = deep
218  deep = None
219  if isinstance(iterable, type(self)):
220  if mapper is not None:
221  self._extend(iterable, mapper)
222  else:
223  self._extend(iterable, deep)
224  else:
225  for record in iterable:
226  if mapper is not None:
227  self._append(self.table.copyRecord(record, mapper))
228  elif deep:
229  self._append(self.table.copyRecord(record))
230  else:
231  self._append(record)
232 
233  def __reduce__(self):
234  import lsst.afw.fits
235  return lsst.afw.fits.reduceToFits(self)
236 
237  def asAstropy(self, cls=None, copy=False, unviewable="copy"):
238  """!Return an astropy.table.Table (or subclass thereof) view into this catalog.
239 
240  @param[in] cls Table subclass to use; None implies astropy.table.Table itself.
241  Use astropy.table.QTable to get Quantity columns.
242 
243  @param[in] copy Whether to copy data from the LSST catalog to the astropy table.
244  Not copying is usually faster, but can keep memory from being
245  freed if columns are later removed from the Astropy view.
246 
247  @param[in] unviewable One of the following options, indicating how to handle field types
248  (string and Flag) for which views cannot be constructed:
249  - 'copy' (default): copy only the unviewable fields.
250  - 'raise': raise ValueError if unviewable fields are present.
251  - 'skip': do not include unviewable fields in the Astropy Table.
252  This option is ignored if copy=True.
253  """
254  import astropy.table
255  if cls is None:
256  cls = astropy.table.Table
257  if unviewable not in ("copy", "raise", "skip"):
258  raise ValueError(
259  "'unviewable'=%r must be one of 'copy', 'raise', or 'skip'" % (unviewable,))
260  ps = self.getMetadata()
261  meta = ps.toOrderedDict() if ps is not None else None
262  columns = []
263  items = self.schema.extract("*", ordered=True)
264  for name, item in items.items():
265  key = item.key
266  unit = item.field.getUnits() or None # use None instead of "" when empty
267  if key.getTypeString() == "String":
268  if not copy:
269  if unviewable == "raise":
270  raise ValueError("Cannot extract string "
271  "unless copy=True or unviewable='copy' or 'skip'.")
272  elif unviewable == "skip":
273  continue
274  data = np.zeros(
275  len(self), dtype=np.dtype((str, key.getSize())))
276  for i, record in enumerate(self):
277  data[i] = record.get(key)
278  elif key.getTypeString() == "Flag":
279  if not copy:
280  if unviewable == "raise":
281  raise ValueError("Cannot extract packed bit columns "
282  "unless copy=True or unviewable='copy' or 'skip'.")
283  elif unviewable == "skip":
284  continue
285  data = self.columns.get_bool_array(key)
286  elif key.getTypeString() == "Angle":
287  data = self.columns.get(key)
288  unit = "radian"
289  if copy:
290  data = data.copy()
291  elif "Array" in key.getTypeString() and key.isVariableLength():
292  # Can't get columns for variable-length array fields.
293  if unviewable == "raise":
294  raise ValueError("Cannot extract variable-length array fields unless unviewable='skip'.")
295  elif unviewable == "skip" or unviewable == "copy":
296  continue
297  else:
298  data = self.columns.get(key)
299  if copy:
300  data = data.copy()
301  columns.append(
302  astropy.table.Column(
303  data,
304  name=name,
305  unit=unit,
306  description=item.field.getDoc()
307  )
308  )
309  return cls(columns, meta=meta, copy=False)
310 
311  def __dir__(self):
312  """
313  This custom dir is necessary due to the custom getattr below.
314  Without it, not all of the methods available are returned with dir.
315  See DM-7199
316  """
317  def recursive_get_class_dir(cls):
318  """
319  Return a set containing the names of all methods
320  for a given class *and* all of its subclasses.
321  """
322  result = set()
323  if cls.__bases__:
324  for subcls in cls.__bases__:
325  result |= recursive_get_class_dir(subcls)
326  result |= set(cls.__dict__.keys())
327  return result
328  return sorted(set(dir(self.columns)) | set(dir(self.table)) |
329  recursive_get_class_dir(type(self)) | set(self.__dict__.keys()))
330 
331  def __getattr__(self, name):
332  # Catalog forwards unknown method calls to its table and column view
333  # for convenience. (Feature requested by RHL; complaints about magic
334  # should be directed to him.)
335  if name == "_columns":
336  self._columns = None
337  return None
338  try:
339  return getattr(self.table, name)
340  except AttributeError:
341  return getattr(self.columns, name)
342 
343  def __str__(self):
344  if self.isContiguous():
345  return str(self.asAstropy())
346  else:
347  fields = ' '.join(x.field.getName() for x in self.schema)
348  string = "Non-contiguous afw.Catalog of %d rows.\ncolumns: %s" % (len(self), fields)
349  return string
350 
351  def __repr__(self):
352  return "%s\n%s" % (type(self), self)
353 
354 Catalog.register("Base", BaseCatalog)
def asAstropy(self, cls=None, copy=False, unviewable="copy")
Return an astropy.table.Table (or subclass thereof) view into this catalog.
def extend(self, iterable, deep=False, mapper=None)