lsst.afw  14.0-17-gfc02bf727
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 
27 import numpy as np
28 
29 from lsst.utils import continueClass, TemplateMeta
30 from .base import BaseRecord, BaseCatalog
31 from ..schema import Key
32 
33 __all__ = ["Catalog"]
34 
35 
36 @continueClass
37 class BaseRecord:
38 
39  def extract(self, *patterns, **kwds):
40  """Extract a dictionary of {<name>: <field-value>} in which the field names
41  match the given shell-style glob pattern(s).
42 
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.
45 
46  Parameters
47  ----------
48 
49  items : `dict`
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.
55 
56  split : `bool`
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.
61 
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.
66 
67  sub : `str`
68  A replacement string (see `re.MatchObject.expand`) used to set the
69  dictionary keys of any fields matched by regex.
70 
71  ordered : `bool`
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`.
75  """
76  d = kwds.pop("items", None)
77  split = kwds.pop("split", False)
78  if d is None:
79  d = self.schema.extract(*patterns, **kwds).copy()
80  elif kwds:
81  raise ValueError(
82  "Unrecognized keyword arguments for extract: %s" % ", ".join(kwds.keys()))
83  # must use list because we might be adding/deleting elements
84  for name, schemaItem in list(d.items()):
85  key = schemaItem.key
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)
89  del d[name]
90  else:
91  d[name] = self.get(schemaItem.key)
92  return d
93 
94  def __str__(self):
95  return '\n'.join("%s: %s"%(x.field.getName(), self.extract("*")[x.field.getName()])
96  for x in self.schema)
97 
98  def __repr__(self):
99  return "%s\n%s" % (type(self), str(self))
100 
101 
102 class Catalog(with_metaclass(TemplateMeta, object)):
103 
104  def getColumnView(self):
105  self._columns = self._getColumnView()
106  return self._columns
107 
108  def __getColumns(self):
109  if not hasattr(self, "_columns") or self._columns is None:
110  self._columns = self._getColumnView()
111  return self._columns
112  columns = property(__getColumns, doc="a column view of the catalog")
113 
114  def __getitem__(self, key):
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.
119  """
120  if type(key) is slice:
121  (start, stop, step) = (key.start, key.stop, key.step)
122  if step is None:
123  step = 1
124  if start is None:
125  start = 0
126  if stop is None:
127  stop = len(self)
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):
132  return self.columns[key]
133  else:
134  return self._getitem_(key)
135 
136  def __setitem__(self, key, value):
137  """
138  If ``key`` is an integer, set ``catalog[key]`` to ``value``. Otherwise select column ``key``
139  and set it to ``value``.
140  """
141  self._columns = None
142  if isinstance(key, Key) or isinstance(key, basestring):
143  self.columns[key] = value
144  else:
145  return self.set(key, value)
146 
147  def __delitem__(self, key):
148  self._columns = None
149  if isinstance(key, slice):
150  self._delslice_(key)
151  else:
152  self._delitem_(key)
153 
154  def append(self, record):
155  self._columns = None
156  self._append(record)
157 
158  def insert(self, key, value):
159  self._columns = None
160  self._insert(key, value)
161 
162  def clear(self):
163  self._columns = None
164  self._clear()
165 
166  def addNew(self):
167  self._columns = None
168  return self._addNew()
169 
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.
173  """
174  if deep:
175  table = self.table.clone()
176  table.preallocate(len(self))
177  else:
178  table = self.table
179  copy = type_(table)
180  copy.extend(self, deep=deep)
181  return copy
182 
183  def copy(self, deep=False):
184  """
185  Copy a catalog (default is not a deep copy).
186  """
187  return self.cast(type(self), deep)
188 
189  def extend(self, iterable, deep=False, mapper=None):
190  """Append all records in the given iterable to the catalog.
191 
192  Arguments:
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
197  """
198  self._columns = None
199  # We can't use isinstance here, because the SchemaMapper symbol isn't available
200  # when this code is part of a subclass of Catalog in another package.
201  if type(deep).__name__ == "SchemaMapper":
202  mapper = deep
203  deep = None
204  if isinstance(iterable, type(self)):
205  if mapper is not None:
206  self._extend(iterable, mapper)
207  else:
208  self._extend(iterable, deep)
209  else:
210  for record in iterable:
211  if mapper is not None:
212  self._append(self.table.copyRecord(record, mapper))
213  elif deep:
214  self._append(self.table.copyRecord(record))
215  else:
216  self._append(record)
217 
218  def __reduce__(self):
219  import lsst.afw.fits
220  return lsst.afw.fits.reduceToFits(self)
221 
222  def asAstropy(self, cls=None, copy=False, unviewable="copy"):
223  """!Return an astropy.table.Table (or subclass thereof) view into this catalog.
224 
225  @param[in] cls Table subclass to use; None implies astropy.table.Table itself.
226  Use astropy.table.QTable to get Quantity columns.
227 
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.
231 
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.
238  """
239  import astropy.table
240  if cls is None:
241  cls = astropy.table.Table
242  if unviewable not in ("copy", "raise", "skip"):
243  raise ValueError(
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
247  columns = []
248  items = self.schema.extract("*", ordered=True)
249  for name, item in items.items():
250  key = item.key
251  unit = item.field.getUnits() or None # use None instead of "" when empty
252  if key.getTypeString() == "String":
253  if not copy:
254  if unviewable == "raise":
255  raise ValueError("Cannot extract string "
256  "unless copy=True or unviewable='copy' or 'skip'.")
257  elif unviewable == "skip":
258  continue
259  data = np.zeros(
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":
264  if not copy:
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":
269  continue
270  data = self.columns.get_bool_array(key)
271  elif key.getTypeString() == "Angle":
272  data = self.columns.get(key)
273  unit = "radian"
274  if copy:
275  data = data.copy()
276  elif "Array" in key.getTypeString() and key.isVariableLength():
277  # Can't get columns for variable-length array fields.
278  if unviewable == "raise":
279  raise ValueError("Cannot extract variable-length array fields unless unviewable='skip'.")
280  elif unviewable == "skip" or unviewable == "copy":
281  continue
282  else:
283  data = self.columns.get(key)
284  if copy:
285  data = data.copy()
286  columns.append(
287  astropy.table.Column(
288  data,
289  name=name,
290  unit=unit,
291  description=item.field.getDoc()
292  )
293  )
294  return cls(columns, meta=meta, copy=False)
295 
296  def __dir__(self):
297  """
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.
300  See DM-7199
301  """
302  def recursive_get_class_dir(cls):
303  """
304  Return a set containing the names of all methods
305  for a given class *and* all of its subclasses.
306  """
307  result = set()
308  if cls.__bases__:
309  for subcls in cls.__bases__:
310  result |= recursive_get_class_dir(subcls)
311  result |= set(cls.__dict__.keys())
312  return result
313  return sorted(set(dir(self.columns)) | set(dir(self.table)) |
314  recursive_get_class_dir(type(self)) | set(self.__dict__.keys()))
315 
316  def __getattr__(self, name):
317  # Catalog forwards unknown method calls to its table and column view
318  # for convenience. (Feature requested by RHL; complaints about magic
319  # should be directed to him.)
320  if name == "_columns":
321  self._columns = None
322  return None
323  try:
324  return getattr(self.table, name)
325  except AttributeError:
326  return getattr(self.columns, name)
327 
328  def __str__(self):
329  if self.isContiguous():
330  return str(self.asAstropy())
331  else:
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)
334  return string
335 
336  def __repr__(self):
337  return "%s\n%s" % (type(self), self)
338 
339 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)