TopoAlgos.py 15.6 KB
Newer Older
1
2
# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration

3
4
from collections import OrderedDict as odict

5
6
7
8
from AthenaCommon.Logging import logging
from TriggerJobOpts.TriggerFlags import TriggerFlags
import re

9
10
from .ThresholdType import ThrType

11
log = logging.getLogger(__name__)
12

13
14
15
16
17
18
19
##
## These classes are base classes for the auto-generated algorithm python representations
## 
## C++ L1Topo algorithms are defined in Trigger/TrigT1/L1Topo/L1TopoAlgorithms
## During the build, from each class a python class is generated and put in the release
## Those generated python classes derive fro SortingAlgo and DecisionAlgo below.

20
21
22
23
24
class TopoAlgo(object):

    _availableVars = []

    #__slots__ = ['_name', '_selection', '_value', '_generic']
25
    def __init__(self, classtype, name, algoId=-1):
26
27
        self.classtype = classtype
        self.name = name
28
        self.algoId = algoId
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
        self.generics = []
        self.variables = []
        
    def __str__(self):  
        return self.name

    def isSortingAlg(self):
        return False

    def isDecisionAlg(self):
        return False

    def isMultiplicityAlg(self):
        return False

44
45
46
    def setThresholds(self, thresholds):
        # link to all thresholds in the menu need for configuration
        self.menuThr = thresholds
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

    def addvariable(self, name, value, selection = -1):
        if name in self._availableVars:
            self.variables += [ Variable(name, selection, value) ]
        else:
            raise RuntimeError("Variable parameter '%s' does not exist for algorithm %s of type %s,\navailable parameters are %r" % (name,self.name, self.classtype, self._availableVars))
        return self

    def addgeneric(self, name, value):
        if name in self._availableVars:
            self.generics += [ Generic(name, value) ]
        else:
            raise RuntimeError("Generic parameter '%s' does not exist for algorithm %s of type %s,\navailable parameters are %r" % (name,self.name, self.classtype, self._availableVars))
        return self

    def json(self):
        confObj = odict()
        confObj["algId"] = self.algoId
65
        confObj["klass"] = self.classtype
66
67
        return confObj

68
    def getScaleToCountsEM(self):  # legacy Et conversion!!
69
        tw = self.menuThr.typeWideThresholdConfig(ThrType["EM"])
70
        return 1000 // tw["resolutionMeV"]
71

72
73
74
75
76
77
78
79
80
81
82
83
84
class Variable(object):
    def __init__(self, name, selection, value):
        self.name = name
        self.selection = int(selection)
        self.value = int(value)
            
class Generic(object):
    def __init__(self, name, value):
        self.name = name
        from L1TopoHardware.L1TopoHardware import HardwareConstrainedParameter
        if isinstance(value,HardwareConstrainedParameter):
            self.value = ":%s:" % value.name
        else:
85
            self.value = value
86
87
88
89
90
91
92
93
94
95
96

        
class SortingAlgo(TopoAlgo):
    
    def __init__(self, classtype, name, inputs, outputs, algoId):
        super(SortingAlgo, self).__init__(classtype=classtype, name=name, algoId=algoId)
        self.inputs = inputs
        self.outputs = outputs
        self.inputvalue=  self.inputs
        if self.inputs.find("Cluster")>=0: # to extract inputvalue (for FW) from output name
            if self.outputs.find("TAU")>=0:
97
                self.inputvalue= self.inputvalue.replace("Cluster","Tau")
98
99
100
101
102
103
104
            if self.outputs.find("EM")>=0:
                self.inputvalue= self.inputvalue.replace("Cluster","Em")

    def isSortingAlg(self):
        return True
        
    def json(self):
105
106
        confObj = super(SortingAlgo, self).json()
        confObj["input"] = self.inputvalue
107
108
109
110
111
112
113
        confObj["output"] = self.outputs
        confObj["fixedParameters"] = odict()
        confObj["fixedParameters"]["generics"] = odict()
        for (pos, genParm) in enumerate(self.generics):
            confObj["fixedParameters"]["generics"][genParm.name] = odict([("value", genParm.value), ("position", pos)]) 

        confObj["variableParameters"] = list()
