Gaudi.Main.gaudimain Class Reference
Inheritance diagram for Gaudi.Main.gaudimain:
Collaboration diagram for Gaudi.Main.gaudimain:

Public Member Functions

def __init__ (self)
 
def setupParallelLogging (self)
 
def generatePyOutput
 
def generateOptsOutput
 
def printconfig
 
def writeconfig
 
def run
 Instantiate and run the application. More...
 
def basicInit (self)
 
def gaudiPythonInit (self)
 
def runSerial (self)
 
def runParallel (self, ncpus)
 

Public Attributes

 log
 
 printsequence
 
 ip
 
 g
 

Static Public Attributes

 mainLoop = None
 

Private Member Functions

def _writepickle (self, filename)
 

Detailed Description

Definition at line 133 of file Main.py.

Constructor & Destructor Documentation

def Gaudi.Main.gaudimain.__init__ (   self)

Definition at line 137 of file Main.py.

137  def __init__(self) :
138  from Configurables import ApplicationMgr
139  appMgr = ApplicationMgr()
140  if "GAUDIAPPNAME" in os.environ:
141  appMgr.AppName = str(os.environ["GAUDIAPPNAME"])
142  if "GAUDIAPPVERSION" in os.environ:
143  appMgr.AppVersion = str(os.environ["GAUDIAPPVERSION"])
144  self.log = logging.getLogger(__name__)
145  self.printsequence = False
146 
The Application Manager class.
def __init__(self)
Definition: Main.py:137

Member Function Documentation

def Gaudi.Main.gaudimain._writepickle (   self,
  filename 
)
private

Definition at line 199 of file Main.py.

199  def _writepickle(self, filename) :
200  #--- Lets take the first file input file as the name of the pickle file
201  import pickle
202  output = open(filename, 'wb')
203  # Dump only the the configurables that make sense to dump (not User ones)
204  from GaudiKernel.Proxy.Configurable import getNeededConfigurables
205  to_dump = {}
206  for n in getNeededConfigurables():
207  to_dump[n] = Configuration.allConfigurables[n]
208  pickle.dump(to_dump, output, -1)
209  output.close()
210 
def _writepickle(self, filename)
Definition: Main.py:199
def Gaudi.Main.gaudimain.basicInit (   self)
Bootstrap the application with minimal use of Python bindings.

Definition at line 246 of file Main.py.

246  def basicInit(self):
247  '''
248  Bootstrap the application with minimal use of Python bindings.
249  '''
250  try:
251  from GaudiKernel.Proxy.Configurable import expandvars
252  except ImportError:
253  # pass-through implementation if expandvars is not defined (AthenaCommon)
254  expandvars = lambda data : data
255 
256  from GaudiKernel.Proxy.Configurable import Configurable, getNeededConfigurables
257 
258  global _bootstrap
259  if _bootstrap is None:
260  _bootstrap = BootstrapHelper()
261 
262  self.log.debug('basicInit: instantiate ApplicationMgr')
263  self.ip = self.g = _bootstrap.createApplicationMgr()
264 
265  self.log.debug('basicInit: apply options')
266 
267  # set ApplicationMgr properties
268  comp = 'ApplicationMgr'
269  props = Configurable.allConfigurables.get(comp, {})
270  if props:
271  props = expandvars(props.getValuedProperties())
272  for p, v in props.items() + [('JobOptionsType', 'NONE')]:
273  if not self.g.setProperty(p, str(v)):
274  self.log.error('Cannot set property %s.%s to %s', comp, p, v)
275  sys.exit(10)
276  # issue with missing dictionary with ROOT < 6.2.7
277  if _bootstrap.ROOT_VERSION < (6, 2, 7):
278  # we need to load GaudiPython
279  import GaudiPython
280 
281  self.g.configure()
282 
283  # set MessageSvc properties
284  comp = 'MessageSvc'
285  msp = self.g.getService(comp)
286  if not msp:
287  self.log.error('Cannot get service %s', comp)
288  sys.exit(10)
289  props = Configurable.allConfigurables.get(comp, {})
290  if props:
291  props = expandvars(props.getValuedProperties())
292  for p, v in props.items():
293  if not _bootstrap.setProperty(msp, p, str(v)):
294  self.log.error('Cannot set property %s.%s to %s', comp, p, v)
295  sys.exit(10)
296 
297  # feed JobOptionsSvc
298  comp = 'JobOptionsSvc'
299  jos = self.g.getService(comp)
300  if not jos:
301  self.log.error('Cannot get service %s', comp)
302  sys.exit(10)
303  for n in getNeededConfigurables():
304  c = Configurable.allConfigurables[n]
305  if n in ['ApplicationMgr','MessageSvc']:
306  continue # These are already done
307  for p, v in c.getValuedProperties().items() :
308  v = expandvars(v)
309  # Note: AthenaCommon.Configurable does not have Configurable.PropertyReference
310  if hasattr(Configurable,"PropertyReference") and type(v) == Configurable.PropertyReference:
311  # this is done in "getFullName", but the exception is ignored,
312  # so we do it again to get it
313  v = v.__resolve__()
314  if type(v) == str : v = '"%s"' % v # need double quotes
315  elif type(v) == long: v = '%d' % v # prevent pending 'L'
316  _bootstrap.addPropertyToCatalogue(jos, n, p, str(v))
317  if hasattr(Configurable,"_configurationLocked"):
318  Configurable._configurationLocked = True
319  self.log.debug('basicInit: done')
320 
def basicInit(self)
Definition: Main.py:246
string type
Definition: gaudirun.py:127
def Gaudi.Main.gaudimain.gaudiPythonInit (   self)
Initialize the application with full Python bindings.

