示例#1
0
def sim_ev(cfg, particle, lg, energy):
    print 'Configuration loaded'
    if particle == None:
        sim, analyzer = setup.sim_setup(cfg,
                                        paths.get_calibration_file_name(
                                            cfg, cl),
                                        useGeant4=False)
        det_res = analyzer.det_res
        energy = int(energy * 8000)
        gun = setup.create_double_source_events(np.asarray([0, 0, 0]),
                                                np.asarray([0, 0, 0]), 0.01,
                                                energy / 2, energy / 2)
        #gun = kabamland2.gaussian_sphere(lg, 0.01, energy)
        #gun = gen_test(20,1,det_res)
    else:
        sim, analyzer = setup.sim_setup(cfg,
                                        paths.get_calibration_file_name(
                                            cfg, cl),
                                        useGeant4=True)
        det_res = analyzer.det_res
        gun = vertex.particle_gun([particle], vertex.constant(lg),
                                  vertex.isotropic(),
                                  vertex.flat(energy * 0.999, energy * 1.001))
    for ev in sim.simulate(gun,
                           keep_photons_beg=True,
                           keep_photons_end=True,
                           run_daq=False,
                           max_steps=100):
        vert = ev.photons_beg.pos
        tracks, arr_bin = analyzer.generate_tracks(ev,
                                                   qe=(1. / 3.),
                                                   heat_map=True)
        pixel_loc = det_res.pmt_bin_to_position(arr_bin)
    return vert, tracks, pixel_loc, det_res, arr_bin
示例#2
0
def gen_ev(sample,cfg,particle,energy,i_r,o_r):
	seed_loc = 'r%i-%i'%(i_r,o_r)
	data_file_dir = paths.get_data_file_path(cfg.config_name)
	if not os.path.exists(data_file_dir):
		os.makedirs(data_file_dir)
        fname = data_file_dir+seed_loc+'_'+str(energy)+particle+'_'+'sim.h5'
	sim,analyzer = utilities.sim_setup(cfg, paths.get_calibration_file_name(cfg.config_name), useGeant4=True)
	print 'configuration loaded'
	location = utilities.sph_scatter(sample,i_r*1000,o_r*1000)
	arr_tr, arr_depo = [],[]
	with h5py.File(fname,'w') as f:
		first = True
		for lg in location:
			gun = vertex.particle_gun([particle], vertex.constant(lg), vertex.isotropic(), vertex.flat(float(energy) * 0.999, float(energy) * 1.001))
			for ev in sim.simulate(gun,keep_photons_beg=True, keep_photons_end=True, run_daq=False, max_steps=100):
				vert = ev.photons_beg.pos
				tracks = analyzer.generate_tracks(ev,qe=(1./3.))
			if first:
				en_depo = f.create_dataset('en_depo',maxshape=(None,3),data=vert,chunks=True)
				coord = f.create_dataset('coord',maxshape=(2,None,3),data=[tracks.hit_pos.T, tracks.means.T],chunks=True)
				uncert = f.create_dataset('sigma',maxshape=(None,),data=tracks.sigmas,chunks=True)
				f.create_dataset('r_lens',data=tracks.lens_rad)
			else:
				en_depo.resize(en_depo.shape[0]+vert.shape[0], axis=0)
				en_depo[-vert.shape[0]:,:] = vert
				coord.resize(coord.shape[1]+tracks.means.shape[1], axis=1)
				coord[:,-tracks.means.shape[1]:,:] = [tracks.hit_pos.T, tracks.means.T]
				uncert.resize(uncert.shape[0]+tracks.sigmas.shape[0], axis=0)
				uncert[-tracks.sigmas.shape[0]:] = tracks.sigmas
			arr_depo.append(en_depo.shape[0])
			arr_tr.append(uncert.shape[0])
			first = False
		f.create_dataset('idx_tr',data=arr_tr)
		f.create_dataset('idx_depo',data=arr_depo)
