Ejemplo n.º 1
0
def readHists(prods=['disV50','disV60','disV70','disV80','disCLBY0','disCLBY1','disCLBY2','disCLBY3']):
 first = True
 if not os.uname()[1].find('ubuntu')<0:  
   path = '/media/Data/HNL/'
   sdir = {'disV':'muVetoDIS','disCLBY':'clbyDIS','disEM':'muVetoEM'}
 else: 
   path = '/afs/cern.ch/project/lbcern/vol2/truf/'
   sdir = {'disV':'muVDIS','disCLBY':'clbyDIS','disEM':'muVetoEM'}
 sweights = {'disV':1E4,'disCLBY':5*1E3,'disEM':1E3}
# known productions:
# muDIS ship.10.0.muonDIS-TGeant4V10X_rec.root
# clby  ship.10.0.muonDIS-TGeant4_Ana_disCLBY30.root
# nu in air: ship.10.0.Genie-TGeant4_neutrino_82X_Ana.root
 listOfFiles = []
 tmp = "ship.10.0.muonDIS-TGeant4_Ana.root"
 for r in prods:
    for x in sdir: 
     if x in r: subdir = path+sdir[x]+'/'
    for i in range(1,10):
     theFile = subdir+r+str(i)+'/'+tmp 
     if os.path.exists(theFile):   
      listOfFiles.append(theFile)  
 for outFileH in listOfFiles:
  print 'read histograms from ',outFileH
  for x in sdir: 
     if x in outFileH: sweight = sweights[x]
  ut.readHists(h,outFileH)
  outFileP = outFileH.replace('.root','.pkl')
  f = open(outFileP)
  if first:
    first = False
    weightsUsed = pickle.load(f)
    for wkey in weightsUsed: 
     weightsUsed[wkey][1]=weightsUsed[wkey][1]*sweight
  else:
    temp =  pickle.load(f)
    for wkey in temp: 
     if not weightsUsed.has_key(wkey) : weightsUsed[wkey]=[0,0]
     weightsUsed[wkey][0]+= temp[wkey][0]
     weightsUsed[wkey][1]+= temp[wkey][1]*sweight
 makePlots()
 makeV0Plots()
 makePlotsForTP()
 print "Analysis of weights"
 #   weightsUsed[wkey][0]+= Nexptected # sum of expected muon interactions   
 #   weightsUsed[wkey][1]+= 1.         # counts how often a muon weight had been used
 print "weight    sum of weights  sum of entries     mean"
 for wkey in weightsUsed:
  mean = weightsUsed[wkey][0]/weightsUsed[wkey][1]
  print wkey, weightsUsed[wkey], mean 
  # print "corresponding pot: %10.2G"%(2E15/wkey/mean*1E4*60) # ??? discovered 5 August, why 2E15? should be 5E13!!!
  print "corresponding pot: %10.2G * number of iterations(2*30) * reuse of muon 1E4 * 2(like sign)"%(5E13/wkey/mean)  
  print " == %10.2G"%(5E13/wkey/mean*60*2*2)  # 60 == 30 x CERN/Yandex statistics,  2 iterations, 2 like sign
#
 print "veto counters"
 for c in vetoDets:
  print c,h['IP0/mass-'+c].GetEntries()
# save the summed histos
 fsum = "ship.10.0.muonDIS-TGeant4_Ana-Prods"+str(len(prods))+".root" 
 ut.writeHists(h,fsum,plusCanvas=True)
def makePrintout():
 # Histos_2000000-2001500_10.0.root
 ut.readHists(hunbiased,'/media/microdisk/HNL/muonBackground/Histos_1000000-1000600_10.0.root')
 ut.readHists(hbiased,'hadded_Histos_1_10.0.root')

 unbiased = {}
 biased = {}
 for l in hunbiased:
  unbiased[l]=hunbiased[l].GetSumOfWeights()
 for l in hbiased:
  if l.find('proj') < 0 and l.find('test') < 0 and l.find('pids') < 0 : biased[l]=hbiased[l].GetSumOfWeights()
 p={}
 for i in range( 1,hbiased['pids'].GetNbinsX() + 1 ):
   c = hbiased['pids'].GetBinContent(i)
   if c>0: p[int(hbiased['pids'].GetBinCenter(i))]=c
 
 sorted_p = sorted(p.items(), key=operator.itemgetter(1))
 for p in sorted_p:
  print "%25s : %5.2G"%(pdg.GetParticle(p[0]).GetName(),float(p[1]))
 sorted_pr = sorted(biased.items(), key=operator.itemgetter(1))
 print "origin of muons"
 for p in sorted_pr:
  if not p[0].find('Hadronic inelastic')<0:
     if len(p[0])>len( 'Hadronic inelastic' ): continue
  denom = 0
  if unbiased.has_key(p[0]): denom = unbiased[p[0]]
  if denom >0:
   fac = float(p[1])/denom
   print "%40s : %5.2G %5.1F"%(p[0],float(p[1]),fac)
  else:
   print "%40s : %5.2G "%(p[0],float(p[1]))
Ejemplo n.º 3
0
def BigEventLoop():
# how to parallelize?
# one process for each file?
 # Setup a list of processes that we want to run
 processes = []
 for fn in fchain: 
  processes.append(mp.Process(target=processOneFile, args=(fn,output) ) )
# Run processes
 for p in processes: p.start()
# Exit the completed processes
 for p in processes: p.join()
# clean histos before reading in the new ones
 for x in h: h[x].Reset()
 for fn in fchain: 
   ut.readHists(h,fn.replace(".root","-hists.root")) 
# make list of hists with entries
 k = 1
 for x in histlistAll:
  if h.has_key(histlistAll[x]): 
   histlist[k]=histlistAll[x]
# add muons and make total
   for x in ['','_E','_P','_LP','_OP','_id','_mul','_evmul','_origin']:
    rc = h[histlist[k]+'_mu'+x].Add(h[histlist[k]+'_muV0'+x],1.)
    rc = h[histlist[k]+x].Add(h[histlist[k]+'_mu'+x],1.)
   k+=1
 nstations = len(histlist)
 makePlots(nstations)
Ejemplo n.º 4
0
def makePrintout():
 # Histos_2000000-2001500_10.0.root
 ut.readHists(hunbiased,'/media/microdisk/HNL/muonBackground/Histos_1000000-1000600_10.0.root')
 ut.readHists(hbiased,'hadded_Histos_1_10.0.root')

 unbiased = {}
 biased = {}
 for l in hunbiased:
  unbiased[l]=hunbiased[l].GetSumOfWeights()
 for l in hbiased:
  if l.find('proj') < 0 and l.find('test') < 0 and l.find('pids') < 0 : biased[l]=hbiased[l].GetSumOfWeights()
 p={}
 for i in range( 1,hbiased['pids'].GetNbinsX() + 1 ):
   c = hbiased['pids'].GetBinContent(i)
   if c>0: p[int(hbiased['pids'].GetBinCenter(i))]=c
 
 sorted_p = sorted(p.items(), key=operator.itemgetter(1))
 for p in sorted_p:
  print("%25s : %5.2G"%(pdg.GetParticle(p[0]).GetName(),float(p[1])))
 sorted_pr = sorted(biased.items(), key=operator.itemgetter(1))
 print("origin of muons")
 for p in sorted_pr:
  if not p[0].find('Hadronic inelastic')<0:
     if len(p[0])>len( 'Hadronic inelastic' ): continue
  denom = 0
  if p[0] in unbiased: denom = unbiased[p[0]]
  if denom >0:
   fac = float(p[1])/denom
   print("%40s : %5.2G %5.1F"%(p[0],float(p[1]),fac))
  else:
   print("%40s : %5.2G "%(p[0],float(p[1])))
Ejemplo n.º 5
0
def mergeHistosMakePlots(p):
 if not type(p)==type([]): pl=[p]
 else: pl = p
 hlist = ''
 for p in pl:
   prefix = str(p) 
   for x in os.listdir('.'):
    if not x.find(prefix)<0: 
       if os.path.isdir(x) : 
         hlist += x+'/ShipAna.root '
 print "-->",hlist
 os.system('hadd -f ShipAna.root '+hlist)
 ut.readHists(h,"ShipAna.root")
 print h['meanhits'].GetEntries()
 if 1>0: 
   ut.bookCanvas(h,key='strawanalysis',title='Distance to wire and mean nr of hits',nx=1200,ny=600,cx=2,cy=1)
#
   cv = h['strawanalysis'].cd(1)
   h['disty'].DrawCopy()
   h['distu'].DrawCopy('same')
   h['distv'].DrawCopy('same')
   cv = h['strawanalysis'].cd(2)
   h['meanhits'].DrawCopy()
   print h['meanhits'].GetEntries()

   ut.bookCanvas(h,key='fitresults',title='Fit Results',nx=1600,ny=1200,cx=2,cy=2)
   cv = h['fitresults'].cd(1)
   h['delPOverP'].Draw('box')
   cv = h['fitresults'].cd(2)
   cv.SetLogy(1)
   h['chi2'].Draw()
   cv = h['fitresults'].cd(3)
   h['delPOverP_proj'] = h['delPOverP'].ProjectionY()
   ROOT.gStyle.SetOptFit(11111)
   h['delPOverP_proj'].Draw()
   h['delPOverP_proj'].Fit('gaus')
   cv = h['fitresults'].cd(4)
   h['delPOverP2_proj'] = h['delPOverP2'].ProjectionY()
   h['delPOverP2_proj'].Draw()
   fitSingleGauss('delPOverP2_proj')
   h['fitresults'].Print('fitresults.gif')
   ut.bookCanvas(h,key='fitresults2',title='Fit Results',nx=1600,ny=1200,cx=2,cy=2)
   print 'finished with first canvas'
   cv = h['fitresults2'].cd(1)
   h['Doca'].Draw()
   cv = h['fitresults2'].cd(2)
   h['IP0'].Draw()
   cv = h['fitresults2'].cd(3)
   h['HNL'].Draw()
   fitSingleGauss('HNL',0.,2.)
   cv = h['fitresults2'].cd(4)
   h['IP0/mass'].Draw('box')
   h['fitresults2'].Print('fitresults2.gif')
   h['strawanalysis'].Print('strawanalysis.gif')
   print 'finished making plots'
Ejemplo n.º 6
0
def addAllHistograms():
 h={}
 ecut = '10.0'
 Nmax=45000
 path = os.environ['EOSSHIP']+"/eos/experiment/ship/data/Mbias/background-prod-2018/"
 ut.bookCanvas(h,key='canvas',title='debug',nx=1600,ny=1200,cx=1,cy=1)
 h['canvas'].SetLogy(1)
 for i in range(0,Nmax,1000):
  fname = "pythia8_Geant4_"+ecut+"_c"+str(i)+".root"
  ut.readHists(h,path+fname)
  if i==0:
    h[1012].Draw()
 for x in h.keys():
   if h[x].GetName().find('proj')>0: rc = h.pop(x)
 ut.writeHists(h,"pythia8_Geant4_"+ecut+"_c"+str(Nmax)+"-histos.root")
Ejemplo n.º 7
0
def readAndMergeHistos(prods):
 for p in prods:
   x=p
   if p.find('.root')<0: x=p+'.root' 
   ut.readHists(h,x)
# make list of hists with entries
 k = 1
 for x in histlistAll:
  if h.has_key(histlistAll[x]): 
   histlist[k]=histlistAll[x]
   k+=1
 nstations = len(histlist)
 print "make plots for ",nstations 
 makePlots(nstations)
 printAndCopy(prods[0].replace('.root',''))
Ejemplo n.º 8
0
def readAndMergeHistos(prods):
 for p in prods:
   x=p
   if p.find('.root')<0: x=p+'.root' 
   ut.readHists(h,x)
# make list of hists with entries
 k = 1
 for x in histlistAll:
  if h.has_key(histlistAll[x]): 
   histlist[k]=histlistAll[x]
   k+=1
 nstations = len(histlist)
 print "make plots for ",nstations 
 makePlots(nstations)
 printAndCopy(prods[0].replace('.root',''))
def addAllHistograms():
 h={}
 ecut = '10.0'
 Nmax=45000
 path = os.environ['EOSSHIP']+"/eos/experiment/ship/data/Mbias/background-prod-2018/"
 ut.bookCanvas(h,key='canvas',title='debug',nx=1600,ny=1200,cx=1,cy=1)
 h['canvas'].SetLogy(1)
 for i in range(0,Nmax,1000):
  fname = "pythia8_Geant4_"+ecut+"_c"+str(i)+".root"
  ut.readHists(h,path+fname)
  if i==0:
    h[1012].Draw()
 tmp = h.keys()
 for x in tmp:
   if h[x].GetName().find('proj')>0: rc = h.pop(x)
 ut.writeHists(h,"pythia8_Geant4_"+ecut+"_c"+str(Nmax)+"-histos.root")
Ejemplo n.º 10
0
def checkHistos():
 dirList=getFilesLocal()
 Ntot = 0
 shit = []
 for d in dirList:
  nfailed = 0
  for x in os.listdir(d):
    if not x.find('histos-analysis-')<0:
        h={}
        ut.readHists(h,d+'/'+x,['p/pt'])
        N = h['p/pt'].GetEntries()
        if N == 0: nfailed+=1
        print d+'/'+x,N
        Ntot+=N
  print nfailed
  if nfailed == 10: shit.append(d)
 print Ntot
 return shit
Ejemplo n.º 11
0
def checkHistos():
    dirList = getFilesLocal()
    Ntot = 0
    shit = []
    for d in dirList:
        nfailed = 0
        for x in os.listdir(d):
            if not x.find('histos-analysis-') < 0:
                h = {}
                ut.readHists(h, d + '/' + x, ['p/pt'])
                N = h['p/pt'].GetEntries()
                if N == 0: nfailed += 1
                print d + '/' + x, N
                Ntot += N
        print nfailed
        if nfailed == 10: shit.append(d)
    print Ntot
    return shit
Ejemplo n.º 12
0
def finalResult():
 h10={}
 ut.readHists(h10,'pythia8_Geant4_10.0_c0-67000_nu.root')
 h1={}
 ut.readHists(h1,'pythia8_Geant4_1.0_c0-19000_nu.root')
 c10={}
 ut.readHists(c10,'pythia8_Geant4_charm_10.0_nu.root')
 c1={}
 ut.readHists(c1,'pythia8_Geant4_charm_1.0_nu.root')
 cmd = "hadd pythia8_Geant4_10.0_withCharm_nu.root pythia8_Geant4_10.0_c0-67000_nu.root pythia8_Geant4_charm_10.0_nu.root"
 os.system(cmd)
 cmd = "hadd pythia8_Geant4_1.0_withCharm_nu.root pythia8_Geant4_1.0_c0-19000_nu.root pythia8_Geant4_charm_1.0_nu.root"
 os.system(cmd)
Ejemplo n.º 13
0
def readBack(fn):
  ut.readHists(h,fn)
  for x in h:
   if h[x].ClassName()=='TCanvas': h[x].Draw()
Ejemplo n.º 14
0
def BigEventLoop():
 pid = 1
 for fn in fchain: 
  if os.path.islink(fn): 
    rfn = os.path.realpath(fn).split('eos')[1]
    fn  = 'root://eoslhcb.cern.ch//eos/'+rfn
  elif not os.path.isfile(fn): 
    print "Don't know what to do with",fn
    1/0 
  if parallel: 
# process files parallel instead of sequential
   processes.append(mp.Process(target=executeOneFile, args=(fn,output,pid) ) )
   pid+=1 
  else:
   processes.append(fn)
# Run processes
 n=0
 for p in processes:
   if parallel: 
       p.start()
       n+=1
   else: executeOneFile(p)
 if parallel:
# Exit the completed processes
   for p in processes: p.join()
# clean histos before reading in the new ones
   for x in h: h[x].Reset()
   print "now, collect the output"
   pid = 1
   for p in processes:
    ut.readHists(h,'tmpHists_'+str(pid)+'.root')
    pid+=1
# compactify liquid scintillator
 for mu in ['','_mu','_muV0']:
  for x in ['','_E','_P','_LP','_OP','_id','_mul','_evmul','_origin','_originmu']:
    for k in [1,2,3,5]: 
     first = True
     for j in hLiSc[k]:
      detName=hLiSc[k][j]
      tag  = detName+mu+x
      newh = detName[0:2]+'LiSc'+mu+x
      if not h.has_key(tag): continue 
      if first: 
         h[newh] = h[tag].Clone(newh)
         h[newh].SetTitle( h[tag].GetTitle().split('_')[0])
         first = False
      else:  rc = h[newh].Add(h[tag])
# compactify muon stations
 for mu in ['','_mu','_muV0']:
   for x in ['','_E','_P','_LP','_OP','_id','_mul','_evmul','_origin','_originmu']:
    first = True
    for j in hMuon: 
     detName=hMuon[j]
     tag  = detName+mu+x
     newh = 'muondet'+mu+x
     if first: 
       h[newh] = h[tag].Clone(newh)
       h[newh].SetTitle( h[tag].GetTitle().split(' ')[0]+' '+newh)
       first = False
     else:  rc = h[newh].Add(h[tag])
 
 # make list of hists with entries
 k = 1
 for x in histlistAll:
  if h.has_key(histlistAll[x]):
   histlist[k]=histlistAll[x]    
# make cumulative histograms
   for c in ['','_E','_P','_LP','_OP','_id','_mul','_evmul','_origin','_originmu']:
    h[histlist[k]+'_mu'+c].Add(  h[histlist[k]+'_muV0'+c] )
    h[histlist[k]+c].Add(  h[histlist[k]+'_mu'+c] )
    h[histlist[k]+c].SetMinimum(0.) 
    h[histlist[k]+'_mu'+c].SetMinimum(0.) 
    h[histlist[k]+'_muV0'+c] .SetMinimum(0.) 
   k+=1
 nstations = len(histlist)
 makePlots(nstations)
Ejemplo n.º 15
0
def makeSummaryPlot():
    # using data in /mnt/hgfs/microDisk/Data/eloss/eloss_sum.root
    # krypton total interaction length= 1.97246306079 total rad length= 26.5231000393
    pdg = {
        10.0: 1.914,
        14.0: 1.978,
        20.0: 2.055,
        30.0: 2.164,
        40.0: 2.263,
        80.0: 2.630,
        100.: 2.810,
        140.: 3.170,
        200.: 3.720,
        277.: 4.420,
        300.: 4.631,
        400.: 5.561
    }
    h['Gpdg'] = ROOT.TGraph(len(pdg))
    Gpdg = h['Gpdg']
    Gpdg.SetMarkerColor(ROOT.kRed)
    Gpdg.SetMarkerStyle(20)
    keys = sorted(pdg.keys())
    for n in range(len(keys)):
        Gpdg.SetPoint(n, keys[n], pdg[keys[n]])
    density = 2.413
    length = 125.0
    ut.readHists(h, "/mnt/hgfs/microDisk/Data/eloss/eloss_sum.root")
    ut.readHists(h, "/mnt/hgfs/microDisk/Data/eloss/eloss_withRaw.root")
    ut.bookCanvas(h, key='summary', title=" ", nx=1200, ny=600, cx=2, cy=1)
    tc = h['summary'].cd(1)
    h['0'] = h['eloss'].ProjectionX('0', 1, h['eloss'].GetNbinsY())
    h['0'].Sumw2()
    NA62()
    for t in [93, 95]:
        h[t] = h['eloss'].ProjectionX(str(t),
                                      int(h['eloss'].GetNbinsY() * t / 100.),
                                      h['eloss'].GetNbinsY())
        h[t].Sumw2()
        h[t].SetStats(0)
        h[t].SetMarkerStyle(24)
        rc = h[t].Divide(h['0'])
        h[t].Rebin(2)
        h[t].Scale(1. / 2.)
        if t != 93:
            h[t].SetMarkerColor(ROOT.kBlue)
            h[t].Draw('same')
        else:
            h[t].SetMaximum(1E-5)
            h[t].SetMarkerColor(ROOT.kMagenta)
            h[t].SetXTitle('incoming muon momentum [GeV/c]')
            h[t].SetYTitle('prob #DeltaE>X%')
            h[t].SetTitle('')
            h[t].Draw()
        h['NA62'].Draw('sameP')
    h['lg'] = ROOT.TLegend(0.53, 0.79, 0.98, 0.94)
    h['lg'].AddEntry(h['NA62'], 'NA62 measurement >95%', 'PL')
    h['lg'].AddEntry(h[95], 'FairShip >95%', 'PL')
    h['lg'].AddEntry(h[93], 'FairShip >93%', 'PL')
    h['lg'].Draw()
    tc = h['summary'].cd(2)
    h['meanEloss'] = h['elossRaw'].ProjectionX()
    for n in range(1, h['elossRaw'].GetNbinsX() + 1):
        tmp = h['elossRaw'].ProjectionY('tmp', n, n)
        eloss = tmp.GetMean()
        h['meanEloss'].SetBinContent(n, eloss / density / length * 1000)
        h['meanEloss'].SetBinError(n, 0)
    h['meanEloss'].SetTitle('mean energy loss MeV cm^{2}/g')
    h['meanEloss'].SetStats(0)
    h['meanEloss'].SetMaximum(7.)
    h['meanEloss'].SetXTitle('incoming muon momentum [GeV/c]')
    h['meanEloss'].SetYTitle('mean energy loss [MeV cm^[2]]/g')
    h['meanEloss'].SetTitle('')
    h['meanEloss'].Draw()
    Gpdg.Draw('sameP')
    h['lg2'] = ROOT.TLegend(0.53, 0.79, 0.98, 0.94)
    h['lg2'].AddEntry(h['Gpdg'], 'muon dE/dx, PDG ', 'PL')
    h['lg2'].AddEntry(h['meanEloss'], 'energy deposited in krypton, FairShip',
                      'PL')
    h['lg2'].Draw()
    h['summary'].Print('catastrophicEnergyLoss.png')
Ejemplo n.º 16
0
def mergeHistosMakePlots(p):
    if not type(p) == type([]): pl = [p]
    else: pl = p
    hlist = ''
    for p in pl:
        prefix = str(p)
        for x in os.listdir('.'):
            if not x.find(prefix) < 0:
                if os.path.isdir(x):
                    hlist += x + '/ShipAna.root '
    print "-->", hlist
    os.system('hadd -f ShipAna.root ' + hlist)
    ut.readHists(h, "ShipAna.root")
    print h['meanhits'].GetEntries()
    if 1 > 0:
        ut.bookCanvas(h,
                      key='strawanalysis',
                      title='Distance to wire and mean nr of hits',
                      nx=1200,
                      ny=600,
                      cx=2,
                      cy=1)
        #
        cv = h['strawanalysis'].cd(1)
        h['disty'].DrawCopy()
        h['distu'].DrawCopy('same')
        h['distv'].DrawCopy('same')
        cv = h['strawanalysis'].cd(2)
        h['meanhits'].DrawCopy()
        print h['meanhits'].GetEntries()

        ut.bookCanvas(h,
                      key='fitresults',
                      title='Fit Results',
                      nx=1600,
                      ny=1200,
                      cx=2,
                      cy=2)
        cv = h['fitresults'].cd(1)
        h['delPOverP'].Draw('box')
        cv = h['fitresults'].cd(2)
        cv.SetLogy(1)
        h['chi2'].Draw()
        cv = h['fitresults'].cd(3)
        h['delPOverP_proj'] = h['delPOverP'].ProjectionY()
        ROOT.gStyle.SetOptFit(11111)
        h['delPOverP_proj'].Draw()
        h['delPOverP_proj'].Fit('gaus')
        cv = h['fitresults'].cd(4)
        h['delPOverP2_proj'] = h['delPOverP2'].ProjectionY()
        h['delPOverP2_proj'].Draw()
        fitSingleGauss('delPOverP2_proj')
        h['fitresults'].Print('fitresults.gif')
        ut.bookCanvas(h,
                      key='fitresults2',
                      title='Fit Results',
                      nx=1600,
                      ny=1200,
                      cx=2,
                      cy=2)
        print 'finished with first canvas'
        cv = h['fitresults2'].cd(1)
        h['Doca'].Draw()
        cv = h['fitresults2'].cd(2)
        h['IP0'].Draw()
        cv = h['fitresults2'].cd(3)
        h['HNL'].Draw()
        fitSingleGauss('HNL', 0., 2.)
        cv = h['fitresults2'].cd(4)
        h['IP0/mass'].Draw('box')
        h['fitresults2'].Print('fitresults2.gif')
        h['strawanalysis'].Print('strawanalysis.gif')
        print 'finished making plots'
Ejemplo n.º 17
0
def BigEventLoop():
 pid = 1
 for fn in fchain: 
  if os.path.islink(fn): 
    rfn = os.path.realpath(fn).split('eos')[1]
    fn  = 'root://eoslhcb//eos/'+rfn
  elif not os.path.isfile(fn): 
    print "Don't know what to do with",fn
    1/0 
  if parallel: 
# process files parallel instead of sequential
   processes.append(mp.Process(target=executeOneFile, args=(fn,output,pid) ) )
   pid+=1 
  else:
   processes.append(fn)
# Run processes
 n=0
 for p in processes:
   if parallel: 
       p.start()
       n+=1
   else: executeOneFile(p)
 if parallel:
# Exit the completed processes
   for p in processes: p.join()
# clean histos before reading in the new ones
   for x in h: h[x].Reset()
   print "now, collect the output"
   pid = 1
   for p in processes:
    ut.readHists(h,'tmpHists_'+str(pid)+'.root')
    pid+=1
# compactify liquid scintillator
 for mu in ['','_mu','_muV0']:
  for x in ['','_E','_P','_LP','_OP','_id','_mul','_evmul','_origin','_originmu']:
    for k in [1,2,3,5]: 
     first = True
     for j in hLiSc[k]:
      detName=hLiSc[k][j]
      tag  = detName+mu+x
      newh = detName[0:2]+'LiSc'+mu+x
      if not h.has_key(tag): continue 
      if first: 
         h[newh] = h[tag].Clone(newh)
         h[newh].SetTitle( h[tag].GetTitle().split('_')[0])
         first = False
      else:  rc = h[newh].Add(h[tag])
# compactify muon stations
 for mu in ['','_mu','_muV0']:
   for x in ['','_E','_P','_LP','_OP','_id','_mul','_evmul','_origin','_originmu']:
    first = True
    for j in hMuon: 
     detName=hMuon[j]
     tag  = detName+mu+x
     newh = 'muondet'+mu+x
     if first: 
       h[newh] = h[tag].Clone(newh)
       h[newh].SetTitle( h[tag].GetTitle().split(' ')[0]+' '+newh)
       first = False
     else:  rc = h[newh].Add(h[tag])
 
 # make list of hists with entries
 k = 1
 for x in histlistAll:
  if h.has_key(histlistAll[x]):
   histlist[k]=histlistAll[x]    
# make cumulative histograms
   for c in ['','_E','_P','_LP','_OP','_id','_mul','_evmul','_origin','_originmu']:
    h[histlist[k]+'_mu'+c].Add(  h[histlist[k]+'_muV0'+c] )
    h[histlist[k]+c].Add(  h[histlist[k]+'_mu'+c] )
    h[histlist[k]+c].SetMinimum(0.) 
    h[histlist[k]+'_mu'+c].SetMinimum(0.) 
    h[histlist[k]+'_muV0'+c] .SetMinimum(0.) 
   k+=1
 nstations = len(histlist)
 makePlots(nstations)
Ejemplo n.º 18
0
def absorptionLength(plotOnly=True):
    materials = {
        'Boratedpolyethylene': ROOT.kGreen,
        'BoronCarbide': ROOT.kBlue,
        'Concrete': ROOT.kGray,
        'EmulsionAg109': ROOT.kOrange,
        'H2O': ROOT.kCyan
    }
    B10Parameter = {}
    B10Parameter['Boratedpolyethylene'] = 0.01 * 0.94 / (10. * 1.672E-24)
    B10Parameter['BoronCarbide'] = 0.125 * 1.360 / (10. * 1.672E-24)
    Xsec = 0.61E-24
    h['Fabsorp'] = {}
    Fabsorp = h['Fabsorp']
    for m in B10Parameter:
        Fabsorp[m] = ROOT.TF1('fabs' + m, '1./([0]/sqrt(10**x)*[1])', -10., 4.)
        Fabsorp[m].SetParameter(0, Xsec)
        Fabsorp[m].SetParameter(1, B10Parameter[m])
    if not plotOnly:
        for material in materials:
            for Erange in [
                    '-14_-12', '-12_-10', '-10_-8', '-8_-7', '-7_-6', '-6_-4',
                    '-4_-2'
            ]:
                fname = "thermNeutron_" + material + "_100.0_" + Erange + "_0.root"
                if not fname in os.listdir('.'): continue
                count(fname)
                h['Esecondary' + '_' + material +
                  Erange] = h['Esecondary'].Clone('Esecondary' + '_' +
                                                  material + Erange)
                h['electrons' + '_' + material +
                  Erange] = h['electrons'].Clone('electrons' + '_' + material +
                                                 Erange)
                h['photons' + '_' + material +
                  Erange] = h['photons'].Clone('photons' + '_' + material +
                                               Erange)
                for x in ['Lab', 'Labz']:
                    hname = x + '_' + material + Erange
                    h[hname] = h[x].ProfileX(hname, 1, -1, 'g')
                    hsum = x + '_' + material
                    if not hsum in h:
                        h[hsum] = h[hname].Clone(hsum)
                        h[hsum].SetLineColor(materials[material])
                    else:
                        h[hsum].Add(h[hname])
        ROOT.gROOT.cd()
        ut.writeHists(h, 'thermalNeutrons-histograms.root', plusCanvas=True)
    else:
        ut.readHists(h, 'thermalNeutrons-histograms.root')
# make stats about secondary neutrons:
    for material in materials:
        for Erange in [
                '-14_-12', '-12_-10', '-10_-8', '-8_-7', '-7_-6', '-6_-4',
                '-4_-2'
        ]:
            histo = h['Esecondary' + '_' + material + Erange]
            print("secondary neutrons for %s %s %5.2F%%" %
                  (material, Erange, 100. * histo.GetEntries() /
                   h['Labz' + '_' + material + Erange].GetEntries()))
    for X in ['electrons', 'photons']:
        for material in materials:
            h[X + '_' + material] = h[X].Clone(X + '_' + material)
            for Erange in [
                    '-14_-12', '-12_-10', '-10_-8', '-8_-7', '-7_-6', '-6_-4',
                    '-4_-2'
            ]:
                h[X + '_' + material].Add(h[X + '_' + material + Erange])
            norm = h[X + '_' + material].ProjectionX('norm', 1, 101)
            for p in [1, 2, 5, 10]:
                h[X + str(p) + 'Percent_' +
                  material] = h[X + '_' + material].ProjectionX(
                      X + str(p) + 'Percent_' + material, 1, p)
                h[X + str(p) + 'Percent_' + material].Divide(norm)
        ut.bookCanvas(h, 'T' + X, '', 1200, 800, 1, 1)
        h['T' + X].cd()
        material = 'EmulsionAg109'
        h[X + '1Percent_' + material].SetLineColor(ROOT.kRed)
        h[X + '2Percent_' + material].SetLineColor(ROOT.kOrange)
        h[X + '5Percent_' + material].SetLineColor(ROOT.kBlue)
        h[X + '10Percent_' + material].SetLineColor(ROOT.kGreen)
        h[X + '1Percent_' + material].SetTitle('')
        h[X + '1Percent_' +
          material].GetYaxis().SetTitle('fraction of events with < N_{' + X +
                                        '}')
        h[X + '1Percent_' + material].GetXaxis().SetRangeUser(-12., 1)
        h[X + '1Percent_' + material].SetStats(0)
        h[X + '1Percent_' + material].Draw('hist')
        h['leg' + X] = ROOT.TLegend(0.63, 0.25, 0.88, 0.40)
        for p in [1, 2, 5, 10]:
            h[X + str(p) + 'Percent_' + material].Draw('histsame')
            rc = h['leg' + X].AddEntry(h[X + str(p) + 'Percent_' + material],
                                       'N_{' + X + '}<' + str(p), 'PL')
        h['leg' + X].Draw('same')
        myPrint(h['T' + X], 'fracEveWith' + X)
#
    fntuple = ROOT.TFile.Open('neutronsTI18.root')
    nt = fntuple.nt
    ROOT.gROOT.cd()
    tcanv = 'TFig12'
    if tcanv in h: h.pop(tcanv)
    ut.bookCanvas(h, tcanv, '', 1200, 800, 1, 1)
    # figure 12 of technical proposal
    nt.Draw('log10(N*Eleft):log10(Eleft)>>rates', '', 'box')
    h['rates'] = ROOT.gROOT.FindObjectAny('rates').Clone('rates')

    for x in ['Lab', 'Labz']:
        tcanv = 'abs' + x
        if tcanv in h: h.pop(tcanv)
        ut.bookCanvas(h, tcanv, '', 1200, 800, 1, 1)
        h['abs' + x].cd()
        h['abs' + x].SetLogy()
        hsum = x + '_Concrete'
        h[hsum].GetXaxis().SetRangeUser(-12., 1)
        h[hsum].SetMaximum(30.)
        h[hsum].SetMinimum(0.004)
        h[hsum].GetXaxis().SetTitle('logE[MeV]')
        h[hsum].GetYaxis().SetTitle('absorption Length  [cm]')
        h[hsum].SetLineWidth(2)
        h[hsum].Draw('hist')
        h['leg' + x] = ROOT.TLegend(0.6, 0.2, 0.86, 0.36)
        for material in materials:
            hsum = x + '_' + material
            h[hsum].SetStats(0)
            h[hsum].SetLineWidth(2)
            h[hsum].Draw('histsame')
            if material in Fabsorp: Fabsorp[material].Draw('same')
            rc = h['leg' + x].AddEntry(h[hsum], material, 'PL')
        h['leg' + x].Draw('same')
        myPrint(h['abs' + x], 'AbsLength' + x)

# folding with neutron rate
    h['Fig12'] = ROOT.TGraph()
    h['dE'] = ROOT.TGraph()
    h['neutronRate'] = ROOT.TGraph()
    h['dangerZone'] = ROOT.TGraph()
    h['dangerZone'].SetPoint(0, -5.6, 0.)
    h['dangerZone'].SetPoint(1, -5.6, 1.E7)
    h['dangerZone'].SetPoint(2, -5.1, 1.E7)
    h['dangerZone'].SetPoint(3, -5.1, 0.)
    h['dangerZone'].SetFillStyle(1001)
    h['dangerZone'].SetFillColor(ROOT.kYellow)

    n = 0
    RateIntegrated = 0
    RateIntegratedW = 0
    for nt in fntuple.nt:
        E = (nt.Eleft + nt.Eright) / 2.
        dE = nt.Eright - nt.Eleft
        h['Fig12'].SetPoint(n, ROOT.TMath.Log10(E), ROOT.TMath.Log10(nt.N * E))
        h['neutronRate'].SetPoint(n, E, nt.N)
        h['dE'].SetPoint(n, E, dE)
        RateIntegrated += nt.N
        RateIntegratedW += nt.N * dE
        n += 1

    h['TFig12'].cd()
    h['Fig12'].Draw('same')
    #
    ut.bookHist(h, 'Nr', ';E [MeV];dn/dlogE [cm^{-2}y^{-1}] ', 100, -12., 1.)
    h['Nr'].SetMaximum(2.E8)
    h['Nr'].SetMinimum(1.E-4)
    h['Nr'].SetStats(0)
    intRates = {}
    thick = {
        0.0: ROOT.kBlue,
        0.5: ROOT.kOrange,
        1: ROOT.kRed,
        2: ROOT.kRed + 2,
        5: ROOT.kRed - 7,
        10: ROOT.kGreen
    }
    for material in ['Boratedpolyethylene', 'BoronCarbide']:
        intRates[material] = {}
        tcanv = 'ratesWith_' + material
        if tcanv in h: h.pop(tcanv)
        ut.bookCanvas(h, tcanv, material, 1200, 800, 1, 1)
        h[tcanv].SetLogy(1)
        h[tcanv].cd()
        h['ratesWith_' + material].cd()
        h['Nr'].Draw()
        h['dangerZone'].Draw('sameF')
        h['legthick' + material] = ROOT.TLegend(0.6, 0.2, 0.86, 0.36)
        for d in thick:  # try different thicknesses
            intRates[material][d] = 0
            absorbLength = h['Labz_' + material]
            gname = 'neutronRate_' + material + '_' + str(d)
            h[gname] = ROOT.TGraph()
            h[gname].SetLineWidth(2)
            h[gname].SetLineColor(thick[d])
            for n in range(h['Fig12'].GetN()):
                logE = h['Fig12'].GetX()[n]
                R = ROOT.TMath.Power(10., h['Fig12'].GetY()[n])
                dE = h['dE'].GetPointY(n)
                E = ROOT.TMath.Power(10., logE)
                absorpt = 0
                if d == 0.0:
                    h[gname].SetPoint(n, logE, R)
                    intRates[material][d] += dE * R / E
                else:
                    L = absorbLength.GetBinContent(absorbLength.FindBin(logE))
                    Rnew = 0
                    if L > 0:
                        absorpt = ROOT.TMath.Exp(-d / L)
                        Rnew = R * absorpt
                    h[gname].SetPoint(n, logE, Rnew)
                    #            E = (nt.Eleft+nt.Eright)/2.     h['Fig12'].SetPoint(n,ROOT.TMath.Log10(E),ROOT.TMath.Log10(nt.N*E))
                    intRates[material][d] += dE * Rnew / E
            h[gname].Draw('same')
            rc = h['legthick' + material].AddEntry(h[gname],
                                                   'thickness %3.1Fcm' % (d),
                                                   'PL')
            reduction = intRates[material][d] / intRates[material][0]
            print(
                'integrated rate with %s  d=%3.1Fcm: %6.4G   reduction factor=%6.2G'
                % (material, d, intRates[material][d], reduction))
            # make integrated rates:
            h['IUp-neutronRate_' + material + str(d)] = ROOT.TGraph()
            h['IUp-neutronRateW_' + material + str(d)] = ROOT.TGraph()
            h['IDown-neutronRate_' + material + str(d)] = ROOT.TGraph()
            up = h['IUp-neutronRate_' + material + str(d)]
            down = h['IDown-neutronRate_' + material + str(d)]
            N = h[gname].GetN()
            S = 0
            for n in range(N):
                logE = h[gname].GetX()[n]
                dE = h['dE'].GetPointY(n)
                Rnew = h[gname].GetY()[n]
                E = ROOT.TMath.Power(10., logE)
                S += dE * Rnew / E
                up.SetPoint(n, logE, S)
                # with damage function
                W = 1 - h['electrons1Percent_EmulsionAg109'].GetBinContent(n)
                h['IUp-neutronRateW_' + material + str(d)].SetPoint(
                    n, logE, W * S)
            S = up.GetY()[N - 1]
            for n in range(N):
                logE = up.GetX()[n]
                S -= up.GetY()[n]
                down.SetPoint(n, logE, S)


#
            for Elimit in [100., 1., 0.1, 0.01]:  #MeV
                g = h['IUp-neutronRate_' + material + str(d)]
                gW = h['IUp-neutronRateW_' + material + str(d)]
                N = g.GetN()
                for n in range(N - 1, 1, -1):
                    if ROOT.TMath.Power(10, g.GetX()[n]) < Elimit: break
                reduction = g.GetY()[n] / h['IUp-neutronRate_' + material +
                                            str(0.0)].GetY()[N - 1]
                reductionW = gW.GetY()[n] / h['IUp-neutronRate_' + material +
                                              str(0.0)].GetY()[N - 1]
                print(
                    'integrated rate  E < %5.3F with %s  d=%3.1Fcm: %6.4G   reduction factor=%6.2G  |     %6.4G   reduction factor=%6.2G'
                    % (Elimit, material, d, g.GetY()[n], reduction,
                       gW.GetY()[n], reductionW))

        h['legthick' + material].Draw('same')
        myPrint(h['ratesWith_' + material], 'reducedRates_' + material)
Ejemplo n.º 19
0
def coldBox(plotOnly=True, pas=''):

    if 1 > 0:
        tmp = options.inputFile.split('/')
        gFile = "geofile-" + (tmp[len(tmp) - 1].split('_coldbox')[0] +
                              '_coldbox.root').replace('histos-', '')
        g = ROOT.TFile(gFile)
        sGeo = g.FAIRGeom
        ROOT.gROOT.cd()
        vbox = sGeo.FindVolumeFast('vbox')
        sbox = sGeo.FindVolumeFast('sensBox')
        dX, dY, dZ = vbox.GetShape().GetDX(), vbox.GetShape().GetDY(
        ), vbox.GetShape().GetDZ()
        nav = sGeo.GetCurrentNavigator()
        boundaries = {}
        # find y boundaries
        start = array('d', [0, 200, 0])
        direction = array('d', [0, -1, 0])
        startnode = sGeo.InitTrack(start, direction)
        length = c_double(200.)
        node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE)
        boundaries['topIn'] = nav.GetCurrentPoint()[1]
        node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE)
        boundaries['topSens'] = nav.GetCurrentPoint()[1]
        start = array('d', [0, -200, 0])
        direction = array('d', [0, 1, 0])
        startnode = sGeo.InitTrack(start, direction)
        node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE)
        node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE)
        boundaries['botSens'] = nav.GetCurrentPoint()[1]
        # find x boundaries
        start = array('d', [-200, 0, 0])
        direction = array('d', [1, 0, 0])
        startnode = sGeo.InitTrack(start, direction)
        node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE)
        boundaries['leftIn'] = nav.GetCurrentPoint()[0]
        node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE)
        boundaries['leftSens'] = nav.GetCurrentPoint()[0]
        start = array('d', [200, 0, 0])
        direction = array('d', [-1, 0, 0])
        startnode = sGeo.InitTrack(start, direction)
        node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE)
        boundaries['rightIn'] = nav.GetCurrentPoint()[0]
        node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE)
        boundaries['rightSens'] = nav.GetCurrentPoint()[0]
        # find z boundaries
        start = array('d', [0, 0, -200])
        direction = array('d', [0, 0, 1])
        startnode = sGeo.InitTrack(start, direction)
        node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE)
        boundaries['backIn'] = nav.GetCurrentPoint()[2]
        node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE)
        boundaries['backSens'] = nav.GetCurrentPoint()[2]
        start = array('d', [0, 0, 200])
        direction = array('d', [0, 0, -1])
        startnode = sGeo.InitTrack(start, direction)
        node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE)
        boundaries['frontIn'] = nav.GetCurrentPoint()[2]
        node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE)
        boundaries['frontSens'] = nav.GetCurrentPoint()[2]
        Rin = {
            '': '',
            'topIn': 'Y',
            'leftIn': 'X',
            'rightIn': 'X',
            'frontIn': 'Z',
            'backIn': 'Z'
        }
        Rsens = {
            '': '',
            'topSens': 'Y',
            'botSens': 'Y',
            'leftSens': 'X',
            'rightSens': 'X',
            'frontSens': 'Z',
            'backSens': 'Z'
        }
        epsi = 0.1
#     side with holes is the front
#
    if not plotOnly:
        # example file "root://eospublic.cern.ch:1094//eos/experiment/sndlhc/MonteCarlo/ThermalNeutrons//thermNeutron_Borated30polyethylene_10.0_coldbox_0-20M.root"
        f = ROOT.TFile.Open(options.inputFile)
        ROOT.gROOT.cd()
        ut.bookHist(h, 'start', 'start neutron;x [cm] ;y [cm] ;z [cm]', 100,
                    -200, 200, 100, -200, 200, 100, -200, 200)
        ut.bookHist(h, 'startR', 'start neutron;R', 100, 0, 200)
        for o in ['_seco', '_prim']:
            for T in ['', 'cold', 'hot']:
                ut.bookHist(h, 'entry' + T + o,
                            'entry neutron;x [cm] ;y [cm] ;z [cm]', 100, -100,
                            100, 100, -100, 100, 100, -100, 100)
                ut.bookHist(h, 'exit' + T + '-original' + o,
                            'enter coldbox neutron;x [cm] ;y [cm] ;z [cm]',
                            100, -100, 100, 100, -100, 100, 100, -100, 100)
                ut.bookHist(h, 'exit' + T + o,
                            'enter coldbox neutron;x [cm] ;y [cm] ;z [cm]',
                            100, -100, 100, 100, -100, 100, 100, -100, 100)
            for r in Rin:
                ut.bookHist(h, 'EkinE' + r + o, 'log10(Ekin)', 100, -13., 0,
                            100, -200., 200.)
                ut.bookHist(h, 'Ekin' + r + o, 'log10(Ekin)', 100, -13., 0,
                            100, -200., 200.)
            for r in Rsens:
                ut.bookHist(h, 'DF' + r + o, 'travel  distance', 100, 0., 200.)
                ut.bookHist(h, 'EkinF' + r + o, 'log10(Ekin) vs distance', 100,
                            -13., 0, 100, -200., 200.)
                ut.bookHist(h, 'EkinF-original' + r + o,
                            'log10(Ekin) vs distance', 100, -13., 0, 100,
                            -200., 200.)
                ut.bookHist(h, 'checkBox' + r + o,
                            'enter coldbox neutron;x [cm] ;y [cm] ;z [cm]',
                            100, -100, 100, 100, -100, 100, 100, -100, 100)
        ut.bookHist(h, 'EkinG', 'log10(Ekin)', 100, -13., 0.)
        ut.bookHist(h, 'EkinW', 'log10(Ekin)', 100, -13., 0.)
        ut.bookHist(h, 'EkinWlin', 'Ekin', 100, 1E-9, 100 * 1E-9)
        ut.bookHist(h, 'multS', 'mult veto points shielding', 100, -0.5, 99.5)
        ut.bookHist(h, 'multC', 'mult veto points inside', 100, -0.5, 99.5)
        ut.bookHist(h, 'multN', 'mult neutrons', 100, -0.5, 99.5)

        flukaRateIntegrated()
        Nsim = f.cbmsim.GetEntries()
        for sTree in f.cbmsim:
            rc = h['multN'].Fill(sTree.MCTrack.GetEntries())
            neutron = sTree.MCTrack[0]
            start = ROOT.TVector3(neutron.GetStartX(), neutron.GetStartY(),
                                  neutron.GetStartZ())
            if start.y() < boundaries['botSens']: continue

            P = ROOT.TVector3(neutron.GetPx(), neutron.GetPy(),
                              neutron.GetPz())
            Ekin = ROOT.TMath.Sqrt(P.Mag2() + neutronMass**2) - neutronMass
            W = h['Fig12'].Eval(ROOT.TMath.Log10(Ekin * 1000)) / Nsim
            rc = h['start'].Fill(start.Z(), start.X(), start.Y(), W)
            rc = h['EkinW'].Fill(ROOT.TMath.Log10(Ekin), W)
            rc = h['EkinWlin'].Fill(Ekin, W)
            rc = h['EkinG'].Fill(ROOT.TMath.Log10(Ekin))
            rc = h['startR'].Fill(start.Mag(), W)
            nC, nS = 0, 0
            for p in sTree.vetoPoint:
                if p.PdgCode() != 2112: continue
                if p.GetDetectorID() == 13: nC += 1
                else: nS += 1
            rc = h['multC'].Fill(nC)
            rc = h['multS'].Fill(nS)
            trajectory = {}
            for p in sTree.vetoPoint:
                if p.PdgCode() != 2112: continue
                trackID = p.GetTrackID()
                if not trackID in trajectory: trajectory[trackID] = []
                trajectory[trackID].append(p)
            for trackID in trajectory:
                firstSens = True
                for p in trajectory[trackID]:
                    origin = '_seco'
                    if trackID == 0: origin = '_prim'
                    lastPoint = p.LastPoint()
                    mPoint = ROOT.TVector3(p.GetX(), p.GetY(), p.GetZ())
                    firstPoint = 2 * mPoint - lastPoint
                    D = lastPoint - firstPoint
                    TD = firstPoint - start
                    firstMom = ROOT.TVector3(p.GetPx(), p.GetPy(), p.GetPz())
                    Ekin_entry = ROOT.TMath.Sqrt(firstMom.Mag2() +
                                                 neutronMass**2) - neutronMass
                    if p.GetDetectorID(
                    ) == 13 and firstSens:  # first point inside coldbox
                        firstSens = False
                        rc = h['exit' + origin].Fill(firstPoint.X(),
                                                     firstPoint.Y(),
                                                     firstPoint.Z(), W)

                        if Ekin * 1E9 < 10:
                            rc = h['exitcold-original' + origin].Fill(
                                firstPoint.X(), firstPoint.Y(), firstPoint.Z(),
                                W)  # 10eV
                        else:
                            rc = h['exithot-original' + origin].Fill(
                                firstPoint.X(), firstPoint.Y(), firstPoint.Z(),
                                W)

                        if Ekin_entry * 1E9 < 10:
                            rc = h['exitcold' + origin].Fill(
                                firstPoint.X(), firstPoint.Y(), firstPoint.Z(),
                                W)  # 10eV
                        else:
                            rc = h['exithot' + origin].Fill(
                                firstPoint.X(), firstPoint.Y(), firstPoint.Z(),
                                W)
                        rc = h['DF' + origin].Fill(TD.Mag(), W)
                        rc = h['EkinF' + origin].Fill(
                            ROOT.TMath.Log10(Ekin_entry), D.Mag(), W)
                        rc = h['EkinF-original' + origin].Fill(
                            ROOT.TMath.Log10(Ekin), D.Mag(), W)
                        # find location     Rsens = ['','topSens','botSens','leftSens','rightSens','frontSens','backSens']
                        found = False
                        for r in Rsens:
                            if r == '': continue
                            X = eval('firstPoint.' + Rsens[r] + '()')
                            if abs(X - boundaries[r]) < epsi:
                                #           if r=='botSens' and p!=trajectory[trackID][0]: continue    # to enter from bottom is without crossing shield. It is more complicated!
                                found = True
                                break
                        if not found:
                            txt = ''
                            for r in Rsens:
                                if r == '': continue
                                X = eval('firstPoint.' + Rsens[r] + '()')
                                txt += " " + r + " " + str(X)
                                print("this should no happen", txt, boundaries)
                                for P in trajectory[trackID]:
                                    print(P.GetDetectorID(),
                                          P.LastPoint().X(),
                                          P.LastPoint().Y(),
                                          P.LastPoint().Z())
                        rc = h['DF' + r + origin].Fill(TD.Mag(), W)
                        rc = h['EkinF' + r + origin].Fill(
                            ROOT.TMath.Log10(Ekin_entry), D.Mag(), W)
                        rc = h['EkinF-original' + r + origin].Fill(
                            ROOT.TMath.Log10(Ekin), D.Mag(), W)
                        rc = h['checkBox' + r + origin].Fill(
                            firstPoint.X(), firstPoint.Y(), firstPoint.Z(), W)

                    if p.GetDetectorID() == 1:  # inside shielding
                        # check that first point is further out.
                        if firstPoint.Mag() < lastPoint.Mag(): continue
                        rc = h['Ekin' + origin].Fill(ROOT.TMath.Log10(Ekin),
                                                     D.Mag(), W)
                        rc = h['EkinE' + origin].Fill(
                            ROOT.TMath.Log10(Ekin_entry), D.Mag(), W)
                        rc = h['entry' + origin].Fill(firstPoint.X(),
                                                      firstPoint.Y(),
                                                      firstPoint.Z(), W)
                        if Ekin * 1E9 < 10:
                            rc = h['entrycold' + origin].Fill(
                                firstPoint.X(), firstPoint.Y(), firstPoint.Z(),
                                W)  # 10eV
                        else:
                            rc = h['entryhot' + origin].Fill(
                                firstPoint.X(), firstPoint.Y(), firstPoint.Z(),
                                W)
                        # find location
                        for r in Rin:
                            if r == '': continue
                            X = eval('firstPoint.' + Rin[r] + '()')
                            if abs(X - boundaries[r]) < epsi: break
                        rc = h['Ekin' + r + origin].Fill(
                            ROOT.TMath.Log10(Ekin), X, W)
                        rc = h['EkinE' + r + origin].Fill(
                            ROOT.TMath.Log10(Ekin_entry), X, W)

        tmp = options.inputFile.split('/')
        outFile = 'histos-' + tmp[len(tmp) - 1]
        # make sum of seco and prim
        hkeys = list(h.keys())
        for x in hkeys:
            if x.find('_seco') > 0:
                hname = x.replace('_seco', '')
                h[hname] = h[x].Clone(hname)
                h[hname].Add(h[x.replace('_seco', '_prim')])
#
        ut.writeHists(h, outFile)
        print('finished making histograms ',
              'histos-noConc-' + options.inputFile)

    else:
        ut.readHists(h, options.inputFile)
        if pas != '':
            ut.readHists(
                hnorm, 'histos-thermNeutron_vacuums_0.0001_coldbox_pass1.root')
        else:
            ut.readHists(hnorm, options.inputFile)
        tmp = options.inputFile.split('_')
        material = tmp[1] + "_coldbox/"
        thickness = "_" + tmp[2]

        binning = {}
        for c in ['entry', 'exit']:
            binning[c] = {}
            for p in ['x', 'y', 'z']:
                tmp = h[c].Project3D(p)
                for imin in range(1, tmp.GetNbinsX() + 1):
                    if tmp.GetBinContent(imin) > 0: break
                for imax in range(tmp.GetNbinsX(), 0, -1):
                    if tmp.GetBinContent(imax) > 0: break
                binning[c][p] = {'min': imin, 'max': imax}

#
        ytop = {
            'axis': 'Y',
            'proj': 'xz',
            'entry': binning['entry']['y']['max'],
            'exit': h['exit'].GetYaxis().FindBin(boundaries['topSens']),
            'xdist': dZ,
            'ydist': dX
        }
        ybot = {
            'axis': 'Y',
            'proj': 'xz',
            'entry': binning['entry']['y']['min'],
            'exit': h['exit'].GetYaxis().FindBin(boundaries['botSens']),
            'xdist': dZ,
            'ydist': dX
        }
        xLeft = {
            'axis': 'X',
            'proj': 'yz',
            'entry': binning['entry']['x']['min'],
            'exit': h['exit'].GetXaxis().FindBin(boundaries['leftSens']),
            'xdist': dZ,
            'ydist': dY
        }
        xRight = {
            'axis': 'X',
            'proj': 'yz',
            'entry': binning['entry']['x']['max'],
            'exit': h['exit'].GetXaxis().FindBin(boundaries['rightSens']),
            'xdist': dZ,
            'ydist': dY
        }
        zMin = {
            'axis': 'Z',
            'proj': 'yx',
            'entry': binning['entry']['z']['min'],
            'exit': h['exit'].GetZaxis().FindBin(boundaries['backSens']),
            'xdist': dX,
            'ydist': dY
        }
        zMax = {
            'axis': 'Z',
            'proj': 'yx',
            'entry': binning['entry']['z']['max'],
            'exit': h['exit'].GetXaxis().FindBin(boundaries['frontSens']),
            'xdist': dX,
            'ydist': dY
        }
        print('boundaries', boundaries)

        # make projections
        projections = {
            'Top': ytop,
            'Bot': ybot,
            'Right': xRight,
            'Left': xLeft,
            'Front': zMax,
            'Back': zMin
        }
        h['fluences'] = {}
        for o in ['', '_prim']:
            for T in ['', 'cold', 'hot']:
                for Z in ['entry', 'exit', 'exit-original']:
                    tmp = Z.split('-')
                    c = tmp[0]
                    x = ''
                    if len(tmp) > 1: x = '-' + tmp[1]
                    case = c + T + x + o
                    ut.bookCanvas(h, 't' + case, case, 1200, 1800, 2, 3)
                    k = 1
                    for p in projections:
                        h['t' + case].cd(k)
                        tmp = h[case]
                        axis = eval('tmp.Get' + projections[p]['axis'] +
                                    'axis()')
                        if Z == 'entry':
                            axis.SetRange(projections[p][c] - 1,
                                          projections[p][c] + 1)
                        else:
                            axis.SetRange(projections[p][c], projections[p][c])
                            if p == 'xBot':
                                xax = tmp.GetXaxis()
                                xax.SetRange(
                                    xax.FindBin(boundaries['leftSens']) + 1,
                                    xax.FindBin(boundaries['rightSens']) - 1)
                                zax = tmp.GetZaxis()
                                zax.SetRange(
                                    zax.FindBin(boundaries['backSens']) + 1,
                                    zax.FindBin(boundaries['frontSens']) - 1)
                        h[case + p] = tmp.Project3D(projections[p]['proj'])
                        h[case + p].SetName(case + p)
                        tmp.GetXaxis().SetRange(0, 0)
                        tmp.GetYaxis().SetRange(0, 0)
                        tmp.GetZaxis().SetRange(0, 0)
                        h[case + p].SetStats(0)
                        h[case + p].SetMinimum(0)
                        h[case + p].SetTitle(p)
                        h[case + p].Draw('colz')
                        # check uniformity:
                        h['X-' + case + p] = h[case + p].ProjectionX('X-' +
                                                                     case + p)
                        h['Y-' + case + p] = h[case + p].ProjectionY('Y-' +
                                                                     case + p)
                        k += 1
                        sqcm = projections[p]['xdist'] * projections[p]['ydist']
                        entries = h[case + p].GetSumOfWeights()
                        X = entries / sqcm
                        if X > 100: txt = "%5.1F/cm^{2}" % (X)
                        else: txt = "%5.2F/cm^{2}" % (X)
                        h['fluences'][case + p] = X
                        L = ROOT.TLatex()
                        rc = L.DrawLatexNDC(0.2, 0.85, txt)
                        h['X-' + case + p].Scale(1. / projections[p]['ydist'])
                        h['Y-' + case + p].Scale(1. / projections[p]['xdist'])
                    myPrint(h['t' + case], material + 't' + case + thickness)


# make cross checks
        ut.bookCanvas(h, 'crosschecks', 'cross checks', 900, 600, 1, 1)
        tc = h['crosschecks'].cd()
        tc.SetLogy(1)
        tc.SetGridx()
        tc.SetGridy()
        h['EkinW'].SetStats(0)
        h['EkinW'].SetStats(0)
        h['EkinW'].SetLineWidth(3)
        h['EkinW'].SetTitle(';log(E) [GeV];dn/dlogE [cm^{-2}y^{-1}] ')
        h['EkinW'].SetMaximum(1E8)
        h['EkinW'].SetMinimum(1E2)
        h['EkinW'].Draw()
        myPrint(h['crosschecks'], material + 'kinEnergy' + thickness)
        tc.SetLogy(0)
        k = -10
        for p in projections:
            for l in ['X-', 'Y-']:
                case = l + 'entry' + p
                h[case].SetLineColor(ROOT.kRed + k)
                h[case].SetStats(0)
                if k < -9:
                    h[case].SetTitle('; x,y,z  [cm]; N/L [cm^{-1}]')
                    tpl = ut.findMaximumAndMinimum(h[case])
                    h[case].SetMaximum(tpl[1] * 1.5)
                    h[case].Draw()
                else:
                    h[case].Draw('same')
                k += 1
        myPrint(h['crosschecks'], material + 'irradiationXYZ' + thickness)
        #
        tc.SetLogy(1)
        #  Ekin     Rin      = {'':'','topIn':'Y','leftIn':'X','rightIn':'X','frontIn':'Z','backIn':'Z'}
        #  EkinF   Rsens = {'':'','topSens':'Y','botSens':'Y','leftSens':'X','rightSens':'X','frontSens':'Z','backSens':'Z'}
        ut.bookCanvas(h, 'trej', 'rejections', 1200, 1800, 2, 3)
        k = 0
        for r in ['', 'top', 'bot', 'right', 'left', 'front', 'back']:
            rej = 'rej' + r
            rejo = 'rejo' + r
            if r == '':
                norm = hnorm['Ekin'].ProjectionX('norm')
                h[rej] = h['EkinF'].ProjectionX(rej)
                h[rejo] = h['EkinF-original'].ProjectionX(rejo)
            else:
                k += 1
                if r == 'bot': norm = hnorm['EkintopIn'].ProjectionX('norm')
                else: norm = hnorm['Ekin' + r + 'In'].ProjectionX('norm')
                h[rej] = h['EkinF' + r + 'Sens'].ProjectionX(rej)
                h[rejo] = h['EkinF-original' + r + 'Sens'].ProjectionX(rejo)
            h[rej].Divide(norm)
            h[rejo].Divide(norm)
            h[rej].SetStats(0)
            h[rejo].SetStats(0)
            h[rej].SetTitle(';log10(Ekin) GeV; rejection')
            h[rej].SetLineColor(ROOT.kBlue)
            h[rej].SetLineWidth(2)
            h[rejo].SetLineWidth(2)
            h[rejo].SetLineColor(ROOT.kGreen)
            h[rej].GetXaxis().SetRangeUser(-13., -1.)
            h[rej].SetMaximum(1.2)
            h[rej].SetMinimum(1.E-4)
            if k == 0: tc = h['crosschecks'].cd()
            else:
                tc = h['trej'].cd(k)
                tc.SetGridx()
                tc.SetGridy()
                h[rej].SetMinimum(1.E-6)
                h[rej].SetTitle(r[0].upper() + r[1:])
            tc.SetLogy()
            h[rej].Draw('hist')
            h[rejo].Draw('histsame')
            h['legR' + r] = ROOT.TLegend(0.11, 0.74, 0.72, 0.82)
            rc = h['legR' + r].AddEntry(
                h[rejo],
                'reduction as function of original E_{kin} when entering shield',
                'PL')
            rc = h['legR' + r].AddEntry(
                h[rej], 'reduction as function of E_{kin} when leaving shield',
                'PL')
            h['legR' + r].Draw('same')
            if k == 0:
                myPrint(h['crosschecks'], material + 'rejections' + thickness)
        myPrint(h['trej'], material + 'Listrejections' + thickness + pas)
        #
        h['dangerZone'] = ROOT.TGraph()
        h['dangerZone'].SetPoint(0, -8.6, 0.)
        h['dangerZone'].SetPoint(1, -8.6, 1.)
        h['dangerZone'].SetPoint(2, -8.1, 1.)
        h['dangerZone'].SetPoint(3, -8.1, 0.)
        h['dangerZone'].SetFillStyle(1001)
        h['dangerZone'].SetFillColor(ROOT.kYellow)
        for r in ['rej', 'rejo']:
            ut.bookCanvas(h, r + 'ection2', 'rejectionRate', 900, 600, 1, 1)
            h[r + 'TopLeftRightBack'] = h[r + 'top'].Clone(r +
                                                           'TopLeftRightBack')
            h[r + 'TopLeftRightBack'].Add(h[r + 'left'])
            h[r + 'TopLeftRightBack'].Add(h[r + 'right'])
            h[r + 'TopLeftRightBack'].Add(h[r + 'back'])
            h[r + 'TopLeftRightBack'].Scale(1. / 4.)
            h[r + 'TopLeftRightBack'].SetTitle('')
            if r == 'rej':
                h[r + 'TopLeftRightBack'].GetXaxis().SetTitle(
                    'outgoing   ' +
                    h[r + 'TopLeftRightBack'].GetXaxis().GetTitle())
            if r == 'rejo':
                h[r + 'TopLeftRightBack'].GetXaxis().SetTitle(
                    'incoming   ' +
                    h[r + 'TopLeftRightBack'].GetXaxis().GetTitle())
            h[r + 'TopLeftRightBack'].SetLineColor(ROOT.kGreen)
            h[r + 'bot'].SetLineColor(ROOT.kGray)
            h[r + 'front'].SetLineColor(ROOT.kRed)
            h[r + 'TopLeftRightBack'].SetMaximum(1.2)
            h[r + 'TopLeftRightBack'].SetMinimum(1.E-6)
            tc = h[r + 'ection2'].cd()
            tc.SetGridx()
            tc.SetGridy()
            tc.SetLogy()
            h[r + 'TopLeftRightBack'].Draw()
            h['dangerZone'].Draw('sameF')
            h[r + 'TopLeftRightBack'].Draw('same')
            h[r + 'bot'].Draw('same')
            h[r + 'front'].Draw('same')
            h[r + 'legR2'] = ROOT.TLegend(0.55, 0.30, 0.86, 0.45)
            rc = h[r + 'legR2'].AddEntry(h[r + 'TopLeftRightBack'],
                                         'av. rejection top/left/right/back',
                                         'PL')
            rc = h[r + 'legR2'].AddEntry(h[r + 'bot'],
                                         'rejction bottom, only concrete',
                                         'PL')
            rc = h[r + 'legR2'].AddEntry(h[r + 'front'],
                                         'rejction front, with holes', 'PL')
            h[r + 'legR2'].Draw('same')
            myPrint(h[r + 'ection2'],
                    material + 'Sum ' + r + 'ections' + thickness + pas)

        if pas == '':
            ut.writeHists(h, options.inputFile.replace('.root', '_pass1.root'))

        # statistics:
        for o in ['', '-original']:
            for T in ['cold', 'hot']:
                norm = 0
                exit = 0
                concrete = 0
                holes = 0
                for p in projections:
                    if p != 'Bot' and norm != 'Front':
                        norm += h['fluences']['entry' + T + p]
                        exit += h['fluences']['exit' + T + o + p]
                    if p == 'Bot': concrete = h['fluences']['exit' + T + o + p]
                    elif p == 'Front':
                        holes = h['fluences']['exit' + T + o + p]
                norm = norm / float(4)
                exit = exit / float(4)
                #! do not need average, need total.
                # incoming = 6 * average !
                print(
                    '%s  %s region:  %5.2F  concrete: %5.2F    holes:   %5.2F x permille     total:   %5.2F x permille'
                    % (o, T, exit / norm * 1000, concrete / norm * 1000,
                       holes / norm * 1000,
                       (4 * exit + concrete + holes) / (6 * norm) * 1000))