Пример #1
0
    def __init__(self, poolfile, **args):
        """An AOD file pointer (not a string) must be given as argument"""

        self.__dict__.__setitem__("_TriggerConfigARA__curConf",
                                  _TrigConfHolder())
        self.__currentIOV = {}
        self.verbose = False
        if 'verbose' in args: self.verbose = args['verbose']

        plcClass = cppyy.makeClass("IOVPayloadContainer")
        plcClass.iter = _iter

        tiClass = cppyy.makeClass("TrigConf::TriggerItem")
        tiClass.__str__ = lambda x: "%s (ctpid %i), ps %g" % (x.name(),
                                                              x.ctpId(), x.ps)

        chClass = cppyy.makeClass("TrigConf::HLTChain")
        chClass.__str__ = _chPrint

        ROOT.IOVTime.__str__ = lambda x: "%i/%i" % (x.run(), x.event())
        ROOT.IOVTime.__lt__ = lambda s, o: s.run() < o.run() or s.run(
        ) == o.run() and s.event() < o.event()
        ROOT.IOVTime.__eq__ = lambda s, o: s.run() == o.run() and s.event(
        ) == o.event()
        ROOT.IOVTime.__le__ = lambda s, o: s < o or s == o
        ROOT.IOVRange.__str__ = lambda x: "%s - %s" % (x.start(), x.stop())
        ROOT.IOVRange.isInRange = lambda x, e: x.start() <= e and e < x.stop()

        print("Opening file(s) and creating transient metadata ...")
        if type(poolfile) == list:
            self._collection = ROOT.AthenaROOTAccess.TChainROOTAccess(
                'MetaData')
            for file in poolfile:
                self._collection.Add(file)
            self.mdt = AthenaROOTAccess.transientTree.makeTree(
                self._collection,
                persTreeName='MetaData',
                dhTreeName='MetaDataHdr',
                dhfilt=_elemFilter)
        else:
            treeNames = [k.GetName() for k in poolfile.GetListOfKeys()]
            if "MetaDataHdrDataHeader" in treeNames:
                dhTreeName = 'MetaDataHdrDataHeader'  # old style
            else:
                dhTreeName = 'MetaDataHdr'
            self.mdt = AthenaROOTAccess.transientTree.makeTree(
                poolfile,
                persTreeName='MetaData',
                dhTreeName=dhTreeName,
                dhfilt=_elemFilter)

        for key in self.__class__.__keysInUpdateOrder:
            if not hasattr(self.mdt, self.__class__.__folderName[key]):
                print("No key %s in file %s, use checkFile.py to verify" %
                      (self.__class__.__folderName[key], poolfile))
                sys.exit(0)
Пример #2
0
def deserialize_string(lwords):
    """Wrapper for the C++ StringSerializer"""

    v = cppyy.makeClass('std::vector<unsigned int>')()
    s = cppyy.makeClass('std::string')()
    v.reserve(len(lwords))
    for w in lwords:
        v.push_back(w)
    stringSerializer.deserialize(v, s)
    return str(s)
Пример #3
0
    def BadChan_GetCoolChannelNameFromHWIdentifier(self,sHWid):
        """ Get channel name from HW identifier (only for text menu purpose)"""

        self.class_LArBadChannelState=cppyy.makeClass('LArBadChannelState')
        inst_larBadChannelState=self.class_LArBadChannelState()
        
        sChannelName=""
        if self.onlineID.isEMBchannel(sHWid):
            if self.onlineID.pos_neg(sHWid)==1:
                iEnumChannel=inst_larBadChannelState.EMBA
            else:
                iEnumChannel=inst_larBadChannelState.EMBC
        if self.onlineID.isEMECchannel(sHWid):
            if self.onlineID.pos_neg(sHWid)==1:
                iEnumChannel=inst_larBadChannelState.EMECA
            else:
                iEnumChannel=inst_larBadChannelState.EMECC
        if self.onlineID.isHECchannel(sHWid):
            if self.onlineID.pos_neg(sHWid)==1:
                iEnumChannel=inst_larBadChannelState.HECA
            else:
                iEnumChannel=inst_larBadChannelState.HECC
        if self.onlineID.isFCALchannel(sHWid):
            if self.onlineID.pos_neg(sHWid)==1:
                iEnumChannel=inst_larBadChannelState.FCALA
            else:
                iEnumChannel=inst_larBadChannelState.FCALC
        
        sChannelName=inst_larBadChannelState.coolChannelName(iEnumChannel)+" ("+str(iEnumChannel)+")"
        return sChannelName
