Пример #1
0
def flukaRateIntegrated(save=False):
    fntuple = ROOT.TFile.Open('neutronsTI18.root')
    h['Fig12'] = ROOT.TGraph()
    h['neutronRate'] = ROOT.TGraph()
    h['N'] = ROOT.TGraph()
    n = 0
    for nt in fntuple.nt:
        # nt.N  = [cm/MeV]
        E = (nt.Eleft + nt.Eright) / 2.
        dE = nt.Eright - nt.Eleft
        h['Fig12'].SetPoint(n, ROOT.TMath.Log10(E), E * nt.N)
        h['neutronRate'].SetPoint(n, ROOT.TMath.Log10(E), dE * nt.N)
        h['N'].SetPoint(n, E, dE * nt.N)
        n += 1
    S = 0
    h['neutronRate<E'] = h['neutronRate'].Clone('S')
    for n in range(h['neutronRate'].GetN() - 1, -1, -1):
        S += h['neutronRate'].GetY()[n]
        h['neutronRate<E'].SetPoint(n, h['neutronRate'].GetX()[n], S)
    h['neutronRate<E%'] = h['neutronRate'].Clone('S%')
    for n in range(h['neutronRate<E'].GetN()):
        h['neutronRate<E%'].SetPoint(
            n, h['neutronRate<E'].GetX()[n],
            h['neutronRate<E'].GetY()[n] / h['neutronRate<E'].GetY()[0])
    ut.bookHist(h, 'Nr', ';E [MeV];dn/dlogE [cm^{-2}y^{-1}] ', 100, -12., 2.)
    h['Nr'].SetMaximum(1.1)
    h['Nr'].SetMinimum(0.)
    h['Nr'].SetStats(0)
    h['Nr'].SetTitle('; log10(E [MeV]();N(E>x)/total')
    h['neutronRate<E%'].SetLineWidth(2)
    h['Nr'].Draw()
    h['neutronRate<E%'].Draw('same')
    if save: ut.writeHists(h, 'flukaNeutronRates')
Пример #2
0
def analyzePionBeam(fn,pid=[411]):
 f = ROOT.TFile(fn)
 sTree=f.pythia6
 for n in range(sTree.GetEntries()):
   rc = sTree.GetEvent(n)
   si =  str(sTree.id)
   if not h.has_key(si): 
     ut.bookHist(h,si,PDG.GetParticle(int(sTree.id)).GetName()+' xF',25,0.,1.) 
   rc = h[si].Fill(sTree.xf)
 if 1>0:
   ROOT.gROOT.cd()
   first = True 
   col = 2
   for x in h:
    nx = int(float(x))
    if nx<0 or nx not in pid: continue
    A['asym'+x]=h[x].Clone('asym'+x)
    temp=h[x].Clone('temp')
    A['asym'+x].Sumw2() 
    temp.Sumw2() 
    A['asym'+x].SetTitle(PDG.GetParticle(nx).GetName()+' asymmetry as function of xF')
    A['asym'+x].Add(h['-'+x],-1.)
    temp.Add(h['-'+x],1.)
    A['asym'+x].Divide(temp)
    A['asym'+x].SetLineColor(col)
    A['asym'+x].SetMaximum(1)
    A['asym'+x].SetMinimum(-1)
    if first: 
     A['asym'+x].Draw()
     first = False
    else: 
     A['asym'+x].Draw('same')
    col+=1
Пример #3
0
def muonSpect():
    inputFiles()
    for x in h["datasets"]:
        for ori in h["cuts"]:
            for p in ["P", "Pt"]:
                hn = x + p + ori
                print "work on histogram", hn
                if p == "P":
                    ut.bookHist(h, hn, "muon momentum " + ori + " " + p, 80, 0.0, 400.0)
                    h[hn].SetYTitle("[N/5GeV/c/spill]")
                    h[hn].SetXTitle("P [GeV/c]")
                else:
                    ut.bookHist(h, hn, "muon momentum " + ori + " " + p, 100, 0.0, 5.0)
                    h[hn].SetYTitle("[N/50MeV/c/spill]")
                    h[hn].SetXTitle("Pt [GeV/c]")
                h[hn].SetStats(0)
                h[hn].SetLineWidth(2)
                ROOT.gROOT.cd()
                sTree = h[x].FindObjectAny("pythia8-Geant4")
                if p == "P":
                    sTree.Draw(
                        "sqrt(px*px+py*py+pz*pz)>>" + hn, "w*(" + h["cuts"][ori] + "&&sqrt(px*px+py*py+pz*pz)>0.5)"
                    )
                else:
                    sTree.Draw("sqrt(px*px+py*py)>>" + hn, "w*(" + h["cuts"][ori] + "&&sqrt(px*px+py*py+pz*pz)>0.5)")
    h.pop("datasets")
    h.pop("cuts")
    ut.writeHists(h, "muSpectrum.root")
def afterFirstMagnet(lz=12.):
# assume there is a gap between First and second magnet, like in ..Zpl
# exciting C1orC2 
 zEndOfAbsorb = z0+2*0.25+2*1.50
 sz = str(int(lz))
 hk =  'afterFirstMagnet_XY'+sz
 u.bookHist(h,hk,'afterFirstMagnet XY at z='+sz+'m' ,100,-2.,2.,100,-2.,2.)
 volDict = {}
 for x in dictVol: volDict[dictVol[x]]=x
 t = h['T']
 t.SetEventList(0) 
 ntotal = h['T'].GetEntries() 
 previous = -999
 f = open('afterFirstMagnet.txt','w')
 for i in range( ntotal ):  
  t.GetEntry(i)
  for m in range(t.Nmeas):  
   if (previous == volDict['MagC1'] or previous == volDict['MagC2']) and t.volid[m]==volDict['Snoopy']: 
     line = '%3i %9.5F %9.5F %9.5F %9.5F %9.5F %9.5F %9.5F %9.5F\n'%(
            t.id, TMath.sqrt(t.px[m]**2+t.py[m]**2+t.pz[m]**2),t.px[m],t.py[m],t.pz[m],t.x[m],t.y[m],t.z[m],t.w)
     f.write(line)
     Xf,Yf = extrapXY(zEndOfAbsorb+lz,t.x[m],t.y[m],t.z[m],t.px[m],t.py[m],t.pz[m])
     h[hk].Fill(Xf,Yf,t.w)
   previous = t.volid[m]
 f.close()
Пример #5
0
def runStability(C=None):
    if not C: C = getCalibrationParameters(options.runNumbers)
    runEvol = {1:{},2:{}}
    badChannels = {1:{},2:{}}
    for r in C:
       for s in C[r]:
          for l in C[r][s]:
            for i in C[r][s][l]['mean']:
               value = C[r][s][l]['mean'][i]
               key = l+'_'+str(i)
               rError = value[1] / value[0]
               if rError > 0.05: continue # remove distributions with low statistics
               if not key in runEvol[s]: runEvol[s][key] = ROOT.TGraph()
               n = runEvol[s][key].GetN()
               runEvol[s][key].SetPoint(n,value[0],1.)
          ut.bookHist(h,'rms'+sdict[s],'rms',1000,-1.,1.)
          ut.bookCanvas(h,sdict[s],'',900,600,1,1)
          h[sdict[s]].cd()
          for key in runEvol[s]:
            x = runEvol[s][key].GetRMS()/runEvol[s][key].GetMean()
            rc = h['rms'+sdict[s]].Fill(x)
            if abs(x)>0.2: badChannels[key]=x
            print("%s : %5.2F  %5.2F  %5.2F"%(key,x,runEvol[s][key].GetRMS(),runEvol[s][key].GetMean()))
          h['rms'+sdict[s]+'100']=h['rms'+sdict[s]].Rebin(10,'rms'+sdict[s]+'100')
          h['rms'+sdict[s]+'100'].Draw()
    return runEvol,badChannels
Пример #6
0
def checkLocalPosition(fibresSiPM):
    ut.bookHist(h, 'delta', 'central - weighted', 100, -20., 20.)
    L = localPosition(fibresSiPM)
    sGeo = ROOT.gGeoManager
    SiPMmapVol = sGeo.FindVolumeFast("SiPMmapVol")
    for l in SiPMmapVol.GetNodes():
        n = l.GetNumber()
        ty = l.GetMatrix().GetTranslation()[1]
        delta = ty - L[n]
        rc = h['delta'].Fill(delta * 10 * 1000.)
Пример #7
0
def analyzeCharm(statsOnly=False):
 if not statsOnly:
  f=ROOT.TFile("/media/Data/HNL/ShipSoft/data/Charm/Cascade-parp16-MSTP82-1-MSEL4-ntuple_prod_18M.root")
  #f=ROOT.TFile("ccbar-Mbias-MSEL2-ntuple.root")
  #f = ROOT.TFile("ccbar-Mbias-500gevpiminus-MSEL2-test1M.root")
  sTree=f.pythia6
  for n in range(sTree.GetEntries()):
   rc = sTree.GetEvent(n)
   si =  str(sTree.id)
   if not h.has_key(si): 
     ut.bookHist(h,si,PDG.GetParticle(int(sTree.id)).GetName()+' momentum (GeV)',400,0.,400.) 
     ut.bookHist(h,'p'+si,PDG.GetParticle(int(sTree.id)).GetName()+' momentum (GeV)',400,0.,400.) 
   p = ROOT.TMath.Sqrt(sTree.px*sTree.px+sTree.py*sTree.py+sTree.pz*sTree.pz)
   rc = h[si].Fill(p)
   mpt = ROOT.TMath.Sqrt(sTree.mpx*sTree.mpx+sTree.mpy*sTree.mpy)
   if mpt<1E-5 : rc = h['p'+si].Fill(p)
   #print n,sTree.id,p,mpt,rc,rc1
 if 1>0:
  first = True
  for k in ['','p']:
   print "################################################"
   for x in h:
    if k!='p' and x[0] == 'p': continue
    if k=='p' and x[0] != 'p': continue
    nx = int(float(x.replace('p','')))
    if nx<0: continue
    h[x].SetLineColor(3)
    if first: 
     h[x].Draw()
     first = False
    else: 
     h[x].Draw('same')
    A = h[x].GetEntries()
    print "total:"
    txt = "%14s : %10i"%(PDG.GetParticle(nx).GetName(),A)
    bx = '-'+x 
    if x[0] == 'p': bx = 'p-'+x.replace('p','')
    if h.has_key(bx):
     h[bx].SetLineColor(2)
     h[bx].Draw('same')
     B = h[bx].GetEntries()
     asym = ( A - B ) / float( A + B +1E-10) 
     txt+="  %14s : %10i   asymmetry=%6.3F "%(PDG.GetParticle(-nx).GetName(),B,asym)
    print txt
    t =49
    print "P>50GeV:"
    A = h[x].GetEntries()*(1.-h[x].GetIntegral()[t])
    txt = "%14s : %10i"%(PDG.GetParticle(nx).GetName(),A)
    if h.has_key(bx):
     B = h[bx].GetEntries()*(1.-h[bx].GetIntegral()[t])
     asym = ( A - B ) / float( A + B +1E-10) 
     txt+="  %14s : %10i   asymmetry=%6.3F "%(PDG.GetParticle(-nx).GetName(),B,asym)
    print txt
Пример #8
0
def plotEvent(n):
   rc = sTree.GetEvent(n)
   for c in hitCollection: rc=hitCollection[c][1].Set(0)
   global stereoHits
   stereoHits = []
   ut.bookHist(h,'xz','x (y) vs z',500,0.,1200.,100,-150.,150.)
   if not h.has_key('simpleDisplay'): ut.bookCanvas(h,key='simpleDisplay',title='simple event display',nx=1600,ny=1200,cx=1,cy=0)
   rc = h[ 'simpleDisplay'].cd(1)
   h['xz'].SetMarkerStyle(30)
   h['xz'].SetStats(0)
   h['xz'].Draw('b')
   for hit in sTree.Digi_MufluxSpectrometerHits:
    statnb,vnb,pnb,lnb,view = stationInfo(hit)
    # print statnb,vnb,pnb,lnb,view,hit.GetDetectorID()
    rc = hit.MufluxSpectrometerEndPoints(vbot,vtop)
    if view != '_x':
      stereoHit = ROOT.TGraph()
      stereoHit.SetPoint(0,vbot[2],vbot[0])
      stereoHit.SetPoint(1,vtop[2],vtop[0])
      stereoHits.append(stereoHit)
      continue
    if statnb<3:  
     c = hitCollection['upstream'] 
     rc = c[1].SetPoint(c[0],vbot[2],vbot[0])
     c[0]+=1 
    else:
     c = hitCollection['downstream'] 
     rc = c[1].SetPoint(c[0],vbot[2],vbot[0])
     c[0]+=1
   c = hitCollection['muonTagger'] 
   for hit in sTree.Digi_MuonTaggerHits:
    channelID = hit.GetDetectorID()
    statnb = channelID/10000
    view   = (channelID-10000*statnb)/1000
    channel = channelID%1000
    if view == 1:
    #poor man geometry , probably completly wrong
     x = +rpc[statnb][0] - 2*rpc[statnb][0]/rpcchannels*channel
     rc = c[1].SetPoint(c[0],rpc[statnb][2],x)
     c[0]+=1
   hitCollection['downstream'][1].SetMarkerColor(ROOT.kRed)
   hitCollection['upstream'][1].SetMarkerColor(ROOT.kBlue)
   hitCollection['muonTagger'][1].SetMarkerColor(ROOT.kGreen)
   for c in hitCollection: rc=hitCollection[c][1].SetMarkerStyle(30)
   for c in hitCollection:
     if hitCollection[c][1].GetN()<1: continue
     rc=hitCollection[c][1].Draw('sameP')
     h['display:'+c]=hitCollection[c][1]
   for g in stereoHits:
     g.SetLineWidth(2)
     g.Draw('same')
   h[ 'simpleDisplay'].Update()
Пример #9
0
def analyzeConcrete():
 for m in ['','mu']:
  ut.bookHist(h,'conc_hitz'+m,'concrete hit z '+m,100,-100.,100.)
  ut.bookHist(h,'conc_hity'+m,'concrete hit y '+m,100,-15.,15.)
  ut.bookHist(h,'conc_p'+m,'concrete hit p '+m,100,0.,300.)
  ut.bookHist(h,'conc_pt'+m,'concrete hit pt '+m,100,0.,10.)
  ut.bookHist(h,'conc_hitzy'+m,'concrete hit zy '+m,100,-100.,100.,100,-15.,15.)
 top = fGeo.GetTopVolume()
 magn = top.GetNode("magyoke_1")
 z0 = magn.GetMatrix().GetTranslation()[2]/u.m
 for fn in fchain:
  f = ROOT.TFile(fn)
  if not f.FindObjectAny('cbmsim'): 
   print 'skip file ',f.GetName() 
   continue
  sTree = f.cbmsim
  nEvents = sTree.GetEntries()
  for n in range(nEvents):
   sTree.GetEntry(n)
   wg = sTree.MCTrack[0].GetWeight()   
   for ahit in sTree.vetoPoint:
     detID = ahit.GetDetectorID()
     if logVols[detID] != 'rockD': continue  
     m=''       
     if abs(ahit.PdgCode()) == 13: m='mu'
     h['conc_hitz'+m].Fill(ahit.GetZ()/u.m-z0,wg)
     h['conc_hity'+m].Fill(ahit.GetY()/u.m,wg)
     P = ROOT.TMath.Sqrt(ahit.GetPx()**2+ahit.GetPy()**2+ahit.GetPz()**2)
     h['conc_p'+m].Fill(P/u.GeV,wg)
     Pt = ROOT.TMath.Sqrt(ahit.GetPx()**2+ahit.GetPy()**2)
     h['conc_pt'+m].Fill(Pt/u.GeV,wg)
     h['conc_hitzy'+m].Fill(ahit.GetZ()/u.m-z0,ahit.GetY()/u.m,wg)
 #
     start = [ahit.GetX()/u.m,ahit.GetY()/u.m,ahit.GetZ()/u.m]
     direc = [-ahit.GetPx()/P,-ahit.GetPy()/P,-ahit.GetPz()/P]
     t = - start[0]/direc[0]
     
 ut.bookCanvas(h,key='Resultsmu',title='muons hitting concrete',nx=1000,ny=600,cx=2,cy=2)  
 ut.bookCanvas(h,key='Results',title='hitting concrete',nx=1000,ny=600,cx=2,cy=2)  
 for m in ['','mu']:
  tc = h['Results'+m].cd(1)
  h['conc_hity'+m].Draw()
  tc = h['Results'+m].cd(2)
  h['conc_hitz'+m].Draw()
  tc = h['Results'+m].cd(3)
  tc.SetLogy(1)
  h['conc_pt'+m].Draw()
  tc = h['Results'+m].cd(4)
  tc.SetLogy(1)
  h['conc_p'+m].Draw()
Пример #10
0
def exMCTracks():
 ut.bookHist(h,'pz','pz',100,0.,100.)
 ut.bookHist(h,'oz','oz',100,-10000.,10000.)
 ut.bookHist(h,'ex','ex to det',100,-2.5,2.5,100,-2.5,2.5)
 ut.bookHist(h,'N','N tracks',300,0.5,299.5)
# 
 sTree.SetBranchAddress("MCTrack", MCTracks)
 detPos = (3.5*u.m+70*u.m+40*u.m-100*u.m)
 for n in range(nEvents):
  rc = sTree.GetEvent(n) 
  nMCTracks = MCTracks.GetEntriesFast() 
  rc = h['N'].Fill( nMCTracks )
  for i in range(nMCTracks):
   atrack = MCTracks.At(i)
   pdgCode = atrack.GetPdgCode()
   mom = ROOT.TLorentzVector()
   atrack.Get4Momentum(mom)
   if abs(pdgCode)==13 or abs(pdgCode)==211:  
    rc = h['pz'].Fill( mom.Pz() )
    rc = h['oz'].Fill( atrack.GetStartZ() )  
    lam = ( detPos-atrack.GetStartZ() )/mom.Pz()
    xdet = (atrack.GetStartX()+lam*mom.Px() )/u.m
    ydet = (atrack.GetStartY()+lam*mom.Py() )/u.m
    rc = h['ex'].Fill(xdet,ydet ) 
 h['N'].Draw('box')
Пример #11
0
def exMCTracks():
    ut.bookHist(h, 'pz', 'pz', 100, 0., 100.)
    ut.bookHist(h, 'oz', 'oz', 100, -10000., 10000.)
    ut.bookHist(h, 'ex', 'ex to det', 100, -2.5, 2.5, 100, -2.5, 2.5)
    ut.bookHist(h, 'N', 'N tracks', 300, 0.5, 299.5)
    #
    sTree.SetBranchAddress("MCTrack", MCTracks)
    detPos = (3.5 * u.m + 70 * u.m + 40 * u.m - 100 * u.m)
    for n in range(nEvents):
        rc = sTree.GetEvent(n)
        nMCTracks = MCTracks.GetEntriesFast()
        rc = h['N'].Fill(nMCTracks)
        for i in range(nMCTracks):
            atrack = MCTracks.At(i)
            pdgCode = atrack.GetPdgCode()
            mom = ROOT.TLorentzVector()
            atrack.Get4Momentum(mom)
            if abs(pdgCode) == 13 or abs(pdgCode) == 211:
                rc = h['pz'].Fill(mom.Pz())
                rc = h['oz'].Fill(atrack.GetStartZ())
                lam = (detPos - atrack.GetStartZ()) / mom.Pz()
                xdet = (atrack.GetStartX() + lam * mom.Px()) / u.m
                ydet = (atrack.GetStartY() + lam * mom.Py()) / u.m
                rc = h['ex'].Fill(xdet, ydet)
    h['N'].Draw('box')
Пример #12
0
def analyze():
 ut.bookHist(h,'PinPout','pin pout',105,-0.5,10.,105,-0.5,10.)
 f=ROOT.TFile(outFile)
 sTree = f.cbmsim
 for n in range(sTree.GetEntries()):
  rc = sTree.GetEvent(n)
  mu = sTree.MCTrack[0]
  Pout = -0.49
  for v in sTree.vetoPoint:
   if v.GetTrackID()==0:
    if v.LastPoint()[2]>119.9:
     Pout = v.LastMom().Mag()
  rc = h['PinPout'].Fill(mu.GetP(),Pout)
 ut.writeHists(h,'PinPout.root')
Пример #13
0
def absorptionLengthOLD():
    Lfun = ROOT.TF1('Lfun', '[0]*(10**x)**[1]', -9, -6)
    Lfun.SetParameter(0, 6.4)
    Lfun.SetParameter(1, 0.98)
    hFiles = {
        "thermNeutron_BoronCarbide_X.XX_-E_-E_0.root": [0.08, 0.3],
        "thermNeutron_Boratedpolyethylene_X.XX_0.root": [1.0, 100.]
    }
    # thermNeutron_BoronCarbide_4.0_-8_-7_0.root

    Ls = {
        0.01: ROOT.kRed,
        0.1: ROOT.kOrange,
        0.04: ROOT.kCyan,
        0.4: ROOT.kBlue,
        4.0: ROOT.kMagenta
    }

    for hFile in hFiles:
        material = hFile.split('_')[1]
        ut.bookCanvas(h, 'absorb' + material, '', 1200, 800, 1, 1)
        h['absorb' + material].cd()
        for L in Ls:
            l = str(L)
            if L < 3: tmp = hFile.replace("X.XX", l).replace(" _-E_-E", "")
            else: tmp = hFile.replace("X.XX", l).replace(" _-E_-E", "_-8_-7")
            count(tmp)
            h['Eff_' + l] = h['Eff'].Clone('Eff_' + l)
            h['L_' + l] = ROOT.TGraph()
            h['L_' + l].SetLineColor(Ls[L])
            h['Eff'].Draw()
            g = h['Eff'].GetPaintedGraph()
            for n in range(g.GetN()):
                logE, p = g.GetPointX(n), g.GetPointY(n)
                if p > 0:
                    absL = -L / ROOT.TMath.Log(p)
                else:
                    absL = 0
                h['L_' + l].SetPoint(n, logE, absL)
        ut.bookHist(h, 'L', ';logE; L [cm]', 100, -9., -6.)
        h['L'].SetMaximum(hFiles[hFile][0])
        h['L'].SetStats(0)
        h['L'].Draw()
        for L in Ls:
            if L > hFiles[hFile][1]: continue
            h['L_' + str(L)].Draw('same')
            h['L_' + str(0.1)].Fit(Lfun)
        myPrint(h['absorb' + material], 'absorbLength' + material)
Пример #14
0
def beamSpot():
    A, B = ROOT.TVector3(), ROOT.TVector3()
    ut.bookHist(h, 'bs', 'beam spot', 100, -100., 10., 100, 0., 80.)
    for event in eventTree:
        xMean = 0
        yMean = 0
        w = 0
        for d in event.Digi_ScifiHits:
            detID = d.GetDetectorID()
            s = int(detID / 1000000)
            modules['Scifi'].GetSiPMPosition(detID, A, B)
            vertical = int(detID / 100000) % 10 == 1
            if vertical: xMean += A[0]
            else: yMean += A[1]
            w += 1
        rc = h['bs'].Fill(xMean / w, yMean / w)
Пример #15
0
def printScalers():
   ut.bookHist(h,'rate','rate',100,-0.5,99.5)
   if not h.has_key('rates'): ut.bookCanvas(h,key='rates',title='Rates',nx=600,ny=400,cx=1,cy=1)
   rc = h['rates'].cd(1)
   scalers = f.scalers
   if not scalers:
     print "no scalers in this file"
     return
   scalers.GetEntry(0)
   for x in scalers.GetListOfBranches():
    name = x.GetName()
    s = eval('scalers.'+name)
    if name!='slices': print "%20s :%8i"%(name,s)
    else:
      for n in range(s.size()):
        rc=h['rate'].Fill(n,s[n])
Пример #16
0
def someDrawings(F, channel):
    AF = ROOT.TVector3()
    BF = ROOT.TVector3()
    ut.bookCanvas(h, 'c1', ' ;x;y', 800, 800, 1, 1)
    s = int(channel / 1000000)
    o = int((channel - 1000000 * s) / 100000)
    locChannel = channel % 100000
    fibreVol = sGeo.FindVolumeFast('FiberVolume')
    R = fibreVol.GetShape().GetDX()
    sipmVol = sGeo.FindVolumeFast("ChannelVol")
    DY = sipmVol.GetShape().GetDY()
    DZ = sipmVol.GetShape().GetDZ()
    n = 0
    xmin = 999.
    xmax = -999.
    ymin = 999.
    ymax = -999.
    for fibre in F[locChannel]:
        globFibre = int(s * 1000000 + o * 100000 + fibre)
        scifi.GetPosition(globFibre, AF, BF)
        loc = scifi.GetLocalPos(globFibre, AF)
        h['ellipse' + str(n)] = ROOT.TEllipse(loc[0], loc[2], R, 0)
        n += 1
        if xmin > loc[0]: xmin = loc[0]
        if ymin > loc[2]: ymin = loc[2]
        if xmax < loc[0]: xmax = loc[0]
        if ymax < loc[2]: ymax = loc[2]
    print(xmin, xmax, ymin, ymax)
    D = ymax - ymin + 3 * R
    x0 = (xmax + xmin) / 2.
    ut.bookHist(h, 'x', '', 100, x0 - D / 2, x0 + D / 2, 100, ymin - 1.5 * R,
                ymax + 1.5 * R)
    h['x'].SetStats(0)
    h['x'].Draw()
    for i in range(n):
        print(fibre, globFibre, loc[0], loc[1], loc[2])
        el = h['ellipse' + str(i)]
        el.SetFillColor(6)
        el.Draw('same')
    scifi.GetSiPMPosition(channel, AF, BF)
    loc = scifi.GetLocalPos(globFibre, AF)
    h['rectang'] = ROOT.TBox(loc[0] - DY, loc[2] - DZ, loc[0] + DY,
                             loc[2] + DZ)
    h['rectang'].SetFillColor(4)
    h['rectang'].SetFillStyle(3001)
    h['rectang'].Draw('same')
Пример #17
0
def studyNoV0():
 counters = {}
 for v in vetoDets: ut.bookHist(h,'Vz'+v,'z position of vertex [m] '+v,1000,-30.,50.)
 ut.bookHist(h,'oa','cos opening angle',100,0.999,1.)
 for f in flist:
  fp = open(f)
  weightsUsed = pickle.load(fp) 
  bckg = pickle.load(fp)
  fp.close()
  inputFile = f.replace('Ana','rec').replace('pkl','root')
  ft = ROOT.TFile(inputFile)
  sTree = ft.cbmsim
  print "==> input file ",f
  for nb in bckg:
    v0 = bckg[nb][8]
    if v0 in V0dict: continue
    sTree.GetEvent(nb)
    vetoDets['SBT'],w = veto.SBT_decision(sTree)
    vetoDets['SVT'],w = veto.SVT_decision(sTree)
    vetoDets['UVT'],w = veto.UVT_decision(sTree)
    vetoDets['RPC'],w = veto.RPC_decision(sTree)
    vetoDets['TRA'],w = veto.Track_decision(sTree)
    p = sTree.Particles[bckg[nb][0]]
    HNLPos = ROOT.TLorentzVector()
    p.ProductionVertex(HNLPos)
    xv,yv,zv,doca  =  HNLPos.X()/u.m,HNLPos.Y()/u.m,HNLPos.Z()/u.m,HNLPos.T()/u.cm
    for v in vetoDets: 
     if not vetoDets[v]: 
        h['Vz'+v].Fill(zv)
        print 'no V0:',nb,bckg[nb][0],zv,ROOT.TMath.Sqrt(xv*xv+yv*yv),v 
    newPos = ROOT.TVector3(xv,yv,zv)
    t1,t2 = sTree.FitTracks[p.GetDaughter(0)].getFittedState(),sTree.FitTracks[p.GetDaughter(1)].getFittedState()
    rep1,rep2 = ROOT.genfit.RKTrackRep(t1.getPDG()),ROOT.genfit.RKTrackRep(t2.getPDG())  
    state1,state2 = ROOT.genfit.StateOnPlane(rep1),ROOT.genfit.StateOnPlane(rep2)
    rep1.setPosMom(state1,t1.getPos(),t1.getMom())
    rep2.setPosMom(state2,t2.getPos(),t2.getMom())
    try:
     rep1.extrapolateToPoint(state1, newPos, False)
     rep2.extrapolateToPoint(state2, newPos, False)
     mom1,mom2 = rep1.getMom(state1),rep2.getMom(state2)
    except:
     print "extrapolation failed. take stored state"  
     mom1,mom2 = t1.getMom(),t2.getMom()
    oa = mom1.Dot(mom2)/(mom1.Mag()*mom2.Mag()) 
    h['oa'].Fill(oa)
Пример #18
0
def checkPolarities():
 t=h['T'] 
 t.SetEventList(0) 
 for m in dictVol:  u.bookHist(h,'polCheck_'+str(m),dictVol[m],100,-10.,10.)   
 for iev in range(t.GetEntries()):
  t.GetEntry(iev)
  pxPrev  = 0.
  volPrev = -999.  
  for m in range( int(t.Nmeas) ):  
   volid  = t.volid[m]
   if volid == 99: break
   px     = t.px[m]
   if volid != volPrev :
    delpx   = pxPrev - px
    if volPrev > -900: h['polCheck_'+str(volPrev)].Fill(delpx*t.id/13.)    
    pxPrev  = px
    volPrev = volid  
 for m in dictVol: 
   if not dictVol[m].find('Mag')<0: print dictVol[m],h['polCheck_'+str(m)].GetMean() 
Пример #19
0
def plotRPCHitmap():
 ut.bookHist(h,'rpcHitmap','rpc Hitmaps',60,-0.5,59.5)
 for n in range(1,6):
  for l in range(2):
    ut.bookHist(h,'rpcHitmap'+str(n)+str(l),'rpc Hitmaps station '+str(n)+'layer '+str(l),200,-0.5,199.5)
 for event in sTree:
    for m in event.Digi_MuonTaggerHits:
      layer = m.GetDetectorID()/1000
      rc = h['rpcHitmap'].Fill(layer)
      channel = m.GetDetectorID()%1000
      rc = h['rpcHitmap'+str(layer)].Fill(channel)
 if not h.has_key('rpcPlot'): ut.bookCanvas(h,key='rpcPlot',title='RPC Hitmaps',nx=1200,ny=600,cx=4,cy=3)
 j=0
 for n in range(1,6):
  for l in range(2):
    j+=1
    rc = h['rpcPlot'].cd(j)
    h['rpcHitmap'+str(n)+str(l)].Draw()
 j+=1
 rc = h['rpcPlot'].cd(j)
 h['rpcHitmap'].Draw()
Пример #20
0
 def calibrationReport():
     ut.bookHist(h,'chi2','chi2',1000,0.,10000)
     report = {}
     TDC = 0
     for b in qdc_cal:
          for t in  qdc_cal[b]:
               for c in qdc_cal[b][t]:
                    for tac in qdc_cal[b][t][c]:
                              par    = qdc_cal[b][t][c][tac]
                              if 'chi2Ndof' in par:                             chi2 = par['chi2Ndof']
                              else: chi2=-1
                              parT = qdc_cal[b][t][c][tac][TDC]
                              if 'chi2Ndof' in parT:   chi2T = parT['chi2Ndof']
                              else: chi2T=-1
                              key = tac +10*c + t*10*100 + b*10*100*100
                              if not key in report: report[key]=[chi2,chi2T]
     for key in report:
          rc=h['chi2'].Fill(report[key][0])
          rc=h['chi2'].Fill(report[key][1])
     h['chi2'].Draw()
     return report
Пример #21
0
def testClusters():
  topA,botA = ROOT.TVector3(),ROOT.TVector3()
  topB,botB = ROOT.TVector3(),ROOT.TVector3()
  clusters = {}
  for s in range(1,5):
   for view in ['_x','_u','_v']: 
    ut.bookHist(h,'del'+view+str(s),'del x for '+str(s)+view,100,-20.,20.)
    clusters[s]={view:{}}
  ut.bookHist(h,'clsN','cluster sizes',10,-0.5,9.5)
  for event in sTree:
   spectrHitsSorted = sortHits(event)
   for s in range(1,5):
    for view in ['_x','_u','_v']:
     allHits = {}
     for hit in spectrHitsSorted[view][s]:
      statnb,vnb,pnb,layer,view = stationInfo(hit)
      if not allHits.has_key(layer):allHits[layer]=[]
      allHits[layer].append(hit)
     ncl = 0
     for l in allHits:
      for n in range(len(allHits[l])-1):
       hitA = allHits[l][n]
       rc = hitA.MufluxSpectrometerEndPoints(botA,topA)
       xA = (botA[0]+topA[0])/2.
       clusters[s][view][ncl]=[[hitA.GetDetectorID(),xA]]
       for m in range(n,len(allHits)):
        hitB = allHits[m]
        rc = hitB.MufluxSpectrometerEndPoints(botB,topB)
        xB = (botB[0]+topB[0])/2.
        delx = xA-xB
        rc = h['del'+view+str(s)].Fill(delx)
        if abs(delx)<5.:
         clusters[s][view][ncl].append([hitB.GetDetectorID(),xB])
         ncl+=1
     rc = h['clsN'].Fill(ncl)
  for s in range(1,5):
   for view in ['_x','_u','_v']: 
     next = raw_input("Next (Ret/Quit): ")
     if next<>'':  break
     h['del'+view+str(s)].Draw()
Пример #22
0
def makeHistos(rfile):
 f=ROOT.TFile.Open(rfile)
 sTree = f.cbmsim
 nTot = 0
 for k in f.GetListOfKeys():
  if k.GetName() == 'FileHeader':
   tmp =  k.GetTitle().split('=')[1]
   tmp2 = tmp.split('with')[0]
   if tmp2.find('E')<0: nTot += int(tmp2)
   else: nTot += float(tmp2)
 print("POT = ",nTot," number of events:",sTree.GetEntries())
# particle statistics
 h={}
 ut.bookHist(h,'pids','pid',19999,-9999.5,9999.5)
 ut.bookHist(h,'test','muon p/pt',100,0.,400.,100,0.,5.)
 diMuonDecays = [221, 223, 113, 331, 333]
 pDict = {}
 procDict = {}
 for n in range(sTree.GetEntries()):
  rc = sTree.GetEvent(n)
  for p in sTree.vetoPoint:
   t = sTree.MCTrack[p.GetTrackID()]
   pid = t.GetPdgCode()
   rc = h['pids'].Fill(pid)
   if abs(pid)==13:
     procID = t.GetProcName().Data()
     mother = t.GetMotherId()
     if not mother < 0:
         moPid = sTree.MCTrack[mother].GetPdgCode()
         name = pdg.GetParticle(moPid).GetName()
         name = procID+' '+name
         if name not in h:  h[name]=h['test'].Clone(name)
         rc=h[name].Fill(t.GetP(),t.GetPt())
     if procID not in h:  h[procID]=h['test'].Clone(procID)
     rc=h[procID].Fill(t.GetP(),t.GetPt())
 for x in h:
  h[x].Scale(1./nTot)
 tmp = rfile.split('/')
 hname = tmp[len(tmp)-1].replace('pythia8_Geant4','Histos')
 ut.writeHists(h,hname)
def makeHistos(rfile):
 f=ROOT.TFile.Open(rfile)
 sTree = f.cbmsim
 nTot = 0
 for k in f.GetListOfKeys():
  if k.GetName() == 'FileHeader':
   tmp =  k.GetTitle().split('=')[1]
   tmp2 = tmp.split('with')[0]
   if tmp2.find('E')<0: nTot += int(tmp2)
   else: nTot += float(tmp2)
 print "POT = ",nTot," number of events:",sTree.GetEntries()
# particle statistics
 h={}
 ut.bookHist(h,'pids','pid',19999,-9999.5,9999.5)
 ut.bookHist(h,'test','muon p/pt',100,0.,400.,100,0.,5.)
 diMuonDecays = [221, 223, 113, 331, 333]
 pDict = {}
 procDict = {}
 for n in range(sTree.GetEntries()):
  rc = sTree.GetEvent(n)
  for p in sTree.vetoPoint:
   t = sTree.MCTrack[p.GetTrackID()]
   pid = t.GetPdgCode()
   rc = h['pids'].Fill(pid)
   if abs(pid)==13:
     procID = t.GetProcName().Data()
     mother = t.GetMotherId()
     if not mother < 0:
         moPid = sTree.MCTrack[mother].GetPdgCode()
         name = pdg.GetParticle(moPid).GetName()
         name = procID+' '+name
         if not h.has_key(name):  h[name]=h['test'].Clone(name)
         rc=h[name].Fill(t.GetP(),t.GetPt())
     if not h.has_key(procID):  h[procID]=h['test'].Clone(procID)
     rc=h[procID].Fill(t.GetP(),t.GetPt())
 for x in h:
  h[x].Scale(1./nTot)
 tmp = rfile.split('/')
 hname = tmp[len(tmp)-1].replace('pythia8_Geant4','Histos')
 ut.writeHists(h,hname)
Пример #24
0
def moreChecks(modules):
    ut.bookHist(h, 'dx', 'dx', 100, -0.1, 0.1)
    ut.bookHist(h, 'dy', 'dy', 100, -1., 1.)
    ut.bookHist(h, 'dz', 'dz', 100, -0.2, 0.2)
    AS = ROOT.TVector3()
    BS = ROOT.TVector3()
    AF = ROOT.TVector3()
    BF = ROOT.TVector3()
    scifi = modules['Scifi']
    F = getFibre2SiPMCPP(modules)
    for station in range(1, 6):
        for orientation in range(0, 2):
            for channel in F:
                globChannel = station * 1000000 + orientation * 100000 + channel
                scifi.GetSiPMPosition(globChannel, AS, BS)
                for fibre in F[channel]:
                    globFibre = station * 1000000 + orientation * 100000 + fibre
                    scifi.GetPosition(globFibre, AF, BF)
                    if orientation == 0:
                        dx = AS[1] - AF[1]
                        dy = AS[0] - AF[0]
                    else:
                        dx = AS[0] - AF[0]
                        dy = AS[1] - AF[1]
                    dz = AS[2] - AF[2]
                    rc = h['dx'].Fill(dx)
                    rc = h['dy'].Fill(dy)
                    rc = h['dz'].Fill(dz)
Пример #25
0
def eventTime(Nev=-1):
 Tprev = -1
 if Nev < 0 : Nev = eventTree.GetEntries()
 ut.bookHist(h,'Etime','delta event time; dt [s]',100,0.0,1.)
 ut.bookHist(h,'EtimeZ','delta event time; dt [ns]',1000,0.0,10000.)
 ut.bookCanvas(h,'T',' ',1024,2*768,1,2)
 eventTree.GetEvent(0)
 t0 =  eventTree.EventHeader.GetEventTime()/160.E6
 eventTree.GetEvent(Nev-1)
 tmax = eventTree.EventHeader.GetEventTime()/160.E6
 ut.bookHist(h,'time','elapsed time; t [s]',1000,0,tmax-t0)

 N=-1
 for event in eventTree:
    N+=1
    if N>Nev: break
    T = event.EventHeader.GetEventTime()
    dT = 0
    if Tprev >0: dT = T-Tprev
    Tprev = T
    rc = h['Etime'].Fill(dT/freq)
    rc = h['EtimeZ'].Fill(dT*1E9/160.E6)
    rc = h['time'].Fill( (T/freq-t0))
 tc = h['T'].cd(1)
 tc.SetLogy(1)
 h['EtimeZ'].Draw()
 tc.Update()
 tc = h['T'].cd(2)
 h['time'].Draw()
 h['T'].Update()
 h['T'].Print('time-run'+str(options.runNumber)+'.png')
def energyLoss():
    t = h["T"]
    u.bookHist(h, "elossW", "energy loss as function of distance in W", 100, 0.0, 50.0, 100, 0.0, 300.0)
    u.bookHist(h, "elossPb", "energy loss as function of distance in Pb", 100, 0.0, 50.0, 100, 0.0, 200.0)
    u.bookHist(h, "elossFe", "energy loss as function of distance in Fe", 100, 0.0, 50.0, 100, 0.0, 200.0)
    nmax = t.GetEntries()
    leaves = t.GetListOfLeaves()
    names = u.setAttributes(pyl, leaves)
    for n in range(nmax):
        rc = t.GetEntry(n)
        nmeas = int(pyl.Nmeas.GetValue())
        measW = {}
        measPb = {}
        measFe = {}
        w = pyl.w.GetValue()
        for j in range(nmeas):
            volid = int(pyl.volid.GetValue(j))
            procid = int(pyl.procid.GetValue(j))
            z = pyl.z.GetValue(j)
            px = pyl.px.GetValue(j)
            py = pyl.py.GetValue(j)
            pz = pyl.pz.GetValue(j)
            E = math.sqrt(px * px + py * py + pz * pz + Mmu2)
            if volid == 0 and procid < 0:
                # attention, there are entry and exit points !
                if not measW.has_key(0):
                    measW[0] = [z, E]
            elif (volid > 3 and volid < 7) and procid < 0:  # enter Pbshield1
                if not measW.has_key(1):
                    measW[1] = [z, E]
            if volid == 4 and procid < 0:
                if not measPb.has_key(0):
                    measPb[0] = [z, E]
            elif volid == 6 and procid < 0:
                if not measPb.has_key(1):
                    measPb[1] = [z, E]
                if not measFe.has_key(0):
                    measFe[0] = [z, E]
            elif volid != 6 and measFe.has_key(0) and procid < 0:
                if not measFe.has_key(1):
                    measFe[1] = [z, E]
        if len(measW) == 2:
            dist = measW[1][0] - measW[0][0]
            Eloss = measW[0][1] - measW[1][1]
            h["elossW"].Fill(dist, Eloss, w)
        if len(measPb) == 2:
            dist = measPb[1][0] - measPb[0][0]
            Eloss = measPb[0][1] - measPb[1][1]
            h["elossPb"].Fill(dist, Eloss, w)
        if len(measFe) == 2:
            dist = measFe[1][0] - measFe[0][0]
            Eloss = measFe[0][1] - measFe[1][1]
            h["elossFe"].Fill(dist, Eloss, w)
    h["mean_elossW"] = h["elossW"].ProfileX()
    h["mean_elossW"].SetTitle("mean energy loss as function of distance in W")
    h["mean_elossPb"] = h["elossPb"].ProfileX()
    h["mean_elossPb"].SetTitle("mean energy loss as function of distance in Pb")
    h["mean_elossFe"] = h["elossFe"].ProfileX()
    h["mean_elossFe"].SetTitle("mean energy loss as function of distance in Fe")
Пример #27
0
def makeTable(pcut=0,rcut=1.E10):
 print '### for pcut > ',pcut,' and rcut < ',rcut
 pcutsq = str(pcut*pcut)
 rcutsq = str(rcut*rcut)
 for o in opts:
  ok = 'id'+o 
  u.bookHist(h,ok,'id '+o,5001,-2500.5,2499.5)
  opts[o][0].Draw('id>>'+ok,'px*px+py*py+pz*pz>'+pcutsq+'&&x*x+y*y<'+rcutsq)
    # count how many originate from Pythia
  u.bookHist(h,ok+'Py','id '+o+' from pythia',5001,-2500.5,2499.5)
  opts[o][0].Draw('id>>'+ok+'Py','pythiaid==id&&(px*px+py*py+pz*pz)>'+pcutsq+'&&(x*x+y*y)<'+rcutsq)   
  h[ok].SetLineColor(ocol[o])
 tc = h['Results'].cd(1)
 h[ok].Draw()
 tc.SetLogy(1)
 for o in opts:
  ok = 'id'+o 
  h[ok].Draw('same')
# make a zero suppressed table
 table = {}
 for i in range(h[ok].GetNbinsX()):
  for o in opts:
   ok = 'id'+o 
   ncont  = h[ok].GetBinContent(i+1)
   ncontP = h[ok+'Py'].GetBinContent(i+1)
   pid   = h[ok].GetBinCenter(i+1) 
   if ncont > 0:
    if table.has_key(pid) : table[pid][o]=[ncont*scaleFac[o],ncontP/ncont]
    else: table[pid] = {o:[ncont*scaleFac[o],ncontP/ncont]}
 print headline
 ktable = table.keys()
 ktable.sort()
 for i in ktable:
  txt = '%5i %11s'%(int(i),pdg.GetParticle(int(i)).GetName())
  for o in sopts:
   if table[i].has_key(o): txt += ' %8.3G %5.1F '%(table[i][o][0],100*table[i][o][1])
   else: txt += ' %8.3G %5.1F '%(0,0)  
  print txt
Пример #28
0
def overlap(F, Finv):
    ut.bookHist(h, 'W', 'overlap/fibre', 110, 0., 1.1)
    ut.bookHist(h, 'C', 'coverage', 50, 0., 10.)
    ut.bookHist(h, 'S', 'fibres/sipm', 15, -0.5, 14.5)
    ut.bookHist(h, 'Eff', 'efficiency', 110, 0., 1.1)
    for n in F:
        C = 0
        for fid in F[n]:
            rc = h['W'].Fill(F[n][fid]['weight'])
            C += F[n][fid]['weight']
        rc = h['C'].Fill(C)
    for n in Finv:
        E = 0
        for sipm in Finv[n]:
            E += Finv[n][sipm]['weight']
        rc = h['Eff'].Fill(E)
        rc = h['S'].Fill(len(Finv[n]))
Пример #29
0
def eventTime():
    Tprev = -1
    freq = 160.E6
    ut.bookHist(h, 'Etime', 'delta event time; dt [s]', 100, 0.0, 1.)
    ut.bookCanvas(h, 'E', ' ', 1024, 2 * 768, 1, 2)
    eventTree.GetEvent(0)
    t0 = eventTree.EventHeader.GetEventTime() / 160.E6
    eventTree.GetEvent(eventTree.GetEntries() - 1)
    tmax = eventTree.EventHeader.GetEventTime() / 160.E6
    ut.bookHist(h, 'time', 'elapsed time; t [s]', 1000, t0, tmax)
    for event in eventTree:
        T = event.EventHeader.GetEventTime()
        dT = 0
        if Tprev > 0: dT = T - Tprev
        Tprev = T
        rc = h['Etime'].Fill(dT / freq)
        rc = h['time'].Fill((T / freq - t0))
    tc = h['E'].cd(1)
    rc = h['Etime'].Fit('expo')
    tc.Update()
    stats = h['Etime'].FindObject("stats")
    stats.SetOptFit(111)
    tc = h['E'].cd(2)
    h['time'].Draw()
Пример #30
0
def hitMaps(Nev=-1):
    for mat in range(30):
        ut.bookHist(h, 'mat_' + str(mat), 'hit map / mat', 512, -0.5, 511.5)
        ut.bookHist(h, 'sig_' + str(mat), 'signal / mat', 150, 0.0, 150.)
    N = -1
    if Nev < 0: Nev = eventTree.GetEntries()
    for event in eventTree:
        N += 1
        if N > Nev: break
        for aHit in event.Digi_ScifiHits:
            if not aHit.isValid(): continue
            X = xPos(aHit.GetDetectorID())
            rc = h['mat_' + str(X[0] * 3 + X[1])].Fill(X[2])
            rc = h['sig_' + str(X[0] * 3 + X[1])].Fill(aHit.GetSignal(0))
    ut.bookCanvas(h, 'hitmaps', ' ', 1024, 768, 6, 5)
    ut.bookCanvas(h, 'signal', ' ', 1024, 768, 6, 5)
    for mat in range(30):
        tc = h['hitmaps'].cd(mat + 1)
        A = h['mat_' + str(mat)].GetSumOfWeights() / 512.
        if h['mat_' + str(mat)].GetMaximum() > 10 * A:
            h['mat_' + str(mat)].SetMaximum(10 * A)
        h['mat_' + str(mat)].Draw()
        tc = h['signal'].cd(mat + 1)
        h['sig_' + str(mat)].Draw()
Пример #31
0
def interactionRegion():
 import rootUtils as ut
 import shipunit as u
 f = ROOT.TFile('pythia8_Geant4_13_350.0.root')
 sTree=f.FindObjectAny('pythia8-Geant4')
 ut.bookHist(h,'originz','z',100,-50.5,-49.)
 ut.bookHist(h,'originzr','r vs z',100,-50.5,-49.,100,0.,0.5)
 ut.bookHist(h,'originxy','x vs y',100,-0.5,0.5,100,-0.5,0.5)
 ROOT.gROOT.cd()
 sTree.Draw('z>>originz') 
 sTree.Draw('1000*sqrt(x*x+y*y):z>>originzr') 
 sTree.Draw('1000*x:1000*y>>originxy') 
Пример #32
0
def HNLKinematics():
 ut.bookHist(h,'HNLmomNoW','momentum unweighted',100,0.,300.)
 ut.bookHist(h,'HNLmom','momentum',100,0.,300.)
 ut.bookHist(h,'HNLmom_recTracks','momentum',100,0.,300.)
 ut.bookHist(h,'HNLmomNoW_recTracks','momentum unweighted',100,0.,300.)
 for n in range(sTree.GetEntries()): 
  rc = sTree.GetEntry(n)
  wg = sTree.MCTrack[1].GetWeight()
  if not wg>0.: wg=1.
  P = sTree.MCTrack[1].GetP()
  h['HNLmom'].Fill(P,wg) 
  h['HNLmomNoW'].Fill(P) 
  for HNL in sTree.Particles:
     t1,t2 = HNL.GetDaughter(0),HNL.GetDaughter(1) 
     for tr in [t1,t2]:
      xx  = sTree.FitTracks[tr].getFittedState()
      Prec = xx.getMom().Mag()
      h['HNLmom_recTracks'].Fill(Prec,wg) 
      h['HNLmomNoW_recTracks'].Fill(Prec) 
Пример #33
0
def makePlots(sTree):
 ut.bookHist(h,'muP','muon mom',100,0.,400.)
 ut.bookHist(h,'nOut','outgoing part',100,-0.5,99.5)
 ut.bookHist(h,'pos','position',100,-25.,100.,100,-12.,12.,100,-13.,13.)
 for n in range(sTree.GetEntries()):
   rc = sTree.GetEvent(n)
   inMu = sTree.InMuon[0]
   w = inMu[8]
   P = ROOT.TMath.Sqrt(inMu[1]**2+inMu[2]**2+inMu[3]**2)
   rc = h['muP'].Fill(P,w)
   rc = h['nOut'].Fill(sTree.Particles.GetEntries() )
   rc = h['pos'].Fill(inMu[7],inMu[5],inMu[6] )
Пример #34
0
def interactionRegion():
    import rootUtils as ut
    import shipunit as u
    f = ROOT.TFile('pythia8_Geant4_13_350.0.root')
    sTree = f.FindObjectAny('pythia8-Geant4')
    ut.bookHist(h, 'originz', 'z', 100, -50.5, -49.)
    ut.bookHist(h, 'originzr', 'r vs z', 100, -50.5, -49., 100, 0., 0.5)
    ut.bookHist(h, 'originxy', 'x vs y', 100, -0.5, 0.5, 100, -0.5, 0.5)
    ROOT.gROOT.cd()
    sTree.Draw('z>>originz')
    sTree.Draw('1000*sqrt(x*x+y*y):z>>originzr')
    sTree.Draw('1000*x:1000*y>>originxy')
Пример #35
0
def interactionRegion():
    import rootUtils as ut
    import shipunit as u

    f = ROOT.TFile("pythia8_Geant4_13_350.0.root")
    sTree = f.FindObjectAny("pythia8-Geant4")
    ut.bookHist(h, "originz", "z", 100, -50.5, -49.0)
    ut.bookHist(h, "originzr", "r vs z", 100, -50.5, -49.0, 100, 0.0, 0.5)
    ut.bookHist(h, "originxy", "x vs y", 100, -0.5, 0.5, 100, -0.5, 0.5)
    ROOT.gROOT.cd()
    sTree.Draw("z>>originz")
    sTree.Draw("1000*sqrt(x*x+y*y):z>>originzr")
    sTree.Draw("1000*x:1000*y>>originxy")
Пример #36
0
def makePlots(sTree):
    ut.bookHist(h, 'muP', 'muon mom', 100, 0., 400.)
    ut.bookHist(h, 'nOut', 'outgoing part', 100, -0.5, 99.5)
    ut.bookHist(h, 'pos', 'position', 100, -25., 100., 100, -12., 12., 100,
                -13., 13.)
    for n in range(sTree.GetEntries()):
        rc = sTree.GetEvent(n)
        inMu = sTree.InMuon[0]
        w = inMu[8]
        P = ROOT.TMath.Sqrt(inMu[1]**2 + inMu[2]**2 + inMu[3]**2)
        rc = h['muP'].Fill(P, w)
        rc = h['nOut'].Fill(sTree.Particles.GetEntries())
        rc = h['pos'].Fill(inMu[7], inMu[5], inMu[6])
Пример #37
0
def energyLoss():
  t = h['T']
  u.bookHist(h,'elossW','energy loss as function of distance in W' ,100,0.,50.,100,0.,300.) 
  u.bookHist(h,'elossPb','energy loss as function of distance in Pb',100,0.,50.,100,0.,200.) 
  u.bookHist(h,'elossFe','energy loss as function of distance in Fe',100,0.,50.,100,0.,200.) 
  nmax   = t.GetEntries()
  for n in range(nmax):
   rc    = t.GetEntry(n)
   nmeas = int(t.Nmeas)
   measW  = {}
   measPb = {}
   measFe = {}
   w =  t.w
   for j in range(nmeas):
    volid  = int(t.volid(j))
    procid = int(t.procid(j))
    z  = t.z(j)
    px = t.px(j)
    py = t.py(j)
    pz = t.pz(j)
    E  = math.sqrt(px*px+py*py+pz*pz+Mmu2)
    if volid == 0 and procid < 0: 
# attention, there are entry and exit points !
      if not measW.has_key(0): measW[0] = [z,E] 
    elif  (volid > 3 and volid < 7) and procid < 0: # enter Pbshield1
      if not measW.has_key(1): measW[1] = [z,E] 
    if volid == 4 and procid < 0: 
      if not measPb.has_key(0):   measPb[0] = [z,E] 
    elif volid == 6 and procid < 0: 
      if not measPb.has_key(1): measPb[1] = [z,E]  
      if not measFe.has_key(0): measFe[0] = [z,E]  
    elif volid !=6 and  measFe.has_key(0) and procid < 0: 
      if not measFe.has_key(1): measFe[1] = [z,E]  
   if len(measW)==2: 
    dist  = measW[1][0]- measW[0][0]
    Eloss = measW[0][1]- measW[1][1] 
    h['elossW'].Fill(dist,Eloss,w)
   if len(measPb)==2: 
    dist  = measPb[1][0]- measPb[0][0]
    Eloss = measPb[0][1]- measPb[1][1] 
    h['elossPb'].Fill(dist,Eloss,w)
   if len(measFe)==2: 
    dist  = measFe[1][0]- measFe[0][0]
    Eloss = measFe[0][1]- measFe[1][1] 
    h['elossFe'].Fill(dist,Eloss,w)
  h['mean_elossW'] = h['elossW'].ProfileX()
  h['mean_elossW'].SetTitle('mean energy loss as function of distance in W')
  h['mean_elossPb'] = h['elossPb'].ProfileX()
  h['mean_elossPb'].SetTitle('mean energy loss as function of distance in Pb')
  h['mean_elossFe'] = h['elossFe'].ProfileX()
  h['mean_elossFe'].SetTitle('mean energy loss as function of distance in Fe')
Пример #38
0
 def __init__(self,hp,main):
  self.sTree = main.sTree
  self.fPartArray  = ROOT.TClonesArray("TParticle")
  if not self.sTree.GetBranch("Particles"):
   self.Particles   = self.sTree.Branch("Particles",  self.fPartArray,32000,-1)
  else: 
   self.Particles = self.sTree.Particles
  self.reps,self.states,self.newPosDir = {},{},{}
  self.LV={1:ROOT.TLorentzVector(),2:ROOT.TLorentzVector()}
  self.h = hp
  self.PDG = ROOT.TDatabasePDG.Instance()
  ut.bookHist(self.h,'Vzpull','Vz pull',100,-3.,3.)
  ut.bookHist(self.h,'Vxpull','Vx pull',100,-3.,3.)
  ut.bookHist(self.h,'Vypull','Vy pull',100,-3.,3.)
Пример #39
0
def exMCHits():
 ut.bookHist(h,'tz','tracking hits z',100,-100.,100.)
 ut.bookHist(h,'tztx','tracking hits x vs z',100,-100.,100.,100,-2.5,2.5)
 ut.bookHist(h,'txty','tracking hits y vs x',100,-2.5,2.5,100,-2.5,2.5)
 sTree.SetBranchAddress("vetoPoint", TrackingHits)
 for n in range(nEvents):
  rc = sTree.GetEvent(n) 
  nHits = TrackingHits.GetEntriesFast() 
  for i in range(nHits):
    ahit = TrackingHits.At(i)
    rc = h['tz'].Fill( ahit.GetZ()/u.m )
    rc = h['txty'].Fill( ahit.GetX()/u.m,ahit.GetY()/u.m )
    rc = h['tztx'].Fill( ahit.GetZ()/u.m,ahit.GetX()/u.m ) 
 h['tztx'].Draw('box') 
Пример #40
0
def HNLKinematics():
    ut.bookHist(h, 'HNLmomNoW', 'momentum unweighted', 100, 0., 300.)
    ut.bookHist(h, 'HNLmom', 'momentum', 100, 0., 300.)
    ut.bookHist(h, 'HNLmom_recTracks', 'momentum', 100, 0., 300.)
    ut.bookHist(h, 'HNLmomNoW_recTracks', 'momentum unweighted', 100, 0., 300.)
    for n in range(sTree.GetEntries()):
        rc = sTree.GetEntry(n)
        for hnlkey in [1, 2]:
            if abs(sTree.MCTrack[hnlkey].GetPdgCode()) == 9900015:
                theHNL = sTree.MCTrack[hnlkey]
                wg = theHNL.GetWeight()
                if not wg > 0.: wg = 1.
                P = theHNL.GetP()
                h['HNLmom'].Fill(P, wg)
                h['HNLmomNoW'].Fill(P)
                for HNL in sTree.Particles:
                    t1, t2 = HNL.GetDaughter(0), HNL.GetDaughter(1)
                    for tr in [t1, t2]:
                        xx = sTree.FitTracks[tr].getFittedState()
                        Prec = xx.getMom().Mag()
                        h['HNLmom_recTracks'].Fill(Prec, wg)
                        h['HNLmomNoW_recTracks'].Fill(Prec)
Пример #41
0
def testT0():
 ut.bookHist(h,'means0','mean vs s0',100,0.,3000.,100,0.,3000.)
 ut.bookHist(h,'means1','mean vs s1',100,0.,3000.,100,0.,3000.)
 ut.bookHist(h,'means2','mean vs s2',100,0.,3000.,100,0.,3000.)
 for event in sTree:
    sumOfTDCs = 0
    if event.Digi_MufluxSpectrometerHits.GetEntries() < 15 or event.Digi_MufluxSpectrometerHits.GetEntries() > 30: continue
    for m in event.Digi_MufluxSpectrometerHits:
      sumOfTDCs+=m.GetDigi()
    mean = sumOfTDCs/float(event.Digi_MufluxSpectrometerHits.GetEntries())
    if event.Digi_ScintillatorHits.GetEntries()==0:
      print "no scint"
    else:
     rc = h['means0'].Fill(mean,event.Digi_ScintillatorHits[0].GetDigi())
     rc = h['means1'].Fill(mean,event.Digi_ScintillatorHits[1].GetDigi())
     if event.Digi_ScintillatorHits.GetEntries()>2:
      rc = h['means2'].Fill(mean,event.Digi_ScintillatorHits[2].GetDigi())
Пример #42
0
 def __init__(self, hp, main):
     self.sTree = main.sTree
     self.fPartArray = ROOT.TClonesArray("TParticle")
     if not self.sTree.GetBranch("Particles"):
         self.Particles = self.sTree.Branch("Particles", self.fPartArray,
                                            32000, -1)
     else:
         self.Particles = self.sTree.Particles
     self.reps, self.states, self.newPosDir = {}, {}, {}
     self.LV = {1: ROOT.TLorentzVector(), 2: ROOT.TLorentzVector()}
     self.h = hp
     self.PDG = ROOT.TDatabasePDG.Instance()
     if sys.modules['__main__'].realPR != "":
         self.fitTrackLoc = "FitTracks_PR"
     else:
         self.fitTrackLoc = "FitTracks"
     ut.bookHist(self.h, 'Vzpull', 'Vz pull', 100, -3., 3.)
     ut.bookHist(self.h, 'Vxpull', 'Vx pull', 100, -3., 3.)
     ut.bookHist(self.h, 'Vypull', 'Vy pull', 100, -3., 3.)
Пример #43
0
def exMCHits(dump=False):
 ut.bookHist(h,'tz','tracking hits z',100,-100.,100.)
 ut.bookHist(h,'tztx','tracking hits x vs z',1000,-40.,40.,100,-2.5,2.5)
 ut.bookHist(h,'txty','tracking hits y vs x',100,-2.5,2.5,100,-2.5,2.5)
 sTree.SetBranchAddress("vetoPoint", TrackingHits)
 for n in range(nEvents):
  rc = sTree.GetEvent(n) 
  nHits = TrackingHits.GetEntriesFast() 
  for i in range(nHits):
    ahit = TrackingHits.At(i)
    rc = h['tz'].Fill( ahit.GetZ()/u.m )
    rc = h['txty'].Fill( ahit.GetX()/u.m,ahit.GetY()/u.m )
    rc = h['tztx'].Fill( ahit.GetZ()/u.m,ahit.GetX()/u.m ) 
 h['tztx'].Draw('box') 
 if dump:
  for n in range( min(10,nEvents) ):
   rc = sTree.GetEvent(n) 
   nHits = TrackingHits.GetEntriesFast() 
   for i in range(nHits):
    ahit = TrackingHits.At(i)
    print ahit.GetZ()/u.m, ahit.GetDetectorID(),ahit.GetLength(),ahit.GetEnergyLoss() 
Пример #44
0
def exMCHits(dump=False):
    ut.bookHist(h, 'tz', 'tracking hits z', 100, -100., 100.)
    ut.bookHist(h, 'tztx', 'tracking hits x vs z', 1000, -40., 40., 100, -2.5,
                2.5)
    ut.bookHist(h, 'txty', 'tracking hits y vs x', 100, -2.5, 2.5, 100, -2.5,
                2.5)
    sTree.SetBranchAddress("vetoPoint", TrackingHits)
    for n in range(nEvents):
        rc = sTree.GetEvent(n)
        nHits = TrackingHits.GetEntriesFast()
        for i in range(nHits):
            ahit = TrackingHits.At(i)
            rc = h['tz'].Fill(ahit.GetZ() / u.m)
            rc = h['txty'].Fill(ahit.GetX() / u.m, ahit.GetY() / u.m)
            rc = h['tztx'].Fill(ahit.GetZ() / u.m, ahit.GetX() / u.m)
    h['tztx'].Draw('box')
    if dump:
        for n in range(min(10, nEvents)):
            rc = sTree.GetEvent(n)
            nHits = TrackingHits.GetEntriesFast()
            for i in range(nHits):
                ahit = TrackingHits.At(i)
                print ahit.GetZ() / u.m, ahit.GetDetectorID(), ahit.GetLength(
                ), ahit.GetEnergyLoss()
Пример #45
0
 geoFile = tmp.replace('_rec','')

fgeo = ROOT.TFile.Open(geoFile)
geoMat =  ROOT.genfit.TGeoMaterialInterface()  # if only called in ShipDigiReco -> crash, reason unknown

from ShipGeoConfig import ConfigRegistry
from rootpyPickler import Unpickler
#load Shipgeo dictionary
upkl    = Unpickler(fgeo)
ShipGeo = upkl.load('ShipGeo')
ecalGeoFile = ShipGeo.ecal.File

h={}
log={}
if withHists:
 ut.bookHist(h,'distu','distance to wire',100,0.,5.)
 ut.bookHist(h,'distv','distance to wire',100,0.,5.)
 ut.bookHist(h,'disty','distance to wire',100,0.,5.)
 ut.bookHist(h,'nmeas','nr measuerements',100,0.,50.)
 ut.bookHist(h,'chi2','Chi2/DOF',100,0.,20.)

import shipDet_conf
run = ROOT.FairRunSim()
run.SetName("TGeant4")  # Transport engine
run.SetOutputFile(ROOT.TMemFile('output', 'recreate'))  # Output file
run.SetUserConfig("g4Config_basic.C") # geant4 transport not used, only needed for creating VMC field
rtdb = run.GetRuntimeDb()
# -----Create geometry----------------------------------------------
modules = shipDet_conf.configure(run,ShipGeo)
# run.Init()
fgeo.FAIRGeom
Пример #46
0
  fGeo = ROOT.gGeoManager  
  vetoDet = {}
  i = 0
  for v in fGeo.GetListOfVolumes():
   i+=1
   nm = v.GetName()
   if nm.find('STr')<0 and nm.find('Sveto')<0 : continue
   vetoDet[i] = nm
  return vetoDet

h={}
vetoDet = detMap()
for i in vetoDet:
 for mu in ['','_mu']:
  tag = vetoDet[i]+mu
  ut.bookHist(h,tag,'x/y '+vetoDet[i],100,-2.5,2.5,100,-2.5,2.5)
  ut.bookHist(h,tag+'_E','deposited energy MeV '+vetoDet[i],100,0.,2.)
  ut.bookHist(h,tag+'_P','particle mom GeV '+vetoDet[i],100,0.,200.)
  ut.bookHist(h,tag+'_id','particle id '+vetoDet[i],5001,-2499.5,2499.5)
  ut.bookHist(h,tag+'_mul','multiplicity of hits/tracks '+vetoDet[i],10,-0.5,9.5)
  ut.bookHist(h,tag+'_evmul','multiplicity of hits/event '+vetoDet[i],10,-0.5,9.5)
  ut.bookHist(h,tag+'_origin','r vs z',100,  ztarget,totl,100,0.,12.)
  ut.bookHist(h,tag+'_originmu','r vs z',100,ztarget,totl,100,0.,12.)
 
for i in ['Ecal','muon']:
 for mu in ['','_mu']:
   tag = i+mu
   ut.bookHist(h,tag,'x/y '+i,100,-2.5,2.5,100,-2.5,2.5)
   ut.bookHist(h,tag+'_E','deposited energy MeV '+i,100,0.,100.)
ut.bookHist(h,'origin','r vs z',100,ztarget,totl,50,0.,3.)
ut.bookHist(h,'borigin','r vs z',100,ztarget,totl,500,0.,30.)
Пример #47
0
nb = 400
t0 = time.time()
idhist = len(idbeam) * 4 * [0]
print 'Get chi vs momentum for all beam+target particles'
for idp in range(0, len(idbeam)):
    #  particle or antiparticle
    for idpm in range(-1, 3, 2):
        idw = idbeam[idp] * idpm
        if PDG.GetParticle(idw) <> None:
            name = PDG.GetParticle(idw).GetName()
            #  particle exists, book hists etc..
            id = id + 1
            for idnp in range(2):
                idb = id * 10 + idnp * 4
                ut.bookHist(h, str(idb + 1),
                            'sigma vs p, ' + name + '->' + target[idnp], nb,
                            0.5, pbeamh + 0.5)
                ut.bookHist(h, str(idb + 2),
                            'sigma-tot vs p, ' + name + '->' + target[idnp],
                            nb, 0.5, pbeamh + 0.5)
                ut.bookHist(h, str(idb + 3),
                            'chi vs p, ' + name + '->' + target[idnp], nb, 0.5,
                            pbeamh + 0.5)
                ut.bookHist(h, str(idb + 4),
                            'Prob(normalised), ' + name + '->' + target[idnp],
                            nb, 0.5, pbeamh + 0.5)
#  keep track of histogram<->Particle id relation.
            idhist[id] = idw
            #  target is proton or neutron
            for idpn in range(2):
                idadd = idpn * 4
Пример #48
0
def bookHist(detName):
 for mu in ['','_mu','_muV0']:
  tag = detName+mu
  if detName.find('LiSc')<0:  
   ut.bookHist(h,tag,'x/y '+detName+';X [m];Y [m]',100,-3.,3.,100,-6.,6.)
  else:  
   ut.bookHist(h,tag,'z phi '+detName+';Z [m];Phi [/#pi rad]',100,-30.,40.,100,-1.,1.)
  ut.bookHist(h,tag+'_E','deposited energy MeV '+detName+';E [MeV/c^{2}]',100,0.,2.)
  ut.bookHist(h,tag+'_P','particle mom GeV '+detName+';P [GeV/c^{2}]',400,0.,400.)
  ut.bookHist(h,tag+'_LP','particle mom GeV '+detName+';P [GeV/c^{2}]',100,0.,1.)
  ut.bookHist(h,tag+'_OP','original particle mom GeV '+detName+';P [GeV/c^{2}]',400,0.,400.)
  ut.bookHist(h,tag+'_id','particle id '+detName,5001,-2499.5,2499.5)
  ut.bookHist(h,tag+'_mul','multiplicity of hits/tracks '+detName,10,-0.5,9.5)
  ut.bookHist(h,tag+'_evmul','multiplicity of hits/event '+detName,10,-0.5,9.5)
  ut.bookHist(h,tag+'_origin','r vs z;Z [m];R [m]',100,  ztarget,totl,100,0.,12.)
Пример #49
0
 for mu in ['','_mu','_muV0']:
  tag = detName+mu
  if detName.find('LiSc')<0:  
   ut.bookHist(h,tag,'x/y '+detName+';X [m];Y [m]',100,-3.,3.,100,-6.,6.)
  else:  
   ut.bookHist(h,tag,'z phi '+detName+';Z [m];Phi [/#pi rad]',100,-30.,40.,100,-1.,1.)
  ut.bookHist(h,tag+'_E','deposited energy MeV '+detName+';E [MeV/c^{2}]',100,0.,2.)
  ut.bookHist(h,tag+'_P','particle mom GeV '+detName+';P [GeV/c^{2}]',400,0.,400.)
  ut.bookHist(h,tag+'_LP','particle mom GeV '+detName+';P [GeV/c^{2}]',100,0.,1.)
  ut.bookHist(h,tag+'_OP','original particle mom GeV '+detName+';P [GeV/c^{2}]',400,0.,400.)
  ut.bookHist(h,tag+'_id','particle id '+detName,5001,-2499.5,2499.5)
  ut.bookHist(h,tag+'_mul','multiplicity of hits/tracks '+detName,10,-0.5,9.5)
  ut.bookHist(h,tag+'_evmul','multiplicity of hits/event '+detName,10,-0.5,9.5)
  ut.bookHist(h,tag+'_origin','r vs z;Z [m];R [m]',100,  ztarget,totl,100,0.,12.)
 
ut.bookHist(h,'origin','r vs z;Z [m];R [m]',100,ztarget,totl,100,0.,15.)
ut.bookHist(h,'borigin','r vs z;Z [m];R [m]',100,ztarget,totl,500,0.,30.)
ut.bookHist(h,'porigin','r vs z secondary',100,ztarget,totl,500,0.,30.)
ut.bookHist(h,'mu-inter','r vs z',100,ztarget,totl,50,0.,3.)
ut.bookHist(h,'muonP','muon momentum',100,0.,400.)
ut.bookHist(h,'weight','muon weight',1000,1.E3,1.E6)
ut.bookHist(h,'delx13','x diff first and last point,  mu-',100,-10.,10.)
ut.bookHist(h,'delx-13','x diff first and last point, mu+',100,-10.,10.)
ut.bookHist(h,'deltaElec','energy of delta electrons',100,0.,10.)
ut.bookHist(h,'secondaries','energy of delta electrons',100,0.,10.)
ut.bookHist(h,'prop_deltaElec','energy of delta elec / muon energy',100,0.,1.)
ut.bookHist(h,'dummy','',10,0.,1.)
ut.bookHist(h,'dE','',100,0.,10.,100,0.,10.)
h['dummy'].SetMaximum(10.)

histlistAll = {1:'VetoTimeDet',2:'strawstation_5',3:'strawstation_1',4:'strawstation_4',
Пример #50
0
# need to figure out which geometry was used
if not dy:
  # try to extract from input file name
  tmp = inputFile.split('.')
  try:
    dy = float( tmp[1]+'.'+tmp[2] )
  except:
    dy = None
print 'configured to process ',nEvents,' events from ' ,inputFile, ' with option Yheight = ',dy,' with vertexing',vertexing
outFile = inputFile.replace('.root','_rec.root') 
os.system('cp '+inputFile+' '+outFile)

if withHists:
 h={}
 ut.bookHist(h,'distu','distance to wire',100,0.,5.)
 ut.bookHist(h,'distv','distance to wire',100,0.,5.)
 ut.bookHist(h,'disty','distance to wire',100,0.,5.)
 ut.bookHist(h,'nmeas','nr measuerements',100,0.,50.)
#-----prepare python exit-----------------------------------------------
def pyExit():
 global fitter
 del fitter
 print "finishing pyExit" 
import atexit
atexit.register(pyExit)

from array import array
import shipunit as u
import rootUtils as ut
from ShipGeoConfig import ConfigRegistry
Пример #51
0
def myEventLoop(n):
  global ecalReconstructed
  rc = sTree.GetEntry(n)
# check if tracks are made from real pattern recognition
  measCut = measCutFK
  if sTree.GetBranch("FitTracks_PR"):    
    sTree.FitTracks = sTree.FitTracks_PR
    measCut = measCutPR
  if sTree.GetBranch("fitTrack2MC_PR"):  sTree.fitTrack2MC = sTree.fitTrack2MC_PR
  if sTree.GetBranch("Particles_PR"):    sTree.Particles   = sTree.Particles_PR
  if not checkHNLorigin(sTree): return
  wg = sTree.MCTrack[1].GetWeight()
  if not wg>0.: wg=1.
# 
# make some ecal cluster analysis if exist
  if sTree.FindBranch("EcalClusters"):
   if calReco:  ecalReconstructed.Delete()
   else:        ecalReconstructed = sTree.EcalReconstructed
   for x in caloTasks: 
    if x.GetName() == 'ecalFiller': x.Exec('start',sTree.EcalPointLite)
    elif x.GetName() == 'ecalMatch':  x.Exec('start',ecalReconstructed,sTree.MCTrack)
    else : x.Exec('start')
   for aClus in ecalReconstructed:
    mMax = aClus.MCTrack()
    if mMax <0 or mMax > sTree.MCTrack.GetEntries(): 
     aP = None # this should never happen, otherwise the ECAL MC matching has a bug
    else: aP = sTree.MCTrack[mMax]
    if aP:    
      tmp = PDG.GetParticle(aP.GetPdgCode())
      if tmp: pName = 'ecalReconstructed_'+tmp.GetName()
      else: pName = 'ecalReconstructed_'+str(aP.GetPdgCode())
    else:
      pName = 'ecalReconstructed_unknown' 
    if not h.has_key(pName): 
      ut.bookHist(h,pName,'x/y and energy for '+pName.split('_')[1],50,-3.,3.,50,-6.,6.)
    rc = h[pName].Fill(aClus.X()/u.m,aClus.Y()/u.m,aClus.RecoE()/u.GeV)
# look at distance to tracks 
    for fT in sTree.FitTracks:
     rc,pos,mom = TrackExtrapolateTool.extrapolateToPlane(fT,z_ecal)
     if rc>0:
      pdgcode = fT.getFittedState().getPDG()
      tmp = PDG.GetParticle(pdgcode)
      if tmp: tName = 'ecalReconstructed_dist_'+tmp.GetName()
      else: tName = 'ecalReconstructed_dist_'+str(aP.GetPdgCode())
      if not h.has_key(tName): 
       p = tName.split('dist_')[1]
       ut.bookHist(h,tName,'Ecal cluster distance t0 '+p,100,0.,100.*u.cm)
       ut.bookHist(h,tName.replace('dist','distx'),'Ecal cluster distance to '+p+' in X ',100,-50.*u.cm,50.*u.cm)
       ut.bookHist(h,tName.replace('dist','disty'),'Ecal cluster distance to '+p+' in Y ',100,-50.*u.cm,50.*u.cm)
      dist = ROOT.TMath.Sqrt( (aClus.X()-pos.X())**2+(aClus.Y()-pos.Y())**2 )
      rc = h[tName].Fill(dist)
      rc = h[tName.replace('dist','distx')].Fill( aClus.X()-pos.X() )
      rc = h[tName.replace('dist','disty')].Fill( aClus.Y()-pos.Y() )
# compare with old method
   for aClus in sTree.EcalClusters:
     rc = h['ecalClusters'].Fill(aClus.X()/u.m,aClus.Y()/u.m,aClus.Energy()/u.GeV)
     mMax,frac = ecalCluster2MC(aClus)
# return MC track most contributing, and its fraction of energy
     if mMax>0:    
      aP = sTree.MCTrack[mMax]   
      tmp = PDG.GetParticle(aP.GetPdgCode())
      if tmp: pName = 'ecalClusters_'+tmp.GetName()
      else: pName = 'ecalClusters_'+str(aP.GetPdgCode())
     else:
      pName = 'ecalClusters_unknown' 
     if not h.has_key(pName): ut.bookHist(h,pName,'x/y and energy for '+pName.split('_')[1],50,-3.,3.,50,-6.,6.)
     rc = h[pName].Fill(aClus.X()/u.m,aClus.Y()/u.m,aClus.Energy()/u.GeV)
     
# make some straw hit analysis
  hitlist = {}
  for ahit in sTree.strawtubesPoint:
     detID = ahit.GetDetectorID()
     top = ROOT.TVector3()
     bot = ROOT.TVector3()
     modules["Strawtubes"].StrawEndPoints(detID,bot,top)
     dw  = ahit.dist2Wire()
     if detID < 50000000 : 
      if abs(top.y())==abs(bot.y()): h['disty'].Fill(dw)
      if abs(top.y())>abs(bot.y()): h['distu'].Fill(dw)
      if abs(top.y())<abs(bot.y()): h['distv'].Fill(dw)
#
     trID = ahit.GetTrackID()
     if not trID < 0 :
      if hitlist.has_key(trID):  hitlist[trID]+=1
      else:  hitlist[trID]=1
  for tr in hitlist:  h['meanhits'].Fill(hitlist[tr])
  key = -1
  fittedTracks = {}
  for atrack in sTree.FitTracks:
   key+=1
# kill tracks outside fiducial volume
   if not checkFiducialVolume(sTree,key,dy): continue
   fitStatus   = atrack.getFitStatus()
   nmeas = fitStatus.getNdf()
   h['meas'].Fill(nmeas)
   if not fitStatus.isFitConverged() : continue
   h['meas2'].Fill(nmeas)
   if nmeas < measCut: continue
   fittedTracks[key] = atrack
# needs different study why fit has not converged, continue with fitted tracks
   rchi2 = fitStatus.getChi2()
   prob = ROOT.TMath.Prob(rchi2,int(nmeas))
   h['prob'].Fill(prob)
   chi2 = rchi2/nmeas
   fittedState = atrack.getFittedState()
   h['chi2'].Fill(chi2,wg)
   h['measVSchi2'].Fill(atrack.getNumPoints(),chi2)
   P = fittedState.getMomMag()
   Px,Py,Pz = fittedState.getMom().x(),fittedState.getMom().y(),fittedState.getMom().z()
   cov = fittedState.get6DCov()
   if len(sTree.fitTrack2MC)-1<key: continue
   mcPartKey = sTree.fitTrack2MC[key]
   mcPart    = sTree.MCTrack[mcPartKey]
   if not mcPart : continue
   Ptruth_start     = mcPart.GetP()
   Ptruthz_start    = mcPart.GetPz()
   # get p truth from first strawpoint
   Ptruth,Ptruthx,Ptruthy,Ptruthz = getPtruthFirst(sTree,mcPartKey)
   delPOverP = (Ptruth - P)/Ptruth
   h['delPOverP'].Fill(Ptruth,delPOverP)
   delPOverPz = (1./Ptruthz - 1./Pz) * Ptruthz
   h['pullPOverPx'].Fill( Ptruth,(Ptruthx-Px)/ROOT.TMath.Sqrt(cov[3][3]) )   
   h['pullPOverPy'].Fill( Ptruth,(Ptruthy-Py)/ROOT.TMath.Sqrt(cov[4][4]) )   
   h['pullPOverPz'].Fill( Ptruth,(Ptruthz-Pz)/ROOT.TMath.Sqrt(cov[5][5]) )   
   h['delPOverPz'].Fill(Ptruthz,delPOverPz)
   if chi2>chi2CutOff: continue
   h['delPOverP2'].Fill(Ptruth,delPOverP)
   h['delPOverP2z'].Fill(Ptruth,delPOverPz)
# try measure impact parameter
   trackDir = fittedState.getDir()
   trackPos = fittedState.getPos()
   vx = ROOT.TVector3()
   mcPart.GetStartVertex(vx)
   t = 0
   for i in range(3):   t += trackDir(i)*(vx(i)-trackPos(i)) 
   dist = 0
   for i in range(3):   dist += (vx(i)-trackPos(i)-t*trackDir(i))**2
   dist = ROOT.TMath.Sqrt(dist)
   h['IP'].Fill(dist) 
# ---
# loop over particles, 2-track combinations
  for HNL in sTree.Particles:
    t1,t2 = HNL.GetDaughter(0),HNL.GetDaughter(1) 
# kill tracks outside fiducial volume, if enabled
    if not checkFiducialVolume(sTree,t1,dy) or not checkFiducialVolume(sTree,t2,dy) : continue
    checkMeasurements = True
# cut on nDOF
    for tr in [t1,t2]:
      fitStatus  = sTree.FitTracks[tr].getFitStatus()
      nmeas = fitStatus.getNdf()
      if nmeas < measCut: checkMeasurements = False
    if not checkMeasurements: continue
# check mc matching 
    if not match2HNL(HNL): continue
    HNLPos = ROOT.TLorentzVector()
    HNL.ProductionVertex(HNLPos)
    HNLMom = ROOT.TLorentzVector()
    HNL.Momentum(HNLMom)
# check if DOCA info exist
    if HNL.GetMother(1)==99 :
      xv,yv,zv,doca  =  HNLPos.X(),HNLPos.Y(),HNLPos.Z(),HNLPos.T()
    else:
# redo doca calculation
     xv,yv,zv,doca,HNLMom  = RedoVertexing(t1,t2)
     if HNLMom == -1: continue
 # check if decay inside decay volume
    if Rsq(xv,yv,dy) > 1 : continue
    if zv < vetoStation_zDown  : continue  
    if zv > T1Station_zUp      : continue  
    h['Doca'].Fill(doca) 
    # if  doca > docaCut : continue
    tr = ROOT.TVector3(0,0,ShipGeo.target.z0)
    dist = ImpactParameter(tr,HNLPos,HNLMom)
    mass = HNLMom.M()
    h['IP0'].Fill(dist)  
    h['IP0/mass'].Fill(mass,dist)
    h['HNL'].Fill(mass)
    h['HNLw'].Fill(mass,wg)
#
    vetoDets['SBT'] = veto.SBT_decision(sTree)
    vetoDets['SVT'] = veto.SVT_decision(sTree)
    vetoDets['UVT'] = veto.UVT_decision(sTree)
    vetoDets['RPC'] = veto.RPC_decision(sTree)
    vetoDets['TRA'] = veto.Track_decision(sTree)
    h['nrtracks'].Fill(vetoDets['TRA'][2])
    h['nrSVT'].Fill(vetoDets['SVT'][2])
    h['nrUVT'].Fill(vetoDets['UVT'][2])
    h['nrSBT'].Fill(vetoDets['SBT'][2])
    h['nrRPC'].Fill(vetoDets['RPC'][2])
#   HNL true
    mctrack = sTree.MCTrack[sTree.fitTrack2MC[t1]]
    h['Vzresol'].Fill( (mctrack.GetStartZ()-zv)/u.cm )
    h['Vxresol'].Fill( (mctrack.GetStartX()-xv)/u.cm )
    h['Vyresol'].Fill( (mctrack.GetStartY()-yv)/u.cm )
    PosDir,newPosDir,CovMat,scalFac = {},{},{},{}
# opening angle at vertex
    newPos = ROOT.TVector3(xv,yv,zv)
    st1,st2 = sTree.FitTracks[t1].getFittedState(),sTree.FitTracks[t2].getFittedState()
    PosDir[t1] = {'position':st1.getPos(),'direction':st1.getDir(),'momentum':st1.getMom()}
    PosDir[t2] = {'position':st2.getPos(),'direction':st2.getDir(),'momentum':st2.getMom()}
    CovMat[t1] = st1.get6DCov() 
    CovMat[t2] = st2.get6DCov() 
    rep1,rep2 = ROOT.genfit.RKTrackRep(st1.getPDG()),ROOT.genfit.RKTrackRep(st2.getPDG())  
    state1,state2 = ROOT.genfit.StateOnPlane(rep1),ROOT.genfit.StateOnPlane(rep2)
    rep1.setPosMom(state1,st1.getPos(),st1.getMom())
    rep2.setPosMom(state2,st2.getPos(),st2.getMom())
    try:
     rep1.extrapolateToPoint(state1, newPos, False)
     rep2.extrapolateToPoint(state2, newPos, False)
     mom1,mom2 = rep1.getMom(state1),rep2.getMom(state2)
    except:
     mom1,mom2 = st1.getMom(),st2.getMom()
    newPosDir[t1] = {'position':rep1.getPos(state1),'direction':rep1.getDir(state1),'momentum':mom1}
    newPosDir[t2] = {'position':rep2.getPos(state2),'direction':rep2.getDir(state2),'momentum':mom2}
    oa = mom1.Dot(mom2)/(mom1.Mag()*mom2.Mag()) 
    h['oa'].Fill(oa)
# error on vertex
    scalFac[t1] = (zv-PosDir[t1]['position'][2])/PosDir[t1]['direction'][2]/PosDir[t1]['momentum'].Mag()
    scalFac[t2] = (zv-PosDir[t2]['position'][2])/PosDir[t2]['direction'][2]/PosDir[t2]['momentum'].Mag()
    XPos,covX,dist = VertexError(t1,t2,newPosDir,CovMat,scalFac)
    h['Vzpull'].Fill( (mctrack.GetStartZ()-XPos[2])/ROOT.TMath.Sqrt(covX[2][2]) )
    h['Vxpull'].Fill( (mctrack.GetStartX()-XPos[0])/ROOT.TMath.Sqrt(covX[0][0]) )
    h['Vypull'].Fill( (mctrack.GetStartY()-XPos[1])/ROOT.TMath.Sqrt(covX[1][1]) )
Пример #52
0
fM = ROOT.genfit.FieldManager.getInstance()
fM.init(bfield)

# prepare veto decisions
import shipVeto
veto = shipVeto.Task()
vetoDets={}

# fiducial cuts
vetoStation = ROOT.gGeoManager.GetTopVolume().GetNode('Veto_5')
vetoStation_zDown = vetoStation.GetMatrix().GetTranslation()[2]+vetoStation.GetVolume().GetShape().GetDZ()
T1Station = ROOT.gGeoManager.GetTopVolume().GetNode('Tr1_1')
T1Station_zUp = T1Station.GetMatrix().GetTranslation()[2]-T1Station.GetVolume().GetShape().GetDZ()

h = {}
ut.bookHist(h,'delPOverP','delP / P',400,0.,200.,100,-0.5,0.5)
ut.bookHist(h,'pullPOverPx','delPx / sigma',400,0.,200.,100,-3.,3.)
ut.bookHist(h,'pullPOverPy','delPy / sigma',400,0.,200.,100,-3.,3.)
ut.bookHist(h,'pullPOverPz','delPz / sigma',400,0.,200.,100,-3.,3.)
ut.bookHist(h,'delPOverP2','delP / P chi2/nmeas<'+str(chi2CutOff),400,0.,200.,100,-0.5,0.5)
ut.bookHist(h,'delPOverPz','delPz / Pz',400,0.,200.,100,-0.5,0.5)
ut.bookHist(h,'delPOverP2z','delPz / Pz chi2/nmeas<'+str(chi2CutOff),400,0.,200.,100,-0.5,0.5)
ut.bookHist(h,'chi2','chi2/nmeas after trackfit',100,0.,10.)
ut.bookHist(h,'prob','prob(chi2)',100,0.,1.)
ut.bookHist(h,'IP','Impact Parameter',100,0.,10.)
ut.bookHist(h,'Vzresol','Vz reco - true [cm]',100,-50.,50.)
ut.bookHist(h,'Vxresol','Vx reco - true [cm]',100,-10.,10.)
ut.bookHist(h,'Vyresol','Vy reco - true [cm]',100,-10.,10.)
ut.bookHist(h,'Vzpull','Vz pull',100,-3.,3.)
ut.bookHist(h,'Vxpull','Vx pull',100,-3.,3.)
ut.bookHist(h,'Vypull','Vy pull',100,-3.,3.)
Пример #53
0
#!/usr/bin/env python
# file to convert goliath fieldmap text file to root
# EvH 11/4/2018

import ROOT, os, sys
import rootUtils as ut
import shipunit as u
import shipRoot_conf

h = {}
# new limits x: -1118.6, 1241.4 (59); y: -411.40, 768.60 (20); z: -2512.7, 2537.3 (101)
#

ut.bookHist(h, 'Bx', 'Bx', 60, -113.86, 126.14, 21, -44.09, 79.81, 102,
            -253.77, 256.27)
ut.bookHist(h, 'By', 'By', 60, -113.86, 126.14, 21, -44.09, 79.81, 102,
            -253.77, 256.27)
ut.bookHist(h, 'Bz', 'Bz', 60, -113.86, 126.14, 21, -44.09, 79.81, 102,
            -253.77, 256.27)
ut.bookHist(h, 'Byvsz', 'By vs z for x=1.4,y=1.6', 102, -253.77, 256.27)
f = open('ExtGoliathFieldMap.txt', 'r')

i = 0
for line in f:
    i += 1
    if i < 6: continue
    x, y, z, Bx, By, Bz = line.split()
    x = float(x) / 10.
    y = float(y) / 10.
    z = float(z) / 10.
    Bx = Bx
Пример #54
0
def HNLKinematics():
    HNLorigin = {}
    ut.bookHist(h, 'HNLmomNoW', 'momentum unweighted', 100, 0., 300.)
    ut.bookHist(h, 'HNLmom', 'momentum', 100, 0., 300.)
    ut.bookHist(h, 'HNLPtNoW', 'Pt unweighted', 100, 0., 10.)
    ut.bookHist(h, 'HNLPt', 'Pt', 100, 0., 10.)
    ut.bookHist(h, 'HNLmom_recTracks', 'momentum', 100, 0., 300.)
    ut.bookHist(h, 'HNLmomNoW_recTracks', 'momentum unweighted', 100, 0., 300.)
    for n in range(sTree.GetEntries()):
        rc = sTree.GetEntry(n)
        for hnlkey in [1, 2]:
            if abs(sTree.MCTrack[hnlkey].GetPdgCode()) == 9900015:
                theHNL = sTree.MCTrack[hnlkey]
                wg = theHNL.GetWeight()
                if not wg > 0.: wg = 1.
                idMother = abs(sTree.MCTrack[hnlkey - 1].GetPdgCode())
                if not HNLorigin.has_key(idMother): HNLorigin[idMother] = 0
                HNLorigin[idMother] += wg
                P = theHNL.GetP()
                Pt = theHNL.GetPt()
                h['HNLmom'].Fill(P, wg)
                h['HNLmomNoW'].Fill(P)
                h['HNLPt'].Fill(Pt, wg)
                h['HNLPtNoW'].Fill(Pt)
                for HNL in sTree.Particles:
                    t1, t2 = HNL.GetDaughter(0), HNL.GetDaughter(1)
                    for tr in [t1, t2]:
                        xx = sTree.FitTracks[tr].getFittedState()
                        Prec = xx.getMom().Mag()
                        h['HNLmom_recTracks'].Fill(Prec, wg)
                        h['HNLmomNoW_recTracks'].Fill(Prec)
    theSum = 0
    for x in HNLorigin:
        theSum += HNLorigin[x]
    for x in HNLorigin:
        print "%4i : %5.4F relative fraction: %5.4F " % (x, HNLorigin[x],
                                                         HNLorigin[x] / theSum)
Пример #55
0
def analyzeConcrete():
 fout = ROOT.TFile('muConcrete.root','recreate')
 h['ntuple'] = ROOT.TNtuple("muons","muon flux concrete","id:px:py:pz:x:y:z:w")
 for m in ['','mu','V0']:
  ut.bookHist(h,'conc_hitz'+m,'concrete hit z '+m,100,-100.,100.)
  ut.bookHist(h,'conc_hitzP'+m,'concrete hit z vs P'+m,100,-100.,100.,100,0.,25.)
  ut.bookHist(h,'conc_hity'+m,'concrete hit y '+m,100,-15.,15.)
  ut.bookHist(h,'conc_p'+m,'concrete hit p '+m,100,0.,300.)
  ut.bookHist(h,'conc_pt'+m,'concrete hit pt '+m,100,0.,10.)
  ut.bookHist(h,'conc_hitzy'+m,'concrete hit zy '+m,100,-100.,100.,100,-15.,15.)
 top = fGeo.GetTopVolume()
 magn = top.GetNode("magyoke_1")
 z0 = magn.GetMatrix().GetTranslation()[2]/u.m
 for fn in fchain:
  f = ROOT.TFile(fn)
  if not f.FindObjectAny('cbmsim'): 
   print 'skip file ',f.GetName() 
   continue
  sTree = f.cbmsim
  nEvents = sTree.GetEntries()
  for n in range(nEvents):
   sTree.GetEntry(n)
   if sTree.MCTrack.GetEntries() > 1: 
      wg = sTree.MCTrack[1].GetWeight() 
   else: 
      wg = sTree.MCTrack[0].GetWeight() 
   for ahit in sTree.vetoPoint:
     detID = ahit.GetDetectorID()
     if logVols[detID] != 'rockD': continue  
     m=''    
     pid = ahit.PdgCode()    
     if abs(pid) == 13: m='mu'
     P = ROOT.TMath.Sqrt(ahit.GetPx()**2+ahit.GetPy()**2+ahit.GetPz()**2)
     if abs(pid) == 13 and P>3/u.GeV: 
       m='V0'
       h['ntuple'].Fill(float(pid), float(ahit.GetPx()/u.GeV),float(ahit.GetPy()/u.GeV),float(ahit.GetPz()/u.GeV),\
                   float(ahit.GetX()/u.m),float(ahit.GetY()/u.m),float(ahit.GetZ()/u.m),float(wg) )
     h['conc_hitz'+m].Fill(ahit.GetZ()/u.m-z0,wg)
     h['conc_hity'+m].Fill(ahit.GetY()/u.m,wg)
     h['conc_p'+m].Fill(P/u.GeV,wg)
     h['conc_hitzP'+m].Fill(ahit.GetZ()/u.m,P/u.GeV,wg)
     Pt = ROOT.TMath.Sqrt(ahit.GetPx()**2+ahit.GetPy()**2)
     h['conc_pt'+m].Fill(Pt/u.GeV,wg)
     h['conc_hitzy'+m].Fill(ahit.GetZ()/u.m-z0,ahit.GetY()/u.m,wg)
 #
     #start = [ahit.GetX()/u.m,ahit.GetY()/u.m,ahit.GetZ()/u.m]
     #direc = [-ahit.GetPx()/P,-ahit.GetPy()/P,-ahit.GetPz()/P]
     #t = - start[0]/direc[0]
     
 ut.bookCanvas(h,key='Resultsmu',title='muons hitting concrete',nx=1000,ny=600,cx=2,cy=2)  
 ut.bookCanvas(h,key='Results',title='hitting concrete',nx=1000,ny=600,cx=2,cy=2)  
 for m in ['','mu']:
  tc = h['Results'+m].cd(1)
  h['conc_hity'+m].Draw()
  tc = h['Results'+m].cd(2)
  h['conc_hitz'+m].Draw()
  tc = h['Results'+m].cd(3)
  tc.SetLogy(1)
  h['conc_pt'+m].Draw()
  tc = h['Results'+m].cd(4)
  tc.SetLogy(1)
  h['conc_p'+m].Draw()
  fout.cd()
  h['ntuple'].Write()
Пример #56
0
  if saveDisk: os.system('mv '+inputFile+' '+outFile)
  else :       os.system('cp '+inputFile+' '+outFile)

if not geoFile:
 tmp = inputFile.replace('ship.','geofile_full.')
 geoFile = tmp.replace('_rec','')
# try to figure out which ecal geo to load
fgeo = ROOT.TFile(geoFile)
sGeo = fgeo.FAIRGeom
if sGeo.GetVolume('EcalModule3') :  ecalGeoFile = "ecal_ellipse6x12m2.geo"
else: ecalGeoFile = "ecal_ellipse5x10m2.geo" 
print 'found ecal geo for ',ecalGeoFile

if withHists:
 h={}
 ut.bookHist(h,'distu','distance to wire',100,0.,5.)
 ut.bookHist(h,'distv','distance to wire',100,0.,5.)
 ut.bookHist(h,'disty','distance to wire',100,0.,5.)
 ut.bookHist(h,'nmeas','nr measuerements',100,0.,50.)
 ut.bookHist(h,'chi2','Chi2/DOF',100,0.,20.)
 ut.bookHist(h,'Vzpull','Vz pull',100,-3.,3.)
 ut.bookHist(h,'Vxpull','Vx pull',100,-3.,3.)
 ut.bookHist(h,'Vypull','Vy pull',100,-3.,3.)

#-----prepare python exit-----------------------------------------------
def pyExit():
 global fitter
 del fitter
 print "finishing pyExit" 
import atexit
atexit.register(pyExit)
Пример #57
0
def HNLKinematics():
 HNLorigin={}
 ut.bookHist(h,'HNLmomNoW','momentum unweighted',100,0.,300.)
 ut.bookHist(h,'HNLmom','momentum',100,0.,300.)
 ut.bookHist(h,'HNLPtNoW','Pt unweighted',100,0.,10.)
 ut.bookHist(h,'HNLPt','Pt',100,0.,10.)
 ut.bookHist(h,'HNLmom_recTracks','momentum',100,0.,300.)
 ut.bookHist(h,'HNLmomNoW_recTracks','momentum unweighted',100,0.,300.)
 for n in range(sTree.GetEntries()): 
  rc = sTree.GetEntry(n)
  for hnlkey in [1,2]: 
   if abs(sTree.MCTrack[hnlkey].GetPdgCode()) == 9900015: 
    theHNL = sTree.MCTrack[hnlkey]
    wg = theHNL.GetWeight()
    if not wg>0.: wg=1.
    idMother = abs(sTree.MCTrack[hnlkey-1].GetPdgCode())
    if not HNLorigin.has_key(idMother): HNLorigin[idMother]=0
    HNLorigin[idMother]+=wg
    P = theHNL.GetP()
    Pt = theHNL.GetPt()
    h['HNLmom'].Fill(P,wg) 
    h['HNLmomNoW'].Fill(P) 
    h['HNLPt'].Fill(Pt,wg) 
    h['HNLPtNoW'].Fill(Pt) 
    for HNL in sTree.Particles:
     t1,t2 = HNL.GetDaughter(0),HNL.GetDaughter(1) 
     for tr in [t1,t2]:
      xx  = sTree.FitTracks[tr].getFittedState()
      Prec = xx.getMom().Mag()
      h['HNLmom_recTracks'].Fill(Prec,wg) 
      h['HNLmomNoW_recTracks'].Fill(Prec)
 theSum = 0
 for x in HNLorigin: theSum+=HNLorigin[x]   
 for x in HNLorigin: print "%4i : %5.4F relative fraction: %5.4F "%(x,HNLorigin[x],HNLorigin[x]/theSum)
Пример #58
0
print('h')
bfield = ROOT.genfit.FairShipFields()
print('i')
fM = ROOT.genfit.FieldManager.getInstance()
print('j')
fM.init(bfield)
print('k')
volDict = {}
i = 0
for x in ROOT.gGeoManager.GetListOfVolumes():
    volDict[i] = x.GetName()
    i += 1
print('l')

h = {}
ut.bookHist(h, 'delPOverP', 'delP / P', 400, 0., 200., 100, -0.5, 0.5)
ut.bookHist(h, 'pullPOverPx', 'delPx / sigma', 400, 0., 200., 100, -3., 3.)
ut.bookHist(h, 'pullPOverPy', 'delPy / sigma', 400, 0., 200., 100, -3., 3.)
ut.bookHist(h, 'pullPOverPz', 'delPz / sigma', 400, 0., 200., 100, -3., 3.)
ut.bookHist(h, 'delPOverP2', 'delP / P chi2/nmeas<' + str(chi2CutOff), 400, 0.,
            200., 100, -0.5, 0.5)
ut.bookHist(h, 'delPOverPz', 'delPz / Pz', 400, 0., 200., 100, -0.5, 0.5)
ut.bookHist(h, 'delPOverP2z', 'delPz / Pz chi2/nmeas<' + str(chi2CutOff), 400,
            0., 200., 100, -0.5, 0.5)
ut.bookHist(h, 'chi2', 'chi2/nmeas after trackfit', 100, 0., 10.)
ut.bookHist(h, 'prob', 'prob(chi2)', 100, 0., 1.)
ut.bookHist(h, 'IP', 'Impact Parameter', 100, 0., 10.)
ut.bookHist(h, 'Vzresol', 'Vz reco - true [cm]', 100, -50., 50.)
ut.bookHist(h, 'Vxresol', 'Vx reco - true [cm]', 100, -10., 10.)
ut.bookHist(h, 'Vyresol', 'Vy reco - true [cm]', 100, -10., 10.)
ut.bookHist(h, 'Vzpull', 'Vz pull', 100, -5., 5.)
Пример #59
0
def main():
    parser = argparse.ArgumentParser(description='Script to create flux maps.')
    parser.add_argument(
        'inputfile',
        help='''Simulation results to use as input. '''
        '''Supports retrieving files from EOS via the XRootD protocol.''')
    parser.add_argument(
        '-o',
        '--outputfile',
        default='flux_map.root',
        help='''File to write the flux maps to. '''
        '''Will be recreated if it already exists.''')
    args = parser.parse_args()
    f = r.TFile.Open(args.outputfile, 'recreate')
    f.cd()
    maxpt = 10. * u.GeV
    maxp = 360. * u.GeV
    h = {}

    # Define histograms
    for nplane in range(0, 23):
        ut.bookHist(h, 'NuTauMu_all_{}'.format(nplane),
                    'Rpc_{};x[cm];y[cm]'.format(
                        nplane), 100, -300, +300, 100, -300,
                    300)
        ut.bookHist(h, 'NuTauMu_mu_{}'.format(nplane),
                    'Rpc_{};x[cm];y[cm]'.format(
                        nplane), 100, -300, +300, 100, -300,
                    300)
    for suffix, title in [('mu', '#mu#pm hits'), ('all', 'All hits')]:
        ut.bookHist(h, 'muon_tiles_{}'.format(suffix),
                    '{};x[cm];y[cm]'.format(title), 200, -1000, +1000, 90,
                    -900, 900)
        ut.bookHist(h, 'muon_bars_x_{}'.format(suffix),
                    '{};x[cm];y[cm]'.format(title), 2, -300, +300, 240, -600,
                    600)
        ut.bookHist(h, 'muon_bars_y_{}'.format(suffix),
                    '{};x[cm];y[cm]'.format(title), 120, -300, +300, 4, -600,
                    600)
        ut.bookHist(h, 'timing_{}'.format(suffix),
                    '{};x[cm];y[cm]'.format(title), 3, -252, +252, 167, -501,
                    501)
        ut.bookHist(h, 'TargetTracker_{}'.format(suffix),
                    '{};x[cm];y[cm]'.format(title), 120, -60, 60, 120, -60,
                    60)
        ut.bookHist(h, 'TargetTracker_yvsz_{}'.format(suffix),
                    '{};z[cm];y[cm]'.format(
                        title), 400, -3300, -2900, 120, -60,
                    60)
        ut.bookHist(h, 'TargetTracker_xvsz_{}'.format(suffix),
                    '{};z[cm];x[cm]'.format(
                        title), 400, -3300, -2900, 120, -60,
                    60)
        ut.bookHist(h, 'NuTauMu_{}'.format(suffix),
                    '{};x[cm];y[cm]'.format(title), 100, -300, +300, 100, -300,
                    300)
        ut.bookHist(h, 'NuTauMu_yvsz_{}'.format(suffix),
                    '{};z[cm];y[cm]'.format(
                        title), 200, -2680, -2480, 600, -300,
                    300)
        ut.bookHist(h, 'NuTauMu_xvsz_{}'.format(suffix),
                    '{};z[cm];x[cm]'.format(
                        title), 200, -2680, -2480, 600, -300,
                    300)
        ut.bookHist(h, 'ECAL_TP_{}'.format(suffix),
                    '{};x[cm];y[cm]'.format(title), 167, -501, +501, 334,
                    -1002, 1002)
        ut.bookHist(h, 'ECAL_Alt_{}'.format(suffix),
                    '{};x[cm];y[cm]'.format(title), 50, -500, +500, 100, -1000,
                    1000)
        ut.bookHist(h, 'SBT_Liquid_{}'.format(suffix),
                    '{};z[cm];#phi'.format(title), 100, -3000, +3000, 100,
                    -r.TMath.Pi(), r.TMath.Pi())
        ut.bookHist(h, 'SBT_Plastic_{}'.format(suffix),
                    '{};z[cm];#phi'.format(title), 100, -3000, +3000, 100,
                    -r.TMath.Pi(), r.TMath.Pi())
        for station in range(1, 5):
            ut.bookHist(h, 'T{}_{}'.format(station, suffix),
                        '{};x[cm];y[cm]'.format(title), 10, -250, +250, 20,
                        -500, 500)

    ut.bookHist(h, 'NuTauMu_mu_p', '#mu#pm;p[GeV];', 100, 0, maxp)
    ut.bookHist(h, 'NuTauMu_mu_pt', '#mu#pm;p_t[GeV];', 100, 0,
                maxpt)
    ut.bookHist(h, 'NuTauMu_mu_ppt', '#mu#pm;p[GeV];p_t[GeV];',
                100, 0, maxp, 100, 0, maxpt)
    ut.bookHist(h, 'NuTauMu_all_p', '#mu#pm;p[GeV];', 100, 0, maxp)
    ut.bookHist(h, 'NuTauMu_all_pt', '#mu#pm;p_t[GeV];', 100, 0,
                maxpt)
    ut.bookHist(h, 'NuTauMu_all_ppt', '#mu#pm;p[GeV];p_t[GeV];',
                100, 0, maxp, 100, 0, maxpt)

    for suffix in ['', '_original']:
        ut.bookHist(h, 'mu_p{}'.format(suffix), '#mu#pm;p[GeV];', 100, 0, maxp)
        ut.bookHist(h, 'mu_pt{}'.format(suffix), '#mu#pm;p_t[GeV];', 100, 0,
                    maxpt)
        ut.bookHist(h, 'mu_ppt{}'.format(suffix), '#mu#pm;p[GeV];p_t[GeV];',
                    100, 0, maxp, 100, 0, maxpt)
    ut.bookHist(h, 'ECAL_TP_e', 'e#pm with E#geq 250 MeV;x[cm];y[cm]', 167,
                -501, +501, 334, -1002, 1002)
    ut.bookHist(h, 'ECAL_Alt_e', 'e#pm with E#geq 250 MeV;x[cm];y[cm]', 50,
                -500, +500, 100, -1000, 1000)
    ut.bookHist(h, 'ECAL_TP_gamma', '#gamma;x[cm];y[cm]', 167, -501, +501, 334,
                -1002, 1002)
    ut.bookHist(h, 'ECAL_Alt_gamma', '#gamma;x[cm];y[cm]', 50, -500, +500, 100,
                -1000, 1000)
    ut.bookHist(h, 'ECAL_e_E', 'e#pm;E[GeV/c^{2}];', 100, 0, 1)
    ut.bookHist(h, 'ECAL_gamma_E', '#gamma;E[GeV/c^{2}];', 100, 0, 1)
    ch = r.TChain('cbmsim')
    ch.Add(args.inputfile)
    n = ch.GetEntries()
    print n
    i = 0
    for event in ch:
        if i % 10000 == 0:
            print '{}/{}'.format(i, n)
        i += 1
        muon = False
        for hit in event.strawtubesPoint:
            if hit:
                if not hit.GetEnergyLoss() > 0:
                    continue
                trid = hit.GetTrackID()
                assert trid > 0
                weight = event.MCTrack[trid].GetWeight()
                x = hit.GetX()
                y = hit.GetY()
                z = hit.GetZ()
                px = hit.GetPx()
                py = hit.GetPy()
                pz = hit.GetPz()
                pt = np.hypot(px, py)
                P = np.hypot(pz, pt)
                pid = hit.PdgCode()
                assert pid not in [12, -12, 14, -14, 16, -16]
                detector_ID = hit.GetDetectorID()
                station = detector_ID / 10000000
                h['T{}_all'.format(station)].Fill(x, y, weight)
                if abs(pid) == 13:
                    muon = True
                    muonid = trid
                    h['T{}_mu'.format(station)].Fill(x, y, weight)
                    h['mu_p'].Fill(P, weight)
                    h['mu_pt'].Fill(pt, weight)
                    h['mu_ppt'].Fill(P, pt, weight)
        for hit in event.EcalPoint:
            if hit:
                if not hit.GetEnergyLoss() > 0:
                    continue
                trid = hit.GetTrackID()
                assert trid > 0
                weight = event.MCTrack[trid].GetWeight()
                x = hit.GetX()
                y = hit.GetY()
                px = hit.GetPx()
                py = hit.GetPy()
                pz = hit.GetPz()
                pt = np.hypot(px, py)
                P = np.hypot(pz, pt)
                pid = hit.PdgCode()
                if pid in [12, -12, 14, -14, 16, -16]:
                    continue
                h['ECAL_TP_all'].Fill(x, y, weight)
                h['ECAL_Alt_all'].Fill(x, y, weight)
                if abs(pid) == 13:
                    muon = True
                    muonid = trid
                    h['mu_p'].Fill(P, weight)
                    h['mu_pt'].Fill(pt, weight)
                    h['mu_ppt'].Fill(P, pt, weight)
                    h['ECAL_TP_mu'].Fill(x, y, weight)
                    h['ECAL_Alt_mu'].Fill(x, y, weight)
                elif abs(pid) == 11:
                    Esq = px ** 2 + py ** 2 + pz ** 2 + 0.000511 ** 2
                    h['ECAL_e_E'].Fill(np.sqrt(Esq), weight)
                    h['ECAL_TP_e'].Fill(x, y, weight)
                    h['ECAL_Alt_e'].Fill(x, y, weight)
                elif abs(pid) == 22:
                    Esq = px ** 2 + py ** 2 + pz ** 2
                    h['ECAL_gamma_E'].Fill(np.sqrt(Esq), weight)
                    h['ECAL_TP_gamma'].Fill(x, y, weight)
                    h['ECAL_Alt_gamma'].Fill(x, y, weight)
        for hit in event.TTPoint:
            if hit:
                if not hit.GetEnergyLoss() > 0:
                    continue
                trid = hit.GetTrackID()
                assert trid > 0
                detID = hit.GetDetectorID()
                weight = event.MCTrack[trid].GetWeight()
                x = hit.GetX()
                y = hit.GetY()
                z = hit.GetZ()
                px = hit.GetPx()
                py = hit.GetPy()
                pz = hit.GetPz()
                pt = np.hypot(px, py)
                P = np.hypot(pz, pt)
                pid = hit.PdgCode()
                assert pid not in [12, -12, 14, -14, 16, -16]
                if detID == 0:
                    h['TargetTracker_all'].Fill(x, y, weight)
                h['TargetTracker_xvsz_all'].Fill(z, x, weight)
                h['TargetTracker_yvsz_all'].Fill(z, y, weight)
                if abs(pid) == 13:
                    muon = True
                    muonid = trid
                    h['mu_p'].Fill(P, weight)
                    h['mu_pt'].Fill(pt, weight)
                    h['mu_ppt'].Fill(P, pt, weight)
                    if detID == 0:
                        h['TargetTracker_mu'].Fill(x, y, weight)
                    h['TargetTracker_xvsz_mu'].Fill(z, x, weight)
                    h['TargetTracker_yvsz_mu'].Fill(z, y, weight)
        for hit in event.ShipRpcPoint:
            if hit:
                if not hit.GetEnergyLoss() > 0:
                    continue
                trid = hit.GetTrackID()
                assert trid > 0
                detID = hit.GetDetectorID()
                nplane = detID - 10000
                weight = event.MCTrack[trid].GetWeight()
                x = hit.GetX()
                y = hit.GetY()
                z = hit.GetZ()
                px = hit.GetPx()
                py = hit.GetPy()
                pz = hit.GetPz()
                pt = np.hypot(px, py)
                P = np.hypot(pz, pt)
                pid = hit.PdgCode()
                assert pid not in [12, -12, 14, -14, 16, -16]
                h['NuTauMu_all'].Fill(x, y, weight)
                if nplane >= 0:
                    h['NuTauMu_all_{}'.format(nplane)].Fill(x, y, weight)
                h['NuTauMu_xvsz_all'].Fill(z, x, weight)
                h['NuTauMu_yvsz_all'].Fill(z, y, weight)
                if detID == 10000:
                    h['NuTauMu_all_p'].Fill(P, weight)
                    h['NuTauMu_all_pt'].Fill(pt, weight)
                    h['NuTauMu_all_ppt'].Fill(P, pt, weight)
                if abs(pid) == 13:
                    muon = True
                    muonid = trid
                    h['mu_p'].Fill(P, weight)
                    h['mu_pt'].Fill(pt, weight)
                    h['mu_ppt'].Fill(P, pt, weight)
                    h['NuTauMu_mu'].Fill(x, y, weight)
                    if nplane >= 0:
                        # fill the histogram corresponding to nplane
                        h['NuTauMu_mu_{}'.format(nplane)].Fill(x, y, weight)
                    if detID == 10000:
                        h['NuTauMu_mu_p'].Fill(P, weight)
                        h['NuTauMu_mu_pt'].Fill(pt, weight)
                        h['NuTauMu_mu_ppt'].Fill(P, pt, weight)
                    h['NuTauMu_xvsz_mu'].Fill(z, x, weight)
                    h['NuTauMu_yvsz_mu'].Fill(z, y, weight)
        for hit in event.TimeDetPoint:
            if hit:
                if not hit.GetEnergyLoss() > 0:
                    continue
                trid = hit.GetTrackID()
                assert trid > 0
                weight = event.MCTrack[trid].GetWeight()
                x = hit.GetX()
                y = hit.GetY()
                z = hit.GetZ()
                px = hit.GetPx()
                py = hit.GetPy()
                pz = hit.GetPz()
                pt = np.hypot(px, py)
                P = np.hypot(pz, pt)
                pid = hit.PdgCode()
                assert pid not in [12, -12, 14, -14, 16, -16]
                h['timing_all'].Fill(x, y, weight)
                if abs(pid) == 13:
                    muon = True
                    muonid = trid
                    h['mu_p'].Fill(P, weight)
                    h['mu_pt'].Fill(pt, weight)
                    h['mu_ppt'].Fill(P, pt, weight)
                    h['timing_mu'].Fill(x, y, weight)
        for hit in event.muonPoint:
            if hit:
                if not hit.GetEnergyLoss() > 0:
                    continue
                trid = hit.GetTrackID()
                assert trid > 0
                weight = event.MCTrack[trid].GetWeight()
                x = hit.GetX()
                y = hit.GetY()
                px = hit.GetPx()
                py = hit.GetPy()
                pz = hit.GetPz()
                pt = np.hypot(px, py)
                P = np.hypot(pz, pt)
                pid = hit.PdgCode()
                assert pid not in [12, -12, 14, -14, 16, -16]
                h['muon_tiles_all'].Fill(x, y, weight)
                h['muon_bars_x_all'].Fill(x, y, weight)
                h['muon_bars_y_all'].Fill(x, y, weight)
                if abs(pid) == 13:
                    muon = True
                    muonid = trid
                    h['mu_p'].Fill(P, weight)
                    h['mu_pt'].Fill(pt, weight)
                    h['mu_ppt'].Fill(P, pt, weight)
                    h['muon_tiles_mu'].Fill(x, y, weight)
                    h['muon_bars_y_mu'].Fill(x, y, weight)
                    h['muon_bars_x_mu'].Fill(x, y, weight)
        for hit in event.vetoPoint:
            if hit:
                if not hit.GetEnergyLoss() > 0:
                    continue
                trid = hit.GetTrackID()
                assert trid > 0
                weight = event.MCTrack[trid].GetWeight()
                x = hit.GetX()
                y = hit.GetY()
                z = hit.GetZ()
                px = hit.GetPx()
                py = hit.GetPy()
                pz = hit.GetPz()
                pt = np.hypot(px, py)
                P = np.hypot(pz, pt)
                pid = hit.PdgCode()
                detector_ID = hit.GetDetectorID()
                assert pid not in [12, -12, 14, -14, 16, -16]
                phi = r.TMath.ATan2(y, x)
                if 99999 < detector_ID < 999999:
                    h['SBT_Liquid_all'].Fill(z, phi, weight)
                    if abs(pid) == 13:
                        muon = True
                        muonid = trid
                        h['mu_p'].Fill(P, weight)
                        h['mu_pt'].Fill(pt, weight)
                        h['mu_ppt'].Fill(P, pt, weight)
                        h['SBT_Liquid_mu'].Fill(z, phi, weight)
                    continue
                elif detector_ID > 999999:
                    h['SBT_Plastic_all'].Fill(z, phi, weight)
                    if abs(pid) == 13:
                        muon = True
                        muonid = trid
                        h['mu_p'].Fill(P, weight)
                        h['mu_pt'].Fill(pt, weight)
                        h['mu_ppt'].Fill(P, pt, weight)
                        h['SBT_Plastic_mu'].Fill(z, phi, weight)
                    continue
                print 'Unidentified vetoPoint.'
        if muon:
            original_muon = event.MCTrack[muonid]
            weight = original_muon.GetWeight()
            h['mu_p_original'].Fill(original_muon.GetP(), weight)
            h['mu_pt_original'].Fill(original_muon.GetPt(), weight)
            h['mu_ppt_original'].Fill(original_muon.GetP(),
                                      original_muon.GetPt(), weight)
            # NOTE: muons are counted several times if they create several hits
            #       But the original muon is only counted once.
    print 'Event loop done'
    for key in h:
        classname = h[key].Class().GetName()
        if 'TH' in classname or 'TP' in classname:
            h[key].Write()
    f.Close()