lsst.afw  14.0-34-g2d9284d60+1
schemaContinued.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__ = ["Key", "Field", "SchemaItem"]
25 
26 from past.builtins import basestring
27 from builtins import str as futurestr
28 from future.utils import with_metaclass
29 
30 import numpy as np
31 import fnmatch
32 import re
33 import collections
34 import astropy.units
35 
36 from ...geom import Angle
37 from lsst.utils import continueClass, TemplateMeta
38 
39 from .schema import _Key, _Field, _SchemaItem, Schema
40 
41 # Objects we prefer to use over the C++ string name for
42 # Key/Field/SchemaItem types.
43 _dtypes = {
44  "String": str,
45  "B": np.uint8,
46  "U": np.uint16,
47  "I": np.int32,
48  "L": np.int64,
49  "F": np.float32,
50  "D": np.float64,
51  "Angle": Angle
52 }
53 
54 
55 class Key(with_metaclass(TemplateMeta, object)):
56  pass
57 
58 
59 class Field(with_metaclass(TemplateMeta, object)):
60  pass
61 
62 
63 class SchemaItem(with_metaclass(TemplateMeta, object)):
64  pass
65 
66 
67 def _registerInstantiations(abc, types):
68  """Iterate over a private dict (filled by template instantiations in C++)
69  to register template instantiations a TemplateMeta ABCs.
70 
71  If an entry for the type string exists in _dtypes, we use that instead of
72  the string as the key, and use the string as an alias.
73  """
74  for k, v in types.items():
75  dtype = _dtypes.get(k, None)
76  if dtype is not None:
77  abc.register(dtype, v)
78  abc.alias(k, v)
79  else:
80  abc.register(k, v)
81 
82 
83 # _Key, _Field, and _SchemaItem are {str: class} dicts populated by the C++
84 # wrappers. The keys are a superset of those in _dtypes.
85 _registerInstantiations(Key, _Key)
86 _registerInstantiations(Field, _Field)
87 _registerInstantiations(SchemaItem, _SchemaItem)
88 
89 # Also register `float->D` and 'futurestr->String' as aliases; can't include
90 # in _dtypes because we have (and prefer) np.float64/str there.
91 Key.alias(float, _Key["D"])
92 Field.alias(float, _Field["D"])
93 SchemaItem.alias(float, _SchemaItem["D"])
94 if futurestr is not str:
95  Key.alias(futurestr, _Key["String"])
96  Field.alias(futurestr, _Field["String"])
97  SchemaItem.alias(futurestr, _SchemaItem["String"])
98 
99 
100 @continueClass
101 class Schema:
102 
103  def getOrderedNames(self):
104  """Return a list of field names in the order the fields were added to the Schema.
105  """
106  names = []
107 
108  def func(item):
109  names.append(item.field.getName())
110  self.forEach(func)
111  return names
112 
113  def __iter__(self):
114  """Iterate over the items in the Schema.
115  """
116  items = []
117  self.forEach(items.append)
118  return iter(items)
119 
120  def checkUnits(self, parse_strict='raise'):
121  """Check that all units in the Schema are valid Astropy unit strings.
122  """
123  def func(item):
124  astropy.units.Unit(item.field.getUnits(),
125  parse_strict=parse_strict)
126  self.forEach(func)
127 
128  def addField(self, field, type=None, doc="", units="", size=None,
129  doReplace=False, parse_strict="raise"):
130  """Add a field to the Schema.
131 
132  Parameters
133  ----------
134  field : str,Field
135  The string name of the Field, or a fully-constructed Field object.
136  If the latter, all other arguments besides doReplace are ignored.
137  type\n : str,type
138  The type of field to create. Valid types are the keys of the
139  afw.table.Field dictionary.
140  doc : str
141  Documentation for the field.
142  unit : str
143  Units for the field, or an empty string if unitless.
144  size : int
145  Size of the field; valid for string and array fields only.
146  doReplace : bool
147  If a field with this name already exists, replace it instead of
148  raising pex.exceptions.InvalidParameterError.
149  parse_strict : str
150  One of 'raise' (default), 'warn', or 'strict', indicating how to
151  handle unrecognized unit strings. See also astropy.units.Unit.
152  """
153  if isinstance(field, basestring):
154  field = Field[type](field, doc=doc, units=units,
155  size=size, parse_strict=parse_strict)
156  return field._addTo(self, doReplace)
157 
158  def extract(self, *patterns, **kwds):
159  """
160  Extract a dictionary of {<name>: <schema-item>} in which the field names
161  match the given shell-style glob pattern(s).
162 
163  Any number of glob patterns may be passed; the result will be the union of all
164  the result of each glob considered separately.
165 
166  Additional Keyword Arguments
167  ----------------------------
168  regex : `str` or `re` pattern
169  A regular expression to be used in addition to any glob patterns
170  passed as positional arguments. Note that this will be compared
171  with re.match, not re.search.
172 
173  sub : `str`
174  A replacement string (see re.MatchObject.expand) used to set the
175  dictionary keys of any fields matched by regex.
176 
177  ordered : `bool`
178  If True, a collections.OrderedDict will be returned instead of a
179  standard dict, with the order corresponding to the definition
180  order of the Schema. Default is False.
181  """
182  if kwds.pop("ordered", False):
183  d = collections.OrderedDict()
184  else:
185  d = dict()
186  regex = kwds.pop("regex", None)
187  sub = kwds.pop("sub", None)
188  if sub is not None and regex is None:
189  raise ValueError(
190  "'sub' keyword argument to extract is invalid without 'regex' argument")
191  if kwds:
192  raise ValueError(
193  "Unrecognized keyword arguments for extract: %s" % ", ".join(kwds.keys()))
194  for item in self:
195  trueName = item.field.getName()
196  names = [trueName]
197  for alias, target in self.getAliasMap().items():
198  if trueName.startswith(target):
199  names.append(trueName.replace(target, alias, 1))
200  for name in names:
201  if regex is not None:
202  m = re.match(regex, name)
203  if m is not None:
204  if sub is not None:
205  name = m.expand(sub)
206  d[name] = item
207  continue # continue middle loop so we don't match the same name twice
208  for pattern in patterns:
209  if fnmatch.fnmatchcase(name, pattern):
210  d[name] = item
211  break # break inner loop so we don't match the same name twice
212  return d
def addField(self, field, type=None, doc="", units="", size=None, doReplace=False, parse_strict="raise")
def checkUnits(self, parse_strict='raise')