Пример #4
0
    def getMultiCondContainer(self, channels, attrListColl, iovs):

        # Args:
        #   channels     - list of channels from COOL
        #   attrListColl - collection of AttributeLists with string address from COOL for each channel
        #   iovs         - list of IOVs for each channel
        #   cont         - the LArConditionsContainer object

        # Print out channels and IOV
        print("Channels, IOV, and string addresses")
        i = 0
        for chan in channels:
            iov = iovs[i]
            print("added chan/iov: ", chan, iov.iovPrint())
            i += 1

        # print out collection
        #attrListColl.dump()

        # Must set dummy string address to include type name for
        # AthenaPoolCnvSvc statistics gathering
        strAddress = self.header

        # Get IOpaqueAddress
        print("Create IOpaqueAddress pointer")
        ioa = PyLCGDict.libPyROOT.MakeNullPointer('GenericAddress')

        # Get DataBucketBase pointer
        print("Create DataBucketBase pointer")
        dbb = PyLCGDict.libPyROOT.MakeNullPointer('DataBucketBase')

        # Create IOA from string address
        print("Create IOpaqueAddress for address list")
        sc = self.iaddr.createAddress(0, 0, strAddress, ioa)
        print("Status code: ", sc)

        # Create CondAttrListCollAddress and add in attribute list
        CondAttrListCollAddress = PyLCGDict.makeClass(
            'CondAttrListCollAddress')
        collAddr = CondAttrListCollAddress(ioa)
        collAddr.setAttrListColl(attrListColl)

        # Read in object as DataObject (or DatabucketBase)
        print("Retrieve data object for IOA")
        sc = self.icnv.createObj(collAddr, dbb)
        print("Status code: ", sc)
        if sc.isFailure(): raise RuntimeError("Cannot read object")

        # Cast to correct type and return it
        print("cast data object to correct type: ", self.typeName)
        result = PyLCGDict.libPyROOT.MakeNullPointer(self.type)
        self.dbCast.castObject(self.typeName, dbb, result)

        # Reset iterator to allow a new type - bug in pyroot
        #self.pyroot_typedef_bug_workaround()

        return result
Пример #5
0
    def setDescription(self, descr):
        self.descr = descr
        # extract type name and type
        decoder = DescriptionDecoder(descr)
        self.typeName = decoder.extract('<typeName>', '</typeName>')
        self.type = PyLCGDict.makeClass(self.typeName)
        # extract the address header
        self.header = decoder.extract('<addrHeader>', '</addrHeader>')
        self.header += 'POOLContainer_CondAttrListCollection][CLID=x'

        print("Type name, type, header ", self.typeName, self.type,
              self.header)
Пример #6
0
    def __init__(self, theApp):
        # PersistencySvc
        pers = theApp.service('EventPersistencySvc')

        # PersistencySvc via its IConverter interface
        iConverter = InterfaceRDS('IConverter')
        self.icnv = iConverter.cast(pers)

        # PersistencySvc via its IAddressCreator interface
        iAddrCreator = InterfaceRDS('IAddressCreator')
        self.iaddr = iAddrCreator.cast(pers)

        # Create instance of cast object
        self.dbCast = PyLCGDict.makeClass('DataBucketCast')
Пример #7
0
    def __init__(self, t):

        # t is either the class name or the class itself
        if type(t) is str:
            self.typeName = t
            t = cppyy.makeClass(t)
        else:
            self.typeName = t.type.__name__

        # Save type
        self.type = t

        # Add on iterators for the different containers
        self.type.conditionsIter = conditionsIter
        self.type.correctionsIter = correctionsIter
        self.type.coolChannelIter = coolChannelIter
        self.type.coolIOVIter = coolIOVIter
Пример #8
0
 def init(name):
     """Initialize the python binding with the callback previously registered
     If no callback was registered, swallow the warning...
     """
     klass = None
     try: klass = _PyAthenaBindingsCatalog.instances[name]()
     except KeyError:
         ROOT = _import_ROOT()
         from AthenaServices.Dso import registry
         registry.load_type (name)
         try:
             import cppyy
             #klass = getattr(ROOT, name)
             klass = cppyy.makeClass(name)
         except AttributeError:
             raise AttributeError("no reflex-dict for type [%s]"%name)
     return klass
Пример #9
0
 def init(name):
     """Initialize the python binding with the callback previously registered
     If no callback was registered, swallow the warning...
     """
     klass = None
     try:
         klass = _PyAthenaBindingsCatalog.instances[name]()
     except KeyError:
         ROOT = _import_ROOT()  # noqa: F841
         from AthenaServices.Dso import registry
         registry.load_type(name)
         try:
             import cppyy
             #klass = getattr(ROOT, name)
             klass = cppyy.makeClass(name)
         except AttributeError:
             raise AttributeError("no reflex-dict for type [%s]" % name)
     return klass