114
115
116
117
        _emscale_for_decision = self.getScaleToCountsEM() # for legacy algos
        _mu_for_decision= 10 # MU4->3GeV, MU6->5GeV, MU10->9GeV because selection is done by pt>X in 100 MeV units for Run3 muons
        if "MUCTP-" in self.name:
            _mu_for_decision= 1 
118
119
        for (pos, variable) in enumerate(self.variables): 
            if variable.name == "MinET":
120
121
122
                if "e" in self.outputs or "j" in self.outputs or "g" in self.outputs: 
                    variable.value *= 1 # no conversion needed in Run3 algo
                elif "TAU" in self.outputs or "EM" in self.outputs:
123
                    variable.value *= _emscale_for_decision
124
125
                if "MU" in self.outputs:
                    variable.value = ((variable.value - _mu_for_decision ) if variable.value>0 else variable.value)
126
            confObj["variableParameters"].append(odict([("name", variable.name),("value", variable.value)]))
127
128
129

            if type(variable.value) == float:
                raise RuntimeError("In algorithm %s the variable %s with value %r is of type float but must be int" % (self.name,variable.name,variable.value))
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
        return confObj

    def xml(self):
        _emscale_for_decision=2
        _mu_for_decision=1 # MU4->3GeV, MU6->5GeV, MU10->9GeV
        if hasattr(TriggerFlags, 'useRun1CaloEnergyScale'):
            if TriggerFlags.useRun1CaloEnergyScale :
                _emscale_for_decision=1
                log.info("Changed mscale_for_decision %s for Run1CaloEnergyScale", _emscale_for_decision)
        
        s='  <SortAlgo type="%s" name="%s" output="%s" algoId="%i">\n' % (self.classtype, self.name, self.outputs, self.algoId)
        s+='    <Fixed>\n'
        s+='      <Input name="%s" value="%s"/>\n' % (self.inputs, self.inputvalue) 
        s+='      <Output name="TobArrayOut" value="%s"/>\n' % (self.outputs)
        for gene in self.generics:
            s += '      <Generic name="%s" value="%s"/>\n' % (gene.name, gene.value)
        s+='    </Fixed>\n'            
        s+='    <Variable>\n'

        for (pos, variable) in enumerate(self.variables):
            # scale MinET if outputs match with EM or TAU
            if variable.name=="MinET" and (self.outputs.find("TAU")>=0 or self.outputs.find("EM")>=0):
                variable.value = variable.value * _emscale_for_decision
            if variable.name=="MinET" and self.outputs.find("MU")>=0:
                variable.value = ((variable.value - _mu_for_decision) if variable.value>0 else variable.value)
            s+='      <Parameter pos="%i" name="%s" value="%i"/>\n' % ( pos, variable.name, variable.value )
        s+='    </Variable>\n'    
        s+='  </SortAlgo>\n'
        return s


class DecisionAlgo(TopoAlgo):

    def __init__(self, classtype, name, inputs, outputs, algoId):
        super(DecisionAlgo, self).__init__(classtype=classtype, name=name, algoId=algoId)
        self.inputs = inputs if type(inputs)==list else [inputs]
        self.outputs = outputs if type(outputs)==list else [outputs]

    def isDecisionAlg(self):
        return True

    def json(self):
172
173
        confObj = super(DecisionAlgo, self).json()
        confObj["input"] = self.inputs # list of input names
174
175
176
177
178
179
180
181
182
        confObj["output"] = self.outputs # list of output names
        # fixed parameters
        confObj["fixedParameters"] = odict()
        confObj["fixedParameters"]["generics"] = odict()
        for (pos, genParm) in enumerate(self.generics):
            confObj["fixedParameters"]["generics"][genParm.name] = odict([("value", genParm.value), ("position", pos)]) 

        # variable parameters
        confObj["variableParameters"] = list()
