Esempio n. 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.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
Esempio n. 2
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_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
Esempio n. 4
0
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)

######################################################
# track cuts
######################################################

var.addAlias('EoverP', 'formula( ifNANgiveX( clusterE, -1 )/p )')
                               path + 'Bd2K0spi0_to_test.root']
        elif step == 'apply_signal':
            input_file_list = [path + 'Bd2K0spi0_to_test.root']
        elif step == 'apply_qqbar':
            input_file_list = [path + 'ccbar_sample_to_test.root', ]
        else:
            sys.exit('Step does not match any of the available samples: `train`, `test`, `apply_signal`or `apply_qqbar`')
        outfile = step + '.root'

# ---------------------------------------------------------------------------------------------

# Perform analysis.
my_path = b2.create_path()

ma.inputMdstList(environmentType=magnetic_field,
                 filelist=input_file_list,
                 path=my_path)

ma.fillParticleList(decayString='gamma:all',
                    cut='',
                    path=my_path)
ma.fillParticleList(decayString='pi+:good',
                    cut='chiProb > 0.001 and pionID > 0.5',
                    path=my_path)
ma.fillParticleList(decayString='pi-:good',
                    cut='chiProb > 0.001 and pionID > 0.5',
                    path=my_path)

ma.reconstructDecay(decayString='K_S0 -> pi+:good pi-:good',
                    cut='0.480<=M<=0.516',
                    dmID=1,
Esempio n. 6
0
                    dest='out_dir')
args = parser.parse_args()

# Set up output file (not integrated into basf2 command line yet)
if len(args.in_file) > 0:
    out_filename = '{}.h5'.format(
        os.path.splitext(os.path.basename(args.in_file))[0])
else:
    out_filename = 'train_data.h5'
os.makedirs(args.out_dir, exist_ok=True)
outfile = os.path.join(args.out_dir, out_filename)
print("Output file set to:\t" + outfile)

# Main processing
################################################################################
path = ma.create_path()

# Should change to RootInput with keppParents=True
# Don't need the other junk added by inputMdst since we're only dealing with MCParticles
ma.inputMdstList('default', filelist=[args.in_file], path=path)

TrainDataSaver_module = TrainDataSaver(
    evt_num_file=args.evtnum_file,
    output_file=outfile,
    keep_only=args.keep_only,
)
path.add_module(TrainDataSaver_module)

b2.process(path)
print(b2.statistics)
Esempio n. 7
0
from basf2 import *
from modularAnalysis import inputMdst
from modularAnalysis import inputMdstList
from modularAnalysis import analysis_main
from simulation import add_simulation
from reconstruction import add_reconstruction
from reconstruction import add_mdst_output

import sys

# load input ROOT file

inputName = ['testSkimming_BBbar-10M-1.root']
outputName = 'reconstructedBBbar.root'

inputMdstList(inputName)

bkgdir = '/b2data/gaz/local_installation/bkg/bkg/'
bkgFiles = [bkgdir + '*.root']

# simulation
add_simulation(analysis_main)

# reconstruction
add_reconstruction(analysis_main)

# dump in MDST format
add_mdst_output(analysis_main, True,outputName)

# Show progress of processing
progress = register_module('Progress')
Esempio n. 8
0
    mp = b2.create_path()
    
    print_env()
    
    if len(sys.argv) == 1:
        infile = '/ghi/fs01/belle2/bdata/MC/release-03-01-00/DB00000547/MC12b/prod00007426/s00/e1003/4S/r00000/ccbar/mdst/sub00'\
                 '/mdst_000001_prod00007426_task10020000001.root'
        outfile = 'test.root'
    else:
        infile = sys.argv[1]
        outfile = sys.argv[2]
    
    print(f"Input = {infile}")
    print(f"Output = {outfile}")
    
    ma.inputMdstList('default', [infile], path = mp)

    eff = 60
    stdSigmas(f'pi0eff{eff}', path = mp)
    ma.matchMCTruth('Sigma+:std', path = mp)
    
    va.addAlias('cosa', 'cosAngleBetweenMomentumAndVertexVector')
    va.addAlias('cosaXY', 'cosAngleBetweenMomentumAndVertexVectorInXYPlane')
    va.addAlias('abs_dM', 'abs(dM)')
    va.addAlias('M_noupdate', 'extraInfo(M_noupdate)')
    va.addAlias('p_noupdate', 'extraInfo(p_noupdate)')
    
    ntuple = ['M', 'p', 'chiProb', 'cosa', 'cosaXY', 'dr', 'dz', 'distance', 'isSignal', 'genMotherPDG']
    ntuple += ['IPX', 'IPY', 'IPZ']
    ntuple += create_aliases_for_selected(['protonID', 'pionID', 'dr', 'dz', 'p', 'isSignal'],
                                          'Sigma+ -> ^p+ pi0', prefix = ['p'])
    'nECLClusters',
    'nKLMClusters',
    # 'R2EventLevel',
    # Training labels
    'eventExtraInfo(smartBKG)',
]