Пример #10
0
    def inspect(self, typename):
        if self.debug: print 'inspecting ', typename

        dontAdd = False

        for b in self.blacklist:
            if typename.find(b) == 0:
                if self.debug: print 'blacklisted ', typename
                dontAdd = True

        # print self.classlist
        if typename in self.classlist:
            if self.debug: print 'seen before ', typename
            dontAdd = True

        try:
            t = self.type.ByName(typename)
            print t
            if t.IsFundamental():
                if self.debug: print typename, ' is fundamental'
                return
            if t.IsAbstract():
                dontAdd = True
        except:
            pass

        try:
            cl = cppyy.makeClass(typename)
            if not dontAdd: self.classlist.append(typename)
        except:
            print 'Cannot create class of ', typename

        t = self.type.ByName(typename)

        if t.IsComplete():
            if self.debug: print typename, 'is complete'
        else:
            print typename, ' isn\'t complete'

        if t.IsPointer():
            if self.debug: print typename, ' is a pointer'
        elif t.IsTypedef():
            if self.debug: print typename, ' is typedef'
            underlying = t.ToType()
            if (underlying):
                self.inspect(underlying.Name(7))
        elif t.IsArray():
            print typename, ' is an array'
        elif t.IsTemplateInstance():
            print typename, ' is template'
            if typename.find('std::') == 0:
                print 'std::business removed'
                try:
                    self.classlist.remove(typename)
                except:
                    pass
            for i in range(t.TemplateArgumentSize()):
                tt = t.TemplateArgumentAt(i)
                ttname = tt.Name(7)
                if tt.IsPointer() or tt.IsArray() or tt.IsTypedef():
                    ttname = tt.ToType().Name(7)
                self.inspect(ttname)
        elif t.IsClass():
            if self.debug: print typename, ' is a class'
            cname = t.Name(7)
            if self.debug: print cname

            for i in range(t.DataMemberSize()):
                d = t.DataMemberAt(i)
                dname = d.Name()
                dtype = d.TypeOf().Name(7)
                if self.debug:
                    print 'DataMember: ', dname, ' ', dtype, '  transient=', d.IsTransient(
                    )
                if not d.IsTransient():
                    self.inspect(dtype)

        else:
            print 'what to do about ', typename, '?'
            self.problemclasses.append(typename)
            return
Пример #11
0
 def __init__(self, t):
     if type(t) is str: t = PyLCGDict.makeClass(t)
     #  print "type is string: ",t
     #  t = PyLCGDict.makeClass(t)
     #t = PyLCGDict.makeClass(t)
     self.type = t
Пример #12
0
    def BadChan_SaveBadChannelCorrectionsToDatabase(self,dbstring,dbSvc,dbFolderName,selectedTag):

        listKeys=self.dict_vectBadChanEntry.keys()
        listKeys.sort()

        # Create LArBadChannel object for defined BadChanEntry vector and coolChan
        self.class_LArBadChannelState=cppyy.makeClass('LArBadChannelState')
        inst_larBadChannelState=self.class_LArBadChannelState()

        # Loop over cool channels
        bNewDBCreated=False
        for coolChan in listKeys:

            vect_BadChanEntry=cppyy.gbl.std.vector('std::pair<HWIdentifier,LArBadChannel>')()
            
            listHWidKeys=[x for x in self.dict_vectBadChanEntry[coolChan].keys()]
            listHWidKeys.sort()
            iNbCorrection=0
            for key in listHWidKeys:
                
                sHWid=key
                if self.dict_vectBadChanEntry_Status[coolChan][sHWid]==STATUS_INIT:
                    badChan_word=self.dict_vectBadChanEntry_Init[coolChan][sHWid][1]
                elif self.dict_vectBadChanEntry_Status[coolChan][sHWid]==STATUS_MODIFIED or self.dict_vectBadChanEntry_Status[coolChan][sHWid]==STATUS_NEW:
                    iNbCorrection += 1
                    badChan_word=self.dict_vectBadChanEntry[coolChan][sHWid][1]
                elif self.dict_vectBadChanEntry_Status[coolChan][sHWid]==STATUS_REMOVED:
                    iNbCorrection += 1
                    continue
            
                obj_HWid=self.class_HWIdentifier()
                obj_HWid.set(sHWid)
                larBadChannel=self.class_LArBadChannel(badChan_word)

                pair_BadChanEntry=cppyy.gbl.pair('HWIdentifier,LArBadChannel')(obj_HWid, larBadChannel)
                vect_BadChanEntry.push_back(pair_BadChanEntry)

            # if correction were made => store BadChanEntry vector
            if iNbCorrection>0:
                for sEntry in vect_BadChanEntry:
                    inst_larBadChannelState.add(sEntry,coolChan)
            else:
                continue

            # Create object based on new LArBadChannelState (via LArBadChannelDBTools python interface) 
            attrListSpec=cppyy.gbl.coral.AttributeListSpecification()
            athenaAttrList=cppyy.gbl.AthenaAttributeList()
        
            attrListSpec=self.nspace_LArBadChannelDBTools.createCoolSpec()
            athenaAttrList=self.nspace_LArBadChannelDBTools.createPayload(inst_larBadChannelState.coolChannel(coolChan), attrListSpec)

            # if save DB has not been created => do it
            if bNewDBCreated is False:
                try:
                    dbSave = dbSvc.createDatabase(dbstring)
                except Exception as e:
                    print ('Problem opening database',e)
                    sys.exit(-1)
                print ("Opened database",dbstring)

                desc='<timeStamp>run-event</timeStamp><addrHeader><address_header service_type="71" clid="40774348" /></addrHeader><typeName>AthenaAttributeList</typeName>'

                # Create cool spec from AttributeListSpec
                coolSpec=cool.RecordSpecification()
                for iElemt in range(0,attrListSpec.size()):
                    attrSpec=attrListSpec[iElemt]
                    typeName=attrSpec.typeName()
                    if typeName=="unsigned int":
                        coolSpec.extend(attrSpec.name(),cool.StorageType.UInt32)
                    elif typeName=="blob":
                        coolSpec.extend(attrSpec.name(),cool.StorageType.Blob64k)
                    else:
                        print ("Undefined cool.StorageType "+typeName)