示例#3
0
def proj(config_name, cl):
    in_file = paths.get_calibration_file_name(config_name, cl)
    config = detectorconfig.get_detector_config(config_name)
    det_res = dr.DetectorResponseGaussAngle(config, 10, 10, 10, in_file)
    n_lens = det_res.n_lens_sys
    n_pmts_per_surf = det_res.n_pmts_per_surf
    lns_center = det_res.lens_centers
    means = (det_res.means).T
    sigmas = det_res.sigmas
    px_lens_means = means.reshape((n_lens, n_pmts_per_surf, 3))
    px_lens_sigmas = sigmas.reshape((n_lens, n_pmts_per_surf))
    u_dir = np.cross(lns_center, [0, 0, 1])
    mask = np.all(u_dir == 0, axis=1)
    u_dir[mask] = np.cross(lns_center[mask], [0, 1, 0])
    u_dir = normalize(u_dir, 1)
    v_dir = normalize(np.cross(lns_center, u_dir), 1)
    u_proj = np.einsum('ijk,ik->ij', px_lens_means, u_dir)
    v_proj = np.einsum('ijk,ik->ij', px_lens_means, v_dir)
    return px_lens_means, px_lens_sigmas, u_proj, v_proj
示例#4
0
    def __init__(self, cfg, gun, fov, qe=1.0/3.0):
        self._cfg = cfg
        self.u_vers = None
        self.v_vers = None
        self.b_dir = None
        self._fov = fov

        if type(gun).__name__ == 'generator': g4 = True
        elif type(gun).__name__ == 'Photons': g4 = False

        sim, analyzer = setup.sim_setup(self._cfg,paths.get_calibration_file_name(self._cfg.config_name),useGeant4=g4)
        self._det_res = analyzer.det_res

        for ev in sim.simulate(gun,keep_photons_beg=True, keep_photons_end=True, run_daq=False, max_steps=100):
            _,self._arr_bin,detected = analyzer.generate_tracks(ev,qe,heat_map=True,detec=True)

        self.u_vers = config_stat.normalize(np.cross(np.random.rand(self._det_res.n_lens_sys,3),self._det_res.lens_centers),1)
        self.v_vers = config_stat.normalize(np.cross(self.u_vers,self._det_res.lens_centers),1)
        self.b_dir = analyzer.photons_beg_dir[detected]
        self._lns_index = self._arr_bin/self._det_res.n_pmts_per_surf
示例#5
0

def ring_return(arr_bin, ring):
    ring_arr = np.zeros((arr_bin.shape))
    for i, px in enumerate(arr_bin):
        ring_th = px / np.cumsum(ring)
        try:
            ring_arr[i] = np.where(ring_th == 0)[-1][0]
        except IndexError:
            ring_arr[i] = 0
    return ring_arr.astype(int)


cfg = detectorconfig.get_detector_config('cfSam1_l200_p107600_b4_e10')
sim, analyzer = setup.sim_setup(cfg,
                                paths.get_calibration_file_name(
                                    cfg.config_name),
                                useGeant4=False)
