def check_detres_sigmas(config, detres, datadir=""):
    det_res = DetectorResponseGaussAngle(config, infile=(datadir + detres))
    sig_test = det_res.sigmas[np.where(det_res.sigmas > 0.0001)]
    print "Total PMT bins: " + str(np.shape(det_res.sigmas))
    print "Calibrated PMT bins: " + str(np.shape(sig_test))
    print "Mean sigma: " + str(np.mean(sig_test))
    print "Max sigma: " + str(max(sig_test))
    max_ang = 0.3
    max_y = 60
    plt.hist(sig_test, 100, normed=True, range=(0., max_ang))
    plt.axis([0., max_ang, 0., max_y])
    plt.xlabel('Incident Angle Std (rad)')
    plt.ylabel('PMTs/Unit Angle')
    plt.show()

    # Find PMTs with large sigma
    ind_peak2 = np.array(
        np.where(det_res.sigmas > 0.1)
    )[0]  #np.array(np.where(np.logical_and(det_res.sigmas>0.1,det_res.sigmas>0.1)))[0]
    print 'PMTs with high angular uncertainty: ', len(ind_peak2)
    single_face = True  # Draw only a single face of the icosahedron
    if single_face:
        ind_peak2 = ind_peak2[np.where(
            ind_peak2 < det_res.n_pmts_per_surf * det_res.n_lens_sys)]
    pos_peak2 = det_res.pmt_bin_to_position(ind_peak2)

    # Get first PMT location for each curved surface (center of curved surface)
    center_pmt_bins = np.linspace(0,
                                  det_res.npmt_bins,
                                  det_res.n_lens_sys * 20,
                                  endpoint=False,
                                  dtype=np.int)
    if single_face:
        center_pmt_bins = center_pmt_bins[np.where(
            center_pmt_bins < det_res.n_pmts_per_surf * det_res.n_lens_sys)]
    #print len(center_pmt_bins)
    center_pmt_pos = det_res.pmt_bin_to_position(center_pmt_bins)

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(pos_peak2[:, 0], pos_peak2[:, 1], pos_peak2[:, 2], color='blue')
    ax.scatter(center_pmt_pos[:, 0],
               center_pmt_pos[:, 1],
               center_pmt_pos[:, 2],
               color='red')
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    ax.set_title('PMTs with high angular uncertainty')
    plt.show()
def create_detres(config,
                  simname,
                  detresname,
                  detxbins=10,
                  detybins=10,
                  detzbins=10,
                  method="PDF",
                  nevents=-1,
                  datadir="",
                  fast_calibration=False):
    #saves a detector response list of pdfs- 1 for each pixel- given a simulation file of photons emitted isotropically throughout the detector.
    if method == "PDF":
        smalltest = DetectorResponsePDF(config, detxbins, detybins, detzbins)
    elif method == "GaussAngle":
        smalltest = DetectorResponseGaussAngle(config, detxbins, detybins,
                                               detzbins)
    else:
        print "Warning: using generic DetectorResponse base class."
        smalltest = DetectorResponse(config)
    smalltest.calibrate(datadir + simname,
                        datadir,
                        nevents,
                        fast_calibration=fast_calibration)
    # print smalltest.means[68260]
    # print smalltest.sigmas[68260]
    smalltest.write_to_ROOT(datadir + detresname)
def reconstruct_event_AVF(config,
                          event,
                          detres=None,
                          detbins=10,
                          event_pos=None,
                          sig_cone=0.01,
                          n_ph=0,
                          min_tracks=4,
                          chiC=3.,
                          temps=[256, 0.25],
                          tol=1.0,
                          debug=False,
                          lens_dia=None,
                          datadir=""):
    if detres is None:
        det_res = DetectorResponseGaussAngle(config, detbins, detbins, detbins)
    else:
        det_res = DetectorResponseGaussAngle(config,
                                             detbins,
                                             detbins,
                                             detbins,
                                             infile=(datadir + detres))
        # print det_res.sigmas
        # sig_test = det_res.sigmas[np.where(det_res.sigmas>0.)]
        # print max(sig_test)
        # print np.mean(sig_test)
    analyzer = EventAnalyzer(det_res)
    reader = ShortRootReader(datadir + event)
    for ev in reader:

        # Temporary
        #plot_event(ev)
        #quit()

        # End temp

        vtcs = analyzer.analyze_one_event_AVF(ev, sig_cone, n_ph, min_tracks,
                                              chiC, temps, tol, debug,
                                              lens_dia)
        # performance checks: speed, distance from recon vertex to event position for each, uncertainty for each
        if event_pos is not None:
            print "Distance to true event pos: " + str(
                np.linalg.norm(vtcs[0].pos - event_pos))