#                myfolder=dbSave.createFolder(dbFolderName, coolSpec, desc, cool.FolderVersioning.SINGLE_VERSION,True)
                myfolder=dbSave.createFolder(dbFolderName, coolSpec, desc, cool.FolderVersioning.MULTI_VERSION,True)

                import string
                IOVBeginEnd=["90","9999999"]
                beginRun = string.atoi(IOVBeginEnd[0]) << 32
                endRun   = string.atoi(IOVBeginEnd[1]) << 32

                bNewDBCreated=True

            # Create cool payload from AthenaAttributeList payload
            coolPayload=cool.Record(coolSpec)
            for iElemt in range(0,attrListSpec.size()):
                attrSpec=attrListSpec[iElemt]
                coolPayload[attrSpec.name()]=athenaAttrList[attrSpec.name()]

            # Store cool object to folder
            myfolder.storeObject(beginRun,endRun,coolPayload,coolChan,selectedTag)
            
        # Close new databse
        if bNewDBCreated is True:
            dbSave.closeDatabase()
Пример #13
0
                iovStop = "until " + str(ctime(stop.timestamp() / 1000000000))
        except Exception, e:
            print "## Caught exception [%s] !!" % str(e.__class__)
            print "## What:", e
            import sys
            print sys.exc_info()[0]
            print sys.exc_info()[1]
            sc = 1
            return "Invalid"
    output = iovStart + iovStop
    return output


if __name__ == "__main__":

    t = cppyy.makeClass("IOVPayloadContainer")
    # Add on iterators for the different containers
    t.iter = iter
    #print "t type ",t
    t = cppyy.makeClass("CondAttrListCollection")
    # Add on iterators for the different containers
    t.attr_iter = attr_iter
    t.iov_iter = iov_iter
    t.name_iter = name_iter
    t = cppyy.makeClass("std::set<unsigned int>")
    t.iter = iter
    #print "t type ",t
    IOVRange = cppyy.makeClass('IOVRange')
    IOVRange.iovPrint = iovPrint

    # read in and treat options
Пример #14
0
 def get_chain(self,counter, s):
     #Prints chains and their information
     ch = cppyy.makeClass('HLT::Chain')(s)
     #ch.deserialize(s)
     print (".... chain %-3d : %s Counter:%-4d Passed: %d (Raw:%d Prescaled: %d PassThrough:%d) Rerun: %d LastStep: %d Err: %s"\
         % ( counter, self.HLT_Chain_Names[ch.getChainCounter()], ch.getChainCounter(), ch.chainPassed(), ch.chainPassedRaw(), ch.isPrescaled(), ch.isPassedThrough(), ch.isResurrected(), ch.getChainStep(), ch.getErrorCode().str()))
Пример #15
0
# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
#### This is the dbgHLTResult class for the Debug Stream event analysis

from __future__ import print_function

from PyUtils import RootUtils
ROOT = RootUtils.import_root()
from ROOT import std
import cppyy
from CLIDComps.clidGenerator import clidGenerator

clidg = clidGenerator("")

cppyy.makeNamespace('HLT')
ActualHLTResult = cppyy.makeClass('HLT::HLTResult')

stringSerializer = cppyy.makeClass('StringSerializer')()


class hltResult(ActualHLTResult):
    def __init__(self):
        super(hltResult, self).__init__()
        self.as_int_v = std.vector('unsigned int')()

    def load(self, rob):
        self.nav_payload = []

        data = list(rob.rod_data())
        self.as_int_v.clear()
        self.as_int_v.reserve(len(data))
