def test_adc_samples(): seen_at_least_one_event = False # testing on 10MB_part, so expecting EOF Error here with pytest.raises(EOFError): for z, e in zip(SimTelFile(TEST_FILE_PATH), SimTelFile(TEST_FILE_PATH_NORMAL)): for tel_id in e['telescope_events']: try: zas = z['telescope_events'][tel_id]['adc_samples'] eas = e['telescope_events'][tel_id]['adc_samples'] survivors = (zas != 0).all(axis=-1) assert survivors.sum() > 0 assert np.array_equal(zas[survivors], eas[survivors]) seen_at_least_one_event = True except KeyError as exc: print('event:', e['event_id'], 'tel:', tel_id, 'KeyError:', exc) assert seen_at_least_one_event
def test_adc_sums(): pyhessio = pytest.importorskip("pyhessio") with pyhessio.open_hessio(TEST_FILE_PATH) as hessio_file: eventstream = hessio_file.move_to_next_event() for EE, HE in zip(SimTelFile(TEST_FILE_PATH), eventstream): EE_tel_ids = sorted(EE['telescope_events'].keys()) HE_tel_ids = sorted(hessio_file.get_teldata_list()) assert EE_tel_ids == HE_tel_ids for tel_id in HE_tel_ids: HE_adc_sum = hessio_file.get_adc_sum(tel_id) EE_adc_sum = EE['telescope_events'][tel_id]['adc_sums'] assert np.array_equal(HE_adc_sum, EE_adc_sum)
def __init__( self, path: str, disable_remapping: bool = False, only_triggered_events: bool = False, n_events: int = None, ): """ Read Photoelectron arrays directly from simtelarray files Parameters ---------- path : str Path to the simtel file disable_remapping : bool Disables the remapping of the pixels to the sstcam-simulation pixel mapping only_triggered_events : bool Only read events which caused a telescope trigger n_events : int Number of telescope events to process """ self._file = SimTelFile(path) self._disable_remapping = disable_remapping self._only_triggered_events = only_triggered_events self._n_events = n_events self.n_pixels = 2048 self._camera_settings = {} self._pixel_remap = {} mapping = SSTCameraMapping() for telid, tel in self._file.telescope_descriptions.items(): camera_settings = tel['camera_settings'] self._camera_settings[telid] = camera_settings self._pixel_remap[telid] = get_pixel_remap( camera_settings['pixel_x'], camera_settings['pixel_y'], mapping.pixel)
import numpy as np from matplotlib import colors, cm, pyplot as plt from eventio import SimTelFile from ctapipe.io import SimTelEventSource from ctapipe.visualization import CameraDisplay bad_pixels = {'color': 'black', 'alpha': 0.1} cw = cm.coolwarm cw.set_bad(**bad_pixels) vi = cm.viridis vi.set_bad(**bad_pixels) p = "build/simtel-output.zst" f = SimTelFile(p) s = SimTelEventSource(p) geom = s.subarray.tel[1].camera.geometry fig, (ax_im, ax_t) = plt.subplots(ncols=2, figsize=(8, 4)) disp_im = CameraDisplay(geom, ax=ax_im, cmap=vi) disp_im.add_colorbar() disp_t = CameraDisplay(geom, ax=ax_t, cmap=cw) disp_t.add_colorbar() fig.tight_layout() fig.show() def plot(pe): image = pe['photoelectrons']
from eventio import SimTelFile import numpy as np input_path = "build/simtel-output.zst" f = SimTelFile(input_path) tel = f.telescope_descriptions[1] cam = tel['camera_settings'] def test_focal_length(): assert np.isclose(cam['focal_length'], [4.889], atol=0.01) def test_n_pixels(): assert cam['n_pixels'] == 1440
mpl_camera.PIXEL_EPSILON = 0 path = 'build/simtel-output.zst' # just to directly get the cam geom subarray = SimTelEventSource(input_url=path).subarray geom = subarray.tel[1].camera.geometry fig, ax = plt.subplots() im_disp = CameraDisplay(geom, ax=ax) fig.show() im_disp.add_colorbar() for e in SimTelFile(path).iter_mc_events(): true_pe = e['photoelectrons'].get(0) if true_pe is not None: mc_shower = e['mc_shower'] energy = mc_shower['energy'] event_id = e['event_id'] pe = true_pe['photoelectrons'] time = np.empty(1440) time[true_pe['pixel_id']] = true_pe['time'] max_pe = int(np.max(pe)) im_disp.axes.set_title(f'{event_id}: {energy:.2f} TeV') im_disp.image = pe
# coding: utf-8 from ctapipe.visualization import CameraDisplay from ctapipe.instrument import CameraGeometry from eventio import SimTelFile import astropy.units as u import numpy as np import matplotlib.pyplot as plt f = SimTelFile('tests/resources/gamma_20deg_0deg_run103___cta-prod4-sst-astri_desert-2150m-Paranal-sst-astri.simtel.gz') cam = f.telescope_descriptions[1]['camera_settings'] geom = CameraGeometry( 'astri', np.arange(cam['n_pixels']), cam['pixel_x'] * u.m, cam['pixel_y'] * u.m, cam['pixel_area']* u.m**2, pix_type='rectangular', ) it = iter(f) plt.ion() fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6)) d1 = CameraDisplay(geom, ax=ax1) d2 = CameraDisplay(geom, ax=ax2)
class SimtelReader: def __init__( self, path: str, disable_remapping: bool = False, only_triggered_events: bool = False, n_events: int = None, ): """ Read Photoelectron arrays directly from simtelarray files Parameters ---------- path : str Path to the simtel file disable_remapping : bool Disables the remapping of the pixels to the sstcam-simulation pixel mapping only_triggered_events : bool Only read events which caused a telescope trigger n_events : int Number of telescope events to process """ self._file = SimTelFile(path) self._disable_remapping = disable_remapping self._only_triggered_events = only_triggered_events self._n_events = n_events self.n_pixels = 2048 self._camera_settings = {} self._pixel_remap = {} mapping = SSTCameraMapping() for telid, tel in self._file.telescope_descriptions.items(): camera_settings = tel['camera_settings'] self._camera_settings[telid] = camera_settings self._pixel_remap[telid] = get_pixel_remap( camera_settings['pixel_x'], camera_settings['pixel_y'], mapping.pixel) @property def camera_settings(self): return self._camera_settings @property def pixel_remap(self): return self._pixel_remap def __iter__(self): n_events = 0 if self._only_triggered_events: it = self._file.iter_array_events() else: it = self._file.iter_mc_events() for iev, event in enumerate(it): if 'photoelectrons' not in event: continue photoelectrons = event['photoelectrons'] mc_shower = event['mc_shower'] mc_event = event['mc_event'] if self._only_triggered_events: tel_ids = event['telescope_events'].keys() else: tel_ids = np.array(list(photoelectrons.keys())) + 1 for tel_id in tel_ids: # Retrieve only SST Camera if self._camera_settings[tel_id]['n_pixels'] != self.n_pixels: continue n_events += 1 if self._n_events and n_events > self._n_events: return values = photoelectrons[tel_id - 1] metadata = dict(event_index=iev, event_id=event['event_id'], telescope_id=tel_id, n_photoelectrons=values['time'].size, energy=mc_shower["energy"], alt=mc_shower["altitude"], az=mc_shower["azimuth"], core_x=mc_event["xcore"], core_y=mc_event["ycore"], h_first_int=mc_shower["h_first_int"], x_max=mc_shower["xmax"], shower_primary_id=mc_shower["primary_id"]) pixel = values['pixel_id'] time = values['time'] charge = np.ones(pixel.size) # Shift photoelectron times to sensible reference time start_time = 30 # ns time = start_time + time - time.min() # Convert pixel mapping if not self._disable_remapping: pixel = self._pixel_remap[tel_id][pixel] yield Photoelectrons(pixel=pixel, time=time, charge=charge, metadata=metadata)
from eventio import SimTelFile from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('inputfile') parser.add_argument('-s', '--sort', default='cumtime') parser.add_argument('-l', '--limit', default=50, type=int) parser.add_argument('-t', '--telescopes') args = parser.parse_args() if args.telescopes: allowed_telescopes = set(map(int, args.telescopes.split(','))) print(allowed_telescopes) else: allowed_telescopes = None pr = cProfile.Profile() pr.enable() with SimTelFile(args.inputfile, allowed_telescopes=allowed_telescopes) as f: for e in f: # print(e['telescope_events'].keys()) pass pr.disable() s = StringIO() ps = pstats.Stats(pr, stream=s).sort_stats(args.sort) ps.print_stats(args.limit) print(s.getvalue())
import numpy as np from eventio import SimTelFile from matplotlib import pyplot as plt n_pixels = 10 p = "build/simtel-output.zst" s = SimTelFile(p) for event in s: if event['type'] == 'calibration': break adc_samples = event['telescope_events'][1]['adc_samples'] brightest_pixels = np.sum(adc_samples[0, :, :], axis=1).argsort()[::-1] fig, ax0 = plt.subplots(nrows=1) for i_pix in brightest_pixels[:n_pixels]: ax0.plot(adc_samples[0, i_pix, :], "-", label=f"{i_pix}") for i, ax in enumerate([ax0]): ax.set_title("ADC Samples of Laser (Calibration) Events") ax.set_xlabel("sample") ax.legend(title="pixel id") fig.tight_layout() fig.savefig("build/laser_waveforms.png")