lsst.afw  14.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
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 
26 import numpy as np
27 
28 from lsst.utils import continueClass, TemplateMeta
29 from .base import BaseRecord, BaseCatalog
30 
31 __all__ = ["Catalog"]
32 
33 
34 @continueClass
35 class BaseRecord:
36 
37  def extract(self, *patterns, **kwds):
38  """Extract a dictionary of {<name>: <field-value>} in which the field names
39  match the given shell-style glob pattern(s).
40 
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.
43 
44  Parameters
45  ----------
46 
47  items : `dict`
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.
53 
54  split : `bool`
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.
59 
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.
64 
65  sub : `str`
66  A replacement string (see `re.MatchObject.expand`) used to set the
67  dictionary keys of any fields matched by regex.
68 
69  ordered : `bool`
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`.
73  """
74  d = kwds.pop("items", None)
75  split = kwds.pop("split", False)
76  if d is None:
77  d = self.schema.extract(*patterns, **kwds).copy()
78  elif kwds:
79  raise ValueError(
80  "Unrecognized keyword arguments for extract: %s" % ", ".join(kwds.keys()))
81  # must use list because we might be adding/deleting elements
82  for name, schemaItem in list(d.items()):
83  key = schemaItem.key
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)
87  del d[name]
88  else:
89  d[name] = self.get(schemaItem.key)
90  return d
91 
92  def __str__(self):
93  return '\n'.join("%s: %s"%(x.field.getName(), self.extract("*")[x.field.getName()])
94  for x in self.schema)
95 
96  def __repr__(self):
97  return "%s\n%s" % (type(self), str(self))
98 
99 
100 class Catalog(with_metaclass(TemplateMeta, object)):
101 
102  def getColumnView(self):
103  self._columns = self._getColumnView()
104  return self._columns
105 
106  def __getColumns(self):
107  if not hasattr(self, "_columns") or self._columns is None:
108  self._columns = self._getColumnView()
109  return self._columns
110  columns = property(__getColumns, doc="a column view of the catalog")
111 
112  def __getitem__(self, key):
113  """Return the record at index key if key is an integer,
114  return a column if key is a string field name or Key,
115  or return a subset of the catalog if key is a slice
116  or boolean NumPy array.
117  """
118  if type(key) is slice:
119  (start, stop, step) = (key.start, key.stop, key.step)
120  if step is None:
121  step = 1
122  if start is None:
123  start = 0
124  if stop is None:
125  stop = len(self)
126  return self.subset(start, stop, step)
127  elif isinstance(key, np.ndarray):
128  return self.subset(key)
129  try:
130  # this works only for integer arguments (single record access)
131  return self._getitem_(key)
132  except TypeError:
133  pass
134  # when record access fails, try column access
135  return self.columns[key]
136 
137  def __setitem__(self, key, value):
138  """
139  If ``key`` is an integer, set ``catalog[key]`` to ``value``. Otherwise select column ``key``
140  and set it to ``value``.
141  """
142  self._columns = None
143  try:
144  # this works only for integer arguments (single record access)
145  return self.set(key, value)
146  except TypeError:
147  pass
148  self.columns[key] = value
149 
150  def __delitem__(self, key):
151  self._columns = None
152  if isinstance(key, slice):
153  self._delslice_(key)
154  else:
155  self._delitem_(key)
156 
157  def append(self, record):
158  self._columns = None
159  self._append(record)
160 
161  def insert(self, key, value):
162  self._columns = None
163  self._insert(key, value)
164 
165  def clear(self):
166  self._columns = None
167  self._clear()
168 
169  def addNew(self):
170  self._columns = None
171  return self._addNew()
172 
173  def cast(self, type_, deep=False):
174  """Return a copy of the catalog with the given type, optionally
175  cloning the table and deep-copying all records if deep==True.
176  """
177  if deep:
178  table = self.table.clone()
179  table.preallocate(len(self))
180  else:
181  table = self.table
182  copy = type_(table)
183  copy.extend(self, deep=deep)
184  return copy
185 
186  def copy(self, deep=False):
187  """
188  Copy a catalog (default is not a deep copy).
189  """
190  return self.cast(type(self), deep)
191 
192  def extend(self, iterable, deep=False, mapper=None):
193  """Append all records in the given iterable to the catalog.
194 
195  Arguments:
196  iterable ------ any Python iterable containing records
197  deep ---------- if True, the records will be deep-copied; ignored
198  if mapper is not None (that always implies True).
199  mapper -------- a SchemaMapper object used to translate records
200  """
201  self._columns = None
202  # We can't use isinstance here, because the SchemaMapper symbol isn't available
203  # when this code is part of a subclass of Catalog in another package.
204  if type(deep).__name__ == "SchemaMapper":
205  mapper = deep
206  deep = None
207  if isinstance(iterable, type(self)):
208  if mapper is not None:
209  self._extend(iterable, mapper)
210  else:
211  self._extend(iterable, deep)
212  else:
213  for record in iterable:
214  if mapper is not None:
215  self._append(self.table.copyRecord(record, mapper))
216  elif deep:
217  self._append(self.table.copyRecord(record))
218  else:
219  self._append(record)
220 
221  def __reduce__(self):
222  import lsst.afw.fits
223  return lsst.afw.fits.reduceToFits(self)
224 
225  def asAstropy(self, cls=None, copy=False, unviewable="copy"):
226  """!Return an astropy.table.Table (or subclass thereof) view into this catalog.
227 
228  @param[in] cls Table subclass to use; None implies astropy.table.Table itself.
229  Use astropy.table.QTable to get Quantity columns.
230 
231  @param[in] copy Whether to copy data from the LSST catalog to the astropy table.
232  Not copying is usually faster, but can keep memory from being
233  freed if columns are later removed from the Astropy view.
234 
235  @param[in] unviewable One of the following options, indicating how to handle field types
236  (string and Flag) for which views cannot be constructed:
237  - 'copy' (default): copy only the unviewable fields.
238  - 'raise': raise ValueError if unviewable fields are present.
239  - 'skip': do not include unviewable fields in the Astropy Table.
240  This option is ignored if copy=True.
241  """
242  import astropy.table
243  if cls is None:
244  cls = astropy.table.Table
245  if unviewable not in ("copy", "raise", "skip"):
246  raise ValueError(
247  "'unviewable'=%r must be one of 'copy', 'raise', or 'skip'" % (unviewable,))
248  ps = self.getMetadata()
249  meta = ps.toOrderedDict() if ps is not None else None
250  columns = []
251  items = self.schema.extract("*", ordered=True)
252  for name, item in items.items():
253  key = item.key
254  unit = item.field.getUnits() or None # use None instead of "" when empty
255  if key.getTypeString() == "String":
256  if not copy:
257  if unviewable == "raise":
258  raise ValueError("Cannot extract string "
259  "unless copy=True or unviewable='copy' or 'skip'.")
260  elif unviewable == "skip":
261  continue
262  data = np.zeros(
263  len(self), dtype=np.dtype((str, key.getSize())))
264  for i, record in enumerate(self):
265  data[i] = record.get(key)
266  elif key.getTypeString() == "Flag":
267  if not copy:
268  if unviewable == "raise":
269  raise ValueError("Cannot extract packed bit columns "
270  "unless copy=True or unviewable='copy' or 'skip'.")
271  elif unviewable == "skip":
272  continue
273  data = self.columns.get_bool_array(key)
274  elif key.getTypeString() == "Angle":
275  data = self.columns.get(key)
276  unit = "radian"
277  if copy:
278  data = data.copy()
279  elif "Array" in key.getTypeString() and key.isVariableLength():
280  # Can't get columns for variable-length array fields.
281  if unviewable == "raise":
282  raise ValueError("Cannot extract variable-length array fields unless unviewable='skip'.")
283  elif unviewable == "skip" or unviewable == "copy":
284  continue
285  else:
286  data = self.columns.get(key)
287  if copy:
288  data = data.copy()
289  columns.append(
290  astropy.table.Column(
291  data,
292  name=name,
293  unit=unit,
294  description=item.field.getDoc()
295  )
296  )
297  return cls(columns, meta=meta, copy=False)
298 
299  def __dir__(self):
300  """
301  This custom dir is necessary due to the custom getattr below.
302  Without it, not all of the methods available are returned with dir.
303  See DM-7199
304  """
305  def recursive_get_class_dir(cls):
306  """
307  Return a set containing the names of all methods
308  for a given class *and* all of its subclasses.
309  """
310  result = set()
311  if cls.__bases__:
312  for subcls in cls.__bases__:
313  result |= recursive_get_class_dir(subcls)
314  result |= set(cls.__dict__.keys())
315  return result
316  return sorted(set(dir(self.columns)) | set(dir(self.table)) |
317  recursive_get_class_dir(type(self)) | set(self.__dict__.keys()))
318 
319  def __getattr__(self, name):
320  # Catalog forwards unknown method calls to its table and column view
321  # for convenience. (Feature requested by RHL; complaints about magic
322  # should be directed to him.)
323  if name == "_columns":
324  self._columns = None
325  return None
326  try:
327  return getattr(self.table, name)
328  except AttributeError:
329  return getattr(self.columns, name)
330 
331  def __str__(self):
332  if self.isContiguous():
333  return str(self.asAstropy())
334  else:
335  fields = ' '.join(x.field.getName() for x in self.schema)
336  string = "Non-contiguous afw.Catalog of %d rows.\ncolumns: %s" % (len(self), fields)
337  return string
338 
339  def __repr__(self):
340  return "%s\n%s" % (type(self), self)
341 
342 Catalog.register("Base", BaseCatalog)
def asAstropy
Return an astropy.table.Table (or subclass thereof) view into this catalog.