def compare_sigmas(config1, detres1, config2, detres2, datadir=""):
    det_res1 = DetectorResponseGaussAngle(config1, infile=(datadir + detres1))
    det_res2 = DetectorResponseGaussAngle(config2, infile=(datadir + detres2))
    npmt = det_res1.npmt_bins
    if npmt != det_res2.npmt_bins:
        print "Can't compare the detector responses - different numbers of PMTs!"
        return
    calibrated_pmts = np.where(
        np.logical_and(det_res1.sigmas > 0.001, det_res2.sigmas > 0.001))[0]
    #print det_res1.means[:,calibrated_pmts], np.shape(det_res1.means[:,calibrated_pmts])
    cos_ang = np.einsum('ij,ij->j', det_res1.means[:, calibrated_pmts],
                        det_res2.means[:, calibrated_pmts])
    ang = np.rad2deg(np.arccos(np.clip(cos_ang, -1.0, 1.0)))
    #mean_diff = det_res1.means[:,calibrated_pmts] - det_res2.means[:,calibrated_pmts]
    max_ang = 15
    max_y = 0.6
    plt.hist(ang, 100, normed=True, range=(0., max_ang))
    plt.axis([0., max_ang, 0., max_y])
    plt.xlabel('Relative angle (deg)')
    plt.ylabel('PMTs/Unit Angle')
    plt.show()
Beispiel #5
0
def _calibrate(config,
               photons_file,
               detresname,
               detxbins=10,
               detybins=10,
               detzbins=10,
               method="PDF",
               nevents=-1,
               datadir="",
               fast_calibration=True):
    logger.info('Calibrating with: ' + datadir + photons_file)
    if method == "PDF":
        dr = DetectorResponsePDF(
            config, detxbins, detybins,
            detzbins)  # Do we need to continue to carry this?
    elif method == "GaussAngle":
        dr = DetectorResponseGaussAngle(config, detxbins, detybins, detzbins)
    else:
        logger.warning('Warning: using generic DetectorResponse base class.')
        dr = DetectorResponse(config)
    dr.calibrate(datadir + photons_file,
                 datadir,
                 nevents,
                 fast_calibration=fast_calibration)
    logger.info(
        "=== Detector analysis calibration complete.  Writing calibration file"
    )

    if USE_ROOT:
        # In this case write both hdf5 and ROOT files
        dr.write_to_ROOT(datadir + detresname + '.root')

    # Config dict is just included for human readability (currently)
    detector_data = {
        'config': dr.config,
        'config_dict': vars(dr.config),
        'means': dr.means,
        'sigmas': dr.sigmas
    }
    dd.io.save(datadir + detresname + '.h5', detector_data)
