The Gaudi Framework  master (adcf1ca6)
Loading...
Searching...
No Matches
Gaudi.Main.gaudimain Class Reference
Inheritance diagram for Gaudi.Main.gaudimain:
Collaboration diagram for Gaudi.Main.gaudimain:

Public Member Functions

 __init__ (self)
 
 setupParallelLogging (self)
 
 generatePyOutput (self, all=False)
 
 generateOptsOutput (self, all=False)
 
 printconfig (self, old_format=False, all=False)
 
 writeconfig (self, filename, all=False)
 
 run (self, attach_debugger, ncpus=None)
 
 hookDebugger (self)
 
 runSerial (self, attach_debugger)
 
 runParallel (self, ncpus)
 

Public Attributes

 log = logging.getLogger(__name__)
 
bool printsequence = False
 
str application = "Gaudi::Application"
 

Protected Member Functions

 _writepickle (self, filename)
 

Detailed Description

Definition at line 319 of file Main.py.

Constructor & Destructor Documentation

◆ __init__()

Gaudi.Main.gaudimain.__init__ ( self)

Definition at line 320 of file Main.py.

320 def __init__(self):
321 from Configurables import ApplicationMgr
322
323 appMgr = ApplicationMgr()
324 if os.environ.get("GAUDIAPPNAME"):
325 appMgr.AppName = str(os.environ["GAUDIAPPNAME"])
326 if os.environ.get("GAUDIAPPVERSION"):
327 appMgr.AppVersion = str(os.environ["GAUDIAPPVERSION"])
328 self.log = logging.getLogger(__name__)
329 self.printsequence = False
330 self.application = "Gaudi::Application"
331
The Application Manager class.

Member Function Documentation

◆ _writepickle()

Gaudi.Main.gaudimain._writepickle ( self,
filename )
protected

Definition at line 392 of file Main.py.

392 def _writepickle(self, filename):
393 # --- Lets take the first file input file as the name of the pickle file
394 import pickle
395
396 output = open(filename, "wb")
397 # Dump only the the configurables that make sense to dump (not User ones)
398 from GaudiKernel.Proxy.Configurable import getNeededConfigurables
399
400 to_dump = {}
401 for n in getNeededConfigurables():
402 to_dump[n] = Configuration.allConfigurables[n]
403 pickle.dump(to_dump, output, -1)
404 output.close()
405

◆ generateOptsOutput()

Gaudi.Main.gaudimain.generateOptsOutput ( self,
all = False )

Definition at line 385 of file Main.py.

385 def generateOptsOutput(self, all=False):
386 opts = getAllOpts(all)
387 keys = sorted(opts)
388 return "\n".join(
389 "{} = {};".format(key, toOpt(parseOpt(opts[key]))) for key in keys
390 )
391
GAUDI_API std::string format(const char *,...)
MsgStream format utility "a la sprintf(...)".
Definition MsgStream.cpp:93

◆ generatePyOutput()

Gaudi.Main.gaudimain.generatePyOutput ( self,
all = False )

Definition at line 370 of file Main.py.

370 def generatePyOutput(self, all=False):
371 import re
372 from collections import defaultdict
373 from pprint import pformat
374
375 optDict = defaultdict(dict)
376 allOpts = getAllOpts(all)
377 for key in allOpts:
378 c, p = key.rsplit(".", 1)
379 optDict[c][p] = parseOpt(allOpts[key])
380 formatted = pformat(dict(optDict))
381 # undo splitting of strings on multiple lines
382
383 return re.sub(r'"\n +"', "", formatted, flags=re.MULTILINE)
384

◆ hookDebugger()

Gaudi.Main.gaudimain.hookDebugger ( self)
Hook gdb to the current session. This is done by forking
the current process and replacing the parent with gdb, while
the child continues to run the program.

Definition at line 464 of file Main.py.

464 def hookDebugger(self):
465 """Hook gdb to the current session. This is done by forking
466 the current process and replacing the parent with gdb, while
467 the child continues to run the program.
468 """
469
470 child_pid = os.fork()
471
472 if child_pid == 0:
473 # CHILD PROCESS - runs the actual program
474 return
475 else:
476 # PARENT PROCESS - becomes GDB
477
478 # Replace parent process with GDB
479 args = [arg for arg in sys.argv if arg != "--gdb"]
480 os.execvp(
481 "gdb",
482 [
483 "gdb",
484 "-q",
485 "-p",
486 str(child_pid),
487 "-ex",
488 f"set args {' '.join(args)}",
489 ],
490 )
491

◆ printconfig()

Gaudi.Main.gaudimain.printconfig ( self,
old_format = False,
all = False )

Definition at line 406 of file Main.py.

406 def printconfig(self, old_format=False, all=False):
407 msg = "Dumping all configurables and properties"
408 if not all:
409 msg += " (different from default)"
410 log.info(msg)
411 if old_format:
412 print(self.generateOptsOutput(all))
413 else:
414 print(self.generatePyOutput(all))
415 sys.stdout.flush()
416

◆ run()

Gaudi.Main.gaudimain.run ( self,
attach_debugger,
ncpus = None )

Definition at line 455 of file Main.py.

455 def run(self, attach_debugger, ncpus=None):
456 if not ncpus:
457 # Standard sequential mode
458 result = self.runSerial(attach_debugger)
459 else:
460 # Otherwise, run with the specified number of cpus
461 result = self.runParallel(ncpus)
462 return result
463

◆ runParallel()

Gaudi.Main.gaudimain.runParallel ( self,
ncpus )

Definition at line 534 of file Main.py.

534 def runParallel(self, ncpus):
535 self.setupParallelLogging()
536 import GaudiMP.GMPBase as gpp
537 from Gaudi.Configuration import Configurable
538
539 c = Configurable.allConfigurables
540 self.log.info("-" * 80)
541 self.log.info("%s: Parallel Mode : %i ", __name__, ncpus)
542 for name, value in [
543 ("platform", " ".join(os.uname())),
544 ("config", os.environ.get("BINARY_TAG") or os.environ.get("CMTCONFIG")),
545 ("app. name", os.environ.get("GAUDIAPPNAME")),
546 ("app. version", os.environ.get("GAUDIAPPVERSION")),
547 ]:
548 self.log.info("%s: %30s : %s ", __name__, name, value or "Undefined")
549 try:
550 events = str(c["ApplicationMgr"].EvtMax)
551 except Exception:
552 events = "Undetermined"
553 self.log.info("%s: Events Specified : %s ", __name__, events)
554 self.log.info("-" * 80)
555 # Parall = gpp.Coordinator(ncpus, shared, c, self.log)
556 Parall = gpp.Coord(ncpus, c, self.log)
557 sysStart = time()
558 sc = Parall.Go()
559 self.log.info("MAIN.PY : received %s from Coordinator" % (sc))
560 if sc.isFailure():
561 return 1
562 sysTime = time() - sysStart
563 self.log.name = "Gaudi/Main.py Logger"
564 self.log.info("-" * 80)
565 self.log.info(
566 "%s: parallel system finished, time taken: %5.4fs", __name__, sysTime
567 )
568 self.log.info("-" * 80)
569 return 0

◆ runSerial()

Gaudi.Main.gaudimain.runSerial ( self,
attach_debugger )

Definition at line 492 of file Main.py.