det_res = analyzer.det_res
pmt_center = det_res.pmt_bin_to_position(np.arange(det_res.n_pmts_per_surf))
l_c = det_res.lens_centers[0]
amount = 2000
l_r = det_res.lens_rad
norm_dir = np.cross(np.random.rand(3), l_c)
u_vers = norm_dir / np.linalg.norm(norm_dir)
v_vers = np.cross(u_vers, l_c / np.linalg.norm(l_c))
u_pmt = np.einsum('ij,j->i', pmt_center, u_vers)
v_pmt = np.einsum('ij,j->i', pmt_center, v_vers)
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(u_pmt, v_pmt, s=0.5, c='black')
sample = 15
off_center = np.einsum(
示例#6
0
        arr_sgm.extend(sigmas[mask_bool])
        arr_pos.extend(recon_pos[mask_bool])
    if ofst.shape[0] & 0x1: pass  #condition removed if degeneracy is kept
    else:
        dist, sigmas, recon_pos = roll_funct(ofst, drct, sgm, half, half=True)
        mask_bool = (dist != 0) & (dist < 0.15) & (np.linalg.norm(
            recon_pos, axis=1) < 700)
        arr_dist.extend(dist[mask_bool])
        arr_sgm.extend(sigmas[mask_bool])
    return np.asarray(arr_dist), (np.asarray(arr_sgm) +
                                  dim_len), np.asarray(arr_pos)


cfg = 'cfSam1_K200_8_small'
sim, analyzer = setup.sim_setup(cfg,
                                paths.get_calibration_file_name(cfg),
                                useGeant4=True)
print 'Configuration loaded'
lg = [0, 0, 0]
energy = 2.0
dct = {}
for i in xrange(1):
    n_ph, s_coord = [], []
    particle = np.random.choice(['neutron', 'neutron'])
    vtx, trx = sim_ev(particle, lg, energy)
    for vx in vtx:
        try:
            n_ph.append(vtx[vx]['child_processes']['Scintillation'])
            s_coord.append(vtx[vx]['position'])
        except KeyError:
            pass
示例#7
0
def simulate_and_calibrate(config,
                           build_only=False,
                           force=False,
                           fast_calibration=True):
    config_name = config.config_name
    if (not force) and os.path.isfile(
            paths.get_calibration_file_name(config_name)):
        logger.info('Found calibration file: %s' %
                    paths.get_calibration_file_name(config_name))
    else:
        logger.info('Failed to find calibration file: ' +
                    paths.get_calibration_file_name(config_name))
        logger.info('==== Step 1: Setting up the detector ====')
        photons_file_base = 'sim-' + config_name + '_100million'
        photons_file_full_path_base = paths.detector_calibration_path + photons_file_base
        if force or (
                not (os.path.exists(photons_file_full_path_base + '.root')
                     or os.path.exists(photons_file_full_path_base + '.h5'))):
            if force:
                logger.info('Forcing detector build')
            logger.info('Starting to load/build: %s' % config_name)
            g4_detector_parameters = G4DetectorParameters(
                orb_radius=7., world_material='G4_Galactic')
            kabamland = utilities.load_or_build_detector(
                config,
                lm.create_scintillation_material(),
                g4_detector_parameters=g4_detector_parameters,
                force_build=force)
            logger.warning('=== Detector was loaded/built')
            if build_only:
                return
            logger.info('==== Simulating photons: %s  ====' %
                        photons_file_base)
            _full_detector_simulation(config,
                                      kabamland,
                                      100000,
                                      photons_file_base,
                                      datadir=paths.detector_calibration_path)
            logger.warning('==== Simulation complete')
            simulation_file = photons_file_base + '.h5'

        elif os.path.exists(
                photons_file_full_path_base + '.h5'
        ):  # TODO: The double if's and constantly adding extensions needs to be reworked
            simulation_file = photons_file_base + '.h5'
        else:  # Fall back to root
            simulation_file = photons_file_base + '.root'
        logger.warning('==== Found/created photons file: %s ====' %
                       simulation_file)

        if not build_only:
            logger.info("==== Step 2: Calibrating  ====")
            _calibrate(
                config,
                simulation_file,
                paths.get_calibration_file_name_base_without_path(config_name),
                method="GaussAngle",
                nevents=10000,
                datadir=paths.detector_calibration_path,
                fast_calibration=fast_calibration)
            #os.remove(photons_file)  # Would need to remove both
            logger.warning(
                '==== Calibration complete: %s %s ====' %
                (config_name, 'fast' if fast_calibration else 'slow'))
示例#8
0
def fire_g4_particles(sample_count,
                      config,
                      particle,
                      energy,
                      inner_radius,
                      outer_radius,
                      h5_file,
                      location=None,
                      momentum=None,
                      di_file_base=None,
                      qe=None):
    from chroma.generator import vertex

    config_name = config.config_name
    sim, analyzer = sim_setup(config,
                              paths.get_calibration_file_name(config_name),
                              useGeant4=True,
                              geant4_processes=1,
                              no_gpu=False)
    #analyzer.det_res.is_calibrated=False    # Temporary to test AVF with actual photon angles vs. calibration angles

    logger.info('Configuration:\t%s' % config_name)
    logger.info('Particle:\t\t%s ' % particle)
    logger.info('Energy:\t\t%d' % energy)
    logger.info('Sim count:\t\t%d' % sample_count)
    logger.info('File:\t\t%s' % h5_file)

    if location is None:  # Location is a flag
        loc_array = sph_scatter(sample_count, inner_radius * 1000,
                                outer_radius * 1000)
    else:
        loc_array = [location]

    with h5py.File(h5_file, 'w') as f:
        first = True
        logger.info('Running locations:\t%d' % len(loc_array))
        for i, lg in enumerate(loc_array):
            logger.info('Location:\t\t%s' % str(lg))
            if location is None:
                gun = vertex.particle_gun([particle], vertex.constant(lg),
                                          vertex.isotropic(),
                                          vertex.flat(
                                              float(energy) * 0.999,
                                              float(energy) * 1.001))
            else:
                gun = vertex.particle_gun(
                    [particle], vertex.constant(lg), vertex.constant(momentum),
                    vertex.constant(energy)
                )  # TODO: AWS seems to require: vertex.constant(np.array(momentum))

            events = sim.simulate(gun,
                                  keep_photons_beg=True,
                                  keep_photons_end=True,
                                  run_daq=False,
                                  max_steps=100)
            for ev in events:  # Note: There is really only ever one event because we enumerate loc_array above
                vert = ev.photons_beg.pos
                tracks = analyzer.generate_tracks(ev, qe=qe)
                write_h5_reverse_track_file_event(f, vert, tracks, first)
                first = False

                #vertices = utilities.AVF_analyze_event(analyzer, ev)
                #utilities.plot_vertices(ev.photons_beg.track_tree, 'AVF plot', reconstructed_vertices=vertices)
                if di_file_base is not None:
                    gun_specs = build_gun_specs(particle, lg, None, energy)
                    di_file = DIEventFile(config_name, gun_specs,
                                          ev.photons_beg.track_tree, tracks,
                                          ev.photons_beg, ev)
                    di_file.write(di_file_base + '_' + str(i) + '.h5')

            logger.info('Photons detected:\t%s' % str(tracks.sigmas.shape[0]))
            logger.info('============')
示例#9
0
        calibrated_simulation = True
        if event.simulation_params is not None and 'calibrated' in event.simulation_params:
            calibrated_simulation = event.simulation_params['calibrated']
            logger.info(
                '=== Simulation event used calibrated detector: %s ===' %
                str(calibrated_simulation))
        else:
            logger.info('=== No calibration flag in event file ===')
            logger.info('Photons in file: %d' %
                        len(event.full_event.photons_end))

        config = detectorconfig.get_detector_config(
            event.config_name)  # Cross check UUID

        if calibrated_simulation:
            cal_file = paths.get_calibration_file_name(event.config_name)
            logger.info('Calibration file: ' + cal_file)
            det_res = DetectorResponseGaussAngle.DetectorResponseGaussAngle(
                config, 10, 10, 10, cal_file)  # What are the 10s??
        else:
            det_res = DetectorResponseGaussAngle.DetectorResponseGaussAngle(
                config, 10, 10, 10)  # What are the 10s??

        logger.info('Tracks in file: %d' % len(event.tracks))
        analyzer = EventAnalyzer.EventAnalyzer(det_res)
        # analyzer.plot_tracks(event.tracks)
        logger.info('=== Analyzing tracks from event tracks in file ===')
        vertices_from_original_run = AVF_analyze_tracks(analyzer,
                                                        event.tracks,
                                                        debug=True)
示例#10
0
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('cfg', help='provide configuration')
    args = parser.parse_args()
    cfg = args.cfg
    conf_par = dc.configdict(cfg)
    sys_per_face = (conf_par.base * (conf_par.base + 1)) / 2
    sel_len = np.random.choice(sys_per_face, 3, replace=False)
    heat = []
    g4 = True
    sigma = 0.01
    amount = 1000000
    energy = 2
    #ix = 4
    sim, analyzer = gs.sim_setup(cfg, paths.get_calibration_file_name(cfg))
    pmts_per_surf = analyzer.det_res.n_pmts_per_surf
    lens_center = analyzer.det_res.lens_centers[:sys_per_face]
    dir_to_lens = np.mean(lens_center, axis=0)
    dir_to_lens_n = dir_to_lens / np.linalg.norm(dir_to_lens)
    off_ax = gs.sph_scatter(1, in_shell=0,
                            out_shell=1000).T  #2000*rand_perp(dir_to_lens_n)
    if np.shape(off_ax)[1] == 1:
        off_ax = np.reshape(off_ax, (1, 3))
    else:
        pass
    for lg in off_ax:
        if not g4:
            gun = gaussian_sphere(lg, sigma, amount)
        else:
            gun = vertex.particle_gun(['e-', 'gamma'], vertex.constant(lg),