if __name__ == '__main__':

    args = GetCmdArgs()
    os.makedirs(os.path.dirname(args.out_file), exist_ok=True)

    # Load the input skim file
    path = ma.create_path()
    ma.inputMdstList('MC9', filelist=[], path=path)
    # ma.inputMdstList('default', filelist=[], path=path)

    ma.applyCuts(particle_list, 'nCleanedTracks(dr<2 and abs(dz)<4) <= 12', path=path)

    print(event_vars)

    # Apply the smartBKG NN model
    # Will use extraInfo saved as training labels later,
    # need to be flattened before training to 0 or 1
    NNApplyModule_m = NNApplyModule(
        model_file=args.model,
        model_type='combined-wideCNN',
        threshold=0.,
        # threshold=args.threshold,
        extra_info_var='smartBKG'
Esempio n. 10
0
inputName = [
    'Gen_bbar_gsim-BKGx1-1M-1.root',
    'Gen_bbar_gsim-BKGx1-1M-2.root',
    'Gen_bbar_gsim-BKGx1-1M-3.root',
    'Gen_bbar_gsim-BKGx1-1M-4.root',
    'Gen_bbar_gsim-BKGx1-1M-5.root',
    'Gen_bbar_gsim-BKGx1-1M-6.root',
    'Gen_bbar_gsim-BKGx1-1M-7.root',
    'Gen_bbar_gsim-BKGx1-1M-8.root',
    'Gen_bbar_gsim-BKGx1-1M-9.root',
    'Gen_bbar_gsim-BKGx1-1M-10.root',
]
outputName = 'testSkimming_BBbar-10M-1.root'

# load files
inputMdstList(inputName)

# create lists of FSPs
pions = ('pi+:all', '')
kaons = ('K+:all', '')

fillParticleListsFromMC([pions, kaons], True)

# reconstruct phi and K_S0
reconstructDecay('phi:all -> K+:all K-:all', 'M < 1.3')
reconstructDecay('K_S0:all -> pi+:all pi-:all', '0.4 < M < 0.6')

# recostruct a B candidate out of those
reconstructDecay('B0:all -> phi:all K_S0:all', '5.0 < M < 5.5')

# add SkimFilter module to set condition variable based on the number of reconstructed B-tag mesons
Esempio n. 11
0
import variables.collections as vc
import variables.utils as vu

# filenumber = sys.argv[1]

# set analysis global tag
b2.use_central_database("analysis_tools_release-04-02")

# create path
main = b2.Path()

# load input data from mdst/udst file
filedirectory = '/gpfs/group/belle2/users/seemac/Kstll/signal/BtoKstjpsi/kst0jpsi'
ma.inputMdstList(
    environmentType='default',
    filelist=[
        f'{filedirectory}/mdst_000001_prod00012871_task10020000001.root'
    ],
    path=main)
# fill final state particle lists
impactcut = 'abs(d0)<2.0 and abs(z0)<5.0 '
ma.fillParticleList(decayString='e+:uncorrected',
                    cut=impactcut + ' and electronID > 0.5',
                    path=main)
stdV0s.stdKshorts(path=main)

# apply Bremsstrahlung correction to electrons
variables.addAlias("goodFWDGamma",
                   "passesCut(clusterReg == 1 and clusterE > 0.075)")
variables.addAlias("goodBRLGamma",
                   "passesCut(clusterReg == 2 and clusterE > 0.05)")
variables.addAlias("goodBWDGamma",
Esempio n. 12
0
import modularAnalysis as ma
import variables.collections as vc
import vertex as vx
from beamparameters import add_beamparameters

b2.logging.log_level = b2.LogLevel.DEBUG

b2.conditions.prepend_testing_payloads('localdb/database.txt')


path = b2.create_path()




ma.inputMdstList("default", [input_file], path=path)


print(b2.conditions.globaltags)

# Book charged Kaons and Pions
from stdCharged import stdK, stdPi
stdK("higheff",  path=path)
stdPi("higheff", path=path)

# Reconstruct D0 decay
ma.reconstructDecay('D0:my -> K-:higheff pi+:higheff', cut='1.75 < M < 1.95', path=path)

# Reconstruct D* decay
ma.reconstructDecay('D*+:my -> D0:my pi+:higheff', cut='1.90 < M < 2.25' , path=path)
Esempio n. 13
0
]
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)
modularAnalysis.fillParticleLists([(p, '') for p in particles], path=path)

for p in particles:
    child_vars = []
    for d in detectors:
        for p_2 in particles:
            child_vars += [
                'pidLogLikelihoodValueExpert(' + str(pdg.from_name(p_2)) +
                ', ' + str(d) + ')'
            ]
            child_vars += [
                'pidProbabilityExpert(' + str(pdg.from_name(p_2)) + ', ' +
                str(d) + ')'
            ]
Esempio n. 14
0
import basf2 as b2
import modularAnalysis as ma
import variables.collections as vc
import variables.utils as vu
import stdCharged as stdc
from stdPi0s import stdPi0s

# create path
my_path = b2.create_path()

# load input ROOT file
ma.inputMdstList(environmentType='default',
                 filelist=[
                     b2.find_file('B2pi0D_D2hh_D2hhh_B2munu.root', 'examples',
                                  False),
                     b2.find_file('ccbar_background.root', 'examples', False)
                 ],
                 path=my_path)

# Apply a selection at the event level, to avoid
# processing useless events
ma.applyEventCuts(cut='R2EventLevel < 0.3', path=my_path)

# The following lines cut&pasted from A304

# create and fill final state ParticleLists
# use standard lists
# creates "pi+:loose" ParticleList (and c.c.)
stdc.stdPi(listtype='loose', path=my_path)
# creates "K+:loose" ParticleList (and c.c.)
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