Beispiel #1
0
    def get_root_entries(self, filename, n_entries):
        import ROOT
        import rat
        try:
            # check standard root files
            if rat.dsreader(filename):
                for ds, run in rat.dsreader(filename):
                    if n_entries == run.GetNumberOfEventsSimulated(run):
                        break # assume simulations only do one run
                    else:
                        raise CheckRootException("Number of events simulated is incorrect")

            #check soc files
            elif rat.socreader(filename):
                for soc, run in rat.socreader(filename):
                    if n_entries == run.GetNumberOfEventsSimulated(run):
                        break # assume simulations only do one run
                    else:
                        raise CheckRootException("Number of events simulated is incorrect")
            #check ntuples
            else:
                tf = ROOT.TFile(filename)
                tt = tf.Get("output")

                # check entries in TTrees
                if n_entries == tt.GetEntries():
                    pass
                else:
                    raise CheckRootException("Number of events simulated is incorrect")            
        except Exception as e:
            raise CheckRootException("Cannot get TTree: %s" % e)
Beispiel #2
0
    def get_root_entries(self, filename, n_entries):
        import ROOT
        import rat
        try:
            # check standard root files
            if rat.dsreader(filename):
                for ds, run in rat.dsreader(filename):
                    if n_entries == run.GetNumberOfEventsSimulated(run):
                        break  # assume simulations only do one run
                    else:
                        raise CheckRootException(
                            "Number of events simulated is incorrect")

            #check soc files
            elif rat.socreader(filename):
                for soc, run in rat.socreader(filename):
                    if n_entries == run.GetNumberOfEventsSimulated(run):
                        break  # assume simulations only do one run
                    else:
                        raise CheckRootException(
                            "Number of events simulated is incorrect")
            #check ntuples
            else:
                tf = ROOT.TFile(filename)
                tt = tf.Get("output")

                # check entries in TTrees
                if n_entries == tt.GetEntries():
                    pass
                else:
                    raise CheckRootException(
                        "Number of events simulated is incorrect")
        except Exception as e:
            raise CheckRootException("Cannot get TTree: %s" % e)
Beispiel #3
0
def GetEnergyWindow():
    Histogram = ROOT.TH1D("recoEnergy", "recoEnergy", 100, 0.0, 5.0)

    for ds, run in rat.dsreader(infileName):
        if ds.GetEVCount() == 0:
            continue
        ev = ds.GetEV(0)

        if not ev.FitResultExists("scintFitter"):
            continue
        if not ev.GetFitResult("scintFitter").GetValid():
            continue
        if not ev.GetFitResult("scintFitter").GetVertex(0).ContainsPosition():
            continue
        vertPos = ev.GetFitResult("scintFitter").GetVertex(0).GetPosition()

        if (vertPos.Mag() < fidVolLow) or (vertPos.Mag() >= fidVolHigh):
            continue
        vertEnergy = ev.GetFitResult("scintFitter").GetVertex(0).GetEnergy()
        Histogram.Fill(vertEnergy)

    gaussFit = ROOT.TF1("gaus", "gaus", 0.0, 5.0)
    Histogram.Fit(gaussFit, "RQ")
    lowEnergy = gaussFit.GetParameter(1) - gaussFit.GetParameter(2)
    highEnergy = gaussFit.GetParameter(1) + gaussFit.GetParameter(2)

    energyWindow = [lowEnergy, highEnergy]

    print "\n"
    print "Energy Window (mean reco.energy +/- 1 sigma): " + str(
        lowEnergy) + "MeV to " + str(highEnergy) + "MeV"
    print "\n"

    return energyWindow
Beispiel #4
0
def get_PMT_hits_cone(fname, fibre_pos, max_angle, flag=5241):
    """Find how many times PMTs in a cone surrounding the light injection
    vector were hit during a run.

    :param fname: Name of a .root data file containing the run data.
    :param fibre_pos: Vector of fibre injection position, relative to the centre of the psup.
    :param max_angle: The angle of the cone to be projected. 
    :return pmt_hits: Dictionary containing number of hits at PMTs activated during run.
    """
    pmt_hits = {}
    pmtInfo = rat.utility().GetPMTInfo()
    for ds, run in rat.dsreader(fname):
        for iEV in range(ds.GetEVCount()):
            ev = ds.GetEV(iEV)
            if (ev.GetTrigType() != 32768):
                continue
            unCal_pmts = ev.GetUncalPMTs()
            for pmt in range(unCal_pmts.GetNormalCount()):
                uncal = unCal_pmts.GetPMT(pmt)
                pmtID = unCal_pmts.GetNormalPMT(pmt).GetID()
                pmt_pos = pmtInfo.GetPosition(pmtID)
                fibre_vec = ROOT.TVector3(fibre_pos.GetD("x"),
                                          fibre_pos.GetD("y"),
                                          fibre_pos.GetD("z"))
                fibre_to_pmt = -pmt_pos + fibre_vec
                angle = fibre_to_pmt.Angle(fibre_vec) * (180 / np.pi)
                lcn = uncal.GetID()
                if angle <= max_angle:
                    if lcn != flag:
                        if lcn not in pmt_hits:
                            pmt_hits[lcn] = 1.
                        else:
                            pmt_hits[lcn] += 1.
    return pmt_hits
def getPEcharge(filename):
    '''
    Obtain information on the PEs produced. Returns arrays with:
    - charge per event
    - charge per PMT
    - number of PEs per PMT
    - tracks that contribute to each PE
    '''
    charge = []
    tracks = []
    pexpmt = []
    charge_perev = []
    ratreader = rat.dsreader(filename)
    for ds, run in ratreader:
        mymc = ds.GetMC()
        # Per event
        charge_perev.append(0)
        for pmt_index in range(mymc.GetMCPMTCount()):
            # Per PMT
            mypmt = mymc.GetMCPMT(pmt_index)
            pexpmt.append(mypmt.GetMCPECount())
            for pe_index in range(pexpmt[-1]):
                this_charge = mypmt.GetMCPE(pe_index).GetCharge()
                charge_perev[-1] += this_charge
                charge.append(this_charge)
                try:
                    tracks.append(
                        np.size(mypmt.GetMCPE(pe_index).GetPhotonTrackID()))
                except:
                    # Photoelectron is noise
                    None

    return np.array(charge_perev), np.array(charge), np.array(
        pexpmt), np.array(tracks)
Beispiel #6
0
def plot_edep_step(file_name):
    """ Plot the energy deposited for neutron capture track steps.
    see RAT/include/MCTrackStep.hh for other possible track step processes

    :param file_name: Path to the RAT root file to plot.
    :return: The histogram plot
    """
    process = "nCapture"

    h_edep_step = ROOT.TH1D("hEdepStep", "Energy deposited", 500, 0, 5)
    for ds, run in rat.dsreader(file_name):
        for iev in range(0, ds.GetEVCount()):
            ev = ds.GetEV(iev)
            mc = ds.GetMC()
            for itrack in range(0, mc.GetMCTrackCount()):
                mctrack = mc.GetMCTrack(itrack)
                for istep in range(0, mctrack.GetMCTrackStepCount()):
                    mctrackstep = mctrack.GetMCTrackStep(istep)
                    #note: it is possible to get processes either by name (string) or by enum.
                    if mctrackstep.GetProcess() == process:
                        h_edep_step.Fill(mctrackstep.GetDepositedEnergy())
    h_edep_step.SetXTitle("Energy deposited (MeV)")
    h_edep_step.SetYTitle("Counts per 10 keV")
    h_edep_step.Draw()
    return h_edep_step
