Документ взят из кэша поисковой машины. Адрес оригинального документа : http://www.apo.nmsu.edu/Telescopes/TCC/html/block_to_k_w_8py_source.html
Дата изменения: Tue Sep 15 02:25:37 2015
Дата индексирования: Sun Apr 10 02:19:48 2016
Кодировка:
lsst.tcc: python/tcc/msg/blockToKW.py Source File
lsst.tcc  1.2.2-3-g89ecb63
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
blockToKW.py
Go to the documentation of this file.
1 from __future__ import division, absolute_import
2 """Some tools for managing TCC keyword output from a block
3 """
4 import itertools
5 import math
6 
7 from coordConv import PVT
8 from RO.SeqUtil import isSequence
9 
10 __all__ = ["WriterFromBlock", "FieldKW"]
11 
12 class WriterFromBlock(object):
13  """!A class containing mapping information between fields on a block and a TCC keyword
14  """
15  def __init__(self, objClass, fieldKWDict):
16  """!Construct a WriterFromBlock
17 
18  @param[in] objClass class of block
19  @param[in] fieldKWDict an ordered dictionary of FieldKW objects keyed by TCC keyword.
20  Keywords are output in the order specified by this dict.
21  """
22  # for fkw in fieldKWDict.itervalues():
23  # if not hasattr(block, fkw.blockAttr):
24  # raise RuntimeError("Block has no attribute: %s"%fkw.blockAttr)
25  self.objClass = objClass # keep around for making copies
26  self.block = objClass() # an empty block
27  self.fieldKWDict = fieldKWDict # ordered dict
28  self.suppressionRules = {} # added by addSuppression method
29  self.additionRules = {} # added by addAddition method
30  self.groups = [] # added by addGroup method
31 
32  def writeKWs(self, writeToUsers, cmd=None, keywords=None):
33  """!Write a list of keyword=value messages to users
34 
35  @param[in] writeToUsers provided from the tccActor.writeToUsers method
36  @param[in] cmd command whose ID is used for output (a twistedActor.BaseCmd)
37  @param[in] keywords a list of keywords or None;
38  if None then use self.fieldKWDict.keys()
39  """
40  if keywords:
41  if not isSequence(keywords):
42  raise RuntimeError("keywords=%r; not a sequence" % (keywords,))
43  keywords = set(keywords)
44  # should any be added based on addition rules?
45  for key, logic in self.additionRules.iteritems():
46  if logic():
47  keywords.update([key])
48  # be sure that group output is satisfied.
49  for group in self.groups: # self.groups is a list of sets
50  # if any member of this group is in keywords
51  if len(group & keywords):
52  keywords.update(group)
53 
54  else:
55  keywords = self.fieldKWDict.keys() # write all
56  for kw in self.fieldKWDict.iterkeys(): # iterate over fieldKWDict, because that defines the order
57  if kw not in keywords:
58  # don't write this one!
59  continue
60  self.writeSingleKW(kw, writeToUsers, cmd) # suppression rules checked here
61 
62  def addSuppression(self, keyword, logic):
63  """!Add a suppression rule
64 
65  @param[in] keyword the keyword to be suppressed (must be a keyword in self.fieldKWDict)
66  @param[in] logic a callable that evaluates to True or False. If True keyword will
67  not be output, else keyword will be output
68  """
69  if not keyword in self.fieldKWDict:
70  raise RuntimeError("Keyword :%s, not found in dict"%keyword)
71  if not callable(logic):
72  raise RuntimeError("logic")
73  if keyword in self.suppressionRules:
74  # a suppression rule already exists, add another
75  self.suppressionRules[keyword].append(logic)
76  else:
77  # add the first one
78  self.suppressionRules[keyword]=[logic]
79 
80  def addAddition(self, keyword, logic):
81  """!Add an addition rule
82 
83  @param[in] keyword the keyword to be added (must be a keyword in self.fieldKWDict)
84  @param[in] logic a callable that evaluates to True or False. If True keyword will
85  be output
86  """
87  if not keyword in self.fieldKWDict:
88  raise RuntimeError("Keyword :%s, not found in dict"%keyword)
89  if not callable(logic):
90  raise RuntimeError("logic")
91  self.additionRules[keyword]=logic
92 
93  def addGroup(self, keywords):
94  """!Define a keyword group
95 
96  @param[in] keywords a list of keywords.
97  If one is specified, then all are output
98  """
99  self.groups.append(set(keywords))
100 
101 
102  def writeSingleKW(self, keyword, writeToUsers, cmd=None):
103  """!Write a single keyword to users; if a suppression rule for this keyword exists, test it
104 
105  @param[in] keyword the keyword to be suppressed (must be a keyword in self.fieldKWDict)
106  @param[in] writeToUsers output function (a twistedActor.BaseActor.writeToUsers)
107  @param[in] cmd command whose ID is used for output (a twistedActor.BaseCmd)
108  """
109  if keyword in self.suppressionRules:
110  for logic in self.suppressionRules[keyword]:
111  if logic():
112  # a suppression exists
113  return
114  outStr = self.fieldKWDict[keyword].getKeyValStr(self.block)
115  writeToUsers('i', outStr, cmd)
116 
117  def updateBlock(self, newBlock):
118  """!Compare attributes on the newBlock, vs. the cached block
119 
120  @param[in] newBlock the new block with possibly (likely) new values
121  @return a list of keywords which have been updated
122  """
123  newBlock = self.objClass(newBlock)
124  if "userSys" in dir(newBlock): # this is an obj block, explicitly clone usersys for safety
125  newBlock.userSys = newBlock.userSys.clone()
126  updatedKWs = [kw for kw, val in self.fieldKWDict.iteritems() if val.wasUpdated(self.block, newBlock)]
127  # start with an empty object (cannot deep copy a swig item)
128  self.block = newBlock #CopyBlock(newBlock)
129  # self.block = newBlock
130  return updatedKWs
131 
132 def isEqualOrNan(a, b):
133  """Return True if a==b or False otherwise, with special handling for float and coordConv.PVT
134 
135  Handle these types specially (and assumes a and b are the same type)
136  - float: return True if both are nan
137  - coordConv.PVT: return True if neither is finite
138  """
139  if a==b:
140  return True
141  if isinstance(a, float):
142  if math.isnan(a) and math.isnan(b):
143  return True
144  elif isinstance(a, PVT):
145  if not a.isfinite() and not b.isfinite():
146  return True
147  return False
148 
149 class FieldKW(object):
150  """!Object for holding an attribute of a block, and a formatting function for that attribute
151 
152  A block is a struct-like object, such as tcc.base.Obj
153  """
154  def __init__(self, tccKW, blockAttr, stringCast):
155  """!Construct a FieldKW
156 
157  @param[in] tccKW keyword used to output the value
158  @param[in] blockAttr name of attribute on the block
159  @param[in] stringCast function that formats the specified attribute;
160  called with the Block.blockAttr as the only argument.
161  """
162  self.tccKW = tccKW
163  self.blockAttr = blockAttr
164  self.stringCast = stringCast
165 
166  def wasUpdated(self, oldBlock, newBlock):
167  """!Return True if the attribute has changed
168 
169  @param[in] oldBlock old value of the block
170  @param[in] newBlock new value of the block
171  """
172  attr1 = getattr(oldBlock, self.blockAttr)
173  attr2 = getattr(newBlock, self.blockAttr)
174  wasUpdated = False
175  if isSequence(attr1):
176  for x, y in itertools.izip(attr1, attr2):
177  if not isEqualOrNan(x, y):
178  wasUpdated = True
179  break
180  else:
181  # this attribute isn't iterable
182  # directly compare
183  if not isEqualOrNan(attr1, attr2):
184  wasUpdated = True
185  return wasUpdated
186 
187  def getKeyValStr(self, block):
188  """!Format the attribute as a key=value string
189 
190  @param[in] block block whose attribute is to be formatted
191  """
192  return "%s=%s" % (self.tccKW, self.stringCast(getattr(block, self.blockAttr)))
def writeKWs
Write a list of keyword=value messages to users.
Definition: blockToKW.py:32
def __init__
Construct a FieldKW.
Definition: blockToKW.py:154
def wasUpdated
Return True if the attribute has changed.
Definition: blockToKW.py:166
def addAddition
Add an addition rule.
Definition: blockToKW.py:80
def getKeyValStr
Format the attribute as a key=value string.
Definition: blockToKW.py:187
def __init__
Construct a WriterFromBlock.
Definition: blockToKW.py:15
A class containing mapping information between fields on a block and a TCC keyword.
Definition: blockToKW.py:12
def writeSingleKW
Write a single keyword to users; if a suppression rule for this keyword exists, test it...
Definition: blockToKW.py:102
def addGroup
Define a keyword group.
Definition: blockToKW.py:93
Object for holding an attribute of a block, and a formatting function for that attribute.
Definition: blockToKW.py:149
def addSuppression
Add a suppression rule.
Definition: blockToKW.py:62
def updateBlock
Compare attributes on the newBlock, vs.
Definition: blockToKW.py:117