492 def runSerial(self, attach_debugger):
493 try:
494 from GaudiKernel.Proxy.Configurable import expandvars
495 except ImportError:
496 # pass-through implementation if expandvars is not defined (AthenaCommon)
497 def expandvars(data):
498 return data
499
500 from GaudiKernel.Proxy.Configurable import Configurable
501
502 self.log.debug("runSerial: apply options")
503 conf_dict = expandvars(getAllOpts())
504 conf_dict["ApplicationMgr.JobOptionsType"] = '"NONE"'
505
506 if self.printsequence:
507 conf_dict["ApplicationMgr.PrintAlgsSequence"] = "true"
508
509 if hasattr(Configurable, "_configurationLocked"):
510 Configurable._configurationLocked = True
511
512 if attach_debugger:
513 self.hookDebugger()
514
515 self.log.debug("-" * 80)
516 self.log.debug("%s: running in serial mode", __name__)
517 self.log.debug("-" * 80)
518 sysStart = time()
519
520 import Gaudi
521
522 app = Gaudi.Application.create(self.application, conf_dict)
523 retcode = app.run()
524
525 sysTime = time() - sysStart
526 self.log.debug("-" * 80)
527 self.log.debug(
528 "%s: serial system finished, time taken: %5.4fs", __name__, sysTime
529 )
530 self.log.debug("-" * 80)
531
532 return retcode
533
create(cls, appType, opts)
Definition __init__.py:129

◆ setupParallelLogging()

Gaudi.Main.gaudimain.setupParallelLogging ( self)

Definition at line 332 of file Main.py.

332 def setupParallelLogging(self):
333 # ---------------------------------------------------
334 # set up Logging
335 # ----------------
336 # from multiprocessing import enableLogging, getLogger
337 import multiprocessing
338
339 # preliminaries for handlers/output files, etc.
340 from time import ctime
341
342 datetime = ctime()
343 datetime = datetime.replace(" ", "_")
344 outfile = open("gaudirun-%s.log" % (datetime), "w")
345 # two handlers, one for a log file, one for terminal
346 streamhandler = logging.StreamHandler(stream=outfile)
347 console = logging.StreamHandler()
348 # create formatter : the params in parentheses are variable names available via logging
349 formatter = logging.Formatter(
350 "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
351 )
352 # add formatter to Handler
353 streamhandler.setFormatter(formatter)
354 console.setFormatter(formatter)
355 # now, configure the logger
356 # enableLogging( level=0 )
357 # self.log = getLogger()
358 self.log = multiprocessing.log_to_stderr()
359 self.log.setLevel(logging.INFO)
360 self.log.name = "Gaudi/Main.py Logger"
361 self.log.handlers = []
362 # add handlers to logger : one for output to a file, one for console output
363 self.log.addHandler(streamhandler)
364 self.log.addHandler(console)
365 self.log.removeHandler(console)
366 # set level!!
367 self.log.setLevel = logging.INFO
368 # ---------------------------------------------------
369

◆ writeconfig()

Gaudi.Main.gaudimain.writeconfig ( self,
filename,
all = False )

Definition at line 417 of file Main.py.

417 def writeconfig(self, filename, all=False):
418 import json
419
420 write = {
421 ".pkl": lambda filename, all: self._writepickle(filename),
422 ".py": lambda filename, all: open(filename, "w").write(
423 self.generatePyOutput(all) + "\n"
424 ),
425 ".opts": lambda filename, all: open(filename, "w").write(
426 self.generateOptsOutput(all) + "\n"
427 ),
428 ".json": lambda filename, all: json.dump(
429 getAllOpts(all), open(filename, "w"), indent=2, sort_keys=True
430 ),
431 }
432 try:
433 import yaml
434
435 write[".yaml"] = lambda filename, all: yaml.safe_dump(
436 getAllOpts(all), open(filename, "w")
437 )
438 write[".yml"] = write[".yaml"]
439 except ImportError:
440 pass # yaml support is optional
441
442 from os.path import splitext
443
444 ext = splitext(filename)[1]
445 if ext in write:
446 write[ext](filename, all)
447 else:
448 log.error(
449 "Unknown file type '%s'. Must be any of %r.", ext, sorted(write.keys())
450 )
451 sys.exit(1)
452

Member Data Documentation

◆ application

str Gaudi.Main.gaudimain.application = "Gaudi::Application"

Definition at line 330 of file Main.py.

◆ log

Gaudi.Main.gaudimain.log = logging.getLogger(__name__)

Definition at line 328 of file Main.py.

◆ printsequence

bool Gaudi.Main.gaudimain.printsequence = False

Definition at line 329 of file Main.py.


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