def get_AVF_performance(config,
                        event,
                        n_repeat=10,
                        detres=None,
                        detbins=10,
                        event_pos=None,
                        sig_cone=[0.01],
                        n_ph=[0],
                        min_tracks=[4],
                        chiC=[3.],
                        temps=[[256, 0.25]],
                        tol=[1.0],
                        debug=False,
                        lens_dia=None,
                        datadir=""):
    # Calls analyze_one_event_AVF multiple times for each configuration, where a configuration is
    # a set of parameters (sig_cone to tol). Uses the last entry of a parameter's list if
    # there are fewer entries for it than the current iteration number. Prints the average
    # performance across multiple runs for each configuration.

    if detres is None:
        det_res = DetectorResponseGaussAngle(config, detbins, detbins, detbins)
    else:
        det_res = DetectorResponseGaussAngle(config,
                                             detbins,
                                             detbins,
                                             detbins,
                                             infile=(datadir + detres))
    analyzer = EventAnalyzer(det_res)
    reader = ShortRootReader(datadir + event)
    max_iter = max([
        len(sig_cone),
        len(n_ph),
        len(min_tracks),
        len(chiC),
        len(temps),
        len(tol)
    ])

    for ev in reader:
        for it in range(max_iter):
            sig_cone_i = idx_check(sig_cone, it)
            n_ph_i = idx_check(n_ph, it)
            min_tracks_i = idx_check(min_tracks, it)
            chiC_i = idx_check(chiC, it)
            temps_i = idx_check(temps, it)
            tol_i = idx_check(tol, it)
            print "sig_cone: " + str(sig_cone_i)
            print "n_ph: " + str(n_ph_i)
            print "min_tracks: " + str(min_tracks_i)
            print "chiC: " + str(chiC_i)
            print "temps: " + str(temps_i)
            print "tol: " + str(tol_i)
            times = []
            vtx_disp = []
            vtx_err = []
            vtx_unc = []
            n_vtcs = []
            for ind in range(n_repeat):
                print "Iteration " + str(ind + 1) + " of " + str(n_repeat)
                t0 = time.time()
                vtcs = analyzer.analyze_one_event_AVF(ev, sig_cone_i, n_ph_i,
                                                      min_tracks_i, chiC_i,
                                                      temps_i, tol_i, debug,
                                                      lens_dia)
                t1 = time.time()
                # Check performance: speed, dist from recon vertex to event pos for each, uncertainty for each
                doWeights = True  # Weight vertices by n_ph
                if vtcs:  # Append results unless no vertices were found
                    times.append(t1 - t0)
                    n_vtcs.append(len(vtcs))
                    vtx_unc.append(np.mean([vtx.err for vtx in vtcs
                                            ]))  # weight by vtx.n_ph?
                    if event_pos is not None:
                        min_errs = []
                        weights = []
                        #print vtcs[0].n_ph
                        for vtx in vtcs:
                            if np.linalg.norm(
                                    vtx.pos
                            ) > det_res.inscribed_radius:  # Skip vertices outside detector
                                break
                            errs = [vtx.pos - ev_pos for ev_pos in event_pos]
                            min_ind = np.argmin(
                                [np.linalg.norm(err) for err in errs])
                            if doWeights:
                                min_errs.append(errs[min_ind] * vtx.n_ph)
                                weights.append(vtx.n_ph)
                            else:
                                min_errs.append(errs[min_ind])
                                weights.append(1.0)
                            #break #To use only the first vtx found
                        avg_err = np.sum(min_errs, axis=0) / np.sum(weights)
                        vtx_disp.append(avg_err)
                        vtx_err.append(np.linalg.norm(avg_err))
            # Print mean values instead?
            print "vtx_err: " + str(
                vtx_err
            )  # weighted distance of vertices to true event position
            print "mean vtx_err: " + str(
                np.mean(vtx_err))  # averaged over all iterations
            print "mean vtx_disp: " + str(np.mean(vtx_disp,
                                                  axis=0))  #vtx-event
            print "avg n_vtcs: " + str(np.mean(n_vtcs))
            # print "vtx_unc: " + str(vtx_unc)
            # print np.mean(vtx_unc)
            print "times: " + str(times)
            print "mean time: " + str(np.mean(times))
