Esempio n. 1
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])
Esempio n. 2
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()
Esempio n. 3
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])
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]
Esempio n. 5
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
Esempio n. 6
0
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)
Esempio n. 7
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
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)]
Esempio n. 9
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)
 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()]
Esempio n. 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_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
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']
Esempio n. 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()
Esempio n. 16
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
Esempio n. 17
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)

}
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()]
Esempio n. 19
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()]
Esempio n. 20
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)
Esempio n. 21
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])
Esempio n. 22
0
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()])
Esempio n. 23
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'
Esempio n. 24
0
#################################################
from Configurables import CombineParticles, FilterDesktop


#DaVinci v28
#_pions = DataOnDemand(Location='Phys/StdLoosePions/Particles')
#DaVinci v26
#######################################
# pions
_pions = DataOnDemand(Location='Phys/StdLoosePions')
_filter = FilterDesktop("filterPions", Code = "TRCHI2DOF<4")
_selPions = Selection("SelFilterPions",
                            Algorithm = _filter,
                            RequiredSelections = [_pions])
_seqPions = SelectionSequence("SeqFilterPions", TopSelection = _selPions)

#######################################
# kaons
_kaons = DataOnDemand(Location='Phys/StdLooseKaons')
_filterkaons = FilterDesktop("filterKaons", Code = "TRCHI2DOF<4")
_selKaons = Selection("SelFilterKaons",
                            Algorithm = _filterkaons,
                            RequiredSelections = [_kaons])
_seqKaons = SelectionSequence("SeqFilterKaons", TopSelection = _selKaons)

_muons = DataOnDemand(Location='Phys/StdLooseMuons')
_filtermuons = FilterDesktop("filterMuons", Code = "TRCHI2DOF<4")
_selMuons = Selection("SelFilterMuons",
                            Algorithm = _filtermuons,
                            RequiredSelections = [_muons])
Esempio n. 25
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
Esempio n. 26
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"
Esempio n. 27
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"
Esempio n. 28
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",
Esempio n. 29
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'
Esempio n. 30
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()]