예제 #1
0
def runsandbox(head,
               find=None,
               outputname="sandbox.dst",
               runAllAfter=False,
               findalg=findalg):
    from GaudiConf.Manipulations import configurableInstanceFromString, nameFromConfigurable, postConfigCallable, configurableClassFromString
    if find is None:
        raise ValueError("You didn't ask me to search for anything!")
    found, before, contains, after, contained_stuff = findalg(head, find)
    print found, before, contains, after, contained_stuff
    if not found:
        raise NameError("I could not find the thing you asked me to excise!")
    user_algs = getUserAlgs()
    for a in before:
        if a not in contains and a not in user_algs and a not in contained_stuff:
            ac = configurableInstanceFromString(a)
            ac.Enable = False
    if not insertEmptyKiller(contains[-1], find):
        raise ValueError("Could not insert EmptyNodeKiller")
    if not insertSomething(contains[-1], find,
                           GaudiSequencer('PreExciseUserAlgs')):
        raise ValueError("Could not insert PreAlgs")
    if not insertSomething(
            contains[-1], find, GaudiSequencer('PostExciseUserAlgs'),
            before=False):
        raise ValueError("Could not insert PostAlgs")
    if not runAllAfter:
        for a in after:
            if a not in before and a not in contains and a not in user_algs and a not in contained_stuff:
                ac = configurableInstanceFromString(a)
                ac.Enable = False
    from GaudiConf import IOExtension
    IOExtension().inputFiles([outputname], clear=True)
    return
예제 #2
0
    def monitorSeq(self):
        from Configurables import (TrackVertexMonitor,
                                   ParticleToTrackContainer)
        from Configurables import LoKi__VoidFilter as Filter
        monitorSeq = GaudiSequencer("AlignMonitorSeq", IgnoreFilterPassed=True)
        for i in self.getProp("TrackSelections"):
            if isinstance(i, str): i = TrackSelection(i)
            name = i.name()
            location = i.location()
            monitorSeq.Members += self.createTrackMonitors(name, location)
        for i in self.getProp("ParticleSelections"):
            location = i.location()
            name = i.name()
            pmonseq = GaudiSequencer("AlignMonitorSeq" + name)
            # add a filter on the alignment particles
            fltr = Filter('Seq' + name + 'Output',
                          Code=" 0 < CONTAINS ( '%s') " % location)
            pmonseq.Members += [fltr]
            pmonseq.Members += [
                ParticleToTrackContainer(name + "ParticleToTrackForMonitoring",
                                         ParticleLocation=location,
                                         TrackLocation=location + "Tracks")
            ]
            pmonseq.Members += self.createTrackMonitors(
                name, location + "Tracks")
            monitorSeq.Members.append(pmonseq)

        if self.getProp("VertexLocation") != "":
            monitorSeq.Members.append(
                TrackVertexMonitor("AlignVertexMonitor",
                                   PVContainer=self.getProp("VertexLocation")))
        return monitorSeq
예제 #3
0
    def _lumi(self):
        """
        read FSR and accumulate event and luminosity data
        calculate normalization - toolname:
        """
        log.info("Creating Lumi Algorithms")
        seq = []
        self.setOtherProps(LumiAlgsConf(), ["DataType", "InputType"])

        # add merge, touch-and-count sequence
        lumiSeq = GaudiSequencer("LumiSeq")
        LumiAlgsConf().LumiSequencer = lumiSeq
        seq += [lumiSeq]

        if self.getProp("Lumi"):
            tupleFile = self.getProp('TupleFile')
            if tupleFile == '':
                log.warning(
                    'TupleFile has not been set. No Lumi ntuple will be produced.'
                )
            # add integrator for normalization
            self.setOtherProps(LumiIntegratorConf(),
                               ["InputType", "TupleFile", "IgnoreDQFlags"])
            lumiInt = GaudiSequencer("IntegratorSeq")
            LumiIntegratorConf().LumiSequencer = lumiInt
            seq += [lumiInt]

        return seq
예제 #4
0
def muonTracksFORmuonAlignment():

    # this still needs to be worked out
    from Configurables import Escher
    Escher().RecoSequence = [
        "Hlt", "Decoding", "AlignTr", "Vertex", "RICH", "CALO", "MUON", "PROTO"
    ]  # ????
    Escher().MoniSequence = ["Tr", "OT"]

    # if the Escher hlt filter is not set, set it here
    if not hasattr(Escher(), "HltFilterCode") or not Escher().HltFilterCode:
        Escher(
        ).HltFilterCode = "HLT_PASS_RE( 'Hlt1DiMuonHighMass*Decision' )"  # Hlt2-->Hlt1 requirement

    # revive only particles used for trigger
    print 'Hlt lines to be used: '
    print ReviveHltTracks(['Hlt1DiMuonHighMassDecision'])

    # Now create the J/psi candidates
    from Configurables import CombineParticles, FilterDesktop
    from CommonParticles.StdAllLooseMuons import StdAllLooseMuons  # requires IsMuon==1
    from CommonParticles.StdLooseJpsi2MuMu import StdLooseJpsi2MuMu  # requires (ADAMASS('J/psi')<100.*MeV)&(ADOCACHI2CUT(30,'')) && "(VFASPF(VCHI2) < 25.)"

    StdLooseJpsi2MuMu.DaughtersCuts = {"mu-": "( P> 6000*MeV)"}  # momentum cut

    ## tighten the mass window for candidates used in alignment
    AlignJpsi2MuMu = FilterDesktop(
        "AlignJpsi2MuMu",
        Inputs=["Phys/StdLooseJpsi2MuMu"],
        Code="(ADMASS('J/psi(1S)') < 35.*MeV) & (VFASPF(VCHI2) < 10.)"
    )  # tighter requirements

    from Configurables import ChargedProtoParticleMaker, ChargedProtoParticleAddMuonInfo
    #####, ChargedProtoCombineDLLsAlg
    from Configurables import TrackParticleMonitor, GaudiSequencer
    recoJpsiSeq = GaudiSequencer("RecoJpsiSeq")
    recoJpsiSeq.Members = [
        ChargedProtoParticleMaker('ChargedProtoPMaker'),
        ChargedProtoParticleAddMuonInfo('ChargedProtoPAddMuon'),
        ###ChargedProtoCombineDLLsAlg('ChargedProtoPCombDLLs'),
        StdAllLooseMuons,
        StdLooseJpsi2MuMu,
        TrackParticleMonitor(
            'StdLooseJpsi2MuMuMonitor',
            InputLocation='/Event/Phys/StdLooseJpsi2MuMu/Particles',
            MinMass=3000,
            MaxMass=3190),
        AlignJpsi2MuMu,
        TrackParticleMonitor(
            'AlignJpsi2MuMuMonitor',
            InputLocation='/Event/Phys/AlignJpsi2MuMu/Particles',
            MinMass=3000,
            MaxMass=3190),
    ]

    sel = ParticleSelection(Name='MufromJpsiMuMu',
                            Location='/Event/Phys/AlignJpsi2MuMu/Particles',
                            Algorithm=recoJpsiSeq)
    return sel
예제 #5
0
 def postMonitorSeq(self):
     from Configurables import (TrackMonitor, TrackVertexMonitor)
     monitorSeq = GaudiSequencer("AlignMonitorSeq")
     postMonitorSeq = GaudiSequencer("AlignPostMonitorSeq")
     for m in monitorSeq.Members:
         copy = m.clone(m.name() + "Post")
         postMonitorSeq.Members.append(copy)
     return postMonitorSeq
예제 #6
0
 def PostConfigurationActions():
     from Configurables import GaudiSequencer
     if not TrackContainter:
         GaudiSequencer('MoniTrSeq').Members += [goodtracksselector]
     if Efficiency:
         GaudiSequencer('MoniTrSeq').Members += [itEff, ttEff]
     if Residuals:
         GaudiSequencer('MoniTrSeq').Members += [ttMon, itMon]
    def configure(self, name="MuonPID", UseMC=True, HistosLevel="OfflineFull"):
        """
    configure the MuonPIDchecker algorithm
    """

        if self.debug: print "CONFIGURING MUONPIDCHECKER"

        ## check if input is already an instance or this must be created
        ext = "Checker"
        if (not UseMC): ext = "Monitor"

        myalg1 = MuonPIDChecker(name + ext + "Long")
        myalg1.HistoTopDir = "Muon/"
        myalg1.RunningMC = UseMC
        myalg1.TrackType = 0
        myalg1.MonitorCutValues = self.info.MonitorCutValues
        myalg1.HistoDir = name + "/" + ext + "Long"

        if (HistosLevel == "Expert" or HistosLevel == "OfflineFull"):
            myalg1.HistosOutput = 4
            # Configure and additional instance to look at Downstream tracks
            myalg2 = MuonPIDChecker(name + ext + "Down")
            myalg2.HistoTopDir = "Muon/"
            myalg2.RunningMC = UseMC
            myalg2.HistosOutput = 1
            myalg2.TrackType = 1
            myalg2.MonitorCutValues = self.info.MonitorCutValues
            myalg2.HistoDir = name + "/" + ext + "Down"
            myalg2.HistosOutput = 4
            if (HistosLevel == "OfflineFull"):
                myalg1.HistosOutput = 3
                myalg2.HistosOutput = 3
            if (UseMC):
                GaudiSequencer("CheckMUONSeq").Members += [
                    "MuonPIDChecker/" + name + ext + "Down"
                ]
            else:
                GaudiSequencer("MoniMUONSeq").Members += [
                    "MuonPIDChecker/" + name + ext + "Down"
                ]

        else:

            if (HistosLevel == "OfflineExpress"):
                myalg1.HistosOutput = 2
            if (HistosLevel == "Online"):
                myalg1.HistosOutput = 1
            if (HistosLevel == "None"):
                myalg1.HistosOutput = 0

        if (UseMC):
            GaudiSequencer("CheckMUONSeq").Members += [
                "MuonPIDChecker/" + name + ext + "Long"
            ]
        else:
            GaudiSequencer("MoniMUONSeq").Members += [
                "MuonPIDChecker/" + name + ext + "Long"
            ]