183
184
185
186
        _emscale_for_decision = self.getScaleToCountsEM() # for legacy algos
        _mu_for_decision= 10 # MU4->3GeV, MU6->5GeV, MU10->9GeV because selection is done by pt>X in 100 MeV units for Run3 muons
        if "MUCTP-" in self.name:
            _mu_for_decision= 1 
187
188
189
190
191
        for (pos, variable) in enumerate(self.variables):
            # scale MinET if inputs match with EM or TAU
            for _minet in ["MinET"]:
                if variable.name==_minet+"1" or variable.name==_minet+"2" or variable.name==_minet+"3" or variable.name==_minet:
                    for (tobid, _input) in enumerate(self.inputs):
192
193
194
                        if (_input.find("e")>=0 or _input.find("j")>=0 or _input.find("g")>=0):
                            variable.value *= 1 # no conversion needed in Run3 algo
                        elif (_input.find("TAU")>=0 or _input.find("EM")>=0):
195
196
197
198
199
200
201
                            if (len(self.inputs)>1 and (variable.name==_minet+str(tobid+1) or (tobid==0 and variable.name==_minet))) or (len(self.inputs)==1 and (variable.name.find(_minet)>=0)):
                                variable.value *= _emscale_for_decision

                        if _input.find("MU")>=0:
                            if (len(self.inputs)>1 and (variable.name==_minet+str(tobid+1) or (tobid==0 and variable.name==_minet))) or (len(self.inputs)==1 and (variable.name.find(_minet)>=0)):
                                variable.value = ((variable.value - _mu_for_decision ) if variable.value>0 else variable.value)

202
203
204
            if type(variable.value) == float:
                raise RuntimeError("In algorithm %s the variable %s with value %r is of type float but must be int" % (self.name,variable.name,variable.value))

205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
            if variable.selection >= 0:
                confObj["variableParameters"].append(odict([("name", variable.name), ("selection",variable.selection), ("value", variable.value)]))
            else:
                confObj["variableParameters"].append(odict([("name", variable.name), ("value", variable.value)]))

        return confObj


    def xml(self): 
        _emscale_for_decision=2
        _mu_for_decision=1 
        if hasattr(TriggerFlags, 'useRun1CaloEnergyScale'):
            if TriggerFlags.useRun1CaloEnergyScale :
                _emscale_for_decision=1
                log.info("Changed mscale_for_decision %s for Run1CaloEnergyScale", _emscale_for_decision)
        
        s='  <DecisionAlgo type="%s" name="%s" algoId="%i">\n' % (self.classtype, self.name, self.algoId )
        s+='    <Fixed>\n'
        input_woovlp = []
        for (tobid, _input) in enumerate(self.inputs):
            if len(self.inputs)>1:
                if _input not in input_woovlp:
                    s+='      <Input name="Tob%s" value="%s" position="%s"/>\n' % (str(tobid+1), _input, str(tobid))
                    input_woovlp += [_input]
                else:
                    s+='      <Input name="Tob%s" value="%s" position="%s"/>\n' % (str(tobid+1), _input, str(tobid))
            else:
                s+='      <Input name="Tob" value="%s" position="%s"/>\n' % (_input, str(tobid))
        s+='      <Output name="Results" bits="%s">\n' % str(len(self.outputs))
        for (bitid, _output) in enumerate(self.outputs):
            s+='        <Bit selection="%s" name="%s"/>\n' % (str(bitid), _output)
        s+='      </Output>\n'
        for gene in self.generics:
            s += '      <Generic name="%s" value="%s"/>\n' % (gene.name, gene.value)
        s+='    </Fixed>\n'     
        s+='    <Variable>\n'

        for (pos, variable) in enumerate(self.variables):
            # scale MinET if inputs match with EM or TAU
            for _minet in ["MinET"]:
                if variable.name==_minet+"1" or variable.name==_minet+"2" or variable.name==_minet+"3" or variable.name==_minet:
                    for (tobid, _input) in enumerate(self.inputs):
                        if (_input.find("TAU")>=0 or _input.find("EM")>=0):
                            if (len(self.inputs)>1 and (variable.name==_minet+str(tobid+1) or (tobid==0 and variable.name==_minet))) or (len(self.inputs)==1 and (variable.name.find(_minet)>=0)):
                                variable.value = variable.value * _emscale_for_decision

                        if _input.find("MU")>=0:
                            if (len(self.inputs)>1 and (variable.name==_minet+str(tobid+1) or (tobid==0 and variable.name==_minet))) or (len(self.inputs)==1 and (variable.name.find(_minet)>=0)):
                                variable.value = ((variable.value - _mu_for_decision ) if variable.value>0 else variable.value)
                            
            s+='      <Parameter pos="%i" name="%s"%s value="%i"/>\n' % ( pos, variable.name, ((' selection="%i"'%variable.selection) if (variable.selection>=0) else ""), variable.value )
        s+='    </Variable>\n'    
        s+='  </DecisionAlgo>\n'
        return s




