def __init__(self, info=None): """ Initializes the branch. If info is defined, tries to generate the branch using it. :parameter info: string describing the branch in bracket notation (e.g. [[e+],[jet]]) """ self.masses = [] self.particles = [] self.PIDs = [] self.maxWeight = None self.vertnumb = None self.vertparts = None if type(info) == type(str()): branch = elementsInStr(info) if not branch or len(branch) > 1: logger.error("Wrong input string " + info) raise SModelSError() else: branch = branch[0] vertices = elementsInStr(branch[1:-1]) for vertex in vertices: ptcs = vertex[1:-1].split(',') # Syntax check: for ptc in ptcs: if not ptc in rEven.values() \ and not ptc in ptcDic: logger.error("Unknown particle. Add " + ptc + " to smodels/particle.py") raise SModelSError() self.particles.append(ptcs) self.vertnumb = len(self.particles) self.vertparts = [len(v) for v in self.particles]
def __init__(self, info=None): """ Initializes the branch. If info is defined, tries to generate the branch using it. :parameter info: string describing the branch in bracket notation (e.g. [[e+],[jet]]) """ self.masses = [] self.particles = [] self.momID = None self.daughterID = None self.maxWeight = None if type(info) == type(str()): branch = elementsInStr(info) if not branch or len(branch) > 1: logger.error("Wrong input string " + info) sys.exit() else: branch = branch[0] vertices = elementsInStr(branch[1:-1]) for vertex in vertices: ptcs = vertex[1:-1].split(',') # Syntax check: for ptc in ptcs: if not ptc in rEven.values() \ and not ptc in ptcDic: logger.error("Unknown particle. Add " + ptc + " to smodels/particle.py") sys.exit() self.particles.append(ptcs)
def __init__(self, info=None, finalState=None): """ Initializes the element. If info is defined, tries to generate the element using it. :parameter info: string describing the element in bracket notation (e.g. [[[e+],[jet]],[[e-],[jet]]]) :parameter finalState: list containing the final state labels for each branch (e.g. ['MET', 'HSCP'] or ['MET','MET']) """ self.branches = [Branch(), Branch()] self.weight = crossSection.XSectionList() self.motherElements = [] self.elID = 0 self.covered = False self.tested = False if info: # Create element from particle string if type(info) == type(str()): elements = elementsInStr(info) if not elements or len(elements) > 1: nel = 0 if elements: nel = len(elements) logger.error("Malformed input string. Number of elements " "is %d (expected 1) in: ``%s''", nel, info) return None else: el = elements[0] branches = elementsInStr(el[1:-1]) if not branches or len(branches) != 2: logger.error("Malformed input string. Number of " "branches is %d (expected 2) in: ``%s''", len(branches), info) return None self.branches = [] for branch in branches: if branch == '[*]': self.branches.append(InclusiveBranch()) else: self.branches.append(Branch(branch)) # Create element from branch pair elif type(info) == type([]) and type(info[0]) == type(Branch()): for ib, branch in enumerate(info): self.branches[ib] = branch.copy() if finalState is None: self.setFinalState([finalState]*len(self.branches)) else: self.setFinalState(finalState)
def __init__(self, info=None, finalState=None): """ Initializes the branch. If info is defined, tries to generate the branch using it. :parameter info: string describing the branch in bracket notation (e.g. [[e+],[jet]]) :parameter finalState: final state label string for the branch (e.g. 'MET' or 'HSCP') """ from smodels.particlesLoader import rEven self.masses = [] self.particles = [] self.PIDs = [] self.maxWeight = None self.vertnumb = None self.vertparts = None self.stable = False self.finalState = None if type(info) == type(str()): branch = elementsInStr(info) if not branch or len(branch) > 1: logger.error("Wrong input string " + info) raise SModelSError() else: branch = branch[0] vertices = elementsInStr(branch[1:-1]) for vertex in vertices: ptcs = vertex[1:-1].split(',') # Syntax check: for i, ptc in enumerate(ptcs): if ptc == "*": ptc = InclusiveStr() ptcs[i] = ptc if not ptc in rEven.values() \ and not ptc in list(ptcDic.keys()): raise SModelSError("Unknown particle. Add " + ptc + " to smodels/particle.py") self.particles.append(ptcs) self.vertnumb = len(self.particles) self.vertparts = [len(v) for v in self.particles] self.setFinalState(finalState)
def _getElementsEffs(constraint,conditions): """ Generate a dictionary of elements with their simple efficiencies as values. Efficiencies are = 1. if the element appears in the constraint or conditions. """ # Get element strings appearing in constraint elStrings = elementsInStr(constraint) if not elStrings: return False if conditions: for cond in conditions: elStrings += elementsInStr(cond) elementsEff = {} if not elStrings: return False elStrings = set(elStrings) for elstr in elStrings: el = element.Element(elstr) elementsEff[el] = 1. return elementsEff
def _getElementsEffs(constraint, conditions): """ Generate a dictionary of elements with their simple efficiencies as values. Efficiencies are = 1. if the element appears in the constraint or conditions. """ # Get element strings appearing in constraint elStrings = elementsInStr(constraint) if not elStrings: return False if conditions: for cond in conditions: elStrings += elementsInStr(cond) elementsEff = {} if not elStrings: return False elStrings = set(elStrings) for elstr in elStrings: el = element.Element(elstr) elementsEff[el] = 1. return elementsEff
def __init__(self, info=None): """ Initializes the element. If info is defined, tries to generate the element using it. :parameter info: string describing the element in bracket notation (e.g. [[[e+],[jet]],[[e-],[jet]]]) """ self.branches = [Branch(), Branch()] self.weight = crossSection.XSectionList() self.motherElements = [] self.elID = 0 self.covered = False self.tested = False if info: # Create element from particle string if type(info) == type(str()): elements = elementsInStr(info) if not elements or len(elements) > 1: nel = 0 if elements: nel = len(elements) logger.error( "Malformed input string. Number of elements " "is %d (expected 1) in: ``%s''", nel, info) return None else: el = elements[0] branches = elementsInStr(el[1:-1]) if not branches or len(branches) != 2: logger.error( "Malformed input string. Number of " "branches is %d (expected 2) in: ``%s''", len(branches), info) return None self.branches = [] for branch in branches: self.branches.append(Branch(branch)) # Create element from branch pair elif type(info) == type([]) and type(info[0]) == type(Branch()): for ib, branch in enumerate(info): self.branches[ib] = branch.copy()
def __init__(self, info=None): """ Initializes the element. If info is defined, tries to generate the element using it. :parameter info: string describing the element in bracket notation (e.g. [[[e+],[jet]],[[e-],[jet]]]) """ self.branches = [Branch(), Branch()] self.weight = crossSection.XSectionList() self.motherElements = [] if info: # Create element from particle string if type(info) == type(str()): elements = elementsInStr(info) if not elements or len(elements) > 1: nel = 0 if elements: nel = len(elements) logging.error("Malformed input string. Number of elements " "is %d, expected 1: in ``%s''", nel, info) return False else: el = elements[0] branches = elementsInStr(el[1:-1]) if not branches or len(branches) != 2: logging.error("Malformed input string. Number of " "branches is %d, expected 2: in ``%s''", len(branches), info) return False self.branches = [] for branch in branches: self.branches.append(Branch(branch)) # Create element from branch pair elif type(info) == type([]) and type(info[0]) == type(Branch()): for ib, branch in enumerate(info): self.branches[ib] = branch.copy()
def _evalExpression(stringExpr,cluster,analysis): """ Auxiliary method to evaluate a string expression using the weights of the elements in the cluster. Replaces the elements in stringExpr (in bracket notation) by their weights and evaluate the expression. e.g. computes the total weight of string expressions such as "[[[e^+]],[[e^-]]]+[[[mu^+]],[[mu^-]]]" or ratios of weights of string expressions such as "[[[e^+]],[[e^-]]]/[[[mu^+]],[[mu^-]]]" and so on... :parameter stringExpr: string containing the expression to be evaluated :parameter cluster: cluster of elements (ElementCluster object) :parameter analysis: analysis (ULanalysis object). Just used to print the error message :returns: value for the expression. Can be a XSectionList object, a float or not numerical (None,string,...) """ #Generate elements appearing in the string expression with zero cross-sections: elements = [] for elStr in elementsInStr(stringExpr): el = element.Element(elStr) elements.append(el) #Replace elements in strings by their weights and add weights from cluster to the elements list: expr = stringExpr[:].replace("'","").replace(" ","") for iel, el in enumerate(elements): expr = expr.replace(str(el), "elements["+ str(iel) +"].weight") for el1 in cluster.elements: if el1.particlesMatch(el): el.weight.combineWith(el1.weight) el.combineMotherElements(el1) ## keep track of all mothers if expr.find("Cgtr") >= 0 or expr.find("Csim") >= 0: expr = expr.replace("Cgtr", "cGtr") expr = expr.replace("Csim", "cSim") logger.warning(analysis.label + " using deprecated functions " "'Cgtr'/'Csim'. Auto-replacing with 'cGtr'/'cSim'.") exprvalue = eval(expr) if type(exprvalue) == type(crossSection.XSectionList()): if len(exprvalue) != 1: logger.error("Evaluation of expression "+expr+" returned multiple values.") return exprvalue else: return exprvalue
def _evalExpression(stringExpr,cluster): """ Auxiliary method to evaluate a string expression using the weights of the elements in the cluster. Replaces the elements in stringExpr (in bracket notation) by their weights and evaluate the expression. e.g. computes the total weight of string expressions such as "[[[e^+]],[[e^-]]]+[[[mu^+]],[[mu^-]]]" or ratios of weights of string expressions such as "[[[e^+]],[[e^-]]]/[[[mu^+]],[[mu^-]]]" and so on... :parameter stringExpr: string containing the expression to be evaluated :parameter cluster: cluster of elements (ElementCluster object) :returns: xsection for the expression. Can be a XSection object, a float or not numerical (None,string,...) """ #Get cross section info from cluster (to generate zero cross section values): infoList = cluster.elements[0].weight.getInfo() #Generate elements appearing in the string expression with zero cross sections: elements = [] for elStr in elementsInStr(stringExpr): el = element.Element(elStr) el.weight = crossSection.XSectionList(infoList) elements.append(el) #Replace elements in strings by their weights and add weights from cluster to the elements list: expr = stringExpr[:].replace("'","").replace(" ","") for iel, el in enumerate(elements): expr = expr.replace(str(el), "elements["+ str(iel) +"].weight") for el1 in cluster.elements: if el1.particlesMatch(el): el.weight.combineWith(el1.weight) el.combineMotherElements(el1) ## keep track of all mothers if expr.find("Cgtr") >= 0 or expr.find("Csim") >= 0: expr = expr.replace("Cgtr", "cGtr") expr = expr.replace("Csim", "cSim") exprvalue = eval(expr) if type(exprvalue) == type(crossSection.XSectionList()): if len(exprvalue) != 1: logger.error("Evaluation of expression "+expr+" returned multiple values.") return exprvalue[0] #Return XSection object return exprvalue
def _evalExpression(stringExpr,cluster): """ Auxiliary method to evaluate a string expression using the weights of the elements in the cluster. Replaces the elements in stringExpr (in bracket notation) by their weights and evaluate the expression. e.g. computes the total weight of string expressions such as "[[[e^+]],[[e^-]]]+[[[mu^+]],[[mu^-]]]" or ratios of weights of string expressions such as "[[[e^+]],[[e^-]]]/[[[mu^+]],[[mu^-]]]" and so on... :parameter stringExpr: string containing the expression to be evaluated :parameter cluster: cluster of elements (ElementCluster object) :returns: xsection for the expression. Can be a XSection object, a float or not numerical (None,string,...) """ #Get cross section info from cluster (to generate zero cross section values): infoList = cluster.elements[0].weight.getInfo() #Get final state info finalStates = cluster.elements[0].getFinalStates() #Get weights for elements appearing in stringExpr weightsDict = {} evalExpr = stringExpr.replace("'","").replace(" ","") for i,elStr in enumerate(elementsInStr(evalExpr)): el = element.Element(elStr) el.setFinalState(finalStates) weightsDict['w%i'%i] = crossSection.XSectionList(infoList) for el1 in cluster.elements: if el1.particlesMatch(el): weightsDict['w%i'%i].combineWith(el1.weight) el.combineMotherElements(el1) evalExpr = evalExpr.replace(elStr,'w%i'%i) weightsDict.update({"Cgtr" : cGtr, "cGtr" : cGtr, "cSim" : cSim, "Csim" : cSim}) exprvalue = eval(evalExpr, weightsDict) if type(exprvalue) == type(crossSection.XSectionList()): if len(exprvalue) != 1: logger.error("Evaluation of expression "+evalExpr+" returned multiple values.") return exprvalue[0] #Return XSection object return exprvalue
def checkForRedundancy(self): """ In case of efficiency maps, check if any txnames have overlapping constraints. This would result in double counting, so we dont allow it. """ if self.getType() == "upperLimit": return False logger.debug("checking for redundancy") datasetElements = [] for tx in self.txnameList: if hasattr(tx, 'finalState'): finalState = tx.finalState else: finalState = ['MET', 'MET'] for el in elementsInStr(str(tx.constraint)): newEl = Element(el, finalState) datasetElements.append(newEl) combos = itertools.combinations(datasetElements, 2) for x, y in combos: if x.particlesMatch(y): errmsg ="Constraints (%s) appearing in dataset %s, %s overlap "\ "(may result in double counting)." % \ (x,self.getID(),self.globalInfo.id ) logger.error(errmsg) raise SModelSError(errmsg)
def checkForRedundancy ( self ): """ In case of efficiency maps, check if any txnames have overlapping constraints. This would result in double counting, so we dont allow it. """ if self.getType() == "upperLimit": return False logger.debug ( "checking for redundancy" ) datasetElements = [] for tx in self.txnameList: if hasattr(tx, 'finalState'): finalState = tx.finalState else: finalState = ['MET','MET'] for el in elementsInStr(str(tx.constraint)): newEl = Element(el,finalState) datasetElements.append(newEl) combos = itertools.combinations ( datasetElements, 2 ) for x,y in combos: if x.particlesMatch ( y ): errmsg ="Constraints (%s) appearing in dataset %s, %s overlap "\ "(may result in double counting)." % \ (x,self.getID(),self.globalInfo.id ) logger.error( errmsg ) raise SModelSError ( errmsg )
def __init__(self, path, globalObj, infoObj): self.path = path self.globalInfo = globalObj self._infoObj = infoObj self.txnameData = None self.txnameDataExp = None ## expected Data self._topologyList = TopologyList() logger.debug('Creating object based on txname file: %s' % self.path) #Open the info file and get the information: if not os.path.isfile(path): logger.error("Txname file %s not found" % path) raise SModelSError() txtFile = open(path, 'r') txdata = txtFile.read() txtFile.close() if not "txName" in txdata: raise TypeError if not 'upperLimits' in txdata and not 'efficiencyMap' in txdata: raise TypeError txfile = open(self.path) content = concatenateLines(txfile.readlines()) txfile.close() #Get tags in info file: tags = [line.split(':', 1)[0].strip() for line in content] data = None expectedData = None dataType = None for i, tag in enumerate(tags): if not tag: continue line = content[i] value = line.split(':', 1)[1].strip() if tags.count(tag) == 1: if ';' in value: value = value.split(';') if tag == 'upperLimits' or tag == 'efficiencyMap': data = value dataType = tag elif tag == 'expectedUpperLimits': expectedData = value dataType = 'upperLimits' else: self.addInfo(tag, value) else: logger.info("Ignoring unknown field %s found in file %s" \ % (tag, self.path)) continue ident = self.globalInfo.id + ":" + dataType[0] + ":" + str( self._infoObj.dataId) ident += ":" + self.txName self.txnameData = TxNameData(data, dataType, ident) if expectedData: self.txnameDataExp = TxNameData(expectedData, dataType, ident) #Builds up a list of elements appearing in constraints: elements = [] if hasattr(self, 'constraint'): elements += [Element(el) for el in elementsInStr(self.constraint)] if hasattr(self, 'condition') and self.condition: conds = self.condition if not isinstance(conds, list): conds = [conds] for cond in conds: for el in elementsInStr(cond): newEl = Element(el) if not newEl in elements: elements.append(newEl) # Builds up TopologyList with all the elements appearing in constraints # and conditions: for el in elements: el.sortBranches() self._topologyList.addElement(el)
def __init__(self, path, globalObj, infoObj): self.path = path self.globalInfo = globalObj self._infoObj = infoObj self.txnameData = None self.txnameDataExp = None ## expected Data self._topologyList = TopologyList() logger.debug('Creating object based on txname file: %s' %self.path) #Open the info file and get the information: if not os.path.isfile(path): logger.error("Txname file %s not found" % path) raise SModelSError() txtFile = open(path,'r') txdata = txtFile.read() txtFile.close() if not "txName" in txdata: raise TypeError if not 'upperLimits' in txdata and not 'efficiencyMap' in txdata: raise TypeError content = concatenateLines(txdata.split("\n")) #Get tags in info file: tags = [line.split(':', 1)[0].strip() for line in content] data = None expectedData = None dataType = None for i,tag in enumerate(tags): if not tag: continue line = content[i] value = line.split(':',1)[1].strip() if tags.count(tag) != 1: logger.info("Duplicated field %s found in file %s" \ % (tag, self.path)) if ';' in value: value = value.split(';') if tag == 'upperLimits' or tag == 'efficiencyMap': data = value dataType = tag elif tag == 'expectedUpperLimits': expectedData = value dataType = 'upperLimits' else: self.addInfo(tag,value) ident = self.globalInfo.id+":"+dataType[0]+":"+ str(self._infoObj.dataId) ident += ":" + self.txName self.txnameData = TxNameData(data, dataType, ident ) if expectedData: self.txnameDataExp = TxNameData( expectedData, dataType, ident ) #Builds up a list of elements appearing in constraints: if hasattr(self,'finalState'): finalState = self.finalState else: finalState = ["MET","MET"] elements = [] if hasattr(self,'constraint'): elements += [Element(el,finalState) for el in elementsInStr(str(self.constraint))] if hasattr(self,'condition') and self.condition: conds = self.condition if not isinstance(conds,list): conds = [conds] for cond in conds: for el in elementsInStr(str(cond)): newEl = Element(el,finalState) if not newEl in elements: elements.append(newEl) # Builds up TopologyList with all the elements appearing in constraints # and conditions: for el in elements: self._topologyList.addElement(el)
def testInStr(self): instring="[[['t+'],['W-']],[['t+'],['W-']]]+[[['t-'],['W+']],[['t-'],['W+']]]+[[['t+'],['W-']],[['t-'],['W+']]]" from smodels.theory import particleNames out= particleNames.elementsInStr( instring ) self.assertEqual ( out, ['[[[t+],[W-]],[[t+],[W-]]]', '[[[t-],[W+]],[[t-],[W+]]]', '[[[t+],[W-]],[[t-],[W+]]]'] )