Пример #16
0
    def commitToDb(self,
                   db,
                   folderPath,
                   tag,
                   bitPatVer,
                   author,
                   comment,
                   since,
                   until=(MAXRUN, MAXLBK),
                   untilCmt=None,
                   moduleList=[]):
        """
        Commits the differences compared to the set of bad channels read in with the
        initialze function to the provided database.
        - author  : author name (string)
        - comment : a comment (string)
        - sinceRun, sinceLbk : start of IOV for which bad channels are valid
        - untilRun, untilLbk : end   of IOV for which bad channels are valid
        """
        #=== check db status
        try:
            if not db.isOpen():
                raise Exception("DB not open: ", db.databaseId())
        except Exception as e:
            raise (e)

        multiVersion = self.__multiVersion
        writer = TileCalibTools.TileBlobWriter(db, folderPath, 'Bch',
                                               multiVersion)
        if len(comment) or isinstance(author, tuple):
            writer.setComment(author, comment)
        nUpdates = 0
        goodComment = True
        #=== get latest state from db
        if moduleList != ['CMT']:
            if since != (MINRUN, MINLBK):
                justBefore = list(since)
                if justBefore[1] > MINLBK:
                    justBefore[1] = justBefore[1] - 1
                else:
                    justBefore[0] = justBefore[0] - 1
                    justBefore[1] = MAXLBK
                justBefore = tuple(justBefore)
                if self.__mode != 2:
                    self.log().info(
                        "Reading db state just before %s, i.e. at %s", since,
                        justBefore)
                    self.__updateFromDb(db, folderPath, tag, justBefore, 0)
                else:
                    self.log().info(
                        "Using previous bad channel list from input DB")
                self.log().info(
                    "And comparing it with new list of bad channels")
            else:
                if self.__mode != 2:
                    reader = TileCalibTools.TileBlobReader(db, folderPath, tag)
                    multiVersion = reader.folderIsMultiVersion()
                self.log().info(
                    "Filling db from %s, resetting old status cache",
                    list(since))
                self.__oldStat = len(self.__oldStat) * [TileBchStatus()]

            #=== print status information
            self.log().info("Committing changes to DB \'%s\'", db.databaseId())
            self.log().info(
                "... using tag \'%s\' and [run,lumi] range: [%i,%i] - [%i,%i]",
                tag, since[0], since[1], until[0], until[1])
            if isinstance(author, tuple) and len(author) == 3:
                self.log().info("... author : \'%s\'", author[0])
                self.log().info("... comment: \'%s\'", author[1])
            else:
                self.log().info("... author : \'%s\'", author)
                self.log().info("... comment: \'%s\'", comment)

            #=== default for drawer initialization
            loGainDefVec = cppyy.gbl.std.vector('unsigned int')()
            loGainDefVec.push_back(0)
            hiGainDefVec = cppyy.gbl.std.vector('unsigned int')()
            hiGainDefVec.push_back(0)
            comChnDefVec = cppyy.gbl.std.vector('unsigned int')()
            comChnDefVec.push_back(0)
            cppyy.makeClass('std::vector<unsigned int>')
            defVec = cppyy.gbl.std.vector('std::vector<unsigned int>')()
            defVec.push_back(loGainDefVec)
            defVec.push_back(hiGainDefVec)
            defVec.push_back(comChnDefVec)

            #=== loop over the whole detector
            bchDecoder = TileBchDecoder(bitPatVer)
            for ros in range(0, TileCalibUtils.max_ros()):
                for mod in range(TileCalibUtils.getMaxDrawer(ros)):
                    modName = TileCalibUtils.getDrawerString(ros, mod)
                    nChange = self.checkModuleForChanges(ros, mod)
                    if nChange == 0 and (len(moduleList) == 0
                                         or modName not in moduleList
                                         or 'ALL' not in moduleList):
                        #=== do nothing if nothing changed
                        continue
                    if nChange == -1:
                        nUpdates += 1
                        self.log().info("Drawer %s reset to GOOD", modName)
                        if modName not in comment and not (
                                "ONL" not in folderPath
                                or "syncALL" not in comment):
                            goodComment = False
                            self.log().error(
                                "Comment string - '%s' - doesn't contain drawer %s",
                                comment, modName)
                        writer.zeroBlob(ros, mod)
                    else:
                        nUpdates += 1
                        self.log().info("Applying %2i changes to drawer %s",
                                        nChange, modName)
                        if modName not in comment and ("ONL" not in folderPath
                                                       or "syncALL"
                                                       not in comment):
                            goodComment = False
                            self.log().error(
                                "Comment string - '%s' - doesn't contain drawer %s",
                                comment, modName)
                        drawer = writer.getDrawer(ros, mod)
                        drawer.init(defVec, TileCalibUtils.max_chan(),
                                    bitPatVer)
                        for chn in range(TileCalibUtils.max_chan()):
                            #=== get low gain bit words
                            wordsLo = bchDecoder.encode(
                                self.getAdcStatus(ros, mod, chn, 0))
                            chBits = wordsLo[0]
                            loBits = wordsLo[1]
                            #=== get high gain bit words
                            wordsHi = bchDecoder.encode(
                                self.getAdcStatus(ros, mod, chn, 1))
                            chBits = wordsHi[0] | chBits
                            hiBits = wordsHi[1]
                            #=== set low, high and common channel word in calibDrawer
                            drawer.setData(chn, 0, 0, loBits)
                            drawer.setData(chn, 1, 0, hiBits)
                            drawer.setData(chn, 2, 0, chBits)
                            #=== synchronizing channel status in low and high gain
                            if wordsLo[0] != chBits:
                                self.log().info(
                                    "Drawer %s ch %2d - sync LG status with HG ",
                                    modName, chn)
                                status = TileBchStatus(
                                    bchDecoder.decode(chBits, loBits))
                                self.setAdcStatus(ros, mod, chn, 0, status)
                            if wordsHi[0] != chBits:
                                self.log().info(
                                    "Drawer %s ch %2d - sync HG status with LG ",
                                    modName, chn)
                                status = TileBchStatus(
                                    bchDecoder.decode(chBits, hiBits))
                                self.setAdcStatus(ros, mod, chn, 1, status)

        #=== register
        if nUpdates > 0 or moduleList == ['CMT']:
            if goodComment:
                self.log().info(
                    "Attempting to register %i modified drawers...", nUpdates)
                if untilCmt is not None and untilCmt != until:
                    if moduleList != ['CMT'] and until > since:
                        writer.register(since, until, tag, 1)
                    if untilCmt > since:
                        writer.register(since, untilCmt, tag, -1)
                else:
                    writer.register(since, until, tag)
            else:
                self.log().error(
                    "Aborting update due to errors in comment string")
        else:
            self.log().warning(
                "No drawer modifications detected, ignoring commit request")
