示例#1
0
def get_lifetime_weight(tree, ctau, ctau_MC):
    if len(tree.Rhadron_properdecaytime) != 2:
        #print('vector size of Rhadron_properdecaytime is not 2. return weight=0.')
        return 0
    dt1 = tree.Rhadron_properdecaytime[0] * 1e-9  # [ns]->[s]
    dt2 = tree.Rhadron_properdecaytime[1] * 1e-9  # [ns]->[s]
    tau = ctau / TMath.C()
    tau_MC = ctau_MC / TMath.C()
    weight_rhad1 = tau_MC / tau * TMath.Exp(dt1 / tau_MC - dt1 / tau)
    weight_rhad2 = tau_MC / tau * TMath.Exp(dt2 / tau_MC - dt2 / tau)
    return weight_rhad1 * weight_rhad2
示例#2
0
def fill_ntuple():
    print('*** starting fill_ntuple() ')
    AtlasStyle.SetAtlasStyle()

    #    # get key list
    #    tfile = TFile(BasicConfig.workdir + 'systTree.root')
    #    key_list_all = [key.GetName() for key in gDirectory.GetListOfKeys()]
    #    regex = re.compile('PRW|JET|MET.*')
    #    key_list = [key for key in key_list_all if re.match(regex, key)]
    #    tfile.Close()

    # start making ttree
    #output_tfile = TFile('rhadron_v06-00-05.root', 'recreate')
    output_tfile = TFile(args.outputFile, 'recreate')

    # initialize TTree
    tree = TTree('rhadron', 'tree of rhadron properties for limit setting')
    # leaf variables
    from array import array
    mass_gluino = array('f', [0.])
    delta_mass = array('f', [0.])
    ctau = array('f', [0.])
    eff = array('f', [0.])
    eff_stat_error = array('f', [0.])
    eff_syst_error = array('f', [0.])
    eff_syst_error_ISR = array('f', [0.])
    eff_syst_error_PRW = array('f', [0.])
    eff_syst_error_JET = array('f', [0.])
    eff_syst_error_MET = array('f', [0.])
    # set branch
    tree.Branch("mGluino", mass_gluino, 'mGluino/F')
    tree.Branch("deltaM", delta_mass, 'deltaM/F')
    tree.Branch("ctau", ctau, 'ctau/F')
    tree.Branch("eff", eff, 'eff/F')
    tree.Branch("effRelStatErr", eff_stat_error, 'effRelStatErr/F')
    tree.Branch("effRelSystErr", eff_syst_error, 'effRelSystErr/F')
    tree.Branch("effRelSystErrISR", eff_syst_error_ISR, 'effRelSystErrISR/F')
    tree.Branch("effRelSystErrPRW", eff_syst_error_PRW, 'effRelSystErrPRW/F')
    tree.Branch("effRelSystErrJET", eff_syst_error_JET, 'effRelSystErrJET/F')
    tree.Branch("effRelSystErrMET", eff_syst_error_MET, 'effRelSystErrMET/F')

    #directory = '/afs/cern.ch/work/k/kmotohas/DisplacedVertex/DV_xAODAnalysis/submitDir_LSF/mc/hist_DVPlusMETSys/'
    #directory = BasicConfig.workdir + 'hist_DVPlusMETSys/'
    #directory = '/home/motohash/data/mc15_13TeV/DVPlusMETSys/v06-00-05/'

    #tfile = TFile(args.referenceFile)
    tfile = TFile(args.inputFile)
    key_list_all = [key.GetName() for key in gDirectory.GetListOfKeys()]
    print(len(key_list_all), key_list_all)
    regex = re.compile('Nominal|PRW|JET|MET.*')
    key_list = [key for key in key_list_all if re.match(regex, key)]
    print(len(key_list), key_list)
    tfile.Close()
    #c = 299792458.  # [m/s]
    #tchains = [[dsid, TChain('Nominal', str(dsid))] for dsid in range(402700, 402740)]
    #tchains = [[dsid, TChain('Nominal', str(dsid))] for dsid in mc.parameters.keys()]
    #tchains = [[dsid, [TChain(key, key+str(dsid)) for key in key_list]] for dsid in mc.parameters.keys()]
    dsids = [args.DSID]
    tchains = [[dsid, [TChain(key, key + str(dsid)) for key in key_list]]
               for dsid in dsids]

    cut_flow = [
        'Initial', 'Trigger', 'Filter', 'Cleaning', 'GRL', 'PV', 'NCB veto',
        'MET', 'DV Selection'
    ]
    #systematic_tables = TFile('systematic_summary_SimpleMETFilter.root', 'open')
    #table = TH1F()

    m_MET_min = 250.

    # loop over dsid
    try:
        for dsid, each_tchain in tchains:
            print('')
            print(dsid)
            #index = 0
            #for input in glob(directory + 'systTree_' + str(dsid) + '_*.root'):
            for tchain in each_tchain:
                #for input_file in glob(directory+'systTree_mc15_13TeV.' + str(dsid) + '*.root'):
                #    print(input_file)
                #    tchain.Add(input_file)
                tchain.Add(args.inputFile)

            mass_gluino[0] = mc.parameters[dsid]['g']
            delta_mass[0] = mass_gluino[0] - mc.parameters[dsid]['chi0']
            n_reweight_steps = 40
            xmin = 1.
            xmax = 10000.
            ratio = xmax / xmin
            bins = []
            for ii in range(n_reweight_steps):
                bins.append(
                    xmax *
                    10**(ii * TMath.Log10(xmax / xmin) / n_reweight_steps -
                         TMath.Log10(xmax / xmin)))
            #n_passed_w1 = [0. for _ in range(n_reweight_steps)]
            #n_passed = [0. for _ in range(n_reweight_steps)]
            from array import array
            limitsLifetime = array('d', bins)
            #
            tefficiency = [[
                TEfficiency('tefficiency_{0}_{1}_{2}'.format(key, step, dsid),
                            ';c#tau [mm]; Event-level efficiency',
                            len(limitsLifetime) - 1, limitsLifetime)
                for step in range(n_reweight_steps)
            ] for key in key_list]
            #h_syst_diff = [[TH1F('syst_diff_{0}_{1}_{2}'.format(key, step, dsid), ';;(N_{shifted} - N_{nominal}) / N_{nominal}', len(key_list)+1, 0, len(key_list)+1)
            #                for step in range(n_reweight_steps)] for key in key_list]
            h_syst_diff = [
                TH1F('syst_diff_{0}_{1}_{2}'.format(key, step, dsid),
                     ';;(N_{shifted} - N_{nominal}) / N_{nominal}',
                     len(key_list) + 1, 0,
                     len(key_list) + 1) for step in range(n_reweight_steps)
            ]

            for step in range(n_reweight_steps):
                for jj, key in enumerate(key_list):
                    h_syst_diff[step].GetXaxis().SetBinLabel(jj + 1, key)
                h_syst_diff[step].GetXaxis().SetBinLabel(
                    len(key_list) + 1, 'ISR_Py2MG_SF_removed')
            n_events_weighted = [[0. for _ in range(n_reweight_steps)]
                                 for key in key_list]
            n_events_weighted_noISR = [[0. for _ in range(n_reweight_steps)]
                                       for key in key_list]

            # loop over tchain of each systematic
            for ii, tchain in enumerate(each_tchain):
                entries = tchain.GetEntries()
                print('*** processed systs: {0} / {1}'.format(
                    ii, len(each_tchain)))
                #n_reweight_steps = 50
                #for step in range(n_reweight_steps):
                #    tefficiency.append(TEfficiency('tefficiency_'+str(step), ';c#tau [mm]; Event-level efficiency',
                #                                   len(limitsLifetime)-1, limitsLifetime))
                #    h_syst_diff.append(TH1F('syst_diff_'+str(step), ';;(N_{shifted} - N_{nominal}) / N_{nominal}', len(key_list)+1, 0, len(key_list)+1))
                for step in range(n_reweight_steps):
                    tefficiency[ii][step].SetUseWeightedEvents()
                    #for jj, key in enumerate(key_list):
                    #     h_syst_diff[ii][step].GetXaxis().SetBinLabel(jj+1, key)
                    #h_syst_diff[ii][step].GetXaxis().SetBinLabel(len(key_list)+1, 'ISR_Py2MG_SF_removed')
                #    h_syst_diff[step].SetMinimum(-0.3)
                #    h_syst_diff[step].SetMaximum(0.3)
                if entries == 0:
                    continue
                for entry in range(entries):
                    #if entry % 1000 == 0:
                    #    print('* processed events: {0} / {1}'.format(entry, entries))
                    utils.show_progress(entry, entries)
                    #if entry == 605:
                    #    break
                    # get the next tree in the chain and verify
                    ientry = tchain.LoadTree(entry)
                    if ientry < 0:
                        break
                    # copy next entry into memory and verify
                    nb = tchain.GetEntry(entry)
                    if nb <= 0:
                        continue
                    event_weight = tchain.McEventWeight * tchain.PileupWeight * tchain.ISRWeight
                    ctau_MC = TMath.C(
                    ) * mc.parameters[dsid]['t'] * 1e-9  # [nm]->[m]
                    for step in range(n_reweight_steps):
                        #print(tchain.GetListOfBranches())
                        pass_all = pass_event_cut(tchain, len(cut_flow) - 1)
                        if pass_all:
                            matched = False
                            for idv in range(len(tchain.DV_x)):
                                matched = matched or match(
                                    tchain, idv, cut=1.0)
                            #print('pass_all is ', pass_all, ', matched is ', matched)
                            pass_all = pass_all and matched
                        target_ctau = xmax * 10**(
                            step * TMath.Log10(xmax / xmin) / n_reweight_steps
                            - TMath.Log10(xmax / xmin)) * 1e-3  # [mm]->[m]
                        #print(target_ctau)
                        lifetime_weight = get_lifetime_weight(
                            tchain, target_ctau, ctau_MC)
                        n_events_weighted[ii][
                            step] += event_weight * lifetime_weight
                        n_events_weighted_noISR[ii][
                            step] += tchain.McEventWeight * tchain.PileupWeight * lifetime_weight
                        #print(event_weight)
                        #print(event_weight*lifetime_weight)
                        #print(pass_all)
                        tefficiency[ii][step].FillWeighted(
                            pass_all, event_weight * lifetime_weight,
                            target_ctau * 1e3)
                # end of loop over entries of each TChain
            # end loop over tchain of each systematic
            for step in range(n_reweight_steps):
                n_events_nominal = [0. for _ in range(n_reweight_steps)]
                for ii in range(len(each_tchain)):
                    # if Nominal TTree, set syst diff of ISR as well
                    if ii == 0:
                        n_events_nominal[step] = n_events_weighted[ii][step]
                        if n_events_nominal[step] < 1e-4:
                            #h_syst_diff[ii][step].SetBinContent(len(key_list)+1, 0)
                            h_syst_diff[step].SetBinContent(
                                len(key_list) + 1, 0)
                        else:
                            #h_syst_diff[ii][step].SetBinContent(len(key_list)+1,
                            h_syst_diff[step].SetBinContent(
                                len(key_list) + 1,
                                float((n_events_weighted_noISR[ii][step] -
                                       n_events_nominal[step]) /
                                      n_events_nominal[step]))
                            #float((n_events_weighted[ii][step]-n_events_nominal[step])/n_events_nominal[step]))
                    diff = n_events_weighted[ii][step] - n_events_nominal[step]
                    #print(n_events_nominal, n_events_weighted, diff)
                    if n_events_nominal[step] < 1e-4:
                        #h_syst_diff[ii][step].SetBinContent(ii+1, 0)
                        h_syst_diff[step].SetBinContent(ii + 1, 0)
                    else:
                        #h_syst_diff[ii][step].SetBinContent(ii+1, float(diff/n_events_nominal[step]))
                        h_syst_diff[step].SetBinContent(
                            ii + 1, float(diff / n_events_nominal[step]))
                    #systematic_tables.GetObject('systematic_table_'+str(dsid), table)
                    #syst_up, syst_down = root_sum_squares(table, 'x')
                #systs = root_sum_squares(h_syst_diff[ii][step], 'x')
                systs = root_sum_squares(h_syst_diff[step], 'x')
                #eff_syst_error[0] = max(syst_up, syst_down)  # TODO
                #eff_syst_error[0] = (syst_up**2 + syst_down**2)**0.5

                ####    ############################
                eff_syst_error[0] = (systs[0]**2 + systs[1]**2)**0.5
                eff_syst_error_ISR[0] = systs[2]
                eff_syst_error_PRW[0] = systs[3]
                eff_syst_error_JET[0] = systs[4]
                eff_syst_error_MET[0] = systs[5]
                if eff_syst_error[0] > 1:
                    print('eff_syst_error[0] = ' + str(eff_syst_error[0]))
                    #eff_syst_error[0] = 1.
                #for step in range(n_reweight_steps):
                #for ct in bins:
                #    print(len(bins), bins)
                #print(n_total_w1[step], n_total[step])
                #sf =  n_total_w1[step] / n_total[step]
                #n_passed[step] *= sf
                #n_total[step] *= sf
                #eff_no_weight, stat_error_no_weight = utils.division_error_propagation(n_passed_w1[step], n_total_w1[step])
                #ctau[0] = TMath.Power(300, step/float(n_reweight_steps-1)) * 1e-3  # [mm]->[m]
                ct = bins[step]
                #print(ct)
                ctau[0] = ct * 1e-3  # [mm]->[m]
                #print(ctau[0])
                bin_ctau = tefficiency[0][step].GetPassedHistogram().FindBin(
                    ct)
                print(tefficiency[0][step].GetPassedHistogram().GetBinContent(
                    bin_ctau))
                print(tefficiency[0][step].GetTotalHistogram().GetBinContent(
                    bin_ctau))
                #print(bin_ctau)
                #print('ct', ct, 'bin_ctau', bin_ctau)
                eff[0] = tefficiency[0][step].GetEfficiency(bin_ctau)
                print(eff[0])
                abs_stat_error = (
                    tefficiency[0][step].GetEfficiencyErrorLow(bin_ctau)**2 +
                    tefficiency[0][step].GetEfficiencyErrorUp(bin_ctau)**
                    2)**0.5
                #eff[0], abs_stat_error = utils.binomial_ratio_and_error(n_passed[step], n_total[step])
                #if eff[0] < 1e-4:
                if eff[0] == 0:
                    eff_stat_error[
                        0] = 1.  # avoid zero division error and divergence
                    continue  # not fill values in tree if efficiency is too small
                else:
                    eff_stat_error[0] = abs_stat_error / eff[0]
                #if eff_stat_error[0] > 1:
                #    print(n_passed[step], n_total[step], abs_stat_error, eff[0], eff_stat_error[0])
                #    eff_stat_error[0] = 1.
                tree.Fill()
            # end loop over n_reweight_steps
    except KeyboardInterrupt:
        pass
    output_tfile.Write()
    output_tfile.Close()
示例#3
0
    def GetTuple(self, chain):

        print(
            " ----> The following general mask will be applyied to the chain : \n"
        )
        print('-- muon : {}'.format(
            self.filter_mask['daughter_mask'].split('**')))
        print('-- Jpsi : {}'.format(
            self.filter_mask['mother_mask'].split('**')))
        print('-- other : {}'.format(self.filter_mask['other'].split('**')))
        print("\n *** You may also want to check \n"
              " *** AnnaTupleFilterJpsiPbPbV2::IsInLuminosityRegion() \n"
              " *** and AnnaTupleFilterJpsiPbPbV2::IsMuonsGhosts() \n"
              " *** where other cuts are also defined \n")

        ntuple = self.CreateTuple()
        okBranch = self.CheckChainBranch(chain)
        if okBranch is False:
            error(' attributes are missing')
            return None

        # counters
        entry_number = 0
        entry_exlude = 0
        tot_entries = chain.GetEntriesFast()
        muon_all = list()

        print(' --- Start running over events ...')
        with ProgressBar(max_value=tot_entries, silent=False) as bar:
            for entry in chain:
                entry_number += 1
                bar.update_amount(entry_number)

                ok_lumi, v_OWNPV, v_ENDVERTEX = self.IsInLuminosityRegion(
                    entry_number, entry)
                if ok_lumi is False:
                    info("entry {} does not pass the luminosity cut".format(
                        entry_number))
                    entry_exlude += 1
                    continue

                ok_muon = self.PassMuonCuts(entry_number, entry)
                if ok_muon is False:
                    info("entry {} do not pass muons cut".format(entry_number))
                    entry_exlude += 1
                    continue

                # Check muon ghost probability
                is_ghost = self.IsMuonsGhosts(entry_number, entry, muon_all)
                if is_ghost is True:
                    info("entry {} most likely have ghosts".format(
                        entry_number))
                    entry_exlude += 1
                    continue

                ok_mother = self.PassMuonCuts(entry_number, entry)
                if ok_mother is False:
                    info(
                        "entry {} do not pass mother cut".format(entry_number))
                    entry_exlude += 1
                    continue

                # Prepare Data
                rho = v_OWNPV.Perp()
                v_OWNPV -= v_ENDVERTEX
                dZ = (getattr(entry, self.mother_leaf + '_ENDVERTEX_Z') -
                      getattr(entry, self.mother_leaf + '_OWNPV_Z')) * 1e-3
                tZ = dZ * 3096.916 / (
                    getattr(entry, self.mother_leaf + '_PZ') * TMath.C())

                ntuple.Fill(getattr(entry, self.mother_leaf + '_MM'),
                            getattr(entry, self.mother_leaf + '_PT'),
                            getattr(entry, self.mother_leaf + '_Y'),
                            getattr(entry, self.mother_leaf + '_OWNPV_Z'),
                            v_OWNPV.Mag(), dZ, tZ,
                            getattr(entry, self.dimuon_leafs[0] + '_PIDmu'),
                            getattr(entry, self.dimuon_leafs[1] + '_PIDmu'),
                            getattr(entry, self.dimuon_leafs[0] + '_PIDK'),
                            getattr(entry, self.dimuon_leafs[1] + '_PIDK'),
                            getattr(entry, 'eHcal'), getattr(entry, 'eEcal'),
                            getattr(entry, 'nVeloClusters'))

        print(
            ' --- Done ! Ran over {} events with {:.1f}% removed from cuts !'.
            format(entry_number,
                   float(entry_exlude) / float(entry_number) * 100))
        return ntuple
示例#4
0
def generateEvents( outputFileName, nEvents ):
    
    random = TRandom3( 12345 )
    
    # define a particle source
    sourcePosition = TVector3( 0., 0., 0. )
    sourceSpreadXY = 10.
    pdgid = 13
    charge = -1.
    mass = 0.105658
    momentum = TVector3( 0.3, 0.1, 10. )
    runNumber = 321
    
    # define a detector with positions for the tracker planes
    detectorName = 'ToyTracker'
    trackerPlanePositions = []
    hitResolution = 0.01
    planeNormal = TVector3( 0., 0., 1. )
    for planeZ in [ 100., 250., 480., 510., 640. ]:
        trackerPlanePositions.append( TVector3( 0., 0., planeZ ) )
    
    # create a writer and open the output file
    writer = IOIMPL.LCFactory.getInstance().createLCWriter()
    writer.open( outputFileName, EVENT.LCIO.WRITE_NEW )
    
    # create a run header and add it to the file (optional)
    run = IMPL.LCRunHeaderImpl()
    run.setRunNumber( runNumber )
    run.setDetectorName( detectorName )
    run.setDescription( 'This is a test run' )
    writer.writeRunHeader( run )
    
    for iEvent in xrange( nEvents ):
        
        # create an event and set its parameters
        event = IMPL.LCEventImpl()
        event.setEventNumber( iEvent )
        event.setDetectorName( detectorName )
        event.setRunNumber( runNumber )
        event.setTimeStamp( int( time() * 1000000000. ) )
        
        # create the mc particle collection
        mcParticles = IMPL.LCCollectionVec( EVENT.LCIO.MCPARTICLE )
        
        # calculate the origin of the particle
        x = random.Gaus( sourcePosition.x(), sourceSpreadXY )
        y = random.Gaus( sourcePosition.y(), sourceSpreadXY )
        z = sourcePosition.z()
        origin = TVector3( x, y, z )
        
        # create a particle
        mcParticle = IMPL.MCParticleImpl()
        mcParticle.setPDG( pdgid )
        mcParticle.setMass( mass )
        mcParticle.setMomentumVec( momentum )
        mcParticle.setGeneratorStatus( 1 )
        mcParticle.setVertexVec( origin )
        mcParticle.setTime( 0. )
        mcParticles.addElement( mcParticle )
        
        # create a tracker hit collection
        trackerHits = IMPL.LCCollectionVec( EVENT.LCIO.SIMTRACKERHIT )
        trackerHits.setFlag( UTIL.set_bit( trackerHits.getFlag(), EVENT.LCIO.THBIT_MOMENTUM ) )
        
        # create an IDEncoder to store hit IDs
        # defines the tags and the number of bits for the different bit fields
        encodingString = 'system:3,layer:6'
        idEncoder = UTIL.CellIDEncoder( IMPL.SimTrackerHitImpl )( encodingString, trackerHits )
        
        # add a hit for each layer
        for planePosition in trackerPlanePositions:
            # calculate the intersection with the plane
            distance = ( planePosition - origin ).Dot( planeNormal ) / momentum.Dot( planeNormal )
            intersect = TVector3( momentum )
            intersect.SetMag( distance )

            # smear the hit position with the resolution            
            hitX = random.Gaus( intersect.x(), hitResolution )
            hitY = random.Gaus( intersect.x(), hitResolution )
            hitPosition = TVector3( hitX, hitY, intersect.z() )
            
            # build the tracker hit
            trackerHit = IMPL.SimTrackerHitImpl()
            trackerHit.setPositionVec( hitPosition )
            trackerHit.setMomentumVec( momentum )
            trackerHit.setMCParticle( mcParticle )
            trackerHit.setTime( distance / TMath.C() )
            trackerHit.setEDep( 0.1 )
            
            # set the cell ID
            idEncoder.reset()
            idEncoder['layer'] = trackerPlanePositions.index( planePosition )
            idEncoder['system'] = 1
            idEncoder.setCellID( trackerHit )
            
            trackerHits.addElement( trackerHit )
        
        event.addCollection( mcParticles, EVENT.LCIO.MCPARTICLE )
        event.addCollection( trackerHits, 'SimTrackerHits' )
        
        writer.writeEvent( event )
    
    writer.flush()
    writer.close()
示例#5
0
#chargino tau values in cm
lifetimes = [
    '2', '3', '4', '5', '6', '7', '8', '9', '10', '20', '30', '40', '50', '60',
    '70', '80', '90', '100', '200', '300', '400', '500', '600', '700', '800',
    '900', '1000', '2000', '3000', '4000', '5000', '6000', '7000', '8000',
    '9000', '10000'
]

convertCmToNs = True
makeColorPlot = False
convertToMassSplitting = False
outputName = "limit_plot.root"
#yAxisRangeFor1DMassLimits = [0.01, 10000]
yAxisRangeFor1DMassLimits = [5.0e-3, 2.0e3]

speedLightCmPerNs = TMath.C() * 1.0e-7
convertToNs = (lambda a: round(a / speedLightCmPerNs, 2))

# description of all the plots to be made
plotDefinitions = [

    #each entry corresponds to a canvas in the output file

    ######################LIFETIME (ns) VS MASS
    {
        # this will be the name of the canvas in the output root file
        'title':
        'lifetime_vs_mass',

        # current options are 'mass' and 'lifetime'
        'xAxisType':
    def GetTuple(self, chain):
        """The main method of the class

		Here the class run in all events in the tree/chain
		and return a filled new tuple for events passing the
		selection

		Arguments:
			chain {TChain}

		Returns:
			TNtuple
		"""

        general_mask = self.GetGeneralMask()
        print(
            " ----> The following general mask will be applyied to the chain : \n"
        )
        print('-- muon_mask : {}'.format(
            self.filter_mask['muon_mask'].split('**')))
        print('-- mother_mask : {}'.format(
            self.filter_mask['mother_mask'].split('**')))
        print('-- other : {}'.format(self.filter_mask['other'].split('**')))
        print("\n *** You may also want to check \n"
              " *** AnnaTupleFilterD0PbPb::IsInLuminosityRegion() \n"
              " *** and AnnaTupleFilterD0PbPb::IsMuonsGhosts() \n"
              " *** where other cuts are also defined \n")

        if general_mask is None:
            error(':GetTuple: Cannot get the mask')
            return None

        ntuple = self.CreateTuple()
        okBranch = self.CheckChainBranch(chain)
        if okBranch is False:
            error(' attributes are missing')
            return None

        # counters
        entry_number = 0
        entry_exlude = 0
        muon_all = list()

        print(' --- Start running over events ...')
        for entry in chain.withCuts(general_mask, progress=True):
            entry_number += 1

            # Check the vertex position
            ok_lumi, v_OWNPV, v_ENDVERTEX = self.IsInLuminosityRegion(
                entry_number, entry)
            if ok_lumi is False:
                info("entry {} does not pass the luminosity cut".format(
                    entry_number))
                entry_exlude += 1
                continue

            # Check muon ghost probability
            is_ghost = self.IsMuonsGhosts(entry_number, entry, muon_all)
            if is_ghost is True:
                info("entry {} most likely have ghosts".format(entry_number))
                entry_exlude += 1
                continue

            # Prepare Data
            v_OWNPV -= v_ENDVERTEX
            dZ = (getattr(entry, self.mother_leaf + '_ENDVERTEX_Z') -
                  getattr(entry, self.mother_leaf + '_OWNPV_Z')) * 1e-3
            tZ = dZ * 3096.916 / (getattr(entry, self.mother_leaf + '_PZ') *
                                  TMath.C())

            ntuple.Fill(getattr(entry, self.mother_leaf + '_MM'),
                        getattr(entry, self.mother_leaf + '_PT'),
                        getattr(entry, self.mother_leaf + '_Y'),
                        getattr(entry, self.mother_leaf + '_OWNPV_Z'),
                        v_OWNPV.Mag(), dZ, tZ,
                        getattr(entry, self.dimuon_leafs[0] + '_PIDmu'),
                        getattr(entry, self.dimuon_leafs[1] + '_PIDmu'),
                        getattr(entry, self.dimuon_leafs[0] + '_PIDK'),
                        getattr(entry, self.dimuon_leafs[1] + '_PIDK'),
                        getattr(entry, 'eHcal'), getattr(entry, 'eEcal'),
                        getattr(entry, 'nVeloClusters'))

        print(
            ' --- Done ! Ran over {} events with {:.1f}% removed from cuts !'.
            format(entry_number,
                   float(entry_exlude) / float(entry_number) * 100))
        return ntuple
#!/usr/bin/env python

from DisappTrks.LimitSetting.limitOptions import *
from DisappTrks.LimitSetting.winoElectroweakLimits import *

from ROOT import TMath

convertCmToNs = True
outputName = "limit_plots.root"
yAxisRangeFor1DMassLimits = [1.e-3, 1.e3]

roundLumiText = True

speedLightCmPerNs = TMath.C() * 1.0e-7
convertToNs = (lambda a: round(a / speedLightCmPerNs, 2))

showObserved = True

theoryComments = [
    'tan #beta = 5, #mu > 0',
    'pp #rightarrow #tilde{#chi}^{#pm}_{1}#tilde{#chi}^{#mp}_{1}, wino-like #tilde{#chi}_{0}'
]

# description of all the plots to be made
plotDefinitions = [

    #each entry corresponds to a canvas in the output file

    ######################LIFETIME (ns) VS MASS
    {
        # this will be the name of the canvas in the output root file
示例#8
0
                  "goff")

bragg_max = events_inside_hist.GetMean()

try:
    args = (p, n, b, bragg_max)
    retcode = subprocess.call("my_bragg_400 dati/%i_ %i %i %f" % args,
                              shell=True)
    if retcode < 0:
        print("Child was terminated by signal", -retcode, file=sys.stderr)
    else:
        print("Child returned", retcode, file=sys.stderr)
except OSError, e:
    print("Execution failed:", retcode, file=sys.stderr)

bragg_new = Bragg.Bragg(p)
events_escaped_can = TCanvas("escaped_can", "escaped_can")
events_escaped_hist = TH1S("escaped", "escaped", 30, 30, 60)
bragg.ntuple.Draw("deltaT>>escaped", "maxC < 149 && integr > 5000")

distance = 11e-2
escape_time = events_escaped_hist.GetMean() * 1e-7

b_600 = Bragg.Bragg(600)
b_600.ntuple.Draw("energy_fraction", b_600.spectral_lines[0])
print(escape_time)

electron_beta = distance / escape_time / TMath.C()
print(electron_beta)
raw_input()