예제 #8
0
    def _unpackProtoParticles(self):

        from Configurables import (GaudiSequencer, UnpackProtoParticle)

        # Neutrals
        # --------

        neutralLoc = "/Event/Rec/ProtoP/Neutrals"
        unpackNeutrals = UnpackProtoParticle(
            name="UnpackNeutralProtos",
            OutputName=neutralLoc,
            InputName="/Event/pRec/ProtoP/Neutrals")
        DataOnDemandSvc().AlgMap[neutralLoc] = unpackNeutrals

        # Charged
        # -------

        chargedLoc = "/Event/Rec/ProtoP/Charged"
        chargedSeq = GaudiSequencer("UnpackChargedProtosSeq")
        DataOnDemandSvc().AlgMap[chargedLoc] = chargedSeq

        # Unpacker
        unpackCharged = UnpackProtoParticle(
            name="UnpackChargedProtos",
            OutputName=chargedLoc,
            InputName="/Event/pRec/ProtoP/Charged")
        chargedSeq.Members += [unpackCharged]

        # Additional processing, not for MDST
        inputtype = self.getProp('DstType').upper()
        if inputtype != 'MDST':

            # PID calibration
            from Configurables import (ChargedProtoParticleAddRichInfo,
                                       ChargedProtoParticleAddMuonInfo,
                                       ChargedProtoCombineDLLsAlg, TESCheck)
            recalib = GaudiSequencer("ProtoParticleCombDLLs")
            recalib.IgnoreFilterPassed = False
            chargedSeq.Members += [recalib]
            # Filter to check in Protos exist
            recalib.Members += [
                TESCheck(name="CheckChargedProtosExist",
                         Inputs=[chargedLoc],
                         OutputLevel=5,
                         Stop=False)
            ]
            # Add Rich and Muon PID results to protoparticles
            recalib.Members += [
                ChargedProtoParticleAddMuonInfo("ChargedProtoPAddMuon")
            ]
            recalib.Members += [
                ChargedProtoParticleAddRichInfo("ChargedProtoPAddRich")
            ]
            # Combined DLLs
            recalib.Members += [
                ChargedProtoCombineDLLsAlg("ChargedProtoPCombDLL")
            ]
예제 #9
0
    def __configure(self):
        recoSeq = GaudiSequencer("Hlt2JetRecoSequence", ModeOR = True, ShortCircuit = False)

        from HltTracking.Hlt2TrackingConfigurations import Hlt2BiKalmanFittedForwardTracking
        from HltTracking.Hlt2TrackingConfigurations import Hlt2BiKalmanFittedDownstreamTracking

        # Long charged proto particles
        longTracking = Hlt2BiKalmanFittedForwardTracking()
        longChargedProtos = longTracking.hlt2ChargedNoPIDsProtos()
        longSeq = GaudiSequencer("Hlt2JetLongRecoSequence", Members = longChargedProtos.members())

        # Downstream charged proto particles
        downTracking = Hlt2BiKalmanFittedDownstreamTracking()
        downChargedProtos = downTracking.hlt2ChargedNoPIDsProtos()
        downSeq = GaudiSequencer("Hlt2JetDownRecoSequence", Members = downChargedProtos.members())

        from Hlt2SharedParticles.TrackFittedBasicParticles import BiKalmanFittedPhotons as Photons
        from Hlt2SharedParticles.Pi0 import ResolvedPi0s
        from Hlt2SharedParticles.Pi0 import MergedPi0s
        from Hlt2SharedParticles.Ks import KsLLTF as KsLL
        from Hlt2SharedParticles.Ks import KsLLTF as KsDD
        from Hlt2SharedParticles.Lambda import LambdaLLTrackFitted as LambdaLL
        from Hlt2SharedParticles.Lambda import LambdaDDTrackFitted as LambdaDD

        self.__caloProcessor = longTracking.caloProcessor()
        ecalSeq = self.__caloProcessor.clusters()

        inputs = [
            ['Particle',       'particle', self.__sharedParticleInput(Photons, "Photons")],
            ['Particle',       'particle', self.__sharedParticleInput(ResolvedPi0s, "ResolvedPi0s")],
            ['Particle',       'particle', self.__sharedParticleInput(MergedPi0s, "MergedPi0s")],
            ['Particle',       'particle', self.__sharedParticleInput(KsLL, "KsLL")],
            ['Particle',       'particle', self.__sharedParticleInput(KsDD, "KsDD")],
            ['Particle',       'particle', self.__sharedParticleInput(LambdaLL, "LambdaLL")],
            ['Particle',       'particle', self.__sharedParticleInput(LambdaDD, "LambdaDD")],
            ['ProtoParticle',  'best',     (longSeq, longChargedProtos.outputSelection())],
            ['ProtoParticle',  'best',     (downSeq, downChargedProtos.outputSelection())],
            ['CaloCluster',    'gamma',    (None, self.__findCaloLocation(Photons.members(), CellularAutomatonAlg, "OutputData"))],
            ['CaloCluster',    'gamma',    self.__hcalClusters()],
            ['IClusTrTable2D', 'ecal',     (None, self.__findCaloLocation(Photons.members(), PhotonMatchAlg, "Output"))],
            ['IClusTrTable2D', 'hcal',     self.__hcal2Track(longTracking, Photons)]
        ]

        pfInputs = []
        for inputClass, inputType, (seq, loc) in inputs:
            if seq and seq not in recoSeq.Members:
                recoSeq.Members += [seq]
            pfInputs.append([inputClass, inputType, loc])

        from Configurables import HltParticleFlow
        particleFlow = HltParticleFlow("HltParticleFlow", **self.getProp('ParticleFlowOptions'))
        particleFlow.Inputs = pfInputs
        particleFlow.Output = "Hlt2/ParticleFlow/Particles"

        from HltLine.HltLine    import bindMembers
        self.__particleFlow = bindMembers("Hlt2Jet", [recoSeq, particleFlow])
예제 #10
0
    def inputSeq(self, outputLevel=INFO):
        if not allConfigurables.get("AlignInputSeq"):
            if outputLevel == VERBOSE:
                print "VERBOSE: Filter Sequencer not defined! Defining!"

            inputSequencer = GaudiSequencer("AlignInputSeq")
            inputSequencer.MeasureTime = True
            trackselections = self.getProp("TrackSelections")
            if len(trackselections) > 0:
                trackInputSeq = GaudiSequencer("AlignTrackSelSeq",
                                               IgnoreFilterPassed=True)
                inputSequencer.Members.append(trackInputSeq)
                # add the algorithms for the track selections to the sequence.
                # also merge the tracks lists into one list
                from Configurables import TrackListMerger
                trackmerger = TrackListMerger(
                    "AlignTracks", outputLocation="Rec/Track/AlignTracks")
                self.setProp("TrackLocation", trackmerger.outputLocation)
                for i in trackselections:
                    alg = i.algorithm()
                    if alg: trackInputSeq.Members.append(alg)
                    trackmerger.inputLocations.append(i.location())
                trackInputSeq.Members.append(trackmerger)

            # add all particle selections
            if len(self.getProp("ParticleSelections")) > 0:
                particleInputSeq = GaudiSequencer("AlignParticleSelSeq",
                                                  IgnoreFilterPassed=True)
                inputSequencer.Members.append(particleInputSeq)
                from Configurables import FilterDesktop
                particlemerger = FilterDesktop("AlignParticles", Code="ALL")
                particlemerger.Code = "ALL"
                particlemerger.CloneFilteredParticles = False
                for i in self.getProp("ParticleSelections"):
                    alg = i.algorithm()
                    if alg:
                        particleInputSeq.Members.append(alg)
                        print "adding particleinputsel to sequence: ", i.name(
                        ), i.algorithm(), i.location()
                    particlemerger.Inputs.append(i.location())
                particleInputSeq.Members.append(particlemerger)
                self.setProp("ParticleLocation",
                             '/Event/Phys/AlignParticles/Particles')

            # add the PV selection
            if hasattr(self, "PVSelection"):
                inputSequencer.Members.append(
                    self.getProp("PVSelection").algorithm())
                self.setProp("VertexLocation",
                             self.getProp("PVSelection").location())

            return inputSequencer
        else:
            if outputLevel == VERBOSE:
                print "VERBOSE: AlignInputSeq already defined!"
            return allConfigurables.get("AlignInputSeq")
예제 #11
0
 def sequence(self, tracks=[]):
     seq = GaudiSequencer('CaloLines' + self.getName())
     seq.Members[:] = []
     self.setProp("Sequencer", seq)
     context = self.getProp('Context')
     if context == '':
         self.setProp("Context", self.getName())
     self.setProp("TrackLocations", tracks)
     self.applyConf()
     return seq
예제 #12
0
 def _configureHistos(self):
     monitorSeq = GaudiSequencer('TelaMonitors')
     monitorSeq.IgnoreFilterPassed = True 
     monitorSeq.Members += self.getProp('Monitors')
     self.teslaSeq.Members += [ monitorSeq ]
     #
     ApplicationMgr().HistogramPersistency = "ROOT"
     
     if ( self.getProp("Histogram") != "" ):
         HistogramPersistencySvc().OutputFile = self.getProp("Histogram")
예제 #13
0
def fullReco() :
    from Configurables import ( ProcessPhase, GaudiSequencer, RecSysConf )
    brunelSeq = GaudiSequencer("BrunelSequencer")
    # analysis and Phys init are not run with MDF
    GaudiSequencer("DaVinciInitSeq").Members += [ brunelSeq ] 
    brunelSeq.Members += [ "ProcessPhase/Init", "ProcessPhase/Reco", "ProcessPhase/Moni"]
    ProcessPhase("Init").DetectorList += [ "Brunel", "Calo"]
    GaudiSequencer("InitCaloSeq").Members += ["GaudiSequencer/CaloBanksHandler"]
    importOptions("$CALODAQROOT/options/CaloBankHandler.opts")
    configureMoni(False,False)
예제 #14
0
def getUserAlgs(findalg=findalg):
    allalgs = []
    from Configurables import GaudiSequencer
    for alg in [
            GaudiSequencer("PreExciseUserAlgs"),
            GaudiSequencer('PostExciseUserAlgs')
    ]:
        found, b, c, a, ci = findalg(alg, find="THisisprobablynotgoingtoexist")
        allalgs = allalgs + b + c + a + ci
    return allalgs
예제 #15
0
    def __apply_configuration__(self):
        print "******* calling ", self.name()
        mainseq = self.getProp("Sequencer")
        mainseq.getProperties()
        if mainseq.name() == "":
            mainseq = GaudiSequencer("AlignSeq")
        mainseq.MeasureTime = True

        print "****** setting up Kalman type alignment!"
        self.setProp("Incident", 'UpdateConstants')
        self.sequencers()
예제 #16
0
def Tuples():
    """
  Simple class-like method to return DecayTreeTuple which can be used to 
  do quick-check on the output DST.

  Usage:
  >> from StrippingSelections.StrippingQEE import StrippingDitau
  >> DaVinci().appendToMainSequence( StrippingDitau.Tuples() )
  >> DaVinci().TupleFile = 'tuple.root'

  """
    import re
    from DecayTreeTuple.Configuration import DecayTreeTuple, EventTuple

    seq = GaudiSequencer('TupleSeq')
    seq.ModeOR = True
    seq.ShortCircuit = False
    for lname, decays in lines_decays.iteritems():
        for process, desc in decays.iteritems():
            desc = re.sub(r'  ([a-z])', r' ^\1', desc)  # regex insert ^
            desc = desc.replace('cc', 'CC')  # different between CombineP & DTT
            #
            ## Extra complication for cand with RIF, such that the input location
            # after isolation filter is not at default line location, but on the
            # last algo's location. Otherwise the tuple will pick up candidates
            # before isolation filtering.
            root = 'Phys/Ditau%sLine' % lname
            # if 'noiso' not in root:
            #   root = root.replace('Line','isoLine')
            #
            tup = DecayTreeTuple('Tup_' + process,
                                 NTupleDir='Ditau',
                                 TupleName=process)
            tup.Inputs = [root + '/Particles']
            tup.Decay = desc
            tup.ToolList = [
                'TupleToolKinematic',
            ]
            tool = tup.addTupleTool('TupleToolConeIsolation')
            tool.MinConeSize = 0.5
            tool.MaxConeSize = 0.5
            tool = tup.addTupleTool('LoKi::Hybrid::TupleTool')
            tool.Variables = {
                'CONEPX1': "RELINFO('%s/IsoPlus' , 'CONEPX')" % root,
                'CONEPX2': "RELINFO('%s/IsoMinus', 'CONEPX')" % root,
                'CONEPY1': "RELINFO('%s/IsoPlus' , 'CONEPY')" % root,
                'CONEPY2': "RELINFO('%s/IsoMinus', 'CONEPY')" % root,
                'CONEPT1': "RELINFO('%s/IsoPlus' , 'CONEPT')" % root,
                'CONEPT2': "RELINFO('%s/IsoMinus', 'CONEPT')" % root,
            }
            seq.Members.append(tup)
    return [seq]
예제 #17
0
    def __apply_configuration__(self):
        print "******* calling ", self.name()
        mainseq = self.getProp("Sequencer")
        mainseq.MeasureTime = True
        mainseq.getProperties()
        if mainseq.name() == "":
            mainseq = GaudiSequencer("Align")

        import VeloAlignment.VeloAlignmentConf
        if 'Module' in self.getProp("ElementsToAlign"):
            va = VeloAlignment.VeloAlignmentConf.VAlign()
            print "Adding ", va.name(), " to sequence ", mainseq.name()
            mainseq.Members += [va]
            importOptions("$VELOALIGNMENTOPTS/VeloAlign.py")
            self.sequencers()
예제 #18
0
    def caloSequence(self, tracks=[]):
        seq = GaudiSequencer(self.getName() + 'CaloSeq')
        seq.Members[:] = []
        self.setProp("CaloSequencer", seq)
        context = self.getProp('Context')
        if context == '':
            self.setProp("Context", self.getName())
        if tracks != []:
            self.setProp("TrackLocations", tracks)
            _log.info(
                "CaloProcessor.caloSequence : update TrackLocation %s: " %
                tracks)

        self.applyConf()
        return seq
    def myHackedSequence():
        decodeSeq = GaudiSequencer("RecoDecodingSeq")
        from DAQSys.Decoders import DecoderDB
        from DAQSys.DecoderClass import decodersForBank
        
        decodeSeq.Members = []
        vdec = DecoderDB["DecodeVeloRawBuffer/createVeloLiteClusters"]
        vdec.DecodeToVeloClusters = False
        vdec.DecodeToVeloLiteClusters = True
        vdec.Active = True
        decodeSeq.Members += [vdec.setup()]

        tt = DecoderDB["RawBankToSTLiteClusterAlg/createTTLiteClusters"]
        it = DecoderDB["RawBankToSTLiteClusterAlg/createITLiteClusters"]
        decodeSeq.Members += [tt.setup(),it.setup()]
예제 #20
0
def configMonitor():
    import os
    from Gaudi.Configuration import EventPersistencySvc, HistogramPersistencySvc
    from Configurables import (LHCbApp,
                               LHCb__RawDataCnvSvc,
                               GaudiSequencer,
                               UpdateAndReset,
                               createODIN,
                               ApplicationMgr )

    app = LHCbApp()
    app.DataType = '2015'
    app.EvtMax = -1

    EventPersistencySvc().CnvServices.append( LHCb__RawDataCnvSvc('RawDataCnvSvc') )
    HistogramPersistencySvc().OutputFile = ''
    HistogramPersistencySvc().Warnings = False

    UpdateAndReset().saveHistograms = 1
    #UpdateAndReset().saverCycle     = 3600

    from Configurables import EventClockSvc
    EventClockSvc().EventTimeDecoder = 'OdinTimeDecoder'

    appMgr = ApplicationMgr()

    # Decoder
    from Configurables import HCRawBankDecoder
    decoder = HCRawBankDecoder()
    decoder.Monitoring = True

    # Monitor
    from Configurables import HCDigitMonitor
    monitor = HCDigitMonitor()
    monitor.CrateB = 0
    monitor.CrateF = 1
    monitor.ChannelsB0 = [47, 46, 45, 44]
    monitor.ChannelsB1 = [23, 22, 21, 20]
    monitor.ChannelsB2 = [11, 10,  9,  8]
    monitor.ChannelsF1 = [23, 22, 21, 46]
    monitor.ChannelsF2 = [11, 10,  9,  8]

    # Top level sequence
    topSeq = GaudiSequencer("TopSequence")
    topSeq.Members = [createODIN(), decoder, monitor]

    appMgr.TopAlg = [topSeq]
    return app, monitor
예제 #21
0
    def algorithm(self):
        Name = self._name
        inputTrackLocation = self._inputLocation
        from Configurables import GaudiSequencer, HltTrackConverter, TrackContainerCopy, Escher
        from Configurables import TrackContainerCopy, TrackSelector
        trackRefitSeq = GaudiSequencer(
            self.name() + "Seq")  # GaudiSequencer("TrackRefitSeq")

        # create a track list for tracks with velo hits
        velotrackselector = TrackContainerCopy(
            "GoodLongRefittedVeloTracks",
            inputLocations=["Rec/Track/Best"],
            outputLocation="Rec/Track/GoodLongRefittedVeloTracks",
            Selector=TrackSelector())
        velotrackselector.Selector.MinNVeloRHits = 7
        velotrackselector.Selector.MinNVeloPhiHits = 6
        # refit the tracks in that list
        from TrackFitter.ConfiguredFitters import *
        velotrackrefitter = ConfiguredEventFitter(
            Name="TracksWithVeloHitsFitter",
            TracksInContainer="Rec/Track/GoodLongRefittedVeloTracks",
            FieldOff=True)
        velotrackrefitter.Fitter.MeasProvider.IgnoreIT = True
        velotrackrefitter.Fitter.MeasProvider.IgnoreOT = True
        velotrackrefitter.Fitter.MeasProvider.IgnoreTT = True
        velotrackrefitter.Fitter.MeasProvider.IgnoreMuon = True
        velotrackrefitter.Fitter.MakeNodes = True
        velotrackrefitter.Fitter.MakeMeasurements = True

        trackRefitSeq.Members += [velotrackselector, velotrackrefitter]
        return trackRefitSeq
예제 #22
0
def configuredParticleListFromDST(ParticleLocation, FilterCode=""):
    from Configurables import GaudiSequencer
    from Configurables import TrackParticleRefitter, TrackMasterFitter
    from TrackFitter.ConfiguredFitters import ConfiguredMasterFitter
    # create a sequence to refit and monitor
    name = ParticleLocation
    name = name.replace("/Event", "")
    name = name.replace("/Phys", "")
    name = name.replace("/Particles", "")
    name = name.replace("/", "")
    fitter = TrackParticleRefitter(name + "Refitter",
                                   TrackFitter=TrackMasterFitter(),
                                   ParticleLocation=ParticleLocation)
    ConfiguredMasterFitter(fitter.TrackFitter, SimplifiedGeometry=True)
    seq = GaudiSequencer(name + "Seq", IgnoreFilterPassed=True)
    seq.Members.append(fitter)
    if FilterCode != "":
        from Configurables import FilterDesktop
        newLocation = ParticleLocation.replace("/Particles", "") + "Filtered"
        newfilter = FilterDesktop(  #name + "Filter",#Output =
            newLocation,
            Inputs=[ParticleLocation],
            CloneFilteredParticles=False,
            Code=FilterCode)
        seq.Members.append(newfilter)
        ParticleLocation = newLocation + "/Particles"
    sel = ParticleSelection(Name=name,
                            Location=ParticleLocation,
                            Algorithm=seq)
    return sel
예제 #23
0
    def _init(self):
        from Configurables import (PhysConf, AnalysisConf)

        inputType = self.getProp("InputType").upper()

        initSeqs = []

        if ((inputType != 'MDST') & (inputType != "MDF") &
            (inputType != "DIGI")):
            physinit = PhysConf().initSequence()  # PhysConf initSequence
            # Analysis
            AnalysisConf().RedoMCLinks = self.getProp("RedoMCLinks")
            analysisinit = AnalysisConf().initSequence()
            initSeqs = [physinit, analysisinit]
#        if inputType == 'RDST' :
#            log.info('Setting HltDecReportsDecoders RawEventLocations to ["pRec/RawEvent"]')
#            from DAQSys.Decoders import DecoderDB
#            from DAQSys.DecoderClass import decodersForBank
#            for bank in ["Sel","Dec","Vertex","Track"]:
#                for d in decodersForBank(DecoderDB,"Hlt"+bank+"Reports"):
#                    d.overrideInputs("pRec/RawEvent")
#                    #d.setup()
#            from Configurables import ANNDispatchSvc
#
#            ANNDispatchSvc().RawEventLocation = "pRec/RawEvent"

        return GaudiSequencer('DaVinciEventInitSeq',
                              Members=initSeqs,
                              IgnoreFilterPassed=True)
def selMuonPParts(name, trackingSeq):
    """
       Make ProtoParticles out of VeloMuon tracks
   """
    veloprotos = ChargedProtoParticleMaker(name + "ProtoPMaker")
    veloprotos.Inputs = ["Rec/VeloMuon/Tracks"]
    veloprotos.Output = "Rec/ProtoP/" + name + "ProtoPMaker/ProtoParticles"
    veloprotos.addTool(DelegatingTrackSelector, name="TrackSelector")
    tracktypes = ["Long"]
    veloprotos.TrackSelector.TrackTypes = tracktypes
    selector = veloprotos.TrackSelector
    for tsname in tracktypes:
        selector.addTool(TrackSelector, name=tsname)
        ts = getattr(selector, tsname)
        # Set Cuts
        ts.TrackTypes = [tsname]

    veloprotoseq = GaudiSequencer(name + "ProtoPSeq")
    veloprotoseq.Members += [veloprotos]

    return GSWrapper(name="WrappedVeloMuonProtoPSeqFor" + name,
                     sequencer=veloprotoseq,
                     output='Rec/ProtoP/' + name +
                     'ProtoPMaker/ProtoParticles',
                     requiredSelections=[trackingSeq])
예제 #25
0
 def configureSequence(self):
     misalignSeq = GaudiSequencer("MisAlignSequence")
     ApplicationMgr().TopAlg = [misalignSeq]
     misalignSeq.Members += ["MisAlignAlg"]
     from Configurables import WriteAlignmentConditions
     if "VELO" in self.getProp("Detectors"):
         writeVelo = WriteAlignmentConditions()
         writeVelo.topElement = "/dd/Structure/LHCb/BeforeMagnetRegion/Velo"
         writeVelo.outputFile = "VeLo_1.xml"
         writeVelo.depths = [0, 1, 2, 3]
         misalignSeq.Members += [writeVelo]
     if "OT" in self.getProp("Detectors"):
         writeOT = WriteAlignmentConditions()
         writeOT.topElement = "/dd/Structure/LHCb/AfterMagnetRegion/T/OT"
         writeOT.depths = [0, 1, 2, 3]
         writeOT.outputFile = "OT_1.xml"
         misalignSeq.Members += [writeOT]
     if "TT" in self.getProp("Detectors"):
         writeTT = WriteAlignmentConditions()
         writeTT.topElement = "/dd/Structure/LHCb/BeforeMagnetRegion/TT"
         writeTT.outputFile = "TT_1.xml"
         writeTT.depths = [0, 1, 2, 3]
         misalignSeq.Members += [writeTT]
     if "IT" in self.getProp("Detectors"):
         writeIT = WriteAlignmentConditions()
         writeIT.topElement = "/dd/Structure/LHCb/AfterMagnetRegion/T/IT"
         writeIT.outputFile = "IT_1.xml"
         writeIT.depths = [0, 1, 2, 3]
         misalignSeq.Members += [writeIT]
def trackingPreFilter(name, prefilter):

    VeloMuonBuilder1 = VeloMuonBuilder("VeloMuonBuilder")
    VeloMuonBuilder1.OutputLevel = 6
    VeloMuonBuilder1.MuonLocation = "Hlt1/Track/MuonSeg"
    VeloMuonBuilder1.VeloLocation = "Rec/Track/UnFittedVelo"
    VeloMuonBuilder1.lhcbids = 4
    VeloMuonBuilder1.OutputLocation = "Rec/VeloMuon/Tracks"

    preve = TrackPrepareVelo("preve")
    preve.inputLocation = "Rec/Track/Velo"
    preve.outputLocation = "Rec/Track/UnFittedVelo"
    preve.bestLocation = ""

    alg = GaudiSequencer(
        "VeloMuonTrackingFor" + name,
        Members=[
            DecodeVeloRawBuffer(name + "VeloDecoding",
                                DecodeToVeloLiteClusters=True,
                                DecodeToVeloClusters=True),
            FastVeloTracking(name + "FastVelo",
                             OutputTracksName="Rec/Track/Velo"), preve,
            StandaloneMuonRec(name + "MuonStandalone"), VeloMuonBuilder1
        ])

    return GSWrapper(name="WrappedVeloMuonTracking",
                     sequencer=alg,
                     output='Rec/VeloMuon/Tracks',
                     requiredSelections=prefilter)
예제 #27
0
        def genConfigAction():
            def gather(c, overrule):
                def check(config, prop, value):
                    if prop not in config.getDefaultProperties(): return False
                    if hasattr(config, prop):
                        return getattr(config, prop) == value
                    return config.getDefaultProperties()[prop] == value

                def addOverrule(config, rule):
                    if c.name() not in overrule.keys():
                        overrule[c.name()] = []
                    if rule not in overrule[c.name()]:
                        overrule[c.name()] += [rule]

                if check(c, 'HistoProduce', False):
                    addOverrule(c, 'HistoProduce:@OnlineEnv.Monitor@False')
                if c.getType() in ['FilterDesktop', 'CombineParticles'
                                   ] and check(c, 'Monitor', False):
                    addOverrule(c, 'Monitor:@OnlineEnv.Monitor@False')
                if check(c, 'Enable', False):
                    addOverrule(c, 'OutputLevel:3')
                for p in ['Members', 'Filter0', 'Filter1']:
                    if not hasattr(c, p): continue
                    x = getattr(c, p)
                    if list is not type(x): x = [x]
                    for i in x:
                        gather(i, overrule)

            from Configurables import HltGenConfig, GaudiSequencer
            HltGenConfig().Overrule = {
                'Hlt1ODINTechnicalPreScaler':
                ['AcceptFraction:@OnlineEnv.AcceptRate@0']
            }
            gather(GaudiSequencer('Hlt'), HltGenConfig().Overrule)
            print HltGenConfig()
def trackingPreFilter(name, prefilter):

    VeloMuonBuilder1 = VeloMuonBuilder("VeloMuonBuilder")
    VeloMuonBuilder1.OutputLevel = 6
    VeloMuonBuilder1.MuonLocation = "Hlt1/Track/MuonSeg"
    VeloMuonBuilder1.VeloLocation = "Rec/Track/UnFittedVelo"
    VeloMuonBuilder1.lhcbids = 4
    VeloMuonBuilder1.OutputLocation = "Rec/VeloMuon/Tracks"

    preve = TrackPrepareVelo("preve")
    preve.inputLocation = "Rec/Track/Velo"
    preve.outputLocation = "Rec/Track/UnFittedVelo"
    preve.bestLocation = ""

    #TODO: apparently FastVelo is now (april 2012) run with fixes in the production which don't neccessarily apply to the stripping...
    alg = GaudiSequencer(
        "VeloMuonTrackingFor" + name,
        Members=[
            DecodeVeloRawBuffer(name + "VeloDecoding",
                                DecodeToVeloLiteClusters=True,
                                DecodeToVeloClusters=True),
            FastVeloTracking(name + "FastVelo",
                             OutputTracksName="Rec/Track/Velo"), preve,
            StandaloneMuonRec(name + "MuonStandalone"), VeloMuonBuilder1
        ])

    return GSWrapper(name="WrappedVeloMuonTracking",
                     sequencer=alg,
                     output='Rec/VeloMuon/Tracks',
                     requiredSelections=prefilter)
예제 #29
0
    def configureInput(self, inputType):
        """
        Tune initialisation according to input type
        """

        # By default, Brunel only needs to open one input file at a time
        # Only set to zero if not previously set to something else.
        if not IODataManager().isPropertySet("AgeLimit") : IODataManager().AgeLimit = 0

        if self._isReprocessing(inputType):
            # Kill knowledge of any previous Brunel processing
            from Configurables import ( TESCheck, EventNodeKiller )
            InitReprocSeq = GaudiSequencer( "InitReprocSeq" )
            if ( self.getProp("WithMC") and inputType in ["XDST","DST"] ):
                # Load linkers, to kill them (avoid appending to them later)
                InitReprocSeq.Members.append( "TESCheck" )
                TESCheck().Inputs = ["Link/Rec/Track/Best"]
            killer = EventNodeKiller()
            killer.Nodes += [ "Raw", "Link/Rec" ]
            if self.getProp("SkipTracking"):
                killer.Nodes += [ "pRec/Rich", "pRec/Muon", "pRec/Calo", "pRec/Track/Muon", "pRec/ProtoP" ]
            else:
                killer.Nodes += [ "pRec", "Rec" ]
            InitReprocSeq.Members.append( killer )
            ### see configureOutput to see how the remainder of the juggler is configured
            
        # Get the event time (for CondDb) from ODIN
        from Configurables import EventClockSvc
        EventClockSvc().EventTimeDecoder = "OdinTimeDecoder";
def trackingPreFilter(name, prefilter):

    VeloMuonBuilder1 = VeloMuonBuilder("VeloMuonBuilder")
    VeloMuonBuilder1.OutputLevel = 6
    VeloMuonBuilder1.MuonLocation = "Hlt1/Track/MuonSeg"
    VeloMuonBuilder1.VeloLocation = "Rec/Track/FittedVelo"
    VeloMuonBuilder1.lhcbids = 4
    VeloMuonBuilder1.OutputLocation = "Rec/VeloMuon/Tracks"

    preve = TrackPrepareVelo("preve")
    preve.inputLocation = "Rec/Track/Velo"
    preve.outputLocation = "Rec/Track/UnfittedPreparedVelo"
    preve.bestLocation = ""
    vefit = ConfiguredFit("vefit", "Rec/Track/UnfittedPreparedVelo")
    vefit.TracksOutContainer = "Rec/Track/FittedVelo"
    vefit.addTool(TrackMasterFitter, name='Fitter')
    ConfiguredFastFitter(getattr(vefit, 'Fitter'))

    alg = GaudiSequencer(
        "VeloMuonTrackingFor" + name,
        Members=[
            DecodeVeloRawBuffer(name + "VeloDecoding",
                                DecodeToVeloLiteClusters=True,
                                DecodeToVeloClusters=True),
            FastVeloTracking(name + "FastVelo",
                             OutputTracksName="Rec/Track/Velo"), preve, vefit,
            StandaloneMuonRec(name + "MuonStandalone"), VeloMuonBuilder1
        ])

    return GSWrapper(name="WrappedVeloMuonTracking",
                     sequencer=alg,
                     output='Rec/VeloMuon/Tracks',
                     requiredSelections=prefilter)
예제 #31
0
def copyGoodEvents(filename, extraitems=[], incident='GoodEvent'):
    """
    Utitity to copy ``good/tagged'' events

    It is based on configurables,
    thus it needs to be invoked BEFORE GaudiPython
    
    #
    ##Configurables:
    #
    from Bender.Utils import copyGoodEvents
    copyGoodEvents ( filename = 'SelectedEvents' )
    
    """
    from GaudiConf import IOHelper
    ioh = IOHelper('ROOT', 'ROOT')
    algs = ioh.outputAlgs(filename, 'InputCopyStream/%s' % incident)

    ioh.setupServices()
    from Configurables import Gaudi__IncidentFilter as Tagger
    tag = Tagger("%sInc" % incident, Incidents=[incident])

    from Configurables import GaudiSequencer
    seq = GaudiSequencer('%sSeq' % incident, Members=[tag] + algs)

    from Configurables import ApplicationMgr
    AM = ApplicationMgr()

    if not AM.OutStream: AM.OutStream = []

    AM.OutStream.append(seq)

    logger.info("Prepare the file %s to keep ``%s'' incidents" %
                (filename, incident))
def ParticleRefitterSeq(inputs = [],rootInTES = "/Event",scale=True):
  from Configurables import GaudiSequencer
  from Configurables import TrackScaleState as SCALER
  from Configurables import ParticleRefitter
  scaler = SCALER("Scaler", RootInTES = rootInTES)
  seq = GaudiSequencer("ParticleRefitterSeq")
  if scale:
     seq.Members = [ scaler ]
  else:
     seq.Members = [  ]
  refitter = ParticleRefitter()
  if isinstance(inputs, basestring) :
    refitter.Inputs = [inputs]
  else :
    refitter.Inputs = inputs
  refitter.RootInTES = rootInTES
  print "ParticleRefitterSeq is applied to the following inputs:"
  for i in refitter.Inputs:
    print "   - on of the inputs is ", i
  seq.Members += [refitter]
  return seq
예제 #33
0
    "phi"                     : "PHI",
    "LV01"                    : "LV01" }

#BJpsiKS.addBranches({  # remove all "^" except where needed.
#        "Jpsi"       : "^(J/psi(1S) -> mu- mu+)",
#        "muplus"     : "J/psi -> mu- ^mu+",
#        "muminus"    : "J/psi -> ^mu- mu+"
#        })

### Bplus tools
### Jpsi tools
#BJpsiKS.Jpsi.addTupleTool("TupleToolDownEff")

################################################################
################################################################
Seq1 = GaudiSequencer("Seq1")
Seq1.Members += [ SeqKsPiPi.sequence(), KsPiPiTuple ]
Seq1.Members += [ SeqLambdaPPi.sequence(), LambdaPPiTuple ]
Seq1.ShortCircuit = False
Seq1.ModeOR = True
# ######################################################################################################
DaVinci().MainOptions = ""
DaVinci().UserAlgorithms = [Seq1]
########################################################################
DaVinci().EvtMax    = -1
DaVinci().DataType  = "2016"
DaVinci().PrintFreq = 100
DaVinci().Lumi      = False

DaVinci().InputType = "DST"
예제 #34
0
# Standard app configuration
from Configurables import (ApplicationMgr,
                           GaudiSequencer,
                           GaudiTesting__OddEventsFilter as OddEvents,
                           GaudiTesting__EvenEventsFilter as EvenEvents,
                           SubAlg as EmptyAlg,
                           OutputStream, InputCopyStream)

oddEvtSelect = GaudiSequencer('OddEventsSelection')
oddEvtSelect.Members = [OddEvents('OddEvents'),
                        OutputStream('Stream1')]

evenEvtSelect = GaudiSequencer('EvenEventsSelection')
evenEvtSelect.Members = [EvenEvents('EvenEvents'),
                         InputCopyStream('Stream2')]

app = ApplicationMgr(EvtSel='NONE', EvtMax=4)
app.TopAlg = [EmptyAlg("EventInit"), evenEvtSelect, oddEvtSelect]


# Extension used to enforce deferring
from Configurables import (ApplicationMgr, EventDataSvc,
                           ReplayOutputStream,
                           SubAlg as EmptyAlg)

app = ApplicationMgr()
app.AlgTypeAliases['OutputStream'] = 'RecordOutputStream'
app.AlgTypeAliases['InputCopyStream'] = 'RecordOutputStream'
EventDataSvc(ForceLeaves=True)

outDelegate = ReplayOutputStream()
예제 #35
0
    lb_mother = lb_mother_template.format(mu)
    lb_combine = lb_combine_template.clone(lb_combine_name)
    lb_combine.DecayDescriptor = lb_decay
    lb_combine.DaughtersCuts = lb_daughters
    lb_combine.MotherCut = lb_mother
    # Output of combining Lc daughters is input to combining Lb daughters
    lb_combine.Inputs = [
        "Phys/StdAllNoPIDsMuons",
        "Phys/{0}".format(lc_combine_name)
    ]
    # Clone the DecayTreeTuple created above
    cheat_tuple = tuple.clone("Tuple{0}".format(lb_combine_name))
    cheat_tuple.Inputs = ["Phys/{0}".format(lb_combine_name)]

    # Sequences for ntuple creation
    dec_sequence = GaudiSequencer("SeqBook{0}".format(line))
    dec_sequence.Members = [filter, tuple]
    mc_sequence = GaudiSequencer("SeqMCGenBook{0}".format(line))
    mc_sequence.Members = [mc_tuple]
    cheat_sequence = GaudiSequencer("SeqMCCheatBook{0}".format(line))
    cheat_sequence.Members = [lc_combine, lb_combine, cheat_tuple]

    # Sequence for ntuple sequences
    tuples_sequence = GaudiSequencer("SeqTuples{0}".format(line))
    tuples_sequence.IgnoreFilterPassed = True
    tuples_sequence.Members = [dec_sequence, mc_sequence, cheat_sequence]

    # Sequence for MC filter then ntuple sequences
    master_sequence = GaudiSequencer("SeqMaster{0}".format(line))
    master_sequence.Members = [mc_filter, tuples_sequence]

particlesAndCuts = { "/Event/AllStreams/Phys/FullDSTDiMuonJpsi2MuMuDetachedLine/Particles" : "ALL" }

from PhysSelPython.Wrappers import Selection, SelectionSequence, AutomaticData
from Configurables import FilterDesktop

myInputParticlesList = []
myParticlesFilterList = []
myParticlesList = []
myParticlesSeqList = []
myParticlesLocationList = []

from Configurables import GaudiSequencer

filterSeq = GaudiSequencer( 'FilterSeq' )
filterSeq.ModeOR = True

mainSeq = GaudiSequencer( 'MainSeq' )
mainSeq.MeasureTime = True
mainSeq.IgnoreFilterPassed = False

codeIN = ""

for particles, cuts in particlesAndCuts.iteritems():
    codeIN = codeIN.replace("||","|")
    codeIN += "(CONTAINS( '"+str(particles)+"' )>0) || "
    
    myParticlesName = particles.split("/")[-2]

    myInputParticlesList += [ AutomaticData( Location = particles ) ]
예제 #37
0
파일: mctuples.py 프로젝트: mazurov/chib
def configure(datafiles, catalogs=[], castor=True, params=None):
    """
    Configure the job
    """

    from Configurables import DaVinci  # needed for job configuration
    # from Configurables import EventSelector  # needed for job configuration
    # from Configurables import NTupleSvc

    from PhysConf.Filters import LoKi_Filters

    fltrs = LoKi_Filters(
        STRIP_Code="""
        HLT_PASS_RE ( 'Stripping.*DiMuonHighMass.*Decision' )
        """,
        VOID_Code="""
        0 < CONTAINS (
            '/Event/AllStreams/Phys/FullDSTDiMuonDiMuonHighMassLine/Particles')
        """
    )

    filters = fltrs.filters('Filters')
    filters.reverse()

    from PhysSelPython.Wrappers import AutomaticData, Selection, SelectionSequence

    #
    # defimuon in stripping DST
    #
    # DiMuLocation  =
    # '/Event/Dimuon/Phys/FullDSTDiMuonDiMuonHighMassLine/Particles'
    DiMuLocation = '/Event/AllStreams/Phys/FullDSTDiMuonDiMuonHighMassLine/Particles'

    from PhysSelPython.Wrappers import AutomaticData
    DiMuData = AutomaticData(Location=DiMuLocation)

    # =========================================================================
    # Upsilon -> mumu, cuts by  Giulia Manca
    # ========================================================================
    from GaudiConfUtils.ConfigurableGenerators import FilterDesktop
    UpsAlg = FilterDesktop(
        Code="""
        ( M > 7 * GeV ) &
        DECTREE   ('Meson -> mu+ mu-'  )                      &
        CHILDCUT( 1 , HASMUON & ISMUON )                      &
        CHILDCUT( 2 , HASMUON & ISMUON )                      &
        ( MINTREE ( 'mu+' == ABSID , PT ) > 1 * GeV         ) &
        ( MAXTREE ( ISBASIC & HASTRACK , TRCHI2DOF ) < 4    ) &
        ( MINTREE ( ISBASIC & HASTRACK , CLONEDIST ) > 5000 ) &
        ( VFASPF  ( VPCHI2 ) > 0.5/100 )
        & ( abs ( BPV ( VZ    ) ) <  0.5 * meter     )
        & (       BPV ( vrho2 )   < ( 10 * mm ) ** 2 )
        """,
        Preambulo=[
            "vrho2 = VX**2 + VY**2"
        ],
        ReFitPVs=True
    )

    UpsSel = Selection(
        'UpsSel',
        Algorithm=UpsAlg,
        RequiredSelections=[DiMuData]
    )

    # =========================================================================
    # chi_b -> Upsilon gamma
    # ========================================================================
    from GaudiConfUtils.ConfigurableGenerators import CombineParticles
    ChibCombine = CombineParticles(
        DecayDescriptor="chi_b1(1P) ->  J/psi(1S) gamma",
        DaughtersCuts={
            "gamma": " ( 350 * MeV < PT ) & ( CL > 0.01 )  "
        },
        CombinationCut="""
        ( AM - AM1 ) < 3 * GeV
        """,
        MotherCut=" PALL",
        #
        # we are dealing with photons!
        #
        ParticleCombiners={
        '': 'LoKi::VertexFitter'
        }
    )
    from StandardParticles import StdLooseAllPhotons  # needed for chi_b
    ChibSel1 = Selection(
        'PreSelChib',
        Algorithm=ChibCombine,
        RequiredSelections=[UpsSel, StdLooseAllPhotons]
    )
    from GaudiConfUtils.ConfigurableGenerators import Pi0Veto__Tagger
    TagAlg = Pi0Veto__Tagger(
        ExtraInfoIndex=25001,  # should be unique!
        MassWindow=20 * MeV,  # cut on delta-mass
        MassChi2=-1,  # no cut for chi2(mass)
    )
    ChibSel2 = Selection(
        'Chi_b',
        Algorithm=TagAlg,
        RequiredSelections=[ChibSel1]
    )
    Chib = SelectionSequence("ChiB", TopSelection=ChibSel2)

    # print 'OUTPUT!!!' , output_loc

    # =========================================================================
    # Upsilons
    # ========================================================================
    Ups = SelectionSequence("UpsSelSeq", TopSelection=UpsSel)
    # ========================================================================
    from Configurables import GaudiSequencer
    myChibSeq = GaudiSequencer('MyChibSeq')
    myChibSeq.Members = [Chib.sequence()] + ["ChibAlg"]

    myUpsSeq = GaudiSequencer('MyUpsSeq')
    myUpsSeq.Members = [Ups.sequence()] + ["UpsilonAlg"]

    davinci = DaVinci(
        EventPreFilters=filters,
        DataType='2011',
        Simulation=True,
        InputType='DST',
        HistogramFile="chib_histos.root",
        TupleFile="chib_tuples.root",
        PrintFreq=1000,
        Lumi=True,
        EvtMax=-1
    )

    davinci.UserAlgorithms = [myChibSeq, myUpsSeq]

    # =========================================================================
    from Configurables import Gaudi__IODataManager as IODataManager
    IODataManager().AgeLimit = 2
    # =========================================================================
    # come back to Bender
    setData(datafiles, catalogs, castor)
    gaudi = appMgr()

    alg_chib = ChibMC(
        'ChibAlg',  # Algorithm name ,
        # input particles
        Inputs=[
            Chib.outputLocation()
        ],
        # take care about the proper particle combiner
        ParticleCombiners={'': 'LoKi::VertexFitter'}
    )

    alg_ups = UpsilonMC(
        'UpsilonAlg',  # Algorithm name ,
        # input particles
        Inputs=[
            Ups.outputLocation()
        ],
        # take care about the proper particle combiner
        ParticleCombiners={'': 'LoKi::VertexFitter'}
    )

    alg_chib.nb = alg_ups.nb = params['nb']
    alg_chib.np = alg_ups.np = params['np']

    # =========================================================================
    return SUCCESS
예제 #38
0
def defaultD0Selection():

    from Configurables import Escher, TAlignment
    Escher().RecoSequence = ["Hlt","Decoding","AlignTr","Vertex","RICH" ]
    Escher().MoniSequence = ["Tr","OT"]

    # Tweak a little bit RICH
    from TAlignment.ParticleSelections import MinimalRichSequence
    MinimalRichSequence()

    # now create the D0->K-Pi+ candidates
    from Configurables import FilterDesktop
    from Configurables import ChargedProtoParticleMaker, ChargedProtoParticleAddRichInfo, ChargedProtoCombineDLLsAlg

    # take as much as possible from CommonParticles
    from CommonParticles.StdAllLooseKaons import StdAllLooseKaons
    from CommonParticles.StdAllLoosePions import StdAllLoosePions
    from CommonParticles.StdLooseKaons import StdLooseKaons
    from CommonParticles.StdLoosePions import StdLoosePions
    from CommonParticles.StdLooseD02HH import StdLooseD02KPi
    # remove cuts that require a PV
    StdLooseD02KPi.MotherCut = "((VFASPF(VCHI2)<10) & (ADMASS('D0')<100*MeV))"
    StdLooseKaons.Code = "ALL"
    StdLoosePions.Code = "ALL"

    # add tight PID cuts basically toensure that we don't swap the
    # kaon and pion.
    AlignD02KPiWide = FilterDesktop("AlignD02KPiWide",
                                    Inputs = ["Phys/StdLooseD02KPi"], 
                                    Code = "(ADMASS('D0') < 50.*MeV) & (VFASPF(VCHI2) < 9.)" \
                                    " & (MINTREE('K+'==ABSID, PIDK) > 0)" \
                                    " & (MINTREE('pi+'==ABSID, PIDK) < 0)" )
    
    # tighten the mass window for candidates used in alignment.
    AlignD02KPi = FilterDesktop("AlignD02KPi",
                                Inputs = ["Phys/AlignD02KPiWide"], 
                                Code = "(ADMASS('D0') < 20.*MeV)" )

    # create the sequence that we pass to the alignment
    from Configurables import TrackParticleMonitor, GaudiSequencer
    recoD0Seq= GaudiSequencer("RecoD0Seq")
    recoD0Seq.Members = [ 
        ChargedProtoParticleMaker('ChargedProtoPMaker'),
        ChargedProtoParticleAddRichInfo('ChargedProtoPAddRich'),
        ChargedProtoCombineDLLsAlg('ChargedProtoPCombDLLs'),
        TrackParticleMonitor('StdLooseD02KPiMonitor', 
                              InputLocation = '/Event/Phys/StdLooseD02KPi/Particles',
                              MinMass = 1810, MaxMass = 1930),
        AlignD02KPiWide,
        TrackParticleMonitor('AlignD02KPiWideMonitor', 
                             InputLocation = '/Event/Phys/AlignD02KPiWide/Particles',
                             MinMass = 1810, MaxMass = 1930),
        AlignD02KPi,
        TrackParticleMonitor('AlignD02KPiMonitor', 
                             InputLocation = '/Event/Phys/AlignD02KPi/Particles',
                             MinMass = 1810, MaxMass = 1930)
                        ]

    from TAlignment.ParticleSelections import ParticleSelection
    sel = ParticleSelection( Name = 'D02KPi',
                             Location = '/Event/Phys/AlignD02KPi/Particles',
                             Algorithm = recoD0Seq )
    return sel

# Configure Stripping
from Configurables import ProcStatusCheck
filterBadEvents = ProcStatusCheck()

sc = StrippingConf( Streams = [ MyStream ],
                    MaxCandidates = 2000,
                    AcceptBadEvents = False,
                    BadEventSelection = filterBadEvents )


from Configurables import StrippingReport
sr = StrippingReport(Selections = sc.selections());

MySequencer = GaudiSequencer('Sequence')
MySequencer.Members = [sc.sequence(),sr]
MySequencer.IgnoreFilterPassed = True 

DaVinci().appendToMainSequence([killer, MySequencer])


 
from Configurables import FilterInTrees

rho_list = FilterInTrees( 'rho_list', Code = "'rho(770)0'==ABSID")
rho_Sel = Selection ( "rho_Sel" , Algorithm =rho_list  , RequiredSelections = [ AutomaticData(Location = location) ] )
rho_Seq = SelectionSequence("rho_Seq", TopSelection = rho_Sel)


예제 #40
0
        mothers[mother] = mothers_templates[mother].format(*tracks)
    for daughter in daughters_templates:
        daughters[daughter] = daughters_templates[daughter].format(*tracks)
    for mother in mc_mothers_templates:
        mc_mothers[mother] = mc_mothers_templates[mother].format(*tracks)
    for daughter in mc_daughters_templates:
        mc_daughters[daughter] = mc_daughters_templates[daughter].format(*tracks)

    # Tuple for stripped and reconstructed events
    t = tuple_templates.lc2pxx_tuple(
        "Tuple{0}".format(line),
        decay_template.format(*tracks),
        mothers,
        daughters,
        inputs_template.format(stripping),
        True
    )
    # Tuple for generated events
    mc_t = tuple_templates.mc_decay_tree_tuple(
        "MCGenTuple{0}".format(line),
        mc_decay_template.format(*tracks),
        mc_mothers,
        mc_daughters
    )

    # Stripped tuple will only be filled if MC tuple is
    sequence = GaudiSequencer("SeqBook{0}".format(line))
    sequence.Members = [mc_t, t]

    DaVinci().UserAlgorithms.append(sequence)
def configure ( inputdata        ,    ## the list of input files  
                catalogs = []    ,    ## xml-catalogs (filled by GRID)
                castor   = False ,    ## use the direct access to castor/EOS ? 
                params   = {}    ) :

    ## configure  Track <--> MC relation table  
    import LoKiPhysMC.Track2MC_Configuration
    import LoKiMC.MC
    
    ## import DaVinci 
    from Configurables import DaVinci, GaudiSequencer
    ## delegate the actual configurtaion to DaVinci 
    dv = DaVinci ( DataType   = '2011' ,
                   InputType  = 'MDST',
                   Lumi = True,
                   Simulation = True,
                   DDDBtag="MC11-20111102",
                   CondDBtag="sim-20111111-vc-md100",
                   HistogramFile = "mcd02kpi_tracks7_histo.root",
                   TupleFile = "mcd02kpi_tracks7_ntuple.root",
                   PrintFreq = 1000)
    

    from Configurables import DecayTreeTuple, FilterDesktop, TupleToolGeometry, CombineParticles
    from Configurables import MCDecayTreeTuple, TupleToolMCTruth, MCTupleToolHierarchy
    from PhysSelPython.Wrappers import AutomaticData, Selection, SelectionSequence, DataOnDemand
    from Configurables import CheckPV
    

    # First using CombineParticle to create the D0
    ################################################################################
    #from StandardParticles import  StdAllNoPIDsPions, StdAllNoPIDsKaons
    _pions = DataOnDemand(Location='Phys/StdAllNoPIDsPions/Particles')
    _kaons = DataOnDemand(Location='Phys/StdAllNoPIDsKaons/Particles')

    _d2kpi = CombineParticles("d2kpi")
    _d2kpi.DecayDescriptor = "[D0 -> K- pi+]cc"
    _d2kpi.DaughtersCuts = { "K-"  : "(PT > 500.0) & (0.0 < PIDK)",
                             "pi+" : "(PT > 500.0) & (5.0 > PIDK)",
                             "K+"  : "(PT > 500.0) & (0.0 < PIDK)",
                             "pi-" : "(PT > 500.0) & (5.0 > PIDK) " }
    _d2kpi.MotherCut = "(VFASPF(VCHI2/VDOF)<10)"
    _d2kpi.CombinationCut = "(ADAMASS('D0') < 50.0)"
    _d2kpi.Preambulo = [ 
        "from LoKiPhysMC.decorators import *" ,
        "from PartProp.Nodes import CC"      ]
    #_d2kpi.ReFitPVs = True

    SelD2KPi = Selection( "SelD2KPi",
                          Algorithm= _d2kpi,
                          RequiredSelections=[_pions,_kaons] ) 
    
    SeqD2KPi = SelectionSequence('SeqD2KPi',TopSelection = SelD2KPi)

    
    # Now the CheckPV method to filter algorithms
    c = CheckPV("OnePV")
    c.MinPVs = 1

    # And a sequencer to put them together
    gseq = GaudiSequencer()
    gseq.Members = [ c, SeqD2KPi.sequence() ]
    
    ## define the input data
    setData  ( inputdata , catalogs , castor )
    
    ## get/create application manager
    gaudi = appMgr() 
    
    #
    ## modify/update the configuration:
    #
    
    ## (1) create the algorithm
    alg = TrackFilter( 'TrackFilter' )
    
    #seq = createSequencer()
    ## (2) replace the list of top level algorithm by
    #     new list, which contains only *THIS* algorithm
    gaudi.setAlgorithms( [ gseq, alg ] )
             
    return SUCCESS
예제 #42
0
def doIt():
   #------------------------------
   #Configure PrChecker
   #------------------------------
   from Configurables import GaudiSequencer
   from Configurables import PrChecker
   from Configurables import IdealStateCreator
   GaudiSequencer("CheckPatSeq").Members += []
   prChecker = PrChecker()
   from Configurables import IdealStateCreator

   if (Plotta):
      prChecker.WriteTTrackHistos = 2
      prChecker.Eta25Cut = Eta25Cut
      prChecker.UseElectrons = False
      prChecker.TriggerNumbers = True
   GaudiSequencer("CheckPatSeq").Members +=[prChecker]
   from Configurables import MCParticle2MCHitAlg, IdealStateCreator, PrPlotFTHits
   # Define the algorithms
   FTAssoc = MCParticle2MCHitAlg( "MCP2FTMCHitAlg", 
                                  MCHitPath = "MC/FT/Hits", 
                                  OutputData = "/Event/MC/Particles2MCFTHits" )
   
   # tell the Data On Demand Service about them
   DataOnDemandSvc().AlgMap[ "/Event/Link/MC/Particles2MCFTHits" ]    = FTAssoc
   DataOnDemandSvc().NodeMap[ "/Event/Link" ]    = "DataObject"
   DataOnDemandSvc().NodeMap[ "/Event/Link/MC" ] = "DataObject"
   
   #---------------------------------
   #Configure the HitManager
   #---------------------------------
   #if (ConfigureManager):
#      from Configurables import PrFTHitManager
#      manager = PrFTHitManager("PrFTHitManager")
      
#      manager.fracPosOffset = fracPos
#      manager.doTuple = manager
#      manager.HackSize1 = False
#      manager.FixError = False
#      manager.SizeFix = FixedSize

   
   #---------------------------------
   #Configure the Seeding Tracking
   #---------------------------------
   seedingSeq = GaudiSequencer("TrSeedingSeq")
   GaudiSequencer("TrBestSeq").Members = []
   GaudiSequencer("TrSeedingSeq").Members = []
   #if you do truthmatching in the pat reco
   GaudiSequencer("MCLinksUnpackSeq").Members =[]
   GaudiSequencer("RecoTrSeq").Members += [ seedingSeq ]
   from Configurables import PrHybridSeeding
   seeding = PrHybridSeeding()
   #seeding.OutputLevel = DEBUG #Uncomment this line for debug      
   seeding.InputName ="" #Standalone seeding Put "Forward to get forward imput"
   seeding.MaxNHits = 12 #Force algorithm to find 12 Hits track when > 12
   seeding.DecodeData = True # Switch it off if Runned after Forward
   seeding.XOnly = False
   #N Cases
   seeding.NCases = 3
   seeding.MinXPlanes = 4
   #Clones Kill
   seeding.RemoveClonesX = True
   seeding.RemoveClones = True
   seeding.minNCommonUV = 7 #>=7
   seeding.minCommonX = [2,2,2] # N Common X (Remove Clones [Case0,Case1,Case2])
   seeding.RemoveClonesUpDown = False # should Speed Up
   seeding.minNCommonUVUpDown = 2 #>=2
   
   #Flag Hits
   seeding.FlagHits = True
   seeding.SizeToFlag = 12 # >=size
   seeding.RemoveFlagged = True # Case 1 and 2 will not use flagged Hits
   #If Flag Size = 11
   seeding.Flag_MaxChi2 = 0.3 # track.chi2(hit) = 0.3
   seeding.Flag_MaxX0  = 200  # <200
   #dRatio Business
   seeding.UseCubicCorrection = True # dRatio correction in the fit
   seeding.dRatio = -0.000262
   seeding.UseCorrPosition = True # dRatio( x,y)
   seeding.UseCorrSlopes = False #  dRatio( bx, by)
   seeding.CConst = 2.458e8 # BackwardProjection ( To be used somewhere in the algo )
   #Recover Track ( to be fully implemented properly)
   seeding.RecoverTrack = False
   seeding.ChiDoFRecover = -1.0
   #Case 0,1,2 parameters 1st Last search

   #XZ-Search
   # 1st - Last Layer
   seeding.L0_AlphaCorr = [120.64, 510.64, 730.64 ]
   seeding.L0_tolHp     = [280.0 , 540.0 , 1080.0 ]
   # ParabolaSeedHits
   seeding.x0Corr        =     [0.002152, 0.001534, 0.001534]
   
   seeding.X0SlopeChange =     [500.    ,    500. ,    500. ]
   seeding.x0Cut        =      [4000.   ,    4000.,   4000. ]
   seeding.TolAtX0Cut   =      [12.0    ,     8.0 ,    8.0  ]
   seeding.ToleranceX0Up =     [ 0.75   ,     0.75,    0.75 ]

   seeding.X0SlopeChangeDown = [ 1500.  ,    2000.,    1500. ]
   seeding.TolAtX0CutOpp     = [3.0     ,      2.0,     2.0  ]
   seeding.ToleranceX0Down   = [ 0.75   ,      0.75,    0.75 ]
   
   seeding.TolXRemaining     = [1.0     ,      1.0 ,     1.0]
   seeding.maxParabolaSeedHits = 12 # Hits are sorted by the distance from
   #  x0 = first-last projection to z=0 ; then hits sorted by xParabola - (x0+tx_1stLast*z_PlaneParabola + x0Corr*x0)  and we keep the first maxParabolaSeedHits list
   seeding.maxChi2HitsX     = [5.5      , 5.5     , 5.5   ]
   seeding.maxChi2DoFX      = [4.0      , 5.0     , 6.0   ]
   
   #Add Stereo Part
   seeding.DoAsymm = True
   seeding.TriangleFix = True
   seeding.TriangleFix2ndOrder = True
   seeding.yMin = -1.0
   seeding.yMin_TrFix = -2.0
   seeding.yMax =    2700
   seeding.yMax_TrFix = 30.0
   seeding.RemoveHole = True
   #Hough Cluster Size settings Hits are sorted by y/z where y is computed from the XZ-segment processed
   seeding.TolTyOffset = [ 0.002  , 0.002 , 0.0035  ]
   seeding.TolTySlope  = [ 0.0    , 0.0   , 0.015   ]

   #Once you find The UV hits you check the Line Y ?
   seeding.UseLineY = True
   
   #9 and 10 hits
   seeding.Chi2LowLine =           [ 5.0 , 6.0  , 7.0  ] #Chi2PerDoF when 10 Hits or 9
   seeding.maxChi2Hits_less11Hit = [ 2.5 , 2.5  , 2.5  ]
   seeding.maxYatZeroLow =         [ 50., 50.   , 50.  ]
   seeding.maxYatzRefLow =         [500., 500.  , 500. ]
   #11 and 12 Hits
   seeding.Chi2HighLine =          [30.0, 50.0 , 80.0] #Chi2PerDoF when 11 or 12 hits Using LineChi2DoF + XZChi2DoF
   seeding.maxChi2Hits_11and12Hit =[ 5.5, 5.5, 5.5    ] 
   
   #Make the Full Fit
   seeding.maxChi2PerDoF          = [4.0, 6.0, 7.0]
      
   seeding.RecoverTrack = False #Get only tracks with 6 UV or 6 X
   seeding.ChiDoFRecover = -1.0 #Change it only if RecoverTrack = True
   
   #TruthMatching Settings (Comment all of them if you want to run the normal seeding 
   if(ConfigureManager):
      from Configurables import PrFTHitManager
      #seeding.addTool(manager)
      #seeding.PrFTHitManager.SizeFix = FixedSize
      #seeding.PrFTHitManager.FixError = True
   seedingSeq.Members = [seeding]
예제 #43
0
from Configurables import (ApplicationMgr, EventDataSvc,
                           RecordOutputStream, ReplayOutputStream,
                           GaudiSequencer,
                           GaudiTesting__OddEventsFilter as OddEvents,
                           GaudiTesting__EvenEventsFilter as EvenEvents,
                           SubAlg as EmptyAlg)

outDelegate = ReplayOutputStream()
outDelegate.OutputStreams = [EmptyAlg('Stream1'), EmptyAlg('Stream2')]

oddEvtSelect = GaudiSequencer('OddEventsSelection')
oddEvtSelect.Members = [OddEvents('OddEvents'),
                        RecordOutputStream('Rec1', OutputStreamName='Stream1')]

evenEvtSelect = GaudiSequencer('EvenEventsSelection')
evenEvtSelect.Members = [EvenEvents('EvenEvents'),
                         RecordOutputStream('Rec2', OutputStreamName='Stream2')]

app = ApplicationMgr(EvtSel='NONE', EvtMax=4)
app.TopAlg = [EmptyAlg("EventInit"), evenEvtSelect, oddEvtSelect]
app.OutStream = [outDelegate]

EventDataSvc(ForceLeaves=True)

#from Gaudi.Configuration import VERBOSE
#from Configurables import MessageSvc
#MessageSvc(OutputLevel=VERBOSE)
        "Tuple{0}".format(line),
        decay_template.format(*tracks),
        mothers,
        daughters,
        # The input to the tuple is the output of the filter
        inputs_template.format(stripping),
        mc
    )

    # MCDecayTreeTuple
    mc_tuple = tuple_templates.mc_decay_tree_tuple(
        "MCGenTuple{0}".format(line),
        mc_decay_template.format(*tracks),
        mc_mothers,
        mc_daughters
    )

    # Sequences for ntuple creation
    dec_sequence = GaudiSequencer("SeqBook{0}".format(line))
    dec_sequence.Members = [tuple]
    mc_sequence = GaudiSequencer("SeqMCGenBook{0}".format(line))
    mc_sequence.Members = [mc_tuple]

    # Sequence for ntuple sequences
    tuples_sequence = GaudiSequencer("SeqTuples{0}".format(line))
    tuples_sequence.IgnoreFilterPassed = True
    tuples_sequence.Members = [dec_sequence, mc_sequence]

    DaVinci().UserAlgorithms.append(tuples_sequence)

예제 #45
0
tuple.ToolList   += [ 'LoKi::Hybrid::TupleTool/LoKiVariables2']

##################################################
from Configurables import CondDB, CondDBAccessSvc
CondDB().LatestGlobalTagByDataType = DataYear
##################################################
from Configurables import LHCbApp
LHCbApp().XMLSummary='summary.xml'