Пример #17
0
def print_chain(counter, s):
    ch = cppyy.makeClass('HLT::Chain')(s)
    #ch.deserialize(s)
    print(".... chain %-3d Counter:%-4d Passed: %d (Raw:%d Prescaled: %d PassThrough:%d) Rerun: %d LastStep: %d Err: %s"\
          % ( counter, ch.getChainCounter(), ch.chainPassed(), ch.chainPassedRaw(), ch.isPrescaled(), ch.isPassedThrough(),\
              ch.isResurrected(), ch.getChainStep(), ch.getErrorCode().str()))
Пример #18
0
mlog = logging.getLogger('TrigConfigCheckInPool.py')  ## get the logger
mlog.level = 1

MetaDataTree = ROOT.AthenaROOTAccess.TChainROOTAccess('MetaData')


def _iter(self):
    sequential = self.begin()
    end = self.end()
    while sequential != end:
        yield sequential.__deref__()
        sequential.__preinc__()
    raise StopIteration


_plcClass = cppyy.makeClass("IOVPayloadContainer")
_plcClass.iter = _iter

ROOT.IOVTime.__str__ = lambda x: "%i/%i" % (x.run(), x.event())
ROOT.IOVRange.__str__ = lambda x: "%s - %s" % (x.start(), x.stop())


def checkPoolFileForRunLevel(poolfilename):
    folderName = {
        "L1M": "_TRIGGER_LVL1_Menu",
        "HLTM": "_TRIGGER_HLT_Menu",
        "L1K": "_TRIGGER_LVL1_Lvl1ConfigKey",
        "HLTK": "_TRIGGER_HLT_HltConfigKeys",
        "L1PS": "_TRIGGER_LVL1_Prescales"
    }
    MetaDataTree.Add(poolfilename + '/MetaData')
Пример #19
0
        #=== print status information
        self.log().info("Committing changes to DB \'%s\'" % db.databaseId())
        self.log().info(
            "... using tag \'%s\' and [run,lumi] range: [%i,%i] - [%i,%i]" %
            (tag, since[0], since[1], until[0], until[1]))
        self.log().info("... author : \'%s\'" % author)
        self.log().info("... comment: \'%s\'" % comment)

        #=== default for drawer initialization
        loGainDefVec = cppyy.gbl.std.vector('unsigned int')()
        loGainDefVec.push_back(0)
        hiGainDefVec = cppyy.gbl.std.vector('unsigned int')()
        hiGainDefVec.push_back(0)
        comChnDefVec = cppyy.gbl.std.vector('unsigned int')()
        comChnDefVec.push_back(0)
        cppyy.makeClass('std::vector<unsigned int>')
        defVec = cppyy.gbl.std.vector('std::vector<unsigned int>')()
        defVec.push_back(loGainDefVec)
        defVec.push_back(hiGainDefVec)
        defVec.push_back(comChnDefVec)

        #=== loop over the whole detector
        writer = TileCalibTools.TileBlobWriter(db, folderPath, 'Bch',
                                               multiVersion)
        if len(comment): writer.setComment(author, comment)
        bchDecoder = TileBchDecoder(bitPatVer)
        nUpdates = 0
        goodComment = True
        for ros in xrange(0, TileCalibUtils.max_ros()):
            for mod in xrange(TileCalibUtils.getMaxDrawer(ros)):
                modName = TileCalibUtils.getDrawerString(ros, mod)
    def initialize(self):
        ## note that we are using the python logging service
        ## and that the PyAthena.Alg base class has already initialized
        ## it for us

        # Get DetectorStore...
        from StoreGateBindings.Bindings import StoreGate
        self._detStore = StoreGate.pointer("DetectorStore")
        if self._detStore is None:
            self.msg.error("Failed to get DetectorStore")
            return StatusCode.Failure
        # Get LArOnlineID helper class
        self.onlineID = self._detStore.retrieve("LArOnlineID", "LArOnlineID")
        if self.onlineID is None:
            self.msg.error("Failed to get LArOnlineID")
            return StatusCode.Failure

        # Get CaloCell_ID
        self.offlineID = self._detStore.retrieve("CaloCell_ID", "CaloCell_ID")
        if self.offlineID is None:
            self.msg.error("Failed to get CaloCell_ID")
            return StatusCode.Failure

        # -----------------------------------------------------------
        # Initialize LArCabling service
        self.larCablingSvc = PyAthena.py_tool("LArCablingService")
        if self.larCablingSvc is None:
            self.msg.error('Problem retrieving LArCablingService pointer !')
            return StatusCode.Failure
        else:
            self.msg.info('retrieved [%s]', self.larCablingSvc.name())

        self.badChannelTool = PyAthena.py_tool("LArBadChanTool",
                                               iface="ILArBadChanTool")
        if self.badChannelTool is None:
            self.msg.error('Problem retrieving LArBadChanTool pointer !')
            return StatusCode.Failure
        else:
            self.msg.info('retrieved [%s]', self.badChannelTool.name())

        self.class_larBCBitPacking = cppyy.makeClass("LArBadChanBitPacking")
        self.bc_packing = self.class_larBCBitPacking()

        self.noisepattern = 0L
        for n in ("lowNoiseHG", "highNoiseHG", "unstableNoiseHG", "lowNoiseMG",
                  "highNoiseMG", "unstableNoiseMG", "lowNoiseLG",
                  "highNoiseLG", "unstableNoiseLG", "sporadicBurstNoise"):
            stat = self.bc_packing.enumName(n)
            if stat[0]:
                self.noisepattern |= 1 << stat[1]

        self.deadpattern = 0L
        for n in ("deadReadout", "deadPhys", "almostDead"):
            stat = self.bc_packing.enumName(n)
            if stat[0]:
                self.deadpattern |= 1 << stat[1]

        self.noid = Identifier()

        if self.includeLocation:
            try:
                self.caloDDM = CaloDetDescrManager.instance()
            except:
                print "Failed to retrieve CaloDDM"
                return StatusCode.Failure

        self.larPedestal = None
        self.larMphysOverMcal = None
        self.larRamp = None
        self.larDAC2uA = None
        self.laruA2MeV = None
        self.larhvScaleCorr = None
        self.larDSPThr = None

        return StatusCode.Success
