Beispiel #1
0
    def add_mc_unbiased_sequence(self, decayDesc, arrow = '==>',
                                 toolList = ["TupleToolPropertime",
                                             "TupleToolKinematic",
                                             "TupleToolGeometry",
                                             "TupleToolEventInfo",
                                             "TupleToolPrimaries",
                                             "TupleToolPid",
                                             "TupleToolANNPID",
                                             "TupleToolTrackInfo",
                                             "TupleToolRecoStats",],
                                 mcToolList = ['TupleToolMCTruth',
                                               'TupleToolMCBackgroundInfo',
                                               'MCTupleToolPrompt'],
                                 L0List = [],
                                 HLT1List = [],
                                 HLT2List = [],
                                 strippingList = []) :
        decayDescCC = decayDesc.copy()
        decayDescCC.cc = True

        sel = build_mc_unbiased_selection(decayDesc, arrow)
        selseq = SelectionSequence(decayDesc.get_full_alias() + '_MCSeq',
                                   TopSelection = sel)
        seq = selseq.sequence()
        seq.Members.insert(0, CheckPV())
        dtt = DecayTreeTuple(decayDesc.get_full_alias() + '_MCTuple',
                             Decay = decayDesc.to_string(carets = True),
                             Inputs = [sel.outputLocation()], 
                             ToolList = [])
        dtt.addBranches(decayDesc.branches())
        headBranch = getattr(dtt, decayDesc.get_alias())

        dtt.configure_tools(toolList = toolList,
                            mcToolList = mcToolList,
                            L0List = L0List,
                            HLT1List = HLT1List,
                            HLT2List = HLT2List,
                            strippingList = strippingList,
                            headBranch = headBranch)

        lokituple = headBranch.addTupleTool('LoKi::Hybrid::TupleTool')
        lokituple.Preambulo = ['from LoKiPhysMC.decorators import *',
                               'from LoKiPhysMC.functions import mcMatch']
        mcmatch = 'switch(mcMatch({0!r}), 1, 0)'.format(decayDescCC.to_string(carets = False,
                                                                              arrow = '==>'))
        lokituple.Variables = {'mcMatch' : mcmatch}


        seq.Members.append(dtt)
        self.UserAlgorithms.append(seq)

        mcdtt = MCDecayTreeTuple(decayDesc.get_full_alias() + '_MCDecayTreeTuple')
        mcdtt.addBranches(decayDesc.branches())
        mcdtt.Decay = decayDescCC.to_string(arrow = arrow, carets = True)
        mcdtt.ToolList += filter(lambda t : t.startswith('MC'), mcToolList)
        self.UserAlgorithms.append(mcdtt)

        return seq
Beispiel #2
0
def test_instantiate_multi_sequencer():
    sel00 = AutomaticData(Location='Phys/Sel00')
    sel01 = AutomaticData(Location='Phys/Sel01')
    alg00 = MockConfGenerator()
    alg01 = MockConfGenerator()
    sel00 = Selection('100011', Algorithm=alg00, RequiredSelections=[sel00])
    sel01 = Selection('100012', Algorithm=alg01, RequiredSelections=[sel01])
    seq00 = SelectionSequence('Seq000', TopSelection=sel00)
    seq01 = SelectionSequence('Seq001', TopSelection=sel01)
    seq = MultiSelectionSequence('MultiSeq00z', Sequences=[seq00, seq01])
Beispiel #3
0
def make_mc_unbiased_seq(desc, arrow = '==>', refitpvs = True) :
    '''Make a selection sequence for the given decay descriptor that has no cuts besides
    truth matching.'''
    desc = desc.copy()
    desc.clear_aliases()
    sel = build_mc_unbiased_selection(desc, arrow, refitpvs)
    selseq = SelectionSequence(desc.get_full_alias() + '_MCUnbiasedSeq',
                               TopSelection = sel)
    seq = selseq.sequence()
    seq.Members.insert(0, CheckPV())
    return seq, selseq
Beispiel #4
0
def test_call_important_methods():
    sel00 = AutomaticData(Location='Phys/Sel00/Particles')
    sel01 = AutomaticData(Location='Phys/Sel01/Particles')
    seq00 = SelectionSequence('Seq00y', TopSelection=sel00)
    seq01 = SelectionSequence('Seq01y', TopSelection=sel01)
    seq = MultiSelectionSequence('MultiSeq00y', Sequences=[seq00, seq01])
    assert seq.outputLocations() == [
        'Phys/Sel00/Particles', 'Phys/Sel01/Particles'
    ]
    algs = seq.algorithms()
    seq = seq.sequence()
    def add_mc_unbiased_sequence(self, decayDesc, arrow = '==>',
                                 toolList = ["TupleToolPropertime",
                                             "TupleToolKinematic",
                                             "TupleToolGeometry",
                                             "TupleToolEventInfo",
                                             "TupleToolPrimaries",
                                             "TupleToolPid",
                                             "TupleToolANNPID",
                                             "TupleToolTrackInfo",
                                             "TupleToolRecoStats",],
                                 mcToolList = ['TupleToolMCTruth',
                                               'TupleToolMCBackgroundInfo',
                                               'MCTupleToolPrompt'],
                                 L0List = [],
                                 HLT1List = [],
                                 HLT2List = [],
                                 strippingList = []) :
        sel = build_mc_unbiased_selection(decayDesc, arrow)
        selseq = SelectionSequence(decayDesc.get_full_alias() + '_MCSeq',
                                   TopSelection = sel)
        seq = selseq.sequence()
        seq.Members.insert(0, CheckPV())
        dtt = DecayTreeTuple(decayDesc.get_full_alias() + '_MCTuple',
                             Decay = decayDesc.to_string(carets = True),
                             Inputs = [sel.outputLocation()], 
                             ToolList = [])
        dtt.addBranches(decayDesc.branches())
        headBranch = getattr(dtt, decayDesc.get_alias())

        dtt.configure_tools(toolList = toolList,
                            mcToolList = mcToolList,
                            L0List = L0List,
                            HLT1List = HLT1List,
                            HLT2List = HLT2List,
                            strippingList = strippingList,
                            headBranch = headBranch)

        lokituple = headBranch.addTupleTool('LoKi::Hybrid::TupleTool')
        lokituple.Preambulo = ['from LoKiPhysMC.decorators import *',
                               'from LoKiPhysMC.functions import mcMatch']
        mcmatch = 'switch(mcMatch({0!r}), 1, 0)'.format(decayDesc.to_string(carets = False,
                                                                            arrow = '==>'))
        lokituple.Variables = {'mcMatch' : mcmatch}


        seq.Members.append(dtt)
        self.UserAlgorithms.append(seq)

        mcdtt = MCDecayTreeTuple(decayDesc.get_full_alias() + '_MCDecayTreeTuple')
        mcdtt.Decay = decayDesc.to_string(arrow = arrow, carets = True)
        self.UserAlgorithms.append(mcdtt)

        return seq
Beispiel #6
0
def test_multiselectionsequence_with_existing_configurable_name_raises():

    fd = FilterDesktop('MultiSeq00')
    sel00 = AutomaticData(Location='Phys/Sel00')
    sel01 = AutomaticData(Location='Phys/Sel01')
    seq00 = SelectionSequence('SelSeq00x', TopSelection=sel00)
    seq01 = SelectionSequence('SelSeq01x', TopSelection=sel01)

    raises(NameError,
           MultiSelectionSequence,
           'MultiSeq00',
           Sequences=[seq00, seq01])
def test_sequencer_sequence():
    _sel00 = AutomaticData(Location='Phys/Sel00')
    _sel01 = AutomaticData(Location='Phys/Sel01')
    _sel02 = AutomaticData(Location='Phys/Sel02')
    _sel03 = AutomaticData(Location='Phys/Sel03')

    sel01 = Selection('000110',
                      Algorithm=MockConfGenerator(),
                      RequiredSelections=[_sel00, _sel01])
    sel02 = Selection('000111',
                      Algorithm=MockConfGenerator(),
                      RequiredSelections=[_sel02, _sel03])
    sel03 = Selection('000112',
                      Algorithm=MockConfGenerator(),
                      RequiredSelections=[sel01, sel02])

    presel0 = MockConfGenerator()
    presel1 = MockConfGenerator()
    postsel0 = MockConfGenerator()
    postsel1 = MockConfGenerator()

    presels = [presel0, presel1]
    postsels = [postsel0, postsel1]
    seq = SelectionSequence('Seq0002',
                            TopSelection=sel03,
                            EventPreSelector=presels,
                            PostSelectionAlgs=postsels,
                            sequencerType=DummySequencer)

    seqAlgos = seq.sequence().Members

    ref_algos = [
        presel0, presel1,
        _sel00.algorithm(),
        _sel01.algorithm(),
        _sel02.algorithm(),
        _sel03.algorithm(),
        sel02.algorithm(),
        sel01.algorithm(),
        sel03.algorithm(), postsel0, postsel1
    ]

    assert len(seqAlgos) == 11

    assert presels == ref_algos[:len(presels)]

    assert postsels == ref_algos[len(ref_algos) - len(postsels):]

    for sel in [sel01, sel02, sel03]:
        assert sel.algorithm() in ref_algos[len(presels):len(ref_algos) -
                                            len(postsels)]
 def __init__(self, _name, _config={}):
     self.name = _name
     self.config = {
         "ALL":
         {  # Cuts made on all charged input particles in all lines (excpt. upstream)
             'TRCHI2DOF_MAX': 5,
             'PT_MIN': '100*MeV',
             'P_MIN': '1000*MeV',
             'MIPCHI2DV_MIN': 4,
             'TRGHP_MAX': 0.4
         },
         "V0s": {
             'PT_MIN': '500*MeV',
             'P_MIN': '1000*MeV',
             'MIPCHI2DV_MIN': 4
         },
         "Photons": {
             'PT_MIN': '2500*MeV',
             'P_MIN': '4000*MeV'
         },
         'BB': {
             'ADDSUMPT': 0,
             'COSANGLE_MAX': 0.99,
             'COSDPHI_MAX': 0,
             'M_MIN': 0,
             'MAXPT_MIN': 4000
         },
         'PIDE_MIN': -2.0
     }
     self.config.update(_config)
     self.algorithms = []
     self.kaons = self.filterInputs('mK', [StdAllNoPIDsKaons],
                                    self.config['ALL'])
     self.V0s = self.filterInputs('mV0s', [
         self.dataOnDemand('StdLooseKsLL'),
         self.dataOnDemand('StdLooseKsDD'),
         self.dataOnDemand('StdLooseLambdaLL'),
         self.dataOnDemand('StdLooseLambdaDD')
     ], self.config['V0s'])
     self.Photons = self.filterInputs(
         'mG', [self.dataOnDemand('StdLooseAllPhotons')],
         self.config['Photons'])
     self.topoKaons = self.topoInputs('mK', [self.kaons])
     self.topos = self.makeTopoCands(
         MergedSelection('allInput', [self.topoKaons, self.V0s]),
         self.config['BB']['ADDSUMPT'])
     self.seq = SelectionSequence('seq', TopSelection=self.topos)
     self.algorithms = [self.seq.sequence()]
class SelectionTree(object):
    sel000 = Selection('0.00000',
                       Algorithm=MockConfGenerator(),
                       RequiredSelections=[])
    sel001 = Selection('0.00001',
                       Algorithm=MockConfGenerator(),
                       RequiredSelections=[])
    sel002 = Selection('0.00002',
                       Algorithm=MockConfGenerator(),
                       RequiredSelections=[])
    sel003 = Selection('0.00003',
                       Algorithm=MockConfGenerator(),
                       RequiredSelections=[])

    sel100 = Selection('1.00000',
                       Algorithm=MockConfGenerator(),
                       RequiredSelections=[sel000, sel001])

    sel101 = Selection('1.00001',
                       Algorithm=MockConfGenerator(),
                       RequiredSelections=[sel002, sel003])

    sel200 = Selection('2.00000',
                       Algorithm=MockConfGenerator(),
                       RequiredSelections=[sel100, sel101])

    selSeq = SelectionSequence('Seq06', TopSelection=sel200)
    algs = selSeq.algorithms()
    alg_names = [a.name() for a in algs]
def get_selection_sequence(name):
    """Get the selection from stripping stream"""
    # Relative lesLoc for uDST, no preceeding '/'
    tesLoc = 'Phys/B2DPiPiD2HHHCFPIDBeauty2CharmLine/Particles'
    alg = FilterDesktop('SelFilterFor{}B2D'.format(name))
    alg.Code = 'ALL'
    reqSels = [DataOnDemand(Location=tesLoc)]
    sel = Selection('Sel' + name, Algorithm=alg, RequiredSelections=reqSels)
    return SelectionSequence('SelSeq' + name, TopSelection=sel)
Beispiel #11
0
def add_tuples():
    '''Make ntuples for the D0->hhpi0 stripping lines. Assumes the data settings have already
    been configured in DaVinci.'''

    # Normal data
    stream = 'Charm.mdst'
    simulation = DaVinci().getProp('Simulation')
    # For restripping
    if DaVinci().getProp('ProductionType') == 'Stripping':
        stream = 'CharmCompleteEvent.dst'
    # For MC.
    elif simulation:
        stream = 'AllStreams.dst'

    fulldst = stream.endswith('.dst')
    streamname = '.'.join(stream.split('.')[:-1])

    tuples = []
    seqs = []
    for line in get_line_docs():
        stripdata = StrippingData(line.name,
                                  stream=(streamname if fulldst else None))
        if not simulation:
            stripdata = MomentumScaling(stripdata)
        lineconfig = line.tuple_config()
        del lineconfig['Inputs']
        dttsel = TupleSelection(line.name + 'Tuple', [stripdata], **lineconfig)
        dtt = dttsel.algorithm()
        dtt.addBranches(line.branches)
        tuples.append(dtt)
        add_tools(dtt)
        seq = SelectionSequence(line.name + 'Seq', TopSelection=dttsel)
        DaVinci().UserAlgorithms += [seq.sequence()]
    #DaVinci(**line.davinci_config(stream))
    DaVinci().StrippingStream = streamname

    DaVinci().TupleFile = 'DaVinciTuples.root'
    if DaVinci().getProp('Simulation'):
        for dtt in tuples:
            add_mc_tools(dtt)
    else:
        DaVinci().Lumi = True

    return tuples
def test_remove_duplicates():

    sel000 = SelectionTree.sel000
    sel001 = SelectionTree.sel001
    sel002 = SelectionTree.sel002
    sel003 = SelectionTree.sel003

    sel100 = Selection('1.10000',
                       Algorithm=MockConfGenerator(),
                       RequiredSelections=[sel000, sel001, sel002])

    sel101 = Selection('1.10001',
                       Algorithm=MockConfGenerator(),
                       RequiredSelections=[sel001, sel002, sel003])

    sel200 = Selection('2.10000',
                       Algorithm=MockConfGenerator(),
                       RequiredSelections=[sel100, sel101])

    selSeq = SelectionSequence('Seq07', TopSelection=sel200)
    algs = selSeq.algorithms()
    alg_names = [a.name() for a in algs]

    assert len(algs) == 7
    assert alg_names.count('0.00000') == 1
    assert alg_names.count('0.00001') == 1
    assert alg_names.count('0.00002') == 1
    assert alg_names.count('0.00003') == 1
    assert alg_names.count('1.10000') == 1
    assert alg_names.count('1.10001') == 1
    assert alg_names.count('2.10000') == 1

    assert alg_names.index('0.00000') < alg_names.index('1.10000')
    assert alg_names.index('0.00001') < alg_names.index('1.10000')
    assert alg_names.index('0.00002') < alg_names.index('1.10000')
    assert alg_names.index('0.00001') < alg_names.index('1.10001')
    assert alg_names.index('0.00002') < alg_names.index('1.10001')
    assert alg_names.index('0.00003') < alg_names.index('1.10001')
    assert alg_names.index('1.10000') < alg_names.index('2.10000')
    assert alg_names.index('1.10001') < alg_names.index('2.10000')
def test_order_line():

    sel000 = Selection('0.0000',
                       Algorithm=MockConfGenerator(),
                       RequiredSelections=[])
    sel001 = Selection('0.0001',
                       Algorithm=MockConfGenerator(),
                       RequiredSelections=[sel000])
    sel101 = Selection('1.0000',
                       Algorithm=MockConfGenerator(),
                       RequiredSelections=[sel001])
    sel102 = Selection('1.0001',
                       Algorithm=MockConfGenerator(),
                       RequiredSelections=[sel101])
    sel203 = Selection('2.0000',
                       Algorithm=MockConfGenerator(),
                       RequiredSelections=[sel102])

    selSeq = SelectionSequence('Seq04', TopSelection=sel203)
    algs = selSeq.algorithms()
    assert [a.name() for a in algs
            ] == ['0.0000', '0.0001', '1.0000', '1.0001', '2.0000']
def test_sequencer_algos():
    _sel00 = AutomaticData(Location='Phys/Sel00')
    _sel01 = AutomaticData(Location='Phys/Sel01')
    _sel02 = AutomaticData(Location='Phys/Sel02')
    _sel03 = AutomaticData(Location='Phys/Sel03')

    sel01 = Selection('00100',
                      Algorithm=MockConfGenerator(),
                      RequiredSelections=[_sel00, _sel01])
    sel02 = Selection('00101',
                      Algorithm=MockConfGenerator(),
                      RequiredSelections=[_sel02, _sel03])
    sel03 = Selection('00102',
                      Algorithm=MockConfGenerator(),
                      RequiredSelections=[sel01, sel02])
    seq = SelectionSequence('Seq01', TopSelection=sel03)

    seqAlgos = seq.algorithms()

    assert len(seqAlgos) == 7
    for sel in [sel01, sel02, sel03]:
        assert sel.algorithm() in seqAlgos
