def display_event(event, geoms): """an extremely inefficient display. It creates new instances of CameraDisplay for every event and every camera, and also new axes for each event. It's hacked, but it works """ print("Displaying... please wait (this is an inefficient implementation)") global fig ntels = len(event.r0.tels_with_data) fig.clear() plt.suptitle("EVENT {}".format(event.r0.event_id)) disps = [] for ii, tel_id in enumerate(event.r0.tels_with_data): print("\t draw cam {}...".format(tel_id)) nn = int(ceil(sqrt(ntels))) ax = plt.subplot(nn, nn, ii + 1) x, y = event.inst.pixel_pos[tel_id] geom = geoms[tel_id] disp = CameraDisplay(geom, ax=ax, title="CT{0}".format(tel_id)) disp.pixels.set_antialiaseds(False) disp.autoupdate = False disp.cmap = 'afmhot' chan = 0 signals = event.r0.tel[tel_id].adc_sums[chan].astype(float) signals -= signals.mean() disp.image = signals disp.set_limits_percent(95) disp.add_colorbar() disps.append(disp) return disps
def Simple_CamPlot(image, geom, pix_ids, title=""): disp1 = CameraDisplay(geom, title=title) disp1.add_colorbar() disp1.set_limits_minmax(zmin=image.min() * 0.98, zmax=image.max() * 1.02) blankam1 = np.zeros(1855) blankam1[pix_ids] = image disp1.image = blankam1 plt.show()
def remove_star_and_run(self, list_of_file, max_events, noise_pixels_id_list): signal_place_after_clean = np.zeros(1855) sum_ped_ev = 0 alive_ped_ev = 0 for input_file in list_of_file: print(input_file) r0_r1_calibrator = LSTR0Corrections(pedestal_path=None, r1_sample_start=3, r1_sample_end=39) reader = LSTEventSource(input_url=input_file, max_events=max_events) for i, ev in enumerate(reader): r0_r1_calibrator.calibrate(ev) if i % 10000 == 0: print(ev.r0.event_id) if ev.lst.tel[1].evt.tib_masked_trigger == 32: sum_ped_ev += 1 self.r1_dl1_calibrator(ev) img = ev.dl1.tel[1].image img[noise_pixels_id_list] = 0 geom = ev.inst.subarray.tel[1].camera clean = tailcuts_clean(geom, img, **self.cleaning_parameters) cleaned = img.copy() cleaned[~clean] = 0.0 signal_place_after_clean[np.where(clean == True)] += 1 if np.sum(cleaned > 0) > 0: alive_ped_ev += 1 fig, ax = plt.subplots(figsize=(10, 8)) geom = ev.inst.subarray.tel[1].camera disp0 = CameraDisplay(geom, ax=ax) disp0.image = signal_place_after_clean / sum_ped_ev disp0.highlight_pixels(noise_pixels_id_list, linewidth=3) disp0.add_colorbar(ax=ax, label="N times signal remain after cleaning [%]") disp0.cmap = 'gnuplot2' ax.set_title("{} \n {}/{}".format( input_file.split("/")[-1][8:21], alive_ped_ev, sum_ped_ev), fontsize=25) print("{}/{}".format(alive_ped_ev, sum_ped_ev)) ax.set_xlabel(" ") ax.set_ylabel(" ") plt.tight_layout() plt.show()
def plot_event(event, reco, pdf): cams = [ event.inst.subarray.tels[i].camera for i in event.r0.tels_with_data ] cams = [c for c in cams if c.cam_id in allowed_cameras] n_tels = len(cams) p = 1 params = {} pointing_azimuth = {} pointing_altitude = {} for telescope_id, dl1 in event.dl1.tel.items(): camera = event.inst.subarray.tels[telescope_id].camera if camera.cam_id not in allowed_cameras: continue nn = int(np.ceil(np.sqrt(n_tels))) ax = plt.subplot(nn, nn, p) p += 1 boundary_thresh, picture_thresh = cleaning_level[camera.cam_id] mask = tailcuts_clean(camera, dl1.image[0], boundary_thresh=boundary_thresh, picture_thresh=picture_thresh, min_number_picture_neighbors=1) # if mask.sum() < 3: # only two pixel remaining. No luck anyways. continue h = hillas_parameters( camera[mask], dl1.image[0, mask], ) disp = CameraDisplay(camera, ax=ax, title="CT{0}".format(telescope_id)) disp.pixels.set_antialiaseds(False) disp.autoupdate = False disp.add_colorbar() # Show the camera image and overlay Hillas ellipse and clean pixels disp.image = dl1.image[0] disp.cmap = 'viridis' disp.highlight_pixels(mask, color='white') disp.overlay_moments(h, color='red', linewidth=5) pointing_azimuth[ telescope_id] = event.mc.tel[telescope_id].azimuth_raw * u.rad pointing_altitude[ telescope_id] = event.mc.tel[telescope_id].altitude_raw * u.rad params[telescope_id] = h return reco.predict(params, event.inst, pointing_altitude, pointing_azimuth)
def create(self, df, geom): count = np.stack(df['tc']).sum(0) camera = CameraDisplay(geom, ax=self.ax, image=count, cmap='viridis') camera.add_colorbar() camera.colorbar.set_label("Count") self.ax.set_title("Pixel Hits after Tailcuts For Run") self.ax.axis('off')
def plot(self, df, n_frames, geom, output_path, title): camera = CameraDisplay(geom, ax=self.ax_camera, image=np.zeros(2048), cmap='viridis') camera.add_colorbar() camera.colorbar.set_label("Amplitude (p.e.)") self.fig.suptitle(title + " - " + self.description) # Create animation interval = 25 # Fast # interval = 100 # Slow def animation_generator(): for index, row in df.iterrows(): event_id = row['event_id'] images = row['images'] tc = row['tc'] # max_ = np.percentile(event.max(), 60) # camera.image = image # camera.set_limits_minmax(min_, max_) tc_2d = np.ones(images.shape, dtype=np.bool) * tc[None, :] cleaned_events = np.ma.masked_array(images, mask=~tc_2d) max_ = cleaned_events.max() # np.percentile(dl1, 99.9) if max_ < 6: max_ = 6 min_ = np.percentile(images, 0.1) camera.set_limits_minmax(min_, max_) self.ax_camera.set_title("Event: {}".format(event_id)) for s in images: camera.image = s yield source = animation_generator() self.log.info("Output: {}".format(output_path)) with tqdm(total=n_frames, desc="Creating animation") as pbar: def animate(_): pbar.update(1) next(source) anim = animation.FuncAnimation(self.fig, animate, frames=n_frames - 1, interval=interval) anim.save(output_path) self.log.info("Created animation: {}".format(output_path))
def create(self, image, coords, title): camera = CameraDisplay(coords.geom, ax=self.ax, image=image, cmap='viridis') camera.add_colorbar() camera.colorbar.set_label("Residual RMS (p.e.)", fontsize=20) camera.image = image camera.colorbar.ax.tick_params(labelsize=30) self.fig.suptitle("Jupiter RMS ON-OFF") self.ax.set_title(title) self.ax.axis('off')
def create(self, image, label, title): camera = CameraDisplay(get_geometry(), ax=self.ax, image=image, cmap='viridis') camera.add_colorbar() camera.colorbar.set_label(label, fontsize=20) camera.image = image camera.colorbar.ax.tick_params(labelsize=30) # self.ax.set_title(title) self.ax.axis('off')
def plot_muon_event(ax, geom, image, centroid, ringrad_camcoord, ringrad_inner, ringrad_outer, event_id): """ Function to plot single muon events Parameters ---------- image ax : `matplotlib.pyplot.axis` geom : CameraGeometry centroid : `float` Centroid of the muon ring ringrad_camcoord : `float` Ring radius in camera coordinates ringrad_inner : `float` Inner ring radius in camera coordinates ringrad_outer : `float` Outer ring radius in camera coordinates event_id : `int` ID of the analyzed event Returns ------- ax : `matplotlib.pyplot.axis` """ disp0 = CameraDisplay(geom, ax=ax) disp0.image = image disp0.cmap = 'viridis' disp0.add_colorbar(ax=ax) disp0.add_ellipse(centroid, ringrad_camcoord.value, ringrad_camcoord.value, 0., 0., color="red") disp0.add_ellipse(centroid, ringrad_inner.value, ringrad_inner.value, 0., 0., color="magenta") disp0.add_ellipse(centroid, ringrad_outer.value, ringrad_outer.value, 0., 0., color="magenta") ax.set_title(f"Event {event_id}") return ax
def Simple_AxCamPlot(image, geom, pix_ids, title=""): f, ax = plt.subplots() disp1 = CameraDisplay(geom, title=title, ax=ax) disp1.add_colorbar(ax=ax) # ~ disp1.set_limits_minmax(zmin=image.min()*0.98,zmax=image.max()*1.02) disp1.set_limits_minmax(zmin=image.min(), zmax=image.max()) blankam1 = np.zeros(1855) blankam1[pix_ids] = image disp1.image = blankam1 ax.set_ylim(-0.65, 0.65) ax.set_xlim(-0.6, 0.6) return ax
def test_pixel_shapes(pix_type): """ test CameraDisplay functionality """ from ..mpl_camera import CameraDisplay geom = CameraGeometry.from_name("LSTCam") geom.pix_type = pix_type disp = CameraDisplay(geom) image = np.random.normal(size=len(geom.pix_x)) disp.image = image disp.add_colorbar() disp.highlight_pixels([1, 2, 3, 4, 5]) disp.add_ellipse(centroid=(0, 0), width=0.1, length=0.1, angle=0.1)
def start(self): # n_events = self.reader.num_events source = self.reader.read() desc = "Looping through file" for event in tqdm(source, desc=desc): #, total=n_events): ev = event.count self.calibrator.calibrate(event) for tel_id in event.r0.tels_with_data: geom = self.geometry.get_camera(tel_id) nom_geom = self.geometry.get_nominal(tel_id) image = event.dl1.tel[tel_id].image[0] # Cleaning cuts = self.tail_cut[geom.cam_id] tc = tailcuts_clean(geom, image, *cuts) if not tc.any(): # self.log.warning('No image') continue # cleaned = np.ma.masked_array(image, mask=~tc) cleaned = image * tc # Hillas try: hillas = hillas_parameters(nom_geom, cleaned) except HillasParameterizationError: # self.log.warning('HillasParameterizationError') continue # embed() fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111) camera = CameraDisplay(nom_geom, ax=ax, image=image, cmap='viridis') camera.add_colorbar() cen_x = u.Quantity(hillas.cen_x).value cen_y = u.Quantity(hillas.cen_y).value length = u.Quantity(hillas.length).value width = u.Quantity(hillas.width).value print(cen_x, cen_y, length, width) camera.add_ellipse(centroid=(cen_x, cen_y), length=length * 2, width=width * 2, angle=hillas.psi.rad) plt.show()
def draw_several_cams(geom, ncams=4): cmaps = ["jet", "afmhot", "terrain", "autumn"] fig, axs = plt.subplots( 1, ncams, figsize=(15, 4), ) for ii in range(ncams): disp = CameraDisplay( geom, ax=axs[ii], title="CT{}".format(ii + 1), ) disp.cmap = cmaps[ii] model = toymodel.Gaussian( x=(0.2 - ii * 0.1) * u.m, y=(-ii * 0.05) * u.m, width=(0.05 + 0.001 * ii) * u.m, length=(0.15 + 0.05 * ii) * u.m, psi=ii * 20 * u.deg, ) image, _, _ = model.generate_image( geom, intensity=1500, nsb_level_pe=5, ) mask = tailcuts_clean( geom, image, picture_thresh=6 * image.mean(), boundary_thresh=4 * image.mean(), ) cleaned = image.copy() cleaned[~mask] = 0 hillas = hillas_parameters(geom, cleaned) disp.image = image disp.add_colorbar(ax=axs[ii]) disp.set_limits_percent(95) disp.overlay_moments(hillas, linewidth=3, color="blue")
def draw_several_cams(geom, ncams=4): cmaps = ['jet', 'afmhot', 'terrain', 'autumn'] fig, axs = plt.subplots( 1, ncams, figsize=(15, 4), ) for ii in range(ncams): disp = CameraDisplay( geom, ax=axs[ii], title="CT{}".format(ii + 1), ) disp.cmap = cmaps[ii] model = toymodel.generate_2d_shower_model( centroid=(0.2 - ii * 0.1, -ii * 0.05), width=0.05 + 0.001 * ii, length=0.15 + 0.05 * ii, psi=ii * 20 * u.deg, ) image, sig, bg = toymodel.make_toymodel_shower_image( geom, model.pdf, intensity=1500, nsb_level_pe=5, ) mask = tailcuts_clean( geom, image, picture_thresh=6 * image.mean(), boundary_thresh=4 * image.mean() ) cleaned = image.copy() cleaned[~mask] = 0 hillas = hillas_parameters(geom, cleaned) disp.image = image disp.add_colorbar(ax=axs[ii]) disp.set_limits_percent(95) disp.overlay_moments(hillas, linewidth=3, color='blue')
def plot_event_with_shower_position_seperate_events(self, event1, event2): x, y, alt, az = self.transform_to_telescope_xy_altaz_from_event(event1) x = x.to_value(u.m) y = y.to_value(u.m) # Cameras m1_cam = copy.deepcopy(event1.inst.subarray.tel[1].camera) m2_cam = copy.deepcopy(event2.inst.subarray.tel[2].camera) m1_cam.rotate(-19.1*u.deg)#(-90+70.9) m2_cam.rotate((-90+70.9)*u.deg) # Charge images m1_event_image = event1.dl1.tel[1].image m2_event_image = event2.dl1.tel[2].image # Peak position maps #m1_event_times = b5["M1"].dl1.tel[1].peakpos #m2_event_times = b5["M2"].dl1.tel[2].peakpos fig1, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15,10)) # M1 charge map disp1 = CameraDisplay(m1_cam, m1_event_image, ax=ax1, title="MAGIC 1 image") disp1.add_colorbar(ax=ax1) # M2 charge map disp2 = CameraDisplay(m2_cam, m2_event_image, ax=ax2, title="MAGIC 2 image") disp2.add_colorbar(ax=ax2) ax1.plot(x, y, marker='*', color='red') ax1.annotate( s="Peter", xy=(x, y), xytext=(5, 5), textcoords='offset points', color='red', ) #ax1.scatter(cam.pix_x, cam.pix_y, marker="o", s=10, c='red') ax2.plot(x, y, marker='*', color='red') ax2.annotate( s="Peter", xy=(x, y), xytext=(5, 5), textcoords='offset points', color='red', )
def draw_several_cams(geom, ncams=4): cmaps = ['jet', 'afmhot', 'terrain', 'autumn'] fig, axs = plt.subplots( 1, ncams, figsize=(15, 4), sharey=True, sharex=True ) for ii in range(ncams): disp = CameraDisplay( geom, ax=axs[ii], title="CT{}".format(ii + 1), ) disp.cmap = cmaps[ii] model = toymodel.generate_2d_shower_model( centroid=(0.2 - ii * 0.1, -ii * 0.05), width=0.005 + 0.001 * ii, length=0.1 + 0.05 * ii, psi=ii * 20 * u.deg, ) image, sig, bg = toymodel.make_toymodel_shower_image( geom, model.pdf, intensity=50, nsb_level_pe=1000, ) mask = tailcuts_clean( geom, image, picture_thresh=6 * image.mean(), boundary_thresh=4 * image.mean() ) cleaned = image.copy() cleaned[~mask] = 0 hillas = hillas_parameters(geom, cleaned) disp.image = image disp.add_colorbar(ax=axs[ii]) disp.set_limits_percent(95) disp.overlay_moments(hillas, linewidth=3, color='blue')
def main(filename, config_file=None): geom = read_camera_geometries(filename)["LSTCam"] dl1_parameters_table = Table.read(filename, path=dl1_params_lstcam_key) images_table = Table.read(filename, path=dl1_images_lstcam_key) dl1_table = join( dl1_parameters_table, images_table, keys=["event_id", "tel_id", "obs_id"] ) params_cleaning = get_cleaning_config(config_file) selected_table = dl1_table[np.isfinite(dl1_table["intensity"])] selected_table = dl1_table[dl1_table["intensity"] > 500] with PdfPages("images_examples.pdf") as pp: for ii, row in enumerate(selected_table[:10]): h = get_hillas_container(row) image = row["image"] peak_time = row["peak_time"] clean_mask = tailcuts_clean(geom, image, **params_cleaning) fig, axes = plt.subplots(1, 2, figsize=(12, 6)) fig.suptitle(f"event id : {row['event_id']}") ax = axes[0] display = CameraDisplay(geom, image, ax=ax) display.add_colorbar(ax=ax) ax.set_title("charges") display.highlight_pixels(clean_mask, color="red", alpha=0.33) display.overlay_moments(h) ax = axes[1] display = CameraDisplay(geom, peak_time, ax=ax) display.highlight_pixels(clean_mask, color="red", alpha=0.2) display.add_colorbar(ax=ax) ax.set_title("peak time") pp.savefig(dpi=100)
def display_array_camera(image, camera_geometry, axes=None, **kwargs): """ Display the image of an event Parameters ---------- image: array_like axes: matplotlib.pyplot.axes Returns ------- d1: ctapipe.visualization.CameraDisplay """ if axes is None: fig, axes = plt.subplots(figsize=(10, 8)) d1 = CameraDisplay(camera_geometry, image, ax=axes, **kwargs) d1.add_colorbar(ax=axes) return d1
def plot_all(data_file, legend='camera average'): mean_charge_all, std_charge_all, mean_t_all, std_t_all, true_pe = \ load_data(data_file) mean_t_100pe = np.array( [np.interp(100, true_pe[:, i], mean_t_all[:, i]) for i in range(1296)]) std_t_100pe = np.array( [np.interp(100, true_pe[:, i], std_t_all[:, i]) for i in range(1296)]) fig, axes = plt.subplots(2, 3, figsize=(24, 18)) plot_zone(true_pe, mean_charge_all, [np.logspace(.5, 2.75, 101), np.logspace(-.3, 2.8, 101)], axes[0, 0], legend, yscale='log') axes[0, 0].loglog([0.1, 1000], [0.1, 1000], 'k--') axes[0, 0].set_ylabel('mean charge reco. [p.e]') plot_zone(true_pe, std_charge_all, [np.logspace(.5, 2.75, 101), np.logspace(-0.5, 1.5, 101)], axes[0, 1], legend, yscale='log') axes[0, 1].loglog([0.1, 1000], np.sqrt([0.1, 1000]), 'k--') axes[0, 1].set_ylabel('std charge reco. [p.e]') plot_resol(data_file, legend=legend, ax=axes[0, 2]) plot_offset(data_file, legend=legend, ax=axes[1, 0]) display = CameraDisplay(DigiCam.geometry, ax=axes[1, 1], title='timing offset (at 100 p.e) [ns]') display.image = mean_t_100pe - np.nanmean(mean_t_100pe) display.set_limits_minmax(-2, 2) display.add_colorbar(ax=axes[1, 1]) display = CameraDisplay(DigiCam.geometry, ax=axes[1, 2], title='timing resolution (at 100 p.e.) [ns]') display.image = std_t_100pe display.set_limits_minmax(0.1, 0.3) display.add_colorbar(ax=axes[1, 2]) plt.tight_layout()
def plot_camera_display(self, image, input_file, noise_pixels_id_list, alive_ped_ev, sum_ped_ev): fig, ax = plt.subplots(figsize=(10, 8)) geom = CameraGeometry.from_name('LSTCam-003') disp0 = CameraDisplay(geom, ax=ax) disp0.image = image disp0.highlight_pixels(noise_pixels_id_list, linewidth=3) disp0.add_colorbar(ax=ax, label="N times signal remain after cleaning [%]") disp0.cmap = 'gnuplot2' ax.set_title("{} \n {}/{}".format( input_file.split("/")[-1][8:21], alive_ped_ev, sum_ped_ev), fontsize=25) print("{}/{}".format(alive_ped_ev, sum_ped_ev)) ax.set_xlabel(" ") ax.set_ylabel(" ") plt.tight_layout() plt.show()
def trigger_uniformity(files, plot="show", event_types=None, disable_bar=False): events = event_stream(files, disable_bar=disable_bar) if event_types is not None: events = filter_event_types(events, flags=event_types) # patxh matrix is a bool of size n_patch x n_pixel patch_matrix = compute_patch_matrix(camera=DigiCam) n_patch, n_pixel = patch_matrix.shape top7 = np.zeros([n_patch], dtype=np.float32) n_event = 0 for event in events: n_event += 1 tel = event.r0.tels_with_data[0] top7 += np.sum(event.r0.tel[tel].trigger_output_patch7, axis=1) patches_rate = top7 / n_event pixels_rate = patches_rate.reshape([1, -1]).dot(patch_matrix).flatten() print('pixels_rate from', np.min(pixels_rate), 'to', np.max(pixels_rate), 'trigger/event') if plot is None: return pixels_rate fig1 = plt.figure() ax = plt.gca() display = CameraDisplay(DigiCam.geometry, ax=ax, title='Trigger uniformity') display.add_colorbar() display.image = pixels_rate output_path = os.path.dirname(plot) if plot == "show" or not os.path.isdir(output_path): if not plot == "show": print('WARNING: Path ' + output_path + ' for output trigger ' + 'uniformity does not exist, displaying the plot instead.\n') plt.show() else: plt.savefig(plot) plt.close(fig1) return pixels_rate
def start(self): geom = None imsum = None disp = None for data in hessio_event_source(self.infile, allowed_tels=self._selected_tels, max_events=self.max_events): self.calibrator.calibrate(data) if geom is None: x, y = data.inst.pixel_pos[self._base_tel] flen = data.inst.optical_foclen[self._base_tel] geom = CameraGeometry.guess(x, y, flen) imsum = np.zeros(shape=x.shape, dtype=np.float) disp = CameraDisplay(geom, title=geom.cam_id) disp.add_colorbar() disp.cmap = 'viridis' if len(data.dl0.tels_with_data) <= 2: continue imsum[:] = 0 for telid in data.dl0.tels_with_data: imsum += data.dl1.tel[telid].image[0] self.log.info("event={} ntels={} energy={}" \ .format(data.r0.event_id, len(data.dl0.tels_with_data), data.mc.energy)) disp.image = imsum plt.pause(0.1) if self.output_suffix is not "": filename = "{:020d}{}".format(data.r0.event_id, self.output_suffix) self.log.info("saving: '{}'".format(filename)) plt.savefig(filename)
def start(self): geom = None imsum = None disp = None for data in hessio_event_source(self.infile, allowed_tels=self._selected_tels, max_events=self.max_events): self.calibrator.calibrate(data) if geom is None: x, y = data.inst.pixel_pos[self._base_tel] flen = data.inst.optical_foclen[self._base_tel] geom = CameraGeometry.guess(x, y, flen) imsum = np.zeros(shape=x.shape, dtype=np.float) disp = CameraDisplay(geom, title=geom.cam_id) disp.add_colorbar() disp.cmap = 'viridis' if len(data.dl0.tels_with_data) <= 2: continue imsum[:] = 0 for telid in data.dl0.tels_with_data: imsum += data.dl1.tel[telid].image[0] self.log.info("event={} ntels={} energy={}" \ .format(data.r0.event_id, len(data.dl0.tels_with_data), data.mc.energy)) disp.image = imsum plt.pause(0.1) if self.output_suffix is not "": filename = "{:020d}{}".format(data.r0.event_id, self.output_suffix) self.log.info("saving: '{}'".format(filename)) plt.savefig(filename)
def start(self): geom = None imsum = None disp = None for event in self.reader: self.calibrator(event) if geom is None: geom = event.inst.subarray.tel[self._base_tel].camera imsum = np.zeros(shape=geom.pix_x.shape, dtype=np.float) disp = CameraDisplay(geom, title=geom.cam_id) disp.add_colorbar() disp.cmap = 'viridis' if len(event.dl0.tels_with_data) <= 2: continue imsum[:] = 0 for telid in event.dl0.tels_with_data: imsum += event.dl1.tel[telid].image[0] self.log.info( "event={} ntels={} energy={}".format( event.r0.event_id, len(event.dl0.tels_with_data), event.mc.energy ) ) disp.image = imsum plt.pause(0.1) if self.output_suffix is not "": filename = "{:020d}{}".format( event.r0.event_id, self.output_suffix ) self.log.info(f"saving: '{filename}'") plt.savefig(filename)
def plot_residual(fitter, image, geometry, save=False, ids=''): """ Plot the residuals image- spatial_model in the camera after fitting Parameters ---------- image: Distribution of signal for the event in number of p.e. save: bool Save and close the figure if True, return it otherwise ids: string Can be used to modify the save location Returns ------- cam_display: `ctapipe.visualization.CameraDisplay` Camera image using matplotlib """ params = fitter.end_parameters rl = 1 + params['rl'] if params['rl'] >= 0 else 1 / (1 - params['rl']) mu = asygaussian2d(params['charge'] * geometry.pix_area.to_value(u.m**2), geometry.pix_x.value, geometry.pix_y.value, params['x_cm'], params['y_cm'], params['wl'] * params['length'], params['length'], params['psi'], rl) residual = image - mu fig, axes = plt.subplots(figsize=(10, 8)) cam_display = CameraDisplay(geometry, residual, ax=axes) cam_display.add_colorbar(ax=axes) if save: cam_display.axes.get_figure().savefig('event/' + ids + '_residuals.png') plt.close() return None if save else cam_display
def start(self): geom = None imsum = None disp = None for event in self.reader: self.calibrator.calibrate(event) if geom is None: geom = event.inst.subarray.tel[self._base_tel].camera imsum = np.zeros(shape=geom.pix_x.shape, dtype=np.float) disp = CameraDisplay(geom, title=geom.cam_id) disp.add_colorbar() disp.cmap = 'viridis' if len(event.dl0.tels_with_data) <= 2: continue imsum[:] = 0 for telid in event.dl0.tels_with_data: imsum += event.dl1.tel[telid].image[0] self.log.info( "event={} ntels={} energy={}".format( event.r0.event_id, len(event.dl0.tels_with_data), event.mc.energy ) ) disp.image = imsum plt.pause(0.1) if self.output_suffix is not "": filename = "{:020d}{}".format( event.r0.event_id, self.output_suffix ) self.log.info(f"saving: '{filename}'") plt.savefig(filename)
def start(self): geom = None imsum = None disp = None for event in self.reader: self.calibrator(event) if geom is None: geom = self.reader.subarray.tel[self._base_tel].camera.geometry imsum = np.zeros(shape=geom.pix_x.shape, dtype=np.float64) disp = CameraDisplay(geom, title=geom.camera_name) disp.add_colorbar() disp.cmap = "viridis" if len(event.dl0.tel.keys()) <= 2: continue imsum[:] = 0 for telid in event.dl0.tel.keys(): imsum += event.dl1.tel[telid].image self.log.info( "event={} ntels={} energy={}".format( event.index.event_id, len(event.dl0.tel.keys()), event.simulation.shower.energy, ) ) disp.image = imsum plt.pause(0.1) if self.output_suffix != "": filename = "{:020d}{}".format(event.index.event_id, self.output_suffix) self.log.info(f"saving: '{filename}'") plt.savefig(filename)
def plot_allparam_map(df): nc = 4 nr = 2 f,axs = plt.subplots(ncols=nc,nrows=nr,figsize=(12,6)) # ~ table = Table.read('./NewNectarCam.camgeom.fits.gz') # ~ geom = CameraGeometry.from_table(table) # ~ geom.rotate(10.3*u.deg) geom = CameraGeometry.from_name("NectarCam-002") for ii,key in enumerate(df): # ~ for ii,key in enumerate(['Light I', 'ped mean', 'ped width', 'res', 'Mu2', 'gain']): ax = axs[ii%nr,ii//nr%nc] blankam = np.zeros(1855) blankam[pix_ids]=df[key] disp = CameraDisplay(geom,title=key,ax=ax) disp.add_colorbar(ax=ax) disp.set_limits_minmax(zmin=np.min(df[key])*.99,zmax=np.max(df[key])*1.01) disp.image = blankam ax.set_ylim(-0.8,0.8) ax.set_xlim(-0.5,0.4) plt.show() return
def transform_and_clean_hex_samples(pmt_samples, cam_geom): # rotate all samples in the image to a rectangular image rot_geom, rot_samples = convert_geometry_1d_to_2d( cam_geom, pmt_samples, cam_geom.cam_id) print("rot samples.shape:", rot_samples.shape) # rotate the samples back to hex image unrot_geom, unrot_samples = convert_geometry_back(rot_geom, rot_samples, cam_geom.cam_id) global fig global cb1, ax1 global cb2, ax2 global cb3, ax3 if fig is None: fig = plt.figure(figsize=(10, 10)) else: fig.delaxes(ax1) fig.delaxes(ax2) fig.delaxes(ax3) cb1.remove() cb2.remove() cb3.remove() ax1 = fig.add_subplot(221) disp1 = CameraDisplay(rot_geom, image=np.sum(rot_samples, axis=-1), ax=ax1) plt.gca().set_aspect('equal', adjustable='box') plt.title("rotated image") disp1.cmap = plt.cm.inferno disp1.add_colorbar() cb1 = disp1.colorbar ax2 = fig.add_subplot(222) disp2 = CameraDisplay(cam_geom, image=np.sum(pmt_samples, axis=-1), ax=ax2) plt.gca().set_aspect('equal', adjustable='box') plt.title("original image") disp2.cmap = plt.cm.inferno disp2.add_colorbar() cb2 = disp2.colorbar ax3 = fig.add_subplot(223) disp3 = CameraDisplay(unrot_geom, image=np.sum(unrot_samples, axis=-1), ax=ax3) plt.gca().set_aspect('equal', adjustable='box') plt.title("de-rotated image") disp3.cmap = plt.cm.inferno disp3.add_colorbar() cb3 = disp3.colorbar plt.pause(.1) response = input("press return to continue") if response != "": exit()
class ImagePlotter(Component): display = Bool(True, help='Display the photoelectron images on-screen as they ' 'are produced.').tag(config=True) output_path = Unicode(None, allow_none=True, help='Output path for the pdf containing all the ' 'images. Set to None for no saved ' 'output.').tag(config=True) def __init__(self, config=None, parent=None, **kwargs): """ Plotter for camera images. Parameters ---------- config : traitlets.loader.Config Configuration specified by config file or cmdline arguments. Used to set traitlet values. Set to None if no configuration to pass. tool : ctapipe.core.Tool Tool executable that is calling this component. Passes the correct logger to the component. Set to None if no Tool to pass. kwargs """ super().__init__(config=config, parent=parent, **kwargs) self._current_tel = None self.c_intensity = None self.c_pulse_time = None self.cb_intensity = None self.cb_pulse_time = None self.pdf = None self._init_figure() def _init_figure(self): self.fig = plt.figure(figsize=(16, 7)) self.ax_intensity = self.fig.add_subplot(1, 2, 1) self.ax_pulse_time = self.fig.add_subplot(1, 2, 2) if self.output_path: self.log.info(f"Creating PDF: {self.output_path}") self.pdf = PdfPages(self.output_path) @staticmethod def get_geometry(event, telid): return event.inst.subarray.tel[telid].camera def plot(self, event, telid): chan = 0 image = event.dl1.tel[telid].image[chan] pulse_time = event.dl1.tel[telid].pulse_time[chan] if self._current_tel != telid: self._current_tel = telid self.ax_intensity.cla() self.ax_pulse_time.cla() # Redraw camera geom = self.get_geometry(event, telid) self.c_intensity = CameraDisplay(geom, ax=self.ax_intensity) self.c_pulse_time = CameraDisplay(geom, ax=self.ax_pulse_time) tmaxmin = event.dl0.tel[telid].waveform.shape[2] t_chargemax = pulse_time[image.argmax()] cmap_time = colors.LinearSegmentedColormap.from_list( 'cmap_t', [(0 / tmaxmin, 'darkgreen'), (0.6 * t_chargemax / tmaxmin, 'green'), (t_chargemax / tmaxmin, 'yellow'), (1.4 * t_chargemax / tmaxmin, 'blue'), (1, 'darkblue')]) self.c_pulse_time.pixels.set_cmap(cmap_time) if not self.cb_intensity: self.c_intensity.add_colorbar(ax=self.ax_intensity, label='Intensity (p.e.)') self.cb_intensity = self.c_intensity.colorbar else: self.c_intensity.colorbar = self.cb_intensity self.c_intensity.update(True) if not self.cb_pulse_time: self.c_pulse_time.add_colorbar(ax=self.ax_pulse_time, label='Pulse Time (ns)') self.cb_pulse_time = self.c_pulse_time.colorbar else: self.c_pulse_time.colorbar = self.cb_pulse_time self.c_pulse_time.update(True) self.c_intensity.image = image if pulse_time is not None: self.c_pulse_time.image = pulse_time self.fig.suptitle("Event_index={} Event_id={} Telescope={}".format( event.count, event.r0.event_id, telid)) if self.display: plt.pause(0.001) if self.pdf is not None: self.pdf.savefig(self.fig) def finish(self): if self.pdf is not None: self.log.info("Closing PDF") self.pdf.close()
# load the camera tel = TelescopeDescription.from_name("SST-1M", "DigiCam") print(tel, tel.optics.effective_focal_length) geom = tel.camera # poor-man's coordinate transform from telscope to camera frame (it's # better to use ctapipe.coordiantes when they are stable) scale = tel.optics.effective_focal_length.to(geom.pix_x.unit).value fov = np.deg2rad(4.0) maxwid = np.deg2rad(0.01) maxlen = np.deg2rad(0.03) disp = CameraDisplay(geom, ax=ax) disp.cmap = plt.cm.terrain disp.add_colorbar(ax=ax) def update(frame): centroid = np.random.uniform(-fov, fov, size=2) * scale width = np.random.uniform(0, maxwid) * scale length = np.random.uniform(0, maxlen) * scale + width angle = np.random.uniform(0, 360) intens = np.random.exponential(2) * 50 model = toymodel.generate_2d_shower_model( centroid=centroid, width=width, length=length, psi=angle * u.deg, ) image, sig, bg = toymodel.make_toymodel_shower_image( geom,
from matplotlib import pyplot as plt from ctapipe.image import toymodel from ctapipe.instrument import CameraGeometry from ctapipe.visualization import CameraDisplay if __name__ == '__main__': plt.style.use('ggplot') fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(1, 1, 1) geom = CameraGeometry.from_name('NectarCam') disp = CameraDisplay(geom, ax=ax) disp.add_colorbar() model = toymodel.generate_2d_shower_model(centroid=(0.05, 0.0), width=0.005, length=0.025, psi='35d') image, sig, bg = toymodel.make_toymodel_shower_image(geom, model.pdf, intensity=50, nsb_level_pe=20) disp.image = image mask = disp.image > 15 disp.highlight_pixels(mask, linewidth=3)
def transform_and_clean_hex_image(pmt_signal, cam_geom, photo_electrons): start_time = time.time() colors = cm.inferno(pmt_signal/max(pmt_signal)) new_geom, new_signal = convert_geometry_1d_to_2d( cam_geom, pmt_signal, cam_geom.cam_id) print("rot_signal", np.count_nonzero(np.isnan(new_signal))) square_mask = new_geom.mask cleaned_img = wavelet_transform(new_signal, raw_option_string=args.raw) unrot_img = cleaned_img[square_mask] unrot_colors = cm.inferno(unrot_img/max(unrot_img)) cleaned_img_ik = kill_isolpix(cleaned_img, threshold=.5) unrot_img_ik = cleaned_img_ik[square_mask] unrot_colors_ik = cm.inferno(unrot_img_ik/max(unrot_img_ik)) square_image_add_noise = np.copy(new_signal) square_image_add_noise[~square_mask] = \ np.random.normal(0.13, 5.77, np.count_nonzero(~square_mask)) square_image_add_noise_cleaned = wavelet_transform(square_image_add_noise, raw_option_string=args.raw) square_image_add_noise_cleaned_ik = kill_isolpix(square_image_add_noise_cleaned, threshold=1.5) unrot_geom, unrot_noised_signal = convert_geometry_back( new_geom, square_image_add_noise_cleaned_ik, cam_geom.cam_id) end_time = time.time() print(end_time - start_time) global fig global cb1, ax1 global cb2, ax2 global cb3, ax3 global cb4, ax4 global cb5, ax5 global cb6, ax6 global cb7, ax7 global cb8, ax8 global cb9, ax9 if fig is None: fig = plt.figure(figsize=(10, 10)) else: fig.delaxes(ax1) fig.delaxes(ax2) fig.delaxes(ax3) fig.delaxes(ax4) fig.delaxes(ax5) fig.delaxes(ax6) fig.delaxes(ax7) fig.delaxes(ax8) fig.delaxes(ax9) cb1.remove() cb2.remove() cb3.remove() cb4.remove() cb5.remove() cb6.remove() cb7.remove() cb8.remove() cb9.remove() ax1 = fig.add_subplot(333) disp1 = CameraDisplay(cam_geom, image=photo_electrons, ax=ax1) plt.gca().set_aspect('equal', adjustable='box') plt.title("photo-electron image") disp1.cmap = plt.cm.inferno disp1.add_colorbar() cb1 = disp1.colorbar ax2 = fig.add_subplot(336) disp2 = CameraDisplay(cam_geom, image=pmt_signal, ax=ax2) plt.gca().set_aspect('equal', adjustable='box') disp2.cmap = plt.cm.inferno disp2.add_colorbar() cb2 = disp2.colorbar plt.title("noisy image") ax3 = fig.add_subplot(331) plt.imshow(new_signal, interpolation='none', cmap=cm.inferno, origin='lower') plt.gca().set_aspect('equal', adjustable='box') plt.title("noisy, slanted image") cb3 = plt.colorbar() ax4 = fig.add_subplot(334) plt.imshow(cleaned_img, interpolation='none', cmap=cm.inferno, origin='lower') plt.gca().set_aspect('equal', adjustable='box') plt.title("cleaned, slanted image, islands not killed") cb4 = plt.colorbar() ax4.set_axis_off() ax5 = fig.add_subplot(337) plt.imshow(np.sqrt(cleaned_img_ik), interpolation='none', cmap=cm.inferno, origin='lower') plt.gca().set_aspect('equal', adjustable='box') plt.title("cleaned, slanted image, islands killed") cb5 = plt.colorbar() ax5.set_axis_off() # ax6 = fig.add_subplot(332) plt.imshow(square_image_add_noise, interpolation='none', cmap=cm.inferno, origin='lower') plt.gca().set_aspect('equal', adjustable='box') plt.title("slanted image, noise added") cb6 = plt.colorbar() ax6.set_axis_off() # ax7 = fig.add_subplot(335) plt.imshow(np.sqrt(square_image_add_noise_cleaned), interpolation='none', cmap=cm.inferno, origin='lower') plt.gca().set_aspect('equal', adjustable='box') plt.title("slanted image, noise added, cleaned") cb7 = plt.colorbar() ax7.set_axis_off() ax8 = fig.add_subplot(338) plt.imshow(square_image_add_noise_cleaned_ik, interpolation='none', cmap=cm.inferno, origin='lower') plt.gca().set_aspect('equal', adjustable='box') plt.title("slanted image, noise added, cleaned, islands killed") cb8 = plt.colorbar() ax8.set_axis_off() try: ax9 = fig.add_subplot(339) disp9 = CameraDisplay(unrot_geom, image=unrot_noised_signal, ax=ax9) plt.gca().set_aspect('equal', adjustable='box') plt.title("cleaned, original geometry, islands killed") disp9.cmap = plt.cm.inferno disp9.add_colorbar() cb9 = disp9.colorbar except: pass plt.suptitle(cam_geom.cam_id) plt.subplots_adjust(top=0.94, bottom=.08, left=0, right=.96, hspace=.41, wspace=.08) plt.pause(.1) response = input("press return to continue") if response != "": exit()
def start(self): disp = None for event in tqdm(self.source, desc='Tel{}'.format(self.tel), total=self.reader.max_events, disable=~self.progress): self.log.debug(event.trig) self.log.debug("Energy: {}".format(event.mc.energy)) self.calibrator.calibrate(event) if disp is None: x, y = event.inst.pixel_pos[self.tel] focal_len = event.inst.optical_foclen[self.tel] geom = CameraGeometry.guess(x, y, focal_len) self.log.info(geom) disp = CameraDisplay(geom) # disp.enable_pixel_picker() disp.add_colorbar() if self.display: plt.show(block=False) # display the event disp.axes.set_title('CT{:03d} ({}), event {:06d}'.format( self.tel, geom.cam_id, event.r0.event_id) ) if self.samples: # display time-varying event data = event.dl0.tel[self.tel].pe_samples[self.channel] for ii in range(data.shape[1]): disp.image = data[:, ii] disp.set_limits_percent(70) plt.suptitle("Sample {:03d}".format(ii)) if self.display: plt.pause(self.delay) if self.write: plt.savefig('CT{:03d}_EV{:10d}_S{:02d}.png' .format(self.tel, event.r0.event_id, ii)) else: # display integrated event: im = event.dl1.tel[self.tel].image[self.channel] if self.clean: mask = tailcuts_clean(geom, im, picture_thresh=10, boundary_thresh=7) im[~mask] = 0.0 disp.image = im if self.hillas: try: ellipses = disp.axes.findobj(Ellipse) if len(ellipses) > 0: ellipses[0].remove() params = hillas_parameters(pix_x=geom.pix_x, pix_y=geom.pix_y, image=im) disp.overlay_moments(params, color='pink', lw=3, with_label=False) except HillasParameterizationError: pass if self.display: plt.pause(self.delay) if self.write: plt.savefig('CT{:03d}_EV{:010d}.png' .format(self.tel, event.r0.event_id)) self.log.info("FINISHED READING DATA FILE") if disp is None: self.log.warning('No events for tel {} were found in {}. Try a ' 'different EventIO file or another telescope' .format(self.tel, self.infile), ) pass
def start(self): disp = None for event in tqdm( self.event_source, desc=f"Tel{self.tel}", total=self.event_source.max_events, disable=~self.progress, ): self.log.debug(event.trigger) self.log.debug(f"Energy: {event.simulation.shower.energy}") self.calibrator(event) if disp is None: geom = self.event_source.subarray.tel[self.tel].camera.geometry self.log.info(geom) disp = CameraDisplay(geom) # disp.enable_pixel_picker() disp.add_colorbar() if self.display: plt.show(block=False) # display the event disp.axes.set_title("CT{:03d} ({}), event {:06d}".format( self.tel, geom.camera_name, event.index.event_id)) if self.samples: # display time-varying event data = event.dl0.tel[self.tel].waveform for ii in range(data.shape[1]): disp.image = data[:, ii] disp.set_limits_percent(70) plt.suptitle(f"Sample {ii:03d}") if self.display: plt.pause(self.delay) if self.write: plt.savefig( f"CT{self.tel:03d}_EV{event.index.event_id:10d}" f"_S{ii:02d}.png") else: # display integrated event: im = event.dl1.tel[self.tel].image if self.clean: mask = tailcuts_clean(geom, im, picture_thresh=10, boundary_thresh=7) im[~mask] = 0.0 disp.image = im if self.hillas: try: ellipses = disp.axes.findobj(Ellipse) if len(ellipses) > 0: ellipses[0].remove() params = hillas_parameters(geom, image=im) disp.overlay_moments(params, color="pink", lw=3, with_label=False) except HillasParameterizationError: pass if self.display: plt.pause(self.delay) if self.write: plt.savefig( f"CT{self.tel:03d}_EV{event.index.event_id:010d}.png") self.log.info("FINISHED READING DATA FILE") if disp is None: self.log.warning( "No events for tel {} were found in {}. Try a " "different EventIO file or another telescope".format( self.tel, self.infile))
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'] image[image == 0] = np.nan time = np.empty_like(image) mask = pe['pixel_id'] time[:] = np.nan time[mask] = pe['time'] - np.mean(pe['time'])
class ImagePlotter(Component): name = 'ImagePlotter' display = Bool(False, help='Display the photoelectron images on-screen as they ' 'are produced.').tag(config=True) output_path = Unicode(None, allow_none=True, help='Output path for the pdf containing all the ' 'images. Set to None for no saved ' 'output.').tag(config=True) def __init__(self, config, tool, **kwargs): """ Plotter for camera images. Parameters ---------- config : traitlets.loader.Config Configuration specified by config file or cmdline arguments. Used to set traitlet values. Set to None if no configuration to pass. tool : ctapipe.core.Tool Tool executable that is calling this component. Passes the correct logger to the component. Set to None if no Tool to pass. kwargs """ super().__init__(config=config, parent=tool, **kwargs) self._current_tel = None self.c_intensity = None self.c_peakpos = None self.cb_intensity = None self.cb_peakpos = None self.pdf = None self._init_figure() def _init_figure(self): self.fig = plt.figure(figsize=(16, 7)) self.ax_intensity = self.fig.add_subplot(1, 2, 1) self.ax_peakpos = self.fig.add_subplot(1, 2, 2) if self.output_path: self.log.info("Creating PDF: {}".format(self.output_path)) self.pdf = PdfPages(self.output_path) def get_geometry(self, event, telid): return event.inst.subarray.tel[telid].camera def plot(self, event, telid): chan = 0 image = event.dl1.tel[telid].image[chan] peakpos = event.dl1.tel[telid].peakpos[chan] if self._current_tel != telid: self._current_tel = telid self.ax_intensity.cla() self.ax_peakpos.cla() # Redraw camera geom = self.get_geometry(event, telid) self.c_intensity = CameraDisplay(geom, cmap=plt.cm.viridis, ax=self.ax_intensity) self.c_peakpos = CameraDisplay(geom, cmap=plt.cm.viridis, ax=self.ax_peakpos) tmaxmin = event.dl0.tel[telid].pe_samples.shape[2] t_chargemax = peakpos[image.argmax()] cmap_time = colors.LinearSegmentedColormap.from_list( 'cmap_t', [(0 / tmaxmin, 'darkgreen'), (0.6 * t_chargemax / tmaxmin, 'green'), (t_chargemax / tmaxmin, 'yellow'), (1.4 * t_chargemax / tmaxmin, 'blue'), (1, 'darkblue')]) self.c_peakpos.pixels.set_cmap(cmap_time) if not self.cb_intensity: self.c_intensity.add_colorbar(ax=self.ax_intensity, label='Intensity (p.e.)') self.cb_intensity = self.c_intensity.colorbar else: self.c_intensity.colorbar = self.cb_intensity self.c_intensity.update(True) if not self.cb_peakpos: self.c_peakpos.add_colorbar(ax=self.ax_peakpos, label='Peakpos (ns)') self.cb_peakpos = self.c_peakpos.colorbar else: self.c_peakpos.colorbar = self.cb_peakpos self.c_peakpos.update(True) self.c_intensity.image = image if peakpos is not None: self.c_peakpos.image = peakpos self.fig.suptitle("Event_index={} Event_id={} Telescope={}" .format(event.count, event.r0.event_id, telid)) if self.display: plt.pause(0.001) if self.pdf is not None: self.pdf.savefig(self.fig) def finish(self): if self.pdf is not None: self.log.info("Closing PDF") self.pdf.close()
def plot(event, telid, chan, extractor_name): # Extract required images dl0 = event.dl0.tel[telid].waveform[chan] t_pe = event.mc.tel[telid].photo_electron_image dl1 = event.dl1.tel[telid].image[chan] max_time = np.unravel_index(np.argmax(dl0), dl0.shape)[1] max_charges = np.max(dl0, axis=1) max_pix = int(np.argmax(max_charges)) min_pix = int(np.argmin(max_charges)) geom = event.inst.subarray.tel[telid].camera nei = geom.neighbors # Get Neighbours max_pixel_nei = nei[max_pix] min_pixel_nei = nei[min_pix] # Draw figures ax_max_nei = {} ax_min_nei = {} fig_waveforms = plt.figure(figsize=(18, 9)) fig_waveforms.subplots_adjust(hspace=.5) fig_camera = plt.figure(figsize=(15, 12)) ax_max_pix = fig_waveforms.add_subplot(4, 2, 1) ax_min_pix = fig_waveforms.add_subplot(4, 2, 2) ax_max_nei[0] = fig_waveforms.add_subplot(4, 2, 3) ax_min_nei[0] = fig_waveforms.add_subplot(4, 2, 4) ax_max_nei[1] = fig_waveforms.add_subplot(4, 2, 5) ax_min_nei[1] = fig_waveforms.add_subplot(4, 2, 6) ax_max_nei[2] = fig_waveforms.add_subplot(4, 2, 7) ax_min_nei[2] = fig_waveforms.add_subplot(4, 2, 8) ax_img_nei = fig_camera.add_subplot(2, 2, 1) ax_img_max = fig_camera.add_subplot(2, 2, 2) ax_img_true = fig_camera.add_subplot(2, 2, 3) ax_img_cal = fig_camera.add_subplot(2, 2, 4) # Draw max pixel traces ax_max_pix.plot(dl0[max_pix]) ax_max_pix.set_xlabel("Time (ns)") ax_max_pix.set_ylabel("DL0 Samples (ADC)") ax_max_pix.set_title( f'(Max) Pixel: {max_pix}, True: {t_pe[max_pix]}, ' f'Measured = {dl1[max_pix]:.3f}' ) max_ylim = ax_max_pix.get_ylim() for i, ax in ax_max_nei.items(): if len(max_pixel_nei) > i: pix = max_pixel_nei[i] ax.plot(dl0[pix]) ax.set_xlabel("Time (ns)") ax.set_ylabel("DL0 Samples (ADC)") ax.set_title( "(Max Nei) Pixel: {}, True: {}, Measured = {:.3f}" .format(pix, t_pe[pix], dl1[pix]) ) ax.set_ylim(max_ylim) # Draw min pixel traces ax_min_pix.plot(dl0[min_pix]) ax_min_pix.set_xlabel("Time (ns)") ax_min_pix.set_ylabel("DL0 Samples (ADC)") ax_min_pix.set_title( f'(Min) Pixel: {min_pix}, True: {t_pe[min_pix]}, ' f'Measured = {dl1[min_pix]:.3f}' ) ax_min_pix.set_ylim(max_ylim) for i, ax in ax_min_nei.items(): if len(min_pixel_nei) > i: pix = min_pixel_nei[i] ax.plot(dl0[pix]) ax.set_xlabel("Time (ns)") ax.set_ylabel("DL0 Samples (ADC)") ax.set_title( f'(Min Nei) Pixel: {pix}, True: {t_pe[pix]}, ' f'Measured = {dl1[pix]:.3f}' ) ax.set_ylim(max_ylim) # Draw cameras nei_camera = np.zeros_like(max_charges, dtype=np.int) nei_camera[min_pixel_nei] = 2 nei_camera[min_pix] = 1 nei_camera[max_pixel_nei] = 3 nei_camera[max_pix] = 4 camera = CameraDisplay(geom, ax=ax_img_nei) camera.image = nei_camera ax_img_nei.set_title("Neighbour Map") ax_img_nei.annotate( f"Pixel: {max_pix}", xy=(geom.pix_x.value[max_pix], geom.pix_y.value[max_pix]), xycoords='data', xytext=(0.05, 0.98), textcoords='axes fraction', arrowprops=dict(facecolor='red', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top' ) ax_img_nei.annotate( f"Pixel: {min_pix}", xy=(geom.pix_x.value[min_pix], geom.pix_y.value[min_pix]), xycoords='data', xytext=(0.05, 0.94), textcoords='axes fraction', arrowprops=dict(facecolor='orange', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top' ) camera = CameraDisplay(geom, ax=ax_img_max) camera.image = dl0[:, max_time] camera.add_colorbar(ax=ax_img_max, label="DL0 Samples (ADC)") ax_img_max.set_title(f"Max Timeslice (T = {max_time})") ax_img_max.annotate( f"Pixel: {max_pix}", xy=(geom.pix_x.value[max_pix], geom.pix_y.value[max_pix]), xycoords='data', xytext=(0.05, 0.98), textcoords='axes fraction', arrowprops=dict(facecolor='red', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top' ) ax_img_max.annotate( f"Pixel: {min_pix}", xy=(geom.pix_x.value[min_pix], geom.pix_y.value[min_pix]), xycoords='data', xytext=(0.05, 0.94), textcoords='axes fraction', arrowprops=dict(facecolor='orange', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top' ) camera = CameraDisplay(geom, ax=ax_img_true) camera.image = t_pe camera.add_colorbar(ax=ax_img_true, label="True Charge (p.e.)") ax_img_true.set_title("True Charge") ax_img_true.annotate( f"Pixel: {max_pix}", xy=(geom.pix_x.value[max_pix], geom.pix_y.value[max_pix]), xycoords='data', xytext=(0.05, 0.98), textcoords='axes fraction', arrowprops=dict(facecolor='red', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top' ) ax_img_true.annotate( f"Pixel: {min_pix}", xy=(geom.pix_x.value[min_pix], geom.pix_y.value[min_pix]), xycoords='data', xytext=(0.05, 0.94), textcoords='axes fraction', arrowprops=dict(facecolor='orange', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top' ) camera = CameraDisplay(geom, ax=ax_img_cal) camera.image = dl1 camera.add_colorbar(ax=ax_img_cal, label="Calib Charge (Photo-electrons)") ax_img_cal.set_title(f"Charge (integrator={extractor_name})") ax_img_cal.annotate( f"Pixel: {max_pix}", xy=(geom.pix_x.value[max_pix], geom.pix_y.value[max_pix]), xycoords='data', xytext=(0.05, 0.98), textcoords='axes fraction', arrowprops=dict(facecolor='red', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top' ) ax_img_cal.annotate( f"Pixel: {min_pix}", xy=(geom.pix_x.value[min_pix], geom.pix_y.value[min_pix]), xycoords='data', xytext=(0.05, 0.94), textcoords='axes fraction', arrowprops=dict(facecolor='orange', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top' ) fig_waveforms.suptitle(f"Integrator = {extractor_name}") fig_camera.suptitle(f"Camera = {geom.cam_id}") plt.show()
"""Draw lines between a pixel and its neighbors""" neigh = geom.neighbors[pixel_index] # neighbor indices (not pixel ids) x, y = geom.pix_x[pixel_index].value, geom.pix_y[pixel_index].value for nn in neigh: nx, ny = geom.pix_x[nn].value, geom.pix_y[nn].value plt.plot([x, nx], [y, ny], color=color, **kwargs) if __name__ == '__main__': # Load the camera geom = CameraGeometry.from_name("LSTCam") disp = CameraDisplay(geom) disp.set_limits_minmax(0, 300) disp.add_colorbar() # Create a fake camera image to display: model = toymodel.generate_2d_shower_model(centroid=(0.2, 0.0), width=0.01, length=0.1, psi='35d') image, sig, bg = toymodel.make_toymodel_shower_image(geom, model.pdf, intensity=50, nsb_level_pe=1000) # Apply image cleaning cleanmask = tailcuts_clean(geom, image, picture_thresh=200, boundary_thresh=100) clean = image.copy()
if __name__ == '__main__': plt.style.use("ggplot") fig, ax = plt.subplots() # load the camera tel = TelescopeDescription.from_name("SST-1M", "DigiCam") geom = tel.camera fov = 0.3 maxwid = 0.05 maxlen = 0.1 disp = CameraDisplay(geom, ax=ax) disp.cmap = 'inferno' disp.add_colorbar(ax=ax) def update(frame): x, y = np.random.uniform(-fov, fov, size=2) width = np.random.uniform(0.01, maxwid) length = np.random.uniform(width, maxlen) angle = np.random.uniform(0, 180) intens = width * length * (5e4 + 1e5 * np.random.exponential(2)) model = toymodel.Gaussian( x=x * u.m, y=y * u.m, width=width * u.m, length=length * u.m, psi=angle * u.deg, )
def test_convert_geometry(): filename = get_path("gamma_test.simtel.gz") cam_geom = {} source = hessio_event_source(filename) # testing a few images just for the sake of being thorough counter = 5 for event in source: for tel_id in event.dl0.tels_with_data: if tel_id not in cam_geom: cam_geom[tel_id] = CameraGeometry.guess( event.inst.pixel_pos[tel_id][0], event.inst.pixel_pos[tel_id][1], event.inst.optical_foclen[tel_id]) # we want to test conversion of hex to rectangular pixel grid if cam_geom[tel_id].pix_type is not "hexagonal": continue print(tel_id, cam_geom[tel_id].pix_type) pmt_signal = apply_mc_calibration( #event.dl0.tel[tel_id].adc_samples[0], event.dl0.tel[tel_id].adc_sums[0], event.mc.tel[tel_id].dc_to_pe[0], event.mc.tel[tel_id].pedestal[0]) new_geom, new_signal = convert_geometry_1d_to_2d( cam_geom[tel_id], pmt_signal, cam_geom[tel_id].cam_id, add_rot=-2) unrot_geom, unrot_signal = convert_geometry_back( new_geom, new_signal, cam_geom[tel_id].cam_id, event.inst.optical_foclen[tel_id], add_rot=4) # if run as main, do some plotting if __name__ == "__main__": fig = plt.figure() plt.style.use('seaborn-talk') ax1 = fig.add_subplot(131) disp1 = CameraDisplay(cam_geom[tel_id], image=np.sum(pmt_signal, axis=1) if pmt_signal.shape[-1] == 25 else pmt_signal, ax=ax1) disp1.cmap = plt.cm.hot disp1.add_colorbar() plt.title("original geometry") ax2 = fig.add_subplot(132) disp2 = CameraDisplay(new_geom, image=np.sum(new_signal, axis=2) if new_signal.shape[-1] == 25 else new_signal, ax=ax2) disp2.cmap = plt.cm.hot disp2.add_colorbar() plt.title("slanted geometry") ax3 = fig.add_subplot(133) disp3 = CameraDisplay(unrot_geom, image=np.sum(unrot_signal, axis=1) if unrot_signal.shape[-1] == 25 else unrot_signal, ax=ax3) disp3.cmap = plt.cm.hot disp3.add_colorbar() plt.title("geometry converted back to hex") plt.show() # do some tailcuts cleaning mask1 = tailcuts_clean(cam_geom[tel_id], pmt_signal, 1, picture_thresh=10., boundary_thresh=5.) mask2 = tailcuts_clean(unrot_geom, unrot_signal, 1, picture_thresh=10., boundary_thresh=5.) pmt_signal[mask1==False] = 0 unrot_signal[mask2==False] = 0 ''' testing back and forth conversion on hillas parameters... ''' try: moments1 = hillas_parameters(cam_geom[tel_id].pix_x, cam_geom[tel_id].pix_y, pmt_signal) moments2 = hillas_parameters(unrot_geom.pix_x, unrot_geom.pix_y, unrot_signal) except (HillasParameterizationError, AssertionError) as e: ''' we don't want this test to fail because the hillas code threw an error ''' print(e) counter -= 1 if counter < 0: return else: continue ''' test if the hillas parameters from the original geometry and the forth-and-back rotated geometry are close ''' assert np.allclose( [moments1.length.value, moments1.width.value, moments1.phi.value], [moments2.length.value, moments2.width.value, moments2.phi.value], rtol=1e-2, atol=1e-2) counter -= 1 if counter < 0: return
def plot(self, input_file, event, telid, chan, extractor_name, nei): # Extract required images dl0 = event.dl0.tel[telid].adc_samples[chan] t_pe = event.mc.tel[telid].photo_electron_image dl1 = event.dl1.tel[telid].image[chan] max_time = np.unravel_index(np.argmax(dl0), dl0.shape)[1] max_charges = np.max(dl0, axis=1) max_pix = int(np.argmax(max_charges)) min_pix = int(np.argmin(max_charges)) geom = CameraGeometry.guess(*event.inst.pixel_pos[telid], event.inst.optical_foclen[telid]) # Get Neighbours max_pixel_nei = nei[max_pix] min_pixel_nei = nei[min_pix] # Get Windows windows = event.dl1.tel[telid].extracted_samples[chan] length = np.sum(windows, axis=1) start = np.argmax(windows, axis=1) end = start + length # Draw figures ax_max_nei = {} ax_min_nei = {} fig_waveforms = plt.figure(figsize=(18, 9)) fig_waveforms.subplots_adjust(hspace=.5) fig_camera = plt.figure(figsize=(15, 12)) ax_max_pix = fig_waveforms.add_subplot(4, 2, 1) ax_min_pix = fig_waveforms.add_subplot(4, 2, 2) ax_max_nei[0] = fig_waveforms.add_subplot(4, 2, 3) ax_min_nei[0] = fig_waveforms.add_subplot(4, 2, 4) ax_max_nei[1] = fig_waveforms.add_subplot(4, 2, 5) ax_min_nei[1] = fig_waveforms.add_subplot(4, 2, 6) ax_max_nei[2] = fig_waveforms.add_subplot(4, 2, 7) ax_min_nei[2] = fig_waveforms.add_subplot(4, 2, 8) ax_img_nei = fig_camera.add_subplot(2, 2, 1) ax_img_max = fig_camera.add_subplot(2, 2, 2) ax_img_true = fig_camera.add_subplot(2, 2, 3) ax_img_cal = fig_camera.add_subplot(2, 2, 4) # Draw max pixel traces ax_max_pix.plot(dl0[max_pix]) ax_max_pix.set_xlabel("Time (ns)") ax_max_pix.set_ylabel("DL0 Samples (ADC)") ax_max_pix.set_title("(Max) Pixel: {}, True: {}, Measured = {:.3f}" .format(max_pix, t_pe[max_pix], dl1[max_pix])) max_ylim = ax_max_pix.get_ylim() ax_max_pix.plot([start[max_pix], start[max_pix]], ax_max_pix.get_ylim(), color='r', alpha=1) ax_max_pix.plot([end[max_pix], end[max_pix]], ax_max_pix.get_ylim(), color='r', alpha=1) for i, ax in ax_max_nei.items(): if len(max_pixel_nei) > i: pix = max_pixel_nei[i] ax.plot(dl0[pix]) ax.set_xlabel("Time (ns)") ax.set_ylabel("DL0 Samples (ADC)") ax.set_title("(Max Nei) Pixel: {}, True: {}, Measured = {:.3f}" .format(pix, t_pe[pix], dl1[pix])) ax.set_ylim(max_ylim) ax.plot([start[pix], start[pix]], ax.get_ylim(), color='r', alpha=1) ax.plot([end[pix], end[pix]], ax.get_ylim(), color='r', alpha=1) # Draw min pixel traces ax_min_pix.plot(dl0[min_pix]) ax_min_pix.set_xlabel("Time (ns)") ax_min_pix.set_ylabel("DL0 Samples (ADC)") ax_min_pix.set_title("(Min) Pixel: {}, True: {}, Measured = {:.3f}" .format(min_pix, t_pe[min_pix], dl1[min_pix])) ax_min_pix.set_ylim(max_ylim) ax_min_pix.plot([start[min_pix], start[min_pix]], ax_min_pix.get_ylim(), color='r', alpha=1) ax_min_pix.plot([end[min_pix], end[min_pix]], ax_min_pix.get_ylim(), color='r', alpha=1) for i, ax in ax_min_nei.items(): if len(min_pixel_nei) > i: pix = min_pixel_nei[i] ax.plot(dl0[pix]) ax.set_xlabel("Time (ns)") ax.set_ylabel("DL0 Samples (ADC)") ax.set_title("(Min Nei) Pixel: {}, True: {}, Measured = {:.3f}" .format(pix, t_pe[pix], dl1[pix])) ax.set_ylim(max_ylim) ax.plot([start[pix], start[pix]], ax.get_ylim(), color='r', alpha=1) ax.plot([end[pix], end[pix]], ax.get_ylim(), color='r', alpha=1) # Draw cameras nei_camera = np.zeros_like(max_charges, dtype=np.int) nei_camera[min_pixel_nei] = 2 nei_camera[min_pix] = 1 nei_camera[max_pixel_nei] = 3 nei_camera[max_pix] = 4 camera = CameraDisplay(geom, ax=ax_img_nei) camera.image = nei_camera camera.cmap = plt.cm.viridis ax_img_nei.set_title("Neighbour Map") ax_img_nei.annotate("Pixel: {}".format(max_pix), xy=(geom.pix_x.value[max_pix], geom.pix_y.value[max_pix]), xycoords='data', xytext=(0.05, 0.98), textcoords='axes fraction', arrowprops=dict(facecolor='red', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top') ax_img_nei.annotate("Pixel: {}".format(min_pix), xy=(geom.pix_x.value[min_pix], geom.pix_y.value[min_pix]), xycoords='data', xytext=(0.05, 0.94), textcoords='axes fraction', arrowprops=dict(facecolor='orange', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top') camera = CameraDisplay(geom, ax=ax_img_max) camera.image = dl0[:, max_time] camera.cmap = plt.cm.viridis camera.add_colorbar(ax=ax_img_max, label="DL0 Samples (ADC)") ax_img_max.set_title("Max Timeslice (T = {})".format(max_time)) ax_img_max.annotate("Pixel: {}".format(max_pix), xy=(geom.pix_x.value[max_pix], geom.pix_y.value[max_pix]), xycoords='data', xytext=(0.05, 0.98), textcoords='axes fraction', arrowprops=dict(facecolor='red', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top') ax_img_max.annotate("Pixel: {}".format(min_pix), xy=(geom.pix_x.value[min_pix], geom.pix_y.value[min_pix]), xycoords='data', xytext=(0.05, 0.94), textcoords='axes fraction', arrowprops=dict(facecolor='orange', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top') camera = CameraDisplay(geom, ax=ax_img_true) camera.image = t_pe camera.cmap = plt.cm.viridis camera.add_colorbar(ax=ax_img_true, label="True Charge (p.e.)") ax_img_true.set_title("True Charge") ax_img_true.annotate("Pixel: {}".format(max_pix), xy=(geom.pix_x.value[max_pix], geom.pix_y.value[max_pix]), xycoords='data', xytext=(0.05, 0.98), textcoords='axes fraction', arrowprops=dict(facecolor='red', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top') ax_img_true.annotate("Pixel: {}".format(min_pix), xy=(geom.pix_x.value[min_pix], geom.pix_y.value[min_pix]), xycoords='data', xytext=(0.05, 0.94), textcoords='axes fraction', arrowprops=dict(facecolor='orange', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top') camera = CameraDisplay(geom, ax=ax_img_cal) camera.image = dl1 camera.cmap = plt.cm.viridis camera.add_colorbar(ax=ax_img_cal, label="Calib Charge (Photo-electrons)") ax_img_cal.set_title("Charge (integrator={})".format(extractor_name)) ax_img_cal.annotate("Pixel: {}".format(max_pix), xy=(geom.pix_x.value[max_pix], geom.pix_y.value[max_pix]), xycoords='data', xytext=(0.05, 0.98), textcoords='axes fraction', arrowprops=dict(facecolor='red', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top') ax_img_cal.annotate("Pixel: {}".format(min_pix), xy=(geom.pix_x.value[min_pix], geom.pix_y.value[min_pix]), xycoords='data', xytext=(0.05, 0.94), textcoords='axes fraction', arrowprops=dict(facecolor='orange', width=2, alpha=0.4), horizontalalignment='left', verticalalignment='top') fig_waveforms.suptitle("Integrator = {}".format(extractor_name)) fig_camera.suptitle("Camera = {}".format(geom.cam_id)) waveform_output_name = "e{}_t{}_c{}_extractor{}_waveform.pdf"\ .format(event.count, telid, chan, extractor_name) camera_output_name = "e{}_t{}_c{}_extractor{}_camera.pdf"\ .format(event.count, telid, chan, extractor_name) output_dir = self.output_dir if output_dir is None: output_dir = input_file.output_directory output_dir = os.path.join(output_dir, self.name) if not os.path.exists(output_dir): self.log.info("Creating directory: {}".format(output_dir)) os.makedirs(output_dir) waveform_output_path = os.path.join(output_dir, waveform_output_name) self.log.info("Saving: {}".format(waveform_output_path)) fig_waveforms.savefig(waveform_output_path, format='pdf', bbox_inches='tight') camera_output_path = os.path.join(output_dir, camera_output_name) self.log.info("Saving: {}".format(camera_output_path)) fig_camera.savefig(camera_output_path, format='pdf', bbox_inches='tight')