Пример #21
0
#=== folder tag suffix 
tagCon      = "LARTimeCorrectionOflNonRunCon-00"
tagRun      = "LARTimeCorrectionOflRunCon-00"
#=== values for the comment channel
author   = "dhu"
comment  = "Updated time constant values"

#==================================================
#===
#=== Code starts below here
#===
#==================================================
#=== set shortcut
g = cppyy.gbl
cppyy.makeClass('std::vector<float>')

#=== get a logger
log = CaloCondLogger.getLogger("CaloTimeConsWriter")

#=== (re-)create the database
db = CaloCondTools.openDb('SQLITE', 'COMP200', 'UPDATE')

try:
    #=== creating folder specifications
    spec = cool.RecordSpecification()
    spec.extend( 'CaloCondBlob16M', cool.StorageType.Blob16M )
     
    #=== create the folder
    folderPath = CaloCondTools.getCaloPrefix()+"LAR/TimeCorrectionOfl/NonRunCon"
    folderTag  = tagCon
Пример #22
0
    def execute(self):
        self.msg.info('running execute...')
        self.msg.info('dumping [%s] content', self.sg.name())
        self.msg.info(self.sg.dump())

        listOfFolders = [
            "/LAR/BadChannels/BadChannels", "/LAR/BadChannels/MissingFEBs"
        ]
        iSelectedFolder = LArBadChannelBrowserTools.ChooseOptionFromList(
            "Folder list : ", "", "", listOfFolders, +1, False, {})

        if iSelectedFolder == 1:
            self.dbFolderName = "/LAR/BadChannels/BadChannels"
            self.folderId = BAD_CHANNEL
        else:
            self.dbFolderName = "/LAR/BadChannels/MissingFEBs"
            self.folderId = MISSING_FEB

        # -----------------------------------------------------------
        # Browse database a first time to catch tags name and IOV
        listOfTags, dictIOV, self.iNbCoolChannel = self.GetTagsAndIOVFromDatabase(
            self.dbFolderName)

        # -----------------------------------------------------------
        # Create an objec instance for all interfaced python classes

        LArBadChannelDBTools = cppyy.makeNamespace('LArBadChannelDBTools')
        self.nspace_LArBadChannelDBTools = LArBadChannelDBTools()

        self.class_LArBadChannel = cppyy.makeClass('LArBadChannel')
        self.class_HWIdentifier = cppyy.makeClass('HWIdentifier')
        self.class_LArBadChanBitPacking = cppyy.makeClass(
            "LArBadChanBitPacking")

        if self.folderId == BAD_CHANNEL:
            self.dbBrowserBadChan = LArDBFolderBrowser_BadChan.LArDBFolderBrowser_BadChan(
                self.nspace_LArBadChannelDBTools,
                self.class_LArBadChanBitPacking, self.class_LArBadChannel,
                self.class_HWIdentifier, self.onlineID, self.larCablingSvc,
                self.msg)

        elif self.folderId == MISSING_FEB:
            self.dbBrowserMissingFeb = LArDBFolderBrowser_MissingFEBs.LArDBFolderBrowser_MissingFEBs(
                self.nspace_LArBadChannelDBTools,
                self.class_LArBadChanBitPacking,
                self.class_LArBadChannel,
                self.class_HWIdentifier,
                self.onlineID,
                self.larCablingSvc,
            )

        # -----------------------------------------------------------
        # Select the tag
        iSelectedTag = LArBadChannelBrowserTools.ChooseOptionFromList(
            "Tag list : ", "", "", listOfTags, +1, False, {})
        if iSelectedTag < 1:
            return
        self.selectedTag = listOfTags[iSelectedTag - 1]

        # -----------------------------------------------------------
        # Construct IOV list based on selected tag
        self.tagIOVDict = {}
        for iChannel in range(0, self.iNbCoolChannel):
            self.tagIOVDict[iChannel] = dictIOV[
                self.selectedTag][iChannel][-1][0]

        # -----------------------------------------------------------
        # Show database content

        self.channelNameDict = self.ReadObjectsFromDatabase(
            self.dbFolderName, self.selectedTag, self.tagIOVDict)
        if self.folderId == BAD_CHANNEL:
            self.dbBrowserBadChan.BadChan_SetChannelNameDict(
                self.channelNameDict)