Definition at line 321 of file Main.py.

321  def gaudiPythonInit(self):
322  '''
323  Initialize the application with full Python bindings.
324  '''
325  self.log.debug('gaudiPythonInit: import GaudiPython')
326  import GaudiPython
327  self.log.debug('gaudiPythonInit: instantiate ApplicationMgr')
328  self.g = GaudiPython.AppMgr()
329  self.ip = self.g._ip
330  self.log.debug('gaudiPythonInit: done')
331 
def gaudiPythonInit(self)
Definition: Main.py:321
def Gaudi.Main.gaudimain.generateOptsOutput (   self,
  all = False 
)

Definition at line 186 of file Main.py.

186  def generateOptsOutput(self, all = False):
187  from pprint import pformat
188  conf_dict = Configuration.configurationDict(all)
189  out = []
190  names = conf_dict.keys()
191  names.sort()
192  for n in names:
193  props = conf_dict[n].keys()
194  props.sort()
195  for p in props:
196  out.append('%s.%s = %s;' % (n,p, toOpt(conf_dict[n][p])))
197  return "\n".join(out)
198 
def toOpt(value)
Definition: Main.py:111
def generateOptsOutput
Definition: Main.py:186
def Gaudi.Main.gaudimain.generatePyOutput (   self,
  all = False 
)

Definition at line 181 of file Main.py.

181  def generatePyOutput(self, all = False):
182  from pprint import pformat
183  conf_dict = Configuration.configurationDict(all)
184  return pformat(conf_dict)
185 
def generatePyOutput
Definition: Main.py:181
def Gaudi.Main.gaudimain.printconfig (   self,
  old_format = False,
  all = False 
)

Definition at line 211 of file Main.py.

211  def printconfig(self, old_format = False, all = False) :
212  msg = 'Dumping all configurables and properties'
213  if not all:
214  msg += ' (different from default)'
215  log.info(msg)
216  conf_dict = Configuration.configurationDict(all)
217  if old_format:
218  print self.generateOptsOutput(all)
219  else:
220  print self.generatePyOutput(all)
221 
def generateOptsOutput
Definition: Main.py:186
def generatePyOutput
Definition: Main.py:181
def Gaudi.Main.gaudimain.run (   self,
  ncpus = None 
)

Instantiate and run the application.

Depending on the number of CPUs (ncpus) specified, it start

Definition at line 237 of file Main.py.

237  def run(self, ncpus = None):
238  if not ncpus:
239  # Standard sequential mode
240  result = self.runSerial()
241  else:
242  # Otherwise, run with the specified number of cpus
243  result = self.runParallel(ncpus)
244  return result
245 
def runSerial(self)
Definition: Main.py:332
def runParallel(self, ncpus)
Definition: Main.py:398
def run
Instantiate and run the application.
Definition: Main.py:237
def Gaudi.Main.gaudimain.runParallel (   self,
  ncpus 
)

Definition at line 398 of file Main.py.

398  def runParallel(self, ncpus) :
399  if self.mainLoop:
400  self.log.fatal("Cannot use custom main loop in multi-process mode, check your options")
401  return 1
402  self.setupParallelLogging( )
403  from Gaudi.Configuration import Configurable
404  import GaudiMP.GMPBase as gpp
405  c = Configurable.allConfigurables
406  self.log.info('-'*80)
407  self.log.info('%s: Parallel Mode : %i '%(__name__, ncpus))
408  from commands import getstatusoutput as gso
409  metadataCommands = [ 'uname -a',
410  'echo $CMTCONFIG',
411  'echo $GAUDIAPPNAME',
412  'echo $GAUDIAPPVERSION']
413  for comm in metadataCommands :
414  s, o = gso( comm )
415  if s :
416  o = "Undetermined"
417  string = '%s: %30s : %s '%(__name__, comm, o)
418  self.log.info( string )
419  try :
420  events = str(c['ApplicationMgr'].EvtMax)
421  except :
422  events = "Undetermined"
423  self.log.info('%s: Events Specified : %s '%(__name__,events))
424  self.log.info('-'*80)
425  # Parall = gpp.Coordinator(ncpus, shared, c, self.log)
426  Parall = gpp.Coord( ncpus, c, self.log )
427  sysStart = time()
428  sc = Parall.Go()
429  self.log.info('MAIN.PY : received %s from Coordinator'%(sc))
430  if sc.isFailure() :
431  return 1
432  sysTime = time()-sysStart
433  self.log.name = 'Gaudi/Main.py Logger'
434  self.log.info('-'*80)
435  self.log.info('%s: parallel system finished, time taken: %5.4fs', __name__, sysTime)
436  self.log.info('-'*80)
437  return 0
def Gaudi.Main.gaudimain.runSerial (   self)

Definition at line 332 of file Main.py.

332  def runSerial(self) :
333  #--- Instantiate the ApplicationMgr------------------------------
334  if (self.mainLoop or
335  os.environ.get('GAUDIRUN_USE_GAUDIPYTHON')):
336  self.gaudiPythonInit()
337  else:
338  self.basicInit()
339 
340  self.log.debug('-'*80)
341  self.log.debug('%s: running in serial mode', __name__)
342  self.log.debug('-'*80)
343  sysStart = time()
344 
345  if self.mainLoop:
346  runner = self.mainLoop
347  else:
348  def runner(app, nevt):
349  self.log.debug('initialize')
350  sc = app.initialize()
351  if sc.isSuccess():
352  if self.printsequence:
353  app.printAlgsSequences()
354  self.log.debug('start')
355  sc = app.start()
356  if sc.isSuccess():
357  self.log.debug('run(%d)', nevt)
358  sc = app.run(nevt)
359  self.log.debug('stop')
360  app.stop().ignore()
361  self.log.debug('finalize')
362  app.finalize().ignore()
363  self.log.debug('terminate')
364  sc1 = app.terminate()
365  if sc.isSuccess():
366  sc = sc1
367  else:
368  sc1.ignore()
369  self.log.debug('status code: %s',
370  'SUCCESS' if sc.isSuccess() else 'FAILURE')
371  return sc
372 
373  try:
374  statuscode = runner(self.g, int(self.ip.getProperty('EvtMax').toString()))
375  except SystemError:
376  # It may not be 100% correct, but usually it means a segfault in C++
377  self.ip.setProperty('ReturnCode', str(128 + 11))
378  statuscode = False
379  except Exception, x:
380  print 'Exception:', x
381  # for other exceptions, just set a generic error code
382  self.ip.setProperty('ReturnCode', '1')
383  statuscode = False
384  if hasattr(statuscode, "isSuccess"):
385  success = statuscode.isSuccess()
386  else:
387  success = statuscode
388  #success = self.g.exit().isSuccess() and success
389  if not success and self.ip.getProperty('ReturnCode').toString() == '0':
390  # ensure that the return code is correctly set
391  self.ip.setProperty('ReturnCode', '1')
392  sysTime = time()-sysStart
393  self.log.debug('-'*80)
394  self.log.debug('%s: serial system finished, time taken: %5.4fs', __name__, sysTime)
395  self.log.debug('-'*80)
396  return int(self.ip.getProperty('ReturnCode').toString())
397 
def basicInit(self)
Definition: Main.py:246
def gaudiPythonInit(self)
Definition: Main.py:321
def runSerial(self)
Definition: Main.py:332
std::string toString(const TYPE &obj)
the generic implementation of the type conversion to the string
Definition: ToStream.h:403
def Gaudi.Main.gaudimain.setupParallelLogging (   self)