Beispiel #15
0
def oneTosMonitor(name="None", input=None, calo=False):

    from PhysSelPython.Wrappers import Selection, SelectionSequence
    from Configurables import TisTosParticleTagger, ParticleMonitor, PrintDecayTree
    Tosser = TisTosParticleTagger(name + "Tosser")
    Tosser.TisTosSpecs = {name + "Decision%TOS": 0}
    Tosser.ProjectTracksToCalo = calo
    Tosser.CaloClustForCharged = calo

    s1 = Selection("TOSPresel" + name,
                   Algorithm=Tosser,
                   RequiredSelections=[input])

    tools = ["MomentumPlotTool"]
    if ('Muon' in name): tools += ["MuonPlotTool"]
    plotter = ParticleMonitor(name + "TosMoni", PlotTools=tools)
    # Make things a bit faster
    if ('L0Hadron' in name): plotter.MotherCut = "PT>1*GeV"
    else: plotter.MotherCut = "PT>0.5*GeV"
    s2 = Selection("TOSSel" + name, Algorithm=plotter, RequiredSelections=[s1])
    ss = SelectionSequence("TOSSeq" + name, TopSelection=s2)
    return ss.sequence()
Beispiel #16
0
    def select(self):
        """
        Get data and selection
        """

        from PhysSelPython.Wrappers import Selection, SelectionSequence, DataOnDemand, AutomaticData

        # from StandardParticles import StdLooseMuons, StdLooseKaons
        from Configurables import FilterDesktop, CombineParticles, OfflineVertexFitter, LoKi__HDRFilter
        from GaudiKernel.PhysicalConstants import c_light

        evtPreselectors = []

        if dataSample.isPrescaled != False:
            if dataSample.isPrescaled == True:
                dataSample.isPrescaled = 0.1
            prescaler = DeterministicPrescaler("Prescaler", AcceptFraction=dataSample.isPrescaled)
            evtPreselectors.append(prescaler)

        # # Stripping filter
        strippingFilter = LoKi__HDRFilter(
            "StripPassFilter",
            Code="HLT_PASS('Stripping" + self.lineName + "Decision')",
            Location="/Event/Strip/Phys/DecReports",
        )
        evtPreselectors.append(strippingFilter)

        stripped_data = AutomaticData(Location=self.lineLocation)

        # Trigger selection
        # from Configurables import TisTosParticleTagger
        # _tisTosFilter = TisTosParticleTagger( self.name + "Triggered" )
        # _tisTosFilter.TisTosSpecs = { 'L0Global%TUS' : 0,
        #                               'L0Global%TIS' : 0,
        #                               }
        # for trigger in trigger_list:
        #     for tistos in ['TIS', 'TUS']:
        #         _tisTosFilter.TisTosSpecs['{0}%{1}'.format(trigger, tistos)] = 0

        # triggered_data =  Selection( self.name+'TriggerSelection',
        #                              Algorithm = _tisTosFilter,
        #                              RequiredSelections = [ stripped_data ],
        #                              )

        Candidate_selection = stripped_data  # triggered_data

        self.sequence = SelectionSequence(
            "Seq" + self.name, TopSelection=Candidate_selection, EventPreSelector=evtPreselectors
        )
Beispiel #17
0
def makeSelectionSequenceSS(line, stream):

    location = "/Event/" + stream + "/Phys/" + line + "/Particles"

    strippingfilter = LoKi__HDRFilter('StripPassFilter',
                                      Code="HLT_PASS('Stripping" + line +
                                      "Decision')",
                                      Location="/Event/Strip/Phys/DecReports")

    BuSel = AutomaticData(Location=location)

    selBss2bukSS = Selection("selBss2bukSS" + line,
                             Algorithm=bss2bukSS,
                             RequiredSelections=[BuSel, selK])
    return SelectionSequence('seqBss2bukSS' + line, TopSelection=selBss2bukSS)
Beispiel #18
0
        "LoKi_nOThits": "CONTAINS('Raw/OT/Times')",
        "LoKi_nNeutrals": "CONTAINS('Rec/ProtoP/Neutrals')",
        "LoKi_nCharged": "CONTAINS('Rec/ProtoP/Charged')"
    }

    #HRC tool
    tool = tupalg.addTupleTool("TupleToolHerschel")

## for debugging:
from SelPy.graph import graph
for tup in tuples:
    graph(tup, format='png')

from PhysSelPython.Wrappers import SelectionSequence
#seq  = SelectionSequence ( 'LbKSSEQ' , tupLbKS )
#dv.UserAlgorithms += [ seq.sequence() ]
#seq  = SelectionSequence ( 'LbKstSEQ' , tupLbKst )
#dv.UserAlgorithms += [ seq.sequence() ]
#seq  = SelectionSequence ( 'LbKSJpsipKSEQ' , tupLbKS_jpsipk )
#dv.UserAlgorithms += [ seq.sequence() ]
#seq  = SelectionSequence ( 'LbKstJpsipKSEQ' , tupLbKst_jpsipk )
#dv.UserAlgorithms += [ seq.sequence() ]

from Configurables import HCRawBankDecoder
decoder = HCRawBankDecoder()
DaVinci().UserAlgorithms += [decoder]

for tup in tuples:
    seq = SelectionSequence(tup.name() + '_SEQ', tup)
    dv.UserAlgorithms += [seq.sequence()]
Beispiel #19
0
def parseConfiguration(
        tupleConfig,  # TupleConfig object describing sample
        tesFormat,  # Input TES with "<line>" placeholder
        mdstOutputFile,  # MicroDST output extension
        mdstOutputPrefix,  # MicroDST prefix for production
        varsByType,  # requested variables by type
        varsByName,  # requested variables by name
        eventVariables,  # event variables
        writeNullWeightCandidates=True,
        writeMuonPIDPlus=True,
        mdstInput=False,
        tupleOutput=True):
    cfg = tupleConfig
    reviveSequences = []  # mark sequences to unpack std particles
    swSequences = []  # mark sequences to apply sWeights
    filterSequences = []  # mark sequences to be written in tuples
    matchSequences = []  # mark sequences to be written in tuples
    tupleSequences = []  # mark tuple sequences
    dstSequences = []  # sequences writing (Micro)DST files

    triggerList = [
        "L0MuonDecision",
        "L0HadronDecision",
        "L0ElectronDecision",
        "Hlt1TrackMVADecision",
        "Hlt1TrackMuonDecision",
    ]

    for basicPart in ["Muons", "Pions", "Kaons", "Protons", "Electrons"]:
        location = "Phys/StdAllNoPIDs{s}/Particles".format(s=basicPart)
        reviveSequences += [
            SelectionSequence("fs_std" + basicPart,
                              TopSelection=DataOnDemand(location))
        ]

    for basicPart in [
            "DownPions", "DownKaons", "DownProtons", "DownElectrons"
    ]:
        location = "Phys/StdNoPIDs{s}/Particles".format(s=basicPart)
        reviveSequences += [
            SelectionSequence("fs_std" + basicPart,
                              TopSelection=DataOnDemand(location))
        ]

    location = "Phys/StdLooseDownMuons/Particles"
    reviveSequences += [
        SelectionSequence("fs_std" + "DownMuons",
                          TopSelection=DataOnDemand(location))
    ]

    for sample in cfg:
        ################################################################################
        ## Configure sWeighting                                                       ##
        ################################################################################
        for line in cfg[sample].InputLines:
            location = tesFormat.replace('<line>', line)
            protoLocation = location.replace('/Particles', '/Protos')

            #     swSequences+=[ProbNNcalib ("TurboProbNN" + line, protoLocation).sequence()]
            if cfg[sample].Calibration:
                swSequences += [
                    ApplySWeights(
                        "ApplySW" + sample,
                        InputTes=location,
                        sTableDir=cfg[sample].Calibration,
                        sTableName="sTableSignal",
                    )
                ]

################################################################################
## Creates filter sequences to fill nTuples                                   ##
################################################################################

        selectionName = sample
        _cut = "DECTREE ('{}')".format(cfg[sample].Decay.replace("^", ""))

        if writeNullWeightCandidates == False:
            _cut += " & ( WEIGHT != 0 ) "

        if cfg[sample].Filter:
            _cut += " & ({}) ".format(cfg[sample].Filter.cut)

        inputSelection = MergedSelection(
            "input" + selectionName,
            RequiredSelections=[
                DataOnDemand(tesFormat.replace('<line>', line))
                for line in cfg[sample].InputLines
            ],
        )

        selection = Selection(
            selectionName,
            RequiredSelections=[inputSelection],
            Algorithm=FilterDesktop("alg_" + selectionName, Code=_cut),
        )

        filterSequence = SelectionSequence("Seq" + selectionName,
                                           TopSelection=selection)

        filterSequences += [filterSequence]

        ################################################################################
        ## Creates matching selections (used to create the proper locations in mdst)  ##
        ################################################################################
        matchingSel = Selection("Match" + selectionName,
                                Algorithm=CopyAndMatchCombination(
                                    "MatchAlg" + selectionName,
                                    Downstream=cfg[sample].Downstream,
                                ),
                                RequiredSelections=[selection])

        matchingSeq = SelectionSequence("SeqMatch" + selectionName,
                                        TopSelection=matchingSel)

        matchSequences += [matchingSeq]

        partsInBranches = []

        for branchName in cfg[sample].Branches:

            partName = branchName
            if len(cfg[sample].Branches[branchName].isAlso) > 0:
                partName = cfg[sample].Branches[branchName].isAlso[0]

            partsInBranches += [partName]

        #print("partsInBranches = ", partsInBranches)

################################################################################
## Parses the configuration dictionaries and configure the tuples             ##
################################################################################
        tuple = DecayTreeTuple(sample + "Tuple")
        tuple.Inputs = [filterSequence.outputLocation()]
        tuple.Decay = cfg[sample].Decay
        tuple.ToolList = ["TupleToolANNPID"]
        if mdstInput:
            tuple.RootInTES = "/Event/Turbo"

        if "e" in partsInBranches:
            ttBrem = tuple.addTupleTool("TupleToolBremInfo")
            ttBrem.Particle = ["pi+", "p", "K+", "mu+", "e+"]
            ttBrem.Verbose = True
            ttBrem.RootInTES = ""  #### !!!!

        ttPPD = tuple.addTupleTool("TupleToolProtoPData")
        ttPPD.DataList = [
            "VeloCharge", "CaloEoverP", "CaloEcalChi2", "CaloPrsE",
            "CaloHcalE", "EcalPIDe", "PrsPIDe", "HcalPIDe", "CaloEcalE"
        ]

        if writeMuonPIDPlus and ("mu" in partsInBranches):
            muidPlus = tuple.addTupleTool("TupleToolMuonPidPlus")
            muidPlus.MuonIDPlusToolName = "MuonIDPlusTool"
            muidPlus.OutputLevel = 5
            muidPlus.RootInTES = ""  ####  !!!!!
            muidPlus.addTool(MuonIDPlusTool)
            muidPlus.MuonIDPlusTool.OutputLevel = 5
            muidPlus.MuonIDPlusTool.RootInTES = ""  ####  !!!!!
            muidPlus.MuonIDPlusTool.ReleaseObjectOwnership = False
            muidPlus.MuonIDPlusTool.MatchToolName = "MuonChi2MatchTool"
            muidPlus.Verbose = True

        eventTool = tuple.addTupleTool("LoKi::Hybrid::EvtTupleTool/LoKiEvent")
        if 'VOID' in eventVariables.keys():
            eventTool.VOID_Variables = eventVariables['VOID']

        if not mdstInput:
            if 'ODIN' in eventVariables.keys():
                eventTool.ODIN_Variables = eventVariables['ODIN']

        if 'HLT' in eventVariables.keys():
            eventTool.HLT_Variables = eventVariables['HLT']

        if 'L0DU' in eventVariables.keys():
            eventTool.L0DU_Variables = eventVariables['L0DU']

        eventTool.Preambulo = [
            "from LoKiTracks.decorators import *",
            "from LoKiCore.functions import *"
        ]
        tuple.addTool(eventTool)

        if mdstInput:
            matchingLocation = {
                "mu+": "/Event/PIDCALIB/Phys/Match" + sample + "/Particles",
                "pi+": "/Event/PIDCALIB/Phys/Match" + sample + "/Particles",
                "K+": "/Event/PIDCALIB/Phys/Match" + sample + "/Particles",
                "p+": "/Event/PIDCALIB/Phys/Match" + sample + "/Particles",
                "e+": "/Event/PIDCALIB/Phys/Match" + sample + "/Particles",
            }
        else:
            if cfg[sample].Downstream:
                matchingLocation = {
                    "mu+": "Phys/StdLooseDownMuons/Particles",
                    "pi+": "Phys/StdNoPIDsDownPions/Particles",
                    "K+": "Phys/StdNoPIDsDownKaons/Particles",
                    "p+": "Phys/StdNoPIDsDownProtons/Particles",
                    "e+": "Phys/StdNoPIDsDownElectrons/Particles",
                }
            else:
                matchingLocation = {
                    "mu+": "Phys/StdAllNoPIDsMuons/Particles",
                    "pi+": "Phys/StdAllNoPIDsPions/Particles",
                    "K+": "Phys/StdAllNoPIDsKaons/Particles",
                    "p+": "Phys/StdAllNoPIDsProtons/Particles",
                    "e+": "Phys/StdAllNoPIDsElectrons/Particles",
                }

        tupleSequences += [tuple]

        for branchName in cfg[sample].Branches:

            partName = branchName
            if len(cfg[sample].Branches[branchName].isAlso) > 0:
                partName = cfg[sample].Branches[branchName].isAlso[0]

            #print ("PartName = ", partName)

            b = tuple.addBranches(
                {branchName: cfg[sample].Branches[branchName].Particle})
            b = b[branchName]
            matcher = b.addTupleTool("TupleToolTwoParticleMatching/Matcher_" +
                                     branchName)
            matcher.ToolList = []
            matcher.Prefix = ""
            matcher.Suffix = "_Brunel"
            matcher.MatchLocations = matchingLocation

            lokitool = b.addTupleTool("LoKi::Hybrid::TupleTool/LoKi_" +
                                      branchName)
            vardict = copy(varsByType[cfg[sample].Branches[branchName].Type])
            pidcalibtool = b.addTupleTool("TupleToolPIDCalib/PIDCalibTool_" +
                                          branchName)
            pidcalibtool_matched = TTpid("PIDCalibTool_match_" + branchName)
            for partName in [branchName
                             ] + cfg[sample].Branches[branchName].isAlso:
                if partName in varsByName:
                    vardict.update(varsByName[partName])


#        if partName == 'e':
#          pidcalibtool.FillBremInfo = True
#          pidcalibtool_matched.FillBremInfo = True

            lokimatchedtool = LokiTool("LoKi_match_" + branchName)

            matcher.addTool(pidcalibtool_matched)
            matcher.ToolList += [
                "LoKi::Hybrid::TupleTool/LoKi_match_" + branchName,
                "TupleToolPIDCalib/PIDCalibTool_match_" + branchName
            ]

            from Configurables import TupleToolTISTOS
            tistostool = TupleToolTISTOS("TISTOSForTheOffline" + branchName)
            tistostool.FillL0 = True
            tistostool.FillHlt1 = True
            tistostool.FillHlt2 = False
            tistostool.Verbose = True  # 16/01/2020 for L0Calo
            tistostool.VerboseL0 = True
            tistostool.VerboseHlt1 = True
            tistostool.VerboseHlt2 = False
            tistostool.TriggerList = triggerList
            matcher.addTool(tistostool)
            matcher.ToolList += [
                "TupleToolTISTOS/TISTOSForTheOffline" + branchName
            ]

            # 16/01/2020 for L0Calo variables
            from Configurables import TupleToolL0Calo
            l0calotool = TupleToolL0Calo("L0CaloForTheOffline" + branchName)
            l0calotool.WhichCalo = "HCAL"
            l0calotool.TriggerClusterLocation = "Trig/L0/FullCalo"  # Added 29/01/2020 for "trigger" variables
            matcher.addTool(l0calotool)
            matcher.ToolList += [
                "TupleToolL0Calo/L0CaloForTheOffline" + branchName
            ]

            from Configurables import TupleToolBremInfo, TupleToolProtoPData, TupleToolANNPID, TupleToolMuonPidPlus

            if partName == "e":
                ttbi = TupleToolBremInfo("BremInfoForTheOffline" + branchName)
                ttbi.Particle = ["pi+", "p", "K+", "mu+", "e+"]
                ttbi.RootInTES = ""
                matcher.addTool(ttbi)
                matcher.ToolList += [
                    "TupleToolBremInfo/BremInfoForTheOffline" + branchName
                ]

            ttppd = TupleToolProtoPData("ProtoPDataForTheOffline" + branchName)
            ttppd.DataList = [
                "VeloCharge", "CaloEoverP", "CaloEcalChi2", "CaloPrsE",
                "CaloHcalE", "EcalPIDe", "PrsPIDe", "HcalPIDe", "CaloEcalE"
            ]
            matcher.addTool(ttppd)
            matcher.ToolList += [
                "TupleToolProtoPData/ProtoPDataForTheOffline" + branchName
            ]

            ttann = TupleToolANNPID("ANNPIDForTheOffline" + branchName)
            ttann.PIDTypes = [
                "Electron", "Muon", "Pion", "Kaon", "Proton", "Ghost",
                "Deuteron"
            ]
            #      ttann.PIDTypes = [ "Electron","Muon","Pion","Kaon","Proton","Ghost" ]
            ttann.ANNPIDTunes = [
                "MC12TuneV2", "MC12TuneV3", "MC12TuneV4", "MC15TuneV1",
                "MC15TuneDNNV1", "MC15TuneCatBoostV1", "MC15TuneFLAT4dV1"
            ]
            matcher.addTool(ttann)
            matcher.ToolList += [
                "TupleToolANNPID/ANNPIDForTheOffline" + branchName
            ]

            if writeMuonPIDPlus and partName == "mu":
                ttmuidPlus = TupleToolMuonPidPlus(
                    "TupleToolMuonPidPlusForTheOffline" + branchName)
                ttmuidPlus.MuonIDPlusToolName = "MuonIDPlusTool"
                ttmuidPlus.OutputLevel = 5
                ttmuidPlus.RootInTES = ""  ####  !!!!!
                ttmuidPlus.addTool(MuonIDPlusTool)
                ttmuidPlus.MuonIDPlusTool.OutputLevel = 5
                ttmuidPlus.MuonIDPlusTool.RootInTES = ""  ####  !!!!!
                ttmuidPlus.MuonIDPlusTool.ReleaseObjectOwnership = False
                ttmuidPlus.MuonIDPlusTool.MatchToolName = "MuonChi2MatchTool"
                ttmuidPlus.Verbose = True
                matcher.addTool(ttmuidPlus)
                matcher.ToolList += [
                    "TupleToolMuonPidPlus/TupleToolMuonPidPlusForTheOffline" +
                    branchName
                ]

            vardict.update(cfg[sample].Branches[branchName].LokiVariables)
            lokimatchedtool.Variables = vardict
            lokitool.Variables = vardict

            matcher.addTool(lokimatchedtool)

            # Additional variables for Greg/Phoebe's uBDT
            from Configurables import TupleToolANNPIDTrainingLight
            if hasattr(tuple, 'probe'):
                tuple.probe.addTool(TupleToolANNPIDTrainingLight,
                                    name='TupleToolANNPIDTrainingLight')
                tuple.probe.ToolList += [
                    'TupleToolANNPIDTrainingLight/TupleToolANNPIDTrainingLight'
                ]

    print "Input TES: "
    print "\n".join([f.outputLocation() for f in filterSequences])
    if mdstOutputFile:
        dstSequences += configureMicroDSTwriter(
            mdstOutputFile, mdstOutputPrefix, filterSequences + matchSequences)

    if mdstInput:
        return (reviveSequences + swSequences + filterSequences +
                matchSequences + tupleSequences)
    else:
        if tupleOutput:
            return (reviveSequences + swSequences + filterSequences +
                    matchSequences + dstSequences + tupleSequences)
        else:
            return (reviveSequences + filterSequences + matchSequences +
                    dstSequences)
}
d0_comb = "(AMAXDOCA('') < 0.2*mm) & (ADAMASS('D0') < 100*MeV)"
# We can split long selections across multiple lines
d0_mother = ('(VFASPF(VCHI2/VDOF)< 9)'
             '& (BPVDIRA > 0.9997)'
             "& (ADMASS('D0') < 70*MeV)")

d0 = CombineParticles('Combine_D0',
                      DecayDescriptor='([D0 -> pi- K+]CC)',
                      DaughtersCuts=d0_daughters,
                      CombinationCut=d0_comb,
                      MotherCut=d0_mother)

d0_sel = Selection('Sel_D0', Algorithm=d0, RequiredSelections=[Pions, Kaons])

dstar_daughters = {'pi+': '(TRCHI2DOF < 3) & (PT > 100*MeV)'}
dstar_comb = "(ADAMASS('D*(2010)+') < 400*MeV)"
dstar_mother = ("(abs(M-MAXTREE('D0'==ABSID,M)-145.42) < 10*MeV)"
                '& (VFASPF(VCHI2/VDOF)< 9)')
dstar_sel = SimpleSelection('Sel_Dstar',
                            ConfigurableGenerators.CombineParticles,
                            [d0_sel, Pions],
                            DecayDescriptor='[D*(2010)+ -> D0 pi+]cc',
                            DaughtersCuts=dstar_daughters,
                            CombinationCut=dstar_comb,
                            MotherCut=dstar_mother)

dstar_seq = SelectionSequence('Dstar_Seq', TopSelection=dstar_sel)

DaVinci().UserAlgorithms += [dstar_seq.sequence()]
DstConf().Turbo = True
TurboConf().PersistReco = True

pions = DataOnDemand('Phys/StdAllNoPIDsPions/Particles')
ks0 = CombineParticles('Ks0Topipi',
                        DecayDescriptors=['[KS0 -> pi+ pi+]cc'],
                        CombinationCut=("AM < 320*MeV"), #parent
                        MotherCut="ALL")
ks0_sel = Selection(
    'Sel_Ks0Topipi',
    Algorithm=ks0,
    RequiredSelections=[pions]
)
ks0_selseq = SelectionSequence(
    'SelSeq_Ks0Topipi',
    TopSelection=ks0_sel
)

dtt_ks0 = DecayTreeTuple('TupleKs0Topipi')
dtt_ks0.Inputs = ks0_selseq.outputLocations()
dtt_ks0.Decay = '[KS0 -> ^pi+ ^pi+]CC'
dtt_ks0.addBranches({
    'Ks0': '[KS0 -> pi+ pi+]CC',
    'pi1': '[KS0 -> ^pi+ pi+]CC',
    'pi2': '[KS0 -> pi+ ^pi+]CC'
})

DaVinci().UserAlgorithms = [ks0_selseq.sequence(), dtt_ks0]
DaVinci().DataType = '2016'
DaVinci().EvtMax = 1000
DaVinci().TupleFile = 'PersistRecoTuple_ks0_pipi.root'
def ConfigureDaVinci():
    config = Swimming()
    from Configurables import DaVinci
    from StrippingConf.Configuration import StrippingConf
    from Configurables import ProcStatusCheck
    from Configurables import EventNodeKiller, GaudiSequencer
    from PhysSelPython.Wrappers import (AutomaticData, SelectionSequence,
                                        MultiSelectionSequence)

    # Get the stripping line
    from StrippingSettings.Utils import lineBuilderConfiguration
    strippingFile = None
    if config.getProp('StrippingFile') != 'none':
        strippingFile = config.getProp('StrippingFile')
    else:
        strippingFile = config.getProp('StrippingLineGroup')
    myconfig = lineBuilderConfiguration(config.getProp('StrippingVersion'),
                                        config.getProp('StrippingLineGroup'))
    import StrippingArchive
    mylineconf = getattr(
        __import__(
            'StrippingArchive.' +
            config.getProp('StrippingVersion') + '.Stripping' + strippingFile,
            globals(), locals(), [myconfig["BUILDERTYPE"]], -1),
        myconfig["BUILDERTYPE"])
    mylinedict = myconfig["CONFIG"]
    substitutions = config.getProp('StrippingConfigSubstitutions')
    print "mylinedict before substitutions:", mylinedict
    print "stripping config substitutions:", substitutions
    mylinedict.update(substitutions)
    print "mylineconf:", mylineconf
    print "mylinedict after substitutions:", mylinedict

    from StrippingConf.StrippingStream import StrippingStream
    stream = StrippingStream(config.getProp('StrippingStream') + "Swimming")
    allLines = mylineconf(config.getProp('StrippingLineGroup'),
                          mylinedict).lines()
    lines = []
    #lineNames = [l.split('/')[-1] for l in config.getProp('StripCands').keys()]
    lineNames = config.getProp('StrippingLines')
    print "lineNames:", lineNames
    for l in allLines:
        for lineName in lineNames:
            if l.outputLocation().find(lineName) != -1:
                lines.append(l)
                print l.outputLocation()
    stream.appendLines(lines)

    # Define the stream
    filterBadEvents = ProcStatusCheck()
    sc = StrippingConf(Streams=[stream],
                       MaxCandidates=2000,
                       AcceptBadEvents=False,
                       BadEventSelection=filterBadEvents)

    # Define the node killer, and make sure to kill everything corresponding to
    # the stream which we want to swim
    outputs = []
    from Configurables import Swimming__PVReFitter as ReFitter
    for l in lines:
        for f in l.filterMembers():
            if hasattr(f, 'ReFitPVs') and f.ReFitPVs:
                if not config.getProp('RefitPVs'):
                    log.warning('RefitPVs is not set, but stripping line applies refitting. Refitted ' + \
                                'PVs will be used for turning-point lifetime calculations.')
                    config.setProp('RefitPVs', True)
                t = f.PVReFitters['']
                f.PVReFitters = {'': 'Swimming::PVReFitter/PVReFitter'}
                f.addTool(ReFitter, 'PVReFitter')
                f.PVReFitter.PVReFitter = t
            elif not hasattr(f, 'Output'):
                continue
            # Remove the last item so we get everything (Particle, relations,
            # decayVertices, etc...
            o = '/'.join(f.Output.split('/')[:-1])
            outputs.append(o)
    print "Outputs are", outputs
    mykiller = EventNodeKiller("killStripping")
    # Some default nodes which we will want to kill in all cases
    nodestokill = outputs + ['Strip', '/Event/Rec/Vertex/Primary']
    mykiller.Nodes = nodestokill
    deathstar = GaudiSequencer("killStrippingSeq")
    deathstar.Members = [mykiller]

    # Configure DaVinci
    DaVinci().InputType = config.getProp('InputType')
    DaVinci().DataType = config.getProp('DataType')
    DaVinci().Simulation = config.getProp('Simulation')
    DaVinci().DDDBtag = config.getProp('DDDBtag')
    DaVinci().CondDBtag = config.getProp('CondDBtag')
    try:
        DaVinci().Persistency = config.getProp('Persistency')
    except AttributeError:
        print "DaVinci doesn't have a Persistency attribute to set"

    # The sequence for the swimming has to be configured
    # by hand inserting the node killer before it
    DaVinci().appendToMainSequence([deathstar])
    DaVinci().appendToMainSequence([sc.sequence()])

    # Since the name of the output file is configured in two places in DaVinci,
    # do some splitting.
    splitName = config.getProp('OutputFile').split(os.path.extsep)
    seqName = ''
    prefix = ''
    if len(splitName) <= 2:
        seqName = splitName[0]
        print "Warning, an output filename in three parts was specified. This does not work well, " + \
              " so 'Swimming.' will be prefixed."
        prefix = 'Swimming'
    else:
        prefix = splitName[0]
        seqName = os.path.extsep.join(splitName[1:-1])

    dstWriter = None
    print config.getProp('OutputType')

    # Offline candidate selection sequences
    sequences = []
    offCands = config.getProp('OffCands').keys()
    for i, cands in enumerate(offCands):
        data = AutomaticData(Location=cands + "/Particles")
        offSeq = SelectionSequence("OfflineCandidates_%d" % i,
                                   TopSelection=data)
        sequences.append(offSeq)

    # selection sequence for offline candidates
    muCands = config.getProp('MuDSTCands')
    for i, cands in enumerate(muCands):
        # Add extra selections for additional MuDSTCands
        data = AutomaticData(Location=cands + "/Particles")
        seq = SelectionSequence("MuDSTCands_%d" % i, TopSelection=data)
        sequences.append(seq)

    selectionSeq = MultiSelectionSequence(seqName, Sequences=sequences)

    if config.getProp('OutputType') == 'MDST':
        pack = False
        isMC = config.getProp("Simulation")
        SwimmingConf = config.getProp('MicroDSTStreamConf')
        SwimmingElements = config.getProp('MicroDSTElements')
        if SwimmingConf == False:
            from DSTWriters.Configuration import stripMicroDSTStreamConf
            SwimmingConf = stripMicroDSTStreamConf(pack=pack, isMC=isMC)
        if len(SwimmingElements) == 0:
            from DSTWriters.Configuration import stripMicroDSTElements
            from DSTWriters.microdstelements import CloneSwimmingReports, CloneParticleTrees, CloneTPRelations
            mdstElements = stripMicroDSTElements(pack=pack, isMC=isMC)
            SwimmingElements = [CloneSwimmingReports()]
            for element in mdstElements:
                SwimmingElements += [element]
                if type(element) == CloneParticleTrees:
                    SwimmingElements += [CloneTPRelations("P2TPRelations")]

        streamConf = {'default': SwimmingConf}
        elementsConf = {'default': SwimmingElements}
        try:
            from DSTWriters.__dev__.Configuration import MicroDSTWriter
        except:
            from DSTWriters.Configuration import MicroDSTWriter
        dstWriter = MicroDSTWriter('MicroDST',
                                   StreamConf=streamConf,
                                   MicroDSTElements=elementsConf,
                                   WriteFSR=config.getProp('WriteFSR'),
                                   OutputFileSuffix=prefix,
                                   SelectionSequences=[selectionSeq])
    elif config.getProp('OutputType') == 'DST':
        try:
            from DSTWriters.__dev__.streamconf import OutputStreamConf
            from DSTWriters.__dev__.Configuration import SelDSTWriter
        except ImportError:
            from DSTWriters.streamconf import OutputStreamConf
            from DSTWriters.Configuration import SelDSTWriter

        streamConf = OutputStreamConf(streamType = InputCopyStream,
                                      fileExtension = '.dst',
                                      extraItems = [config.getProp('SwimmingPrefix') + '/Reports#1'] +\
                                      list(set([l + '/P2TPRelations#1' for l in config.getProp('OffCands').values()])))
        SelDSTWriterElements = {'default': []}
        SelDSTWriterConf = {'default': streamConf}
        dstWriter = SelDSTWriter('FullDST',
                                 StreamConf=SelDSTWriterConf,
                                 MicroDSTElements=SelDSTWriterElements,
                                 WriteFSR=config.getProp('WriteFSR'),
                                 OutputFileSuffix=prefix,
                                 SelectionSequences=[selectionSeq])

    DaVinci().appendToMainSequence([dstWriter.sequence()])
Beispiel #23
0
#Truth matching
matchpion = "(mcMatch('[^pi-]CC'))" 
#matchpion = "ALL" 

#######################################
# pions
_pions = DataOnDemand(Location='Phys/StdLoosePions')
_filter = FilterDesktop("filterPions", Code = matchpion)
_filter.Preambulo = [
    "from LoKiPhysMC.decorators import *" ,
    "from PartProp.Nodes import CC"    
    ]
_selPions = Selection("SelFilterPions",
                        Algorithm = _filter,
                        RequiredSelections = [_pions])
_seqPions = SelectionSequence("SeqFilterPions", TopSelection = _selPions)

#######################################
# pions
_pions2 = DataOnDemand(Location='Phys/SmrdLoosePions')
_filter2 = FilterDesktop("filterPions", Code = matchpion)
_filter2.Preambulo = [
    "from LoKiPhysMC.decorators import *" ,
    "from PartProp.Nodes import CC"    
    ]
_selPions2 = Selection("SelFilterPions2",
                        Algorithm = _filter2,
                        RequiredSelections = [_pions2])
_seqPions2 = SelectionSequence("SeqFilterPions2", TopSelection = _selPions2)

Beispiel #24
0
# Finish the selection
Phi2KK = Selection("SelPhi2KK",
                   Algorithm=_phi2kk,
                   RequiredSelections=[StdLooseKaons])

_bs2JpsiPhi = CombineParticles(
    "Bs2JpsiPhi",
    DecayDescriptor="B_s0 -> phi(1020) J/psi(1S)",
    CombinationCut="ADAMASS('B_s0')<2*GeV",
    MotherCut="(VFASPF(VCHI2/VDOF)<10) & (BPVIPCHI2()<100)")
Bs2JpsiPhi = Selection("SelBs2JpsiPhi",
                       Algorithm=_bs2JpsiPhi,
                       RequiredSelections=[Phi2KK, Jpsi2MuMu])

from PhysSelPython.Wrappers import SelectionSequence
SeqBs2JpsiPhi = SelectionSequence("SeqBs2JpsiPhi", TopSelection=Bs2JpsiPhi)

simulation = False

from DecayTreeTuple.Configuration import *
tuple = DecayTreeTuple()
tuple.Inputs = ["Phys/SelBs2JpsiPhi/Particles"]
tuple.Decay = "[B_s0 -> ^(J/psi(1S) -> ^mu+ ^mu-) ^(phi(1020) -> ^K+ ^K-)]CC"
tuple.ToolList = []
tuple.UseLabXSyntax = True
tuple.RevertToPositiveID = False