def getHitRegions(filename):
    hits_list = []
    q_list = []
    ratreader = rat.dsreader(filename)
    for ds, run in ratreader:
        for iEv in range(ds.GetMCEVCount()):
            mcev = ds.GetMCEV(iEv)
            hits = mcev.GetMCHits()
            hits_list.append([0, 0, 0])
            q_list.append([0, 0, 0])
            for iHit in range(hits.GetAllCount()):
                pmt = hits.GetAllPMT(iHit)
                pmtz = pmtinfo.GetPosition(pmt.GetID()).z()
                # print pmtinfo.GetType(pmt)
                # Top
                if split_middle < pmtz:
                    hits_list[-1][0] += 1
                    q_list[-1][0] += pmt.GetQHS()
                # Middle
                elif -split_middle < pmtz < split_middle:
                    hits_list[-1][1] += 1
                    q_list[-1][1] += pmt.GetQHS()
                # Bottom
                else:
                    hits_list[-1][2] += 1
                    q_list[-1][2] += pmt.GetQHS()
    ratreader.close()
    return np.array(hits_list), np.array(q_list)
Beispiel #8
0
    def get_nhits_hist(self, filename):
        """Function to get the mean and standard deviation of a nhits distribution

         Args:
          filename (string) : name of input SMELLIE root file

         Returns:
          mean (float) : mean of the nhits distribution
          rms (float) : standard deviation of the nhits distribution
        """

        #define nhits histogram
        h_nhits = ROOT.TH1D("number of hits", "", 200, 0.0, 1000.0)
        #loop over file
        for ds, run in rat.dsreader(filename):
            #loop through events
            for iev in range(ds.GetEVCount()):
                ev = ds.GetEV(iev)
                #extract nhits of event
                h_nhits.Fill(ev.GetNhits())

        #get mean and standard deviation from distribution
        self.mean = h_nhits.GetMean(1)
        self.rms = h_nhits.GetRMS(1)

        return self.mean, self.rms
Beispiel #9
0
def MeanRadialBias(infileName):

    biasPlot = ROOT.TH1D("RadialBias", "RadialBias", 200, -1000.0, 1000.0)
    biasFit = ROOT.TF1("biasFit", "gaus", -1000, 1000)

    for ds, run in rat.dsreader(infileName):
        if ds.GetEVCount() == 0:
            continue

        startPosition = ds.GetMC().GetMCParticle(0).GetPosition()

        ev = ds.GetEV(0)

        if not ev.FitResultExists("positionTimeFit"):
            continue
        if not ev.GetFitResult("positionTimeFit").GetValid():
            continue

        try:
            fitPosition = ev.GetFitResult("positionTimeFit").GetVertex(
                0).GetPosition()
            radialBias = (fitPosition - startPosition).Dot(
                startPosition.Unit())

            if fitPosition.Mag() < fiducialCut:
                biasPlot.Fill(radialBias)
        except:
            pass

    biasPlot.Fit(biasFit)
    return biasFit.GetParameter(1)
Beispiel #10
0
def track_photon(infile):

    file_iterator = rat.dsreader(infile)
    tracking_dict = {}

    for iEntry, anEntry in enumerate(file_iterator):
        if iEntry % 1000 == 0 and iEntry > 0:
            print(iEntry)
        tracking_dict[iEntry] = []
        tempMC = anEntry.GetMC()
        num_tracks = tempMC.GetMCTrackCount()
        #        print("Tracks: %d" % num_tracks)

        photon_track = tempMC.GetMCTrack(0)

        for iTrack in range(num_tracks):
            tempTrack = tempMC.GetMCTrack(iTrack)
            #           print("Steps: ", tempTrack.GetMCTrackStepCount())
            for iStep in range(tempTrack.GetMCTrackStepCount()):
                if iStep == 0:
                    continue
                step = tempTrack.GetMCTrackStep(iStep)
                track_end_point = step.GetEndpoint()
                xPos = track_end_point.x()
                yPos = track_end_point.y()
                zPos = track_end_point.z()
                tracking_dict[iEntry] += [(xPos, yPos, zPos)]


#    print(tracking_dict)

    for particle in tracking_dict:
        coordinates = tracking_dict[particle]
        x_coordinates = [coordinate[0] for coordinate in coordinates]
        y_coordinates = [coordinate[1] for coordinate in coordinates]
        z_coordinates = [coordinate[2] for coordinate in coordinates]
        tracking_dict[particle] = [x_coordinates, y_coordinates, z_coordinates]

    fig = plt.figure()
    ax = Axes3D(fig)
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')

    ax.view_init(180, 0)
    ax.set_xlim3d(-25 * 25.4, 25 * 25.4)
    ax.set_ylim3d(-25 * 25.4, 25 * 25.4)
    ax.set_zlim3d(-25 * 25.4, 25 * 25.4)
    #  ax.set_ylim3d(-1,1)
    #  ax.set_zlim3d(-1,1)
    # plot 10 random particles
    for i in range(2000):

        particle_number = random.randint(0, len(tracking_dict) - 1)
        x_array = np.array(tracking_dict[particle_number][0])
        y_array = np.array(tracking_dict[particle_number][1])
        z_array = np.array(tracking_dict[particle_number][2])
        ax.scatter(x_array, y_array, z_array, c='blue', s=0.5)

    plt.show()
Beispiel #11
0
def GetMeanNhits(infileName):
    Histogram = ROOT.TH1D("alphaNhits", "alphaNhits", 125, 0.0, 500.0)

    for ds, run in rat.dsreader(infileName):
        if ds.GetEVCount() == 0:
            continue
        ev = ds.GetEV(0)

        if not ev.FitResultExists("scintFitter"):
            continue
        if not ev.GetFitResult("scintFitter").GetValid():
            continue
        if not ev.GetFitResult("scintFitter").GetVertex(0).ContainsPosition():
            continue

        vertPos = ev.GetFitResult("scintFitter").GetVertex(0).GetPosition()
        if (vertPos.Mag() < fidVolLow) or (vertPos.Mag() >= fidVolHigh):
            continue
        Histogram.Fill(ev.GetCalPMTs().GetCount())

    gaussFit = ROOT.TF1("gaus", "gaus", 0.0, 500.0)
    Histogram.Fit(gaussFit, "RQ")

    meanNhits = gaussFit.GetParameter(1)
    return meanNhits
def getHitTimeResiduals_MC(filename):
    data = []
    ratreader = rat.dsreader(filename)
    for ds, run in ratreader:
        light_path = rat.utility().GetLightPathCalculator()
        group_velocity = rat.utility().GetGroupVelocity()
        pmt_info = rat.utility().GetPMTInfo()
        event_position = ds.GetMC().GetMCParticle(0).GetPosition()
        for iev in range(0, ds.GetEVCount()):
            calibrated_pmts = ds.GetEV(iev).GetCalPMTs()
            #print calibrated_pmts.GetCount()
            for ipmt in range(0, calibrated_pmts.GetCount()):
                pmt_cal = calibrated_pmts.GetPMT(ipmt)
                light_path.CalcByPosition(
                    event_position, pmt_info.GetPosition(pmt_cal.GetID()))
                inner_av_distance = light_path.GetDistInInnerAV()
                av_distance = light_path.GetDistInAV()
                water_distance = light_path.GetDistInWater()
                transit_time = group_velocity.CalcByDistance(
                    inner_av_distance, av_distance, water_distance)
                # Assumes 400nm photon

                data.append(pmt_cal.GetTime() - transit_time)

    data = np.array(data)
    ratreader.close()
    return data
def getPEcharge_light(filename):
    '''
    Obtain information on the PEs produced. Returns arrays with:
    - charge per event
    - charge per PMT
    - number of PEs per PMT
    '''
    charge = []
    pexpmt = []
    charge_perev = []
    ratreader = rat.dsreader(filename)
    for ds, run in ratreader:
        mymc = ds.GetMC()
        # Per event
        charge_perev.append(0)
        for pmt_index in range(mymc.GetMCPMTCount()):
            # Per PMT
            mypmt = mymc.GetMCPMT(pmt_index)
            pexpmt.append(mypmt.GetMCPECount())
            for pe_index in range(pexpmt[-1]):
                this_charge = mypmt.GetMCPE(pe_index).GetCharge()
                charge_perev[-1] += this_charge
                charge.append(this_charge)

    return np.array(charge_perev), np.array(charge), np.array(pexpmt)
def plot_hit_time_residuals_mc_position(file_name):
    """ Plot the hit time residuals for the MC position.

    :param file_name: Path to the RAT DS file to plot.
    :return: The created histogram
    """
    hit_time_residuals = ROOT.TH1D( "hHitTimeResidualsMC", "Hit time residuals using the MC position", 1000, -500.0, 500.0 );
    hit_time_residuals.SetDirectory(0)
    light_path = rat.utility().GetLightPath()
    group_velocity = rat.utility().GetGroupVelocity()
    pmt_info = rat.utility().GetPMTInfo()
    for ds, run in rat.dsreader(file_name):
        event_position = ds.GetMC().GetMCParticle(0).GetPosition() # At least 1 is somewhat guaranteed
        for iev in range(0, ds.GetEVCount()):
            calibrated_pmts = ds.GetEV(iev).GetCalPMTs()
            for ipmt in range(0, calibrated_pmts.GetCount()):
                pmt_cal = calibrated_pmts.GetPMT(ipmt)
                scint_distance = ROOT.Double()
                av_distance = ROOT.Double()
                water_distance = ROOT.Double()
                light_path.CalcByPosition(event_position, pmt_info.GetPosition(pmt_cal.GetID()), 
                                          scint_distance, av_distance, water_distance)
                transit_time = group_velocity.CalcByDistance(scint_distance, av_distance, water_distance) # Assumes 400nm photon
                hit_time_residuals.Fill(pmt_cal.GetTime() - transit_time)

    hit_time_residuals.GetYaxis().SetTitle("Count per 1 ns bin")
    hit_time_residuals.GetXaxis().SetTitle("Hit time residuals [ns]")
    hit_time_residuals.Draw()
    return hit_time_residuals
Beispiel #15
0
def plot_ticks_vs_events(fname):
    c, start_clock = 0, 0
    time, x, y, y_error = np.array([]), np.array([]), np.array([]), np.array(
        [])
    for ds, run in rat.dsreader(fname):
        for iev in range(0, ds.GetEVCount()):
            ev = ds.GetEV(iev)
            if dqp.check_trig_type(
                    ev.GetTrigType()) and ev.GetClockCount50() != 0:
                c = c + 1
                time = np.hstack((time, [ev.GetClockCount50()]))
                x = np.hstack((x, [c]))
    # Sort stuff
    order = np.argsort(time)
    time_sort = np.array(time)[order]
    x_sort = np.array(x)[order]
    graph = ROOT.TGraph(len(x), x, time)
    graph.SetTitle("Clock tick as a function of event number")
    graph.GetXaxis().SetTitle("Event number")
    graph.GetXaxis().SetTitleOffset(1.2)
    graph.GetYaxis().SetTitle("50MHz clock tick")
    graph.GetYaxis().SetTitleOffset(1.2)
    graph.SetMarkerStyle(33)
    graph = ROOT.TGraph(len(x), x, time_sort)
    sort_graph.SetTitle("Clock tick as a function of event number - SORTED")
    sort_graph.GetXaxis().SetTitle("Event number")
    sort_graph.GetXaxis().SetTitleOffset(1.2)
    sort_graph.GetYaxis().SetTitle("50MHz clock tick")
    sort_graph.GetYaxis().SetTitleOffset(1.2)
    sort_graph.SetMarkerStyle(33)
    return graph, sort_graph
Beispiel #16
0
 def fill_histogram(self, hist_label="default"):
     """ Overloads SpectrumData.fill_histogram, to read DS, extract
     total KE for each event, then apply a gaussian smearing before
     filling the histogram.
     
     """
     if (hist_label == "default"):
         hist_label = self._label
     histogram = self._histograms.get(hist_label)
     assert isinstance(histogram, TH1D), \
         "SpectrumData.fill_histogram: histogram is not a TH1D object"
     energy_resolution = defaults.analysis.get("production_label").\
         get(self._rat_release).get("energy_resolution")
     seed = 12345
     random = TRandom3(seed)
     for ds, run in rat.dsreader(self._path):
         for event in range(0, ds.GetEVCount()):
             mc = ds.GetMC();
             truth_energy = 0
             for particle in range (0, mc.GetMCParticleCount()):
                 # Check they are electrons
                 if (mc.GetMCParticle(particle).GetPDGCode() == 11):
                     truth_energy += mc.GetMCParticle(particle).GetKE()
             # Gausian smearing of events
             mu = truth_energy
             sigma = math.sqrt(truth_energy*energy_resolution)
             sigma /= energy_resolution
             reconstructed_energy = random.Gaus(mu, sigma)
             histogram.Fill(reconstructed_energy)
def plot_hit_time_residuals_fit_position(file_name):
    """ Plot the hit time residuals for the fit position.

    :param file_name: Path to the RAT DS file to plot.
    :return: The created histogram
    """
    hit_time_residuals = ROOT.TH1D( "hHitTimeResidualsFit", "Hit time residuals using the fit position", 1000, -500.0, 500.0 );
    hit_time_residuals.SetDirectory(0)
    light_path = rat.utility().GetLightPath()
    group_velocity = rat.utility().GetGroupVelocity()
    pmt_info = rat.utility().GetPMTInfo()
    for ds, run in rat.dsreader(file_name):
        for iev in range(0, ds.GetEVCount()):
            ev = ds.GetEV(iev)
            if not ev.DefaultFitVertexExists() or not ev.GetDefaultFitVertex().ContainsPosition() or not ev.GetDefaultFitVertex().ValidPosition():
                continue #Didn't fit correctly
            event_position = ev.GetDefaultFitVertex().GetPosition();
            calibrated_pmts = ev.GetCalPMTs()
            for ipmt in range(0, calibrated_pmts.GetCount()):
                pmt_cal = calibrated_pmts.GetPMT(ipmt)
                scint_distance = ROOT.Double()
                av_distance = ROOT.Double()
                water_distance = ROOT.Double()
                light_path.CalcByPosition(event_position, pmt_info.GetPosition(pmt_cal.GetID()), 
                                          scint_distance, av_distance, water_distance)
                transit_time = group_velocity.CalcByDistance(scint_distance, av_distance, water_distance) # Assumes 400nm photon
                hit_time_residuals.Fill(pmt_cal.GetTime() - transit_time)

    hit_time_residuals.GetYaxis().SetTitle("Count per 1 ns bin")
    hit_time_residuals.GetXaxis().SetTitle("Hit time residuals [ns]")
    hit_time_residuals.Draw()
    return hit_time_residuals
Beispiel #18
0
def ProduceTimeResAndEnergyPDF(infileName):

    energyList = []
    nbins = (TimeRes_upperBound - TimeRes_lowerBound) / TimeRes_stepSize
    Histogram = ROOT.TH1D(infileName, "", nbins, TimeRes_lowerBound,
                          TimeRes_upperBound)

    effectiveVelocity = rat.utility().GetEffectiveVelocity()
    lightPath = rat.utility().GetLightPathCalculator()
    pmtInfo = rat.utility().GetPMTInfo()

    for ds, run in rat.dsreader(infileName):

        if ds.GetEVCount() > 0:

            mcParticle = ds.GetMC().GetMCParticle(0)
            mcPos = mcParticle.GetPosition()
            mcTime = mcParticle.GetTime()

            ev = ds.GetEV(0)

            if not ev.FitResultExists("scintFitter"):
                continue
            if not ev.GetFitResult("scintFitter").GetValid():
                continue
            if not ev.GetFitResult("scintFitter").GetVertex(
                    0).ContainsPosition():
                continue

            fitVertex = ev.GetFitResult("scintFitter").GetVertex(0)
            vertPos = fitVertex.GetPosition()
            vertTime = fitVertex.GetTime()
            if (fitVertex.ContainsEnergy()):
                energyList.append(fitVertex.GetEnergy())

            calibratedPMTs = ev.GetCalPMTs()

            for iPMT in range(0, calibratedPMTs.GetCount()):
                pmtPos = pmtInfo.GetPosition(
                    calibratedPMTs.GetPMT(iPMT).GetID())
                pmtTime = calibratedPMTs.GetPMT(iPMT).GetTime()

                lightPath.CalcByPosition(vertPos, pmtPos)
                distInScint = lightPath.GetDistInInnerAV()
                distInAV = lightPath.GetDistInAV()
                distInWater = lightPath.GetDistInWater()
                flightTime = effectiveVelocity.CalcByDistance(
                    distInScint, distInAV, distInWater)
                timeResidual = pmtTime - flightTime - vertTime

                Histogram.Fill(timeResidual)

    Histogram.Scale(1.0 / Histogram.Integral())

    pdfVector = []
    for i in range(1, Histogram.GetNbinsX()):
        pdfVector.append(Histogram.GetBinContent(i))
    Histogram.Delete()
    return (pdfVector, energyList)
 def test_read_from_file(self):
     entries = 0
     events = 0
     for ds, run in rat.dsreader(self._spectrum._path):
         entries += 1
         events += ds.GetEVCount()
     self.assertEqual(entries, 1000)
     self.assertEqual(events, 1021)
Beispiel #20
0
 def get_dq_masks(self):
     """ Reads the RAT DS in DQ-processed root file. Returns DQ status word
     """
     events = rat.dsreader(self._path)
     ds, run = events.next()
     self._dq_flags = run.GetDataQualityFlags().GetFlags(0)
     print self._dq_flags
     self._dq_applied = run.GetDataQualityFlags().GetApplied(0)
     print self._dq_applied
     return self._dq_flags, self._dq_applied
Beispiel #21
0
def PlotHitTimeResiduals(material):

    # Select which energy and fitter to use based on the material in the detector
    energy = 0.0
    fitter = ""
    if material == "lightwater_sno":
        energy = 5.0
        fitter = "waterResult"
    else:
        energy = 2.5
        fitter = "scintFitter"

    energy = 5.0

    infileName = material + "_P=" + str(int(0.0)) + "mm_E=" + str(int(energy * 1000)) + "keV_sf=0.root"
    print infileName

    hit_time_residuals = ROOT.TH1D( "hHitTimeResidualsMC", "Hit time residuals using the MC position", 120, -20.0, 100.0 )
    hit_time_residuals.SetDirectory(0)

    for ds, run in rat.dsreader(infileName):
        # rat.utility().GetLightPath() must be called *after* the rat.dsreader constructor.
        light_path = rat.utility().GetLightPathCalculator()
        group_velocity = rat.utility().GetGroupVelocity()
        pmt_info = rat.utility().GetPMTInfo()
        event_position = ds.GetMC().GetMCParticle(0).GetPosition() # At least 1 is somewhat guaranteed
        for iev in range(0, ds.GetEVCount()):
            ev = ds.GetEV(iev)

            # Check fit worked
            if not ev.FitResultExists(fitter) or not ev.GetFitResult(fitter).GetVertex(0).ContainsTime() or not ev.GetFitResult(fitter).GetVertex(0).ValidTime():
                continue

            event_time = ev.GetFitResult(fitter).GetVertex(0).GetTime()
            calibrated_pmts = ds.GetEV(iev).GetCalPMTs()
            for ipmt in range(0, calibrated_pmts.GetCount()):
                pmt_cal = calibrated_pmts.GetPMT(ipmt)
                light_path.CalcByPosition(event_position, pmt_info.GetPosition(pmt_cal.GetID()))
                inner_av_distance = light_path.GetDistInInnerAV()
                av_distance = light_path.GetDistInAV()
                water_distance = light_path.GetDistInWater()
                transit_time = group_velocity.CalcByDistance(inner_av_distance, av_distance, water_distance) # Assumes 400nm photon
                hit_time_residuals.Fill(pmt_cal.GetTime() - transit_time - event_time)

    hit_time_residuals.GetYaxis().SetTitle("Count per 1 ns bin")
    hit_time_residuals.GetXaxis().SetTitle("Hit time residuals [ns]")
    hit_time_residuals.SetTitle("Hit Time Residuals")

    canvas = ROOT.TCanvas()
    canvas.SetLogy()
    hit_time_residuals.Draw()
    canvas.Update();
    canvas.SaveAs("HitTimeResiduals.eps")

    raw_input("Press 'Enter' to exit")
def getHitTimes_MC(filename):
    data = []
    ratreader = rat.dsreader(filename)
    for ds, run in ratreader:
        for iev in range(0, ds.GetMCEVCount()):
            mc_hits = ds.GetMCEV(iev).GetMCHits()
            for imc in range(0, mc_hits.GetAllCount()):
                data.append(mc_hits.GetAllPMT(imc).GetTime())
    data = np.array(data)
    ratreader.close()
    return data
def getMChits(filename):
    ratreader = rat.dsreader(filename)
    data = []
    counter = 0
    for ds, run in ratreader:
        counter += 1
        for imc in range(0, ds.GetMCEVCount()):
            data.append(ds.GetMCEV(imc).GetMCHits().GetAllCount())
    data = np.array(data)
    ratreader.close()
    return data
def getPETimes_MC(filename):
    data = []
    ratreader = rat.dsreader(filename)
    for ds, run in ratreader:
        mc = ds.GetMC()
        for imcpmt in range(0, mc.GetMCPMTCount()):
            mcpmt = mc.GetMCPMT(imcpmt)
            for imcphotoelectron in range(0, mcpmt.GetMCPECount()):
                data.append(mcpmt.GetMCPE(imcphotoelectron).GetCreationTime())
    data = np.array(data)
    ratreader.close()
    return data
def getPEinfo(filename):
    elist = []
    trackid = []
    ratreader = rat.dsreader(filename)
    for ds, run in ratreader:
        mymc = ds.GetMC()
        for pmt_index in range(mymc.GetMCPMTCount()):
            mypmt = mymc.GetMCPMT(pmt_index)
            for pe_index in range(mypmt.GetMCPECount()):
                elist.append(mypmt.GetMCPE(pe_index).GetCharge())
                trackid.append(mypmt.GetMCPE(pe_index).GetPhotonTrackID())
    ratreader.close()
    return np.array(elist), np.array(trackid)
def getPhotonWlen(filename):
    elist = []
    ratreader = rat.dsreader(filename)
    for ds, run in ratreader:
        mymc = ds.GetMC()
        for itrack in range(mymc.GetMCTrackCount()):
            mytrack = mymc.GetMCTrack(itrack)
            # Take only the first step of each track
            mystep = mymc.GetMCTrack(itrack).GetMCTrackStep(0)
            elist.append(mystep.GetKineticEnergy())

    ratreader.close()
    return energyToWlen(elist)
Beispiel #27
0
def ProduceRatioHistogram(infileName, t1, t2):

    Histogram = ROOT.TH1D(infileName,
                          infileName + ": Prompt PMTs/Total PMTs in Event",
                          100, 0.0, 1.0)

    effectiveVelocity = rat.utility().GetEffectiveVelocity()
    lightPath = rat.utility().GetLightPathCalculator()
    pmtInfo = rat.utility().GetPMTInfo()

    for ds, run in rat.dsreader(infileName):
        if ds.GetEVCount() == 0:
            continue
        ev = ds.GetEV(0)

        if not ev.FitResultExists("scintFitter"):
            continue
        if not ev.GetFitResult("scintFitter").GetValid():
            continue
        if not ev.GetFitResult("scintFitter").GetVertex(0).ContainsPosition():
            continue

        vertPos = ev.GetFitResult("scintFitter").GetVertex(0).GetPosition()
        if vertPos.Mag() > maxRadius:
            continue
        vertTime = ev.GetFitResult("scintFitter").GetVertex(0).GetTime()

        calibratedPMTs = ev.GetCalPMTs()
        peak = total = 0.0

        for j in range(0, calibratedPMTs.GetCount()):
            pmtPos = pmtInfo.GetPosition(calibratedPMTs.GetPMT(j).GetID())
            pmtTime = calibratedPMTs.GetPMT(j).GetTime()

            lightPath.CalcByPosition(vertPos, pmtPos)
            distInScint = lightPath.GetDistInScint()
            distInAV = lightPath.GetDistInAV()
            distInWater = lightPath.GetDistInWater()
            flightTime = effectiveVelocity.CalcByDistance(
                distInScint, distInAV, distInWater)
            timeResid = pmtTime - flightTime - vertTime

            if timeResid > t1 and timeResid < t2:
                peak += 1.0
            if timeResid > t1 and timeResid < maxTimeResid:
                total += 1.0

        ratio = peak / total
        Histogram.Fill(ratio)

    return Histogram
def getPMTWlen(filename):
    elist = []
    trackid = []
    ratreader = rat.dsreader(filename)
    for ds, run in ratreader:
        mymc = ds.GetMC()
        for pmt_index in range(mymc.GetMCPMTCount()):
            mypmt = mymc.GetMCPMT(pmt_index)
            for photon_index in range(mypmt.GetMCPhotonCount()):
                elist.append(mypmt.GetMCPhoton(photon_index).GetEnergy())
                trackid.append(
                    mypmt.GetMCPhoton(photon_index).GetPhotonTrackID())
    ratreader.close()
    return energyToWlen(elist), np.array(trackid)
Beispiel #29
0
def GetHParameterAtCentre(material):
    '''Extract and store the h parameters as a function
    of energy at the centre of the detector.

    Fit each histogram with a gaussian before saving.
    '''

    hFile = ROOT.TFile(CentralHistFilename, "recreate")
    hGraph = ROOT.TGraphErrors() # tgraph of hparameter vs energy

    for i, energy in enumerate(CentralEnergies):

        infilename = CentralFilename(material, energy) + ".root"

        hHist = ROOT.TH1F(CentralHistname(energy), ";H parameter", 10000, 0, 10000)
        for ds, run in rat.dsreader(infilename):
            
            if ds.GetEVCount() == 0:
                continue

            segmentor = rat.utility().GetSegmentor()
            segmentor.SetNumberOfDivisions(NumberOfSegments)
            rawPMTSegmentIDs = segmentor.GetSegmentIDs()
            rawPMTSegmentPopulations = segmentor.GetSegmentPopulations()
            hitPMTSegmentPopulations = [0] * len(rawPMTSegmentPopulations)

            calPMTs = ds.GetEV(0).GetCalPMTs()
            for j in range(0, calPMTs.GetCount()):
                hitPMTSegmentPopulations[rawPMTSegmentIDs[calPMTs.GetPMT(j).GetID()]] += 1

            hValue = 0.0
            for s in range(len(rawPMTSegmentPopulations)):
                if (hitPMTSegmentPopulations[s] >= rawPMTSegmentPopulations[s]):
                    correctedHitPMTSegmentPopulation = rawPMTSegmentPopulations[s] - 1
                else:
                    correctedHitPMTSegmentPopulation = hitPMTSegmentPopulations[s]
                hValue += (rawPMTSegmentPopulations[s] * math.log(1.0 - (float(correctedHitPMTSegmentPopulation) / float(rawPMTSegmentPopulations[s]))))
            hValue *= -1.0

            hHist.Fill(hValue)

        hFile.cd()
        hHist.Fit("gaus", "Q")
        hHist.Write()

        hGraph.SetPoint(i, energy, hHist.GetFunction("gaus").GetParameter(1))
        hGraph.SetPointError(i, 0, hHist.GetFunction("gaus").GetParError(1))

    hGraph.SetName("grHVsEnergy")
    hGraph.Write()
Beispiel #30
0
def saveTree(fname):
    '''
    Print fitted positions

    '''
    use_retriggers = 0

    simCounter, evCounter = 0, 0
    for ds, run in rat.dsreader(fname):

        if simCounter > 0:
            continue

        simCounter += 1

        for iev in range(0, 1):

            # Use retriggers?
            if use_retriggers == 0 and iev > 0:
                continue

            # Increment counter
            evCounter += 1

            # Get DS variables
            ev = ds.GetEV(iev)
            mc = ds.GetMC()

            xTrue = mc.GetMCParticle(0).GetPosition().X()
            yTrue = mc.GetMCParticle(0).GetPosition().Y()
            zTrue = mc.GetMCParticle(0).GetPosition().Z()

            # Get fitter vertex
            try:
                fitResult = ev.GetFitResult("MultiPDFFitter")
                fitVertex = fitResult.GetVertex(0)

            except Exception as e:
                msg = "No {0} for event {1:d}, GTID {2:d} : {3}"
                msg = msg.format("MultiPDFFitter", evCounter, ev.GetGTID(), e)
                print(msg)
                continue

            xFit = fitVertex.GetPosition().X()
            yFit = fitVertex.GetPosition().Y()
            zFit = fitVertex.GetPosition().Z()

            print("True (x y z) = (", xTrue, yTrue, zTrue)
            print("Fit  (x y z) = (", xFit, yFit, zFit)
Beispiel #31
0
def NhitsVsEnergyPosition(material):

    # Select which energies to use based on the material in the detector
    energies = []
    if material == "lightwater_sno":
        energies = WaterEnergies
    else:
        energies = ScintEnergies

    nHitsTable = []

    for energy in energies:

        singleEnergyNhitsTable = []
        for position in Positions:

            infileName = material + "_P=" + str(int(position)) + "mm_E=" + str(
                int(energy * 1000)) + "keV"

            Histogram = ROOT.TH1D(infileName, "Nhits", 1000, 0.0, 10000.0)

            for ds, run in rat.dsreader(infileName):
                if ds.GetEVCount() == 0:
                    continue
                Histogram.Fill(ds.GetEV(0).GetCalPMTs().GetCount())

            tolerance = 10
            lowBin = Histogram.FindFirstBinAbove(0.0)
            lowBin = lowBin - tolerance
            highBin = Hitogram.FindLastBinAbove(0.0)
            highBin = highBin + tolerance
            if lowBin < 1:
                lowBin = 1
            if highBin > Histogram.GetNbinsX():
                highBin = Histogram.GetNbinsX()

            gaussFit = ROOT.TF1("gaus", "gaus", Histogram.GetBinCenter(lowBin),
                                Histogram.GetBinCenter(highBin))
            Histogram.Fit(gaussFit, "RQN")

            singleEnergyNhitsTable.append(gaussFit.GetParameter(1))

            del gaussFit
            del Histogram

        nHitsTable.append(singleEnergyNhitsTable)

    return nHitsTable
Beispiel #32
0
def ProduceNhitsOriginHistogram():

    nhitsOriginHisto = ROOT.TH1D("nhitsOriginHisto", "nhitsOriginHisto", 1000,
                                 0, 1000)

    for ds, run in rat.dsreader("events_E=1MeV.root"):
        if ds.GetEVCount() == 0:
            continue

        mc = ds.GetMC()
        ev = ds.GetEV(0)

        if (mc.GetMCParticle(0).GetPosition().Mag() < 10):
            nhitsOriginHisto.Fill(ev.GetCalPMTs().GetCount())

    return nhitsOriginHisto
Beispiel #33
0
def plot_mc_photoelectron_nhit(file_name):
    """ Plot the number of MC photoelectrons per event (or NumPE).

    :param file_name: Path to the RAT DS file to plot.
    :return: The histogram plot
    """
    h_num_pe = ROOT.TH1D( "hNumPE", "Number of photoelectrons per event", 2000, 0.0, 2000.0 )
    h_num_pe.SetDirectory(0)
    for ds, run in rat.dsreader(file_name):
        for iev in range(0, ds.GetEVCount()):
            ev = ds.GetEV(iev)
            h_num_pe.Fill(ds.GetMC().GetPhotoelectronCount())
    h_num_pe.GetYaxis().SetTitle( "Count per 1 pe bin" )
    h_num_pe.GetXaxis().SetTitle( "Number of photoelectrons per event" )
    h_num_pe.Draw()
    return h_num_pe
Beispiel #34
0
def plot_calibrated_nhit(file_name):
    """ Plot the number of Calibrated hits per event.

    :param file_name: Path to the RAT DS file to plot.
    :return: The histogram plot
    """
    h_cal_hits = ROOT.TH1D( "hCalHits", "Number of Calibrated hits per event", 2000, 0.0, 2000.0 )
    h_cal_hits.SetDirectory(0)
    for ds, run in rat.dsreader(file_name):
        for iev in range(0, ds.GetEVCount()):
            ev = ds.GetEV(iev)
            h_cal_hits.Fill(ev.GetCalPMTs().GetAllCount())
    h_cal_hits.GetYaxis().SetTitle( "Count per 1 Calibrated hit bin" )
    h_cal_hits.GetXaxis().SetTitle( "Number of Calibrated hits per event" )
    h_cal_hits.Draw()
    return h_cal_hits
Beispiel #35
0
 def fill_histogram(self, hist_label="default"):
     """ Method to read DS, extract total KE for each event and fill 
     histogram.
     
     :param hist_label: histogram key in self._histograms
     :type hist_label: str
     """
     if (hist_label == "default"):
         hist_label = self._label
     histogram = self._histograms.get(hist_label)
     assert isinstance(histogram, TH1D), \
         "SpectrumData.fill_histogram: histogram is not a TH1D object"
     for ds, run in rat.dsreader(self._path):
         for event in range(0, ds.GetEVCount()):
             mc = ds.GetMC();
             truth_energy = 0
             for particle in range (0, mc.GetMCParticleCount()):
                 # Check they are electrons
                 if (mc.GetMCParticle(particle).GetPDGCode() == 11):
                     truth_energy += mc.GetMCParticle(particle).GetKE()
             histogram.Fill(truth_energy)
from rat import ROOT, dsreader
import beta14

if __name__ == '__main__':
    h = {
        1: ROOT.TH1F('hbeta_1', 'hbeta_1', 100, 1, 2),
        2: ROOT.TH1F('hbeta_2', 'hbeta_2', 100, 3.5, 4.5),
        3: ROOT.TH1F('hbeta_3', 'hbeta_3', 100, 12.2, 13.2),
        4: ROOT.TH1F('hbeta_4', 'hbeta_4', 100, 47.9, 48.9),
        '14': ROOT.TH1F('hbeta14', 'hbeta14', 200, 194.0, 196.0)
    }

    f = ROOT.TFile('betas_e.root', 'recreate')
    f.cd()

    for jobnum in range(10):
        count = 0
        for ds in dsreader('e_%i.root' % jobnum):
            for ev in [ds.GetEV(n) for n in range(1)]:
                print 'Processing job %i, event %i (GTID %x)' % (jobnum, count, ev.GetEventID())
                betas = beta14.calculate_betas(ev)
                for l in betas:
                    if l in h:
                        h[l].Fill(betas[l])
                        h[l].Write()

                count += 1

    f.Close()

Beispiel #37
0
import rat
import ROOT
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import math
import RootPlotLibs as RPL
import sys
import json

pathToData = '/data/snoplus/home/cbenson/VUV/VUV_Analysis/geoFactorSim/'

fileName = sys.argv[1]

fileIterator = rat.dsreader(pathToData+'data/'+fileName+'.root')

numTracksHist = ROOT.TH1D('numTracks','numTracks',50,0,50)
outgoingDotProdHist = ROOT.TH1D('outDotProd','outDotProd',200,-1,1)
incidentDotProd = ROOT.TH1D('incidentDotProd','incidentDotProd',200,-1,1)
reemissionAngleHist = ROOT.TH1D('angle','angle',200,0,math.pi)

# Some tracking vectors 
secondVertexPoints = []

### geoEffNums
geoEffUV = 0
geoEffVisible = 0

AbsorbedTrackSet = []
UVTrackSet = []

runQuiet = True
Beispiel #38
0
 hist_dq_applied = TH1D("TH1D_dq_applied", hist_title, max_bits, 0, max_bits) 
 hist_dq_applied.GetXaxis().SetBinLabel(1, "run_type")
 hist_dq_applied.GetXaxis().SetBinLabel(2, "mc_flag")
 hist_dq_applied.GetXaxis().SetBinLabel(3, "trigger")
 hist_dq_applied.GetXaxis().SetBinLabel(4, "run_length")
 hist_dq_applied.GetXaxis().SetBinLabel(5, "general_coverage")
 hist_dq_applied.GetXaxis().SetBinLabel(6, "crate_coverage")
 hist_dq_applied.GetXaxis().SetBinLabel(7, "panel_coverage")
 hist_dq_applied.GetXaxis().SetBinLabel(8, "run_header")
 hist_dq_applied.GetXaxis().SetBinLabel(9, "delta_t_comparison")
 hist_dq_applied.GetXaxis().SetBinLabel(10, "clock_forward")
 hist_dq_applied.GetXaxis().SetBinLabel(11, "event_separation")
 hist_dq_applied.GetXaxis().SetBinLabel(12, "retriggers")
 hist_dq_applied.GetXaxis().SetBinLabel(13, "event_rate")
 for file in file_list:
     events = rat.dsreader(file)
     ds, run = events.next()
     flags = run.GetDataQualityFlags().GetFlags(0)
     applied = run.GetDataQualityFlags().GetApplied(0)
     if(flags.Get(dq_bits.GetBitIndex("run_type"))):
         hist_dq_flags.AddBinContent(1)
     if(applied.Get(dq_bits.GetBitIndex("run_type"))):
         hist_dq_applied.AddBinContent(1)
     if(flags.Get(dq_bits.GetBitIndex("mc_flag"))):
         hist_dq_flags.AddBinContent(2)
     if(applied.Get(dq_bits.GetBitIndex("mc_flag"))):
         hist_dq_applied.AddBinContent(2)
     if(flags.Get(dq_bits.GetBitIndex("trigger"))):
         hist_dq_flags.AddBinContent(3)
     if(applied.Get(dq_bits.GetBitIndex("trigger"))):
         hist_dq_applied.AddBinContent(3)
Beispiel #39
0
import beta14

if __name__ == '__main__':
    h = {
        1: ROOT.TH1F('hbeta_1', 'hbeta_1', 100, 1, 2),
        2: ROOT.TH1F('hbeta_2', 'hbeta_2', 100, 3.5, 4.5),
        3: ROOT.TH1F('hbeta_3', 'hbeta_3', 100, 12.2, 13.2),
        4: ROOT.TH1F('hbeta_4', 'hbeta_4', 100, 47.9, 48.9),
        '14': ROOT.TH1F('hbeta14', 'hbeta14', 200, 194.0, 196.0)
    }

    f = ROOT.TFile('betas_g.root', 'recreate')
    f.cd()

    for jobnum in range(10):
        count = 0
        for ds in dsreader('30cm_%i.root' % jobnum):
            for ev in [ds.GetEV(n) for n in range(1)]:
                print 'Processing job %i, event %i (GTID %x)' % (jobnum, count, ev.GetEventID())
                betas = beta14.calculate_betas(ev)
                print betas
                for l in betas:
                    if l in h:
                        h[l].Fill(betas[l])
                        h[l].Write()

                count += 1

    f.Close()

import rat
import ROOT
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

#dataPath = '~/VUV_Analysis/geoFactorSim/newGeoSim/data/config_31/pos13.root'

dataPath = '~/VUV_Analysis/Chrisdata.root'

fileIterator = rat.dsreader(dataPath)

rays = []

for i in range(1000):
    node = fileIterator.next()

    tempMC = node.GetMC()

    print 'Num Tracks: '+str(tempMC.GetMCTrackCount())
    tempTrack = tempMC.GetMCTrack(0)
    tempRay = []
    for iStep in range(tempTrack.GetMCTrackStepCount()):
        tempStep = tempTrack.GetMCTrackStep(iStep)
        tempRay.append({'x':tempStep.GetEndpoint().x(),'y':tempStep.GetEndpoint().y(),'z':tempStep.GetEndpoint().z()})

    rays.append(tempRay)

fig = plt.figure()
ax = fig.add_subplot((111), projection='3d')
ax.set_aspect('equal')
Beispiel #41
0
import rat
import ROOT
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

dataPath = '../data/config_1/'

fileIterator = rat.dsreader(dataPath+'pos12.root')

rays = []

for i in range(1000):
    tempEntry = fileIterator.next()
    
    tempMC = tempEntry.GetMC()
    
    print 'Num Tracks: '+str(tempMC.GetMCTrackCount())
    tempTrack = tempMC.GetMCTrack(0)
    tempRay = []
    for iStep in range(tempTrack.GetMCTrackStepCount()):
        tempStep = tempTrack.GetMCTrackStep(iStep)
        tempRay.append({'x':tempStep.GetEndpoint().x(),'y':tempStep.GetEndpoint().y(),'z':tempStep.GetEndpoint().z()})
    
    rays.append(tempRay)

fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')

for line in rays:
    tempX = []
    tempY = []
Beispiel #42
0
#!usr/bin/env python
import ROOT
import rat
import sys
 
# Read in the root file
# Prepare the plots 
pmtPositions = ROOT.TGraph2D()
telliePositions = ROOT.TGraph2D()
amelliePositions = ROOT.TGraph2D()
smelliePositions = ROOT.TGraph2D()

for ds in rat.dsreader("pmt_ellie_pos.root"):
  pmtProp=ds[1].GetPMTProp()
  for pmt in range (0,pmtProp.GetPMTCount()):
    if pmtProp.GetType(pmt) == 1:    
      pmtPositions.SetPoint(pmt, pmtProp.GetPos(pmt).x(), pmtProp.GetPos(pmt).y(), pmtProp.GetPos(pmt).z())

  ellieProp=ds[1].GetELLIEProp()
  for tellie in range (0,ellieProp.GetTELLIECount()):
    telliePositions.SetPoint(tellie, ellieProp.GetTELLIEPos(tellie).x(), ellieProp.GetTELLIEPos(tellie).y(), ellieProp.GetTELLIEPos(tellie).z())

  for amellie in range (0,ellieProp.GetAMELLIECount()):
    amelliePositions.SetPoint(amellie, ellieProp.GetAMELLIEPos(amellie).x(), ellieProp.GetAMELLIEPos(amellie).y(), ellieProp.GetAMELLIEPos(amellie).z())

  for smellie in range (0,ellieProp.GetSMELLIECount()):
    smelliePositions.SetPoint(smellie, ellieProp.GetSMELLIEPos(smellie).x(), ellieProp.GetSMELLIEPos(smellie).y(), ellieProp.GetSMELLIEPos(smellie).z())

#  Make the plots pretty
pmtPositions.SetMarkerColor(ROOT.kBlack)
telliePositions.SetMarkerColor(ROOT.kYellow);
 def test_dsreader(self):
     events = rat.dsreader(self._spectrum._path)
     ds, run = events.next()
     self.assertIsInstance(ds, ROOT.RAT.DS.Root)
     self.assertIsInstance(run, ROOT.RAT.DS.Run)
Beispiel #44
0
#!/bin/python
import rat
import ROOT
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

pathToData = '/Users/chrisbenson/Documents/Research/VUV/RATSims/simData/'
fileName = 'test.root'

fileIterator = rat.dsreader(pathToData+fileName)

dataVect = []
housingPoints = []

keepGoing = True
while keepGoing:
	try:
		tempEntry = fileIterator.next()
	except:
		keepGoing = False
		continue
	
	tempMC = tempEntry.GetMC()
	for trackIndex in range(tempMC.GetMCTrackCount()):
		tempTrack = tempMC.GetMCTrack(trackIndex)
		tempData = []
		trigStore = False
		monoHousStore = False
		for j in range(tempTrack.GetMCTrackStepCount()):
			tempStep = tempTrack.GetMCTrackStep(j)
			tempCoords = tempStep.GetEndpoint()
Beispiel #45
0
#
# Plot nhit numbers
#
# Author T - //2013 <> : First revision                                                                                                    
#################################################################################################### 
import ROOT
import rat
import sys

#define the histograms
evNhits = ROOT.TH1D("evNits", "evNhits", 150, 0, 3000)
MCPMThits = ROOT.TH1D("MCPMThits", "MCPMThits", 150, 0, 3000)
MCPECount = ROOT.TH1D("MCPECount", "MCPECount", 150, 0, 3000)

#read in the root file, which should be the first argument of the script
for ds, run in rat.dsreader("nhits.root"):
    for iEV in range(0, ds.GetEVCount()):
        evNhits.Fill(ds.GetEV(iEV).GetNhits()) #fill Nhits, retriggers included
    MCPECount.Fill(ds.GetMC().GetNumPE()) #fill the MC photo electron histo
    MCPMThits.Fill(ds.GetMC().GetMCPMTCount()) #fill the MC PMT hits histo

#make things pretty
#set the line width larger than default
evNhits.SetLineWidth(2)
MCPMThits.SetLineWidth(2)
MCPECount.SetLineWidth(2)

#Set the line color
evNhits.SetLineColor(ROOT.kBlack)
MCPMThits.SetLineColor(ROOT.kRed)
MCPECount.SetLineColor(ROOT.kBlue)
Beispiel #46
0
import ROOT
import rat

tempFile = rat.dsreader("../../data/config_1/pos13.root")

trackNumHist = ROOT.TH1D("TrackCounts","TrackCounts",10,0,10)

firstTrackLengthHist = ROOT.TH1D("TrackLengths","TrackLengths",100,0,1000)
histLengthFirstTracksWithAdditionalTracks = ROOT.TH1D("TrackLengthsFirstWithOthers","TrackLengthsFirstWithOthers",100,0,1000)
histLengthFirstTrackWithNoAdditionalTracks = ROOT.TH1D("TrackLengthsFirstWithNoOthers","TrackLengthsFirstWithNoOthers",100,0,1000)


for index,anEvent in enumerate(tempFile):
	tempMC = anEvent.GetMC()
	
	#print str(index)+':'+str(tempMC.GetMCTrackCount())
	#tempTrack = tempMC.GetMCTrack(
	trackNumHist.Fill(tempMC.GetMCTrackCount())
	
	# Get the endpoints of the first track to get distributions
	firstTrack =  tempMC.GetMCTrack(0)
	firstTrackLengthHist.Fill(firstTrack.GetLength())
	
	if tempMC.GetMCTrackCount() > 1:
		histLengthFirstTracksWithAdditionalTracks.Fill(firstTrack.GetLength())
	
	if tempMC.GetMCTrackCount() == 1:
		histLengthFirstTrackWithNoAdditionalTracks.Fill(firstTrack.GetLength())
	
	# Length of first track with additoinal tracks after it, should be a subset of first tracks
	for tIndex in range(tempMC.GetMCTrackCount()):
Beispiel #47
0
	def __init__(self,fileName,saveTrack=False,targetType=1):
		## Create a file iterator
		self.fileName = fileName
		fileIter = rat.dsreader(fileName)
		
		# start a loop over all of tree entries breakout of loop if at end.
		keepLooping = True
		entryIndex = -1
		showStartCoords = True
		#self.testFigure = plt.figure()
		#self.ax = self.testFigure.add_subplot(111,projection='3d')
		
		self.caseCount = [0]*9
		self.WLS_Start = []
		self.WLS_End = []
		
		self.checkpointEventCount = []
		self.geometricFactorCheckPoint = []
		self.caseCountCheckpoint = []
		
		self.targetTracks = []
		
		while keepLooping:
			try:
				tempEntry = fileIter.next()
				entryIndex += 1
				#if entryIndex%1000 == 0:
					#print entryIndex
			except:
				keepLooping = False
				continue
		
			tempMC = tempEntry.GetMC()
			
			# Get number of MC tracks and loop over them
			for iTrack in range(tempMC.GetMCTrackCount()):
				tempTrack = tempMC.GetMCTrack(iTrack)
				if showStartCoords == True:
					# This will store the coords or the very first simulated photon step 0, for source tracking.
					tempEndpoint = tempTrack.GetMCTrackStep(0).GetEndpoint()
					if tempEndpoint.x() < 0.0 and tempEndpoint.y() > 0.0:
						self.startCoords = [tempEndpoint.x(),tempEndpoint.y(),tempEndpoint.z()]
						tempEndpoint = False
				
				### Sort that track
				trackResult = self.endPointSorter(tempTrack)
				
				self.caseCount[trackResult] += 1
				
				if trackResult in [4,5,6,7,8]:
					wavelengthResults = self.getTrackStartEndWavelengths(tempTrack)
					self.WLS_Start.append(wavelengthResults[0])
					self.WLS_End.append(wavelengthResults[1])
				
				if trackResult == 8:
					#wavelengthResults = self.getTrackStartEndWavelengths(tempTrack)
					#self.WLSStart.append(wavelengthResults[0])
					coordsToPlot = convertTrackToXYZVect(tempTrack)
					#self.ax.plot(coordsToPlot[0],coordsToPlot[1],coordsToPlot[2])
					#coordsToPlot = convertTrackToEndpoint(tempTrack,0)
					#self.ax.scatter(coordsToPlot[0],coordsToPlot[1],coordsToPlot[2],color='b')
					#coordsToPlot = convertTrackToEndpoint(tempTrack,1)
					#self.ax.scatter(coordsToPlot[0],coordsToPlot[1],coordsToPlot[2],color='r')
					
					
			if entryIndex % 10000 == 0:
				self.checkpointEventCount.append(entryIndex)
				tempCaseCount = self.caseCount[:]
				self.caseCountCheckpoint.append(tempCaseCount)
				
					
		self.printResuts()