Beispiel #7
0
def eff_test(config,
             detres=None,
             detbins=10,
             sig_pos=0.01,
             n_ph_sim=[0],
             repetition=10,
             max_rad=6600,
             n_pos=10,
             loc1=(0, 0, 0),
             sig_cone=0.01,
             lens_dia=None,
             n_ph=0,
             min_tracks=0.05,
             chiC=3.,
             temps=[256, 0.25],
             tol=0.1,
             debug=False):
    ###############################################

    run = array('i', [0])  # repetition

    pos = array('i', [0])  # n_pos: number of steps
    xpos_true = array('f', [0])
    ypos_true = array('f', [0])
    zpos_true = array('f', [0])
    xpos = array('f', [0])
    ypos = array('f', [0])
    zpos = array('f', [0])
    multiplicity = array('i', [0])
    photon_sim = array('i', [0])
    photon_true = array('i', [0])
    dist_event = array('f', [0])

    ROOT.gROOT.Reset()
    #f1 = ROOT.TFile(rootdir+str(now)+"_"+config+"_rep-"+str(repetition)+"_npos-"+str(n_pos)+".root", "RECREATE")
    f1 = ROOT.TFile(
        rootdir + 'rep-' + str(repetition) + '_npos-' + str(n_pos) + '.root',
        'RECREATE')
    ttree = ROOT.TTree("data", "data")

    ttree.Branch("run", run, "run/I")
    ttree.Branch("pos", pos, "pos/I")
    ttree.Branch("xpos_true", xpos_true, "xpos_true/F")
    ttree.Branch("ypos_true", ypos_true, "ypos_true/F")
    ttree.Branch("zpos_true", zpos_true, "zpos_true/F")
    ttree.Branch("xpos", xpos, "xpos/F")
    ttree.Branch("ypos", ypos, "ypos/F")
    ttree.Branch("zpos", zpos, "zpos/F")
    ttree.Branch("dist_event", dist_event, "dist_event/F")
    ttree.Branch("photon_sim", photon_sim, "photon_sim/I")
    ttree.Branch("photon_true", photon_true, "photon_true/I")
    ttree.Branch("multiplicity", multiplicity, "multiplicity/I")

    # Build detector
    #view(kabamland)
    #quit()

    print "Simulation started."
    sim, analyzer = nog4_sim.sim_setup(config, detres)
    det_res = DetectorResponseGaussAngle(config,
                                         detbins,
                                         detbins,
                                         detbins,
                                         infile=detres)
    # Previous definition of rads
    #rads = [max_rad*float(ii+1)/n_pos for ii in range(n_pos)]

    # Get radius for equal volumes within the detector up to the maximum radius max_rad
    #rads = radius_equal_vol(max_rad = max_rad, steps = n_pos)

    # Get equally seperated radii within the detector up to the maximum radius max_rad
    rads = [ii * max_rad / n_pos for ii in range(n_pos + 1)]

    recon = np.zeros((len(n_ph_sim), repetition, n_pos + 1, 6))

    for ii, amount in enumerate(n_ph_sim):
        for iy, rad in enumerate(rads):
            print "Energy: " + str(amount) + ", radius: " + str(rad)

            events, points = create_single_source_events(
                rad, sig_pos, amount, repetition)

            for ind, ev in enumerate(
                    sim.simulate(events,
                                 keep_photons_beg=True,
                                 keep_photons_end=True,
                                 run_daq=False,
                                 max_steps=100)):

                # Do AVF event reconstruction
                vtcs = analyzer.analyze_one_event_AVF(ev, sig_cone, n_ph,
                                                      min_tracks, chiC, temps,
                                                      tol, debug, lens_dia)

                # Weight vertices by n_ph
                doWeights = True

                # Append results unless no vertices were found
                if vtcs:

                    photons = [vtx.n_ph for vtx in vtcs]
                    n_ph_total = np.sum(photons)
                    n_ph_max = np.max(photons)
                    event_pos = points[ind, :]

                    if event_pos is not None:
                        min_errs = []
                        weights = []
                        for ii, vtx in enumerate(vtcs):

                            #Skip vertex with smaller amount of photon tracks associated with
                            if ii != np.argmax(n_ph_total):
                                print "Two vertices found! Smaller vertex with ", photons[
                                    ii], "photons out of ", n_ph_total
                                break

                            # Skip vertices outside detector
                            if np.linalg.norm(
                                    vtx.pos) > det_res.inscribed_radius:
                                break

                            # Get distances to true source locs
                            errs = vtx.pos - event_pos

                            # Get reconstruced radius
                            r_recon = np.linalg.norm(vtx.pos)

                            # Get distance to true event location
                            vtx_dist = np.linalg.norm(errs)

                            recon[ii, ind, iy, :] = [
                                rad / 10, r_recon / 10, n_ph_total, errs[0],
                                errs[1], errs[2]
                            ]

                            # Fill TTree
                            run[0] = ind
                            pos[0] = iy
                            xpos_true[0] = event_pos[0]
                            ypos_true[0] = event_pos[1]
                            zpos_true[0] = event_pos[2]
                            xpos[0] = vtx.pos[0]
                            ypos[0] = vtx.pos[1]
                            zpos[0] = vtx.pos[2]
                            multiplicity[0] = len(vtcs)
                            photon_sim[0] = amount
                            photon_true[0] = n_ph_total
                            dist_event[0] = vtx_dist
                            #print run[0], pos[0], xpos_true[0], ypos_true[0], zpos_true[0], xpos[0], ypos[0], zpos[0], multiplicity[0], photon_sim[0], photon_true[0], dist_event[0]
                            #print iy, ind, r_recon, vtx_dist, float(n_ph_total)/float(amount), len(vtcs)
                            ttree.Fill()
    f1.Write()
    f1.Close()