LoKi_All = tuple.addTupleTool("LoKi::Hybrid::TupleTool/LoKi_All")
LoKi_All.Variables = {
    "lokiP": "P",
    "lokiPT": "PT",
tau_selection = Selection('SelTau2PhiMu', Algorithm = recoTau, RequiredSelections = [ looseMuons, phi_selection ])

# Select D
recoD = CombineParticles("D2PhiPi")
recoD.DecayDescriptor = '[D- -> phi(1020) pi-]cc'
recoD.DaughtersCuts = { "pi-" : " ( PT > 300 * MeV )  & ( BPVIPCHI2 () >  9 ) & ( TRCHI2DOF < 3 )& (TRGHOSTPROB<0.3)" }
recoD.CombinationCut = "(ADAMASS('tau-')<150*MeV)"
recoD.MotherCut = "( VFASPF(VCHI2) < 10 ) &  ( (BPVLTIME () * c_light)   > 200 * micrometer ) &  ( BPVIPCHI2() < 100 ) "

D_selection = Selection('SelD2PhiPi', Algorithm = recoD, RequiredSelections = [ loosePions, phi_selection ])



tau_sequence = SelectionSequence('SeqTau2PhiMu',
                                 TopSelection = tau_selection,
                                 EventPreSelector = evtPreselectors)


D_sequence = SelectionSequence('SeqD2PhiPi',
                                 TopSelection = D_selection,
                                 EventPreSelector = evtPreselectors)                                 

# ## Per i dati forse funziona:

# tau_stripped = AutomaticData(Location = location)
## #prescaler =  DeterministicPrescaler("Prescaler", AcceptFraction = 1.0)
# tau_filter = FilterDesktop('tauFilter', Code = 'ALL')
# tau_selection = Selection('SelTau2PhiMu', Algorithm = tau_filter, RequiredSelections = [ tau_stripped ])
# tau_sequence = SelectionSequence('SeqTau2PhiMu',
#                                  TopSelection = tau_selection)
from PhysSelPython.Wrappers import SelectionSequence
from PhysSelPython.Wrappers import DataOnDemand

# Stream and stripping line we want to use
tesLoc = '/Event/{0}/Phys/{1}/Particles'.format(stream, line)
# get the selection(s) created by the stripping
strippingSels = [DataOnDemand(Location=tesLoc)]

# create a selection using the substitution algorithm
selSub = Selection(
    'KpforPip_sel',
    Algorithm=subs,
    RequiredSelections=strippingSels
)

selSeq = SelectionSequence('selSeq', TopSelection=selSub)


from Configurables import DecayTreeTuple
from DecayTreeTuple.Configuration import *
tuple=DecayTreeTuple("KpforPipTuple")
tuple.Decay="[B0 -> ^(K*(892)0 -> ^pi+ ^pi-) ^(eta_prime -> ^pi- ^pi+ ^gamma)]CC"
tuple.Branches={"B0":"[B0 -> (K*(892)0 -> pi+ pi-) (eta_prime -> pi- pi+ gamma)]CC"}
tuple.Inputs=[selSeq.outputLocation()]

tuple.ToolList += [
    "TupleToolGeometry"
    , "TupleToolDira"
    , "TupleToolAngles"
    , "TupleToolPid"
    , "TupleToolKinematic"
Beispiel #27
0
def configure(datafiles, catalogs=[], params={}, castor=False):
    """
    Configure the job
    """
    from Configurables           import DaVinci       ## needed for job configuration
    from Configurables           import EventSelector ## needed for job configuration
    
    from Configurables import MessageSvc
    msg = MessageSvc()
    msg.setError += [ 'HcalDet.Quality'   ,
                      'EcalDet.Quality'   ,
                      'MagneticFieldSvc'  ,
                      'PropertyConfigSvc' ]

    from PhysSelPython.Wrappers import AutomaticData
    jpsi_location = 'FullDSTDiMuonJpsi2MuMuDetachedLine'
    jpsi = AutomaticData(
        Location='/Event/AllStreams/Phys/%s/Particles' % jpsi_location)

    
    # =============================================================================
    from StrippingSelections.StrippingPsiXForBandQ import PsiX_BQ_Conf as PsiX

    ## 1) redefine stripping configurations
    def _psi_(self):
        """
        psi(') -> mu+ mu-
        """
        return jpsi

    PsiX.psi = _psi_

    logger.warning("Redefine PsiX .psi")

    ## 2) unify the pion& kaon  selections
    # =============================================================================
    _PionCut_ = """
    ( CLONEDIST   > 5000   ) &
    ( TRCHI2DOF   < 4      ) &
    ( TRGHOSTPROB < 0.4    ) &
    ( PT          > 200 * MeV               ) &
    in_range ( 2          , ETA , 4.9       ) &
    in_range ( 3.2 * GeV  , P   , 150 * GeV ) &
    HASRICH                  &
    ( PROBNNpi     > 0.15  ) &
    ( MIPCHI2DV()  > 9.    )
    """
    _KaonCut_ = """
    ( CLONEDIST   > 5000   ) &
    ( TRCHI2DOF   < 4      ) &
    ( TRGHOSTPROB < 0.4    ) &
    ( PT          > 200 * MeV               ) &
    in_range ( 2          , ETA , 4.9       ) &
    in_range ( 3.2 * GeV  , P   , 150 * GeV ) &
    HASRICH                  &
    ( PROBNNk      > 0.15  ) &
    ( MIPCHI2DV()  > 9.    )
    """

    from GaudiConfUtils.ConfigurableGenerators import FilterDesktop
    _alg_pi = FilterDesktop(
        ##
        Code=_PionCut_,
        ##
    )

    from PhysSelPython.Wrappers import Selection
    from StandardParticles import StdAllNoPIDsPions as input_pions
    pions = Selection(
        "SelPiForBQ",
        Algorithm=_alg_pi,
        RequiredSelections=[input_pions]
    )

    from GaudiConfUtils.ConfigurableGenerators import FilterDesktop
    _alg_k = FilterDesktop(
        ##
        Code=_KaonCut_,
        ##
    )

    from PhysSelPython.Wrappers import Selection
    from StandardParticles import StdAllNoPIDsKaons as input_kaons
    kaons = Selection(
        "SelKForBQ",
        Algorithm=_alg_k,
        RequiredSelections=[input_kaons]
    )

    def _kaons_(self):
        return kaons

    def _pions_(self):
        return pions

    #
    ## get the selections
    #

    for s in [PsiX]:
        s.pions = _pions_
        s.kaons = _kaons_

    logger.warning("Redefine PsiX.kaons          ")
    logger.warning("Redefine PsiX.kaons          ")

    psix = PsiX('PsiX', {})

    for s in [psix.psi_3Kpi()]:
        a = s.algorithm()
        a.ParticleCombiners = {'': 'LoKi::VertexFitter:PUBLIC'}

    from PhysSelPython.Wrappers import SelectionSequence
    sel_seq = SelectionSequence('B2Psi3Kpi', psix . psi_3Kpi())


    davinci = DaVinci(
        InputType     = 'DST'    ,
        Simulation    = True     ,
        PrintFreq     = 1000     ,
        EvtMax        = -1       , 
        Lumi          = True     ,
        DataType = params['Year'],
        DDDBtag = params['DDDB'],
        CondDBtag = params['SIMCOND'],
        # HistogramFile = 'DVHistos.root' ,
        TupleFile     = 'DVNtuples.root' ,
    )
    

    my_name = "Bplus"
    from Configurables import GaudiSequencer
    
    davinci.UserAlgorithms = [ sel_seq.sequence() , my_name ] 
    
    setData ( datafiles , catalogs , castor )
    
    gaudi = appMgr()

    print 'seq.outputLocation()= ', sel_seq.outputLocation()    # Phys/SelPsi3KPiForPsiX/Particles
    # create local algorithm:
    alg = MCAnalysisAlgorithm(
        my_name,
        Inputs = [
        sel_seq.outputLocation()
        ] ,
        PP2MCs = [ 'Relations/Rec/ProtoP/Charged' ]
    )

    return SUCCESS
]


makeBu= CombineParticles("makeBu",
                         Preambulo=preambulo,
                         DecayDescriptors = ['[B+ -> eta_prime pi+]cc'],
                         CombinationCut="(AM>3000.0) & (AM<10000.0) & (ACUTDOCA(0.04*mm,''))",
                         MotherCut ="(VFASPF(VCHI2/VDOF)<20.0)" 
                         )

Bu_sel = Selection("Bu_sel",
                   Algorithm= makeBu,
                   RequiredSelections=[etap_selection,pion_Sel]
                   )

Bu_selSeq = SelectionSequence("Bu_selSeq",TopSelection=Bu_sel)

from Configurables import PrintDecayTree

pt= PrintDecayTree(Inputs=[Bu_selSeq.outputLocation()])

from Configurables import SubstitutePID
SubKToPi = SubstitutePID (name = "SubKToPi",
                          Code = "DECTREE('[(B+ -> eta_prime pi+),(B- -> eta_prime pi-)]')",
                          Substitutions = {
                                  'B+ -> eta_prime ^pi+' : 'K+',
                                  'B- -> eta_prime ^pi-' : 'K-',
                          }
                          )
BuK_Sel=Selection("BuK_Sel",Algorithm=SubKToPi,RequiredSelections=[Bu_sel])
Beispiel #29
0
def configure(datafiles,
              catalogs=[],
              castor=False,
              params={}):
    """
    Job configuration 
    """

    ## needed for job configuration
    from Configurables import DaVinci

    the_year = "2011"

    from BenderTools.Parser import hasInFile

    if params:
        the_year = params['Year']
        logger.info('Year is set from params to be %s ' % the_year)
    else:
        if hasInFile(datafiles, 'Collision11'):
            the_year = '2011'
        elif hasInFile(datafiles, 'Collision12'):
            the_year = '2012'
        elif hasInFile(datafiles, 'Stripping17'):
            the_year = '2011'
        elif hasInFile(datafiles, 'Stripping13'):
            the_year = '2011'
        elif hasInFile(datafiles, 'Stripping15'):
            the_year = '2011'
        elif hasInFile(datafiles, 'Stripping19'):
            the_year = '2012'
        elif hasInFile(datafiles, 'Stripping20'):
            the_year = '2012'
        logger.info('Year is set from files  to be %s ' % the_year)

    #
    # check
    #
    if '2011' == the_year and hasInFile(datafiles, 'Collision12'):
        raise AttributeError, 'Invalid Year %s ' % the_year
    if '2012' == the_year and hasInFile(datafiles, 'Collision11'):
        raise AttributeError, 'Invalid Year %s ' % the_year

    logger.info('Use the Year = %s ' % the_year)

    #
    Jpsi_location = '/Event/Dimuon/Phys/FullDSTDiMuonJpsi2MuMuDetachedLine/Particles'
    #

    # Read only fired events to speed up
    from PhysConf.Filters import LoKi_Filters
    fltrs = LoKi_Filters(
        STRIP_Code="HLT_PASS_RE('Stripping.*DiMuonJpsi2MuMuDeta.*')",
        VOID_Code="""
        0.5 < CONTAINS('%s')
        """ % Jpsi_location
    )
    #
    # protection agains ``corrupted'' Stripping 17b DIMUON.DST
    fltrs_0 = LoKi_Filters(
        VOID_Code="""
        ( EXISTS ( '/Event/DAQ/RawEvent') | EXISTS('/Event/Trigger/RawEvent' ) ) 
        & EXISTS ( '/Event/Strip/Phys/DecReports') 
        """
    )

    davinci = DaVinci(
        EventPreFilters=fltrs_0.filters(
            'Filters0') + fltrs.filters('Filters'),
        DataType=the_year,
        InputType='DST',
        Simulation=False,
        PrintFreq=1000,
        EvtMax=-1,
        #
        HistogramFile='Bcc1_Histos.root',
        TupleFile='Bcc1.root',
        #
        Lumi=True,
        #
    )

    from Configurables import CondDB
    CondDB(LatestGlobalTagByDataType=the_year)

    # ------- decoding set-up start ----------
    ## from BenderTools.MicroDST import uDstConf
    ## uDstConf ( rootInTES )
    # ------- decoding set-up end  -----------

    #
    # dimuon locations in DIMUON.DST
    #
    from PhysSelPython.Wrappers import AutomaticData
    jpsi = AutomaticData(Location=Jpsi_location)
    #
    # get the prompt charm
    #
    from StrippingSelections.StrippingPromptCharm import StrippingPromptCharmConf as PC
    #
    # ======================================
    pc = PC('PromptCharm', {
        'TrackCuts'       : """
        ( TRCHI2DOF   < 4   ) &
        ( TRGHOSTPROB < 0.5 ) &           
        ( PT > 250 * MeV    ) &
        in_range  ( 2 , ETA , 5 ) 
        """ ,
        'KaonCuts': ' & in_range ( 3.2 * GeV , P , 100 * GeV ) & ( 2 < PIDK  - PIDpi ) ',
        'PionCuts': ' & in_range ( 3.2 * GeV , P , 100 * GeV ) & ( 0 < PIDpi - PIDK  ) ',
    }
    )

    pions = pc.pions()
    kaons = pc.kaons()

    Preambulo = [
        # shortcut for chi2 of vertex fit
        'chi2vx = VFASPF(VCHI2) ',
        # shortcut for the c*tau
        "from GaudiKernel.PhysicalConstants import c_light",
        # use the embedded cut for chi2(LifetimeFit)<9 !!!
        "ctau   = BPVLTIME ( 9 ) * c_light "  # ATTENTION, 9 is here!
    ]

    from GaudiConfUtils.ConfigurableGenerators import CombineParticles

    # ========================================================================
    # B -> J/psi + K pi pi
    # ========================================================================
    from GaudiConfUtils.ConfigurableGenerators import CombineParticles
    bc_Kpp = CombineParticles(
        DecayDescriptor='[B+ -> J/psi(1S) K+ pi+ pi-]cc',
        #
        Preambulo=Preambulo,
        DaughtersCuts={
            "J/psi(1S)": " in_range( 3.096 * GeV - 45 * MeV , M , 3.096 * GeV + 45 * MeV ) "
        },
        #
        CombinationCut="""
        in_range ( 5.0 * GeV , AM ,  5.6 * GeV ) 
        """ ,
        #
        MotherCut="""
        in_range  ( 5.1 * GeV , M , 5.5 * GeV ) &
        ( PT      > 1 * GeV          ) &
        ( chi2vx  <  49              ) &
        in_range ( 150 * micrometer , ctau , 1000 * micrometer ) 
        """ ,
        #
        ParticleCombiners={'': 'LoKi::VertexFitter'},
        ReFitPVs=True
    )
    #
    from PhysSelPython.Wrappers import Selection
    Bc_Kpp = Selection(
        'PsiKpp',
        Algorithm=bc_Kpp,
        RequiredSelections=[jpsi, pions, kaons]
    )

    # ========================================================================
    # B -> J/psi + K
    # ========================================================================
    from GaudiConfUtils.ConfigurableGenerators import CombineParticles
    bc_K = CombineParticles(
        DecayDescriptor='[ B+ -> J/psi(1S) K+ ]cc',
        #
        Preambulo=Preambulo,
        DaughtersCuts={
            "J/psi(1S)": " in_range( 3.096 * GeV - 45 * MeV , M , 3.096 * GeV + 45 * MeV ) "
        },
        #
        CombinationCut="""
        in_range ( 5.0 * GeV , AM ,  5.6 * GeV ) 
        """ ,
        #
        MotherCut="""
        in_range  ( 5.1 * GeV , M , 5.5 * GeV ) &
        ( PT      > 1 * GeV          ) &
        ( chi2vx  <  16              ) &
        in_range ( 150 * micrometer , ctau , 1000 * micrometer ) 
        """ ,
        ParticleCombiners={'': 'LoKi::VertexFitter'},
        ReFitPVs=True
    )
    #
    Bc_K = Selection(
        'PsiK',
        Algorithm=bc_K,
        RequiredSelections=[jpsi, kaons]
    )

    from PhysSelPython.Wrappers import SelectionSequence
    Seq_Kpp = SelectionSequence("PSIKPP", TopSelection=Bc_Kpp)
    Seq_K = SelectionSequence("PSIK", TopSelection=Bc_K)

    from Configurables import GaudiSequencer
    davinci.UserAlgorithms = [
        GaudiSequencer(
            'K', Members=[Seq_K  .sequence(), 'B2PsiK']),
        GaudiSequencer('KPP', Members=[Seq_Kpp.sequence(), 'B2PsiKpp'])
    ]

    #
    # come back to Bender
    #
    setData(datafiles, catalogs, castor)

    #
    # start Gaudi
    #
    gaudi = appMgr()

    #
    algKpp = B2Kpp(
        'B2PsiKpp',  # Algorithm name ,
        Inputs=[Seq_Kpp.outputLocation()]
    )
    algK = B2K(
        'B2PsiK',  # Algorithm name ,
        Inputs=[Seq_K  .outputLocation()]
    )

    return SUCCESS
def execute(simulation=True,
            turbo=True,
            decay_descriptor="J/psi(1S) -> mu- mu+"):
    # Configure all the unpacking, algorithms, tags and input files
    appConf = ApplicationMgr()
    appConf.ExtSvc+= ['ToolSvc', 'DataOnDemandSvc', LoKiSvc()]

    ConfigTarFileAccessSvc().File = 'config.tar'
    
    dv = DaVinci()
    dv.DataType = "2012"

    lhcbApp = LHCbApp()
    lhcbApp.Simulation = simulation
    CondDB().Upgrade = False
    
    dtt = DecayTreeTuple("Early2015")
    if turbo:
        tesla_prefix = "Hlt2DiMuonJPsi"
        dtt.Inputs = ["/Event/"+tesla_prefix+"/Particles"]
        dtt.InputPrimaryVertices = "/Event/"+tesla_prefix+"/Primary"
        dtt.WriteP2PVRelations = False

    else:
        LHCbApp().DDDBtag = "dddb-20140729"
        polarity = "u"
        LHCbApp().CondDBtag = "sim-20140730-vc-m%s100"%polarity
        muons = AutomaticData(Location="Phys/StdAllLooseMuons/Particles")

        jpsi = CombineParticles('MyJPsi')
        jpsi.DecayDescriptors = [decay_descriptor]
        jpsi.CombinationCut = "(AM < 7100.0 *GeV)"
        jpsi.DaughtersCuts = {"": "ALL", "mu+": "ALL", "mu-": "ALL"}
        jpsi.MotherCut = "(VFASPF(VCHI2/VDOF) < 999999.0)"
        
        code = """
('J/psi(1S)' == ID) &
in_range(2.990*GeV, M, 3.210*GeV) &
DECTREE('%s') &
CHILDCUT(1, HASMUON & ISMUON) &
CHILDCUT(2, HASMUON & ISMUON) &
(MINTREE('mu+' == ABSID, PT) > 700*MeV) &
(MAXTREE(ISBASIC & HASTRACK, TRCHI2DOF) < 5) &
(MINTREE(ISBASIC & HASTRACK, CLONEDIST) > 5000) &
(VFASPF(VPCHI2) > 0.5/100) &
(abs(BPV(VZ)) <  0.5*meter) &
(BPV(vrho2) < (10*mm)**2)
"""%(decay_descriptor)
        # similar to the HLT2 line
        code = """
(ADMASS('J/psi(1S)')< 120*MeV) &
DECTREE('%s') &
(PT>0*MeV) &
(MAXTREE('mu-'==ABSID,TRCHI2DOF) < 4) &
(MINTREE('mu-'==ABSID,PT)> 0*MeV) &
(VFASPF(VCHI2PDOF)< 25)
"""%(decay_descriptor)
        filter_jpsi = FilterDesktop("MyFilterJPsi",
                                    Code=code,
                                    Preambulo=["vrho2 = VX**2 + VY**2"],
                                    ReFitPVs=True,
                                    #IgnoreP2PVFromInputLocations=True,
                                    #WriteP2PVRelations=True
                                    )
        
        jpsi_sel = Selection("SelMyJPsi", Algorithm=jpsi, RequiredSelections=[muons])
        filter_jpsi_sel = Selection("SelFilterMyJPsi",
                                    Algorithm=filter_jpsi,
                                    RequiredSelections=[jpsi_sel])
        jpsi_seq = SelectionSequence("SeqMyJPsi", TopSelection=filter_jpsi_sel)
        dtt.Inputs = [jpsi_seq.outputLocation()]
    
    # Overwriting default list of TupleTools
    dtt.ToolList = ["TupleToolKinematic",
                    "TupleToolPid",
                    "TupleToolEventInfo",
                    "TupleToolMCBackgroundInfo",
                    "TupleToolMCTruth",
                    #"MCTupleToolHierarchy",
                    #"MCTupleToolPID",
                    "TupleToolGeometry",
                    "TupleToolTISTOS",
                    # with turbo this crashes
                    #"TupleToolTrackInfo",
                    "TupleToolTrigger",
                    ]
    tlist = ["L0HadronDecision", "L0MuonDecision",
             "L0DiMuonDecision", "L0ElectronDecision",
             "L0PhotonDecision",
             "Hlt1DiMuonHighMassDecision", "Hlt1DiMuonLowMassDecision",
             "Hlt1TrackMuonDecision", "Hlt1TrackAllL0Decision",
             "Hlt2DiMuonJPsiDecision", "Hlt2SingleMuonDecision",
             ]
    
    dtt.addTool(TupleToolTrigger, name="TupleToolTrigger")
    dtt.addTool(TupleToolTISTOS, name="TupleToolTISTOS")
    # Get trigger info
    dtt.TupleToolTrigger.Verbose = True
    dtt.TupleToolTrigger.TriggerList = tlist
    dtt.TupleToolTISTOS.Verbose = True
    dtt.TupleToolTISTOS.TriggerList = tlist

    from Configurables import TupleToolMCTruth, MCTupleToolHierarchy
    dtt.addTool(TupleToolMCBackgroundInfo,
                name="TupleToolMCBackgroundInfo")
    dtt.TupleToolMCBackgroundInfo.Verbose = True
    dtt.addTool(MCTupleToolHierarchy,
                name="MCTupleToolHierarchy")
    dtt.MCTupleToolHierarchy.Verbose = True
    dtt.addTool(TupleToolMCTruth,
                name="TupleToolMCTruth")
    dtt.TupleToolMCTruth.Verbose = True

    if turbo:
        assoc_seq = TeslaTruthUtils.associateSequence(tesla_prefix, False)
        ChargedPP2MC(tesla_prefix+"ProtoAssocPP").OutputLevel = 1
        
        assoc_seq.Members.insert(0, PatLHCbID2MCParticle())

        from Configurables import MuonCoord2MCParticleLink
        muon_coords = MuonCoord2MCParticleLink("TeslaMuonCoordLinker")
        assoc_seq.Members.insert(1, muon_coords)
    
        TrackAssociator("TeslaAssocTr").DecideUsingMuons = True
        
        relations = TeslaTruthUtils.getRelLoc(tesla_prefix)

    else:
        relations = "Relations/Rec/ProtoP/Charged"


    TeslaTruthUtils.makeTruth(dtt,
                              relations,
                              ["MCTupleToolKinematic",
                               "MCTupleToolHierarchy",
                               "MCTupleToolPID",
                               ]
                              )
    
    
    dtt.Decay = mark(2, mark(3, decay_descriptor)) #"J/psi(1S) -> ^mu- ^mu+"
    
    dtt.addBranches({"X": "^(%s)"%(decay_descriptor),
                     "muplus": mark(3, decay_descriptor),#"J/psi(1S) -> mu- ^mu+",
                     "muminus": mark(2, decay_descriptor),#"J/psi(1S) -> ^mu- mu+",
                     })
    
    x_preamble = ["DZ = VFASPF(VZ) - BPV(VZ)",
                  ]
    x_vars = {"ETA": "ETA",
              "Y": "Y",
              "PHI": "PHI",
              "VPCHI2": "VFASPF(VPCHI2)",
              "DELTAZ": "DZ",
              # DZ * M / PZ / c with c in units of mm/s
              # XXX should this be the PDG mass or measured mass?
              #"TZ": "DZ*M / PZ / 299792458000.0", #seconds
              "TZ": "DZ*3096.916 / PZ/299792458000.0*(10**12)", #ps
              "minpt": "MINTREE('mu+' == ABSID, PT)",
              "minclonedist": "MINTREE(ISBASIC & HASTRACK, CLONEDIST)",
              "maxtrchi2dof": "MAXTREE(ISBASIC & HASTRACK, TRCHI2DOF)",
              }
    muon_vars = {"ETA": "ETA",
                 "Y": "Y",
                 "PHI": "PHI",
                 "CHARGE": "Q",
                 "CLONEDIST": "CLONEDIST",
                 "TRCHI2DOF": "TRCHI2DOF",
                 }
    
    loki_X = dtt.X.addTupleTool("LoKi::Hybrid::TupleTool/LoKi_X")
    loki_X.Variables = x_vars
    loki_X.Preambulo = x_preamble
    
    loki_mup = dtt.muplus.addTupleTool("LoKi::Hybrid::TupleTool/LoKi_MuPlus")
    loki_mup.Variables = muon_vars
    #dtt.muplus.addTupleTool("TupleToolGeometry")
    
    loki_mum = dtt.muminus.addTupleTool("LoKi::Hybrid::TupleTool/LoKi_MuMinus")
    loki_mum.Variables = muon_vars
    #dtt.muminus.addTupleTool("TupleToolGeometry")
    
    dv.TupleFile = "DVNtuples.root"
    if turbo:
        dv.UserAlgorithms = [assoc_seq, dtt]

    else:
        assocpp = ChargedPP2MC("TimsChargedPP2MC")
        assocpp.OutputLevel = 1
        dv.UserAlgorithms = [jpsi_seq.sequence(), assocpp, dtt]
Beispiel #31
0
def configure(datafiles,
              catalogs=[],
              castor=False,
              params={}):
    """
    Job configuration 
    """

    ## needed for job configuration
    from Configurables import DaVinci

    the_year = "2011"

    from BenderTools.Parser import hasInFile

    if params:
        the_year = params['Year']
        logger.info('Year is set from params to be %s ' % the_year)
    else:
        if hasInFile(datafiles, 'Collision11'):
            the_year = '2011'
        elif hasInFile(datafiles, 'Collision12'):
            the_year = '2012'
        elif hasInFile(datafiles, 'Collision13'):
            the_year = '2013'
        elif hasInFile(datafiles, 'Stripping17'):
            the_year = '2011'
        elif hasInFile(datafiles, 'Stripping13'):
            the_year = '2011'
        elif hasInFile(datafiles, 'Stripping15'):
            the_year = '2011'
        elif hasInFile(datafiles, 'Stripping19'):
            the_year = '2012'
        elif hasInFile(datafiles, 'Stripping20r1'):
            the_year = '2011'
        elif hasInFile(datafiles, 'Stripping20r1p1'):
            the_year = '2011'
        elif hasInFile(datafiles, 'Stripping20r0p1'):
            the_year = '2012'
        elif hasInFile(datafiles, 'MC11'):
            the_year = '2011'
        logger.info('Year is set from files  to be %s ' % the_year)

    #
    # check
    #
    if '2011' == the_year and hasInFile(datafiles, 'Collision12'):
        raise AttributeError, 'Invalid Year %s ' % the_year
    if '2012' == the_year and hasInFile(datafiles, 'Collision11'):
        raise AttributeError, 'Invalid Year %s ' % the_year

    logger.info('Use the Year = %s ' % the_year)

    W_Location = '/Event/AllStreams/Phys/WMuLine/Particles'
    from PhysSelPython.Wrappers import AutomaticData
    W_Strip = AutomaticData(Location=W_Location)

    EW_preambulo = [
        "pion_cuts  = in_range ( 300 * MeV , PT , 10 * GeV ) & ( CLONEDIST > 5000 ) & ( TRCHI2DOF < 5 ) & ( TRGHOSTPROB < 0.5 ) & ( PERR2/P2 < 0.05**2 ) ",
        "ptCone_    =  SUMCONE (   0.25 , PT , '/Event/Phys/StdAllLoosePions/Particles'               )",
        "ptCone_2   =  SUMCONE (   0.25 , PT , '/Event/Phys/StdAllLoosePions/Particles'   , pion_cuts )",
        "etCone_    =  SUMCONE (   0.25 , PT , '/Event/Phys/StdLooseAllPhotons/Particles'             )",
        "ptCone     =    SINFO (  55001 , ptCone_  , True ) ",
        "ptCone2    =    SINFO (  55003 , ptCone_2 , True ) ",
        "etCone     =    SINFO (  55002 , etCone_  , True ) ",
    ]

    # ========================================================================
    # good W
    # ========================================================================
    from GaudiConfUtils.ConfigurableGenerators import FilterDesktop
    gW = FilterDesktop(
        Preambulo=EW_preambulo,
        Code="""
        in_range ( 15 * GeV , PT , 100 * GeV ) &
        ( -1e+10 * GeV < ptCone  ) &
        ( -1e+10 * GeV < ptCone2 ) &
        ( -1e+10 * GeV < etCone  ) 
        """
    )
    from PhysSelPython.Wrappers import Selection
    W_Data = Selection(
        'W',
        Algorithm=gW,
        RequiredSelections=[W_Strip]
    )

    from PhysSelPython.Wrappers import SelectionSequence
    seq = SelectionSequence("Wseq", TopSelection=W_Data)

    # counters
    from Configurables import LoKi__CounterAlg as CounterAlg
    cnt = CounterAlg(
        'CharmEWCounters',
        Location="Counters/CharmEW",
        Preambulo=[
            "from LoKiPhys.decorators import *",
            "from LoKiCore.functions  import *",
            "pion_cuts  = in_range ( 300 * MeV , PT , 120 * GeV ) & ( CLONEDIST > 5000 ) & ( TRCHI2DOF < 5 ) ",
            "gamma_cuts = in_range ( 300 * MeV , PT ,  10 * GeV )  ",
            "pions      = SOURCE ( '/Event/Phys/StdAllNoPIDsPions/Particles'  ,  pion_cuts ) ",
            "gammas     = SOURCE ( '/Event/Phys/StdLooseAllPhotons/Particles' , gamma_cuts ) ",
        ],
        Variables={
            "px_c": " pions  >> sum ( PX ) ",
            "py_c": " pions  >> sum ( PY ) ",
            "px_g": " gammas >> sum ( PX ) ",
            "py_g": " gammas >> sum ( PY ) ",
            "n_c": " pions  >> SIZE       ",
            "g_c": " gammas >> SIZE       ",
        }
    )
    from Configurables import DataOnDemandSvc
    dod = DataOnDemandSvc()
    dod.AlgMap['/Event/Counters/CharmEW'] = cnt

    # ========================================================================
    # prefilters for drastical speedup in the reading of input data
    # ========================================================================
    from PhysConf.Filters import LoKi_Filters
    fltrs = LoKi_Filters(
        STRIP_Code=" HLT_PASS_RE ( 'Stripping.*WMuLine.*Decision' ) "
    )

    davinci = DaVinci(
        EventPreFilters=fltrs.filters('Filters'),  # PREFILTERS
        DataType=the_year,
        InputType='DST',
        Simulation=True,
        PrintFreq=10000,
        EvtMax=-1,
        #
        HistogramFile='MCW_Histos.root',
        TupleFile='MCW.root',
        #
    )

    # connect to DaVinci
    from Configurables import GaudiSequencer
    davinci.UserAlgorithms = [
        GaudiSequencer('MySeq', Members=[seq.sequence(), 'MCW'])
    ]

    #
    # take care abotu DB-tags:
    #
    # try to get the tags from Rec/Header
    from BenderTools.GetDBtags import getDBTags
    tags = getDBTags(
        datafiles[0],
        castor
    )
    logger.info('Extract tags from DATA : %s' % tags)
    if tags.has_key('DDDB') and tags['DDDB']:
        davinci.DDDBtag = tags['DDDB']
        logger.info('Set DDDB    %s ' % davinci.DDDBtag)
    if tags.has_key('CONDDB') and tags['CONDDB']:
        davinci.CondDBtag = tags['CONDDB']
        logger.info('Set CONDDB  %s ' % davinci.CondDBtag)
    if tags.has_key('SIMCOND') and tags['SIMCOND']:
        davinci.CondDBtag = tags['SIMCOND']
        logger.info('Set SIMCOND %s ' % davinci.CondDBtag)

    #
    # remove excessive printout
    #
    from Configurables import MessageSvc
    msg = MessageSvc()
    msg.setError += ['HcalDet.Quality',
                     'EcalDet.Quality',
                     'MagneticFieldSvc',
                     'PropertyConfigSvc',
                     'ToolSvc.L0DUConfig',
                     'ToolSvc.L0CondDBProvider',
                     'L0MuonFromRaw',
                     'IntegrateBeamCrossing']

    #
    # come back to Bender
    #
    setData(datafiles, catalogs, castor)

    #
    # start Gaudi
    #
    gaudi = appMgr()

    #
    # more silence
    #
    _a = gaudi.tool('ToolSvc.L0DUConfig')
    _a.OutputLevel = 4

    alg = MCW(
        'MCW',
        Inputs=[seq.outputLocation()],
        PP2MCs=['Relations/Rec/ProtoP/Charged']
    )

    return SUCCESS
dz=DataOnDemand(turbo_loc.format(dz_line))
pions = DataOnDemand('Phys/StdAllNoPIDsPions/Particles')


dst = CombineParticles('DstToD0pi',
                        DecayDescriptors=['[D*(2010)+ -> D0 pi+]cc'],
                        CombinationCut=("AM - ACHILD(M,1) < 800*MeV"),
                        MotherCut="(VFASPF(VCHI2/VDOF) < 6)") 

dst_sel = Selection(
    'Sel_DstToD0pi',
    Algorithm=dst,
    RequiredSelections=[dz, pions]
)
dst_selseq = SelectionSequence(
    'SelSeq_DstToD0pi',
    TopSelection=dst_sel
)

dtt_dst = DecayTreeTuple('TupleDstToD0pi_D0ToKpi_PersistReco')
dtt_dst.addTupleTool('TupleToolTrackInfo')
dtt_dst.Inputs = dst_selseq.outputLocations()
dtt_dst.Decay = '[D*(2010)+ -> ^(D0 -> ^K- ^pi+) ^pi+]CC'
dtt_dst.addBranches({
    'Dst': '[D*(2010)+ -> (D0 -> K- pi+) pi+]CC',
    'Dst_pi': '[D*(2010)+ -> (D0 -> K- pi+) ^pi+]CC',
    'D0': '[D*(2010)+ -> ^(D0 -> K- pi+) pi+]CC',
    'D0_K': '[D*(2010)+ -> (D0 -> ^K- pi+) pi+]CC',
    'D0_pi': '[D*(2010)+ -> (D0 -> K- ^pi+) pi+]CC',
})

dstar_hybrid = dtt_dst.Dst.addTupleTool('LoKi::Hybrid::TupleTool/LoKi_Dstar')
_selDimuons= Selection( "_selDimuons", Algorithm = _filterDimuons, RequiredSelections = [bothstripping] )

from Configurables import SubstitutePID
subalg = SubstitutePID("_B2Jpsi_SubPID", Code="(DECTREE('B0 -> mu+ mu-'))",
                       Substitutions={'B0 -> mu+ mu-' : 'J/psi(1S)'}, MaxChi2PerDoF=-666)
subsel = Selection("subsel",Algorithm = subalg, RequiredSelections = [_selDimuons])

# Try and make B->J/psi K
_B = CombineParticles()
_B.DaughtersCuts = { "K+" : "(PT>500*MeV)&(MIPCHI2DV(PRIMARY) > 9)" }
_B.MotherCut = "(DMASS('B+')<5000*MeV) & (VFASPF(VCHI2)/VFASPF(VDOF)<5.0) & (BPVDIRA > 0.999)" #need to check these cuts
_B.DecayDescriptors = [ "[B+ -> J/psi(1S) K+]cc" ]


_BdecaySelection = Selection( "TurboB", Algorithm = _B, RequiredSelections = [subsel,kaons] )
SeqB = SelectionSequence('SeqB', TopSelection = _BdecaySelection)

# Here we just put the output candidates in an Tuple

tupleB = DecayTreeTuple("bae-muon-data")
tupleB.Inputs = [SeqB.outputLocation()]
tupleB.Decay = "[B+ -> ^K+ ^(J/psi(1S) -> ^mu+ ^mu-)]CC"


tupleB.ToolList =  [
      "TupleToolKinematic"
    , "TupleToolEventInfo"
    , "TupleToolRecoStats"
    ,    "TupleToolTrigger",
        "TupleToolPid",
        "TupleToolPrimaries",
Beispiel #34
0
#
from PhysSelPython.Wrappers import Selection, DataOnDemand
from PhysSelPython.Wrappers import MergedSelection
from PhysSelPython.Wrappers import SelectionSequence

muons = DataOnDemand('Phys/StdLooseMuons')
jPsiSel = Selection("jPsiSel", Algorithm=JPsi, RequiredSelections=[muons])
mumuSel = Selection("mumuSel", Algorithm=MuMu, RequiredSelections=[muons])
jPsiNBSel = Selection("jPsiNBSel",
                      Algorithm=jPsiNB,
                      RequiredSelections=[jPsiSel])
mumuNBSel = Selection("mumuNBSel",
                      Algorithm=mumuNB,
                      RequiredSelections=[mumuSel])

SelSeqJPsi = SelectionSequence("SeqJPsi", TopSelection=jPsiNBSel)
SelSeqMuMu = SelectionSequence("SeqMuMu", TopSelection=mumuNBSel)
SelSeqMuMuAll = SelectionSequence("SeqMuMuAll", TopSelection=mumuSel)

SeqJPsi = SelSeqJPsi.sequence()
SeqMuMu = SelSeqMuMu.sequence()
SeqMuMuAll = SelSeqMuMuAll.sequence()

########################################################################
#
# NTupling
#
from Configurables import DecayTreeTuple

tupleMuMu = DecayTreeTuple("tupleMuMu")
tupleMuMu.InputLocations = [SelSeqMuMu.outputLocation()]
d0 = CombineParticles('Combine_D0',
                      DecayDescriptor='[D0 -> pi- K+]cc',
                      DaughtersCuts=d0_daughters,
                      CombinationCut=d0_comb,
                      MotherCut=d0_mother)

d0_sel = Selection('Sel_D0',
                   Algorithm=d0,
                   RequiredSelections=[Pions, Kaons])

dstar_daughters = {'pi+': '(TRCHI2DOF < 3) & (PT > 100*MeV)'}
dstar_comb = "(ADAMASS('D*(2010)+') < 400*MeV)"
dstar_mother = (
    "(abs(M-MAXTREE('D0'==ABSID,M)-145.42) < 10*MeV)"
    '& (VFASPF(VCHI2/VDOF)< 9)'
)
dstar_sel = SimpleSelection(
    'Sel_Dstar',
    ConfigurableGenerators.CombineParticles,
    [d0_sel, Pions],
    DecayDescriptor='[D*(2010)+ -> D0 pi+]cc',
    DaughtersCuts=dstar_daughters,
    CombinationCut=dstar_comb,
    MotherCut=dstar_mother
)

dstar_seq = SelectionSequence('Dstar_Seq', TopSelection=dstar_sel)

DaVinci().UserAlgorithms += [dstar_seq.sequence()]
Beispiel #36
0
                              ReFitPVs        = True )



#---- Refit vertices with Jpsi mass constraint----------------
#_Lb2JpsipK.addTool( OfflineVertexFitter() )
#_Lb2JpsipK.VertexFitters.update( { "" : "OfflineVertexFitter"} )
#_Lb2JpsipK.OfflineVertexFitter.applyDauMassConstraint = True


Lb2JpsiS  = Selection( "Lb2JpsiS",
                      Algorithm          = _Lb2JpsiS ,
                      RequiredSelections = [ Jpsi2MuMu, S2L0g, FilterL ] )

### Gaudi sequence
SeqLb2JpsiS = SelectionSequence("SeqLb2JpsiS", TopSelection = Lb2JpsiS)
seq = SeqLb2JpsiS.sequence()

#--------------------------------------------------------------------------
# Configure DaVinci
#-------------------------------------------------------------------------
from Configurables import DaVinci

from Configurables import  OfflineVertexFitter

from Configurables import  DecayTreeTuple, MCDecayTreeTuple
importOptions("Xb2JpsiXTree.py")


tuple = DecayTreeTuple( "Lb2JpsiSTree" )
tuple.Inputs = [ SeqLb2JpsiS.outputLocation() ]
Beispiel #37
0
KsPiPi= CombineParticles("KsPiPi")
KsPiPi.DecayDescriptor =  "KS0 -> pi+ pi-"
KsPiPi.CombinationCut = "ADAMASS('KS0')<100*MeV"
KsPiPi.MotherCut = "(VFASPF(VCHI2/VDOF)<10)"
KsPiPi.DaughtersCuts = { "pi+" : "ALL",
                         "pi-" : "ALL" }
KsPiPi.MotherCut = "(M > 400) & (M < 600) & (BPVVDCHI2 > 100.) & (VFASPF(VCHI2/VDOF) < 10)"
from PhysSelPython.Wrappers import Selection
from StandardParticles import StdNoPIDsDownPions, StdLoosePions
LooseKsPiPi = Selection("SelLooseKsPiPi", 
                        Algorithm = KsPiPi, 
                        RequiredSelections = [StdNoPIDsDownPions ])
                        #RequiredSelections = [StdLoosePions])

from PhysSelPython.Wrappers import SelectionSequence
SeqKsPiPi = SelectionSequence('SeqKsPiPi', TopSelection = LooseKsPiPi)

KsPiPiTuple = DecayTreeTuple("KsPiPiTuple")

# input locations
KsPiPiTuple.Inputs = [ LooseKsPiPi.outputLocation() ]
# decay descriptors
KsPiPiTuple.Decay = "KS0 -> ^pi+ ^pi-"
# define the tools and configure them
KsPiPiTuple.ToolList = [
    "TupleToolKinematic"
    ,"TupleToolGeometry"
    ,"TupleToolPid"
    ,"TupleToolANNPID"
    #,"TupleToolTrackInfo"
    ,"TupleToolRecoStats"
Beispiel #38
0
from Configurables import DaVinci, FilterDesktop, DecayTreeTuple
from PhysSelPython.Wrappers import Selection, SelectionSequence, TupleSelection
import StandardParticles

alg = FilterDesktop('pions')
alg.Code = 'ALL'
sel = Selection('pions_sel',
                Algorithm=alg,
                RequiredSelections=[StandardParticles.StdAllNoPIDsPions])

tuplesel = TupleSelection('pions_tuple_sel',
                          Decay='[pi+]cc',
                          RequiredSelection=sel)

selseq = SelectionSequence('pions_seq', TopSelection=tuplesel)
DaVinci().UserAlgorithms.append(selseq.sequence())
DaVinci().TupleFile = 'DVTuples.root'
Beispiel #39
0
recPF.EcalBest = True
recPF.SprRecover = False
recPF.TrkLnErrMax = 10
recPF.TrkUpErrMax = 10
recPF.TrkDnErrMax = 10
recJB = HltJetBuilder('recJB')
recJB.JetEcPath = ''
recJB.Inputs = [recPF.Output]
recJB.Output = 'Phys/JB/Particles'
recJB.JetPtMin = JetPtMin

from commonSelections import *

from PhysSelPython.Wrappers import SelectionSequence

recSVs_seq = SelectionSequence('recSVs_Seq', TopSelection=recSVs)
recMus_seq = SelectionSequence('recMus_Seq', TopSelection=recMus)

Jpsi_seq = SelectionSequence('Jpsi_Seq', TopSelection=recJpsi)
D0_seq = SelectionSequence('D0_Seq', TopSelection=recD0)
Dp_seq = SelectionSequence('Dp_Seq', TopSelection=recDp)
Ds_seq = SelectionSequence('Ds_Seq', TopSelection=recDs)
Lc_seq = SelectionSequence('Lc_Seq', TopSelection=recLc)
D02K3pi_seq = SelectionSequence('D2K3pi0_Seq', TopSelection=recD02K3pi)

##########################

# Turbo/DaVinci configuration.
from Configurables import DstConf, TurboConf, DaVinci

DaVinci().Simulation = False
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
Beispiel #41
0
# #----Selection /\b -> J/psi /\-------------------
# _Lb2JpsiL = CombineParticles( "_Lb2JpsiL",
#                               DecayDescriptor = "[Lambda_b0 -> J/psi(1S) Lambda0]cc",
#                               CombinationCut = "AM < 6000. * MeV",
#                               
#                               ReFitPVs        = True )

# Lb2JpsiL  = Selection( "Lb2JpsiL",
#                       Algorithm          = _Lb2JpsiL ,
#                       RequiredSelections = [ Jpsi2MuMu, FilterL ] )

### Gaudi sequence
# SeqL2ppi = SelectionSequence("SeqL2ppi", TopSelection = L2ppi)
# seq = SeqL2ppi.sequence()
SeqFilterL = SelectionSequence("SeqFilterL", TopSelection = FilterL)
seq = SeqFilterL.sequence()

#--------------------------------------------------------------------------
# Configure DaVinci
#-------------------------------------------------------------------------
from Configurables import DaVinci

# DaVinci().appendToMainSequence( [sc.sequence() ] )   # Append the stripping selection sequence to DaVinci

from Configurables import  OfflineVertexFitter

from Configurables import  DecayTreeTuple, MCDecayTreeTuple
importOptions("Xb2JpsiXTreeMC.py")

Beispiel #42
0
from StandardParticles import StdLoosePions, StdLooseKsLL, StdLooseKsDD
from Configurables import FilterDesktop, CombineParticles
from DecayTreeTuple.Configuration import *
from GaudiKernel.SystemOfUnits import MeV, GeV, mrad, picosecond


location = "/Event/Charm/Phys/PhiToKSKS_JPsiToKsKsLine/Particles"

JPsiSel = DataOnDemand(Location=location)

jpsiFilter = FilterDesktop("jpsiFilter", Code="PT > 400")


JPsiFilterSel = Selection(name="jpsiFilterSel", Algorithm=jpsiFilter, RequiredSelections=[JPsiSel])

seq = SelectionSequence("Seq", TopSelection=JPsiFilterSel)


# This filter is used just to speed up the process, nothing happens if there
# # is no stripped candidates at that location.
# from PhysConf.Filters import LoKi_Filters
# fltrs = LoKi_Filters(
#   STRIP_Code = "HLT_PASS('StrippingPhiToKSKS_PhiToKsKsLineDecision')")


from Configurables import (
    FitDecayTrees,
    DecayTreeTuple,
    TupleToolDecayTreeFitter,
    TupleToolDecay,
    TupleToolTrigger,
Beispiel #43
0
def configure(datafiles, catalogs=[], params={}, castor=False):
    """
    Configure the job
    """
    from Configurables           import DaVinci       ## needed for job configuration

    ## get the builder
    from StrippingSelections.StrippingPsiXForBandQ  import PsiX_BQ_Conf as  PSIX

    ## for MC it is better to exclude PID/DLL/PROBNN cuts
    builder_configuration = {
        # 'PionCut'   : """
        # ( PT          > 200 * MeV ) &
        'PionCut'   : """
        ( CLONEDIST   > 5000      ) &
        """
        # ( TRGHOSTPROB < 0.5       ) &
        # ( TRCHI2DOF   < 4         ) &
        # in_range ( 2          , ETA , 5         ) &
        # in_range ( 3.2 * GeV  , P   , 150 * GeV ) &
        # HASRICH                     &
        # ( PROBNNpi     > 0.1      )
        #( MIPCHI2DV()  > 4        )
        ,
        # ( PT          > 200 * MeV ) &
        'KaonCut'   : """
        ( CLONEDIST   > 5000      ) &
        ( TRGHOSTPROB < 0.5       ) &
        ( TRCHI2DOF   < 4         ) &
        in_range ( 2          , ETA , 5         ) &
        in_range ( 3.2 * GeV  , P   , 150 * GeV ) &
        HASRICH                     &
        ( PROBNNk      > 0.1      )
        """
        # ( MIPCHI2DV()  > 4        )
    }


    def _kaons_     ( self ) :
        """
        Kaons for   B -> psi X lines
        """
        from GaudiConfUtils.ConfigurableGenerators import FilterDesktop
        ## from StandardParticles                     import StdAllLooseKaons as inpts
        from StandardParticles                     import StdNoPIDsKaons   as inpts
        ##
        return self.make_selection (
            'Kaon'                 ,
            FilterDesktop          ,
            [ inpts ]              ,
            Code = self['KaonCut'] ,
        )


    def _pions_    ( self ) :
        """
        Pions for   B -> psi X lines
        """
        from GaudiConfUtils.ConfigurableGenerators import FilterDesktop
        ## from StandardParticles                     import StdAllLoosePions as inpts
        from StandardParticles                     import StdNoPIDsPions   as inpts
        ##
        return self.make_selection (
            'Pion'                 ,
            FilterDesktop          ,
            [ inpts ]              ,
            Code = self['PionCut'] ,
        )

    jpsi_name = 'FullDSTDiMuonJpsi2MuMuDetachedLine'
    psi2_name = 'FullDSTDiMuonPsi2MuMuDetachedLine'

    from PhysSelPython.Wrappers import AutomaticData
    jpsi  = AutomaticData ( '/Event/AllStreams/Phys/%s/Particles' % jpsi_name )
    psi2s = AutomaticData ( '/Event/AllStreams/Phys/%s/Particles' % psi2_name )
    #
    ## merged selectoon for J/psi & psi'
    #
    from PhysSelPython.Wrappers import MergedSelection
    psis = MergedSelection (
        'SelDetachedPsisForBandQ' ,
        RequiredSelections = [ jpsi ]
    )

    def _psi_ ( self ) :
        """
        psi(') -> mu+ mu-
        """
        return psis


    PSIX.pions = _pions_
    PSIX.kaons = _kaons_
    PSIX.psi   = _psi_

    ## use builder
    builder = PSIX ( 'PsiX' , builder_configuration  )



    from PhysSelPython.Wrappers import SelectionSequence

    psi3k      = SelectionSequence ( 'Psi3K'       , builder.psi_3K   () )
    psi3kpi    = SelectionSequence ( 'Psi3Kpi'     , builder.psi_3Kpi () )

    from PhysConf.Filters import LoKi_Filters
    fltrs   = LoKi_Filters (
        STRIP_Code = """
            HLT_PASS_RE('Stripping.*FullDSTDiMuonJpsi2MuMuDetachedLine.*')
        """
    )

    davinci = DaVinci(
        EventPreFilters = fltrs.filters('WG'),
        InputType     = 'DST'    ,
        Simulation    = True     ,
        PrintFreq     = 1000     ,
        EvtMax        = -1       ,
        Lumi          = True     ,
        DataType = params['Year'],
        DDDBtag = params['DDDB'],
        CondDBtag = params['SIMCOND'],
        # HistogramFile = 'DVHistos.root' ,
        TupleFile     = 'output_kpipi.root' ,
    )

    from Configurables import GaudiSequencer
    # seq   = GaudiSequencer('SEQ1', Members=[psi3k.sequence()])
    seq   = GaudiSequencer('SEQ2', Members=[psi3kpi.sequence()])


    my_name = "Bplus"


    davinci.UserAlgorithms = [ my_name ]

    setData ( datafiles , catalogs , castor )

    gaudi = appMgr()

    from StandardParticles import StdAllNoPIDsPions, StdAllNoPIDsKaons

    # create local algorithm:
    alg = MCAnalysisAlgorithm(
        my_name,
        Inputs = [
            StdAllNoPIDsPions.outputLocation(),
            StdAllNoPIDsKaons.outputLocation(),
            '/Event/AllStreams/Phys/%s/Particles' % jpsi_name
        ] ,
        PP2MCs = [ 'Relations/Rec/ProtoP/Charged' ],
        ReFitPVs = True
    )

    return SUCCESS
Beispiel #44
0
    Substitutions={
        'Charm -> (D0 -> ^K- pi+) Meson': 'pi-',
        'Charm -> (D~0 -> ^K+ pi-) Meson': 'pi+',
        'Charm -> (D0 -> K- ^K+) Meson': 'pi+',
        'Charm -> (D~0 -> K+ ^K-) Meson': 'pi-'
    }
)

# create a selection using the substitution algorithm
selSub = Selection(
    'Dst2D0pi_D02pipi_Sel',
    Algorithm=subs,
    RequiredSelections=strippingSels
)
# in order to add the selection into the program make a sequence
selSeq = SelectionSequence('SelSeq', TopSelection=selSub)


# Create an ntuple to capture D*+ decays from the new selection
dtt = DecayTreeTuple('TupleDstToD0pi_D0Topipi')
dtt.Inputs = [selSeq.outputLocation()]
dtt.Decay = '[D*(2010)+ -> ^(D0 -> ^pi- ^pi+) ^pi+]CC'

# Configure DaVinci

# add our new selection and the tuple into the sequencer
seq = GaudiSequencer('MyTupleSeq')
seq.Members += [selSeq.sequence()]
seq.Members += [dtt]
DaVinci().appendToMainSequence([seq])
Beispiel #45
0
from GaudiKernel import SystemOfUnits as Units
##Type     = 'MC'
JetPtMin = 10 * Units.GeV




from StandardParticles import StdAllNoPIDsMuons as loosemuons
from PhysSelPython.Wrappers import SimpleSelection, MergedSelection, DataOnDemand, Selection
from GaudiConfUtils.ConfigurableGenerators import FilterDesktop, CombineParticles


from commonSelections import *

from PhysSelPython.Wrappers import SelectionSequence
Z_seq = SelectionSequence('Z_Seq', TopSelection=Zs)

# Create the generated jets.
from Configurables import McParticleFlow, McJetBuilder
genPF = McParticleFlow('genPF')
genPF.Inputs = [
    ['PID',        'ban',       '12,-12,14,-14,16,-16'],
    ['PID',        'particle',  '321,211,130,3222,310,3122,3112,3312,3322,'
     '-321,-211,-130,-3222,-310,-3122,-3112,-3312,-3322'],
    ['MCParticle', 'daughters', 'MC/Particles']
    ]
genPF.Output = 'Phys/PF/MCParticles'
genJB = McJetBuilder('genJB')
genJB.JetPtMin = JetPtMin
genJB.JetR = 0.5
genJB.ChrVrt = True
                            Code = " DECTREE('[(B+ -> eta_prime pi+),(B- -> eta_prime pi-) ]') " , 
                            Substitutions = { 
                                'B+ -> eta_prime  ^pi+'  : 'K+', 
                                'B- -> eta_prime  ^pi-'  : 'K-',
                            }
)
                         

B2EtapKSel = Selection("B2EtapKSel", Algorithm = SubKToPi, RequiredSelections = [B2etap_piSub])

#B2EtapKSeq = SelectionSequence("B2EtapKSeq", TopSelection = B2EtapKSel)

#Code="(M>4800 *MeV) & (M<5700 *MeV) & (VFASPF(VCHI2/VDOF)<9.) & (PT> 1500.*MeV)"
B2EtapKFil= FilterDesktop("B2EtapKFil",  Code="(M>4800 *MeV) & (M<5700 *MeV) & (VFASPF(VCHI2/VDOF)<9.)")# & (PT> 1500.*MeV)") 
B2EtapKFil_Sel= Selection('B2EtapKFil_Sel', Algorithm=B2EtapKFil, RequiredSelections=[B2EtapKSel])
B2EtapKFil_Seq = SelectionSequence("B2etap_pi_FilSeq", TopSelection =B2EtapKFil_Sel) 




# Fill Tuple
from Configurables import DecayTreeTuple

tuple = DecayTreeTuple("B2_ETAPK")

 
tuple.ToolList += [
       "TupleToolGeometry",
       "TupleToolPhotonInfo",
       "TupleToolPid",
       "TupleToolMCTruth",
Beispiel #47
0
    tup.B0.addTool( LoKi_B0 )
    tup.B0.ToolList += ["LoKi::Hybrid::TupleTool/LoKi_B0"]
    tup.Jpsi.addTool( LoKi_Jpsi )
    tup.Jpsi.ToolList += ["LoKi::Hybrid::TupleTool/LoKi_Jpsi"]
    tup.muplus.addTool( LoKi_Mu )
    tup.muplus.ToolList += ["LoKi::Hybrid::TupleTool/LoKi_Mu"]
    tup.muminus.addTool( LoKi_Mu )
    tup.muminus.ToolList += ["LoKi::Hybrid::TupleTool/LoKi_Mu"]
    for particle in [ tup.B0 ]:
        particle.addTool(TISTOSTool, name = "TISTOSTool")
        particle.ToolList += [ "TupleToolTISTOS/TISTOSTool" ]



from PhysSelPython.Wrappers import SelectionSequence
rd_SEQ = SelectionSequence  ( 'DATA'  , rd_selection )


###################### DAVINCI SETTINGS ############################################

lum = True
sim = False

if MODE == 'MC':
    lum = False
    sim = True

daVinci = DaVinci (
      EvtMax             = EVTMAX
    , RootInTES          = rootInTES
    , InputType          = "MDST"
Beispiel #48
0
CondDB().LatestGlobalTagByDataType = DataYear 
#CondDB(UseOracle = True, IgnoreHeartBeat = True)

############################################
#from Configurables import *
from Configurables import LHCbApp
LHCbApp().XMLSummary='summary.xml'

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

if myDecayType and IsMC:
    BsPhiRho_Sequence = GaudiSequencer("BsPhiRho_Sequence")
    SeqBsPhiRho = SelectionSequence("SeqBsPhiRho", TopSelection = selSeq)
    BsPhiRho_Sequence.Members += [SeqBsPhiRho.sequence()]
    BsPhiRho_Sequence.Members += [smear]
    BsPhiRho_Sequence.Members += [tuple]
    userAlgos.append(BsPhiRho_Sequence)
elif not myDecayType and IsMC:
    userAlgos.append( smear )
    userAlgos.append( tuple )
elif not IsMC:
    MySequencer.Members += [scaler]
    MySequencer.Members += [tuple]
    userAlgos.append(MySequencer)

from Configurables import EventTuple
etuple = EventTuple()
userAlgos.append( HltSelReportsDecoder() )
def configure ( datafiles , catalogs = [] , castor = False ) :
    """
    Job configuration
    """

    from Configurables           import DaVinci       ## needed for job configuration
    from Configurables           import EventSelector ## needed for job configuration
    
    from Configurables import MessageSvc
    msg = MessageSvc()
    msg.setError += [ 'HcalDet.Quality'   ,
                      'EcalDet.Quality'   ,
                      'MagneticFieldSvc'  ,
                      'PropertyConfigSvc' ]


##     # =========================================================================
##     ## 0) Rerun stripping if MC is nt MC/2011 or MC/2012 
##     # =========================================================================
##     if   '2012' == the_year : 
##         import StrippingArchive.Stripping20.StrippingDiMuonNew              as DiMuon 
##         import StrippingSettings.Stripping20.LineConfigDictionaries_BandQ   as LineSettings
##     elif '2011' == the_year :
##         import StrippingArchive.Stripping20r1.StrippingDiMuonNew            as DiMuon 
##         import StrippingSettings.Stripping20r1.LineConfigDictionaries_BandQ as LineSettings

##     config  = LineSettings.FullDSTDiMuon['CONFIG']
##     name    = 'FullDST'
##     builder = DiMuon.DiMuonConf ( name , config )

##     ## selection
##     jpsi  = builder.SelJpsi2MuMuDetached


    # =========================================================================
    ## 0) Otherwise use existing stripping ilne 
    # =========================================================================
    
    from PhysSelPython.Wrappers import AutomaticData
    jpsi_location = 'FullDSTDiMuonJpsi2MuMuDetachedLine'
    jpsi = AutomaticData ( Location = '/Event/AllStreams/Phys/%s/Particles' % jpsi_location )

    
    # =============================================================================
    from StrippingSelections.StrippingPsiXForBandQ import PsiX_BQ_Conf    as PsiX
    
    # =============================================================================
    ## 1) redefine stripping configurations 
    # ============================================================================= 
    
    #
    ## redefine psi(') -> mu+ mu-
    # 
    def _psi_ ( self ) :
        """
        psi(') -> mu+ mu- 
        """
        return jpsi
    
    PsiX  . psi = _psi_
    
    logger.warning ( "Redefine PsiX .psi" )
    
    # =============================================================================
    ## 2) unify the pion& kaon  selections 
    # =============================================================================
    _PionCut_  = """
    ( CLONEDIST   > 5000   ) & 
    ( TRCHI2DOF   < 4      ) &
    ( TRGHOSTPROB < 0.4    ) &
    ( PT          > 200 * MeV               ) & 
    in_range ( 2          , ETA , 4.9       ) &
    in_range ( 3.2 * GeV  , P   , 150 * GeV ) &
    HASRICH                  &
    ( PROBNNpi     > 0.15  ) &
    ( MIPCHI2DV()  > 9.    )
    """
    _KaonCut_  = """
    ( CLONEDIST   > 5000   ) & 
    ( TRCHI2DOF   < 4      ) & 
    ( TRGHOSTPROB < 0.4    ) & 
    ( PT          > 200 * MeV               ) & 
    in_range ( 2          , ETA , 4.9       ) &
    in_range ( 3.2 * GeV  , P   , 150 * GeV ) &
    HASRICH                  &
    ( PROBNNk      > 0.15  ) &
    ( MIPCHI2DV()  > 9.    ) 
    """ 
    
    from GaudiConfUtils.ConfigurableGenerators import FilterDesktop
    _alg_pi  = FilterDesktop (
        ##
        Code = _PionCut_ ,
        ##
        )
    
    from PhysSelPython.Wrappers  import Selection
    from StandardParticles       import StdAllNoPIDsPions as input_pions 
    pions  = Selection (
        "SelPiForBQ"                       ,
        Algorithm          =  _alg_pi      ,
        RequiredSelections = [ input_pions ]  
        )
    
    from GaudiConfUtils.ConfigurableGenerators import FilterDesktop
    _alg_k  = FilterDesktop (
        ##
        Code = _KaonCut_ ,
        ##
        )
    
    from PhysSelPython.Wrappers  import Selection
    from StandardParticles       import StdAllNoPIDsKaons as input_kaons 
    kaons  = Selection (
        "SelKForBQ"      ,
        Algorithm          =   _alg_k      ,
        RequiredSelections = [ input_kaons ]  
        )
    
    
    def _kaons_   ( self ) : return kaons 
    def _pions_   ( self ) : return pions 
    
    #
    ## get the selections 
    #
    
    for s in [ PsiX ]  :
        s.pions   = _pions_
        s.kaons   = _kaons_
        
    logger.warning ( "Redefine PsiX.kaons          " )
    logger.warning ( "Redefine PsiX.kaons          " )

        
    psix   = PsiX   ( 'PsiX'  , {} )


    for s in [ psix.psi_pi() ] :
        
        a = s.algorithm ()
        a.ParticleCombiners = { '' : 'LoKi::VertexFitter:PUBLIC' } 
        
        
    from PhysSelPython.Wrappers import      SelectionSequence    
    sel_seq = SelectionSequence ( 'B2PsiPi'   , psix . psi_pi   () )
    

    the_year = '2012'
    davinci = DaVinci (
        DataType      = the_year ,
        InputType     = 'DST'    ,
        Simulation    = True     ,
        PrintFreq     = 1000     ,
        EvtMax        = -1       , 
        HistogramFile = 'DVHistos.root' ,
        TupleFile     = 'DVNtuples.root' ,
        Lumi          = True ,
        ##
        # MC : 
        ## SIMCOND : 'Sim08-20130503-1', 'Sim08-20130503-1-vc-md100'
        #
        DDDBtag   = "Sim08-20130503-1"         ,
        CondDBtag = "Sim08-20130503-1-vc-md100"    
        )
    
    
    my_name = "Bplus"
    from Configurables import GaudiSequencer
    
    davinci.UserAlgorithms = [ sel_seq.sequence() , my_name ] 
    
    setData ( datafiles , catalogs , castor )
    
    gaudi = appMgr()
    
    print 'seq.outputLocation()= ', sel_seq.outputLocation()    # Phys/SelPsi3KPiForPsiX/Particles
    alg = Jpsi_mu(
        my_name               ,   ## Algorithm name
        Inputs = [
        sel_seq.outputLocation()
        ] ,
        PP2MCs = [ 'Relations/Rec/ProtoP/Charged' ]
        )

    return SUCCESS 
Beispiel #50
0
def configure(
        inputdata,  ## the list of input files  
        catalogs=[],  ## xml-catalogs (filled by GRID)
        castor=False,  ## use the direct access to castor/EOS ? 
        params={}):

    ## import DaVinci
    from Configurables import DaVinci

    decay = '[(D0 =>  K-  mu+ nu_mu) && ~(D0 --> K- (pi0|eta) mu+ nu_mu ... )]CC'
    decay_K = '[(D0 => ^K-  mu+ nu_mu) && ~(D0 --> K- (pi0|eta) mu+ nu_mu ... )]CC'
    decay_mu = '[(D0 =>  K- ^mu+ nu_mu) && ~(D0 --> K- (pi0|eta) mu+ nu_mu ... )]CC'

    from PhysConf.Filters import LoKi_Filters
    fltrs = LoKi_Filters(MC_Code="has ( MCDECTREE('%s') )" % decay,
                         MC_Preambulo=["from LoKiCore.functions import has"])

    ## delegate the actual configuration to DaVinci
    dv = DaVinci(DataType='2012',
                 EventPreFilters=fltrs.filters('MC-filter'),
                 InputType='DST',
                 Simulation=True,
                 TupleFile='Xuhao.root',
                 DDDBtag='Sim08-20130503-1',
                 CondDBtag='Sim08-20130503-1-vc-md100')

    ##
    ## reconstruct D0 -> K mu candidates
    ##
    from StandardParticles import StdAllLooseKaons as kaons
    from StandardParticles import StdAllLooseMuons as muons

    from PhysSelPython.Wrappers import SimpleSelection
    from GaudiConfUtils.ConfigurableGenerators import FilterDesktop
    #
    true_kaons = SimpleSelection(
        'MCTrueKaon',  ## selection name 
        FilterDesktop,  ## algorithm type
        [kaons],  ## input/required selection
        ## algorithm propperties
        Preambulo=["from LoKiPhysMC.decorators import *"],
        Code="mcMatch ('%s', 2 )" % decay_K)
    #
    true_muons = SimpleSelection(
        'MCTrueMuon',  ## selection name 
        FilterDesktop,  ## algorithm type
        [muons],  ## input/required selection
        ## algorithm propperties
        Preambulo=["from LoKiPhysMC.decorators import *"],
        Code="mcMatch ('%s', 2 )" % decay_mu)

    from GaudiConfUtils.ConfigurableGenerators import CombineParticles
    sel_D0 = SimpleSelection(
        'SelD0',  ## name 
        CombineParticles,  ## algorithm type 
        [true_muons, true_kaons],  ## input/required selections 
        ## the decays to be reconstructed
        DecayDescriptor='[D0 -> K- mu+]cc',
        ## combination cut : mass window
        CombinationCut="""
        in_range ( 1 *  GeV ,  AM , 2 * GeV )
        """,
        ##      mother cut : require good vertex & some separation
        MotherCut="""
        ( VFASPF( VCHI2 ) <  10 ) &
        ( BPVVDCHI2       >   9 )  
        """,
    )

    from PhysSelPython.Wrappers import SelectionSequence
    SEQ_D0 = SelectionSequence('TRUED0', sel_D0)

    alg1_name = 'Lines'
    ## add the name of Bender algorithm into User sequence sequence
    from Configurables import GaudiSequencer
    seq_lines = GaudiSequencer('SEQ_lines',
                               Members=[SEQ_D0.sequence(), alg1_name])

    alg2_name = 'TisTosAlg'
    ## add the name of Bender algorithm into User sequence sequence
    from Configurables import GaudiSequencer
    seq_tistos = GaudiSequencer('SEQ_tistos',
                                Members=[SEQ_D0.sequence(), alg2_name])

    dv.UserAlgorithms = [seq_lines, seq_tistos]

    ## define the input data
    setData(inputdata, catalogs, castor)

    from BenderTools.Utils import silence, totalSilence
    silence()
    totalSilence()

    ## get/create application manager
    gaudi = appMgr()

    alg1 = Lines(alg1_name, Inputs=[SEQ_D0.outputLocation()])
    alg2 = Tistos(alg2_name, Inputs=[SEQ_D0.outputLocation()])

    return SUCCESS
Beispiel #51
0
class strippingLine:
    """
    Class to store information about stripping line that I will need to make nTuple
    """
    def __init__(self,name, lineName, dec, branches):
        self.name = name
        self.lineName = lineName
        self.dec = dec 
        self.branches = branches 
        self.lineLocation = "Phys/"+lineName+"/Particles"
        
         
    def select(self):
        """
        Get data and selection
        """

        from PhysSelPython.Wrappers import Selection, SelectionSequence, DataOnDemand, AutomaticData
        # from StandardParticles import StdLooseMuons, StdLooseKaons
        from Configurables import FilterDesktop, CombineParticles, OfflineVertexFitter, LoKi__HDRFilter 
        from GaudiKernel.PhysicalConstants import c_light

        evtPreselectors = []

        if dataSample.isPrescaled != False:
            if dataSample.isPrescaled == True:
                dataSample.isPrescaled = 0.1
            prescaler =  DeterministicPrescaler("Prescaler", AcceptFraction = dataSample.isPrescaled)
            evtPreselectors.append(prescaler)


        # # Stripping filter
        strippingFilter = LoKi__HDRFilter( 'StripPassFilter', Code="HLT_PASS('Stripping"+self.lineName+"Decision')", Location="/Event/Strip/Phys/DecReports" )
        evtPreselectors.append(strippingFilter)


        stripped_data = AutomaticData(Location = self.lineLocation)
        
        # Trigger selection
        from Configurables import TisTosParticleTagger
        _tisTosFilter = TisTosParticleTagger( self.name + "Triggered" )
        _tisTosFilter.TisTosSpecs = { 'L0Global%TUS' : 0,
                                      'L0Global%TIS' : 0,
                                      }
        for trigger in trigger_list:
            for tistos in ['TIS', 'TUS']:
                _tisTosFilter.TisTosSpecs['{0}%{1}'.format(trigger, tistos)] = 0
        
        triggered_data =  Selection( self.name+'TriggerSelection',
                                     Algorithm = _tisTosFilter,
                                     RequiredSelections = [ stripped_data ],
                                     )
        
        Candidate_selection = stripped_data #triggered_data 
        
        self.sequence = SelectionSequence('Seq'+self.name,
                                          TopSelection = Candidate_selection,
                                          EventPreSelector = evtPreselectors)
        
    def makeTuple(self):
        """
        Make tuple
        """

        from Configurables import FitDecayTrees, DecayTreeTuple, TupleToolDecayTreeFitter, TupleToolDecay, TupleToolTrigger, TupleToolTISTOS, TupleToolPropertime, PropertimeFitter, TupleToolKinematic, TupleToolGeometry, TupleToolEventInfo, TupleToolPrimaries, TupleToolPid, TupleToolTrackInfo, TupleToolRecoStats, TupleToolMCTruth,  LoKi__Hybrid__TupleTool, LoKi__Hybrid__EvtTupleTool
        

        tuple = DecayTreeTuple('Tuple'+self.name) # I can put as an argument a name if I use more than a DecayTreeTuple
        tuple.Inputs = [ self.sequence.outputLocation() ]
        tuple.Decay = self.dec
        tuple.ToolList = ['TupleToolKinematic',
                          'TupleToolEventInfo', 
                          'TupleToolTrackInfo',
                          'TupleToolPid',
                          'TupleToolGeometry', 
                          'TupleToolAngles', # Helicity angle
                          # 'TupleToolPropertime', #proper time TAU of reco particles
                          ]

        
        tuple.InputPrimaryVertices = '/Event/Charm/Rec/Vertex/Primary'


        # Other event infos
        tuple.addTupleTool('LoKi::Hybrid::EvtTupleTool/LoKi_Evt')
        tuple.LoKi_Evt.VOID_Variables = {
            #"nSPDHits" :  " CONTAINS('Raw/Spd/Digits')  " ,
            'nTracks' :  " CONTAINS ('Charm/Rec/Track/Best') "  ,
            }
        
        # # Other variables
        # tuple.addTupleTool('LoKi::Hybrid::TupleTool/LoKi_All')
        # tuple.LoKi_All.Variables = {
        #     'BPVIPCHI2' : 'BPVIPCHI2()',
        #     'BPVDIRA' : 'BPVDIRA',
        #     'BPVLTFITCHI2' : 'BPVLTFITCHI2()',           
        #     } 
        
        tuple.addBranches(self.branches)
        
        tuple.phi.addTupleTool("LoKi::Hybrid::TupleTool/LoKi_phi")
        tuple.phi.LoKi_phi.Variables =  {
            'DOCAMAX' : 'DOCAMAX',
            "MassDiff_Phi" : "DMASS('phi(1020)')",
            "BPVDIRA" : "BPVDIRA",
            "IPS_Phi" : "MIPCHI2DV(PRIMARY)",
            "VFASPF_CHI2DOF" : "VFASPF(VCHI2/VDOF)",
            "VFASPF_CHI2" : "VFASPF(VCHI2)",
            "BPVIPCHI2" : "BPVIPCHI2()",
            "ADOCA" : "DOCA(1,2)",
            "ADOCACHI2" : "DOCACHI2(1,2)",

            "DTF_CHI2_PV"   : "DTF_CHI2( True, 'phi(1020)' )",
            "DTF_NDOF_PV"   : "DTF_NDOF( True, 'phi(1020)' )",
            "DTF_M_PV"      : "DTF_FUN ( M, True, 'phi(1020)' )",
            "DTF_M_Ks1_PV"    : "DTF_FUN ( CHILD(M,1), True, 'phi(1020)' )",
            "DTF_M_Ks2_PV"    : "DTF_FUN ( CHILD(M,2), True, 'phi(1020)' )",
           
            # "DTF_CTAU_Ks1"    : "DTF_CTAU(1, False, 'phi(1020)' )",
            # "DTF_CTAU_Ks2"    : "DTF_CTAU(2, False, 'phi(1020)' )",
            
           
            }
        

        def mySharedConf_Ks(branch):
            atool=branch.addTupleTool('LoKi::Hybrid::TupleTool/LoKi_Ks')
            atool.Variables =  {
                "BPVDIRA" : "BPVDIRA",
                "VFASPF_CHI2DOF" : "VFASPF(VCHI2/VDOF)",
                "VFASPF_CHI2" : "VFASPF(VCHI2)",
                "BPVIPCHI2" : "BPVIPCHI2()",
                "BPVVD" : "BPVVD",
                "BPVVDCHI2" : "BPVVDCHI2",
                "ADOCA" : "DOCA(1,2)",
                "ADOCACHI2" : "DOCACHI2(1,2)",
                'BPVLTIME' : 'BPVLTIME()',
                }
            PropertimeTool = branch.addTupleTool("TupleToolPropertime/Propertime_Ks")
            

        mySharedConf_Ks(tuple.Ks1)
        mySharedConf_Ks(tuple.Ks2)

        def mySharedConf_pi(branch):
            atool=branch.addTupleTool('LoKi::Hybrid::TupleTool/LoKi_pi')
            atool.Variables =  {
                'TRCHI2DOF' : 'TRCHI2DOF',
                'TRGHOSTPROB' : 'TRGHOSTPROB',
                }

        mySharedConf_pi(tuple.pi1)
        mySharedConf_pi(tuple.pi2)     
        mySharedConf_pi(tuple.pi3)
        mySharedConf_pi(tuple.pi4) 

        
        # Triggers:   
        tuple.phi.addTupleTool('TupleToolTISTOS/TISTOS')
        tuple.phi.TISTOS.TriggerList = trigger_list
        tuple.phi.TISTOS.VerboseL0   = True
        tuple.phi.TISTOS.VerboseHlt1 = True
        tuple.phi.TISTOS.VerboseHlt2 = True
        
                
        if dataSample.isMC:
            from Configurables import MCDecayTreeTuple, MCTupleToolKinematic, TupleToolMCTruth, MCTupleToolHierarchy, MCTupleToolReconstructed, MCTupleToolAngles, TupleToolMCBackgroundInfo
            tuple.addTupleTool('TupleToolMCTruth/MCTruth')
            tuple.MCTruth.ToolList = ['MCTupleToolKinematic',
                                      'MCTupleToolHierarchy',
                                      'MCTupleToolReconstructed',
                                      'MCTupleToolAngles',
                                      ]
            tuple.phi.addTupleTool( "TupleToolMCBackgroundInfo")

        
        self.sequence.sequence().Members += [tuple]
Beispiel #52
0
# Stream and stripping line we want to use
stream = 'AllStreams'
line = 'D2hhCompleteEventPromptDst2D2RSLine'
tesLoc = '/Event/{0}/Phys/{1}/Particles'.format(stream, line)

# get the selection(s) created by the stripping
strippingSels = [DataOnDemand(Location=tesLoc)]

# create a selection using the substitution algorithm
selSub = Selection(
    'Dst2D0pi_D02pipi_Sel',
    Algorithm=subs,
    RequiredSelections=strippingSels
)

selSeq = SelectionSequence('SelSeq', TopSelection=selSub)

# Create an ntuple to capture D*+ decays from the new selection
from Configurables import DecayTreeTuple
dtt = DecayTreeTuple('TupleDstToD0pi_D0Topipi')
dtt.Inputs = [selSeq.outputLocation()]
# note the redefined decay of the D0
dtt.Decay = '[D*(2010)+ -> ^(D0 -> ^pi- ^pi+) ^pi+]CC'

# add our new selection and the tuple into the sequencer
from Configurables import GaudiSequencer, DaVinci
seq = GaudiSequencer('MyTupleSeq')
seq.Members += [selSeq.sequence()]
seq.Members += [dtt]
DaVinci().appendToMainSequence([seq])
Beispiel #53
0
Ds = CombineParticles("Ds2PhiPi")

Ds.DecayDescriptor = '[D_s+ -> phi(1020) pi+]cc'
Ds.DaughtersCuts = { '' : 'ALL' , 'phi(1020)' : '(ALL)' , 'pi+' : '(PT >150 *MeV) & (BPVIPCHI2() > 1.0) & ( TRCHI2DOF < 5 )& (TRGHOSTPROB<0.3)'}
Ds.CombinationCut =  "(ADAMASS('D_s+')<180*MeV)"
Ds.MotherCut = "(VFASPF(VCHI2/VDOF) < 25.0)& (((BPVVDCHI2 > 16.0)|(BPVLTIME() > 0.150 * picosecond)))"#& (BPVDIRA > 35.0*mrad)"
Ds.MotherCut += "&(ADMASS('D_s+')<150*MeV)" %config


Ds_Sel = Selection(name = "Sel_Ds2PhiPi",
                Algorithm = Ds,
                RequiredSelections = [Phi_Sel, Pions])

Ds_sequence = SelectionSequence('SeqDs2PhiPi',
                                 TopSelection = Ds_Sel
                                 )
 

#This filter is used just to speed up the process, nothing happens if there
# # is no stripped candidates at that location.
# from PhysConf.Filters import LoKi_Filters
# fltrs = LoKi_Filters(
#   STRIP_Code = "HLT_PASS('StrippingPhiToKSKS_PhiToKsKsLineDecision')")


from Configurables import FitDecayTrees, DecayTreeTuple, TupleToolDecayTreeFitter, TupleToolDecay, TupleToolTrigger, TupleToolTISTOS, TupleToolPropertime, PropertimeFitter, TupleToolKinematic, TupleToolGeometry, TupleToolEventInfo, TupleToolPrimaries, TupleToolPid, TupleToolTrackInfo, TupleToolRecoStats, TupleToolMCTruth,  LoKi__Hybrid__TupleTool, LoKi__Hybrid__EvtTupleTool
from Configurables import LoKi__LifetimeFitter

tuple = DecayTreeTuple("TuplePhi2KsKs")
Beispiel #54
0
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
Beispiel #55
0
sc = StrippingConf( Streams = [ AllStreams ],
                    MaxCandidates = 2000
                    )

stripsel = AutomaticData(Location = "Phys/B2XMuMuIncl_InclDiMuLowQ2Line/Particles")

stripfilter = FilterDesktop("stripfilter",
                             Preambulo = ["from LoKiPhysMC.decorators import *",
                                          "from LoKiPhysMC.functions import mcMatch"],
                             Code = "ALL")

inclmumu = Selection ("Sel"+name,
                     Algorithm = stripfilter,
                     RequiredSelections = [stripsel])
seq = SelectionSequence("seq",
                      TopSelection = inclmumu)


tuple = DecayTreeTuple("Incl_Tuple")

tuple.Inputs = [stripsel.outputLocation()]
tuple.ToolList =  [
      "TupleToolKinematic"
    , "TupleToolEventInfo"
    , "TupleToolRecoStats"
    , "TupleToolMCBackgroundInfo"
    , "TupleToolGeometry"
    , "TupleToolPid"
    , "TupleToolPropertime"
    , "TupleToolPrimaries"
    , "TupleToolTrackInfo"
Beispiel #56
0
combineAB = CombineParticles('CombineAB')
combineAB.DecayDescriptor = "B_s0 -> D_s- D_s+"
combineAB.MotherCut = "ALL"
combineAB.Preambulo = [
    "from LoKiPhysMC.decorators import *",
    "from PartProp.Nodes import CC" ]

selectionA = Selection("FakeDsPlusSel",
                        Algorithm = combineA,
                        RequiredSelections=[_kaons, _pions])

selectionB = Selection("FakeDsMinusSel",
                        Algorithm = combineB,
                        RequiredSelections=[_kaons, _pions])

selASelectionSequence = SelectionSequence('FakeDsPlus', TopSelection = selectionA)
selBSelectionSequence = SelectionSequence('FakeDsMinus', TopSelection = selectionB)

selectionAB = Selection("FakeBsSel",
                        Algorithm = combineAB,
                        RequiredSelections=[DataOnDemand(Location=selASelectionSequence.outputLocation()),
                                            DataOnDemand(Location=selBSelectionSequence.outputLocation())])
                                            
selABSelectionSequence = SelectionSequence('FakeBs', TopSelection = selectionAB)


from Configurables import FitDecayTrees
fitD2KKP = FitDecayTrees ( 
    "fitD2KKP" , 
    Code = "DECTREE('B_s0 -> (D_s+ -> K+ K- pi+) (D_s- -> K- K+ pi-)')",
    MassConstraints = [ 'D_s+', 'D_s-' ], 
			Algorithm = makeeta_prime,
			RequiredSelections= [rhoselection, photonselection])

stdKaons = DataOnDemand("Phys/StdLooseKaons/Particles")

makeBu= CombineParticles('makeBu',
			 DecayDescriptor="[B+ -> eta_prime K+]cc",
			 CombinationCut ="(AM > 4500) & (AM < 6500)",
			 MotherCut = "(VFASPF(VCHI2/VDOF)<9.0)",
			 )

BuSel = Selection('BuSel',
		  Algorithm=makeBu,
		  RequiredSelections = [eta_primesel,stdKaons])

Buseq = SelectionSequence('Buseq',
			  TopSelection= BuSel)
		
# Build an Eta_prime

#eta_prime_daughters = {
#	'pi+' : '(PT > 200*MeV)',
#	'pi-' : '(PT> 200*MeV)',
#	'gamma' : '(PT>400*MeV)'
#	}


#CombEta_prime = CombineParticles('CombEta_prime',
#				 Inputs= ['Phys/StdAllLoosePions/Particles','Phys/StdLooseAllPhotons/Particles',StrippingSels.outputLocation()],
#				 DecayDescriptor = 'eta_prime -> rho(770)0 gamma',
#				 DaughtersCuts=eta_prime_daughters,
#				 CombinationCut='(APT>1200*MeV)',
Beispiel #58
0
):
    a = s.algorithm()
    a.ParticleCombiners = {'': 'LoKi::VertexFitter:PUBLIC'}
    #
    a.MaxCandidates = 2000
    a.StopAtMaxCandidates = True
    a.StopIncidentType = 'ExceedsCombinatoricsLimit'
    #
from PhysSelPython.Wrappers import MultiSelectionSequence
from PhysSelPython.Wrappers import SelectionSequence
psi_x = MultiSelectionSequence(
    "PSIX",
    Sequences=[
        ## channels with chic
        #
        SelectionSequence('B2CHICK', psix0.b2chicK()),
        SelectionSequence('B2CHICKK', psix0.b2chicKK()),
        SelectionSequence('B2CHICKPi', psix0.b2chicKpi()),
        SelectionSequence('B2CHICKPiPi', psix0.b2chicKpipi()),
        SelectionSequence('B2CHICPiPi', psix0.b2chicpipi()),
        #
        SelectionSequence('BC2CHICPi', psix0.bc2chicpi()),
        SelectionSequence('Lb2CHICPi', psix0.lb2chicpK()),
    ])

###################### DAVINCI SETTINGS ############################################
DaVinci().SkipEvents = 0  #1945
DaVinci().PrintFreq = 10000
DaVinci().EvtMax = EVTMAX
DaVinci().TupleFile = "DVTuples1.root"
DaVinci().HistogramFile = 'DVHistos.root'
Beispiel #59
0
# Change mass hypothesis
newDecay = "DECTREE('B_s0 -> (phi(1020) -> K+ K-) (f_0(980) -> K+ K-)')"
_SubstituteB0 = SubstitutePID( name = "_SubstituteB0"
                             , Code = " DECTREE('B0 -> (phi(1020) -> K+ K-) (rho(770)0 -> pi+ pi-)') " 
                             , Substitutions = { 'Beauty -> (phi(1020) -> K+ K-) ^(rho(770)0 -> X+ X-)' : 'f_0(980)'
                                               , 'Beauty -> (phi(1020) -> K+ K-) (X0 -> ^pi+ X-)' : 'K+'
                                               , 'Beauty -> (phi(1020) -> K+ K-) (X0 -> X+ ^pi-)' : 'K-'
                                               , 'Beauty -> (phi(1020) -> K+ K-) (X0 -> X+ X-)' : 'B_s0'
                                               }
                             )
_ddChangeSel = Selection( "_ddChangeSel"
                        , Algorithm = _SubstituteB0
                        , RequiredSelections = [_strippingOutput]
                        )
selSeq = SelectionSequence("selseqname", TopSelection = _ddChangeSel)
# Create Decay Tree Tuple #####################################################
from Configurables import DecayTreeTuple
from DecayTreeTuple.Configuration import *
tuple = DecayTreeTuple()
tuple.Inputs = [ selSeq.outputLocation() ]
#tuple.Inputs = [ strippingline ]

from Configurables import BackgroundCategory
from Configurables import TupleToolTrigger, TupleToolRecoStats, TupleToolTrackIsolation, TupleToolTagging, TupleToolTISTOS

# Universal tools
tuple.ToolList += [ "TupleToolGeometry"
                  , "TupleToolKinematic"
                  , "TupleToolPropertime"
#                  , "TupleToolPrimaries"