class MultiplicityAlgo(TopoAlgo):

    def __init__(self, classtype, name, algoId, threshold, input, output, nbits):
        super(MultiplicityAlgo, self).__init__(classtype=classtype, name=name, algoId=algoId)
        self.threshold = threshold
        self.input = input
        self.outputs = output
        self.nbits = nbits

    def isMultiplicityAlg(self):
        return True            

    def configureFromThreshold(self, thr):
        pass

    def json(self):
279
        confObj = super(MultiplicityAlgo, self).json()
280
281
282
283
284
285
286
        confObj["threshold"] = self.threshold
        confObj["input"] = self.input
        confObj["output"] = self.outputs
        confObj["nbits"] = self.nbits
        return confObj


287
class eEmMultiplicityAlgo(MultiplicityAlgo):
288
    def __init__(self, name, algoId, threshold, nbits, classtype ):
289
        super(eEmMultiplicityAlgo, self).__init__(classtype=classtype, name=name, 
290
291
292
293
                                                 algoId=algoId, 
                                                 threshold = threshold, 
                                                 input=None, output="%s" % threshold,
                                                 nbits=nbits)
294
        mres = re.match("(?P<type>[A-z]*)[0-9]*(?P<suffix>[VHILMT]*)",threshold).groupdict()
295
296
297
        self.input = mres["type"]

class TauMultiplicityAlgo(MultiplicityAlgo):
298
    def __init__(self, name, algoId, threshold, nbits, classtype ):
299
300
301
        super(TauMultiplicityAlgo, self).__init__(classtype=classtype, name=name, 
                                                  algoId=algoId, 
                                                  threshold = threshold, 
302
                                                  input=None, output="%s" % threshold,
303
                                                  nbits=nbits)
304
305
        mres = re.match("(?P<type>[A-z]*)[0-9]*(?P<suffix>[HLMT]*)",threshold).groupdict()
        self.input = mres["type"]
306
307

class JetMultiplicityAlgo(MultiplicityAlgo):
308
    def __init__(self, name, algoId, threshold, nbits, classtype ):
309
310
311
        super(JetMultiplicityAlgo, self).__init__(classtype=classtype, name=name, 
                                                  algoId=algoId, 
                                                  threshold = threshold, 
312
                                                  input=None, output="%s" % threshold,
313
                                                  nbits=nbits)
314
315
        mres = re.match("(?P<type>[A-z]*)[0-9]*(?P<suffix>[A-z]*)",threshold).groupdict()
        self.input = mres["type"]
316
317

class XEMultiplicityAlgo(MultiplicityAlgo):
318
    def __init__(self, name, algoId, threshold, nbits, classtype = "EnergyThreshold"):
319
320
321
        super(XEMultiplicityAlgo, self).__init__( classtype = classtype, name=name, 
                                                  algoId = algoId, 
                                                  threshold = threshold, 
322
                                                  input=None, output="%s" % threshold,
323
324
325
326
327
328
329
330
331
                                                  nbits=nbits)


class MuMultiplicityAlgo(MultiplicityAlgo):
    def __init__(self, classtype, name, algoId, input, output, nbits):
        super(MuMultiplicityAlgo, self).__init__(classtype=classtype, name=name, algoId=algoId, input=input, output=output, nbits=nbits)

    def configureFromThreshold(self, thr):
        pass