Exemple #1
0
def reRunReco(r, fname):
    fRT = fname.replace('.root', '_RT2.root')
    os.system(
        'xrdcp -f $EOSSHIP/eos/experiment/ship/data/muflux/DATA_Rebuild_8000/rootdata/'
        + r + '/' + fname + ' ' + fRT)
    f = ROOT.TFile.Open(os.environ['EOSSHIP'] +
                        '/eos/experiment/ship/user/odurhan/muflux-recodata/' +
                        r + '/' + fname.replace('.root', '_RT.root'))
    ftemp = ROOT.TFile(fRT, 'update')
    ftemp.cd('')
    upkl = Unpickler(f)
    tMinAndTmax = upkl.load('tMinAndTmax')
    pkl = Pickler(ftemp)
    pkl.dump(tMinAndTmax, 'tMinAndTmax')
    ftemp.mkdir('histos')
    ftemp.histos.cd('')
    for tc in ['TDCMapsX', 'hitMapsX']:
        tmp = f.histos.Get(tc)
        X = tmp.Clone()
        X.Write()
    ftemp.Write("", ROOT.TFile.kOverwrite)
    ftemp.Close()
    cmd = "python " + pathToMacro + "drifttubeMonitoring.py -c recoStep1 -u 1 -f " + fRT + ' &'
    os.system(cmd)
    print('step 1:', cmd)
Exemple #2
0
    def __init__(self, geoFile):
        self.fgeo = ROOT.TFile.Open(geoFile)
        #load geo dictionary
        upkl = Unpickler(self.fgeo)
        self.snd_geo = upkl.load('ShipGeo')
        # -----Create geometry----------------------------------------------
        run = "notNeeded"
        self.modules = sndDet_conf.configure(run, self.snd_geo)
        self.sGeo = self.fgeo.FAIRGeom
        self.modules['Scifi'].SiPMmapping()
        lsOfGlobals = ROOT.gROOT.GetListOfGlobals()
        for m in self.modules:
            lsOfGlobals.Add(self.modules[m])

        temp = {}
        for o1 in self.snd_geo:
            key = o1
            x = self.snd_geo[o1]
            if not hasattr(x, 'items'): temp[key] = x
            else:
                for o2 in x:
                    key = o1 + '/' + o2
                    y = x[o2]
                    if not hasattr(y, 'items'): temp[key] = y
                    else:
                        for o3 in y:
                            key = o1 + '/' + o2 + '__' + o3
                            z = y[o3]
                            if not hasattr(z, 'items'): temp[key] = z
        for key in temp:
            if not key.find('MuFilter') < 0:
                self.modules['MuFilter'].SetConfPar(key, temp[key])
            if not key.find('Scifi') < 0:
                self.modules['Scifi'].SetConfPar(key, temp[key])
def reRunReco(r,fname):
 fRT = fname.replace('.root','_RT2.root')
 os.system('xrdcp -f $EOSSHIP/eos/experiment/ship/data/muflux/DATA_Rebuild_8000/rootdata/'+r+'/'+fname+' '+fRT)
 f = ROOT.TFile.Open(os.environ['EOSSHIP']+'/eos/experiment/ship/user/odurhan/muflux-recodata/'+r+'/'+fname.replace('.root','_RT.root'))
 ftemp = ROOT.TFile(fRT,'update')
 ftemp.cd('')
 upkl    = Unpickler(f)
 tMinAndTmax = upkl.load('tMinAndTmax')
 pkl = Pickler(ftemp)
 pkl.dump(tMinAndTmax,'tMinAndTmax')
 ftemp.mkdir('histos')
 ftemp.histos.cd('')
 for tc in ['TDCMapsX','hitMapsX']:
    tmp = f.histos.Get(tc)
    X = tmp.Clone()
    X.Write()
 ftemp.Write("",ROOT.TFile.kOverwrite)
 ftemp.Close()
 cmd = "python "+pathToMacro+"drifttubeMonitoring.py -c recoStep1 -u 1 -f "+fRT+' &'
 os.system(cmd)
 print 'step 1:', cmd
Exemple #4
0
#
fRman = ROOT.FairRootManager.Instance()
sTree = fRman.GetInChain()
fGeo = ROOT.gGeoManager
top = fGeo.GetTopVolume()
evmgr = ROOT.gEve

if not fRun.GetGeoFile().FindKey('ShipGeo'):
    # old geofile, missing Shipgeo dictionary
    # try to figure out which ecal geo to load
    if fGeo.GetVolume('EcalModule3'): ecalGeoFile = "ecal_ellipse6x12m2.geo"
    else: ecalGeoFile = "ecal_ellipse5x10m2.geo"
    ShipGeo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py",
                                    Yheight=float(dy),
                                    EcalGeoFile=ecalGeoFile)
else:
    # new geofile, load Shipgeo dictionary written by run_simScript.py
    upkl = Unpickler(fRun.GetGeoFile())
    ShipGeo = upkl.load('ShipGeo')
    ecalGeoFile = ShipGeo.ecal.File
if hasattr(ShipGeo, 'preshowerOption'):
    if ShipGeo.preshowerOption > 0:
        mcHits['preshowerPoints'] = ROOT.FairMCPointDraw(
            "preshowerPoint", ROOT.kYellow, ROOT.kFullCircle)
        fMan.AddTask(mcHits['preshowerPoints'])
# switchOfAll('RockD')
rulers = Rulers()
SHiPDisplay = EventLoop()
SHiPDisplay.InitTask()
SHiPDisplay.NextEvent()
def run_track_pattern_recognition(input_file, geo_file, output_file, method):
    """
    Runs all steps of track pattern recognition.
    Parameters
    ----------
    input_file : string
        Path to an input .root file with events.
    geo_file : string
        Path to a file with SHiP geometry.
    output_file : string
        Path to an output .root file with quality plots.
    method : string
        Name of a track pattern recognition method.
    """

    ############################################# Load SHiP geometry ###################################################

    # Check geo file
    try:
        fgeo = ROOT.TFile(geo_file)
    except:
        print "An error with opening the ship geo file."
        raise

    sGeo = fgeo.FAIRGeom

    # Prepare ShipGeo dictionary
    if not fgeo.FindKey('ShipGeo'):

        if sGeo.GetVolume('EcalModule3'):
            ecalGeoFile = "ecal_ellipse6x12m2.geo"
        else:
            ecalGeoFile = "ecal_ellipse5x10m2.geo"

        if dy:
            ShipGeo = ConfigRegistry.loadpy(
                "$FAIRSHIP/geometry/geometry_config.py",
                Yheight=dy,
                EcalGeoFile=ecalGeoFile)
        else:
            ShipGeo = ConfigRegistry.loadpy(
                "$FAIRSHIP/geometry/geometry_config.py",
                EcalGeoFile=ecalGeoFile)

    else:
        upkl = Unpickler(fgeo)
        ShipGeo = upkl.load('ShipGeo')

    # Globals
    builtin.ShipGeo = ShipGeo

    ############################################# Load SHiP modules ####################################################

    run = ROOT.FairRunSim()
    modules = shipDet_conf.configure(run, ShipGeo)

    ############################################# Load inpur data file #################################################

    # Check input file
    try:
        fn = ROOT.TFile(input_file, 'update')
    except:
        print "An error with opening the input data file."
        raise

    sTree = fn.cbmsim
    sTree.Write()

    ############################################# Create hists #########################################################

    h = init_book_hist()

    ########################################## Start Track Pattern Recognition #########################################
    import shipPatRec

    # Init book of hists for the quality measurements
    metrics = {
        'n_hits': [],
        'reconstructible': 0,
        'passed_y12': 0,
        'passed_stereo12': 0,
        'passed_12': 0,
        'passed_y34': 0,
        'passed_stereo34': 0,
        'passed_34': 0,
        'passed_combined': 0,
        'reco_passed': 0,
        'reco_passed_no_clones': 0,
        'frac_y12': [],
        'frac_stereo12': [],
        'frac_12': [],
        'frac_y34': [],
        'frac_stereo34': [],
        'frac_34': [],
        'reco_frac_tot': [],
        'reco_mc_p': [],
        'reco_mc_theta': [],
        'fitted_p': [],
        'fitted_pval': [],
        'fitted_chi': [],
        'fitted_x': [],
        'fitted_y': [],
        'fitted_z': [],
        'fitted_mass': []
    }

    # Start event loop
    nEvents = sTree.GetEntries()

    for iEvent in range(nEvents):

        if iEvent % 1000 == 0:
            print 'Event ', iEvent

        ########################################### Select one event ###################################################

        rc = sTree.GetEvent(iEvent)

        ########################################### Reconstructible tracks #############################################

        reconstructible_tracks = getReconstructibleTracks(
            iEvent, sTree, sGeo, ShipGeo)

        metrics['reconstructible'] += len(reconstructible_tracks)
        for i_reco in reconstructible_tracks:
            h['TracksPassed'].Fill("Reconstructible tracks", 1)
            h['TracksPassedU'].Fill("Reconstructible tracks", 1)

        in_y12 = []
        in_stereo12 = []
        in_12 = []
        in_y34 = []
        in_stereo34 = []
        in_34 = []
        in_combo = []

        ########################################## Recognized tracks ###################################################

        nTracklets = sTree.Tracklets.GetEntriesFast()

        for i_track in range(nTracklets):

            atracklet = sTree.Tracklets[i_track]

            if atracklet.getType() != 1:  # this is a not full track (tracklet)
                continue

            atrack = atracklet.getList()

            if atrack.size() == 0:
                continue

            hits = {
                'X': [],
                'Y': [],
                'Z': [],
                'DetID': [],
                'TrackID': [],
                'Pz': [],
                'Px': [],
                'Py': [],
                'dist2Wire': [],
                'Pdg': []
            }

            for ihit in atrack:
                ahit = sTree.strawtubesPoint[ihit]
                hits['X'] += [ahit.GetX()]
                hits['Y'] += [ahit.GetY()]
                hits['Z'] += [ahit.GetZ()]
                hits['DetID'] += [ahit.GetDetectorID()]
                hits['TrackID'] += [ahit.GetTrackID()]
                hits['Pz'] += [ahit.GetPz()]
                hits['Px'] += [ahit.GetPx()]
                hits['Py'] += [ahit.GetPy()]
                hits['dist2Wire'] += [ahit.dist2Wire()]
                hits['Pdg'] += [ahit.PdgCode()]

            # List to numpy arrays
            for key in hits.keys():
                hits[key] = numpy.array(hits[key])

            # Decoding
            statnb, vnb, pnb, lnb, snb = decodeDetectorID(hits['DetID'])
            is_stereo = ((vnb == 1) + (vnb == 2))
            is_y = ((vnb == 0) + (vnb == 3))
            is_before = ((statnb == 1) + (statnb == 2))
            is_after = ((statnb == 3) + (statnb == 4))

            # Metrics
            metrics['n_hits'] += [get_n_hits(hits['TrackID'])]

            # Tracks passed
            frac_y12, tmax_y12 = fracMCsame(hits['TrackID'][is_before * is_y])
            n_hits_y12 = get_n_hits(hits['TrackID'][is_before * is_y])
            frac_stereo12, tmax_stereo12 = fracMCsame(
                hits['TrackID'][is_before * is_stereo])
            n_hits_stereo12 = get_n_hits(hits['TrackID'][is_before *
                                                         is_stereo])
            frac_12, tmax_12 = fracMCsame(hits['TrackID'][is_before])
            n_hits_12 = get_n_hits(hits['TrackID'][is_before])

            frac_y34, tmax_y34 = fracMCsame(hits['TrackID'][is_after * is_y])
            n_hits_y34 = get_n_hits(hits['TrackID'][is_after * is_y])
            frac_stereo34, tmax_stereo34 = fracMCsame(
                hits['TrackID'][is_after * is_stereo])
            n_hits_stereo34 = get_n_hits(hits['TrackID'][is_after * is_stereo])
            frac_34, tmax_34 = fracMCsame(hits['TrackID'][is_after])
            n_hits_34 = get_n_hits(hits['TrackID'][is_after])
            frac_tot, tmax_tot = fracMCsame(hits['TrackID'])
            n_hits_tot = get_n_hits(hits['TrackID'])

            is_reconstructed = 0
            is_reconstructed_no_clones = 0

            if tmax_y12 in reconstructible_tracks:
                metrics['passed_y12'] += 1
                metrics['frac_y12'] += [frac_y12]
                h['TracksPassed'].Fill("Y view station 1&2", 1)
                if tmax_y12 not in in_y12:
                    h['TracksPassedU'].Fill("Y view station 1&2", 1)
                    in_y12.append(tmax_y12)

                if tmax_stereo12 == tmax_y12:
                    metrics['passed_stereo12'] += 1
                    metrics['frac_stereo12'] += [frac_stereo12]
                    h['TracksPassed'].Fill("Stereo station 1&2", 1)
                    if tmax_stereo12 not in in_stereo12:
                        h['TracksPassedU'].Fill("Stereo station 1&2", 1)
                        in_stereo12.append(tmax_stereo12)

                    if tmax_12 == tmax_y12:
                        metrics['passed_12'] += 1
                        metrics['frac_12'] += [frac_12]
                        h['TracksPassed'].Fill("station 1&2", 1)
                        if tmax_12 not in in_12:
                            h['TracksPassedU'].Fill("station 1&2", 1)
                            in_12.append(tmax_12)

                        if tmax_y34 in reconstructible_tracks:
                            metrics['passed_y34'] += 1
                            metrics['frac_y34'] += [frac_y34]
                            h['TracksPassed'].Fill("Y view station 3&4", 1)
                            if tmax_y34 not in in_y34:
                                h['TracksPassedU'].Fill(
                                    "Y view station 3&4", 1)
                                in_y34.append(tmax_y34)

                            if tmax_stereo34 == tmax_y34:
                                metrics['passed_stereo34'] += 1
                                metrics['frac_stereo34'] += [frac_stereo34]
                                h['TracksPassed'].Fill("Stereo station 3&4", 1)
                                if tmax_stereo34 not in in_stereo34:
                                    h['TracksPassedU'].Fill(
                                        "Stereo station 3&4", 1)
                                    in_stereo34.append(tmax_stereo34)

                                if tmax_34 == tmax_y34:
                                    metrics['passed_34'] += 1
                                    metrics['frac_34'] += [frac_34]
                                    h['TracksPassed'].Fill("station 3&4", 1)
                                    if tmax_34 not in in_34:
                                        h['TracksPassedU'].Fill(
                                            "station 3&4", 1)
                                        in_34.append(tmax_34)

                                if tmax_12 == tmax_34:
                                    metrics['passed_combined'] += 1
                                    h['TracksPassed'].Fill(
                                        "Combined stations 1&2/3&4", 1)
                                    metrics['reco_passed'] += 1
                                    is_reconstructed = 1
                                    if tmax_34 not in in_combo:
                                        h['TracksPassedU'].Fill(
                                            "Combined stations 1&2/3&4", 1)
                                        metrics['reco_passed_no_clones'] += 1
                                        in_combo.append(tmax_34)
                                        is_reconstructed_no_clones = 1

            # For reconstructed tracks
            if is_reconstructed == 0:
                continue

            metrics['reco_frac_tot'] += [frac_tot]

            # Momentum
            Pz = hits['Pz']
            Px = hits['Px']
            Py = hits['Py']
            P = numpy.sqrt(Pz**2 + Px**2 + Py**2)
            P = P[hits['TrackID'] == tmax_tot]
            p = numpy.mean(P)

            metrics['reco_mc_p'] += [p]
            h['TracksPassed_p'].Fill(p, 1)

            # Direction
            Z = hits['Z'][(hits['TrackID'] == tmax_tot) * is_before]
            X = hits['X'][(hits['TrackID'] == tmax_tot) * is_before]
            Y = hits['Y'][(hits['TrackID'] == tmax_tot) * is_before]
            Z = Z - Z[0]
            X = X - X[0]
            Y = Y - Y[0]
            R = numpy.sqrt(X**2 + Y**2 + Z**2)
            Theta = numpy.arccos(Z[1:] / R[1:])
            theta = numpy.mean(Theta)

            metrics['reco_mc_theta'] += [theta]

            h['n_hits_reco_y12'].Fill(n_hits_y12)
            h['n_hits_reco_stereo12'].Fill(n_hits_stereo12)
            h['n_hits_reco_12'].Fill(n_hits_12)
            h['n_hits_reco_y34'].Fill(n_hits_y34)
            h['n_hits_reco_stereo34'].Fill(n_hits_stereo34)
            h['n_hits_reco_34'].Fill(n_hits_34)
            h['n_hits_reco'].Fill(n_hits_tot)

            h['n_hits_y12'].Fill(p, n_hits_y12)
            h['n_hits_stereo12'].Fill(p, n_hits_stereo12)
            h['n_hits_12'].Fill(p, n_hits_12)
            h['n_hits_y34'].Fill(p, n_hits_y34)
            h['n_hits_stereo34'].Fill(p, n_hits_stereo34)
            h['n_hits_34'].Fill(p, n_hits_34)
            h['n_hits_total'].Fill(p, n_hits_tot)

            h['frac_y12'].Fill(p, frac_y12)
            h['frac_stereo12'].Fill(p, frac_stereo12)
            h['frac_12'].Fill(p, frac_12)
            h['frac_y34'].Fill(p, frac_y34)
            h['frac_stereo34'].Fill(p, frac_stereo34)
            h['frac_34'].Fill(p, frac_34)
            h['frac_total'].Fill(p, frac_tot)

            # Fitted track

            thetrack = sTree.FitTracks[i_track]

            fitStatus = thetrack.getFitStatus()
            thetrack.prune(
                "CFL"
            )  # http://sourceforge.net/p/genfit/code/HEAD/tree/trunk/core/include/Track.h#l280

            nmeas = fitStatus.getNdf()
            pval = fitStatus.getPVal()
            chi2 = fitStatus.getChi2() / nmeas

            metrics['fitted_pval'] += [pval]
            metrics['fitted_chi'] += [chi2]

            h['chi2fittedtracks'].Fill(chi2)
            h['pvalfittedtracks'].Fill(pval)

            fittedState = thetrack.getFittedState()
            fittedMom = fittedState.getMomMag()
            fittedMom = fittedMom  #*int(charge)

            metrics['fitted_p'] += [fittedMom]
            perr = (p - fittedMom) / p
            h['ptrue-p/ptrue'].Fill(perr)
            h['perr'].Fill(p, perr)
            h['perr_direction'].Fill(numpy.rad2deg(theta), perr)

            if math.fabs(p) > 0.0:
                h['pvspfitted'].Fill(p, fittedMom)
            fittedtrackDir = fittedState.getDir()
            fittedx = math.degrees(math.acos(fittedtrackDir[0]))
            fittedy = math.degrees(math.acos(fittedtrackDir[1]))
            fittedz = math.degrees(math.acos(fittedtrackDir[2]))
            fittedmass = fittedState.getMass()
            h['momentumfittedtracks'].Fill(fittedMom)
            h['xdirectionfittedtracks'].Fill(fittedx)
            h['ydirectionfittedtracks'].Fill(fittedy)
            h['zdirectionfittedtracks'].Fill(fittedz)
            h['massfittedtracks'].Fill(fittedmass)

            metrics['fitted_x'] += [fittedx]
            metrics['fitted_y'] += [fittedy]
            metrics['fitted_z'] += [fittedz]
            metrics['fitted_mass'] += [fittedmass]

    ############################################# Save hists #########################################################

    save_hists(h, output_file)

    return metrics
Exemple #6
0
from __future__ import print_function
import ROOT,sys
from rootpyPickler import Unpickler
badBoys={}
f1,f2 = sys.argv[1], sys.argv[2]
fgeoOld=ROOT.TFile(f1)
upkl    = Unpickler(fgeoOld)
ShipGeoOld = upkl.load('ShipGeo')
fgeoNew=ROOT.TFile(f2)
upkl    = Unpickler(fgeoNew)
ShipGeoNew = upkl.load('ShipGeo')
for x in ShipGeoNew:
   if hasattr(eval('ShipGeoNew.'+x),'z'): 
     zold,znew = eval('ShipGeoOld.'+x+'.z'),eval('ShipGeoNew.'+x+'.z')
     print(x,'z=',znew, ' old:', zold)
     if  zold!=znew: badBoys[x]=[znew,zold]
if len(badBoys)>0: print("following differences detected:")
for x in badBoys:
  print(x,badBoys[x])

Exemple #7
0
def dmetric(input_file, geo_file, dy, reconstructiblerequired, threeprong):

    ############################################# Load SHiP geometry ###################################################

    # Check geo file
    try:
        fgeo = ROOT.TFile(geo_file)
    except:
        print "An error with opening the ship geo file."
        raise

    sGeo = fgeo.FAIRGeom

    # Prepare ShipGeo dictionary
    if not fgeo.FindKey('ShipGeo'):

        if sGeo.GetVolume('EcalModule3') :
            ecalGeoFile = "ecal_ellipse6x12m2.geo"
        else:
            ecalGeoFile = "ecal_ellipse5x10m2.geo"

        if dy:
            ShipGeo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight = dy, EcalGeoFile = ecalGeoFile)
        else:
            ShipGeo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", EcalGeoFile = ecalGeoFile)

    else:
        upkl    = Unpickler(fgeo)
        ShipGeo = upkl.load('ShipGeo')

    ############################################# Load SHiP modules ####################################################

    run = ROOT.FairRunSim()
    modules = shipDet_conf.configure(run,ShipGeo)

    ############################################# Load input data file #################################################

    # Check input file
    try:
        fn = ROOT.TFile(input_file,'update')
    except:
        print "An error with opening the input data file."
        raise

    sTree = fn.cbmsim

    ############################## Initialize SHiP Spectrometer Tracker geometry #######################################

    zlayer, \
    zlayerv2, \
    z34layer, \
    z34layerv2, \
    TStation1StartZ, \
    TStation4EndZ, \
    VetoStationZ, \
    VetoStationEndZ = initialize(ShipGeo)


    ########################################## Start Checking Geometry #################################################

    all_hits = pandas.DataFrame(columns=['event_id', 'det_id', 'track_id', 'xtop', 'ytop', 'z', 'xbot', 'ybot'])
    all_hits_i = 0
    
    # Start event loop
    nEvents   = sTree.GetEntries()

    for iEvent in range(nEvents):

        if iEvent%100 == 0:
            print 'Event ', iEvent

        ########################################### Select one event ###################################################

        rc = sTree.GetEvent(iEvent)

        ############################################# Get hits #########################################################
        
        reco_mc_tracks = getReconstructibleTracks(iEvent,
                                                  sTree,
                                                  sGeo,
                                                  reconstructiblerequired,
                                                  threeprong,
                                                  TStation1StartZ,
                                                  TStation4EndZ,
                                                  VetoStationZ,
                                                  VetoStationEndZ)
        
        #consider only reconstructible events
        if len(reco_mc_tracks) > 1:

            nHits = sTree.strawtubesPoint.GetEntriesFast()
            key = -1

            for i in range(nHits):

                ahit = sTree.strawtubesPoint[i]

                key+=1
                detID = ahit.GetDetectorID()
                trID = ahit.GetTrackID()
                top = ROOT.TVector3()
                bot = ROOT.TVector3()

                modules["Strawtubes"].StrawEndPoints(detID,bot,top)

                all_hits.loc[all_hits_i] = [iEvent, detID, trID, top.x(), top.y(), top.z(), bot.x(), bot.y()]
                all_hits_i += 1
            
    all_hits['StatNb'] = all_hits['det_id'] // 10000000
    all_hits['ViewNb'] = (all_hits['det_id'] - all_hits['StatNb'] * 10000000) // 1000000
    all_hits['PlaneNb'] = (all_hits['det_id'] - all_hits['StatNb'] * 10000000 - all_hits['ViewNb'] * 1000000) // 100000
    all_hits['LayerNb'] = (all_hits['det_id'] - all_hits['StatNb'] * 10000000 - all_hits['ViewNb'] * 1000000 -\
                           all_hits['PlaneNb'] * 100000) // 10000
    all_hits['StrawNb'] = all_hits['det_id'] - all_hits['StatNb'] * 10000000 - all_hits['ViewNb'] * 1000000 -\
                          all_hits['PlaneNb'] * 100000 - all_hits['LayerNb'] * 10000 - 2000
    
    #return daniel's metric
    df_1_view = all_hits[(all_hits.StatNb==1)&(all_hits.ViewNb==0)]
    counts = df_1_view.groupby(['event_id', 'track_id'])['StatNb'].count()
    all_tracks = len(all_hits.groupby(['event_id', 'track_id'])['StatNb'].count())
    
    return 1. * np.sum(counts>1) / all_tracks
def run_track_pattern_recognition(input_file, geo_file, output_file, method):
    """
    Runs all steps of track pattern recognition.
    Parameters
    ----------
    input_file : string
        Path to an input .root file with events.
    geo_file : string
        Path to a file with SHiP geometry.
    output_file : string
        Path to an output .root file with quality plots.
    method : string
        Name of a track pattern recognition method.
    """

    ############################################# Load SHiP geometry ###################################################

    # Check geo file
    try:
        fgeo = ROOT.TFile(geo_file)
    except:
        print("An error with opening the ship geo file.")
        raise

    sGeo = fgeo.FAIRGeom

    # Prepare ShipGeo dictionary
    if not fgeo.FindKey('ShipGeo'):

        if sGeo.GetVolume('EcalModule3'):
            ecalGeoFile = "ecal_ellipse6x12m2.geo"
        else:
            ecalGeoFile = "ecal_ellipse5x10m2.geo"

        if dy:
            ShipGeo = ConfigRegistry.loadpy(
                "$FAIRSHIP/geometry/geometry_config.py",
                Yheight=dy,
                EcalGeoFile=ecalGeoFile)
        else:
            ShipGeo = ConfigRegistry.loadpy(
                "$FAIRSHIP/geometry/geometry_config.py",
                EcalGeoFile=ecalGeoFile)

    else:
        upkl = Unpickler(fgeo)
        ShipGeo = upkl.load('ShipGeo')

    # Globals
    builtin.ShipGeo = ShipGeo

    ############################################# Load SHiP modules ####################################################

    import shipDet_conf
    run = ROOT.FairRunSim()
    run.SetName("TGeant4")  # Transport engine
    run.SetOutputFile("dummy")  # Output file
    run.SetUserConfig(
        "g4Config_basic.C"
    )  # geant4 transport not used, only needed for the mag field
    rtdb = run.GetRuntimeDb()

    modules = shipDet_conf.configure(run, ShipGeo)
    run.Init()

    #run = ROOT.FairRunSim()
    #modules = shipDet_conf.configure(run,ShipGeo)

    ######################################### Load SHiP magnetic field #################################################

    import geomGeant4
    if hasattr(ShipGeo.Bfield, "fieldMap"):
        fieldMaker = geomGeant4.addVMCFields(ShipGeo,
                                             '',
                                             True,
                                             withVirtualMC=False)
    else:
        print("no fieldmap given, geofile too old, not anymore support")
        exit(-1)
    sGeo = fgeo.FAIRGeom
    geoMat = ROOT.genfit.TGeoMaterialInterface()
    ROOT.genfit.MaterialEffects.getInstance().init(geoMat)
    bfield = ROOT.genfit.FairShipFields()
    bfield.setField(fieldMaker.getGlobalField())
    fM = ROOT.genfit.FieldManager.getInstance()
    fM.init(bfield)

    ############################################# Load inpur data file #################################################

    # Check input file
    try:
        fn = ROOT.TFile(input_file, 'update')
    except:
        print("An error with opening the input data file.")
        raise

    sTree = fn.cbmsim
    sTree.Write()

    ############################################# Create hists #########################################################

    h = init_book_hist()

    ########################################## Start Track Pattern Recognition #########################################
    import shipPatRec

    # Init book of hists for the quality measurements
    metrics = {
        'n_hits': [],
        'reconstructible': 0,
        'passed_y12': 0,
        'passed_stereo12': 0,
        'passed_12': 0,
        'passed_y34': 0,
        'passed_stereo34': 0,
        'passed_34': 0,
        'passed_combined': 0,
        'reco_passed': 0,
        'reco_passed_no_clones': 0,
        'frac_y12': [],
        'frac_stereo12': [],
        'frac_12': [],
        'frac_y34': [],
        'frac_stereo34': [],
        'frac_34': [],
        'reco_frac_tot': [],
        'reco_mc_p': [],
        'reco_mc_theta': [],
        'fitted_p': [],
        'fitted_pval': [],
        'fitted_chi': [],
        'fitted_x': [],
        'fitted_y': [],
        'fitted_z': [],
        'fitted_mass': []
    }

    # Start event loop
    nEvents = sTree.GetEntries()

    for iEvent in range(nEvents):

        if iEvent % 1000 == 0:
            print('Event ', iEvent)

        ########################################### Select one event ###################################################

        rc = sTree.GetEvent(iEvent)

        ########################################### Reconstructible tracks #############################################

        reconstructible_tracks = getReconstructibleTracks(
            iEvent, sTree, sGeo, ShipGeo)

        metrics['reconstructible'] += len(reconstructible_tracks)
        for i_reco in reconstructible_tracks:
            h['TracksPassed'].Fill("Reconstructible tracks", 1)
            h['TracksPassedU'].Fill("Reconstructible tracks", 1)

        in_y12 = []
        in_stereo12 = []
        in_12 = []
        in_y34 = []
        in_stereo34 = []
        in_34 = []
        in_combo = []

        found_track_ids = []
        n_tracks = len(reconstructible_tracks)
        n_recognized = 0
        n_clones = 0
        n_ghosts = 0
        n_others = 0

        min_eff = 0.

        ########################################## Recognized tracks ###################################################

        nTracklets = sTree.Tracklets.GetEntriesFast()

        for i_track in range(nTracklets):

            atracklet = sTree.Tracklets[i_track]

            if atracklet.getType() != 1:  # this is a not full track (tracklet)
                continue

            atrack = atracklet.getList()

            if atrack.size() == 0:
                continue

            hits = {
                'X': [],
                'Y': [],
                'Z': [],
                'DetID': [],
                'TrackID': [],
                'Pz': [],
                'Px': [],
                'Py': [],
                'dist2Wire': [],
                'Pdg': []
            }

            for ihit in atrack:
                ahit = sTree.strawtubesPoint[ihit]
                hits['X'] += [ahit.GetX()]
                hits['Y'] += [ahit.GetY()]
                hits['Z'] += [ahit.GetZ()]
                hits['DetID'] += [ahit.GetDetectorID()]
                hits['TrackID'] += [ahit.GetTrackID()]
                hits['Pz'] += [ahit.GetPz()]
                hits['Px'] += [ahit.GetPx()]
                hits['Py'] += [ahit.GetPy()]
                hits['dist2Wire'] += [ahit.dist2Wire()]
                hits['Pdg'] += [ahit.PdgCode()]

            # List to numpy arrays
            for key in hits.keys():
                hits[key] = numpy.array(hits[key])

            # Decoding
            statnb, vnb, pnb, lnb, snb = decodeDetectorID(hits['DetID'])
            is_stereo = ((vnb == 1) + (vnb == 2))
            is_y = ((vnb == 0) + (vnb == 3))
            is_before = ((statnb == 1) + (statnb == 2))
            is_after = ((statnb == 3) + (statnb == 4))

            # Metrics
            metrics['n_hits'] += [get_n_hits(hits['TrackID'])]

            # Tracks passed
            frac_y12, tmax_y12 = fracMCsame(hits['TrackID'][is_before * is_y])
            n_hits_y12 = get_n_hits(hits['TrackID'][is_before * is_y])
            frac_stereo12, tmax_stereo12 = fracMCsame(
                hits['TrackID'][is_before * is_stereo])
            n_hits_stereo12 = get_n_hits(hits['TrackID'][is_before *
                                                         is_stereo])
            frac_12, tmax_12 = fracMCsame(hits['TrackID'][is_before])
            n_hits_12 = get_n_hits(hits['TrackID'][is_before])

            frac_y34, tmax_y34 = fracMCsame(hits['TrackID'][is_after * is_y])
            n_hits_y34 = get_n_hits(hits['TrackID'][is_after * is_y])
            frac_stereo34, tmax_stereo34 = fracMCsame(
                hits['TrackID'][is_after * is_stereo])
            n_hits_stereo34 = get_n_hits(hits['TrackID'][is_after * is_stereo])
            frac_34, tmax_34 = fracMCsame(hits['TrackID'][is_after])
            n_hits_34 = get_n_hits(hits['TrackID'][is_after])
            frac_tot, tmax_tot = fracMCsame(hits['TrackID'])
            n_hits_tot = get_n_hits(hits['TrackID'])

            if tmax_y12 == tmax_stereo12 and tmax_y12 == tmax_y34 and tmax_y12 == tmax_stereo34:
                if frac_y12 >= min_eff and frac_stereo12 >= min_eff and frac_y34 >= min_eff and frac_stereo34 >= min_eff:

                    if tmax_y12 in reconstructible_tracks and tmax_y12 not in found_track_ids:
                        n_recognized += 1
                        found_track_ids.append(tmax_y12)
                    elif tmax_y12 in reconstructible_tracks and tmax_y12 in found_track_ids:
                        n_clones += 1
                    elif tmax_y12 not in reconstructible_tracks:
                        n_others += 1

                else:
                    n_ghosts += 1
            else:
                n_ghosts += 1

            is_reconstructed = 0
            is_reconstructed_no_clones = 0

            if tmax_y12 in reconstructible_tracks:
                metrics['passed_y12'] += 1
                metrics['frac_y12'] += [frac_y12]
                h['TracksPassed'].Fill("Y view station 1&2", 1)
                if tmax_y12 not in in_y12:
                    h['TracksPassedU'].Fill("Y view station 1&2", 1)
                    in_y12.append(tmax_y12)

                if tmax_stereo12 == tmax_y12:
                    metrics['passed_stereo12'] += 1
                    metrics['frac_stereo12'] += [frac_stereo12]
                    h['TracksPassed'].Fill("Stereo station 1&2", 1)
                    if tmax_stereo12 not in in_stereo12:
                        h['TracksPassedU'].Fill("Stereo station 1&2", 1)
                        in_stereo12.append(tmax_stereo12)

                    if tmax_12 == tmax_y12:
                        metrics['passed_12'] += 1
                        metrics['frac_12'] += [frac_12]
                        h['TracksPassed'].Fill("station 1&2", 1)
                        if tmax_12 not in in_12:
                            h['TracksPassedU'].Fill("station 1&2", 1)
                            in_12.append(tmax_12)

                        if tmax_y34 in reconstructible_tracks:
                            metrics['passed_y34'] += 1
                            metrics['frac_y34'] += [frac_y34]
                            h['TracksPassed'].Fill("Y view station 3&4", 1)
                            if tmax_y34 not in in_y34:
                                h['TracksPassedU'].Fill(
                                    "Y view station 3&4", 1)
                                in_y34.append(tmax_y34)

                            if tmax_stereo34 == tmax_y34:
                                metrics['passed_stereo34'] += 1
                                metrics['frac_stereo34'] += [frac_stereo34]
                                h['TracksPassed'].Fill("Stereo station 3&4", 1)
                                if tmax_stereo34 not in in_stereo34:
                                    h['TracksPassedU'].Fill(
                                        "Stereo station 3&4", 1)
                                    in_stereo34.append(tmax_stereo34)

                                if tmax_34 == tmax_y34:
                                    metrics['passed_34'] += 1
                                    metrics['frac_34'] += [frac_34]
                                    h['TracksPassed'].Fill("station 3&4", 1)
                                    if tmax_34 not in in_34:
                                        h['TracksPassedU'].Fill(
                                            "station 3&4", 1)
                                        in_34.append(tmax_34)

                                    if tmax_12 == tmax_34:
                                        metrics['passed_combined'] += 1
                                        h['TracksPassed'].Fill(
                                            "Combined stations 1&2/3&4", 1)
                                        metrics['reco_passed'] += 1
                                        is_reconstructed = 1
                                        if tmax_34 not in in_combo:
                                            h['TracksPassedU'].Fill(
                                                "Combined stations 1&2/3&4", 1)
                                            metrics[
                                                'reco_passed_no_clones'] += 1
                                            in_combo.append(tmax_34)
                                            is_reconstructed_no_clones = 1

            # For reconstructed tracks
            if is_reconstructed == 0:
                continue

            metrics['reco_frac_tot'] += [frac_tot]

            # Momentum
            Pz = hits['Pz']
            Px = hits['Px']
            Py = hits['Py']

            p, px, py, pz = getPtruthFirst(sTree, tmax_tot)
            pt = math.sqrt(px**2 + py**2)

            Z_true = []
            X_true = []
            Y_true = []
            for ahit in sTree.strawtubesPoint:
                if ahit.GetTrackID() == tmax_tot:
                    az, ax, ay = ahit.GetZ(), ahit.GetX(), ahit.GetY()
                    Z_true.append(az)
                    X_true.append(ax)
                    Y_true.append(ay)

            metrics['reco_mc_p'] += [p]
            h['TracksPassed_p'].Fill(p, 1)

            # Direction
            Z = hits['Z'][(hits['TrackID'] == tmax_tot) * is_before]
            X = hits['X'][(hits['TrackID'] == tmax_tot) * is_before]
            Y = hits['Y'][(hits['TrackID'] == tmax_tot) * is_before]
            Z = Z - Z[0]
            X = X - X[0]
            Y = Y - Y[0]
            R = numpy.sqrt(X**2 + Y**2 + Z**2)
            Theta = numpy.arccos(Z[1:] / R[1:])
            theta = numpy.mean(Theta)

            metrics['reco_mc_theta'] += [theta]

            h['n_hits_reco_y12'].Fill(n_hits_y12)
            h['n_hits_reco_stereo12'].Fill(n_hits_stereo12)
            h['n_hits_reco_12'].Fill(n_hits_12)
            h['n_hits_reco_y34'].Fill(n_hits_y34)
            h['n_hits_reco_stereo34'].Fill(n_hits_stereo34)
            h['n_hits_reco_34'].Fill(n_hits_34)
            h['n_hits_reco'].Fill(n_hits_tot)

            h['n_hits_y12'].Fill(p, n_hits_y12)
            h['n_hits_stereo12'].Fill(p, n_hits_stereo12)
            h['n_hits_12'].Fill(p, n_hits_12)
            h['n_hits_y34'].Fill(p, n_hits_y34)
            h['n_hits_stereo34'].Fill(p, n_hits_stereo34)
            h['n_hits_34'].Fill(p, n_hits_34)
            h['n_hits_total'].Fill(p, n_hits_tot)

            h['frac_y12'].Fill(p, frac_y12)
            h['frac_stereo12'].Fill(p, frac_stereo12)
            h['frac_12'].Fill(p, frac_12)
            h['frac_y34'].Fill(p, frac_y34)
            h['frac_stereo34'].Fill(p, frac_stereo34)
            h['frac_34'].Fill(p, frac_34)
            h['frac_total'].Fill(p, frac_tot)

            h['frac_y12_dist'].Fill(frac_y12)
            h['frac_stereo12_dist'].Fill(frac_stereo12)
            h['frac_12_dist'].Fill(frac_12)
            h['frac_y34_dist'].Fill(frac_y34)
            h['frac_stereo34_dist'].Fill(frac_stereo34)
            h['frac_34_dist'].Fill(frac_34)
            h['frac_total_dist'].Fill(frac_tot)

            # Fitted track

            thetrack = sTree.FitTracks[i_track]

            fitStatus = thetrack.getFitStatus()
            thetrack.prune(
                "CFL"
            )  # http://sourceforge.net/p/genfit/code/HEAD/tree/trunk/core/include/Track.h#l280

            nmeas = fitStatus.getNdf()
            pval = fitStatus.getPVal()
            chi2 = fitStatus.getChi2() / nmeas

            metrics['fitted_pval'] += [pval]
            metrics['fitted_chi'] += [chi2]

            h['chi2fittedtracks'].Fill(chi2)
            h['pvalfittedtracks'].Fill(pval)

            try:

                fittedState = thetrack.getFittedState()
                fittedMom = fittedState.getMomMag()
                fittedMom = fittedMom  #*int(charge)

                px_fit, py_fit, pz_fit = fittedState.getMom().x(
                ), fittedState.getMom().y(), fittedState.getMom().z()
                p_fit = fittedMom
                pt_fit = math.sqrt(px_fit**2 + py_fit**2)

                metrics['fitted_p'] += [p_fit]
                perr = (p - p_fit) / p
                h['ptrue-p/ptrue'].Fill(perr)
                h['perr'].Fill(p, perr)
                h['perr_direction'].Fill(numpy.rad2deg(theta), perr)

                pterr = (pt - pt_fit) / pt
                h['pttrue-pt/pttrue'].Fill(pterr)

                pxerr = (px - px_fit) / px
                h['pxtrue-px/pxtrue'].Fill(pxerr)

                pyerr = (py - py_fit) / py
                h['pytrue-py/pytrue'].Fill(pyerr)

                pzerr = (pz - pz_fit) / pz
                h['pztrue-pz/pztrue'].Fill(pzerr)

                if math.fabs(p) > 0.0:
                    h['pvspfitted'].Fill(p, fittedMom)
                fittedtrackDir = fittedState.getDir()
                fittedx = math.degrees(math.acos(fittedtrackDir[0]))
                fittedy = math.degrees(math.acos(fittedtrackDir[1]))
                fittedz = math.degrees(math.acos(fittedtrackDir[2]))
                fittedmass = fittedState.getMass()
                h['momentumfittedtracks'].Fill(fittedMom)
                h['xdirectionfittedtracks'].Fill(fittedx)
                h['ydirectionfittedtracks'].Fill(fittedy)
                h['zdirectionfittedtracks'].Fill(fittedz)
                h['massfittedtracks'].Fill(fittedmass)

                metrics['fitted_x'] += [fittedx]
                metrics['fitted_y'] += [fittedy]
                metrics['fitted_z'] += [fittedz]
                metrics['fitted_mass'] += [fittedmass]

                Z_fit = []
                X_fit = []
                Y_fit = []
                for az in Z_true:
                    rc, pos, mom = extrapolateToPlane(thetrack, az)
                    Z_fit.append(pos.Z())
                    X_fit.append(pos.X())
                    Y_fit.append(pos.Y())

                for i in range(len(Z_true)):
                    xerr = abs(X_fit[i] - X_true[i])
                    yerr = abs(Y_fit[i] - Y_true[i])
                    h['abs(x - x-true)'].Fill(xerr)
                    h['abs(y - y-true)'].Fill(yerr)

                rmse_x = numpy.sqrt(
                    numpy.mean((numpy.array(X_fit) - numpy.array(X_true))**2))
                rmse_y = numpy.sqrt(
                    numpy.mean((numpy.array(Y_fit) - numpy.array(Y_true))**2))
                h['rmse_x'].Fill(rmse_x)
                h['rmse_y'].Fill(rmse_y)

            except:
                print("Problem with fitted state.")

        h['Reco_tracks'].Fill("N total", n_tracks)
        h['Reco_tracks'].Fill("N recognized tracks", n_recognized)
        h['Reco_tracks'].Fill("N clones", n_clones)
        h['Reco_tracks'].Fill("N ghosts", n_ghosts)
        h['Reco_tracks'].Fill("N others", n_others)

    ############################################# Save hists #########################################################

    save_hists(h, output_file)

    return metrics
def run_track_pattern_recognition(input_file, geo_file, output_file, method):
    """
    Runs all steps of track pattern recognition.

    Parameters
    ----------
    input_file : string
        Path to an input .root file with events.
    geo_file : string
        Path to a file with SHiP geometry.
    output_file : string
        Path to an output .root file with quality plots.
    method : string
        Name of a track pattern recognition method.
    """


    ############################################# Load SHiP geometry ###################################################

    # Check geo file
    try:
        fgeo = ROOT.TFile(geo_file)
    except:
        print "An error with opening the ship geo file."
        raise

    sGeo = fgeo.FAIRGeom

    # Prepare ShipGeo dictionary
    if not fgeo.FindKey('ShipGeo'):

        if sGeo.GetVolume('EcalModule3') :
            ecalGeoFile = "ecal_ellipse6x12m2.geo"
        else:
            ecalGeoFile = "ecal_ellipse5x10m2.geo"

        if dy:
            ShipGeo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight = dy, EcalGeoFile = ecalGeoFile)
        else:
            ShipGeo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", EcalGeoFile = ecalGeoFile)

    else:
        upkl    = Unpickler(fgeo)
        ShipGeo = upkl.load('ShipGeo')
    
    # Globals
    builtin.ShipGeo = ShipGeo

    ############################################# Load SHiP modules ####################################################

    run = ROOT.FairRunSim()
    modules = shipDet_conf.configure(run,ShipGeo)

    ############################################# Load inpur data file #################################################

    # Check input file
    try:
        fn = ROOT.TFile(input_file,'update')
    except:
        print "An error with opening the input data file."
        raise

    sTree = fn.cbmsim
    sTree.Write()
    
    ############################################# Create hists #########################################################
    
    h = init_book_hist()

    ########################################## Start Track Pattern Recognition #########################################
    import shipPatRec

    # Init book of hists for the quality measurements
    metrics = {'n_hits': [], 
               'reconstructible': 0, 
               'passed_y12': 0, 'passed_stereo12': 0, 'passed_12': 0, 
               'passed_y34': 0, 'passed_stereo34': 0, 'passed_34': 0, 
               'passed_combined': 0, 'reco_passed': 0, 'reco_passed_no_clones': 0,
               'frac_y12': [], 'frac_stereo12': [], 'frac_12': [], 
               'frac_y34': [], 'frac_stereo34': [], 'frac_34': [], 
               'reco_frac_tot': [], 
               'reco_mc_p': [], 'reco_mc_theta': [], 
               'fitted_p': [], 'fitted_pval': [], 'fitted_chi': [], 
               'fitted_x': [], 'fitted_y': [], 'fitted_z': [], 'fitted_mass': []}

    # Start event loop
    nEvents   = sTree.GetEntries()
   

    for iEvent in range(nEvents):

        if iEvent%1000 == 0:
            print 'Event ', iEvent

        ########################################### Select one event ###################################################

        rc = sTree.GetEvent(iEvent)

        ########################################### Reconstructible tracks #############################################

        reconstructible_tracks = getReconstructibleTracks(iEvent, sTree, sGeo, ShipGeo)
        
        metrics['reconstructible'] += len(reconstructible_tracks)
        for i_reco in reconstructible_tracks:
            h['TracksPassed'].Fill("Reconstructible tracks", 1)
            h['TracksPassedU'].Fill("Reconstructible tracks", 1)
            
        in_y12 = []
        in_stereo12 = []
        in_12 = []
        in_y34 = []
        in_stereo34 = []
        in_34 = []
        in_combo = []
        
        ########################################## Recognized tracks ###################################################
        
        nTracklets = sTree.Tracklets.GetEntriesFast()
        
        for i_track in range(nTracklets):
            
            atracklet = sTree.Tracklets[i_track]
            
            if atracklet.getType() != 1: # this is a not full track (tracklet)
                continue
                
            atrack = atracklet.getList()
            
            if atrack.size() == 0:
                continue
            
            hits = {'X': [], 'Y': [], 'Z': [], 
                    'DetID': [], 'TrackID': [], 
                    'Pz': [], 'Px': [], 'Py': [], 
                    'dist2Wire': [], 'Pdg': []}
            
            for ihit in atrack:
                ahit = sTree.strawtubesPoint[ihit]
                hits['X'] += [ahit.GetX()]
                hits['Y'] += [ahit.GetY()]
                hits['Z'] += [ahit.GetZ()]
                hits['DetID'] += [ahit.GetDetectorID()]
                hits['TrackID'] += [ahit.GetTrackID()]
                hits['Pz'] += [ahit.GetPz()]
                hits['Px'] += [ahit.GetPx()]
                hits['Py'] += [ahit.GetPy()]
                hits['dist2Wire'] += [ahit.dist2Wire()]
                hits['Pdg'] += [ahit.PdgCode()]
                
            # List to numpy arrays
            for key in hits.keys():
                hits[key] = numpy.array(hits[key])
                
            # Decoding
            statnb, vnb, pnb, lnb, snb = decodeDetectorID(hits['DetID'])
            is_stereo = ((vnb == 1) + (vnb == 2))
            is_y = ((vnb == 0) + (vnb == 3))
            is_before = ((statnb == 1) + (statnb == 2))
            is_after = ((statnb == 3) + (statnb == 4)) 
                
            
            # Metrics
            metrics['n_hits'] += [get_n_hits(hits['TrackID'])]
            
            # Tracks passed
            frac_y12, tmax_y12 = fracMCsame(hits['TrackID'][is_before * is_y])
            n_hits_y12 = get_n_hits(hits['TrackID'][is_before * is_y])
            frac_stereo12, tmax_stereo12 = fracMCsame(hits['TrackID'][is_before * is_stereo])
            n_hits_stereo12 = get_n_hits(hits['TrackID'][is_before * is_stereo])
            frac_12, tmax_12 = fracMCsame(hits['TrackID'][is_before])
            n_hits_12 = get_n_hits(hits['TrackID'][is_before])
            
            frac_y34, tmax_y34 = fracMCsame(hits['TrackID'][is_after * is_y])
            n_hits_y34 = get_n_hits(hits['TrackID'][is_after * is_y])
            frac_stereo34, tmax_stereo34 = fracMCsame(hits['TrackID'][is_after * is_stereo])
            n_hits_stereo34 = get_n_hits(hits['TrackID'][is_after * is_stereo])
            frac_34, tmax_34 = fracMCsame(hits['TrackID'][is_after])
            n_hits_34 = get_n_hits(hits['TrackID'][is_after])
            frac_tot, tmax_tot = fracMCsame(hits['TrackID'])
            n_hits_tot = get_n_hits(hits['TrackID'])
            
            is_reconstructed = 0
            is_reconstructed_no_clones = 0
            
            
            if tmax_y12 in reconstructible_tracks:
                metrics['passed_y12'] += 1
                metrics['frac_y12'] += [frac_y12]
                h['TracksPassed'].Fill("Y view station 1&2", 1)
                if tmax_y12 not in in_y12:
                    h['TracksPassedU'].Fill("Y view station 1&2", 1)
                    in_y12.append(tmax_y12)
                
                if tmax_stereo12 == tmax_y12:
                    metrics['passed_stereo12'] += 1
                    metrics['frac_stereo12'] += [frac_stereo12]
                    h['TracksPassed'].Fill("Stereo station 1&2", 1)
                    if tmax_stereo12 not in in_stereo12:
                        h['TracksPassedU'].Fill("Stereo station 1&2", 1)
                        in_stereo12.append(tmax_stereo12)
                    
                    if tmax_12 == tmax_y12:
                        metrics['passed_12'] += 1
                        metrics['frac_12'] += [frac_12]
                        h['TracksPassed'].Fill("station 1&2", 1)
                        if tmax_12 not in in_12:
                            h['TracksPassedU'].Fill("station 1&2", 1)
                            in_12.append(tmax_12)
                        
                        if tmax_y34 in reconstructible_tracks:
                            metrics['passed_y34'] += 1
                            metrics['frac_y34'] += [frac_y34]
                            h['TracksPassed'].Fill("Y view station 3&4", 1)
                            if tmax_y34 not in in_y34:
                                h['TracksPassedU'].Fill("Y view station 3&4", 1)
                                in_y34.append(tmax_y34)
                            
                            if tmax_stereo34 == tmax_y34:
                                metrics['passed_stereo34'] += 1
                                metrics['frac_stereo34'] += [frac_stereo34]
                                h['TracksPassed'].Fill("Stereo station 3&4", 1)
                                if tmax_stereo34 not in in_stereo34:
                                    h['TracksPassedU'].Fill("Stereo station 3&4", 1)
                                    in_stereo34.append(tmax_stereo34)
                                
                                if tmax_34 == tmax_y34:
                                    metrics['passed_34'] += 1
                                    metrics['frac_34'] += [frac_34]
                                    h['TracksPassed'].Fill("station 3&4", 1)
                                    if tmax_34 not in in_34:
                                        h['TracksPassedU'].Fill("station 3&4", 1)
                                        in_34.append(tmax_34)
                                    
                                    if tmax_12 == tmax_34:
                                        metrics['passed_combined'] += 1
                                        h['TracksPassed'].Fill("Combined stations 1&2/3&4", 1)
                                        is_reconstructed = 1
                                        if tmax_34 not in in_combo:
                                            h['TracksPassedU'].Fill("Combined stations 1&2/3&4", 1)
                                            in_combo.append(tmax_34)
                                            is_reconstructed_no_clones = 1
                                        
            # For reconstructed tracks
            if is_reconstructed == 0:
                continue
                
            metrics['reco_passed'] += 1
            metrics['reco_passed_no_clones'] += 1
            metrics['reco_frac_tot'] += [frac_tot]
            
            # Momentum
            Pz = hits['Pz']
            Px = hits['Px']
            Py = hits['Py']
            P = numpy.sqrt(Pz**2 + Px**2 + Py**2)
            P = P[hits['TrackID'] == tmax_tot]
            p = numpy.mean(P)
            
            metrics['reco_mc_p'] += [p]
            h['TracksPassed_p'].Fill(p, 1)
            
            # Direction
            Z = hits['Z'][(hits['TrackID'] == tmax_tot) * is_before]
            X = hits['X'][(hits['TrackID'] == tmax_tot) * is_before]
            Y = hits['Y'][(hits['TrackID'] == tmax_tot) * is_before]
            Z = Z - Z[0]
            X = X - X[0]
            Y = Y - Y[0]
            R = numpy.sqrt(X**2 + Y**2 + Z**2)
            Theta = numpy.arccos(Z[1:] / R[1:])
            theta = numpy.mean(Theta)
            
            metrics['reco_mc_theta'] += [theta]
            
            h['n_hits_reco_y12'].Fill(n_hits_y12)
            h['n_hits_reco_stereo12'].Fill(n_hits_stereo12)
            h['n_hits_reco_12'].Fill(n_hits_12)
            h['n_hits_reco_y34'].Fill(n_hits_y34)
            h['n_hits_reco_stereo34'].Fill(n_hits_stereo34)
            h['n_hits_reco_34'].Fill(n_hits_34)
            h['n_hits_reco'].Fill(n_hits_tot)
            
            h['n_hits_y12'].Fill(p, n_hits_y12)
            h['n_hits_stereo12'].Fill(p, n_hits_stereo12)
            h['n_hits_12'].Fill(p, n_hits_12)
            h['n_hits_y34'].Fill(p, n_hits_y34)
            h['n_hits_stereo34'].Fill(p, n_hits_stereo34)
            h['n_hits_34'].Fill(p, n_hits_34)
            h['n_hits_total'].Fill(p, n_hits_tot)
            
            h['frac_y12'].Fill(p, frac_y12)
            h['frac_stereo12'].Fill(p, frac_stereo12)
            h['frac_12'].Fill(p, frac_12)
            h['frac_y34'].Fill(p, frac_y34)
            h['frac_stereo34'].Fill(p, frac_stereo34)
            h['frac_34'].Fill(p, frac_34)
            h['frac_total'].Fill(p, frac_tot)
            
            # Fitted track
            
            thetrack = sTree.FitTracks[i_track]
            
            fitStatus   = thetrack.getFitStatus()
            thetrack.prune("CFL") # http://sourceforge.net/p/genfit/code/HEAD/tree/trunk/core/include/Track.h#l280

            nmeas = fitStatus.getNdf()
            pval = fitStatus.getPVal()
            chi2 = fitStatus.getChi2() / nmeas
            
            metrics['fitted_pval'] += [pval]
            metrics['fitted_chi'] += [chi2]

            h['chi2fittedtracks'].Fill(chi2)
            h['pvalfittedtracks'].Fill(pval)

            fittedState = thetrack.getFittedState()
            fittedMom = fittedState.getMomMag()
            fittedMom = fittedMom #*int(charge)
            
            metrics['fitted_p'] += [fittedMom]
            perr = (p - fittedMom) / p
            h['ptrue-p/ptrue'].Fill(perr)
            h['perr'].Fill(p, perr)
            h['perr_direction'].Fill(numpy.rad2deg(theta), perr)

            if math.fabs(p) > 0.0 :
                h['pvspfitted'].Fill(p, fittedMom)
            fittedtrackDir = fittedState.getDir()
            fittedx=math.degrees(math.acos(fittedtrackDir[0]))
            fittedy=math.degrees(math.acos(fittedtrackDir[1]))
            fittedz=math.degrees(math.acos(fittedtrackDir[2]))
            fittedmass = fittedState.getMass()
            h['momentumfittedtracks'].Fill(fittedMom)
            h['xdirectionfittedtracks'].Fill(fittedx)
            h['ydirectionfittedtracks'].Fill(fittedy)
            h['zdirectionfittedtracks'].Fill(fittedz)
            h['massfittedtracks'].Fill(fittedmass)
            
            metrics['fitted_x'] += [fittedx]
            metrics['fitted_y'] += [fittedy]
            metrics['fitted_z'] += [fittedz]
            metrics['fitted_mass'] += [fittedmass]
            
    ############################################# Save hists #########################################################
    
    save_hists(h, output_file)

    return metrics
        ecalGeoFile = "ecal_ellipse5x10m2.geo"  #doesnt do this
    print 'found ecal geo for ', ecalGeoFile
    # re-create geometry and mag. field
    if not dy:
        # try to extract from input file name
        tmp = inputFile.split('.')  #doesnt do this
        try:
            dy = float(tmp[1] + '.' + tmp[2])  #doesnt do this
        except:
            dy = 10.  #doesnt do this
    ShipGeo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py",
                                    Yheight=dy,
                                    EcalGeoFile=ecalGeoFile)
else:  #does this
    # new geofile, load Shipgeo dictionary written by run_simScript.py
    upkl = Unpickler(fgeo)
    ShipGeo = upkl.load('ShipGeo')  #load is def in def Unpickler
    ecalGeoFile = ShipGeo.ecal.File
    dy = ShipGeo.Yheight / u.m

# CREATE GEOMETRY
run = ROOT.FairRunSim()
modules = shipDet_conf.configure(run, ShipGeo)

gMan = ROOT.gGeoManager
geoMat = ROOT.genfit.TGeoMaterialInterface()
ROOT.genfit.MaterialEffects.getInstance().init(geoMat)
volDict = {}
i = 0

for x in ROOT.gGeoManager.GetListOfVolumes():
Exemple #11
0
def run_track_pattern_recognition(input_file, geo_file, dy, reconstructiblerequired, threeprong):


    ############################################# Load SHiP geometry ###################################################

    # Check geo file
    try:
        fgeo = ROOT.TFile(geo_file)
    except:
        print "An error with opening the ship geo file."
        raise

    sGeo = fgeo.FAIRGeom

    # Prepare ShipGeo dictionary
    if not fgeo.FindKey('ShipGeo'):

        if sGeo.GetVolume('EcalModule3') :
            ecalGeoFile = "ecal_ellipse6x12m2.geo"
        else:
            ecalGeoFile = "ecal_ellipse5x10m2.geo"

        if dy:
            ShipGeo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight = dy, EcalGeoFile = ecalGeoFile)
        else:
            ShipGeo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", EcalGeoFile = ecalGeoFile)

    else:
        upkl    = Unpickler(fgeo)
        ShipGeo = upkl.load('ShipGeo')

    ############################################# Load SHiP modules ####################################################

    run = ROOT.FairRunSim()
    modules = shipDet_conf.configure(run,ShipGeo)

    ############################################# Load inpur data file #################################################

    # Check input file
    try:
        fn = ROOT.TFile(input_file,'update')
    except:
        print "An error with opening the input data file."
        raise

    sTree = fn.cbmsim

    ############################## Initialize SHiP Spectrometer Tracker geometry #######################################

    zlayer, \
    zlayerv2, \
    z34layer, \
    z34layerv2, \
    TStation1StartZ, \
    TStation4EndZ, \
    VetoStationZ, \
    VetoStationEndZ = initialize(fgeo, ShipGeo)


    ########################################## Start Track Pattern Recognition #########################################

    # Init book of hists for the quality measurements
    h = init_book_hist()

    # Start event loop
    nEvents   = sTree.GetEntries()

    for iEvent in range(nEvents):

        if iEvent%10 == 0:
            print 'Event ', iEvent

        ########################################### Select one event ###################################################

        rc = sTree.GetEvent(iEvent)

        ########################################### Smear hits #########################################################

        smeared_hits = smearHits(sTree, ShipGeo, modules, no_amb=None)

        if len(smeared_hits) == 0:
            continue

        ########################################### Do track pattern recognition #######################################

        reco_tracks, theTracks  = execute(smeared_hits, sTree, ShipGeo)

        ########################################### Get MC truth #######################################################

        y = get_track_ids(sTree, smeared_hits)

        fittedtrackids, fittedtrackfrac = get_fitted_trackids(y, reco_tracks)

        reco_mc_tracks = getReconstructibleTracks(iEvent,
                                                  sTree,
                                                  sGeo,
                                                  reconstructiblerequired,
                                                  threeprong,
                                                  TStation1StartZ,
                                                  TStation4EndZ,
                                                  VetoStationZ,
                                                  VetoStationEndZ) # TODO:!!!

        ########################################### Measure quality metrics ############################################

        quality_metrics(smeared_hits, sTree, reco_mc_tracks, reco_tracks, h)


    ############################################### Save results #######################################################

    save_hists(h, 'hists.root')


    return
Exemple #12
0
    # outfile should be in local directory
    tmp = outFile.split('/')
    outFile = tmp[len(tmp) - 1]
    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', '')

fgeo = ROOT.TFile.Open(geoFile)
#fgeo = ROOT.TFile(geoFile)
from ShipGeoConfig import ConfigRegistry
from rootpyPickler import Unpickler
#load Shipgeo dictionary
upkl = Unpickler(fgeo)
#ShipGeo = upkl.load('ShipGeo')
ShipGeo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/charm-geometry_config.py",
                                Yheight=dy)

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 measurements', 100, 0., 50.)
    ut.bookHist(h, 'chi2', 'Chi2/DOF', 100, 0., 20.)
    ut.bookHist(h, 'p-fittedtracks', 'p of fitted tracks', 40, 0., 400.)
    ut.bookHist(h, '1/p-fittedtracks', '1/p of fitted tracks', 120, -0.2, 1.)
    ut.bookHist(h, 'pt-fittedtracks', 'pt of fitted tracks', 100, 0., 10.)
def run_track_pattern_recognition(input_file, geo_file, output_file, method):
    """
    Runs all steps of track pattern recognition.
    Parameters
    ----------
    input_file : string
        Path to an input .root file with events.
    geo_file : string
        Path to a file with SHiP geometry.
    output_file : string
        Path to an output .root file with quality plots.
    method : string
        Name of a track pattern recognition method.
    """


    ############################################# Load SHiP geometry ###################################################

    # Check geo file
    try:
        fgeo = ROOT.TFile(geo_file)
    except:
        print "An error with opening the ship geo file."
        raise

    sGeo = fgeo.FAIRGeom

    # Prepare ShipGeo dictionary
    if not fgeo.FindKey('ShipGeo'):

        if sGeo.GetVolume('EcalModule3') :
            ecalGeoFile = "ecal_ellipse6x12m2.geo"
        else:
            ecalGeoFile = "ecal_ellipse5x10m2.geo"

        if dy:
            ShipGeo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight = dy, EcalGeoFile = ecalGeoFile)
        else:
            ShipGeo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", EcalGeoFile = ecalGeoFile)

    else:
        upkl    = Unpickler(fgeo)
        ShipGeo = upkl.load('ShipGeo')
    
    # Globals
    builtin.ShipGeo = ShipGeo

    ############################################# Load SHiP modules ####################################################

    import shipDet_conf
    run = ROOT.FairRunSim()
    run.SetName("TGeant4")  # Transport engine
    run.SetOutputFile("dummy")  # Output file
    run.SetUserConfig("g4Config_basic.C") # geant4 transport not used, only needed for the mag field
    rtdb = run.GetRuntimeDb()

    modules = shipDet_conf.configure(run,ShipGeo)
    run.Init()

    #run = ROOT.FairRunSim()
    #modules = shipDet_conf.configure(run,ShipGeo)


    ######################################### Load SHiP magnetic field #################################################


    import geomGeant4
    if hasattr(ShipGeo.Bfield,"fieldMap"):
      fieldMaker = geomGeant4.addVMCFields(ShipGeo, '', True, withVirtualMC = False)
    else:
      print "no fieldmap given, geofile too old, not anymore support"
      exit(-1)
    sGeo   = fgeo.FAIRGeom
    geoMat =  ROOT.genfit.TGeoMaterialInterface()
    ROOT.genfit.MaterialEffects.getInstance().init(geoMat)
    bfield = ROOT.genfit.FairShipFields()
    bfield.setField(fieldMaker.getGlobalField())
    fM = ROOT.genfit.FieldManager.getInstance()
    fM.init(bfield)


    ############################################# Load inpur data file #################################################

    # Check input file
    try:
        fn = ROOT.TFile(input_file,'update')
    except:
        print "An error with opening the input data file."
        raise

    sTree = fn.cbmsim
    sTree.Write()
    
    ############################################# Create hists #########################################################
    
    h = init_book_hist()

    ########################################## Start Track Pattern Recognition #########################################
    import shipPatRec

    # Init book of hists for the quality measurements
    metrics = {'n_hits': [], 
               'reconstructible': 0, 
               'passed_y12': 0, 'passed_stereo12': 0, 'passed_12': 0, 
               'passed_y34': 0, 'passed_stereo34': 0, 'passed_34': 0, 
               'passed_combined': 0, 'reco_passed': 0, 'reco_passed_no_clones': 0,
               'frac_y12': [], 'frac_stereo12': [], 'frac_12': [], 
               'frac_y34': [], 'frac_stereo34': [], 'frac_34': [], 
               'reco_frac_tot': [], 
               'reco_mc_p': [], 'reco_mc_theta': [], 
               'fitted_p': [], 'fitted_pval': [], 'fitted_chi': [], 
               'fitted_x': [], 'fitted_y': [], 'fitted_z': [], 'fitted_mass': []}

    # Start event loop
    nEvents   = sTree.GetEntries()
   

    for iEvent in range(nEvents):

        if iEvent%1000 == 0:
            print 'Event ', iEvent

        ########################################### Select one event ###################################################

        rc = sTree.GetEvent(iEvent)

        ########################################### Reconstructible tracks #############################################

        reconstructible_tracks = getReconstructibleTracks(iEvent, sTree, sGeo, ShipGeo)
        
        metrics['reconstructible'] += len(reconstructible_tracks)
        for i_reco in reconstructible_tracks:
            h['TracksPassed'].Fill("Reconstructible tracks", 1)
            h['TracksPassedU'].Fill("Reconstructible tracks", 1)
            
        in_y12 = []
        in_stereo12 = []
        in_12 = []
        in_y34 = []
        in_stereo34 = []
        in_34 = []
        in_combo = []

        found_track_ids = []
        n_tracks = len(reconstructible_tracks)
        n_recognized = 0
        n_clones = 0
        n_ghosts = 0
        n_others = 0

        min_eff = 0.
        
        ########################################## Recognized tracks ###################################################
        
        nTracklets = sTree.Tracklets.GetEntriesFast()
        
        for i_track in range(nTracklets):
            
            atracklet = sTree.Tracklets[i_track]
            
            if atracklet.getType() != 1: # this is a not full track (tracklet)
                continue
                
            atrack = atracklet.getList()
            
            if atrack.size() == 0:
                continue
            
            hits = {'X': [], 'Y': [], 'Z': [], 
                    'DetID': [], 'TrackID': [], 
                    'Pz': [], 'Px': [], 'Py': [], 
                    'dist2Wire': [], 'Pdg': []}
            
            for ihit in atrack:
                ahit = sTree.strawtubesPoint[ihit]
                hits['X'] += [ahit.GetX()]
                hits['Y'] += [ahit.GetY()]
                hits['Z'] += [ahit.GetZ()]
                hits['DetID'] += [ahit.GetDetectorID()]
                hits['TrackID'] += [ahit.GetTrackID()]
                hits['Pz'] += [ahit.GetPz()]
                hits['Px'] += [ahit.GetPx()]
                hits['Py'] += [ahit.GetPy()]
                hits['dist2Wire'] += [ahit.dist2Wire()]
                hits['Pdg'] += [ahit.PdgCode()]
                
            # List to numpy arrays
            for key in hits.keys():
                hits[key] = numpy.array(hits[key])
                
            # Decoding
            statnb, vnb, pnb, lnb, snb = decodeDetectorID(hits['DetID'])
            is_stereo = ((vnb == 1) + (vnb == 2))
            is_y = ((vnb == 0) + (vnb == 3))
            is_before = ((statnb == 1) + (statnb == 2))
            is_after = ((statnb == 3) + (statnb == 4)) 
                
            
            # Metrics
            metrics['n_hits'] += [get_n_hits(hits['TrackID'])]
            
            # Tracks passed
            frac_y12, tmax_y12 = fracMCsame(hits['TrackID'][is_before * is_y])
            n_hits_y12 = get_n_hits(hits['TrackID'][is_before * is_y])
            frac_stereo12, tmax_stereo12 = fracMCsame(hits['TrackID'][is_before * is_stereo])
            n_hits_stereo12 = get_n_hits(hits['TrackID'][is_before * is_stereo])
            frac_12, tmax_12 = fracMCsame(hits['TrackID'][is_before])
            n_hits_12 = get_n_hits(hits['TrackID'][is_before])
            
            frac_y34, tmax_y34 = fracMCsame(hits['TrackID'][is_after * is_y])
            n_hits_y34 = get_n_hits(hits['TrackID'][is_after * is_y])
            frac_stereo34, tmax_stereo34 = fracMCsame(hits['TrackID'][is_after * is_stereo])
            n_hits_stereo34 = get_n_hits(hits['TrackID'][is_after * is_stereo])
            frac_34, tmax_34 = fracMCsame(hits['TrackID'][is_after])
            n_hits_34 = get_n_hits(hits['TrackID'][is_after])
            frac_tot, tmax_tot = fracMCsame(hits['TrackID'])
            n_hits_tot = get_n_hits(hits['TrackID'])

            if tmax_y12 == tmax_stereo12 and tmax_y12 == tmax_y34 and tmax_y12 == tmax_stereo34:
                if frac_y12 >= min_eff and frac_stereo12 >= min_eff and frac_y34 >= min_eff and frac_stereo34 >= min_eff:

                    if tmax_y12 in reconstructible_tracks and tmax_y12 not in found_track_ids:
                        n_recognized += 1
                        found_track_ids.append(tmax_y12)
                    elif tmax_y12 in reconstructible_tracks and tmax_y12 in found_track_ids:
                        n_clones += 1
                    elif tmax_y12 not in reconstructible_tracks:
                        n_others += 1

                else:
                    n_ghosts += 1
            else:
                n_ghosts += 1
            
            is_reconstructed = 0
            is_reconstructed_no_clones = 0
            
            
            if tmax_y12 in reconstructible_tracks:
                metrics['passed_y12'] += 1
                metrics['frac_y12'] += [frac_y12]
                h['TracksPassed'].Fill("Y view station 1&2", 1)
                if tmax_y12 not in in_y12:
                    h['TracksPassedU'].Fill("Y view station 1&2", 1)
                    in_y12.append(tmax_y12)
                
                if tmax_stereo12 == tmax_y12:
                    metrics['passed_stereo12'] += 1
                    metrics['frac_stereo12'] += [frac_stereo12]
                    h['TracksPassed'].Fill("Stereo station 1&2", 1)
                    if tmax_stereo12 not in in_stereo12:
                        h['TracksPassedU'].Fill("Stereo station 1&2", 1)
                        in_stereo12.append(tmax_stereo12)
                    
                    if tmax_12 == tmax_y12:
                        metrics['passed_12'] += 1
                        metrics['frac_12'] += [frac_12]
                        h['TracksPassed'].Fill("station 1&2", 1)
                        if tmax_12 not in in_12:
                            h['TracksPassedU'].Fill("station 1&2", 1)
                            in_12.append(tmax_12)
                        
                        if tmax_y34 in reconstructible_tracks:
                            metrics['passed_y34'] += 1
                            metrics['frac_y34'] += [frac_y34]
                            h['TracksPassed'].Fill("Y view station 3&4", 1)
                            if tmax_y34 not in in_y34:
                                h['TracksPassedU'].Fill("Y view station 3&4", 1)
                                in_y34.append(tmax_y34)
                            
                            if tmax_stereo34 == tmax_y34:
                                metrics['passed_stereo34'] += 1
                                metrics['frac_stereo34'] += [frac_stereo34]
                                h['TracksPassed'].Fill("Stereo station 3&4", 1)
                                if tmax_stereo34 not in in_stereo34:
                                    h['TracksPassedU'].Fill("Stereo station 3&4", 1)
                                    in_stereo34.append(tmax_stereo34)
                                
                                if tmax_34 == tmax_y34:
                                    metrics['passed_34'] += 1
                                    metrics['frac_34'] += [frac_34]
                                    h['TracksPassed'].Fill("station 3&4", 1)
                                    if tmax_34 not in in_34:
                                        h['TracksPassedU'].Fill("station 3&4", 1)
                                        in_34.append(tmax_34)
                                    
                                    if tmax_12 == tmax_34:
                                        metrics['passed_combined'] += 1
                                        h['TracksPassed'].Fill("Combined stations 1&2/3&4", 1)
                                        metrics['reco_passed'] += 1
                                        is_reconstructed = 1
                                        if tmax_34 not in in_combo:
                                            h['TracksPassedU'].Fill("Combined stations 1&2/3&4", 1)
                                            metrics['reco_passed_no_clones'] += 1
                                            in_combo.append(tmax_34)
                                            is_reconstructed_no_clones = 1
                                        
            # For reconstructed tracks
            if is_reconstructed == 0:
                continue

            metrics['reco_frac_tot'] += [frac_tot]
            
            # Momentum
            Pz = hits['Pz']
            Px = hits['Px']
            Py = hits['Py']

            p, px, py, pz = getPtruthFirst(sTree, tmax_tot)
            pt = math.sqrt(px**2 + py**2)

            Z_true = []
            X_true = []
            Y_true = []
            for ahit in sTree.strawtubesPoint:
                if ahit.GetTrackID() == tmax_tot:
                    az, ax, ay = ahit.GetZ(),ahit.GetX(),ahit.GetY()
                    Z_true.append(az)
                    X_true.append(ax)
                    Y_true.append(ay)

            
            metrics['reco_mc_p'] += [p]
            h['TracksPassed_p'].Fill(p, 1)
            
            # Direction
            Z = hits['Z'][(hits['TrackID'] == tmax_tot) * is_before]
            X = hits['X'][(hits['TrackID'] == tmax_tot) * is_before]
            Y = hits['Y'][(hits['TrackID'] == tmax_tot) * is_before]
            Z = Z - Z[0]
            X = X - X[0]
            Y = Y - Y[0]
            R = numpy.sqrt(X**2 + Y**2 + Z**2)
            Theta = numpy.arccos(Z[1:] / R[1:])
            theta = numpy.mean(Theta)
            
            metrics['reco_mc_theta'] += [theta]
            
            h['n_hits_reco_y12'].Fill(n_hits_y12)
            h['n_hits_reco_stereo12'].Fill(n_hits_stereo12)
            h['n_hits_reco_12'].Fill(n_hits_12)
            h['n_hits_reco_y34'].Fill(n_hits_y34)
            h['n_hits_reco_stereo34'].Fill(n_hits_stereo34)
            h['n_hits_reco_34'].Fill(n_hits_34)
            h['n_hits_reco'].Fill(n_hits_tot)
            
            h['n_hits_y12'].Fill(p, n_hits_y12)
            h['n_hits_stereo12'].Fill(p, n_hits_stereo12)
            h['n_hits_12'].Fill(p, n_hits_12)
            h['n_hits_y34'].Fill(p, n_hits_y34)
            h['n_hits_stereo34'].Fill(p, n_hits_stereo34)
            h['n_hits_34'].Fill(p, n_hits_34)
            h['n_hits_total'].Fill(p, n_hits_tot)
            
            h['frac_y12'].Fill(p, frac_y12)
            h['frac_stereo12'].Fill(p, frac_stereo12)
            h['frac_12'].Fill(p, frac_12)
            h['frac_y34'].Fill(p, frac_y34)
            h['frac_stereo34'].Fill(p, frac_stereo34)
            h['frac_34'].Fill(p, frac_34)
            h['frac_total'].Fill(p, frac_tot)

            h['frac_y12_dist'].Fill(frac_y12)
            h['frac_stereo12_dist'].Fill(frac_stereo12)
            h['frac_12_dist'].Fill(frac_12)
            h['frac_y34_dist'].Fill(frac_y34)
            h['frac_stereo34_dist'].Fill(frac_stereo34)
            h['frac_34_dist'].Fill(frac_34)
            h['frac_total_dist'].Fill(frac_tot)
            
            # Fitted track
            
            thetrack = sTree.FitTracks[i_track]
            
            fitStatus   = thetrack.getFitStatus()
            thetrack.prune("CFL") # http://sourceforge.net/p/genfit/code/HEAD/tree/trunk/core/include/Track.h#l280

            nmeas = fitStatus.getNdf()
            pval = fitStatus.getPVal()
            chi2 = fitStatus.getChi2() / nmeas
            
            metrics['fitted_pval'] += [pval]
            metrics['fitted_chi'] += [chi2]

            h['chi2fittedtracks'].Fill(chi2)
            h['pvalfittedtracks'].Fill(pval)


            try:

                fittedState = thetrack.getFittedState()
                fittedMom = fittedState.getMomMag()
                fittedMom = fittedMom #*int(charge)

                px_fit,py_fit,pz_fit = fittedState.getMom().x(),fittedState.getMom().y(),fittedState.getMom().z()
                p_fit = fittedMom
                pt_fit = math.sqrt(px_fit**2 + py_fit**2)


                metrics['fitted_p'] += [p_fit]
                perr = (p - p_fit) / p
                h['ptrue-p/ptrue'].Fill(perr)
                h['perr'].Fill(p, perr)
                h['perr_direction'].Fill(numpy.rad2deg(theta), perr)

                pterr = (pt - pt_fit) / pt
                h['pttrue-pt/pttrue'].Fill(pterr)

                pxerr = (px - px_fit) / px
                h['pxtrue-px/pxtrue'].Fill(pxerr)

                pyerr = (py - py_fit) / py
                h['pytrue-py/pytrue'].Fill(pyerr)

                pzerr = (pz - pz_fit) / pz
                h['pztrue-pz/pztrue'].Fill(pzerr)

                if math.fabs(p) > 0.0 :
                    h['pvspfitted'].Fill(p, fittedMom)
                fittedtrackDir = fittedState.getDir()
                fittedx=math.degrees(math.acos(fittedtrackDir[0]))
                fittedy=math.degrees(math.acos(fittedtrackDir[1]))
                fittedz=math.degrees(math.acos(fittedtrackDir[2]))
                fittedmass = fittedState.getMass()
                h['momentumfittedtracks'].Fill(fittedMom)
                h['xdirectionfittedtracks'].Fill(fittedx)
                h['ydirectionfittedtracks'].Fill(fittedy)
                h['zdirectionfittedtracks'].Fill(fittedz)
                h['massfittedtracks'].Fill(fittedmass)

                metrics['fitted_x'] += [fittedx]
                metrics['fitted_y'] += [fittedy]
                metrics['fitted_z'] += [fittedz]
                metrics['fitted_mass'] += [fittedmass]


                Z_fit = []
                X_fit = []
                Y_fit = []
                for az in Z_true:
                    rc,pos,mom = extrapolateToPlane(thetrack, az)
                    Z_fit.append(pos.Z())
                    X_fit.append(pos.X())
                    Y_fit.append(pos.Y())

                for i in range(len(Z_true)):
                    xerr = abs(X_fit[i] - X_true[i])
                    yerr = abs(Y_fit[i] - Y_true[i])
                    h['abs(x - x-true)'].Fill(xerr)
                    h['abs(y - y-true)'].Fill(yerr)

                rmse_x = numpy.sqrt(numpy.mean((numpy.array(X_fit) - numpy.array(X_true))**2))
                rmse_y = numpy.sqrt(numpy.mean((numpy.array(Y_fit) - numpy.array(Y_true))**2))
                h['rmse_x'].Fill(rmse_x)
                h['rmse_y'].Fill(rmse_y)



            except:
                print "Problem with fitted state."


        h['Reco_tracks'].Fill("N total", n_tracks)
        h['Reco_tracks'].Fill("N recognized tracks", n_recognized)
        h['Reco_tracks'].Fill("N clones", n_clones)
        h['Reco_tracks'].Fill("N ghosts", n_ghosts)
        h['Reco_tracks'].Fill("N others", n_others)
            
    ############################################# Save hists #########################################################
    
    save_hists(h, output_file)

    return metrics
Exemple #14
0
  eospath = "root://eoslhcb.cern.ch/"+geoFile
  fgeo = ROOT.TFile.Open(eospath)
else:  
  fgeo = ROOT.TFile(geoFile)
sGeo = fgeo.FAIRGeom

if not fgeo.FindKey('ShipGeo'):
 # old geofile, missing Shipgeo dictionary
 if sGeo.GetVolume('EcalModule3') :  ecalGeoFile = "ecal_ellipse6x12m2.geo"
 else: ecalGeoFile = "ecal_ellipse5x10m2.geo" 
 print 'found ecal geo for ',ecalGeoFile
 # re-create geometry and mag. field
 ShipGeo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight = dy, EcalGeoFile = ecalGeoFile )
else: 
 # new geofile, load Shipgeo dictionary written by run_simScript.py
  upkl    = Unpickler(fgeo)
  ShipGeo = upkl.load('ShipGeo')
  ecalGeoFile = ShipGeo.ecal.File

# -----Create geometry----------------------------------------------
import shipDet_conf
run = ROOT.FairRunSim()
modules = shipDet_conf.configure(run,ShipGeo)

gMan  = ROOT.gGeoManager
geoMat =  ROOT.genfit.TGeoMaterialInterface()
ROOT.genfit.MaterialEffects.getInstance().init(geoMat)
volDict = {}
i=0
for x in ROOT.gGeoManager.GetListOfVolumes():
 volDict[i]=x.GetName()
Exemple #15
0
def run_checking(input_file, geo_file, dy, reconstructiblerequired,
                 threeprong):

    ############################################# Load SHiP geometry ###################################################

    # Check geo file
    try:
        fgeo = ROOT.TFile(geo_file)
    except:
        print "An error with opening the ship geo file."
        raise

    sGeo = fgeo.FAIRGeom

    # Prepare ShipGeo dictionary
    if not fgeo.FindKey('ShipGeo'):

        if sGeo.GetVolume('EcalModule3'):
            ecalGeoFile = "ecal_ellipse6x12m2.geo"
        else:
            ecalGeoFile = "ecal_ellipse5x10m2.geo"

        if dy:
            ShipGeo = ConfigRegistry.loadpy(
                "$FAIRSHIP/geometry/geometry_config.py",
                Yheight=dy,
                EcalGeoFile=ecalGeoFile)
        else:
            ShipGeo = ConfigRegistry.loadpy(
                "$FAIRSHIP/geometry/geometry_config.py",
                EcalGeoFile=ecalGeoFile)

    else:
        upkl = Unpickler(fgeo)
        ShipGeo = upkl.load('ShipGeo')

    ############################################# Load SHiP modules ####################################################

    run = ROOT.FairRunSim()
    modules = shipDet_conf.configure(run, ShipGeo)

    ############################################# Load input data file #################################################

    # Check input file
    try:
        fn = ROOT.TFile(input_file, 'update')
    except:
        print "An error with opening the input data file."
        raise

    sTree = fn.cbmsim

    ############################## Initialize SHiP Spectrometer Tracker geometry #######################################

    #zlayer, \
    #zlayerv2, \
    #z34layer, \
    #z34layerv2, \
    #TStation1StartZ, \
    #TStation4EndZ, \
    #VetoStationZ, \
    #VetoStationEndZ = initialize(fgeo, ShipGeo)

    ########################################## Start Checking Geometry #################################################

    all_hits = pandas.DataFrame(
        columns=['event_id', 'det_id', 'xtop', 'ytop', 'z', 'xbot', 'ybot'])
    all_hits_i = 0

    # Start event loop
    nEvents = sTree.GetEntries()

    for iEvent in range(nEvents):

        if iEvent % 100 == 0:
            print 'Event ', iEvent

        ########################################### Select one event ###################################################

        rc = sTree.GetEvent(iEvent)

        ############################################# Get hits #########################################################

        nHits = sTree.strawtubesPoint.GetEntriesFast()
        key = -1

        for i in range(nHits):

            ahit = sTree.strawtubesPoint[i]

            key += 1
            detID = ahit.GetDetectorID()
            top = ROOT.TVector3()
            bot = ROOT.TVector3()

            modules["Strawtubes"].StrawEndPoints(detID, bot, top)

            all_hits.loc[all_hits_i] = [
                iEvent, detID,
                top.x(),
                top.y(),
                top.z(),
                bot.x(),
                bot.y()
            ]
            all_hits_i += 1

    all_hits.to_csv('hits.csv', index=False)
    all_hits['StatNb'] = all_hits['det_id'] // 10000000
    all_hits['ViewNb'] = (all_hits['det_id'] -
                          all_hits['StatNb'] * 10000000) // 1000000
    all_hits['PlaneNb'] = (all_hits['det_id'] - all_hits['StatNb'] * 10000000 -
                           all_hits['ViewNb'] * 1000000) // 100000
    all_hits['LayerNb'] = (all_hits['det_id'] - all_hits['StatNb'] * 10000000 - all_hits['ViewNb'] * 1000000 -\
                           all_hits['PlaneNb'] * 100000) // 10000
    all_hits['StrawNb'] = all_hits['det_id'] - all_hits['StatNb'] * 10000000 - all_hits['ViewNb'] * 1000000 -\
                          all_hits['PlaneNb'] * 100000 - all_hits['LayerNb'] * 10000 - 2000

    dots00 = all_hits[(all_hits['StatNb'].values<3) & ((all_hits['ViewNb'].values==0) + (all_hits['ViewNb'].values==3)) &\
             (all_hits['PlaneNb'].values==0) & (all_hits['LayerNb'].values==0)]['ytop'].values
    dots00 = all_hits[(all_hits['StatNb'].values<3) & ((all_hits['ViewNb'].values==0) + (all_hits['ViewNb'].values==3)) &\
                 (all_hits['PlaneNb'].values==1) & (all_hits['LayerNb'].values==0)]['ytop'].values
    dots01 = all_hits[(all_hits['StatNb'].values<3) & ((all_hits['ViewNb'].values==0) + (all_hits['ViewNb'].values==3)) &\
                 (all_hits['PlaneNb'].values==0) & (all_hits['LayerNb'].values==1)]['ytop'].values
    dots01 = all_hits[(all_hits['StatNb'].values<3) & ((all_hits['ViewNb'].values==0) + (all_hits['ViewNb'].values==3)) &\
                 (all_hits['PlaneNb'].values==1) & (all_hits['LayerNb'].values==1)]['ytop'].values

    min_dist = np.hstack([
        np.diff(np.unique(dots00)),
        np.diff(np.unique(dots01)),
        np.diff(np.unique(dots00)),
        np.diff(np.unique(dots01))
    ]).min()

    print('Pitch: ', np.round(min_dist, 3))

    z0 = all_hits[(all_hits['StatNb']==1) & (all_hits['ViewNb']==0) & (all_hits['PlaneNb'].values==0) &\
                  (all_hits['LayerNb'].values==0)]['z'].mean()
    z1 = all_hits[(all_hits['StatNb']==1) & (all_hits['ViewNb']==0) & (all_hits['PlaneNb'].values==0) &\
                  (all_hits['LayerNb'].values==1)]['z'].mean()

    print('ZShiftLayer: ', np.round(z1 - z0, 3))

    z2 = all_hits[(all_hits['StatNb']==1) & (all_hits['ViewNb']==0) & (all_hits['PlaneNb'].values==1) &\
                  (all_hits['LayerNb'].values==0)]['z'].mean()

    print('ZShiftPlane: ', np.round(z2 - z0, 3))

    xtop = all_hits[(all_hits['StatNb']==1) & (all_hits['ViewNb']==1) & (all_hits['PlaneNb']==0) &\
                    (all_hits['LayerNb']==0)]['xtop'].values[0]
    ytop = all_hits[(all_hits['StatNb']==1) & (all_hits['ViewNb']==1) & (all_hits['PlaneNb']==0) &\
                    (all_hits['LayerNb']==0)]['ytop'].values[0]
    xbot = all_hits[(all_hits['StatNb']==1) & (all_hits['ViewNb']==1) & (all_hits['PlaneNb']==0) &\
                    (all_hits['LayerNb']==0)]['xbot'].values[0]
    ybot = all_hits[(all_hits['StatNb']==1) & (all_hits['ViewNb']==1) & (all_hits['PlaneNb']==0) &\
                    (all_hits['LayerNb']==0)]['ybot'].values[0]

    print('Angle: ',
          np.round(np.arctan((ytop - ybot) / (xtop - xbot)) * 180 / np.pi, 3))

    z0 = all_hits[(all_hits['StatNb']==1) & (all_hits['ViewNb']==0) & (all_hits['PlaneNb'].values==0) &\
            (all_hits['LayerNb'].values==0)]['z'].mean()
    z3 = all_hits[(all_hits['StatNb']==1) & (all_hits['ViewNb']==1) & (all_hits['PlaneNb'].values==0) &\
            (all_hits['LayerNb'].values==0)]['z'].mean()

    print('ZShiftView: ', np.round(z3 - z0, 3))

    dots0 = all_hits[(all_hits['StatNb'].values<3) & ((all_hits['ViewNb'].values==0) + (all_hits['ViewNb'].values==3)) &\
             (all_hits['PlaneNb'].values==0) & (all_hits['LayerNb'].values==0)]['ytop'].values
    dots1 = all_hits[(all_hits['StatNb'].values<3) & ((all_hits['ViewNb'].values==0) + (all_hits['ViewNb'].values==3)) &\
             (all_hits['PlaneNb'].values==0) & (all_hits['LayerNb'].values==1)]['ytop'].values

    min_dist = np.hstack([np.diff(np.unique(np.hstack([dots0, dots1])))]).min()

    print('YOffsetLayer: ', np.round(min_dist, 3))

    dots0 = all_hits[(all_hits['StatNb'].values<3) & ((all_hits['ViewNb'].values==0) + (all_hits['ViewNb'].values==3)) &\
             (all_hits['PlaneNb'].values==0) & (all_hits['LayerNb'].values==0)]['ytop'].values
    dots1 = all_hits[(all_hits['StatNb'].values<3) & ((all_hits['ViewNb'].values==0) + (all_hits['ViewNb'].values==3)) &\
             (all_hits['PlaneNb'].values==1) & (all_hits['LayerNb'].values==0)]['ytop'].values

    min_dist = np.hstack([np.diff(np.unique(np.hstack([dots0, dots1])))]).min()

    print('YOffsetPlane: ', np.round(min_dist, 3))

    return
Exemple #16
0
dy = None
nEvents = 9999999
fiducialCut = True
measCutFK = 25
measCutPR = 22
docaCut = 2.

eosship = ROOT.gSystem.Getenv("EOSSHIP")

# geoFile = '/afs/cern.ch/user/a/amarshal/FairSHiP_run_GAN_muons/geofile_full.conical.MuonBack-TGeant4.root'
# geoFile = '/afs/cern.ch/user/a/amarshal/FairSHiP_run_GAN_muons/geofile_full.conical.Pythia8-TGeant4.root'
geoFile = '/afs/cern.ch/user/a/amarshal/FairSHiP_run_GAN_muons/geofile.root'
fgeo = ROOT.TFile(geoFile)

# new geofile, load Shipgeo dictionary written by run_simScript.py
upkl = Unpickler(fgeo)
ShipGeo = upkl.load('ShipGeo')
ecalGeoFile = ShipGeo.ecal.File
dy = ShipGeo.Yheight / u.m

# -----Create geometry----------------------------------------------
import shipDet_conf
run = ROOT.FairRunSim()
run.SetName("TGeant4")  # Transport engine
run.SetOutputFile("dummy")  # Output file
run.SetUserConfig("g4Config_basic.C"
                  )  # geant4 transport not used, only needed for the mag field
rtdb = run.GetRuntimeDb()
# -----Create geometry----------------------------------------------
print('a')
modules = shipDet_conf.configure(run, ShipGeo)
Exemple #17
0
import ROOT, sys
from rootpyPickler import Unpickler

badBoys = {}
f1, f2 = sys.argv[1], sys.argv[2]
fgeoOld = ROOT.TFile(f1)
upkl = Unpickler(fgeoOld)
ShipGeoOld = upkl.load("ShipGeo")
fgeoNew = ROOT.TFile(f2)
upkl = Unpickler(fgeoNew)
ShipGeoNew = upkl.load("ShipGeo")
for x in ShipGeoNew:
    if hasattr(eval("ShipGeoNew." + x), "z"):
        zold, znew = eval("ShipGeoOld." + x + ".z"), eval("ShipGeoNew." + x + ".z")
        print x, "z=", znew, " old:", zold
        if zold != znew:
            badBoys[x] = [znew, zold]
if len(badBoys) > 0:
    print "following differences detected:"
for x in badBoys:
    print x, badBoys[x]