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