Exemple #1
0
def start_app_mgr():
    gaudi = AppMgr()

    global started
    if not started:
        gaudi.initialize()
        started = True

    ppsvc = gaudi.ppSvc()
    toolsvc = gaudi.toolSvc()
    evtsvc = tes = TES = gaudi.evtSvc()
    return locals()
def start_app_mgr() :
    gaudi = AppMgr()

    global started
    if not started :
        gaudi.initialize()
        started = True

    ppsvc   = gaudi.ppSvc()
    toolsvc = gaudi.toolSvc()
    evtsvc = tes = TES = gaudi.evtSvc()
    return locals()
Exemple #3
0
def _getAppMgr   ( **kwargs  ) :
    """
    Helper private auxiliary function to get Application Manager
    """
    gaudi = kwargs.get ( 'gaudi' , None )
    if not gaudi : gaudi = AppMgr()
    if not gaudi : raise RuntimeError, 'Unable to get valid ApplicationMgr'

    state = gaudi._isvc.FSMState()
    if state < cpp.Gaudi.StateMachine.CONFIGURED  : gaudi.config     ()
    state = gaudi._isvc.FSMState()
    if state < cpp.Gaudi.StateMachine.INITIALIZED : gaudi.initialize ()

    return gaudi                                               ## RETURN
Exemple #4
0
    def finalize(self):
        print "INFO: finalize"
        # dump the histograms to a file
        self.output['histograms'].dump(opts.histofile)

        numAlignEvents = self.output['derivatives'].equations().numEvents()
        print 'INFO: number of events in derivatives: ', self.output[
            'derivatives'].equations().numEvents()
        if numAlignEvents > 0:
            # write the derivative file
            if len(opts.derivativefile) > 0:
                self.output['derivatives'].equations().writeToFile(
                    derivativefile)

            from GaudiPython.Bindings import AppMgr
            appMgr = AppMgr()
            # we want to reinitialize, but we don't want to initialize all
            # the reco algorithms, so we add just the alignment sequence:
            appMgr.setAlgorithms(['GaudiSequencer/AlignSequence'])
            appMgr.configure()
            appMgr.initialize()
            # update the geometry
            # updatetool = appMgr.toolsvc().create( typ = "Al::AlignUpdateTool", name = "ToolSvc.AlignUpdateTool", interface = "IAlignUpdateTool" )
            updatetool = appMgr.toolsvc().create(
                "Al::AlignUpdateTool", interface="Al::IAlignUpdateTool")
            updatetool.process(self.output['derivatives'].equations(),
                               opts.iter, 1)
            # call the xml writer tool
            writertool = appMgr.toolsvc().create(
                "WriteMultiAlignmentConditionsTool",
                interface="IWriteAlignmentConditionsTool")
            writertool.write()
            # now call finalize to write the conditions. there must be a better way.
            det = appMgr.detsvc()
            if self.output['otmonodata'] and det['OTMonoLayerAlignData']:
                det['OTMonoLayerAlignData'].add(self.output['otmonodata'])

            appMgr.finalize()
            # finally create a database layer
            import os
            os.system(
                "copy_files_to_db.py -c sqlite_file:Alignment.db{0} -s xml".
                format(condtag))
Exemple #5
0
def run(input_files, output_file):

    ## Bit of extra configuration
    from GaudiConf import IOHelper
    IOHelper().inputFiles(input_files)
    HistogramPersistencySvc().OutputFile = output_file.replace('.root', '_histos.root')

    ## GaudiPython
    import GaudiPython
    import cppyy
    cppyy.load_reflection_info('libLinkerEvent')
    cppyy.load_reflection_info('libLinkerInstancesDict')

    from GaudiPython.Bindings import AppMgr
    appMgr = AppMgr(outputlevel = 3)
    appMgr.config()

    appMgr.HistogramPersistency = 'ROOT'
    ntSvc = GaudiPython.iService('NTupleSvc')
    ntSvc.Output = ["MATCHZERRLUN DATAFILE='{0}' OPT='NEW'".format(output_file)]

    from Hlt1Muons.MatchAlgo import MatchResidualAlgo
    match_algo = MatchResidualAlgo("MatchResidualAlgo", MatchVeloMuon = mvm.getFullName())
    match_algo.NTupleLUN = 'MATCHZERRLUN'
    appMgr.addAlgorithm(match_algo)

    from Hlt1Muons.MatchAlgo import MatchChi2Algo
    chi2_algo = MatchChi2Algo("MatchChi2Algo", MatchVeloMuon = mvm_chi2.getFullName())
    chi2_algo.NTupleLUN = 'MATCHZERRLUN'
    appMgr.addAlgorithm(chi2_algo)

    if mvm_old:
        chi2_algo_old = MatchChi2Algo("MatchChi2AlgoOld", MatchVeloMuon = mvm_old.getFullName())
        chi2_algo_old.NTupleLUN = 'MATCHZERRLUN'
        appMgr.addAlgorithm(chi2_algo_old)

    appMgr.initialize()
    appMgr.run(options.nevents)
    appMgr.stop()
    appMgr.finalize()
    appMgr.exit()
Exemple #6
0
def initialise(dddbtag = '', datatype = '') :
    global pps
    if pps :
        return
    import PartProp.PartPropAlg
    import PartProp.Service
    from   GaudiPython.Bindings import AppMgr
    import sys
    from Configurables import LHCbApp

    if dddbtag :
        LHCbApp().DDDBtag = dddbtag
    elif datatype:
        from Configurables import CondDB
        CondDB().LatestGlobalTagByDataType = datatype
    gaudi = AppMgr()

    # Annoyingly have to initialise the AppMgr to initialise the ppSvc
    gaudi.initialize()

    pps   = gaudi.ppSvc()
Exemple #7
0
def getCalo ( calo = '/dd/Structure/LHCb/DownstreamRegion/Ecal' ,
              DataType = '2010' ,  **args ) :
    """
    Get DeCalorimeter by name

    >>> name = ...              ## the name of DeCalorimeter 
    
    >>> calo = getCalo ( name ) ## get the calorimeter
    
    """

    from GaudiPython.Bindings import AppMgr
    from GaudiPython.Bindings import _gaudi
    if not _gaudi :
        from DaVinci.Configuration import DaVinci
        dv = DaVinci ( DataType = DataType , **args )
        g = AppMgr()
        g.initialize() 
    
    gaudi   = AppMgr()
    detSvc  = gaudi.detSvc()
    return detSvc[ calo ] 
Exemple #8
0
# get rid of some spam
EventSelector().PrintFreq = 100

from MicroDSTExample.Selections import SeqBs2Jpsi2MuMuPhi2KK
selSequence = SeqBs2Jpsi2MuMuPhi2KK.SeqBs2Jpsi2MuMuPhi2KK
mainLocation = selSequence.outputLocation()

# set up some useful paths of locations on the MicroDST
flavTagPath = locationRoot + "/" + mainLocation + "/FlavourTags"
lhcbApp = LHCbApp()
lhcbApp.DDDBtag = 'default'
lhcbApp.CondDBtag = 'default'

appMgr = AppMgr(outputlevel=4)
appMgr.config(files=['$GAUDIPOOLDBROOT/options/GaudiPoolDbRoot.opts'])
appMgr.initialize()
appMgr.ExtSvc += ['LHCb::ParticlePropertySvc']
appMgr.HistogramPersistency = "ROOT"

evtSvc = appMgr.evtSvc()
toolSvc = appMgr.toolsvc()
evtSel = appMgr.evtSel()
nextEvent = Functors.NextEvent(appMgr)
pp = Functors.PartPropSvc(appMgr)
ppSvc = pp
particleNameFunc = Functors.ParticleName(ppSvc)

# open a DST or MicroDST
evtSel.open(microDSTFile)

histoPath = "MicroDST/Histos/"
Exemple #9
0
    def run(self):
        if lambdas == 'None':
            kali = firstPass(
                ##-- cuts and filters
                PtGamma=250 * MeV,  ## selection cuts
                ## event multiplicity filter
                Filter=
                "(650. > CONTAINS('Raw/Spd/Digits')) & ( CONTAINS('Rec/Vertex/Primary') > 0.) & ( CONTAINS('Rec/Vertex/Primary') < 5.)",

                ##-- output
                NTupleProduce=True,  # produce NTuples
                NTuple=self.__dsname + '.root',  # NTuple name
                Histograms=False,  # do not produce Histograms
                FemtoDST=self.__dsname + '.fmDST',  # output fmDST name

                ##-- general (configuring DaVinci)
                DataType='2015',  # data type
                EvtMax=self.__nevt,  # number of events to run
                OutputLevel=ERROR)
        else:
            kali = secondPass(
                ##
                DestroyTES=False,
                ## ``Physics''
                PtGamma=250 * MeV,
                Pi0Cut="PT > 550 * MeV",
                ## IO
                NTupleProduce=True,  # produce NTuples
                NTuple=self.__dsname + '.root',  # NTuple name
                Histograms=False,  # do not produce Histograms
                FemtoDST="",
                ## Calibration
                KaliDB={
                    'name': lambdas,
                    'ecal': 'ecal'
                },
                ## general
                DataType='2015',
                EvtMax=self.__nevt,
                OutputLevel=ERROR)

        from Configurables import CondDB
        CondDB().Simulation = False
        CondDB().UseDBSnapshot = True
        CondDB().DBSnapshotDirectory = "/group/online/hlt/conditions"
        CondDB().EnableRunChangeHandler = True
        CondDB().Tags["ONLINE"] = 'fake'
        CondDB().setProp("IgnoreHeartBeat", True)
        CondDB().Online = True

        try:
            import AllHlt1
        except ImportError:
            rd = '/group/online/hlt/conditions/RunChangeHandler'
            sys.path.append(rd)
            import AllHlt1

        import AllHlt1
        CondDB().RunChangeHandlerConditions = AllHlt1.ConditionMap

        Online = importOnline()

        ## ======== input data type - 'SDST' ============
        from Configurables import DaVinci
        DaVinci().InputType = 'DST'  # use SDSTs as an input
        DaVinci().CondDBtag = Online.CondDBTag
        DaVinci().DDDBtag = Online.DDDBTag

        from GaudiConf import IOHelper
        IOHelper('ROOT').inputFiles(self.__inputs)

        from GaudiPython.Bindings import AppMgr
        gaudi = AppMgr()
        gaudi.initialize()
        gaudi.run(self.__nevt)
        gaudi.stop()
        gaudi.finalize()
        gaudi.exit()
Exemple #10
0
app.OutputLevel = INFO
RunStart = HLT2Params.RunStartTime*1000000000
RunEnd =  (HLT2Params.RunStartTime+HLT2Params.RunDuration)*1000000000
print args
if len(args)>1:
  lstrun = args[1]
  if lstrun == 'LastRun':
    RunEnd = None
# from Configurables import XmlParserSvc
#RunChangeHandlerSvc(OutputLevel=VERBOSE)
#MessageSvc(OutputLevel=1)
EventDataSvc(ForceLeaves = True)
from GaudiPython.Bindings import AppMgr
Gaudi=AppMgr()
print "===================== Initializing the XML conversion ========================"
stat = Gaudi.initialize()
print "===================== Running the XML conversion ========================"
stat = Gaudi.run(1)
print "============= Status :",stat
if stat.isFailure():
  sys.exit(44)
print "============= Gaudi.ReturnCode :",Gaudi.ReturnCode
if Gaudi.ReturnCode != 0:
  sys.exit(44)
print "===================== Stopping the XML conversion ========================"
stat = Gaudi.stop()
print "============= Status :",stat
if stat.isFailure():
  sys.exit(44)
print "===================== Finalizing the XML conversion ========================"
stat = Gaudi.finalize()
    def run(self):
        from Configurables import Brunel
    
        ## Brunel parameters
        Brunel().Detectors   = ['Spd', 'Prs', 'Ecal', 'Hcal' ]
        Brunel().DataType    = "2015"
        Brunel().InputType   = "MDF"
        Brunel().OutputType  = "DST"
        Brunel().EvtMax      = self.__nevt
        Brunel().WriteFSR    = False
        Brunel().Histograms  = "Online"
        Brunel().OnlineMode  = True
        Brunel().PrintFreq   = 1000
        Brunel().DatasetName = self.__dsname

        ## use the conditions database
        ## configuration for online
        from Configurables import CondDB
        CondDB().Simulation = False
        CondDB().UseDBSnapshot = True
        CondDB().DBSnapshotDirectory = "/group/online/hlt/conditions"
        CondDB().EnableRunChangeHandler = True
        CondDB().Tags["ONLINE"] = 'fake'
        CondDB().setProp("IgnoreHeartBeat", True)
        CondDB().Online = True

        try:
            import AllHlt1
        except ImportError:
            rd = '/group/online/hlt/conditions/RunChangeHandler'
            sys.path.append(rd)
            import AllHlt1

        import AllHlt1
        CondDB().RunChangeHandlerConditions = AllHlt1.ConditionMap

        Online = importOnline()
        Brunel().CondDBtag = Online.CondDBTag
        Brunel().DDDBtag   = Online.DDDBTag

        """
        Messages in the online get redirected.
        Setup here the FMC message service
    
        @author M.Frank
        """
        app=Gaudi.ApplicationMgr()
        #Configs.AuditorSvc().Auditors = []
        app.MessageSvcType = 'LHCb::FmcMessageSvc'
        if Gaudi.allConfigurables.has_key('MessageSvc'):
            del Gaudi.allConfigurables['MessageSvc']
        msg = Configs.LHCb__FmcMessageSvc('MessageSvc')
        msg.fifoPath      = os.environ['LOGFIFO']
        msg.LoggerOnly    = True
        msg.doPrintAlways = False
        msg.OutputLevel   = MSG_INFO # Online.OutputLevel

        from GaudiConf import IOHelper
        IOHelper('MDF').inputFiles(self.__inputs)

        from GaudiPython.Bindings import AppMgr    
        gaudi = AppMgr()
        gaudi.initialize()
        gaudi.run(self.__nevt)
        gaudi.stop()
        gaudi.finalize()
        gaudi.exit()
#app.DDDBtag = 'Sim08-20130503-1'
#app.CondDBtag = 'Sim08-20130503-vc-md100'
# Sim05 (MC11a)
#app.DDDBtag = 'MC11-20111102'
#app.CondDBtag = 'sim-20111111-vc-md100'
# Sim08e (MC2012)
app.DDDBtag = 'dddb-20130929-1'
app.CondDBtag = 'sim-20130522-1-vc-md100'

ApplicationMgr().ExtSvc += [LHCb__ParticlePropertySvc()]

from GaudiPython.Bindings import AppMgr
import PartProp.Service

appMgr = AppMgr()
appMgr.initialize()

ppSvc = appMgr.ppSvc()
B_s0H = ppSvc.find("B_s0H")
B_s0L = ppSvc.find("B_s0L")

GH = 1./B_s0H.lifetime()/1000
GL = 1./B_s0L.lifetime()/1000

G  = (GL + GH)/2.
DG = (GL - GH)
y = DG/(2*G)

#MC2012 values
Azero_sq = 0.5213
Apara_sq = 0.2300
Exemple #13
0
def CreateLifetimeMapCode(config=None, bRetLists=False):
    global codePreamble, codeMakePair, codePostamble, outStream, analysisName, timestampFormat, dataType, dddbTag, bUseLatestCondDB
    if not config is None:
        dataType = config[0]  #year
        dddbTag = config[1]  #DDDB tag
    lbApp = LHCbApp()
    lbApp.DDDBtag = dddbTag
    DDDBConf(DataType=dataType)
    if bUseLatestCondDB:
        CondDB().UseLatestTags = [dataType]
    gaudi = AppMgr()
    gaudi.initialize()
    pps = gaudi.ppSvc()
    if len(pps.all()) == 0:
        eprint(
            "ERROR: No particles returned from Particle Property Service!\n",
            'err')
        return False
    pmap = {}
    pids = []
    for p in pps.all():
        #if p.name().startswith('anti-'):
        #    continue
        pid = p.pid().pid()
        if pid < 0 or pmap.has_key(pid):
            apid = ((pid < 0) and (-pid) or pid)
            if pmap.has_key(apid):
                nlft = "%.8E" % (p.lifetime() / SystemOfUnits.s)
                olft = "%.8E" % (pmap[apid])
                if nlft.startswith(olft):
                    continue
                else:
                    eprint(
                        "(anti-)/Particle lifetimes differ [%d] (%s vs. %s). Use asymmetric algorithm with PID:Lifetime map."
                        % (pid, nlft, olft), 'warn')
                    if pid > 0:
                        pmap[-pid] = pmap[pid]
                        del pmap[pid]
            else:
                pid = apid
        #if len(str(pid)) > 7: #????
        #    print ("Ignored " + str(p))
        #    continue
        if pid > 79 and pid < 101:
            eprint('Ignoring generator dependent PIDs in interval [80-100].')
            eprint(str(p))
            continue
        if len(str(pid)) > 9:  #ignore nuclei
            eprint("Ignoring nucleus " + str(p))
            continue
        lft = p.lifetime()
        if lft < 0.0:
            eprint("Negative lifetime! " + str(p), 'err')
            continue
        if pmap.has_key(pid):
            eprint("Duplicate particle in list with PID " + str(pid), 'warn')
            continue
        if lft < 1.0e-32:
            if not pid in pids:
                pids.append(pid)
            continue
        #express lifetime in seconds
        lft = lft / SystemOfUnits.s
        pmap[pid] = lft
    if not bRetLists:
        if not outStream is None:
            if os.path.isfile(outStream):
                eprint("File '%s' already exists." % (outStream))
                ans = raw_input('Do you really want to overwrite (yes/no)? ')
                if ans.lower() == 'no':
                    eprint('Aborting execution. Please, rename output file.',
                           'warn')
                    exit(9)
            fp = open(outStream, "w")
        else:
            fp = sys.stdout
        fp.write(codePreamble %
                 (dddbTag, dataType,
                  datetime.datetime.utcnow().strftime(timestampFormat)))
        fp.write("  ")
        sortedKeys = pmap.keys()
        sortedKeys.sort()
        k = 2
        for pdgid in sortedKeys:
            svdbl = "%.8E" % (pmap[pdgid])
            smant = svdbl[0:svdbl.rfind('E') - 1]
            sexp = svdbl[svdbl.rfind('E'):]
            smant = smant.rstrip('0')
            svdbl = (smant + sexp)
            spair = codeMakePair % (pdgid, svdbl)
            lts = len(spair)
            k += lts
            if k > 80:
                k = lts
                fp.write("\n  ")
            fp.write(spair)
        fp.write("\n  return true;\n}\n")
        fp.flush()
        if len(pids) > 0:
            pids.sort()
            fp.write(codePreamble2 % (len(pids), analysisName, len(pids)))
            k = 0
            jj = 0
            for jj in xrange(0, len(pids)):
                ii = pids[jj]
                #ignore partons and particle ids below 100
                if ii <= 100:
                    continue
                spid = "%u" % (ii)
                if jj < len(pids) - 1:
                    spid += ","
                k += len(spid)
                fp.write(spid)
                if k > 80:
                    fp.write("\n")
                    k = 0
            fp.write("};\n")
        if not outStream is None:
            fp.flush()
            fp.close()
    gaudi.finalize()
    gaudi.exit()
    del gaudi, lbApp
    return (pmap, pids)
"""
# =============================================================================
__author__ = "Vanya BELYAEV [email protected]"
__version__ = "CVS tag $Name: not supported by cvs2svn $, version $Revision$"
# =============================================================================
import PartProp.PartPropAlg
import PartProp.decorators
import PartProp.Service
from GaudiPython.Bindings import AppMgr
# =============================================================================
## test the nodes
from PartProp.Nodes import *

gaudi = AppMgr()

gaudi.initialize()


## simple test-function
def test():
    """
    
    simple function for the test
    
    """
    pps = gaudi.ppSvc()

    for l in range(1, 6):

        # get
        lst1 = pps.get(lambda x: l == x.pid().lSpin())
Exemple #15
0
## get the application manager   (create if needed) 
gaudi = AppMgr() 

import atexit
atexit.register ( gaudi.exit )


gaudi.EvtSel               = 'NONE' ## no external event input
#gaudi.HistogramPersistency = 'HBOOK' ## define the persistency type for N-tuples
gaudi.HistogramPersistency = 'ROOT' ## define the persistency type for N-tuples


## configure & initialize 
gaudi.config()
gaudi.initialize()

## get some random numbers
Rndm        = cpp.Rndm
IRndmGenSvc = cpp.IRndmGenSvc
rndmSvc     = gaudi.service('RndmGenSvc',IRndmGenSvc) 
if not rndmSvc : gaudi.createSvc('RndmGenSvc') 
rndmSvc     = gaudi.service('RndmGenSvc',IRndmGenSvc)

gauss       = Rndm.Numbers ( cpp.SmartIF("IRndmGenSvc")(rndmSvc) , Rndm.Gauss ( 0.0 , 1.0 ) )
    
## get the first N-tuple
tup1 = TupleUtils.nTuple( "path"             , ## the path 
                          "It is a title for my n-tuple" , ## the title 
                          LUN = 'MYLUN1'                 ) ## logical unit  
## fill it: