ATLAS Offline Software
Loading...
Searching...
No Matches
python.hanwriter Namespace Reference

Classes

class  Document
class  HanAlgorithm
class  HanCannotCreateConf
class  HanCompositeAlgorithm
class  HanDir
class  HanHistogram
class  HanLimit
class  HanOutput
class  HanReference
class  HanThreshold
class  HanWritingError
class  Node

Functions

 _hanAddDQParameter (handocument, dqparameter, output=DQHanConfMaker._default_output)
 _findRoots (input=[], objecttype="DQRegion")
 _findAllDQBaseObjects (rootlist)
 writeHanConfiguration (filename='dq.han.config', roots=[])

Detailed Description

This module contains tools to write a DQConfiguration in han format

Function Documentation

◆ _findAllDQBaseObjects()

python.hanwriter._findAllDQBaseObjects ( rootlist)
protected
This returns all DQBase objects reachable from the rootlist as a set.

Definition at line 694 of file hanwriter.py.

694def _findAllDQBaseObjects(rootlist):
695 """
696 This returns all DQBase objects reachable from the rootlist as a set.
697 """
698 import operator
699
700 def recurse(dqbase):
701 if dqbase is None:
702 return set()
703 if isinstance(dqbase, list):
704 return reduce(operator.ior, [recurse(x) for x in dqbase])
705 if not isinstance(dqbase, DQBase):
706 raise ValueError(
707 '%s is not a valid DQBase object; this should never happen' % dqbase)
708 retset = {dqbase}
709 for rel in dqbase.getAllRelatedObjects():
710 retset |= recurse(rel)
711 return retset
712
713 topset = set()
714 for dqbase in toList(rootlist):
715 topset |= recurse(dqbase)
716 return list(topset)
717
718# Writes the han configuration to a file
719# @param roots: the list of all roots of han trees
720
721
static void reduce(HepMC::GenEvent *ge, HepMC::GenParticle *gp)
Remove an unwanted particle from the event, collapsing the graph structure consistently.
Definition FixHepMC.cxx:39
STL class.

◆ _findRoots()

python.hanwriter._findRoots ( input = [],
objecttype = "DQRegion" )
protected
This helper return the list of objects that are the roots in the tree represented by input.

Definition at line 673 of file hanwriter.py.

673def _findRoots(input=[], objecttype="DQRegion"):
674 """
675 This helper return the list of objects that are the roots in the tree represented by input.
676 """
677 result = []
678 for o in input:
679 try:
680 if o.type == objecttype:
681 if len(o.isReferencedBy) == 0:
682 result += [o]
683 except Exception:
684 raise HanCannotCreateConf(
685 "object %s is not a valid DQBase object" % o)
686 return result
687
688# Gets all DQBase objects that corresponds to the input han objects
689# @param rootlist: a list of han object trees
690# @return: the list of all DQBaseObjects associated to each node of the input tree
691# @note: This function is used internally and should not be used by users of this module
692
693

◆ _hanAddDQParameter()

python.hanwriter._hanAddDQParameter ( handocument,
dqparameter,
output = DQHanConfMaker._default_output )
protected
Add a DQParameter object to a HanDocument, Doing this it creates the tree of 
dir and output.

Definition at line 565 of file hanwriter.py.

565def _hanAddDQParameter(handocument, dqparameter, output=DQHanConfMaker._default_output):
566 """
567 Add a DQParameter object to a HanDocument, Doing this it creates the tree of
568 dir and output.
569 """
570 try:
571 if dqparameter.type != "DQParameter": # This is not valid
572 raise HanCannotCreateConf(
573 "Object: "+str(dqparameter)+" type does not match 'DQParameter'")
574 # gets the directory structure of the histogram and add it, if needed to the document
575 histoname = dqparameter.getInput().split('/')
576 theDir = handocument
577 # add directories to han document if needed
578 for directory in histoname[0:len(histoname)-1]:
579 subdir = theDir.getSubDir(directory)
580 if subdir is None:
581 subdir = theDir.addSubDir(directory)
582 theDir = subdir
583 # prepare to build the han algorithm element
584 algo = dqparameter.getAlgorithm()
585 if algo is None:
586 raise Exception('DQParameter without DQAlgorithm')
587 dqalgoname, dqalgolibrary = algo.id, algo.getLibraryName()
588 # Build the han reference, if any, associated to this DQParameter
589 dqrefname, dqreference, refs = "", dqparameter.getReference(), []
590 if dqreference != [None]: # References are defined
591 refs = '[%s]' % (','.join(_.id for _ in dqreference))
592 for iref in dqreference:
593 ref = iref.id
594 # search if reference is already in the han document
595 if handocument.getReference(ref) is None:
596 # it's not found, let's create it
597 refcompletename = iref.getReference()
598 filename = refcompletename.rpartition(':')[0]
599 refhistoname = refcompletename.rpartition(':')[
600 2].lstrip('/')
601 hanref = HanReference(
602 ref, histogramname=refhistoname, file=filename,
603 info=iref.getAnnotation('info'))
604 handocument.appendChild(hanref)
605 dqrefname = '_'+ref
606 # build the han thresholds
607 # here it's quite tricky: we have to get two sets of DQThresholds and combine them in a single
608 # han thresholds element
609 warnings = toList(dqparameter.getWarnings())
610 errors = toList(dqparameter.getErrors())
611 thresholds, hanthreshold, thresholdsname = '', None, ''
612 if (warnings != [None]) and (errors != [None]):
613 # Found errors and warnings limits
614 thresholds = dqparameter.id.replace(
615 '_', '__').replace('/', '_')+'_thr'
616 hanthreshold = HanThreshold(thresholds)
617 thresholdsname = thresholds
618 thresholds = '_'+thresholds
619
620 def getCorrespondingRed(warningname):
621 for e in errors:
622 if e.getAttribute('Name')[1] == warningname:
623 return e
624 return None
625 for warning in warnings:
626 warningname = warning.getAttribute('Name')[1]
627 error = getCorrespondingRed(warningname)
628 if error is None:
629 raise HanCannotCreateConf(
630 'Cannot find corresponding error for warning names: '+warning.id)
631 hanthreshold.addLimit(warningname, warning.getAttribute(
632 'Value')[1], error.getAttribute('Value')[1])
633 #print DQHanConfMaker._get_NodeType(hanthreshold.nodeType),hanthreshold.name
634 handocument.appendChild(hanthreshold)
635
636 # build the parameter id string and key, value pairs
637 parameterstr = '_'.join([x.id for x in toList(
638 dqparameter.getAlgorithmParameters()) if x is not None])
639 parameters = {}
640 for x in toList(dqparameter.getAlgorithmParameters()):
641 if x is None:
642 continue
643 parameters[x.getName()[1]] = x.getValue()[1][0]
644 # create a unique string identifying this han algorithm element so far
645 hanalgoname = ("%s_%s%s%s%s" % (dqalgolibrary, dqalgoname,
646 dqrefname, thresholds.replace('/', '_'), parameterstr))
647 # Finally add the histogram han element
648 theDir.addHistogram(histogram=histoname[len(histoname)-1], algorithm=hanalgoname,
649 annotations=dqparameter.getAllAnnotations(), output=output, attributes=dqparameter.getAllAttributes())
650 # search the han algorithm in the document
651 if handocument.getAlgorithm(hanalgoname) is None:
652 # This algorithm has never been added before in the document
653 node = HanAlgorithm(name=hanalgoname, algoname=dqalgoname, libname=dqalgolibrary,
654 reference=refs, thresholds=thresholdsname, parameters=parameters)
655 handocument.appendChild(node)
656 # check for possible composite algorithms
657 compalg = algo.getCompositeAlgorithm()
658 if compalg is not None:
659 node = HanCompositeAlgorithm(name=compalg.id, subalgnames=compalg.getSubAlgNames(),
660 libnames=compalg.getLibNames())
661 handocument.appendChild(node)
662 except Exception as msg:
663 raise HanCannotCreateConf(
664 "Object: "+str(dqparameter)+" is not a valid DQParameter. Reason: "+str(msg))
665
666# Finds the root han objects of the input collection
667# @param input: the list of objects @c input: a list of DQBase objects
668# @raise HanCannotCreateConf: in case of errors
669# @return: the list of roots
670# @note: This function is used internally and should not be used by users of this module
671
672
std::string replace(std::string s, const std::string &s2, const std::string &s3)
Definition hcg.cxx:310
std::vector< std::string > split(const std::string &s, const std::string &t=":")
Definition hcg.cxx:177

◆ writeHanConfiguration()

python.hanwriter.writeHanConfiguration ( filename = 'dq.han.config',
roots = [] )
Writes the configuration to a han file. 
The configuration has to be passed as a list of roots in han configuration.

Definition at line 722 of file hanwriter.py.

722def writeHanConfiguration(filename='dq.han.config', roots=[]):
723 """
724 Writes the configuration to a han file.
725 The configuration has to be passed as a list of roots in han configuration.
726 """
727 configList = _findAllDQBaseObjects(roots)
728 # First remove the configuration elements that cannot be saved as han
729 for element in configList:
730 try:
731 if not DQHanConfMaker._isAceptedHanElement(element):
732 print("==========WARNING===========")
733 print("Object: " + \
734 str(element) + \
735 " does not have a valid han representation, cannot save")
736 print("The object is referenced by:", element.isReferencedBy)
737 print("You may need to manually edit the configuration")
738 print("============================")
739 configList.remove(element)
740 except Exception:
741 print(element.isReferencedBy)
742 raise HanCannotCreateConf("Not valid object:" + str(element))
743 # Let's create the han document
744 doc = Document()
745 # Find all root regions
746 rootregions = _findRoots(configList)
747
748 # Navigate through DQRegions tree and add it to the han document
749 def _addchild(hanfather, dqregion, handocument):
750 outputalgo = dqregion.getAlgorithm()
751 if handocument.getAlgorithm(outputalgo.id) is None:
752 # Add to the document the summary maker algorithm
753 # summary makers do not have thresholds or parameters
754 # @todo: in the future extend this to make in enough general to support parameter
755 handocument.appendChild(HanAlgorithm(
756 outputalgo.id, outputalgo.id, outputalgo.getLibraryName())) # , reference, thresholds)
757 output = hanfather.addOutput(dqregion.id, outputalgo.id, annotations=dqregion.getAllAnnotations(
758 ), attributes=dqregion.getAllAttributes())
759 # recursively add subregions
760 for subregion in dqregion.getSubRegions():
761 if subregion is not None:
762 _addchild(output, subregion, doc)
763 # Add each DQParameter to the han document with the helper
764 for parameter in dqregion.getDQParameters():
765 if parameter is not None:
766 _hanAddDQParameter(handocument, parameter,
767 output=output.getOutputPath())
768
769 for region in rootregions:
770 _addchild(doc, region, doc)
771
772 fileout = open(filename, 'w')
773 print(doc.toprettyhan(" "), file=fileout)
void print(char *figname, TCanvas *c1)