lsst.afw  14.0-69-ge506bfb5f
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 # noqa F811
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 __repr__(self):
96  return "%s\n%s" % (type(self), str(self))
97 
98 
99 class Catalog(with_metaclass(TemplateMeta, object)):
100 
101  def getColumnView(self):
102  self._columns = self._getColumnView()
103  return self._columns
104 
105  def __getColumns(self):
106  if not hasattr(self, "_columns") or self._columns is None:
107  self._columns = self._getColumnView()
108  return self._columns
109  columns = property(__getColumns, doc="a column view of the catalog")
110 
111  def __getitem__(self, key):
112  """Return the record at index key if key is an integer,
113  return a column if key is a string field name or Key,
114  or return a subset of the catalog if key is a slice
115  or boolean NumPy array.
116  """
117  if type(key) is slice:
118  (start, stop, step) = (key.start, key.stop, key.step)
119  if step is None:
120  step = 1
121  if start is None:
122  start = 0
123  if stop is None:
124  stop = len(self)
125  return self.subset(start, stop, step)
126  elif isinstance(key, np.ndarray):
127  if key.dtype == bool:
128  return self.subset(key)
129  raise RuntimeError("Unsupported array type for indexing non-contiguous Catalog: %s" %
130  (key.dtype,))
131  elif isinstance(key, Key) or isinstance(key, basestring):
132  if not self.isContiguous():
133  if isinstance(key, basestring):
134  key = self.schema[key].asKey()
135  array = self._getitem_(key)
136  # This array doesn't share memory with the Catalog, so don't let it be modified by
137  # the user who thinks that the Catalog itself is being modified.
138  # Just be aware that this array can only be passed down to C++ as an ndarray::Array<T const>
139  # instead of an ordinary ndarray::Array<T>. If pybind isn't letting it down into C++,
140  # you may have left off the 'const' in the definition.
141  array.flags.writeable = False
142  return array
143  return self.columns[key]
144  else:
145  return self._getitem_(key)
146 
147  def __setitem__(self, key, value):
148  """
149  If ``key`` is an integer, set ``catalog[key]`` to ``value``. Otherwise select column ``key``
150  and set it to ``value``.
151  """
152  self._columns = None
153  if isinstance(key, Key) or isinstance(key, basestring):
154  self.columns[key] = value
155  else:
156  return self.set(key, value)
157 
158  def __delitem__(self, key):
159  self._columns = None
160  if isinstance(key, slice):
161  self._delslice_(key)
162  else:
163  self._delitem_(key)
164 
165  def append(self, record):
166  self._columns = None
167  self._append(record)
168 
169  def insert(self, key, value):
170  self._columns = None
171  self._insert(key, value)
172 
173  def clear(self):
174  self._columns = None
175  self._clear()
176 
177  def addNew(self):
178  self._columns = None
179  return self._addNew()
180 
181  def cast(self, type_, deep=False):
182  """Return a copy of the catalog with the given type, optionally
183  cloning the table and deep-copying all records if deep==True.
184  """
185  if deep:
186  table = self.table.clone()
187  table.preallocate(len(self))
188  else:
189  table = self.table
190  copy = type_(table)
191  copy.extend(self, deep=deep)
192  return copy
193 
194  def copy(self, deep=False):
195  """
196  Copy a catalog (default is not a deep copy).
197  """
198  return self.cast(type(self), deep)
199 
200  def extend(self, iterable, deep=False, mapper=None):
201  """Append all records in the given iterable to the catalog.
202 
203  Arguments:
204  iterable ------ any Python iterable containing records
205  deep ---------- if True, the records will be deep-copied; ignored
206  if mapper is not None (that always implies True).
207  mapper -------- a SchemaMapper object used to translate records
208  """
209  self._columns = None
210  # We can't use isinstance here, because the SchemaMapper symbol isn't available
211  # when this code is part of a subclass of Catalog in another package.
212  if type(deep).__name__ == "SchemaMapper":
213  mapper = deep
214  deep = None
215  if isinstance(iterable, type(self)):
216  if mapper is not None:
217  self._extend(iterable, mapper)
218  else:
219  self._extend(iterable, deep)
220  else:
221  for record in iterable:
222  if mapper is not None:
223  self._append(self.table.copyRecord(record, mapper))
224  elif deep:
225  self._append(self.table.copyRecord(record))
226  else:
227  self._append(record)
228 
229  def __reduce__(self):
230  import lsst.afw.fits
231  return lsst.afw.fits.reduceToFits(self)
232 
233  def asAstropy(self, cls=None, copy=False, unviewable="copy"):
234  """!Return an astropy.table.Table (or subclass thereof) view into this catalog.
235 
236  @param[in] cls Table subclass to use; None implies astropy.table.Table itself.
237  Use astropy.table.QTable to get Quantity columns.
238 
239  @param[in] copy Whether to copy data from the LSST catalog to the astropy table.
240  Not copying is usually faster, but can keep memory from being
241  freed if columns are later removed from the Astropy view.
242 
243  @param[in] unviewable One of the following options, indicating how to handle field types
244  (string and Flag) for which views cannot be constructed:
245  - 'copy' (default): copy only the unviewable fields.
246  - 'raise': raise ValueError if unviewable fields are present.
247  - 'skip': do not include unviewable fields in the Astropy Table.
248  This option is ignored if copy=True.
249  """
250  import astropy.table
251  if cls is None:
252  cls = astropy.table.Table
253  if unviewable not in ("copy", "raise", "skip"):
254  raise ValueError(
255  "'unviewable'=%r must be one of 'copy', 'raise', or 'skip'" % (unviewable,))
256  ps = self.getMetadata()
257  meta = ps.toOrderedDict() if ps is not None else None
258  columns = []
259  items = self.schema.extract("*", ordered=True)
260  for name, item in items.items():
261  key = item.key
262  unit = item.field.getUnits() or None # use None instead of "" when empty
263  if key.getTypeString() == "String":
264  if not copy:
265  if unviewable == "raise":
266  raise ValueError("Cannot extract string "
267  "unless copy=True or unviewable='copy' or 'skip'.")
268  elif unviewable == "skip":
269  continue
270  data = np.zeros(
271  len(self), dtype=np.dtype((str, key.getSize())))
272  for i, record in enumerate(self):
273  data[i] = record.get(key)
274  elif key.getTypeString() == "Flag":
275  if not copy:
276  if unviewable == "raise":
277  raise ValueError("Cannot extract packed bit columns "
278  "unless copy=True or unviewable='copy' or 'skip'.")
279  elif unviewable == "skip":
280  continue
281  data = self.columns.get_bool_array(key)
282  elif key.getTypeString() == "Angle":
283  data = self.columns.get(key)
284  unit = "radian"
285  if copy:
286  data = data.copy()
287  elif "Array" in key.getTypeString() and key.isVariableLength():
288  # Can't get columns for variable-length array fields.
289  if unviewable == "raise":
290  raise ValueError("Cannot extract variable-length array fields unless unviewable='skip'.")
291  elif unviewable == "skip" or unviewable == "copy":
292  continue
293  else:
294  data = self.columns.get(key)
295  if copy:
296  data = data.copy()
297  columns.append(
298  astropy.table.Column(
299  data,
300  name=name,
301  unit=unit,
302  description=item.field.getDoc()
303  )
304  )
305  return cls(columns, meta=meta, copy=False)
306 
307  def __dir__(self):
308  """
309  This custom dir is necessary due to the custom getattr below.
310  Without it, not all of the methods available are returned with dir.
311  See DM-7199
312  """
313  def recursive_get_class_dir(cls):
314  """
315  Return a set containing the names of all methods
316  for a given class *and* all of its subclasses.
317  """
318  result = set()
319  if cls.__bases__:
320  for subcls in cls.__bases__:
321  result |= recursive_get_class_dir(subcls)
322  result |= set(cls.__dict__.keys())
323  return result
324  return sorted(set(dir(self.columns)) | set(dir(self.table)) |
325  recursive_get_class_dir(type(self)) | set(self.__dict__.keys()))
326 
327  def __getattr__(self, name):
328  # Catalog forwards unknown method calls to its table and column view
329  # for convenience. (Feature requested by RHL; complaints about magic
330  # should be directed to him.)
331  if name == "_columns":
332  self._columns = None
333  return None
334  try:
335  return getattr(self.table, name)
336  except AttributeError:
337  return getattr(self.columns, name)
338 
339  def __str__(self):
340  if self.isContiguous():
341  return str(self.asAstropy())
342  else:
343  fields = ' '.join(x.field.getName() for x in self.schema)
344  string = "Non-contiguous afw.Catalog of %d rows.\ncolumns: %s" % (len(self), fields)
345  return string
346 
347  def __repr__(self):
348  return "%s\n%s" % (type(self), self)
349 
350 
351 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)
daf::base::PropertyList * list
Definition: fits.cc:819
daf::base::PropertySet * set
Definition: fits.cc:818