The Gaudi Framework  master (9f3f8895)
Loading...
Searching...
No Matches
Gaudi.Main.gaudimain Class Reference

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 390 of file Main.py.

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

◆ 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(f"{key} = {toOpt(parseOpt(opts[key]))};" for key in keys)
389

◆ 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 462 of file Main.py.

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

◆ printconfig()

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

Definition at line 404 of file Main.py.

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

◆ run()

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

Definition at line 453 of file Main.py.

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

◆ runParallel()

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

Definition at line 532 of file Main.py.

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

◆ runSerial()

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

Definition at line 490 of file Main.py.

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

◆ 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(f"gaudirun-{datetime}.log", "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 415 of file Main.py.

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

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: