Exemple #1
0
 def create_path(self):
     path = basf2.create_path()
     modularAnalysis.inputMdstList(
         'default',
         self.get_input_file_names("reconstructed_output.root"),
         path=path)
     modularAnalysis.fillParticleLists([('K+', 'kaonID > 0.1'),
                                        ('pi+', 'pionID > 0.1')],
                                       path=path)
     modularAnalysis.reconstructDecay('D0 -> K- pi+',
                                      '1.7 < M < 1.9',
                                      path=path)
     modularAnalysis.fitVertex('D0', 0.1, path=path)
     modularAnalysis.matchMCTruth('D0', path=path)
     modularAnalysis.reconstructDecay('B- -> D0 pi-',
                                      '5.2 < Mbc < 5.3',
                                      path=path)
     modularAnalysis.fitVertex('B+', 0.1, path=path)
     modularAnalysis.matchMCTruth('B-', path=path)
     modularAnalysis.variablesToNtuple(
         'D0', [
             'M', 'p', 'E', 'useCMSFrame(p)', 'useCMSFrame(E)',
             'daughter(0, kaonID)', 'daughter(1, pionID)', 'isSignal',
             'mcErrors'
         ],
         filename=self.get_output_file_name("D_n_tuple.root"),
         path=path)
     modularAnalysis.variablesToNtuple(
         'B-', ['Mbc', 'deltaE', 'isSignal', 'mcErrors', 'M'],
         filename=self.get_output_file_name("B_n_tuple.root"),
         path=path)
     return path
    def create_path(self):
        path = basf2.create_path()
        modularAnalysis.setupEventInfo(self.n_events, path)

        if self.event_type == SimulationType.y4s:
            # in current main branch and release 5 the Y(4S)decay file is moved, so try old and new locations
            find_file_ignore_error = True
            dec_file = Belle2.FileSystem.findFile(
                'analysis/examples/tutorials/B2A101-Y4SEventGeneration.dec',
                find_file_ignore_error)
            if not dec_file:
                dec_file = Belle2.FileSystem.findFile(
                    'analysis/examples/simulations/B2A101-Y4SEventGeneration.dec'
                )
        elif self.event_type == SimulationType.continuum:
            dec_file = Belle2.FileSystem.findFile(
                'analysis/examples/simulations/B2A102-ccbarEventGeneration.dec'
            )
        else:
            raise ValueError(
                f"Event type {self.event_type} is not valid. It should be either 'Y(4S)' or 'Continuum'!"
            )

        generators.add_evtgen_generator(path, 'signal', dec_file)
        modularAnalysis.loadGearbox(path)
        simulation.add_simulation(path)

        path.add_module('RootOutput',
                        outputFileName=self.get_output_file_name(
                            'simulation_full_output.root'))

        return path
 def create_path(self):
     path = basf2.create_path()
     modularAnalysis.inputMdstList(
         'default',
         self.get_input_file_names("reconstructed_output.root"),
         path=path)
     modularAnalysis.fillParticleLists([('K+', 'kaonID > 0.1'),
                                        ('pi+', 'pionID > 0.1')],
                                       path=path)
     modularAnalysis.reconstructDecay('D0 -> K- pi+',
                                      '1.7 < M < 1.9',
                                      path=path)
     modularAnalysis.matchMCTruth('D0', path=path)
     modularAnalysis.reconstructDecay('B- -> D0 pi-',
                                      '5.2 < Mbc < 5.3',
                                      path=path)
     try:  # treeFit is the new function name in light releases after release 4 (e.g. light-2002-janus)
         vertex.treeFit('B+', 0.1, update_all_daughters=True, path=path)
     except AttributeError:  # vertexTree is the function name in release 4
         vertex.vertexTree('B+', 0.1, update_all_daughters=True, path=path)
     modularAnalysis.matchMCTruth('B-', path=path)
     modularAnalysis.variablesToNtuple(
         'D0', [
             'M', 'p', 'E', 'useCMSFrame(p)', 'useCMSFrame(E)',
             'daughter(0, kaonID)', 'daughter(1, pionID)', 'isSignal',
             'mcErrors'
         ],
         filename=self.get_output_file_name("D_n_tuple.root"),
         path=path)
     modularAnalysis.variablesToNtuple(
         'B-', ['Mbc', 'deltaE', 'isSignal', 'mcErrors', 'M'],
         filename=self.get_output_file_name("B_n_tuple.root"),
         path=path)
     return path
    def prepare(self):
        """
        A function to prepare a path with the modules given in path.
        """
        if self.path:
            # Append the needed ToFileLogger module
            created_path = basf2.create_path()
            file_logger_module = basf2.register_module("ToFileLogger")
            file_logger_module.param("fileName", self.log_file_name)
            created_path.add_module(file_logger_module)

            # Copy the modules from the path
            for module in self.path.modules():
                created_path.add_module(module)

            # Add the progress python module
            created_path.add_module(python_modules.ProgressPython(self.progress_queue_remote))

            # Add the print collections python module
            created_path.add_module(python_modules.PrintCollections(self.result_queue))

            self.path = created_path

        else:
            self.is_valid = False
Exemple #5
0
    def prepare(self):
        """
        A function to prepare a path with the modules given in path.
        """
        if self.path:
            # Append the needed ToFileLogger module
            created_path = basf2.create_path()
            file_logger_module = basf2.register_module("ToFileLogger")
            file_logger_module.param("fileName", self.log_file_name)
            created_path.add_module(file_logger_module)

            # Copy the modules from the path
            for module in self.path.modules():
                created_path.add_module(module)

            # Add the progress python module
            created_path.add_module(
                python_modules.ProgressPython(self.progress_queue_remote))

            # Add the print collections python module
            created_path.add_module(
                python_modules.PrintCollections(self.result_queue))

            self.path = created_path

        else:
            self.is_valid = False
Exemple #6
0
def main(name1,name2):

    my_path= basf2.create_path()
    
    fileList = name1
    
    inputMdstList('default', fileList, path=my_path)
    
    output_file= '/home/belle2/sanjeeda/D0_Ks_Ks/reconstructed/reco'+name2
    
    #load the lists for pion and kaon
    stdc.stdPi(listtype='all', path=my_path)
    stdc.stdK(listtype='all', path=my_path)
    
    #list of soft pion with cuts
    soft = '[thetaInCDCAcceptance] and [dr<0.5] and [abs(dz)<2] and [nCDCHits>0]'
    fillParticleList('pi+:soft', soft, path=my_path)  
    
    #create merged K_S0 list
    stdKshorts(prioritiseV0=True,fitter='TreeFit',path=my_path) 
    reconstructDecay('K_S0:merged -> pi-:all pi+:all', cut='0.3 < M < 0.7', path=my_path)
    variablesToExtraInfo(particleList= 'K_S0:merged', variables={'M': 'M_preFit'}, path=my_path)
 
    reconstructDecay('D0:sig -> K_S0:merged K_S0:merged', cut='1.7 < M < 2.1', path=my_path)
    
    reconstructDecay('D*+ -> D0:sig pi+:soft', cut='useCMSFrame(p)> 2 and massDifference(0) < 0.16', path=my_path)
    
    matchMCTruth(list_name='D*+',path=my_path)
    
    vx.treeFit(list_name='D*+', conf_level=0.001, ipConstraint=True, updateAllDaughters=True, massConstraint=[310],path=my_path)
    
    vertex_variables = vc.flight_info + ['M','x','y','z','mcX','mcY','mcZ',
                                         'mcProdVertexX','mcProdVertexY','mcProdVertexZ','mcFlightTime','mcFlightDistance']
    d0_vars= vu.create_aliases_for_selected(
        list_of_variables = vc.inv_mass + vc.mc_truth + vertex_variables + vc.kinematics +['isSignalAcceptMissingGamma'],
        decay_string='D*+ -> [^D0:sig -> [K_S0:merged -> pi+:all pi-:all]  [K_S0:merged -> pi+:all pi-:all]] pi+:soft', prefix='Dz')
    
    kshort_vars = vu.create_aliases_for_selected(
        list_of_variables = vc.inv_mass + vc.mc_truth +  vertex_variables + vc.kinematics +  ['extraInfo(M_preFit)'],
        decay_string= 'D*+ -> [D0:sig -> [^K_S0:merged -> pi+:all pi-:all]  [^K_S0:merged -> pi+:all pi-:all]] pi+:soft',prefix=['Ks1','Ks2'])
    
    
    pi_vars = vu.create_aliases_for_selected(
        list_of_variables = vc.kinematics + vc.track + vc.mc_truth + vc.pid,
        decay_string='D*+ -> [D0:sig -> [K_S0:merged -> ^pi+:all ^pi-:all] [K_S0:merged -> ^pi+:all ^pi-:all]] ^pi+:soft',prefix=['pi1','pi2','pi3','pi4','pisoft'])
    
    dstar_vars= vu.create_aliases_for_selected(
        list_of_variables = vc.inv_mass + vc.mc_truth + vc.kinematics+['useCMSFrame(p)','massDifference(0)','isSignalAcceptMissingGamma','Q'] ,
        decay_string='^D*+ -> [D0:sig -> [K_S0:merged -> pi+:all pi-:all] [K_S0:merged -> pi+:all pi-:all]] pi+:soft',prefix ='Dst')
    
    variablesToNtuple('D*+', d0_vars + kshort_vars + pi_vars + dstar_vars,
                      filename=output_file, treename='D0KsKs', path=my_path)
    
 


    process(my_path)
    print(statistics)
Exemple #7
0
def simulation(input_file, output_file):
    my_path = b2.create_path()
    print(f"Number of processes: {b2.get_nprocesses()}")

    # load input ROOT file
    ma.inputMdst(environmentType="default", filename=input_file, path=my_path)
    """
        Loads the specified ROOT (DST/mDST/muDST) files with the RootInput module.

        The correct environment (e.g. magnetic field settings) are determined from the specified environment type.
        The currently available environments are:

        - 'MC5': for analysis of Belle II MC samples produced with releases prior to build-2016-05-01.
          This environment sets the constant magnetic field (B = 1.5 T)
        - 'MC6': for analysis of Belle II MC samples produced with build-2016-05-01 or newer but prior to release-00-08-00
        - 'MC7': for analysis of Belle II MC samples produced with build-2016-05-01 or newer but prior to release-00-08-00
        - 'MC8', for analysis of Belle II MC samples produced with release-00-08-00 or newer but prior to release-02-00-00
        - 'MC9', for analysis of Belle II MC samples produced with release-00-08-00 or newer but prior to release-02-00-00
        - 'MC10', for analysis of Belle II MC samples produced with release-00-08-00 or newer but prior to release-02-00-00
        - 'default': for analysis of Belle II MC samples produced with releases with release-02-00-00 or newer.
          This environment sets the default magnetic field (see geometry settings)
        - 'Belle': for analysis of converted (or during of conversion of) Belle MC/DATA samples
        - 'None': for analysis of generator level information or during simulation/my_reconstruction of
          previously generated events

        Note that there is no difference between MC6 and MC7. Both are given for sake of completion.
        The same is true for MC8, MC9 and MC10

        Parameters:
            environmentType (str): type of the environment to be loaded
            filename (str): the name of the file to be loaded
            path (basf2.Path): modules are added to this path
            skipNEvents (int): N events of the input files are skipped
            entrySequences (list(str)): The number sequences (e.g. 23:42,101) defining
                the entries which are processed for each inputFileName.
            parentLevel (int): Number of generations of parent files (files used as input when creating a file) to be read
    """

    # In case of conflict with geometry, you may use this line instead:
    # analysis_main.add_module("RootInput", inputFileName='B2A101-Y4SEventGeneration-evtgen.root')

    # simulation
    si.add_simulation(path=my_path)

    # my_reconstruction
    re.add_reconstruction(path=my_path)

    # dump in MDST format
    mdst.add_mdst_output(path=my_path, mc=True, filename=output_file)

    # Show progress of processing
    progress = b2.register_module("ProgressBar")
    my_path.add_module(progress)

    # Process the events
    b2.process(my_path)
    print(b2.statistics)
    def create_path(self):
        path = basf2.create_path()

        path.add_module('RootInput',
                        inputFileNames=self.get_input_file_names(
                            "simulation_full_output.root"))
        modularAnalysis.loadGearbox(path)
        reconstruction.add_reconstruction(path)

        modularAnalysis.outputMdst(
            self.get_output_file_name("reconstructed_output.root"), path=path)

        return path
def create_analysis_path(
        b_ntuple_filename="B_ntuple.root",
        d_ntuple_filename="D_ntuple.root",
        mbc_range=(5.2, 5.3),
):
    """
    Example of a minimal reconstruction with a cut as a changeable function
    parameter, adapted from code in the ``B2T_Basics_3_FirstAnalysis.ipynb``
    notebook from b2 starter kit.
    """
    path = basf2.create_path()
    # this local inputMdstList will only be used when this steerig file is run locally, gbasf2 overrides it
    local_input_files = [
        "/group/belle2/dataprod/MC/MC13a/prod00009434/s00/e1003/4S/r00000/mixed/mdst/sub00/mdst_000001_prod00009434_task10020000001.root"
    ]
    mA.inputMdstList(
        environmentType="default",
        filelist=local_input_files,
        path=path,
    )
    stdK("higheff", path=path)
    stdPi("higheff", path=path)
    mA.reconstructDecay('D0:Kpi -> K-:higheff pi+:higheff',
                        '1.7 < M < 1.9',
                        path=path)
    # use try except to have this code work for both the old and new function names for the tree fit
    mA.matchMCTruth('D0:Kpi', path=path)
    mA.reconstructDecay('B- -> D0:Kpi pi-:higheff',
                        f"{mbc_range[0]} < Mbc < {mbc_range[1]}",
                        path=path)
    try:
        vx.treeFit('B+', 0.1, path=path)
    except AttributeError:
        vx.vertexTree('B+', 0.1, path=path)
    mA.setAnalysisConfigParams({"mcMatchingVersion": "BelleII"}, path)
    mA.matchMCTruth('B-', path=path)
    vm.addAlias("p_cms",
                "useCMSFrame(p)")  # include aliases to test if they work
    vm.addAlias("E_cms", "useCMSFrame(E)")
    mA.variablesToNtuple('D0:Kpi', [
        'M', 'p', 'E', 'E_cms', 'p_cms', 'daughter(0, kaonID)',
        'daughter(1, pionID)', 'isSignal', 'mcErrors'
    ],
                         filename=d_ntuple_filename,
                         treename="D",
                         path=path)
    mA.variablesToNtuple('B-', ['Mbc', 'deltaE', 'isSignal', 'mcErrors', 'M'],
                         filename=b_ntuple_filename,
                         treename="B",
                         path=path)
    return path
Exemple #10
0
def submit_generation(n_events, dec_file, out_name, random_seed):
    # Command line args passed as strings, so ensure they're corrected to ints
    n_events = int(n_events)
    random_seed = int(random_seed)
    ge.set_random_seed(random_seed)
    my_path = b2.create_path()
    ma.setupEventInfo(noEvents=n_events, path=my_path)
    ge.add_evtgen_generator(path=my_path,
                            finalstate="signal",
                            signaldecfile=dec_file)
    ma.loadGearbox(path=my_path)
    my_path.add_module("RootOutput", outputFileName=out_name)
    b2.process(path=my_path)
    print(b2.statistics)
Exemple #11
0
import glob
import basf2 as b2
import modularAnalysis as ma
from variables import variables as var
import variables.collections as vc
import variables.utils as vu
import sys

inputFile = glob.glob(
    '/home/belle2/atpathak/PhysicsAnalysis/work/skim_thrust_test/taupair/sub00/*.root'
)

#inputFile = glob.glob('/home/belle2/atpathak/PhysicsAnalysis/work/tau_analysis/kkmc_tautau.root')

my_path = b2.create_path()

tauPlus = sys.argv[1]
tauMinus = sys.argv[2]

#b2.use_central_database("data_reprocessing_prompt_bucket6")

ma.inputMdstList(environmentType='default', filelist=inputFile, path=my_path)
b2.set_module_parameters(path=my_path, name='RootInput', cacheSize=100)

######################################################
# create and fill the ParticleLists
######################################################
ma.fillParticleList('e-:all', '', path=my_path)
ma.fillParticleList('mu+:all', '', path=my_path)
ma.fillParticleList('pi-:all', '', path=my_path)
def my_path():
    return b2.create_path()
    'BELLE2_EXTERNALS_DIR', 'BELLE2_EXTERNALS_SUBSIR',
    'BELLE2_EXTERNALS_OPTION', 'BELLE2_EXTERNALS_VERSION', 'BELLE2_LOCAL_DIR',
    'BELLE2_OPTION', 'BELLE_POSTGRES_SERVER', 'USE_GRAND_REPROCESS_DATA',
    'PANTHER_TABLE_DIR', 'PGUSER'
]

# Print env variables for check
print("Environmental Variables".center(80, '='))
for v in env_list:
    print_env(v)

# Show input and output file info
print("Input: %s" % sys.argv[1])
print("Ouput: %s" % sys.argv[2])

mp = b2.create_path()

b2c.convertBelleMdstToBelleIIMdst(sys.argv[1], applyHadronBJSkim=True, path=mp)

# Aliases for the variables to make the root file easier to understand
variables.addAlias('pid_ppi', 'atcPIDBelle(4,2)')
variables.addAlias('pid_pk', 'atcPIDBelle(4,3)')
variables.addAlias('pid_kpi', 'atcPIDBelle(3,2)')

variables.addAlias('cosa', 'cosAngleBetweenMomentumAndVertexVector')
variables.addAlias('cosaXY', 'cosAngleBetweenMomentumAndVertexVectorInXYPlane')

mc_vars = [
    'isSignal', 'isPrimarySignal', 'mcPDG', 'genMotherPDG', 'nMCMatches',
    'mcP', 'mcE', 'mcPT'
]
def reconstruct(infile='default.root', outfile='output_beta.root', path=None):
    """

    Args:
        infile: Input file name (use overwrite from basf2)
        outfile: output file name (use overwrite from basf2)
        path: (optional) basf2 path

    Returns:
        path
    """

    setup()

    # EXAMPE RECONSTRUCTION CODE
    # DELETE OR MODIFY FROM HERE
    just_an_example = True
    if just_an_example:
        with open(outfile, 'w') as f:
            f.write("Proccessed example input " + infile)
    else:
        path = b2.create_path() if path is None else path

        # Input file
        ma.inputMdstList("default", infile, path=path)

        # Event level cuts examples
        ma.applyEventCuts('R2EventLevel<0.6 and nTracks>=3', path=path)

        #
        # Load Primary particles
        #
        from stdPhotons import stdPhotons
        stdPhotons('cdc', path)
        ma.cutAndCopyList('gamma:sig', 'gamma:cdc',
                          'clusterNHits > 1.5 and E > 1.5', True, path)

        from stdPi0s import stdPi0s
        stdPi0s('eff20', path)

        # Loading charged tracks
        good_track = 'thetaInCDCAcceptance and nCDCHits>20 and dr < 0.5 and abs(dz) < 2'
        ma.fillParticleList("pi+:sig",
                            good_track + " and pionID > 0.0",
                            path=path)
        ma.fillParticleList("K+:sig",
                            good_track + " and kaonID > 0.0",
                            path=path)

        #
        # Combine particles
        #
        ma.reconstructDecay('K*0:sig  -> K+:sig pi-:sig',
                            '0.6 < M < 1.6',
                            path=path)

        ma.reconstructDecay('B0:sig ->  K*0:sig gamma:sig',
                            '5.22 < Mbc < 5.3 and  abs(deltaE)< 1',
                            path=path)

        # Final Calculateions
        ma.rankByHighest("B0:ch1",
                         "formula(-1*abs(deltaE))",
                         outputVariable='Rank_deltaE',
                         path=path)

        ma.buildEventShape(allMoments=True, path=path)

        ma.matchMCTruth("B0:sig", path=path)

        #
        # Write out Ntuples
        #
        all_vars = get_variables()
        ma.variablesToNtuple('B0:ch1',
                             all_vars,
                             filename=outfile,
                             treename="B0",
                             path=path)
    # TO HERE

    #ma.printMCParticles(path=path)
    return path
Exemple #15
0
def makeFSPs(input_file,  isdata):
    path = b2.create_path()
    inputMdstList(environmentType='default', filelist=input_file, path=path)
    printDataStore(path=path)
    # path.add_module('EventInfoPrinter')
    variables.addAlias('pi_k', 'pidPairProbabilityExpert(211, 321, ALL)')
    variables.addAlias('k_pi', 'pidPairProbabilityExpert(321, 211, ALL)')
    # electron
    impactcut = 'abs(d0)<0.5 and abs(z0)<2.0 '
    # NOTE For BtoXll skim
    # event level cuts: R2 and require a minimum number of tracks
    fillParticleList(decayString='pi+:eventShapeForSkims', cut='pt > 0.1', path=path)
    fillParticleList(decayString='gamma:eventShapeForSkims', cut='E > 0.1', path=path)
    buildEventShape(inputListNames=['pi+:eventShapeForSkims', 'gamma:eventShapeForSkims'],
                    allMoments=False,
                    foxWolfram=True,
                    harmonicMoments=False,
                    cleoCones=False,
                    thrust=False,
                    collisionAxis=False,
                    jets=False,
                    sphericity=False,
                    checkForDuplicates=False,
                    path=path)

    fillParticleList(decayString='e+:all',
                     cut=impactcut + ' and electronID > 0.5', path=path)
    # muon
    fillParticleList(decayString='mu+:all',
                     cut=impactcut + ' and muonID > 0.5', path=path)
    # pion
    fillParticleList(decayString='pi+:all',
                     cut=impactcut + ' and pi_k>0.1', path=path)
    # kaon
    fillParticleList(decayString='K+:all',
                     cut=impactcut + ' and k_pi>0.1', path=path)
    # gamma
    fillParticleList(decayString='gamma:all', cut='', path=path)
    if isdata:
        print(yellow, 'Momentum correction for FSPs', end)
        trackingMomentum(inputListNames=['mu+:all', 'e+:all', 'K+:all', 'pi+:all'], scale=1.00056, path=path)
    # Bremrecovery
    correctBremsBelle('e-:corrected', 'e-:all', 'gamma:all', True, 0.05, 0.05,
                      False, path=path)
    # Ks0
    stdKshorts( path=path)
    cutAndCopyList('K_S0:my_ks', 'K_S0:merged', 'goodBelleKshort==1', writeOut=False, path=path)
    matchMCTruth(list_name='K_S0:my_ks', path=path)
    # pi0
    stdPhotons('all', path=path)
    cutAndCopyList(
        'gamma:eff30_Jan2020',
        'gamma:all',
        '[clusterReg==1 and E>0.080] or [clusterReg==2 and E>0.030] or [clusterReg==3 and E>0.060]',
        path=path)
    reconstructDecay('pi0:all -> gamma:eff30_Jan2020 gamma:eff30_Jan2020',
                     '0.1215 < M < 0.1415 and E > 0.4 and abs(cosHelicityAngleMomentum)<0.8', path=path)
    #vertex.KFit('pi0:all', conf_level=0.0, path=path)
    vertex.KFit('pi0:all', conf_level=0.0,fit_type='mass', path=path)
    # K*0->K+ pi-
    reconstructDecay(decayString='K*0:all -> K+:all pi-:all',
                     cut='0.6 < M < 1.2', path=path)
    matchMCTruth(list_name='K*0:all', path=path)
    # K*+ -> K_s pi+
    reconstructDecay(decayString='K*+:ks -> K_S0:my_ks pi+:all',
                     cut='0.6 < M < 1.2', path=path)
    matchMCTruth(list_name='K*+:ks', path=path)
    # K*+ -> K+ pi0
    reconstructDecay(decayString='K*+:pi0 -> K+:all pi0:all',
                     cut='0.6 < M < 1.2', path=path)
    matchMCTruth(list_name='K*+:pi0', path=path)
    return path
import mdst as mdst
import reconstruction as re
import modularAnalysis as ma
from ROOT import Belle2

# set the log level
ma.set_log_level(ma.LogLevel.INFO)

# set the correct GT, not needed for local runs taken with PocketDAQ
ma.reset_database()
ma.use_database_chain()
ma.use_central_database('data_reprocessing_prompt_snapshot_01252019',
                        ma.LogLevel.INFO)

# create the main path and also an empty path
main_path = b2.create_path()

# add input and the progress bar
inputFileName = glob.glob(inputPath + '*.sroot*')
main_path.add_module('SeqRootInput', inputFileNames=inputFileName)
main_path.add_module('Progress')
main_path.add_module('ProgressBar')

# set the geometry
main_path.add_module('Gearbox')
main_path.add_module('Geometry', useDB=True)

# unpack bklm raw dawa
main_path.add_module('BKLMUnpacker')

# analyze bklm digits
Exemple #17
0
def reconstruction(input_file, output_file):
    my_path = b2.create_path()
    ma.inputMdst("default", input_file, my_path)

    # Find decay name from the input file name
    decay_name = "_".join(input_file.split("/")[-1].split("_")[0:2])

    # Load configuration file
    config = yaml.safe_load(open("config/reco_config.yaml"))
    options = config[decay_name]

    # Parse list of subdecays in decay chain
    decays = options["sub_decays"]
    decays = DecayList(decays)

    # Create particle lists for final state particles
    fsps = decays.get_fsps()
    for particle in fsps:
        ma.fillParticleList(particle, "", path=my_path)

    # Reconstruct requested decay chains
    for decay in decays:
        ma.reconstructDecay(str(decay), "", path=my_path)

    # Perform truth matching for requested particles
    truth_match_particles = decays.mothers
    for truth_match_particle in truth_match_particles:
        ma.looseMCTruth(truth_match_particle, path=my_path)

    # Perform vertex fitting
    head = decays.get_head()
    vtx_decay_string = decays.get_chain()
    print(vtx_decay_string)

    vx.vertexRave(head, 0, vtx_decay_string, constraint="iptube", path=my_path)

    # ma.rankByLowest("B0", 'chiProb', numBest=3, outputVariable='B_vtx_rank', path=my_path)
    # ma.variables.addAlias('B_vtx_rank', 'extraInfo(B_vtx_rank)')
    ma.buildRestOfEvent(head, path=my_path)

    # Tag-side
    vx.TagV(head, "breco", 0.001, path=my_path)

    ma.buildEventKinematics(path=my_path)
    ma.buildEventShape(path=my_path)

    # Create centre-of-mass frame variables
    cms_kinematics = vu.create_aliases(
        vc.kinematics, "useCMSFrame({variable})", prefix="CMS"
    )

    variables = [
        item
        for sublist in [
            vc.kinematics,
            cms_kinematics,
            vc.deltae_mbc,
            vc.inv_mass,
            vc.event_shape,
            vc.vertex,
            vc.mc_truth,
            vc.mc_kinematics,
            vc.mc_vertex,
            vc.mc_tag_vertex,
        ]
        for item in sublist
    ]

    trees = yaml.safe_load(open("config/tree_names.yaml"))
    for particle in decays.all_particles:
        ma.variablesToNtuple(
            particle,
            variables,
            filename=output_file,
            treename=trees[particle],
            path=my_path,
        )

    b2.process(my_path)
    print(b2.statistics)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import basf2 as b2  # noqa
import modularAnalysis as ma  # noqa

main = b2.create_path()

main.add_module('RootInput', recovery=True)
main.add_module('RootOutput')

b2.process(main)
Exemple #19
0
                    dest='threshold')
args = parser.parse_args()

assert (len(args.model) == len(
    args.model_type)), 'MODEL files must have exactly on TYPE each'

# User output
print("\nSettings:")
if args.decay_file:
    print("Input file set to:\t" + args.decay_file)
print("Trained model loaded:\t" + str(args.model))
print("Number of events to generate:\t" + str(args.num_events))

# Need to fetch output directory from basf2 -o flag and create it

main = b2.create_path()

# ma.setupEventInfo(args.num_events, path=main)
# Need to input decay file with Y4S -> B0 B0 if I want mixed bkg?
if args.decay_file:
    # add_evtgen_generator(main, 'signal', args.decay_file)
    # Deprecated
    ma.generateY4S(noEvents=args.num_events,
                   decayTable=args.decay_file,
                   path=main)
else:
    # Annoying, need to add flag for this shit now
    # add_evtgen_generator(main, 'mixed')
    ma.generateY4S(noEvents=args.num_events, path=main)

# Override event number -- use skip-events flag for basf2 instead -- easy in htcondor
Exemple #20
0
variables.addAlias('B0_ThrustB','thrustBm')
variables.addAlias('B0_cc4','CleoConeCS(4)')
variables.addAlias('B0_hso02','KSFWVariables(hso02)')
#variables.addAlias('MCTagBFlavor','internalTagVMCFlavor')
variables.addAlias('CSMVA','extraInfo(CSMVA)')
variables.addAlias('XsdM','daughterInvM(0,1,2)')
variables.addAlias('pi0Likeness','extraInfo(Pi0_Prob)')
variables.addAlias('etaLikeness','extraInfo(Eta_Prob)')
variables.addAlias('cosThetaCMS','useCMSFrame(cosTheta)')
variables.addAlias('pCMS','useCMSFrame(p)')
variables.addAlias('ECMS','useCMSFrame(E)')
variables.addAlias('m12','daughterInvariantMass(0,1)')
variables.addAlias('m13','daughterInvariantMass(0,2)')
variables.addAlias('m23','daughterInvariantMass(1,2)')

main_path = b2.create_path() # Declaration of main path
bp.add_beamparameters(main_path,'Y4S')
ma.inputMdst('MC10', inputFilename, path=main_path)
sv.goodBelleKshort(path=main_path)
sg.stdPhotons('loose', path=main_path)
sc.stdPi('95eff', path=main_path)
ma.applyCuts('gamma:loose','1.4 < E < 4', path=main_path)
krescuts = " and daughterInvM(0,1,2) < 2 and daughterInvM(0,1) > 0.6 and daughterInvM(0,1) < 0.9"
#reconstructDecay(Kres+":all -> pi+:good pi-:good K_S0:all", krescuts)
ma.reconstructDecay("B0:signal -> pi+:95eff pi-:95eff K_S0:legacyGoodKS gamma:loose",
        "Mbc > 5.2 and deltaE < 0.2 and deltaE > -0.2 and  -0.65 < daughter(1, cosTheta) < 0.85"+krescuts, path=main_path)
ma.vertexRave('B0:signal',0.0001, 'B0 -> ^pi+ ^pi- ^K_S0 gamma', path=main_path)
#vertexTree('B0:signal',0.0001)

ma.rankByHighest('B0:signal',ratingVar, 1, outputVariable='myRating', path=main_path)
Exemple #21
0
#!/usr/bin/env python3

import basf2
import modularAnalysis
import pdg

path = basf2.create_path()

# Base definitions of stable particles and detector data
particles = ['K+', 'pi+', 'e+', 'mu+', 'p+', 'deuteron']
detectors = ['svd', 'cdc', 'top', 'arich', 'ecl', 'klm', 'all', 'default']

# Default list of variables which should be exported to the root file
root_vars = [
    'isSignal', 'mcErrors', 'mcPDG', 'mcDX', 'mcDY', 'mcDZ', 'isPrimarySignal'
]
root_vars += [
    'p', 'pErr', 'phi', 'phiErr', 'pt', 'ptErr', 'cosTheta', 'cosThetaErr',
    'Theta', 'ThetaErr', 'charge'
]
root_vars += [
    'd0', 'd0Err', 'z0', 'z0Err', 'firstPXDLayer', 'firstSVDLayer', 'nCDCHits',
    'nPXDHits', 'nSVDHits', 'nVXDHits', 'omega', 'omegaErr', 'pValue', 'phi0',
    'phi0Err', 'tanlambda', 'tanlambdaErr'
]
root_vars += [
    'kaonID', 'pionID', 'electronID', 'muonID', 'protonID', 'deuteronID'
]

# Import mdst file and fill particle list without applying any cuts
modularAnalysis.inputMdstList("default", ['sample.mdst.root'], path=path)
Exemple #22
0
#
# Contributors: A. Zupanc (June 2014)
#               K. Ota (Oct 2017)
#               I. Komarov (December 2017)
#               I. Komarov (September 2018)
#
################################################################################

import basf2 as b2
import modularAnalysis as ma
import variables.collections as vc
import variables.utils as vu
import stdCharged as stdc

# create path
my_path = b2.create_path()

# load input ROOT file
ma.inputMdst(environmentType='default',
             filename=b2.find_file('B2rhogamma_rho2pipi.root', 'examples',
                                   False),
             path=my_path)

ma.fillParticleList(decayString='gamma:highE', cut='E > 1.5', path=my_path)
ma.fillParticleList(decayString='pi+:loose',
                    cut='abs(d0) < 0.5 and abs(z0) < 0.5 and pionID > 0.002',
                    path=my_path)

# reconstruct rho -> pi+ pi- decay
# keep only candidates with 0.6 < M(pi+pi-) < 1.0 GeV
ma.reconstructDecay(decayString='rho0 -> pi+:loose pi-:loose',
        else:
            self.return_value(0)

# set the global log level
ma.set_log_level(ma.LogLevel.INFO)

# set the correct GT
ma.reset_database()
ma.use_database_chain()
#ma.use_central_database("staging_data_reprocessing", ma.LogLevel.WARNING)
#ma.use_central_database('data_reprocessing_prompt_bucket6', ma.LogLevel.INFO)

ma.use_central_database('data_reprocessing_prompt_snapshot_02182019', ma.LogLevel.INFO)

# create the main path and also an empty path
main_path = b2.create_path()
empty_path = b2.create_path()

# add input and the progress bar
if useSroot:
    inputFileName = glob.glob(inputPath + '*.*.*.*.*.sroot')
    main_path.add_module('SeqRootInput', inputFileNames=inputFileName)
else:
    inputFileName = glob.glob(inputPath + '*.*.*.*.*.root')
    main_path.add_module('RootInput', inputFileNames=inputFileName)
main_path.add_module('Progress')
main_path.add_module('ProgressBar')

# set geometry w/o the magnetic field
main_path.add_module('Gearbox')
main_path.add_module('Geometry',