def __draw_2d_correlation_map(self, event, correlation_map):
     fig4 = plt.figure(figsize=(4, 12))
     ax4_1 = fig4.add_subplot(311)
     d_0, z_0 = np.meshgrid(self.__distances_2d, self.__z_coordinates_2d)
     ax4_1.pcolor(d_0, z_0, np.max(correlation_map, axis=2).T)
     ax4_1.grid()
     theta_0, d_0 = np.meshgrid(self.__azimuths_2d, self.__distances_2d)
     ax4_2 = fig4.add_subplot(312, projection='polar')
     ax4_2.pcolor(theta_0, d_0, np.max(correlation_map, axis=1))
     ax4_2.grid()
     ax4_3 = fig4.add_subplot(313)
     theta_0, z_0 = np.meshgrid(self.__azimuths_2d, self.__z_coordinates_2d)
     ax4_3.pcolor(theta_0 / units.deg, z_0, np.max(correlation_map, axis=0))
     ax4_3.grid()
     sim_vertex = None
     for sim_shower in event.get_sim_showers():
         sim_vertex = sim_shower.get_parameter(shp.vertex)
         break
     if sim_vertex is not None:
         ax4_1.scatter([np.sqrt(sim_vertex[0]**2 + sim_vertex[1]**2)],
                       [sim_vertex[2]],
                       c='r',
                       alpha=.5,
                       marker='+')
         ax4_2.scatter([
             hp.cartesian_to_spherical(sim_vertex[0], sim_vertex[1],
                                       sim_vertex[2])[1]
         ], [np.sqrt(sim_vertex[0]**2 + sim_vertex[1]**2)],
                       c='r',
                       alpha=.5,
                       marker='+')
         ax4_3.scatter([
             hp.get_normalized_angle(
                 hp.cartesian_to_spherical(sim_vertex[0], sim_vertex[1],
                                           sim_vertex[2])[1]) / units.deg
         ], [(sim_vertex[2])],
                       c='r',
                       alpha=.5,
                       marker='+')
     ax4_1.set_xlabel('d [m]')
     ax4_1.set_ylabel('z [m]')
     ax4_3.set_xlabel(r'$\phi [^\circ]$')
     ax4_3.set_ylabel('z [m]')
     fig4.tight_layout()
     fig4.savefig('{}/{}_{}_2D_correlation_maps.png'.format(
         self.__debug_folder, event.get_run_number(), event.get_id()))
Ejemplo n.º 2
0
def calculate_polarization_vector(launch_vector, shower_axis):
    """ calculates the polarization vector in spherical coordinates (eR, eTheta, ePhi)
	"""
    polarization_direction = np.cross(launch_vector,
                                      np.cross(shower_axis, launch_vector))
    polarization_direction /= np.linalg.norm(polarization_direction)
    cs = cstrans.cstrafo(*hp.cartesian_to_spherical(*launch_vector))
    return cs.transform_from_ground_to_onsky(polarization_direction)
Ejemplo n.º 3
0
 def find_receiving_zenith(self, station, ray_type, channel_id):
     solution_types = {1: 'direct',
                       2: 'refracted',
                       3: 'reflected'}
     nu_vertex_2D = station.get_parameter(stnp.vertex_2D_fit)
     nu_vertex = [nu_vertex_2D[0], 0, nu_vertex_2D[1]]
     ray_tracer = NuRadioMC.SignalProp.analyticraytracing.ray_tracing(
         nu_vertex,
         self.__detector.get_relative_position(station.get_id(), channel_id) + self.__detector.get_absolute_position(station.get_id()),
         NuRadioMC.utilities.medium.get_ice_model('greenland_simple')
     )
     ray_tracer.find_solutions()
     for i_solution, solution in enumerate(ray_tracer.get_results()):
         if solution_types[ray_tracer.get_solution_type(i_solution)] == ray_type:
             receive_vector = ray_tracer.get_receive_vector(i_solution)
             receive_zenith = hp.cartesian_to_spherical(receive_vector[0], receive_vector[1], receive_vector[2])[0]
             travel_time = ray_tracer.get_travel_time(i_solution)
             return receive_zenith, travel_time
     return None, None
Ejemplo n.º 4
0
def dump(filename):
    print(f"!!!!!!!!!!!! dumping relevant file content of {filename}:!!!!!!!!!!!!!!!")
    fin = h5py.File(filename, 'r')
    stations = []
    for key in fin.keys():
        if(key.startswith("station_")):
            stations.append(key)
    event_group_ids = np.array(fin['event_group_ids'])
    for iE, evt_gid in enumerate(event_group_ids):
        t = "index, "
        for key in keys_event:
            t += f"{key}, "
        print(t)
        t = f"{iE} "
        for key in keys_event:
            t += f"{fin[key][iE]} "
        print(t)
        t = "stationid, channelid, rayid, "
        for key in station_keys:
            t += f"{key}, "
        for key in station_keys_3dim:
            t += f"{key}, "
        t += f" zen, az"
        print(t)
        for station in stations:
            if not 'ray_tracing_C0' in station:
                print(f'{station} has not entries')
                continue

            nCh, nR = np.array(fin[station]['ray_tracing_C0'][iE]).shape
            for iCh in range(nCh):
                for iR in range(nR):
                    t = f"\t{station} {iCh} {iR}: "
                    for key in station_keys:
                        t += f"{fin[station][key][iE][iCh][iR]:.9g} "
                    for key in station_keys_3dim:
                        t += "("
                        for iD in range(3):
                            t += f"{fin[station][key][iE][iCh][iR][iD]:.5g},"
                        t += ") "
                    zen, az = hp.cartesian_to_spherical(*np.array(fin[station]["receive_vectors"][iE][iCh][iR]))
                    t += f" {zen/units.deg:.2f} {az/units.deg:.2f}"
                    print(t)
Ejemplo n.º 5
0
	def run_nu_kernel(self, frame):

		# we'll need an array of frequencies at which we'll calculate attens etc
		# declare it here so we don't wast time declaring it over and over again
		ff = np.fft.rfftfreq(self._n_samples, self._dt)

		# get the list of particles from the *thinned* mctree
		if 'I3MCTreeThin' not in frame:
			icetray.logging.log_fatal('Frame does not contain the thinned tree I3MCTreeThin \nPlease tray.AddModule(TreeThinner) first!')
		mctree = frame.Get('I3MCTreeThin')

		primary = mctree.primaries[0]
		num_particles = len(mctree)
		if num_particles == 1:
			icetray.logging.log_info("There are no children of the primary")

		# load the list of antennas
		antgeomap = self.antgeomap

		# for every particle, we create a map between the particle ID and the I3RadioMCSummary
		particle_radio_mc_map = icetradio.I3ParticleRadioMCSummaryMap()

		# now, we loop over every particle, and every antenna, and do ray tracing
		for particle in mctree:

			# skip the primary
			if particle == primary:
				continue

			# time of the vertex in nanoseconds
			vertex_time = particle.time

			# get the source (vertex) position, and move it into surface oriented coordinates
			source = particle.pos
			source = util_geo.convert_i3_to_global(source)
		
			# for this particle, we need a map between the particle id and the signal
			iceantenna_radio_mc_map = icetradio.I3IceAntennaRadioMCSummaryMap()

			# where it's GOING
			# in I3Position format (not simple numpy array)
			# so that we are uniform between shower_axis and launch_vector
			shower_axis = dataclasses.I3Position(particle.dir.x, particle.dir.y, particle.dir.z) 
			deposited_energy = particle.energy / icetray.I3Units.eV # in eV!
			shower_type = particle.type
			em_or_had = util_phys.pick_em_or_had(shower_type)
			if em_or_had is 'UDEF':
				icetray.logging.log_warn("A particle ({}) has an undefined type. Skipping it.".format(shower_type))
				continue

			n_index = self.ice.get_index_of_refraction(source)

			for iceantkey, g in antgeomap:

				# need a radio mc summary object
				radio_mc_summary = icetradio.I3RadioMCSummary()
				
				# get the target (antenna) position, and move it into surface oriented coordinates
				target = g.position
				target = util_geo.convert_i3_to_global(target)

				# do ray tracing
				record, attens = signal_prop.do_ray_tracing(
					propagator=self.propagator,
					ice_model=self.ice,
					attenuation_model=self._att_model,
					source=source,
					target=target,
					ff=ff,
					sampling_rate=self._sampling_rate
					)

				# store the ray trace record
				radio_mc_summary.ray_trace_record = record

				# now, do signals
				for iS in range(record.numSolutions):

					# the time this field arrives at the antenna is the sum
					# of the time of the vertex and the propagation time
					# this is a value in ns, so we have to convert to seconds
					# when we pass it to the signal generator
					arrival_time = vertex_time + record.solutions[iS].travelTime

					signal = signal_gen.generate_signal(
						deposited_energy=deposited_energy,
						shower_axis=shower_axis,
						em_or_had=em_or_had,
						launch_vector=record.solutions[iS].launchVector,
						distance=record.solutions[iS].pathLength,
						arrival_time=arrival_time / icetray.I3Units.s,
						n_index=n_index,
						attenuation_values=attens[iS],
						dt=self._dt,
						n_samples=self._n_samples,
						model=self._askaryan_model,
						seed=self._seed,
						)

					# convert the arrival information into a theta and phi for the signal
					local_recieve_vector = util_dataclasses.i3pos_to_np(record.solutions[iS].receiveVector)
					theta, phi = hp.cartesian_to_spherical(*local_recieve_vector)
					signal.arrival_theta = theta * icetray.I3Units.rad
					signal.arrival_phi = phi * icetray.I3Units.rad

					# finish filling out the signal container
					signal.sol_num = record.solutions[iS].solutionNumber
					signal.sol_type = record.solutions[iS].solutionType

					# append the signal
					radio_mc_summary.signals.append(signal)

				# now, put this radio mc summary into the map for this vertex
				iceantenna_radio_mc_map[iceantkey] = radio_mc_summary

			# now, for this particle, we store the map of radio truths
			particle_radio_mc_map[particle.id] = iceantenna_radio_mc_map

		# now, this gets stored in the frame
		if(len(particle_radio_mc_map)>0):
			# only store the frame if one of the daughter particles actually contributed
			frame.Put("ParticleRadioMCSummaryMap",particle_radio_mc_map)
Ejemplo n.º 6
0
            for i in range(flav.size):
                if (flav[i]):
                    receive_vectors = np.append(receive_vectors, [rvtemp[i]], axis=0)
                    weightstemp = np.append(weightstemp, weights[i])
#                    print("--------------------------")
#                    print(rvtemp[0])
#                    print("----------")
#                    print(receive_vectors[0])
#                    print("--------------------------")
            
            receive_vectors = np.delete(receive_vectors, 0, axis=0)
                        
            # receive_vectors = np.array(station['receive_vectors'])[triggered]
            # for all events, antennas and ray tracing solutions
            zeniths, azimuths = hp.cartesian_to_spherical(receive_vectors[:, :, :, 0].flatten(),
                                                          receive_vectors[:, :, :, 1].flatten(),
                                                          receive_vectors[:, :, :, 2].flatten())
            
            for i in range(len(azimuths)):
                azimuths[i] = hp.get_normalized_angle(azimuths[i])
                weights_matrix = np.outer(weightstemp, np.ones(np.prod(receive_vectors.shape[1:-1]))).flatten()
                mask = ~np.isnan(azimuths)  # exclude antennas with not ray tracing solution (or with just one ray tracing solution)
            
            fig, axs = php.get_histograms([zeniths[mask] / units.deg, azimuths[mask] / units.deg],
                                        bins=[np.arange(0, 181, 5), np.arange(0, 361, 45)],
                                        xlabels=['zenith [deg]', 'azimuth [deg]'],
                                        weights=weights_matrix[mask], stats=False)
       # axs[0].xaxis.set_ticks(np.arange(0, 181, 45))
            majorLocator = MultipleLocator(45)
            majorFormatter = FormatStrFormatter('%d')
            minorLocator = MultipleLocator(5)
Ejemplo n.º 7
0
ax.plot(x1[0], x1[2], 'ko')
for i, x in enumerate([x2, x3, x4, x5]):
    print('finding solutions for ', x)
    r = ray.ray_tracing(x1,x,ice)
    r.find_solutions()
    if(r.has_solution()):
        for iS in range(r.get_number_of_solutions()):
            ray_tracing_C0[i, iS] = r.get_results()[iS]['C0']
            ray_tracing_solution_type[i, iS] = r.get_solution_type(iS)
            print("     Solution %d, Type %d: "%(iS,ray_tracing_solution_type[i, iS]))
            R = r.get_path_length(iS)  # calculate path length
            T = r.get_travel_time(iS)  # calculate travel time
            print("     Ray Distance %.3f and Travel Time %.3f"%(R/units.m,T/units.ns))
            receive_vector = r.get_receive_vector(iS)
            receive_vectors[i, iS] = receive_vector
            zenith, azimuth = hp.cartesian_to_spherical(*receive_vector)
            print("     Receiving Zenith %.3f and Azimuth %.3f "%(zenith/units.deg, azimuth/units.deg))

            #to readout the actual trace, we have to flatten to 2D
            dX = x - x1
            dPhi = -np.arctan2(dX[1],dX[0])
            c,s = np.cos(dPhi), np.sin(dPhi)
            R = np.array(((c,-s,0),(s,c,0),(0,0,1)))
            X1r = x1
            X2r = np.dot(R, x-x1) + x1
            x1_2d = np.array([X1r[0],X1r[2]])
            x2_2d = np.array([X2r[0],X2r[2]])
            r_2d = ray.ray_tracing_2D(ice)
            yy,zz = r_2d.get_path(x1_2d,x2_2d,ray_tracing_C0[i, iS])
            ax.plot(yy, zz, '{}'.format(php.get_color_linestyle(i)), label='{} C0 = {:.4f}'.format(ray_tracing_solution_type[i,iS], ray_tracing_C0[i,iS]))
            ax.plot(x2_2d[0], x2_2d[1], '{}{}-'.format('d',php.get_color(i)))
Ejemplo n.º 8
0
            continue
#         if(d > -800):
#             continue

# calcualte expected angles
        r = ray.ray_tracing(pos_spice + np.array([0, 0, d]),
                            pos_SP1,
                            medium.southpole_simple(),
                            log_level=logging.WARNING)
        r.find_solutions()
        if (not r.has_solution()):
            continue

        results['depth'].append(d)
        rvec = r.get_receive_vector(0)
        zen, az = hp.cartesian_to_spherical(*rvec)
        az = hp.get_normalized_angle(az)
        results['exp'].append((zen, az))
        print("{} depth = {:.1f}m -> {:.2f} {:.2f} (solution type {})".format(
            t, d, zen / units.deg, az / units.deg, r.get_solution_type(0)))

        channelResampler.run(evt, station, det, 50 * units.GHz)
        channelBandPassFilter.run(evt,
                                  station,
                                  det,
                                  passband=[120 * units.MHz, 300 * units.MHz],
                                  filter_type='butterabs',
                                  order=10)
        channelBandPassFilter.run(evt,
                                  station,
                                  det,
    def __draw_search_zones(self, event, slope, offset, line_fit_d, line_fit_z,
                            min_z_offset, max_z_offset, i_max_d, i_max_z,
                            corr_mask_d, corr_mask_z, z_fit, i_max_theta,
                            theta_corr_mask, median_theta):
        fig5 = plt.figure(figsize=(8, 8))
        ax5_1_1 = fig5.add_subplot(221)
        ax5_1_1.grid()
        ax5_1_2 = fig5.add_subplot(222)
        ax5_1_2.grid()
        ax5_1_1.fill_between(
            self.__distances_2d,
            self.__distances_2d * slope + offset + 1.1 * max_z_offset,
            self.__distances_2d * slope + offset - 1.1 * min_z_offset,
            color='k',
            alpha=.2)
        ax5_1_1.scatter(self.__distances_2d[corr_mask_d],
                        self.__z_coordinates_2d[i_max_d][corr_mask_d])
        ax5_1_1.scatter(self.__distances_2d[~corr_mask_d],
                        self.__z_coordinates_2d[i_max_d][~corr_mask_d],
                        c='k',
                        alpha=.5)
        ax5_1_1.plot(self.__distances_2d,
                     self.__distances_2d * slope + offset,
                     color='k',
                     linestyle=':')
        ax5_1_1.fill_between(
            self.__distances_2d,
            self.__distances_2d * slope + offset + 1.1 * max_z_offset,
            self.__distances_2d * slope + offset - 1.1 * min_z_offset,
            color='k',
            alpha=.2)
        ax5_1_1.plot(self.__distances_2d,
                     self.__distances_2d * line_fit_d[0] + line_fit_d[1],
                     color='r',
                     linestyle=':')
        ax5_1_1.fill_between(self.__distances_2d,
                             self.__distances_2d * line_fit_d[0] +
                             line_fit_d[1] + 1.1 * max_z_offset,
                             self.__distances_2d * line_fit_d[0] +
                             line_fit_d[1] - 1.1 * min_z_offset,
                             color='r',
                             alpha=.2)
        ax5_1_2.scatter(self.__distances_2d[i_max_z][corr_mask_z],
                        self.__z_coordinates_2d[corr_mask_z])
        ax5_1_2.scatter(self.__distances_2d[i_max_z][~corr_mask_z],
                        self.__z_coordinates_2d[~corr_mask_z],
                        c='k',
                        alpha=.5)
        ax5_1_2.plot(self.__distances_2d,
                     self.__distances_2d * slope + offset,
                     color='k',
                     linestyle=':')
        ax5_1_2.plot(self.__distances_2d,
                     self.__distances_2d * line_fit_z[0] + line_fit_z[1],
                     color='r',
                     linestyle=':')
        ax5_1_2.fill_between(self.__distances_2d,
                             self.__distances_2d * line_fit_z[0] +
                             line_fit_z[1] + 1.1 * max_z_offset,
                             self.__distances_2d * line_fit_z[0] +
                             line_fit_z[1] - 1.1 * min_z_offset,
                             color='r',
                             alpha=.2)
        ax5_1_2.plot(self.__distances_2d,
                     self.__distances_2d * slope + offset,
                     color='k',
                     linestyle=':')
        ax5_1_2.fill_between(
            self.__distances_2d,
            self.__distances_2d * slope + offset + 1.1 * max_z_offset,
            self.__distances_2d * slope + offset - 1.1 * min_z_offset,
            color='k',
            alpha=.2)

        if z_fit:
            ax5_2 = fig5.add_subplot(2, 2, (3, 4))
            ax5_2.grid()
        else:
            ax5_2 = fig5.add_subplot(2, 2, (3, 4), projection='polar')
        if z_fit:
            ax5_2.scatter(self.__azimuths_2d[i_max_theta][theta_corr_mask],
                          np.abs(self.__z_coordinates_2d)[theta_corr_mask])
            ax5_2.scatter(self.__azimuths_2d[i_max_theta][~theta_corr_mask],
                          np.abs(self.__z_coordinates_2d)[~theta_corr_mask],
                          c='k',
                          alpha=.5)
            ax5_2.plot([median_theta, median_theta], [
                np.abs(self.__z_coordinates_2d[0]),
                np.abs(self.__z_coordinates_2d[-1])
            ],
                       color='k',
                       linestyle=':')
        else:
            ax5_2.scatter(self.__azimuths_2d[i_max_theta][theta_corr_mask],
                          self.__distances_2d[theta_corr_mask])
            ax5_2.scatter(self.__azimuths_2d[i_max_theta][~theta_corr_mask],
                          self.__distances_2d[~theta_corr_mask],
                          c='k',
                          alpha=.5)
            ax5_2.plot([median_theta, median_theta],
                       [self.__distances_2d[0], self.__distances_2d[-1]],
                       color='k',
                       linestyle=':')
        sim_vertex = None
        for sim_shower in event.get_sim_showers():
            sim_vertex = sim_shower.get_parameter(shp.vertex)
            break
        if sim_vertex is not None:
            ax5_1_1.axhline(sim_vertex[2], color='r', linestyle='--', alpha=.5)
            ax5_1_1.axvline(np.sqrt(sim_vertex[0]**2 + sim_vertex[1]**2),
                            color='r',
                            linestyle='--',
                            alpha=.5)
            ax5_1_2.axhline(sim_vertex[2], color='r', linestyle='--', alpha=.5)
            ax5_1_2.axvline(np.sqrt(sim_vertex[0]**2 + sim_vertex[1]**2),
                            color='r',
                            linestyle='--',
                            alpha=.5)
            ax5_2.scatter([
                hp.cartesian_to_spherical(sim_vertex[0], sim_vertex[1],
                                          sim_vertex[2])[1]
            ], [np.sqrt(sim_vertex[0]**2 + sim_vertex[1]**2)],
                          c='r',
                          alpha=.5,
                          marker='+')
        ax5_1_1.set_xlabel('d [m]')
        ax5_1_2.set_xlabel('d [m]')
        ax5_1_1.set_ylabel('z [m]')
        ax5_1_2.set_ylabel('z [m]')
        if z_fit:
            ax5_2.set_xlabel(r'$\phi [^\circ]$')
            ax5_2.set_ylabel('|z| [m]')
        fig5.tight_layout()
        fig5.savefig('{}/{}_{}_search_zones.png'.format(
            self.__debug_folder, event.get_run_number(), event.get_id()))