#        sMessage="IOV : "+str(self.tagIOVDict)+"  /  channel : "+str(self.channelNameDict)
#        LArBadChannelBrowserTools.TypeEnterToContinue(sMessage)

# -------------------------------------------------------------------------------------
#
# LOOP OVER COOL CHANNEL MODIFICATIONS
#
# -------------------------------------------------------------------------------------

        bEndOfCoolChannelModification = False
        while not bEndOfCoolChannelModification:

            # -----------------------------------------------------------
            # MISSING_FEB : go to correction menu
            if self.folderId == MISSING_FEB:  #

                coolChan = 0
                self.dbBrowserMissingFeb.MissingFeb_DisplayMissingFeb(coolChan)
                endOfModif = self.dbBrowserMissingFeb.MissingFeb_ModifyMissingFeb(
                    coolChan)

                if endOfModif == 'q':
                    sDBName = os.environ["PWD"] + "/MissingFebUpdate.db"
                    if os.path.isfile(sDBName):
                        os.remove(sDBName)
                    dbstring = "sqlite://;schema=" + sDBName + ";dbname=BADCHAN"
                    self.dbBrowserMissingFeb.MissingFeb_SaveMissingFebCorrectionsToDatabase(
                        dbstring, self.dbSvc, self.dbFolderName,
                        self.selectedTag)
                    self.dbBrowserMissingFeb.MissingFeb_CheckSavedDatabaseContent(
                        dbstring, self.dbSvc, self.dbFolderName,
                        self.selectedTag)

                return

            # -----------------------------------------------------------
            # Select Cool channel

            sCoolChannelMenuDict = [("s", "(summary)"), ("a", "(abort)"),
                                    ("q", "(save and quit)")]
            listCoolChannel = []
            for i in range(0, self.iNbCoolChannel):
                listCoolChannel.append(self.channelNameDict[i] + " (IOV " +
                                       str(self.tagIOVDict[i]) + ")")
            repCoolChan = LArBadChannelBrowserTools.ChooseOptionFromList(
                "Cool channel list : ", "", "", listCoolChannel, 0, False,
                sCoolChannelMenuDict)

            if repCoolChan == "a":
                iAbortConfirmation = LArBadChannelBrowserTools.YesNoQuestion(
                    "Are you sure you want to quit ? ")
                if iAbortConfirmation == 1:
                    return
            elif repCoolChan == "q":
                print(" SAUVEGARDE FINALE")
                if self.folderId == BAD_CHANNEL:
                    sDBName = os.environ["PWD"] + "/BadChannelUpdate.db"
                    if os.path.isfile(sDBName):
                        os.remove(sDBName)
                    dbstring = "sqlite://;schema=" + sDBName + ";dbname=BADCHAN"
                    self.dbBrowserBadChan.BadChan_SaveBadChannelCorrectionsToDatabase(
                        dbstring, self.dbSvc, self.dbFolderName,
                        self.selectedTag)
                    self.dbBrowserBadChan.BadChan_CheckSavedDatabaseContent(
                        dbstring, self.dbSvc, self.dbFolderName,
                        self.selectedTag)

                bEndOfCoolChannelModification = True
            elif repCoolChan == "s":
                for i in range(0, self.iNbCoolChannel):
                    self.dbBrowserBadChan.BadChan_ShowBadChannelCorrectionsSummary(
                        i)
            else:
                # -----------------------------------------------------------
                # Display selected Cool channel
                coolChan = int(repCoolChan)
                if self.folderId == BAD_CHANNEL:
                    self.dbBrowserBadChan.BadChan_DisplayBadChanEntry(coolChan)
                    self.dbBrowserBadChan.BadChan_ModifyLarBadChannel(coolChan)
Пример #23
0
                     default='',
                     help="2nd file for the comparison")

optparser.add_option("",
                     "--ef",
                     action="store_true",
                     default=False,
                     help="Use EF result instead of L2")

(opt, args) = optparser.parse_args()

res = hltResult()

featureSizes = {}
stats = {}
HLTChain = cppyy.makeClass('HLT::Chain')


def my_dump(bsfile):
    """Runs the dumping routines"""

    # open a file
    print "=" * 100
    print "Opening", bsfile

    events = {}

    input = eformat.istream(bsfile)
    subdet = eformat.helper.SubDetector.TDAQ_EVENT_FILTER if opt.ef else eformat.helper.SubDetector.TDAQ_LVL2

    for event in input: