lsst.afw  14.0-38-g278b05818
baseColumnViewContinued.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__ = [] # importing this module adds methods to BaseColumnView
25 
26 from past.builtins import basestring
27 
28 import numpy as np
29 
30 from lsst.utils import continueClass
31 from ..schema import KeyFlag
32 from .baseColumnView import _BaseColumnViewBase
33 
34 # We can't call this "BaseColumnView" because that's the typedef for
35 # "ColumnViewT<BaseRecord>". This is just a mostly-invisible implementation
36 # base class, so we use the same naming convention we use for those.
37 
38 
39 @continueClass
41 
42  def getBits(self, keys=None):
43  """Get the bits associated with the specified keys
44 
45  Unlike the C++ version, each key may be a field name or a key,
46  and if keys is None then all bits are returned.
47  """
48  if keys is None:
49  return self.getAllBits()
50  arg = []
51  for k in keys:
52  if isinstance(k, basestring):
53  arg.append(self.schema.find(k).key)
54  else:
55  arg.append(k)
56  return self._getBits(arg)
57 
58  def __getitem__(self, key):
59  """Get a column view; key may be a key object or the name of a field.
60  """
61  if isinstance(key, basestring):
62  keyobj = self.schema.find(key).key
63  else:
64  keyobj = key
65  return self._basicget(keyobj)
66 
67  get = __getitem__
68 
69  def __setitem__(self, key, value):
70  """Set a full column to an array or scalar; key may be a key object or
71  the name of a field.
72  """
73  self.get(key)[:] = value
74 
75  set = __setitem__
76 
77  def get_bool_array(self, key):
78  """Get the value of a flag column as a boolean array; key must be a
79  key object or the name of a field.
80  """
81  if isinstance(key, KeyFlag):
82  return self[key]
83  raise TypeError("key={} not an lsst.afw.table.KeyFlag".format(key))
84 
85  def extract(self, *patterns, **kwds):
86  """Extract a dictionary of {<name>: <column-array>} in which the field
87  names match the given shell-style glob pattern(s).
88 
89  Any number of glob patterns may be passed (including none); the result
90  will be the union of all the result of each glob considered
91  separately.
92 
93  Note that extract("*", copy=True) provides an easy way to transform a
94  row-major ColumnView into a possibly more efficient set of contiguous
95  NumPy arrays.
96 
97  This routines unpacks `Flag` columns into full boolean arrays and
98  covariances into dense (i.e. non-triangular packed) arrays with
99  dimension (N,M,M), where N is the number of records and M is the
100  dimension of the covariance matrix. String fields are silently
101  ignored.
102 
103  Additional Keyword Arguments
104  ----------------------------
105  items : `list` The result of a call to self.schema.extract(); this
106  will be used instead of doing any new matching, and allows the
107  pattern matching to be reused to extract values from multiple
108  records. This keyword is incompatible with any position arguments
109  and the regex, sub, and ordered keyword arguments.
110 
111  where : array index expression
112  Any expression that can be passed as indices to a NumPy array,
113  including slices, boolean arrays, and index arrays, that will be
114  used to index each column array. This is applied before arrays
115  are copied when copy is True, so if the indexing results in an
116  implicit copy no unnecessary second copy is performed.
117 
118  copy : `bool`
119  If True, the returned arrays will be contiguous copies rather than
120  strided views into the catalog. This ensures that the lifetime of
121  the catalog is not tied to the lifetime of a particular catalog,
122  and it also may improve the performance if the array is used
123  repeatedly. Default is False.
124 
125  regex : `str` or `re` pattern
126  A regular expression to be used in addition to any glob patterns
127  passed as positional arguments. Note that this will be compared
128  with re.match, not re.search.
129 
130  sub : `str`
131  A replacement string (see re.MatchObject.expand) used to set the
132  dictionary keys of any fields matched by regex.
133 
134  ordered : `bool`
135  If True, a collections.OrderedDict will be returned instead of a
136  standard dict, with the order corresponding to the definition
137  order of the Schema. Default is False.
138  """
139  copy = kwds.pop("copy", False)
140  where = kwds.pop("where", None)
141  d = kwds.pop("items", None)
142  # If ``items`` is given as a kwd, an extraction has already been performed and there shouldn't be
143  # any additional keywords. Otherwise call schema.extract to load the
144  # dictionary.
145  if d is None:
146  d = self.schema.extract(*patterns, **kwds).copy()
147  elif kwds:
148  raise ValueError(
149  "kwd 'items' was specified, which is not compatible with additional keywords")
150 
151  def processArray(a):
152  if where is not None:
153  a = a[where]
154  if copy:
155  a = np.ascontiguousarray(a)
156  return a
157 
158  # must use list because we might be adding/deleting elements
159  for name, schemaItem in list(d.items()):
160  key = schemaItem.key
161  if key.getTypeString() == "String":
162  del d[name]
163  else:
164  d[name] = processArray(self.get(schemaItem.key))
165  return d