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