Definition at line 147 of file Main.py.

147  def setupParallelLogging( self ) :
148  # ---------------------------------------------------
149  # set up Logging
150  # ----------------
151  # from multiprocessing import enableLogging, getLogger
152  import multiprocessing
153  # preliminaries for handlers/output files, etc.
154  from time import ctime
155  datetime = ctime()
156  datetime = datetime.replace(' ', '_')
157  outfile = open( 'gaudirun-%s.log'%(datetime), 'w' )
158  # two handlers, one for a log file, one for terminal
159  streamhandler = logging.StreamHandler(strm=outfile)
160  console = logging.StreamHandler()
161  # create formatter : the params in parentheses are variable names available via logging
162  formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s" )
163  # add formatter to Handler
164  streamhandler.setFormatter(formatter)
165  console.setFormatter(formatter)
166  # now, configure the logger
167  # enableLogging( level=0 )
168  # self.log = getLogger()
169  self.log = multiprocessing.log_to_stderr()
170  self.log.setLevel( logging.INFO )
171  self.log.name = 'Gaudi/Main.py Logger'
172  self.log.handlers = []
173  # add handlers to logger : one for output to a file, one for console output
174  self.log.addHandler(streamhandler)
175  self.log.addHandler(console)
176  self.log.removeHandler(console)
177  # set level!!
178  self.log.setLevel = logging.INFO
179  # ---------------------------------------------------
180 
def setupParallelLogging(self)
Definition: Main.py:147
def Gaudi.Main.gaudimain.writeconfig (   self,
  filename,
  all = False 
)

Definition at line 222 of file Main.py.

222  def writeconfig(self, filename, all = False):
223  write = { ".pkl" : lambda filename, all: self._writepickle(filename),
224  ".py" : lambda filename, all: open(filename,"w").write(self.generatePyOutput(all) + "\n"),
225  ".opts": lambda filename, all: open(filename,"w").write(self.generateOptsOutput(all) + "\n"),
226  }
227  from os.path import splitext
228  ext = splitext(filename)[1]
229  if ext in write:
230  write[ext](filename, all)
231  else:
232  log.error("Unknown file type '%s'. Must be any of %r.", ext, write.keys())
233  sys.exit(1)
234 
def _writepickle(self, filename)
Definition: Main.py:199
def generateOptsOutput
Definition: Main.py:186
def generatePyOutput
Definition: Main.py:181

Member Data Documentation

Gaudi.Main.gaudimain.g

Definition at line 263 of file Main.py.

Gaudi.Main.gaudimain.ip

Definition at line 263 of file Main.py.

Gaudi.Main.gaudimain.log

Definition at line 144 of file Main.py.

Gaudi.Main.gaudimain.mainLoop = None
static

Definition at line 135 of file Main.py.

Gaudi.Main.gaudimain.printsequence

Definition at line 145 of file Main.py.


The documentation for this class was generated from the following file: