Ejemplo n.º 1
0
def main():
    runpath = '/bluearc/storage/SBC-17-data/20170706_4'
    event = 0
    traceIndex = 40

    e = sbc.DataHandling.GetSBCEvent.GetEvent(runpath, event)

    tr = e["PMTtraces"]
    trac = tr["traces"]
    dt = tr["dt"]

    trace = np.fabs(trac[traceIndex][0])
    if max(trace) == 128:
        trace = stitchTraces(trace,
                             np.fabs(e["PMTtraces"]["traces"][traceIndex][1]))
    b = np.mean(trace[0:50])
    trace -= b
    # get the time step, assuming it's constant
    dt_tr = dt[traceIndex][0]
    tPMT = np.arange(len(trace)) * dt_tr
    filteredTrace = filterXeBCTrace(trace, dt_tr)

    plt.figure()
    plt.plot(tPMT, trace)
    plt.plot(tPMT, filteredTrace)
    plt.show()
Ejemplo n.º 2
0
def randomized_t0_scintillation(runs, m):
    #m=4e7

    #m=get_gain("/bluearc/storage/SBC-17-data/",runs[0])

    Ncoinc = 0
    Nblocked = 0
    ntotcoinc = 0
    totevents = 0
    totbub = 0
    diffs = []
    goodz = []
    pmtdiffs = []
    coincspec = []

    allxyzfname = "/pnfs/coupp/persistent/grid_output/SBC-17/output/SimpleXYZ_all.bin"
    xyzf = sbc.DataHandling.ReadBinary.ReadBlock(allxyzfname)
    for run in runs:
        print("randomized_t0_scintillation processing run " + run)
        indices = [
            i for i, x in enumerate(xyzf["runid"])
            if str(x[0]) + "_" + str(x[1]) == run
        ]
        runposreco = {
            "ev": [xyzf["ev"][indices]],
            "x": [xyzf["bubX"][indices]],
            "y": [xyzf["bubY"][indices]],
            "z": [xyzf["bubZ"][indices]]
        }
        runrawpath = "/bluearc/storage/SBC-17-data/%s/" % run
        runreconpath = "/pnfs/coupp/persistent/grid_output/SBC-17/output/%s/" % run
        acousticfilename = runreconpath + "AcousticAnalysis_%s.bin" % run
        a = sbc.DataHandling.ReadBinary.ReadBlock(acousticfilename)
        #c = sbc.DataHandling.ReadBinary.ReadBlock(getbubfile)
        bubt0 = a["bubble_t0"]
        events = [
            evnt for evnt in listdir(runrawpath)
            if not isfile(join(runrawpath, evnt))
        ]

        for x in events:
            totevents += 1
            if not np.isnan(runposreco["z"][0][int(x)]):
                totbub += 1
                e = sbc.DataHandling.GetSBCEvent.GetEvent(runrawpath, x)
                cgate = e["fastDAQ"]["CAMgate"]
                dcam = np.diff(cgate)
                fdt = e["fastDAQ"]["time"]
                camOffTimes = [
                    fdt[i] for i in range(len(dcam)) if dcam[i] > 0.5
                ]

                pmttracetime = e["PMTtraces"]["t0_sec"][:, 0] + e["PMTtraces"][
                    "t0_frac"][:, 0]
                d = sbc.AnalysisModules.PMTfastDAQalignment.PMTandFastDAQalignment(
                    e)
                pmtalign = d["PMT_trigt0_sec"] + d["PMT_trigt0_frac"]
                tracetimes = pmttracetime - pmtalign
                #at0 = bubt0[int(x),0]
                rand_at0 = fdt[randrange(np.shape(fdt)[0])]
                if rand_at0 - fdt[0] < 500e-6:
                    print("too close to beginning")
                    rand_at0 = fdt[randrange(
                        np.shape(fdt)[0])]  # just trying one more time
                #print("real t0: %f"%bubt0[int(x),0])
                #print("randomized t0: %f"%rand_at0)
                i = 0  # to match the indexing of the pre-made code I had 1???
                candidate = 0
                candidate_time = 0
                #candidate_PMTtime = 0
                #candidate_index = 0
                for t in (tracetimes - rand_at0):
                    # loop through every PMT trace for the event

                    if t < 0 and t > -500e-6:

                        lastCamOff = 0
                        for k in range(len(camOffTimes)):
                            if t + rand_at0 > camOffTimes[k]:
                                lastCamOff = camOffTimes[k]
                            elif t + rand_at0 < camOffTimes[k]:
                                break
                        if t + rand_at0 - lastCamOff > 25e-6:
                            # if the trace time is within 500 microseconds before acoustic t0:
                            ntotcoinc += 1
                            pmtdiffs.append(t)

                            #take abs to get positive area:
                            trace = np.fabs(e["PMTtraces"]["traces"][i][0])
                            #if ch0 saturated, stitch in low res channel:
                            if max(trace) == 128:
                                trace = pi.stitchTraces(
                                    trace,
                                    np.fabs(e["PMTtraces"]["traces"][i][1]))
                            dt = e["PMTtraces"]["dt"][i][0]

                            #subtract baseline:
                            #Actually this gets done in pulse_integrator anyway
                            #baseline = np.mean(trace[0:50])
                            #trace -= baseline

                            #integrate and convert to phe:
                            [phe, n, totInt, pktimes
                             ] = pi.SBC_pulse_integrator_bressler(trace, dt)
                            if phe != None:
                                phe /= m
                                #keep track of largest candidate:
                                if phe > candidate:
                                    candidate = phe
                                    candidate_time = t
                                    #candidate_PMTtime = t+at0
                                    #candidate_index = i
                    i += 1
                #i.e. if there is a candidate PMT trace with area greater than zero
                if candidate > 0:
                    Ncoinc += 1
                    #ind = candidate_index
                    #pmtt = candidate_PMTtime
                    diffs.append(candidate_time)
                    goodz.append(runposreco["z"][0][int(x)])
                    coincspec.append(candidate)
                elif candidate == 0 and not np.isnan(float(x)):
                    bl = isBlocked(run, int(x), float(rand_at0),
                                   float(runposreco["z"][0][int(x)]))
                    if bl:
                        Nblocked += 1
                    else:
                        coincspec.append(0)

            gc.collect()
    print("total number of events: " + str(totevents))
    print("total number of bubbles: " + str(totbub))
    print("total coincident triggers: " + str(ntotcoinc))
    print("total blocked bubbles: " + str(Nblocked))
    print("total coincident bubbles with scintillation greater than 0phe: " +
          str(Ncoinc))
    print(
        "fraction of bubbles with a coincident scintillation signal greater than 0phe: "
        + str(Ncoinc * 100 / totbub) + "%")

    return [coincspec, Ncoinc, ntotcoinc, totevents, totbub]
def zdependence(runs, m):
    #m = 1e7

    #m=get_gain("/bluearc/storage/SBC-17-data/",runs[0])

    Ncoinc = [0, 0]
    ntotcoinc = [0, 0]
    totevents = [0, 0]
    totbub = [0, 0]
    diffs = [[], []]
    goodz = [[], []]
    pmtdiffs = [[], []]
    coincspec = [[], []]

    allxyzfname = "/pnfs/coupp/persistent/grid_output/SBC-17/output/SimpleXYZ_all.bin"
    xyzf = sbc.DataHandling.ReadBinary.ReadBlock(allxyzfname)
    for run in runs:
        print("zdependence processing run " + run)
        indices = [
            i for i, x in enumerate(xyzf["runid"])
            if str(x[0]) + "_" + str(x[1]) == run
        ]
        runposreco = {
            "ev": [xyzf["ev"][indices]],
            "x": [xyzf["bubX"][indices]],
            "y": [xyzf["bubY"][indices]],
            "z": [xyzf["bubZ"][indices]]
        }
        runrawpath = "/bluearc/storage/SBC-17-data/%s/" % run
        runreconpath = "/pnfs/coupp/persistent/grid_output/SBC-17/output/%s/" % run
        acousticfilename = runreconpath + "AcousticAnalysis_%s.bin" % run
        a = sbc.DataHandling.ReadBinary.ReadBlock(acousticfilename)
        #c = sbc.DataHandling.ReadBinary.ReadBlock(getbubfile)
        bubt0 = a["bubble_t0"]
        events = [
            evnt for evnt in listdir(runrawpath)
            if not isfile(join(runrawpath, evnt))
        ]
        for j in [0, 1]:
            with open(
                    "/nashome/b/bressler/sbcoutput/%s_PMTmatching_ch%s.txt" %
                (run, str(j)), "w+") as f, open(
                    "/nashome/b/bressler/sbcoutput/%s_muonCoincidences.txt" %
                    run, 'w+') as fmu:
                f.write(
                    "run event PMT_t0_index PMT_t0_-at0_us PMT_t0 at0 phe z\n")
                fmu.write("run event phe\n")
                for x in events:
                    yes = False
                    if int(x) < len(runposreco["z"][0]) - 1:
                        yes = True
                    totevents[j] += 1
                    if yes and not np.isnan(runposreco["z"][0][int(x)]):
                        totbub[j] += 1
                        e = sbc.DataHandling.GetSBCEvent.GetEvent(
                            runrawpath, x)
                        veto = e["fastDAQ"]["VetoCoinc"]
                        cgate = e["fastDAQ"]["CAMgate"]
                        dcam = np.diff(cgate)
                        fdt = e["fastDAQ"]["time"]
                        camOffTimes = [
                            fdt[i] for i in range(len(dcam)) if dcam[i] > 0.5
                        ]
                        muon = False
                        pmttracetime = e["PMTtraces"]["t0_sec"][:, 0] + e[
                            "PMTtraces"]["t0_frac"][:, 0]
                        d = sbc.AnalysisModules.PMTfastDAQalignment.PMTandFastDAQalignment(
                            e)
                        pmtalign = d["PMT_trigt0_sec"] + d["PMT_trigt0_frac"]
                        tracetimes = pmttracetime - pmtalign
                        at0 = bubt0[int(x), j]
                        i = 0  # to match the indexing of the pre-made code I had 1???
                        candidate = 0
                        candidate_time = 0
                        candidate_PMTtime = 0
                        candidate_index = 0
                        for t in (tracetimes - at0):
                            # loop through every PMT trace for the event

                            if t < -150e-6 and t > -600e-6:
                                # if the trace time is within 500 microsec before acoustic t0
                                if max(veto) > 0.1:
                                    if fdt[list(veto).index(
                                            max(veto)
                                    )] - at0 < 0 and fdt[list(veto).index(
                                            max(veto))] - at0 > -500e-6:
                                        print("Veto Coincidence: event " +
                                              run + "-" + str(x))
                                        muon = True

                                #lastCamOff = 0
                                #for k in range(len(camOffTimes)):
                                #    if t+at0 > camOffTimes[k]:
                                #        lastCamOff = camOffTimes[k]
                                #    elif t+at0 < camOffTimes[k]:
                                #        break
                                #if t+at0-lastCamOff > 25e-6:
                                # if the trace time is more than 25 microseconds away from a camera gate rise
                                #but not doing it this way anymore because we'll check for the LED being on later during the merge
                                ntotcoinc[j] += 1
                                pmtdiffs.append(t)

                                #take abs to get positive area:
                                trace = np.fabs(e["PMTtraces"]["traces"][i][0])
                                #if ch0 saturated, stitch in low res channel:
                                if max(trace) == 128:
                                    trace = pi.stitchTraces(
                                        trace,
                                        np.fabs(
                                            e["PMTtraces"]["traces"][i][1]))
                                dt = e["PMTtraces"]["dt"][i][0]

                                #subtract baseline:
                                #Actually this gets done in pulse_integrator anyway
                                #baseline = np.mean(trace[0:50])
                                #trace -= baseline

                                #integrate and convert to phe:
                                [phe, n, totInt,
                                 pktimes] = pi.SBC_pulse_integrator_bressler(
                                     trace, dt)
                                if phe != None:
                                    phe /= m
                                    #keep track of largest candidate:
                                    if phe > candidate:
                                        candidate = phe
                                        candidate_time = t
                                        candidate_PMTtime = t + at0
                                        candidate_index = i
                                #else:
                                #    candidate = -1.0
                            i += 1
                        #i.e. if there is a candidate PMT trace with area greater than zero
                        if candidate > 0:
                            Ncoinc[j] += 1
                            ind = candidate_index
                            pmtt = candidate_PMTtime
                            diffs[j].append(candidate_time)
                            goodz[j].append(runposreco["z"][0][int(x)])
                            coincspec[j].append(candidate)
                            f.write(
                                "%s %s %d %f %f %f %f %f\n" %
                                (run, x, ind, candidate_time * 1e6, pmtt, at0,
                                 candidate, runposreco["z"][0][int(x)]))
                        if muon:
                            fmu.write("%s %s %f\n" % (run, x, candidate))
                    gc.collect()
            print("run " + run + " file %s written" % str(j))
            #pmtdiffs.append(candidate_times[candidates.index(max(candidates))])
    print("total number of events: " + str(totevents))
    print("total number of bubbles: " + str(totbub))
    print("total coincident triggers: " + str(ntotcoinc))
    print("total coincident bubbles with scintillation greater than 0phe: " +
          str(Ncoinc))
    print(
        "fraction of bubbles with a coincident scintillation signal greater than 0phe: "
        + str(sum(Ncoinc) * 100 / sum(totbub)) + "%")

    return [goodz, diffs, coincspec, Ncoinc, ntotcoinc, totevents, totbub]
Ejemplo n.º 4
0
def get_gain(datapath, run, sendPulses=False):

    runpath = datapath + "/" + run + '/'
    events = [
        evnt for evnt in listdir(runpath) if not isfile(join(runpath, evnt))
    ]
    allTraces = []
    pulses = {'zero': [], 'one': [], 'other': []}
    optm = []
    aptm = []
    totInts = []
    for event in events:
        #plt.figure()
        if int(event) < 10:
            e = sbc.DataHandling.GetSBCEvent.GetEvent(runpath, event)

            tr = e["PMTtraces"]
            trac = tr["traces"]
            dt = tr["dt"]
            for i in range(len(trac)):
                stitched = False
                trace = np.fabs(trac[i][0])
                # get the time step, assuming it's constant
                dt_tr = dt[i][0]

                if max(trace) == 128:
                    stitched = True
                    trace = stitchTraces(
                        trace, np.fabs(e["PMTtraces"]["traces"][i][1]))
                #trace = sbcfilter.filterXeBCTrace(trace,dt_tr)
                b = np.mean(trace[0:50])
                trace -= b

                # populate dictionaries arrays based on how many pulses there were

                [a, n, totInt,
                 pktimes] = SBC_pulse_integrator_bressler(trace, dt_tr)

                if n == 0:
                    number = 'zero'
                elif n == 1:
                    number = 'one'
                    #print('single pulse event %d trace %i area %.2f'%(int(event), i, a))
                    if stitched:
                        print('stitched and single pulse!')
                    optm.append(max(trace))
                    totInts.append(totInt)
                    trace = trace[:-100]
                    """
                    if random.random()<0.005:
                        pk_ind = scipy.signal.find_peaks(trace,5)
                        pk_times = [pk*dt_tr for pk in pk_ind[0]]
                        pk_vals = [trace[k] for k in pk_ind[0]]
                        tPMT = np.arange(len(trace))*dt_tr
    
                        p, tp = get_pulse(trace,tPMT,dt_tr, 0.5e-7,pk_times[0], np.std(trace[0:50]))
                        plt.figure()
                        plt.plot(dt_tr * range(len(trace)), trace, 'r')
                        
                        startind = 0
                        for j in range(1,len(tp)):
                            dist = tp[j] - tp[j-1]
                            if dist>dt_tr+1e-9:
                                plt.plot(tp[startind:j],p[startind:j],'k', linewidth=3)
                                startind = j
                            elif j == len(tp) - 2:
                                plt.plot(tp[startind:j+1], p[startind:j+1], 'k', linewidth=3)
                        plt.scatter(pk_times, pk_vals, 50)
                        #plt.title('low area trace')
                        plt.show()
                    
                    elif a>1e7 and random.random()<0.01:
                        pk_ind = scipy.signal.find_peaks(trace,5)
                        pk_times = [pk*dt_tr for pk in pk_ind[0]]
                        pk_vals = [trace[k] for k in pk_ind[0]]
                        tPMT = np.arange(len(trace))*dt_tr
    
                        p, tp = get_pulse(trace,tPMT,dt_tr, 0.5e-7,pk_times[0], np.std(trace[0:50]))
                        plt.figure()
                        plt.plot(dt_tr * range(len(trace)), trace, 'b')
                        startind = 0
                        for j in range(1,len(tp)):
                            dist = tp[j] - tp[j-1]
                            if dist>dt_tr:
                                plt.plot(tp[startind:j],p[startind:j],'k', linewidth=3)
                                
                                startind = j
                            elif j == len(tp) - 2:
                                plt.plot(tp[startind:j+1], p[startind:j+1], 'k', linewidth=3)
                        plt.scatter(pk_times, pk_vals, 50)
                        plt.title('high area trace')
                        plt.show()
                    """
                else:
                    number = "other"

                pulses[number].append(a)
                allTraces.append(a)
                aptm.append(max(trace))
        plt.show()
    for k in pulses:
        pulses[k] = [x for x in pulses[k] if x != None]

    allTraces = [x for x in allTraces if x != None]

    Nbins = int(np.floor(np.sqrt(len(allTraces))))
    allvals, bins, _ = plt.hist(allTraces, Nbins, label='all traces')
    areaVals = {'zero': [], 'one': [], 'other': []}

    Nbins = int(np.floor(np.sqrt(len(pulses["one"]))))
    areaVals["one"], bins = np.histogram(pulses["one"], Nbins)

    spe_spectrum = areaVals['one']

    bincenters = [0.5 * (bins[i + 1] + bins[i]) for i in range(len(bins) - 1)]
    spe_spectrum_efficiency = [
        spe_spectrum[i] /
        scipy.stats.norm.cdf(bincenters[i], 4820746.10225926, 1960279.07188277)
        for i in range(len(bincenters))
    ]

    fitspect = [
        spe_spectrum[i] for i in range(len(spe_spectrum))
        if bincenters[i] > 0.2e7 and bincenters[i] < 1e8
    ]
    fitx = [x for x in bincenters if x > 0.2e7 and x < 1e8]

    def gaussian(x, mu, sigma, amplitude):
        return amplitude * np.exp(-((x - mu) / (np.sqrt(2) * sigma))**2)

    params_spe, params_cov_spe = scipy.optimize.curve_fit(gaussian,
                                                          fitx,
                                                          fitspect,
                                                          p0=[1e7, 4e7, 3000])

    plt.figure()
    plt.hist(pulses["one"], bins, histtype='step', label='Single pulses')
    plt.scatter(bincenters,
                spe_spectrum_efficiency,
                label='after adjusting for efficiency')
    plt.plot(np.arange(0, 1e8, 1e6), [
        gaussian(x, params_spe[0], params_spe[1], params_spe[2])
        for x in np.arange(0, 1e8, 1e6)
    ],
             label=r'Gaussian fit, $\mu=$%.2e, $\sigma=$%.2e' %
             (params_spe[0], params_spe[1]))
    plt.xlabel("Single Pulse Areas [electrons]")
    plt.legend(fontsize=12)
    plt.title(run)
    plt.show

    plt.figure()
    h, x, y, p = plt.hist2d(optm, pulses["one"], 100)
    plt.xlabel('trace max')
    plt.ylabel('area')
    plt.title('single pulses in ' + run)
    plt.show()

    plt.figure()
    plt.hist(optm, 100)
    plt.xlabel('trace max')
    plt.show()

    plt.figure()
    plt.hist(allTraces, 100)
    plt.title("all traces area")
    plt.show()

    plt.figure()
    h, thesebins, _ = plt.hist(aptm, 100)
    plt.hist(optm, thesebins, histtype='step')
    plt.title('all traces max')
    plt.xscale('log')
    plt.yscale('log')
    plt.show()

    if sendPulses:
        return [params_spe[0], pulses["one"], bins]
    else:
        return params_spe[0]
def coincidences(runs, m, PMTsearchwindow):

    Ncoinc = [0, 0]
    ntotcoinc = [0, 0]
    totevents = [0, 0]
    totbub = [0, 0]
    diffs = [[], []]
    goodz = [[], []]
    pmtdiffs = [[], []]
    coincspec = [[], []]

    allxyzfname = "/pnfs/coupp/persistent/grid_output/SBC-17/output/SimpleXYZ_all.bin"
    xyzf = sbc.DataHandling.ReadBinary.ReadBlock(allxyzfname)
    for run in runs:
        print("zdependence processing run " + run)
        indices = [
            i for i, x in enumerate(xyzf["runid"])
            if str(x[0]) + "_" + str(x[1]) == run
        ]
        runposreco = {
            "ev": [xyzf["ev"][indices]],
            "x": [xyzf["bubX"][indices]],
            "y": [xyzf["bubY"][indices]],
            "z": [xyzf["bubZ"][indices]]
        }
        runrawpath = "/bluearc/storage/SBC-17-data/%s/" % run
        runreconpath = "/pnfs/coupp/persistent/grid_output/SBC-17/output/%s/" % run
        acousticfilename = runreconpath + "AcousticAnalysis_%s.bin" % run
        a = sbc.DataHandling.ReadBinary.ReadBlock(acousticfilename)
        bubt0 = a["bubble_t0"]
        events = [
            evnt for evnt in listdir(runrawpath)
            if not isfile(join(runrawpath, evnt))
        ]
        for j in [0, 1]:
            with open(
                    "/nashome/b/bressler/sbcoutput/%s_PMTmatching_ch%s.txt" %
                (run, str(j)), "w+") as f, open(
                    "/nashome/b/bressler/sbcoutput/%s_muonCoincidences.txt" %
                    run, 'w+') as fmu:
                f.write(
                    "run event PMT_t0_index PMT_t0_-at0_us PMT_t0 at0 phe z\n")
                fmu.write("run event phe\n")
                for x in events:
                    oktokeepgoing = False
                    if int(x) < len(runposreco["z"][0]) - 1:
                        oktokeepgoing = True
                    totevents[j] += 1
                    if oktokeepgoing and not np.isnan(
                            runposreco["z"][0][int(x)]):
                        totbub[j] += 1
                        e = sbc.DataHandling.GetSBCEvent.GetEvent(
                            runrawpath, x)
                        veto = e["fastDAQ"]["VetoCoinc"]

                        fdt = e["fastDAQ"]["time"]
                        muon = False
                        pmttracetime = e["PMTtraces"]["t0_sec"][:, 0] + e[
                            "PMTtraces"]["t0_frac"][:, 0]
                        d = sbc.AnalysisModules.PMTfastDAQalignment.PMTandFastDAQalignment(
                            e)
                        pmtalign = d["PMT_trigt0_sec"] + d["PMT_trigt0_frac"]
                        tracetimes = pmttracetime - pmtalign
                        at0 = bubt0[int(x), j]
                        i = 0
                        candidate = 0
                        candidate_time = 0
                        candidate_PMTtime = 0
                        candidate_index = 0
                        for t in (tracetimes - at0):
                            # loop through every PMT trace for the event

                            if t < PMTsearchwindow[1] and t > PMTsearchwindow[
                                    0]:
                                # if the trace time is in the window
                                if max(veto) > 0.1:
                                    if fdt[list(veto).index(max(
                                            veto))] - at0 < PMTsearchwindow[
                                                1] and fdt[list(veto).index(
                                                    max(veto)
                                                )] - at0 > PMTsearchwindow[0]:
                                        print("Veto Coincidence: event " +
                                              run + "-" + str(x))
                                        muon = True

                                ntotcoinc[j] += 1
                                pmtdiffs.append(t)

                                #take abs to get positive area:
                                trace = np.fabs(e["PMTtraces"]["traces"][i][0])
                                #if ch0 saturated, stitch in low res channel:
                                if max(trace) == 128:
                                    trace = pi.stitchTraces(
                                        trace,
                                        np.fabs(
                                            e["PMTtraces"]["traces"][i][1]))
                                dt = e["PMTtraces"]["dt"][i][0]

                                #integrate and convert to phe:
                                [phe, n, totInt,
                                 pktimes] = pi.SBC_pulse_integrator_bressler(
                                     trace, dt)
                                if phe != None:
                                    phe /= m
                                    #keep track of largest candidate:
                                    if phe > candidate:
                                        candidate = phe
                                        candidate_time = t
                                        candidate_PMTtime = t + at0
                                        candidate_index = i

                            i += 1
                        #i.e. if there is a candidate PMT trace with area greater than zero
                        if candidate > 0:
                            Ncoinc[j] += 1
                            ind = candidate_index
                            pmtt = candidate_PMTtime
                            diffs[j].append(candidate_time)
                            goodz[j].append(runposreco["z"][0][int(x)])
                            coincspec[j].append(candidate)
                            f.write(
                                "%s %s %d %f %f %f %f %f\n" %
                                (run, x, ind, candidate_time * 1e6, pmtt, at0,
                                 candidate, runposreco["z"][0][int(x)]))
                        if muon:
                            fmu.write("%s %s %f\n" % (run, x, candidate))
                    gc.collect()
            print("run " + run + " file %s written" % str(j))
    print("total number of events: " + str(totevents))
    print("total number of bubbles: " + str(totbub))
    print("total coincident triggers: " + str(ntotcoinc))
    print("total coincident bubbles with scintillation greater than 0phe: " +
          str(Ncoinc))
    print(
        "fraction of bubbles with a coincident scintillation signal greater than 0phe: "
        + str(sum(Ncoinc) * 100 / sum(totbub)) + "%")
def PMTandPiezoPlot(datadir, run, event, gain):
    """
    Plots the piezo trace from piezo 0 and PMT pulse sizes near the acoustic
        signal on one figure. The green line indicates the time of acoustic t0.
        The red line indicates the time and size of the PMT t0 chosen by Matt's
        analysis. The yellow lines indicate the times and sizes of other PMT
        pulses.
    Also plots in separate windows the PMT traces for pulses 500 microseconds
        or less before acoustic t0.
    """
    en = event
    mu = gain
    e = sbc.DataHandling.GetSBCEvent.GetEvent(datadir + '/' + run, en)
    print(e["fastDAQ"].keys())
    cgate = e["fastDAQ"]["CAMgate"]
    dcam = np.diff(cgate)

    p0 = e["fastDAQ"]["Piezo1"]
    p1 = e["fastDAQ"]["Piezo2"]
    fdt = e["fastDAQ"]["time"]
    runreconpath = "/pnfs/coupp/persistent/grid_output/SBC-17/output/%s/" % run
    pmtdiffs = []
    diffs = []

    camOnTimes = [fdt[i] for i in range(len(dcam)) if dcam[i] < -0.5]
    camOffTimes = [fdt[i] for i in range(len(dcam)) if dcam[i] > 0.5]
    print(len(camOnTimes))
    print(len(camOffTimes))

    acousticfilename = runreconpath + "AcousticAnalysis_%s.bin" % run
    a = sbc.DataHandling.ReadBinary.ReadBlock(acousticfilename)
    bubt0 = a["bubble_t0"]

    pmttracetime = e["PMTtraces"]["t0_sec"][:,
                                            0] + e["PMTtraces"]["t0_frac"][:,
                                                                           0]
    d = sbc.AnalysisModules.PMTfastDAQalignment.PMTandFastDAQalignment(e)
    pmtalign = d["PMT_trigt0_sec"] + d["PMT_trigt0_frac"]
    tracetimes = pmttracetime - pmtalign
    at0 = bubt0[en, 0]
    at0_1 = bubt0[en, 1]

    allxyzfname = "/pnfs/coupp/persistent/grid_output/SBC-17/output/SimpleXYZ_all.bin"
    xyzf = sbc.DataHandling.ReadBinary.ReadBlock(allxyzfname)
    indices = [
        i for i, x in enumerate(xyzf["runid"])
        if str(x[0]) + "_" + str(x[1]) == run
    ]
    xyz_reconstructed = True
    if len(indices) > 0:
        runposreco = {
            "ev": [xyzf["ev"][indices]],
            "x": [xyzf["bubX"][indices]],
            "y": [xyzf["bubY"][indices]],
            "z": [xyzf["bubZ"][indices]]
        }
        z = runposreco["z"][0][int(int(en))]
    else:
        print("no handscan?")
        z = 1.5
        xyz_reconstructed = False
    lag_expected = (-23.387649 * z -
                    261.020495) * 1e-6  # fit from other analysis
    t0_expected_p0 = at0 + lag_expected
    t0_expected_p1 = at0_1 + lag_expected

    i = 0
    candidates = []
    candidate_times = []
    for t in (tracetimes - at0):

        if t < 0.2 and t > -0.2:
            lastCamOff = 0
            for k in range(len(camOffTimes)):
                if t + at0 > camOffTimes[k]:
                    lastCamOff = camOffTimes[k]
                elif t + at0 < camOffTimes[k]:
                    break
            if t + at0 - lastCamOff > 25e-6:

                pmtdiffs.append(t)
                trace = np.fabs(e["PMTtraces"]["traces"][i][0])
                if max(trace) == 128:
                    trace = pi.stitchTraces(
                        trace, np.fabs(e["PMTtraces"]["traces"][i][1]))
                dt = e["PMTtraces"]["dt"][i][0]
                #baseline = np.mean(trace[0:50])
                #trace = trace - baseline
                [phe, n, totInt,
                 pktimes] = pi.SBC_pulse_integrator_bressler(trace, dt)

                if phe != None:
                    phe /= mu
                    candidates.append(phe)
                    candidate_times.append(t)
        i += 1
    candidate_phe = 0
    the_index = 0
    i = 0
    near_trace_indices = []
    for t in candidate_times:
        if t > -500e-6 and t < 0:
            near_trace_indices.append(list(tracetimes - at0).index(t))
            if candidates[i] > candidate_phe:
                candidate_phe = candidates[i]
                the_index = i
        i += 1

    if len(candidates) != 0:
        if max(candidates) > 0:
            diffs.append(candidate_times[candidates.index(max(candidates))])
    fig, ax1 = plt.subplots()
    ax2 = ax1.twinx()
    ax1.plot(fdt, p0, 'b', alpha=0.6, label='piezo 0')
    ax1.plot(fdt, p1, 'k', alpha=0.2, label='piezo 1')
    for i in range(len(candidates)):
        if i == the_index:
            ax2.plot([candidate_times[i] + at0, candidate_times[i] + at0],
                     [0, candidates[i]],
                     'r',
                     lw=4)
        else:
            ax2.plot([candidate_times[i] + at0, candidate_times[i] + at0],
                     [0, candidates[i]],
                     'y',
                     lw=4)
    #ax2.plot([min(candidate_times),max(candidate_times)],[0,0],linewidth=2)
    ax1.plot([at0, at0], [-0.5, 0.5],
             'b',
             linewidth=2,
             label='acoustic t0, p0')
    ax1.plot([at0_1, at0_1], [-0.5, 0.5],
             'k',
             linewidth=2,
             label='acoustic t0, p1')
    """
    if xyz_reconstructed:
        ax1.plot([t0_expected_p0,t0_expected_p0],[-0.5,0.5],'b:',linewidth=2, label = 'expected PMT t0, p0')
        ax1.plot([t0_expected_p1,t0_expected_p1],[-0.5,0.5],'k:',linewidth=2, label = 'expected PMT t0, p1')
    else:
        ax1.plot([t0_expected_p0,t0_expected_p0],[-0.5,0.5],'b:',linewidth=2, label = 'expected PMT t0, p0, center of chamber')
        ax1.plot([t0_expected_p1,t0_expected_p1],[-0.5,0.5],'k:',linewidth=2, label = 'expected PMT t0, p1, center of chamber')
    """
    ax1.plot(fdt, cgate, 'c')
    ax1.plot(fdt[:-1], dcam, 'm')
    ax2.set_ylabel('pmt signal (phe)', fontsize=20)
    ax1.set_xlabel('time (s)', fontsize=20)
    ax1.set_ylabel('Acoustic signa(V)', fontsize=20)
    ax1.set_ylim([min(p1), max(p1)])
    ax2.set_xlim([-0.1, 0.1])
    #ax2.set_ylim([0,5])
    ax1.legend()
    plt.show

    for j in near_trace_indices:
        trace = e["PMTtraces"]["traces"][j][0]
        dt = e["PMTtraces"]["dt"]
        dt_tr = dt[j][0]
        tPMT = np.arange(len(trace)) * dt_tr
        plt.figure()
        plt.plot(tPMT, trace)
        plt.xlabel("t (s)")
        plt.ylabel("PMT signal")
        plt.show

    plt.figure()
    plt.plot(e["fastDAQ"]["time"], e["fastDAQ"]["VetoCoinc"])
    plt.ylabel("Veto Coincidence signal", fontsize=18)
    plt.xlabel("time (s)")
    plt.show
Ejemplo n.º 7
0
theirphe = np.zeros([len(pmt["PMT_pulse_area"]), 1])

for n in range(Nevents):
    i = 0
    print(n)
    indices = [i for i, x in enumerate(pmt["ev"]) if int(x) == n]
    #print(indices)
    areas = pmt["PMT_pulse_area"][indices]
    print(len(areas))
    e = sbc.DataHandling.GetSBCEvent.GetEvent(runpath, n)
    #print(len(e["PMTtraces"]["traces"]))
    for k in range(len(e["PMTtraces"]["traces"])):
        trace = np.fabs(e["PMTtraces"]["traces"][k][0])
        #if ch0 saturated, stitch in low res channel:
        if max(trace) == 128:
            trace = pi.stitchTraces(trace,
                                    np.fabs(e["PMTtraces"]["traces"][k][1]))
        dt = e["PMTtraces"]["dt"][k][0]

        #integrate and convert to phe:
        [a, n, totInt, pktimes] = pi.SBC_pulse_integrator_bressler(trace, dt)
        myphe[i] = a
        theirphe[i] = -areas[i] * CONVERSION_TO_CHARGE
        i += 1
        gc.collect()

plt.figure()
plt.scatter(myphe, theirphe)
plt.show()

plt.figure()
plt.hist(theirphe, 30)
def spectrum(datapath, run, forcebins=False):
    """Returns the spectrum and histogram bins for the scintillation of all events in a run"""
    runpath = datapath + '/' + run
    events = [
        evnt for evnt in listdir(runpath) if not isfile(join(runpath, evnt))
    ]
    allTraces = []
    total_time = 0
    pulses = {'zero': [], 'one': [], 'two': [], 'three': [], 'other': []}
    times = {'zero': [], 'one': [], 'two': [], 'three': [], 'other': []}
    #camextratime = 25e-6
    for event in events:
        if int(event) > 3:
            break
        print(event)
        e = sbc.DataHandling.GetSBCEvent.GetEvent(runpath, event)
        if e["slowDAQ"]["loaded"]:
            #print(e["fastDAQ"].keys())
            cgate = e["fastDAQ"]["CAMgate"]
            #dcam = np.diff(cgate)
            fdt = e['fastDAQ']['time']
            #camOffTimes = np.sort(np.array([fdt[i] for i in range(len(dcam)) if dcam[i] > 0.5]))

            #camOnTimes = np.sort(np.array([fdt[i] for i in range(len(dcam)) if dcam[i] < 0.5]))
            fddt = fdt[1] - fdt[0]
            tfast = fdt[-1] - fdt[0]
            LED_on = [fdt[i] for i in range(len(cgate)) if cgate[i] < -0.5]
            blockedFraction = ((len(LED_on) * fddt)) / tfast
            print(blockedFraction)
            tr = e["PMTtraces"]
            trac = tr["traces"]
            dt = tr["dt"]
            #event_time = (tr['t0_sec'][-1]+tr['t0_frac'][-1]-tr['t0_sec'][0] - tr['t0_frac'][0])[0]
            event_time = (((e["slowDAQ"]["elapsed_time"][-1] -
                            e["slowDAQ"]["elapsed_time"][0])) *
                          (1 - blockedFraction))
            #print(event_time)
            total_time += event_time

            #f,axes = plt.subplots(1,5,sharey=True)
            #f.suptitle(runpath+"/"+str(event))
            #pmttracetime = e["PMTtraces"]["t0_sec"][:,0]+e["PMTtraces"]["t0_frac"][:,0]
            #d=sbc.AnalysisModules.PMTfastDAQalignment.PMTandFastDAQalignment(e)
            #pmtalign = d["PMT_trigt0_sec"]+d["PMT_trigt0_frac"]
            #tracetimes = pmttracetime - pmtalign
            #camoffindex = 0
            #camonindex = 0
            for i in range(len(trac)):
                #print(i)
                """
                thistracetime = tracetimes[i]
                
                #nearestcamoff = min(camOffTimes, key=lambda x:abs(x-thistracetime))
                #nearestcamon = min(camOnTimes, key=lambda x:abs(x-thistracetime))
                print(camOffTimes[camoffindex])
                print(thistracetime)
                if thistracetime > camOffTimes[camoffindex]:
                    camoffindex += 1
                if thistracetime > camOnTimes[camonindex]:
                     camonindex += 1 
                if camoffindex<len(camOffTimes)-1:
                    if abs(camOffTimes[camoffindex]-thistracetime)<camextratime:
                        print('excluding a trace near a camera off')
                        continue
                if camonindex<len(camOnTimes)-1:
                    if abs(camOnTimes[camonindex]-thistracetime)<camextratime:
                        print('excluding a trace near a camera on')
                        continue
                """
                trace = np.fabs(trac[i][0])
                if max(trace) == 128:
                    trace = stitchTraces(
                        trace, np.fabs(e["PMTtraces"]["traces"][i][1]))
                dt_tr = dt[i][0]

                # populate dictionaries arrays based on how many pulses there were
                [a, n, totInt,
                 pktimes] = SBC_pulse_integrator_bressler(trace, dt_tr)
                if n == 0:
                    number = 'zero'
                    allTraces.append(a)
                elif n == 1:
                    number = 'one'
                    allTraces.append(a)
                    times['one'].append(pktimes[0])
                elif n == 2:
                    number = 'two'
                    allTraces.append(a)
                elif n == 3:
                    number = 'three'
                    allTraces.append(a)
                else:
                    number = 'other'
                    allTraces.append(a)
                """
                #if a != None:
                if isZero:
                    if j < 5:
                        if isNegative:
                            if random() >0:
                                print(runpath+"/"+str(event)+" pmt trace "+str(i))
                                tPMT = np.arange(len(trace))*dt_tr
                                axes[j].plot(tPMT,trace,lw=3)
                                axes[j].set_xlabel("time (s)",fontsize=25)
                                axes[j].set_ylabel("PMT response (ADC)",fontsize=25)
                                j+=1
               
    
                plt.show
                """
                pulses[number].append(a)
        gc.collect()

    for k in pulses:
        pulses[k] = [x for x in pulses[k] if x != None]

    allTraces = [x for x in allTraces if x != None]

    plt.figure()

    Nbins = int(np.floor(np.sqrt(len(allTraces))))
    allvals, bins, _ = plt.hist(allTraces, Nbins, label='all traces')

    areaVals = {'zero': [], 'one': [], 'two': [], 'three': [], 'other': []}
    for k in pulses:
        if k != 'other':
            areaVals[k], _, _ = plt.hist(pulses[k],
                                         bins,
                                         histtype='step',
                                         linewidth=3,
                                         label=k + ' hits')
    plt.legend(fontsize=12)
    plt.show()
    #spe_spectrum = areaVals['one']

    #def gaussian(x,mu,sigma,amplitude):
    #    return amplitude * np.exp(-((x - mu) /(np.sqrt(2)* sigma))**2 )

    #params_spe, params_cov_spe = scipy.optimize.curve_fit(gaussian,bins[:len(areaVals['one'])],
    #                                                                    spe_spectrum,
    #                                                                    p0=[0.4e8,1e7,40])
    #params_twohits, params_cov_twohits = scipy.optimize.curve_fit(gaussian,
    #                                                              bins[:len(areaVals['two'])],
    #                                                              areaVals['two'],
    #                                                              p0=[0.8e8,1e7,10])
    #mu_spe = params_spe[0]
    #mu_2 = params_twohits[0] - mu_spe
    #print(mu_spe)
    #print(mu_2)

    #mu_avg = (mu_spe + mu_2)*0.5
    #mu_avg = get_gain(datapath,run)
    mu_avg = 1e7
    print(mu_avg)

    plt.figure()
    plt.grid(True)
    if isinstance(forcebins, np.ndarray):
        bins = forcebins
        fullspect, _, _ = plt.hist([t / mu_avg for t in allTraces],
                                   forcebins,
                                   label='all traces')

    else:
        fullspect, bins, _ = plt.hist([t / mu_avg for t in allTraces],
                                      int(np.floor(np.sqrt(len(allTraces)))),
                                      label='all traces')

    #print(bins)
    plt.yscale('log')
    plt.xlabel('phe based on a gain of ' + str(mu_avg) + ' electrons per phe')
    plt.legend()
    plt.show
    print(sum(fullspect) / total_time)
    print("The Total Exposure Time of run " + str(runpath) + " was " +
          str(total_time) + " Seconds")
    print("The overall PMT trigger rate was " +
          str(len(allTraces) / total_time) + "Hz")
    return [fullspect, bins, total_time]
def check_multibub_scintillation(run, event, at0, PMTgain, PMTwindow):
    tstart = PMTwindow[0]
    t_end = PMTwindow[1]
    scintillation_signal = 0
    datadir = '/bluearc/storage/SBC-17-data'
    e = sbc.DataHandling.GetSBCEvent.GetEvent(datadir + '/' + run, event)
    cgate = e["fastDAQ"]["CAMgate"]
    fdt = e["fastDAQ"]["time"]

    LED_on = [fdt[i] for i in range(len(cgate)) if cgate[i] < -0.5]
    look_times = [x for x in LED_on if (x < 0 and abs(x - at0) < tstart)]
    #print(str(len(LED_on)/len(fdt)))
    if len(look_times) > 0:
        LED_during_window = True

    else:
        LED_during_window = False

        dcam = np.diff(cgate)
        fdt = e["fastDAQ"]["time"]
        camOffTimes = [fdt[i] for i in range(len(dcam)) if dcam[i] > 0.5]
        pmttracetime = e["PMTtraces"]["t0_sec"][:, 0] + e["PMTtraces"][
            "t0_frac"][:, 0]
        d = sbc.AnalysisModules.PMTfastDAQalignment.PMTandFastDAQalignment(e)
        pmtalign = d["PMT_trigt0_sec"] + d["PMT_trigt0_frac"]
        tracetimes = pmttracetime - pmtalign

        i = 0  # to match the indexing of the pre-made code I had 1???
        candidate = 0

        for t in (tracetimes - at0):
            # loop through every PMT trace for the event

            if t < t_end and t > tstart:
                # if the trace time is within 500 microsec before acoustic t0
                """        
                lastCamOff = 0
                for k in range(len(camOffTimes)):
                    if t+at0 > camOffTimes[k]:
                        lastCamOff = camOffTimes[k]
                    elif t+at0 < camOffTimes[k]:
                        break
                if t+at0-lastCamOff > 25e-6:
                    # if the trace time is more than 25 microseconds away from a camera gate rise
                """
                #take abs to get positive area:
                trace = np.fabs(e["PMTtraces"]["traces"][i][0])
                #if ch0 saturated, stitch in low res channel:
                if max(trace) == 128:
                    trace = pi.stitchTraces(
                        trace, np.fabs(e["PMTtraces"]["traces"][i][1]))
                dt = e["PMTtraces"]["dt"][i][0]

                #integrate and convert to phe:
                [phe, n, totInt,
                 pktimes] = pi.SBC_pulse_integrator_bressler(trace, dt)
                if phe != None:
                    phe /= PMTgain
                    #keep track of largest candidate:
                    if phe > candidate:
                        candidate = phe

            i += 1
        #i.e. if there is a candidate PMT trace with area greater than zero
        if candidate > 0:
            scintillation_signal = candidate

    gc.collect()
    return [LED_during_window, scintillation_signal]