#from Configurables import DataOnDemandSvc, L0SelReportsMaker, L0DecReportsMaker
#DataOnDemandSvc().AlgMap["HltLikeL0/DecReports"] = L0DecReportsMaker( OutputLevel = 4 )
#DataOnDemandSvc().AlgMap["HltLikeL0/SelReports"] = L0SelReportsMaker( OutputLevel = 4 )

# User Algorithms
from Configurables import GaudiSequencer
userAlgos = GaudiSequencer("userAlgos")
userAlgos.Members = []
#userAlgos=[]
if  IsMC:
  from Configurables import TrackSmearState as SMEAR
  smear = SMEAR('StateSmear')
  userAlgos.Members.append(smear)
else:
  #
  from Configurables import CheckPV
  checkpv = CheckPV("CheckPV")
  checkpv.MinPVs = 1
  userAlgos.Members.append(checkpv)
  from Configurables import TrackScaleState as SCALER
  scaler = SCALER('StateScale')
  userAlgos.Members.append(scaler)  
예제 #46
0
MessageSvc().Format = "% F%60W%S%7W%R%T %0W%M"

# database
DaVinci().DDDBtag   = "dddb-20150724"
DaVinci().CondDBtag = "cond-20160522"

#
# Raw event juggler to split DAQ/RawEvent into FULL.DST format
#
from Configurables import GaudiSequencer, RawEventJuggler
jseq=GaudiSequencer("RawEventSplitSeq")
juggler=RawEventJuggler("rdstJuggler")
juggler.Sequencer=jseq
juggler.Input=0.3  # 2015 Online (Moore) format 
juggler.Output=4.2 # Reco15 format

# filter out events triggered exclusively by CEP lines
from Configurables import LoKi__HDRFilter as HDRFilter
from DAQSys.Decoders import DecoderDB
Hlt2DecReportsDecoder=DecoderDB["HltDecReportsDecoder/Hlt2DecReportsDecoder"].setup()
HLTFilter2 = HDRFilter("LoKiHLT2Filter"
                      , Code = "HLT_PASS_RE('Hlt2(?!Forward)(?!DebugEvent)(?!Lumi)(?!Transparent)(?!PassThrough)(?!LowMult).*Decision')"
                      , Location = Hlt2DecReportsDecoder.OutputHltDecReportsLocation)
otherseq=GaudiSequencer("filters")
otherseq.Members=[jseq,HLTFilter2]

DaVinci().EventPreFilters = [jseq,HLTFilter2]

# input file
importOptions("$STRIPPINGSELECTIONSROOT/tests/data/Reco16_Run182594.py")
예제 #47
0
    filter.Inputs = [inputs_template.format(stripping)]

    # Fill the branch templates with the appropriate particles
    mothers = {}
    daughters = {}
    for mother in mother_templates:
        mothers[mother] = mother_templates[mother].format(*tracks)
    for daughter in daughter_templates:
        daughters[daughter] = daughter_templates[daughter].format(*tracks)

    # Create a tuple for the mode
    tuple = tuple_templates.decay_tree_tuple(
        "Tuple{0}".format(line),
        decay_template.format(*tracks),
        mothers,
        daughters,
        # The input to the tuple is the output of the filter
        inputs_template.format(filter_name),
        mc
    )
    # Refit the decay tree, storing refitted daughter information
    dtf = tuple.Lambdab.addTupleTool("TupleToolDecayTreeFitter/Fit")
    dtf.Verbose = True

    # Sequence to hold a succession of algorithms
    sequence = GaudiSequencer("SequenceBook{0}".format(line))
    sequence.Members = [filter, tuple]

    DaVinci().UserAlgorithms.append(sequence)

def configure_dv() :
    global toolList
    streams = get_streams(strippingVersion)
    configs = []
    userSeq = GaudiSequencer('UserSeq')
    userSeq.IgnoreFilterPassed = True
    if isMC :
        toolList += ['TupleToolMCTruth',
                     #'TupleToolGeneration'
                     'TupleToolMCBackgroundInfo'
                     ]
    for baryon in charmBaryons :
        for bachelor in bachelors :
            lineName = stripping_line_name(bachelor, baryon)
            dtt, line, stream, conf = \
                make_stripping_tuple(lineName, streams, toolList,
                                     lineName[:-len('Beauty2Charm')] + 'Tuple')
            dttSeq = GaudiSequencer(line.name() + 'Seq', Members = [dtt])
            if 'Xic' == baryon :
                decayDesc = dtt.Decay
                dtt.Decay = decayDesc.replace('Lambda_b0', 'Xi_b0')
                decayDescPlus = reduce(lambda x,y : x.replace(y, ''), ('^', '[', ']', 'CC'), decayDesc)
                decayDescMinus = decayDescPlus.replace('+', '!').replace('->', '#').replace('-', '+')\
                    .replace('!', '-').replace('0', '~0').replace('#', '->').replace('Xi_c-', 'Xi_c~-').replace('p-', 'p~-')
                subPID = SubstitutePID(baryon+bachelor+'SubstitutePID', Code = 'ALL', 
                                       Substitutions = {decayDescPlus : 'Xi_b0',
                                                        decayDescMinus : 'Xi_b~0'},
                                       Inputs = dtt.Inputs,
                                       Output = dtt.Inputs[0].replace('Beauty2CharmLine', 'Beauty2CharmLine-Subd'))
                dtt.Inputs = [subPID.Output]
                dttSeq.Members.insert(0, subPID)
            configs.append({'dtt' : dtt, 'dttSeq' : dttSeq, 'line' : line, 'stream' : stream,
                           'conf' : conf, 'charmBaryon' : baryon, 'bachelor' : bachelor})
            dtt.ReFitPVs = True # Do I need this? - probably yes if you want to use vertex constraints without biasing the lifetime.
            # Configure DTF
            decayNoCaret = dtt.Decay.replace('^', '')

            baryonSymbol = baryonSymbols[baryon]
            baryonDec = baryonDescriptors[baryon]
            decayCharmCaret = decayNoCaret.replace('('+baryonDec, '^(' + baryonDec)

            dtt.addBranches( {'X_b0' : decayNoCaret, 
                              'X_cplus' : decayCharmCaret } )

            bachelorDec = bachelorDescriptors[bachelor]
            otherBachelorDec = oppositeBachelors[bachelor]

            decayBachelorCaret = decayNoCaret[::-1].replace(bachelorDec[::-1], bachelorDec[::-1]+'^', 1)[::-1]
            bachelorSub = {decayBachelorCaret : otherBachelorDec}

            for mass, massName in ([baryonDec], '_Mass'), ([], '') :
                for vtx, vtxName in (True, '_Vtx'), (False, '') :
                    tt_dtf_name = 'TupleToolDecayTreeFitter/DTF' + massName + vtxName
                    tt_dtf = dtt.X_b0.addTupleTool(tt_dtf_name)
                    tt_dtf_sub = dtt.X_b0.addTupleTool(tt_dtf_name + '_Sub')
                    tt_dtf_sub.Substitutions = bachelorSub
                    for dtf in tt_dtf, tt_dtf_sub :
                        dtf.constrainToOriginVertex = vtx
                        dtf.daughtersToConstrain = mass
                        dtf.Verbose = True

    dv.DataType = get_data_type(firstInputFile)

    if isMC :
        for config in configs :
            line = config['line']
            #algs = line.filterMembers()
            algs = line._members
            # Remove TISTOS tagger and BDT filter. 
            algs = algs[:-3]
            # Remove VoidFilter for nTracks < 250.
            #algs.pop(0)
            #remove_selection_criteria(algs[3], algs[5], algs[7], 
            #                          algs[9]) # std particles.
            selalgs = filter(lambda x : isinstance(x, (FilterDesktop, 
                                                       CombineParticles)), algs)
            remove_selection_criteria(*selalgs)
            decayDesc = config['dtt'].Decay.replace('^', '')
            preamble = [ "from LoKiPhysMC.decorators import *" , "from LoKiPhysMC.functions import mcMatch" ]
            # for alg in selalgs :
            #     alg.Preambulo = preamble
            #     if hasattr(alg, 'Code') :
            #         alg.Code += ' & mcMatch({0!r})'.format(decayDesc)
            #     else :
            #         alg.MotherCut += ' & mcMatch({0!r})'.format(decayDesc)
            # filter(lambda x : isinstance(x, CombineParticles), algs)[-1].CombinationCut = '(AM<7000*MeV) & (AM>5200*MeV)'
            #remove_selection_criteria(algs[8], # Lc/Xic
            #                          algs[10]) # Lb
            combineParticles = filter(lambda x : isinstance(x, CombineParticles), algs)
            for comb in combineParticles :
                comb.Preambulo = preamble
            motherSymbol = baryonDescriptors[config['charmBaryon']]
            decayDesc = decayDesc.replace('->', '==>') # to allow for intermediate resonances.
            combineParticles[0].MotherCut += ' & mcMatch({0!r})'.format(decayDesc.replace('(' + motherSymbol, '^(' + motherSymbol))
            combineParticles[0].DaughtersCuts = {'p+' : 'mcMatch({0!r})'.format(decayDesc.replace('p+', '^p+')),
                                                'K-' : 'mcMatch({0!r})'.format(decayDesc.replace('K-', '^K-')),
                                                'pi+' : 'mcMatch({0!r})'.format(decayDesc.replace('pi+', '^pi+'))}
            bachelorSymbol = bachelorDescriptors[config['bachelor']]
            combineParticles[1].DaughtersCuts = {bachelorSymbol : 'mcMatch({0!r})'.format(decayDesc.replace(bachelorSymbol, '^' + bachelorSymbol)),
                                                motherSymbol : 'ALL'}

            #algs = remove_selection_criteria(*algs)
            algs[-1].Output = config['dttSeq'].Members[0].Inputs[0]
            config['dttSeq'].Members = algs + config['dttSeq'].Members
            
        dv.Simulation = True
        dv.DDDBtag = dddbTag 
        dv.CondDBtag = conddbTag

    else :
        scaler = TrackScaleState()
        #scaler.CONDDBpath = '/dd/Conditions/Calibration/LHCb/MomentumScale'
        #scaler.CONDDBpath = '/dd/Conditions/Calibration/LHCb'
        userSeq.Members = [scaler]
        from Configurables import CondDB
        CondDB(LatestGlobalTagByDataType = dv.DataType)

    for config in configs :
        userSeq.Members.append(config['dttSeq'])
    dv.UserAlgorithms = [userSeq]
    dv.InputType = firstInputFile.split('.')[-1].upper()
    if 'MDST' == dv.InputType :
        dv.RootInTES = '/Event/' + configs[0]['stream'].name()