CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
ToolDataAccessor.py
Go to the documentation of this file.
1 import sys
2 import os.path
3 import logging
4 import re
5 import copy
6 import inspect
7 
8 from PyQt4.QtCore import QCoreApplication
9 
10 from Vispa.Main.Exceptions import exception_traceback
11 from Vispa.Share.BasicDataAccessor import BasicDataAccessor
12 
13 import FWCore.ParameterSet.Config as cms
14 import FWCore.GuiBrowsers.EnablePSetHistory
15 FWCore.GuiBrowsers.EnablePSetHistory.ACTIVATE_INSPECTION=False
16 from FWCore.GuiBrowsers.ConfigToolBase import ConfigToolBase
17 from FWCore.GuiBrowsers.editorTools import UserCodeTool
18 
19 import PhysicsTools.PatAlgos.tools as tools
20 standardToolsDir=os.path.abspath(os.path.join(os.path.dirname(tools.__file__)))
21 
22 cmsswDir="$CMSSW_BASE"
23 cmsswReleaseDir="$CMSSW_RELEASE_BASE"
24 standardConfigDir=os.path.abspath(os.path.expandvars(os.path.join(cmsswDir,"src/PhysicsTools/PatAlgos/test")))
25 if not os.path.exists(standardConfigDir):
26  standardConfigDir=os.path.abspath(os.path.expandvars(os.path.join(cmsswReleaseDir,"src/PhysicsTools/PatAlgos/test")))
27 
29  """ Import configuration tool """
30  _label="Import"
31  _defaultParameters={}
32  def __init__(self):
33  ConfigToolBase.__init__(self)
34  self.addParameter(self._defaultParameters,'filename','/', 'The name of the configuration file')
35  self._parameters=copy.deepcopy(self._defaultParameters)
37  def dumpPython(self):
38  dump=""
39  dump += "### Generated by ConfigEditor ###\n"
40  find1=os.path.abspath(os.path.dirname(self._parameters['filename'].value)).find(os.path.abspath(os.path.expandvars(cmsswDir)))
41  find2=os.path.abspath(os.path.dirname(self._parameters['filename'].value)).find(os.path.abspath(os.path.expandvars(cmsswReleaseDir)))
42  if find1>=0 or find2>=0:
43  dump += "import sys\n"
44  dump += "import os.path\n"
45  if find1>=0:
46  dir=os.path.abspath(os.path.dirname(self._parameters['filename'].value))[find1+len(os.path.abspath(os.path.expandvars(cmsswDir)))+1:]
47  else:
48  dir=os.path.abspath(os.path.dirname(self._parameters['filename'].value))[find2+len(os.path.abspath(os.path.expandvars(cmsswReleaseDir)))+1:]
49  dump += "sys.path.append(os.path.abspath(os.path.expandvars(os.path.join('"+cmsswDir+"','"+dir+"'))))\n"
50  dump += "sys.path.append(os.path.abspath(os.path.expandvars(os.path.join('"+cmsswReleaseDir+"','"+dir+"'))))\n"
51  dump += "### ------------------------- ###\n"
52  if self._parameters['filename'].value!="":
53  dump += "\n"
54  dump += "from "+os.path.splitext(os.path.basename(self._parameters['filename'].value))[0]+" import *\n"
55  dump += "\n"
56  dump += "### Generated by ConfigEditor ###\n"
57  dump += "if hasattr(process,'resetHistory'): process.resetHistory()\n"
58  dump += "### ------------------------- ###\n"
59  for command in self._importCommands:
60  dump += command + "\n"
61  return ("",dump)
62  def apply(self,process):
63  pass
64  def setImportCommands(self,commands):
65  self._importCommands=commands
66 
68  """Apply a tool"""
69  _label="Apply tool"
70  def dumpPython(self):
71  return ("","")
72  def apply(self,process):
73  pass
74 
75 class ToolDataAccessor(BasicDataAccessor):
76  def __init__(self):
77  logging.debug(__name__ + ": __init__")
79  self._toolList=[]
82  self._toolModules={}
83  self._processCopy=None
85 
86  def children(self, object):
87  """ Return the children of a container object.
88  """
89  return ()
90 
91  def isContainer(self, object):
92  return False
93 
94  def label(self, object):
95  """ Return a string that is used as caption of an object.
96  """
97  if isinstance(object,type):
98  directory=os.path.splitext(os.path.basename(inspect.getfile(object)))[0]
99  else:
100  directory=os.path.splitext(os.path.basename(inspect.getfile(type(object))))[0]
101  if directory=="ToolDataAccessor":
102  return object._label
103  else:
104  return directory+"."+object._label
105 
106  def _property(self,name,value,description,typ,allowedValues):
107  if typ in [bool] and type(value)!=typ:
108  value=False
109  if typ in [int, long, float] and type(value)!=typ:
110  value=0
111  if not allowedValues is None and typ in [int,long,float,str]:
112  return ("DropDown", name, value,description, False, False, allowedValues)
113  elif typ in [bool]:
114  return ("Boolean", name, value,description)
115  elif typ in [int, long]:
116  return ("Integer", name, value,description)
117  elif typ in [float]:
118  return ("Double", name, value,description)
119  elif name=="filename":
120  return ("File", name, str(value),description)
121  elif name=="code":
122  return ("MultilineString", name, str(value).strip("\n"),description)
123  else:
124  return ("String", name, str(value),description)
125 
126  def properties(self, object):
127  """ Return the list of the properties of an object.
128 
129  Each property is represented by a tuple containing its
130  type, name, value, description and readonly(True/False).
131  Possible types are: 'Category','String','MultilineString','File','FileVector','Boolean','Integer','Double'.
132  """
133  properties=[]
134  if not isinstance(object,(ImportTool,UserCodeTool,ApplyTool)):
135  properties+=[("String","Tool",self.label(object),None,True)]
136  if not isinstance(object,(ImportTool,UserCodeTool)):
137  properties+=[("String","Description",object.description(),None,True)]
138  if not isinstance(object,(UserCodeTool,ApplyTool)):
139  code=object.dumpPython()
140  if isinstance(code,tuple):
141  code=code[1]
142  properties+=[("MultilineString","code",code.strip("\n"),None,True)]
143  if not isinstance(object,(ImportTool,UserCodeTool,ApplyTool)):
144  properties+=[("String","comment",object._comment,None,False)]
145  if len(object.getParameters().items())>0:
146  properties += [("Category", "Parameters", "")]
147  properties+=[self._property(value.name,value.value,value.description,value.type,object.getAllowedValues(value.name)) for key,value in object.getParameters().items()]
148  return properties
149 
150  def setProperty(self, object, name, value, categoryName):
151  """ Change the property 'name' of an object to a new value.
152  """
153  if self.configDataAccessor().process() and name=="code":
154  # for UserCodeTool
155  process=self.configDataAccessor().process()
156  try:
157  process.disableRecording()
158  exec value
159  process.enableRecording()
160  process.resetModified()
161  process.resetModifiedObjects()
162  except Exception,e:
163  error="Error in python code (see logfile for details):\n"+str(e)
164  logging.warning(__name__ + ": setProperty: Error in python code: "+exception_traceback())
165  self._parameterErrors[str(id(object))+"."+name]=error
166  return error
167  elif isinstance(value,str):
168  # for e.g. cms.InputTag
169  try:
170  exec "value="+value
171  except:
172  pass
173  if name!="comment":
174  try:
175  object.setParameter(name,value)
176  except Exception, e:
177  error="Cannot set parameter "+name+" (see logfile for details):\n"+str(e)
178  logging.warning(__name__ + ": setProperty: Cannot set parameter "+name+": "+exception_traceback())
179  self._parameterErrors[str(id(object))+"."+name]=error
180  return error
181  elif name=="comment":
182  try:
183  object.setComment(value)
184  except Exception, e:
185  error="Cannot set comment (see logfile for details):\n"+str(e)
186  logging.warning(__name__ + ": setProperty: Cannot set comment "+exception_traceback())
187  self._parameterErrors[str(id(object))+"."+name]=error
188  return error
189  if str(id(object))+"."+name in self._parameterErrors.keys():
190  del self._parameterErrors[str(id(object))+"."+name]
191  return True
192 
193  def setConfigDataAccessor(self,accessor):
194  self._configDataAccessor=accessor
195  self._importTool.setParameter("filename",accessor.configFile())
196  if accessor.process():
197  self._processCopy=copy.deepcopy(accessor.process())
198  self._processCopy.resetHistory()
199  return self.updateProcess(False)
200 
202  return self._configDataAccessor
203 
204  def removeTool(self,tool):
205  self._toolList.remove(tool)
206  return self.updateProcess()
207 
208  def addTool(self,tool):
209  tool.apply(self.configDataAccessor().process())
210  self.configDataAccessor().setProcess(self.configDataAccessor().process())
211  return True
212 
213  def updateProcess(self,cp=True):
214  logging.debug(__name__ + ": updateProcess")
215  if cp:
216  process=copy.deepcopy(self._processCopy)
217  else:
218  process=self.configDataAccessor().process()
219  try:
220  for tool in self._toolList:
221  tool.apply(process)
222  if not process.checkRecording():
223  logging.error(__name__ + ": Could not apply tool: "+self.label(tool)+" (problem with enable recording flag)")
224  QCoreApplication.instance().errorMessage("Could not apply tool: "+self.label(tool)+" (problem with enable recording flag)")
225  return False
226  except Exception,e:
227  logging.error(__name__ + ": Could not apply tool: "+self.label(tool)+": "+exception_traceback())
228  QCoreApplication.instance().errorMessage("Could not apply tool (see log file for details):\n"+str(e))
229  return False
230  self.configDataAccessor().setProcess(process)
231  self._parameterErrors={}
232  return True
233 
234  def updateToolList(self):
235  logging.debug(__name__ + ": updateToolList")
236  if not self.configDataAccessor().process():
237  return
238  history=self.configDataAccessor().process().history(True)
239  self._toolList=[]
240  self._toolModules={}
241  importCommands=[]
242  for tool,objects in history:
243  if isinstance(tool,str):
244  userTool=UserCodeTool()
245  userTool.setParameter("code",tool)
246  self._toolList+=[userTool]
247  elif isinstance(tool,ConfigToolBase):
248  self._toolList+=[tool]
249  command=tool.dumpPython()[0]
250  if command!="" and not command in importCommands:
251  importCommands+=[command]
252  self._toolModules[self._toolList[-1]]=objects
253  self._importTool.setImportCommands(importCommands)
254 
255  def topLevelObjects(self):
256  objectList=[self._importTool]+self._toolList
257  if self.configDataAccessor().process():
258  objectList+=[self._applyTool]
259  return objectList
260 
261  def toolModules(self):
262  return self._toolModules
263 
264  def parameterErrors(self,object):
265  return [self._parameterErrors[key] for key in self._parameterErrors.keys() if str(id(object))==key.split(".")[0]]
void strip(std::string &input, const std::string &blanks=" \n\t")
Definition: stringTools.cc:16
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:7
tuple process
Definition: LaserDQM_cfg.py:3