def plot_window_trans_perpix(window_number): """ Plot of the mean value of trans_norm_cher per pixel :param window_number: 1 or 2 to choose between the first or second window :return: plot the camera pixels with the mean value of trans_norm_cher for each of the pixels """ pix_trans_cher = np.loadtxt( "data/mean_transmittance_per_pixel_{0}_wdw.txt".format( num[window_number - 1]), usecols=1, skiprows=1, unpack=True) fig = plt.figure() ax = plt.gca() ax.set_alpha(0) CameraDisplay(DigiCam.geometry, pix_trans_cher, cmap='viridis', title='').highlight_pixels(range(1296), color='k', linewidth=0.2) CameraDisplay( DigiCam.geometry, pix_trans_cher, cmap='viridis', title='').add_colorbar(label="Transmittance $\otimes$ norm\_cher") plt.annotate("mean: {0:.2f}\%".format(np.mean(pix_trans_cher) * 100.), xy=(-430, 490), xycoords="data", va="center", ha="center", bbox=dict(boxstyle="round", fc="w", ec="silver")) plt.xlim(-550, 550) plt.ylim(-550, 550) fig.savefig('{0}/trans_values_perpixel_{1}wdw.pdf'.format( folder[window_number - 1], num[window_number - 1])) plt.show()
def create(self, image, coords, title, coeff, fitter): df = fitter.get_curve(coords.xi_mg, coords.yi_mg, coeff) 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) amplitude, x0, y0, sigma, offset = coeff radius = fitter.find_containment_radius(coords, coeff, 0.8) radius_deg = radius * coords.degperm x70 = x0 + radius y70 = y0 z = offset + amplitude * np.exp( - ((((x70 - x0) ** 2) / (2 * sigma ** 2)) + (((y70 - y0) ** 2) / (2 * sigma ** 2)))) CS = self.ax.contour(coords.xi_mg, coords.yi_mg, df, linewidths=0.5, colors='r', levels=[z]) text = "80% Containment \n({:.3} degrees)".format(radius_deg) self.ax.text(x70, y70, text, color='r') self.fig.suptitle("Jupiter RMS ON-OFF") self.ax.set_title(title) self.ax.axis([-0.06, 0.03, -0.06, 0.03]) # self.ax.axis('off') minor_locator = AutoMinorLocator(10) self.ax.xaxis.set_minor_locator(minor_locator) self.ax.yaxis.set_minor_locator(minor_locator)
def plot_window_trans_perpix(fname): """ IMPORTANT display mean value on the camera Plot of the mean value of trans_norm_cher per pixel :param window_number: 1 or 2 to choose between the first or second window :return: plot the camera pixels with the mean value of trans_norm_cher for each of the pixels """ ave_irradiance_per_pixel = np.loadtxt(fname=fname, usecols=1, skiprows=1, unpack=True) fig = plt.figure() ax = plt.gca() ax.set_alpha(0) CameraDisplay(DigiCam.geometry, ave_irradiance_per_pixel, cmap='viridis', title='').highlight_pixels(range(1296), color='k', linewidth=0.2) CameraDisplay(DigiCam.geometry, ave_irradiance_per_pixel, cmap='viridis', title='').add_colorbar(label="I [A]") # plt.annotate("mean: {0:.2f}\%".format(np.mean(ave_irradiance_per_pixel)*100.), # xy=(-430, 490), # xycoords="data", # va="center", # ha="center", # bbox=dict(boxstyle="round", fc="w", ec="silver")) plt.xlim(-550, 550) plt.ylim(-550, 550) return fig, ax
def plot_model(fitter, geometry, save=False, ids=''): """ Create a CameraDisplay object showing the spatial model fitted to the current event Parameters ------- 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) fig, axes = plt.subplots(figsize=(10, 8)) cam_display = CameraDisplay(geometry, mu, ax=axes) cam_display.add_colorbar(ax=axes) if save: cam_display.axes.get_figure().savefig('event/' + ids + '_model.png') plt.close() return None if save else cam_display
def go(self): fig = plt.figure() ax = fig.add_subplot(111) disp = None source = hessio_event_source(self.filename, requested_event=24) for event in source: self.calib.calibrate(event) for i in range(50): ipix = np.random.randint(0, 2048) samp = event.dl0.tel[1]['pe_samples'][0][ipix] # plt.plot(range(len(samp)),samp) plt.show() if disp is None: geom = event.inst.subarray.tel[1].camera disp = CameraDisplay(geom) # disp.enable_pixel_picker() disp.add_colorbar() plt.show(block=False) # im = event.dl1.tel[1].image[0] mask = tailcuts_clean(geom, im, picture_thresh=10, boundary_thresh=5) im[~mask] = 0.0 maxpe = max(event.dl1.tel[1].image[0]) disp.image = im print(np.mean(im), '+/-', np.std(im)) plt.show()
def draw_camera(self, tel, data, axes=None): """ Draw a camera image using the correct geometry. Parameters ---------- tel : int The telescope you want drawn. data : `np.array` 1D array with length equal to npix. axes : `matplotlib.axes.Axes` A matplotlib axes object to plot on, or None to create a new one. Returns ------- `ctapipe.visualization.CameraDisplay` """ geom = self.get_geometry(tel) axes = axes if axes is not None else plt.gca() camera = CameraDisplay(geom, ax=axes) camera.image = data camera.cmap = plt.cm.viridis # camera.add_colorbar(ax=axes, label="Amplitude (ADC)") # camera.set_limits_percent(95) # autoscale return camera
def camera_image(input_file, ax): first_event = input_file.get_event(0) geom = CameraGeometry.guess(*first_event.meta.pixel_pos[telid], first_event.meta.optical_foclen[telid]) camera = CameraDisplay(geom, ax=ax) camera.cmap = plt.cm.viridis import time def update(iframe, source): data = next(source) print(iframe) # data = np.zeros((2048,128)) # data[iframe,0] = iframe camera.image = data return camera.pixels, source = get_data(input_file) anim = FuncAnimation(fig, update, fargs=[source], blit=True, frames=1000, interval=1, repeat=False) plt.show()
def plot_camera(self): #TPA fig2 = plt.figure(2, figsize=(7, 7)) ax2 = fig2.add_subplot(111) # print(self.geom) disp = CameraDisplay(self.geom) disp.add_colorbar() image = [1] * 2048 disp.image = image
def get_observation_parameters(charge: np.array, peak: np.array, cam_name: str, cutflow: CutFlow, boundary_threshold: float = None, picture_threshold: float = None, min_neighbours: float = None, plot: bool = False, cut: bool = True): """ :param charge: Charge image :param peak: Peak time image :param cam_name: Camera name. e.g. FlashCam, ASTRICam, etc. :param cutflow: Cutflow for selection :param boundary_threshold: (Optional) Cleaning parameter: boundary threshold :param picture_threshold: (Optional) Cleaning parameter: picture threshold :param min_neighbours: (Optional) Cleaning parameter: minimum neighbours :param plot: If True, for each observation a plot will be shown (Default: False) :param cut: If true, tight else loose :return: hillas containers, leakage container, number of islands, island IDs, timing container, timing gradient """ charge_biggest, mask = clean_charge(charge, cam_name, boundary_threshold, picture_threshold, min_neighbours) camera = get_camera(cam_name) geometry = camera.geometry charge_biggest, camera_biggest, n_islands = mask_from_biggest_island( charge, geometry, mask) if cut: if cutflow.cut(CFO_MIN_PIXEL, charge_biggest): return if cutflow.cut(CFO_MIN_CHARGE, np.sum(charge_biggest)): return if cutflow.cut(CFO_NEGATIVE_CHARGE, charge_biggest): return leakage_c = leakage(geometry, charge, mask) if plot: _, (ax1, ax2) = plt.subplots(nrows=1, ncols=2) CameraDisplay(geometry, charge, ax=ax1).add_colorbar() CameraDisplay(camera_biggest, charge_biggest, ax=ax2).add_colorbar() plt.show() moments = hillas_parameters(camera_biggest, charge_biggest) if cut: if cutflow.cut(CFO_CLOSE_EDGE, moments, camera.camera_name): return if cutflow.cut(CFO_BAD_ELLIP, moments): return if cutflow.cut(CFO_POOR_MOMENTS, moments): return timing_c = timing_parameters(geometry, charge, peak, moments, mask) time_gradient = timing_c.slope.value if geometry.camera_name != 'ASTRICam' else moments.skewness return moments, leakage_c, timing_c, time_gradient, n_islands
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, ax=self.ax_intensity) self.c_peakpos = CameraDisplay(geom, ax=self.ax_peakpos) tmaxmin = event.dl0.tel[telid].waveform.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 plot(self, event, telid): image = event.dl1.tel[telid].image peak_time = event.dl1.tel[telid].peak_time print("plot", image.shape, peak_time.shape) if self._current_tel != telid: self._current_tel = telid self.ax_intensity.cla() self.ax_peak_time.cla() # Redraw camera geom = self.subarray.tel[telid].camera.geometry self.c_intensity = CameraDisplay(geom, ax=self.ax_intensity) self.c_peak_time = CameraDisplay(geom, ax=self.ax_peak_time) if (peak_time != 0.0).all(): tmaxmin = event.dl0.tel[telid].waveform.shape[1] t_chargemax = peak_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_peak_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_peak_time: self.c_peak_time.add_colorbar(ax=self.ax_peak_time, label="Pulse Time (ns)") self.cb_peak_time = self.c_peak_time.colorbar else: self.c_peak_time.colorbar = self.cb_peak_time self.c_peak_time.update(True) self.c_intensity.image = image if peak_time is not None: self.c_peak_time.image = peak_time self.fig.suptitle("Event_index={} Event_id={} Telescope={}".format( event.count, event.index.event_id, telid)) if self.display: plt.pause(0.001) if self.pdf is not None: self.pdf.savefig(self.fig)
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 plot_cam(geom, geom2d, geom1d, image, image2d, image1d): # plt.viridis() plt.figure(figsize=(12, 4)) ax = plt.subplot(1, 3, 1) CameraDisplay(geom, image=image).add_colorbar() plt.subplot(1, 3, 2, sharex=ax, sharey=ax) CameraDisplay(geom2d, image=image2d).add_colorbar() plt.subplot(1, 3, 3, sharex=ax, sharey=ax) CameraDisplay(geom1d, image=image1d).add_colorbar()
def _display_camera_animation(self): #plt.style.use("ggplot") fig = plt.figure(num="ctapipe Camera Demo", figsize=(7, 7)) ax = plt.subplot(111) # load the camera geom = CameraGeometry.from_name(self.camera) disp = CameraDisplay(geom, ax=ax, autoupdate=True, ) disp.cmap = plt.cm.terrain def update(frame): centroid = np.random.uniform(-0.5, 0.5, size=2) width = np.random.uniform(0, 0.01) length = np.random.uniform(0, 0.03) + 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, model.pdf, intensity=intens, nsb_level_pe=5000) # alternate between cleaned and raw images if self._counter == self.cleanframes: plt.suptitle("Image Cleaning ON") self.imclean = True if self._counter == self.cleanframes*2: plt.suptitle("Image Cleaning OFF") self.imclean = False self._counter = 0 if self.imclean: cleanmask = tailcuts_clean(geom, image/80.0) for ii in range(3): dilate(geom, cleanmask) image[cleanmask == 0] = 0 # zero noise pixels self.log.debug("count = {}, image sum={} max={}" .format(self._counter, image.sum(), image.max())) disp.image = image if self.autoscale: disp.set_limits_percent(95) else: disp.set_limits_minmax(-100, 4000) disp.axes.figure.canvas.draw() self._counter += 1 return [ax,] self.anim = FuncAnimation(fig, update, interval=self.delay, blit=self.blit) plt.show()
def create(self, df, geom): super().save() camera = CameraDisplay(geom, ax=self.ax, image=np.ma.zeros(2048), cmap='viridis') camera.add_colorbar(pad=-0.2) camera.colorbar.set_label("Peak Time (ns)", fontsize=20) with PdfPages(self.output_path) as pdf: n_rows = len(df.index) desc = "Saving image pages" for index, row in tqdm(df.iterrows(), total=n_rows, desc=desc): event_id = row['id'] tel = row['tel'] image = row['peak_time'] tc = row['tc'] hillas = row['hillas'] cleaned_image = np.ma.masked_array(image, mask=~tc) cleaned_image.fill_value = 0 max_ = np.percentile(cleaned_image.compressed(), 99) min_ = np.percentile(cleaned_image.compressed(), 1) camera.image = cleaned_image camera.set_limits_minmax(min_, max_) camera.highlight_pixels(np.arange(2048), 'black', 1, 0.2) # camera.overlay_moments_update(hillas, color='red') self.ax.set_title("Event: {}, Tel: {}".format(event_id, tel)) self.ax.axis('off') camera.colorbar.ax.tick_params(labelsize=30) pdf.savefig(self.fig)
def display_event(event): """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) geom = event.inst.subarray.tel[tel_id].camera disp = CameraDisplay(geom, ax=ax, title="CT{0}".format(tel_id)) disp.pixels.set_antialiaseds(False) disp.autoupdate = False disp.cmap = random.choice(cmaps) 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 test_hillas_overlay(): from ctapipe.visualization import CameraDisplay disp = CameraDisplay(CameraGeometry.from_name("LSTCam")) hillas = CameraHillasParametersContainer(x=0.1 * u.m, y=-0.1 * u.m, length=0.5 * u.m, width=0.2 * u.m, psi=90 * u.deg) disp.overlay_moments(hillas)
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 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 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, 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(self, event, telid): image = event.dl1.tel[telid].image peak_time = event.dl1.tel[telid].peak_time if self._current_tel != telid: self._current_tel = telid self.ax_intensity.cla() self.ax_peak_time.cla() # Redraw camera geom = self.subarray.tel[telid].camera.geometry self.c_intensity = CameraDisplay(geom, ax=self.ax_intensity) time_cmap = copy(plt.get_cmap("RdBu_r")) time_cmap.set_under("gray") time_cmap.set_over("gray") self.c_peak_time = CameraDisplay(geom, ax=self.ax_peak_time, cmap=time_cmap) 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_peak_time: self.c_peak_time.add_colorbar(ax=self.ax_peak_time, label="Pulse Time (ns)") self.cb_peak_time = self.c_peak_time.colorbar else: self.c_peak_time.colorbar = self.cb_peak_time self.c_peak_time.update(True) self.c_intensity.image = image self.c_peak_time.image = peak_time # center around brightes pixel, show 10ns total t_chargemax = peak_time[image.argmax()] self.c_peak_time.set_limits_minmax(t_chargemax - 5, t_chargemax + 5) self.fig.suptitle("Event_index={} Event_id={} Telescope={}".format( event.count, event.index.event_id, telid)) if self.display: plt.pause(0.001) if self.pdf is not None: self.pdf.savefig(self.fig)
def display_dl1_event(event, camera_geometry, tel_id=1, axes=None, **kwargs): """ Display a DL1 event (image and pulse time map) side by side Parameters ---------- event: ctapipe event tel_id: int axes: list of `matplotlib.pyplot.axes` of shape (2,) or None kwargs: kwargs for `ctapipe.visualization.CameraDisplay` Returns ------- axes: `matplotlib.pyplot.axes` """ if axes is None: fig, axes = plt.subplots(1, 2, figsize=(12, 5)) image = event.dl1.tel[tel_id].image peak_time = event.dl1.tel[tel_id].peak_time if image is None or peak_time is None: raise Exception( f"There is no calibrated image or pulse time map for telescope {tel_id}" ) d1 = CameraDisplay(camera_geometry, image, ax=axes[0], **kwargs) d1.add_colorbar(ax=axes[0]) d2 = CameraDisplay(camera_geometry, peak_time, ax=axes[1], **kwargs) d2.add_colorbar(ax=axes[1]) return axes
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 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 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 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 plot_array_camera(data, label='', limits=None, **kwargs): mask = np.isfinite(data) if limits is not None: mask *= (data >= limits[0]) * (data <= limits[1]) data[~mask] = 0 fig = plt.figure() cam = DigiCam geom = cam.geometry cam_display = CameraDisplay(geom, **kwargs) cam_display.cmap.set_bad(color='k') cam_display.image = data cam_display.axes.set_title('') cam_display.axes.set_xticks([]) cam_display.axes.set_yticks([]) cam_display.axes.set_xlabel('') cam_display.axes.set_ylabel('') cam_display.axes.axis('off') cam_display.add_colorbar(label=label) cam_display.axes.get_figure().set_size_inches((10, 10)) plt.axis('equal') if limits is not None: if not isinstance(limits, tuple): raise TypeError('Limits must be a tuple()') cam_display.colorbar.set_clim(vmin=limits[0], vmax=limits[1]) cam_display.update() return cam_display, fig
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 test_overlay_disp_vector(): from ctapipe.image import hillas_parameters geom = CameraGeometry.from_name('LSTCam') image = np.random.rand(geom.n_pixels) display = CameraDisplay(geom, image) hillas = hillas_parameters(geom, image) disp = disp_parameters_event(hillas, 0.1 * u.m, 0.3 * u.m) overlay_disp_vector(display, disp, hillas)
def main(): fig, axs = plt.subplots(1, 2, constrained_layout=True, figsize=(6, 3)) model = Gaussian(0 * u.m, 0.1 * u.m, 0.3 * u.m, 0.05 * u.m, 25 * u.deg) cam = CameraGeometry.from_name('FlashCam') image, *_ = model.generate_image(cam, 2500) CameraDisplay(cam, ax=axs[0], image=image) CameraDisplay( cam.transform_to(EngineeringCameraFrame()), ax=axs[1], image=image, ) axs[0].set_title('CameraFrame') axs[1].set_title('EngineeringCameraFrame') plt.show()
def plot_quick_camera(image, ax=None): ax = ax if ax is not None else plt.gca() cameraconfig = Config() pos = cameraconfig.pixel_pos * u.m foclen = cameraconfig.optical_foclen * u.m geom = CameraGeometry.guess(*pos, foclen) camera = CameraDisplay(geom, ax=ax, image=image, cmap='viridis') return camera
def plot_nevent(events, nevent, filename, bad_pixels=None, norm="lin"): displays = [] fig, axes = plt.subplots( 3, 4, # sharex='all', sharey='all', figsize=[18, 12]) axes = axes.flatten() for index, event in enumerate(events): if index < nevent: axe = index % 12 figure = int(np.floor(index / 12)) if index < 12: displays.append( CameraDisplay(DigiCam.geometry, ax=axes[index], norm=norm, title='')) displays[axe].cmap.set_bad('w') displays[axe].cmap.set_over('w') displays[axe].cmap.set_under('w') displays[axe].add_colorbar(ax=axes[axe]) axes[axe].set_xlabel("") axes[axe].set_ylabel("") axes[axe].set_xlim([-400, 400]) axes[axe].set_ylim([-400, 400]) axes[axe].set_xticklabels([]) axes[axe].set_yticklabels([]) pe = event.data.reconstructed_number_of_pe n_pix = len(pe) mask = event.data.cleaning_mask pe_masked = pe pe_masked[~mask] = np.NaN displays[axe].set_limits_minmax(0, np.nanmax(pe_masked)) displays[axe].image = pe_masked # highlight only bad pixels which pass the tail-cut cleaning highlighted_mask = np.zeros(n_pix, dtype=bool) highlighted_mask[bad_pixels] = mask[bad_pixels] highlighted = np.arange(n_pix)[highlighted_mask] displays[axe].highlight_pixels(highlighted, color='k', linewidth=2) displays[axe].overlay_moments(event.hillas, with_label=False, edgecolor='r', linewidth=2) if index % 12 == 11 or index == nevent - 1: if filename.lower == "show": plt.show() else: if figure == 0: output = filename else: output = filename.replace('.png', '_' + str(figure) + '.png') plt.savefig(output) print(output, 'created.') yield event plt.close(fig)
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 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 __init__(self, waveform_data, geometry, camera_axis, waveform_axis_list, waveform_axis_ylabel): self.__waveform_data = None self.__waveform_axis_list = None self.__integration_window = None self.camera_axis = camera_axis self.waveform_axis_list = [] self.waveform_title_list = [] self.waveform_window_list = [] self.waveforms = [] self.pixel_switch_num = 0 self.colors = itertools.cycle(['r', 'b', 'c', 'm', 'y', 'k', 'w', 'g']) self.current_color = 'r' self.active_pixels = [] self.active_pixel_patches = [] self.active_pixel_labels = [] self.window_start = None self.window_end = None CameraDisplay.__init__(self, geometry, ax=camera_axis) self._active_pixel.set_linewidth(1.5) self.geom = geometry self.waveform_yaxis_label = waveform_axis_ylabel self.waveform_data = waveform_data self.waveform_axis_list = waveform_axis_list geometry_text = "Geometry = {}".format(geometry.cam_id) self.camera_axis.text(0.01, 0.99, geometry_text, horizontalalignment='left', verticalalignment='top', transform=self.camera_axis.transAxes)
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')
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
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()
def _display_camera_animation(self): # plt.style.use("ggplot") fig = plt.figure(num="ctapipe Camera Demo", figsize=(7, 7)) ax = plt.subplot(111) # load the camera tel = TelescopeDescription.from_name(optics_name=self.optics, camera_name=self.camera) geom = tel.camera # poor-man's coordinate transform from telscope to camera frame (it's # better to use ctapipe.coordiantes when they are stable) foclen = tel.optics.equivalent_focal_length.to(geom.pix_x.unit).value fov = np.deg2rad(4.0) scale = foclen minwid = np.deg2rad(0.1) maxwid = np.deg2rad(0.3) maxlen = np.deg2rad(0.5) self.log.debug("scale={} m, wid=({}-{})".format(scale, minwid, maxwid)) disp = CameraDisplay( geom, ax=ax, autoupdate=True, title="{}, f={}".format(tel, tel.optics.equivalent_focal_length) ) disp.cmap = plt.cm.terrain def update(frame): centroid = np.random.uniform(-fov, fov, size=2) * scale width = np.random.uniform(0, maxwid-minwid) * scale + minwid length = np.random.uniform(0, maxlen) * scale + width angle = np.random.uniform(0, 360) intens = np.random.exponential(2) * 500 model = toymodel.generate_2d_shower_model(centroid=centroid, width=width, length=length, psi=angle * u.deg) self.log.debug( "Frame=%d width=%03f length=%03f intens=%03d", frame, width, length, intens ) image, sig, bg = toymodel.make_toymodel_shower_image( geom, model.pdf, intensity=intens, nsb_level_pe=3, ) # alternate between cleaned and raw images if self._counter == self.cleanframes: plt.suptitle("Image Cleaning ON") self.imclean = True if self._counter == self.cleanframes * 2: plt.suptitle("Image Cleaning OFF") self.imclean = False self._counter = 0 disp.clear_overlays() if self.imclean: cleanmask = tailcuts_clean(geom, image, picture_thresh=10.0, boundary_thresh=5.0) for ii in range(2): dilate(geom, cleanmask) image[cleanmask == 0] = 0 # zero noise pixels try: hillas = hillas_parameters(geom, image) disp.overlay_moments(hillas, with_label=False, color='red', alpha=0.7, linewidth=2, linestyle='dashed') except HillasParameterizationError: disp.clear_overlays() pass self.log.debug("Frame=%d image_sum=%.3f max=%.3f", self._counter, image.sum(), image.max()) disp.image = image if self.autoscale: disp.set_limits_percent(95) else: disp.set_limits_minmax(-5, 200) disp.axes.figure.canvas.draw() self._counter += 1 return [ax, ] frames = None if self.num_events == 0 else self.num_events repeat = True if self.num_events == 0 else False self.log.info("Running for {} frames".format(frames)) self.anim = FuncAnimation(fig, update, interval=self.delay, frames=frames, repeat=repeat, blit=self.blit) if self.display: plt.show()
from ctapipe.image import toymodel from ctapipe.io import CameraGeometry from ctapipe.visualization import CameraDisplay from matplotlib import pyplot as plt if __name__ == '__main__': plt.style.use('ggplot') fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(1, 1, 1) geom = CameraGeometry.from_name('hess', 1) 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) plt.show()
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()
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.05, length=0.15, psi='35d' ) image, sig, bg = toymodel.make_toymodel_shower_image( geom, model.pdf, intensity=1500, nsb_level_pe=5 ) disp.image = image mask = disp.image > 10 disp.highlight_pixels(mask, linewidth=2, color='crimson') plt.show()
def draw_neighbors(geom, pixel_index, color='r', **kwargs): """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,
from ctapipe.visualization import CameraDisplay 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,
plt.style.use("ggplot") fig, ax = plt.subplots() # 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, )
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()
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
""" Example of drawing a Camera using a toymodel shower image. """ import matplotlib.pylab as plt from ctapipe.image import toymodel, hillas_parameters, tailcuts_clean from ctapipe.instrument import CameraGeometry from ctapipe.visualization import CameraDisplay if __name__ == '__main__': # Load the camera geom = CameraGeometry.from_name("LSTCam") disp = CameraDisplay(geom) disp.add_colorbar() # Create a fake camera image to display: model = toymodel.generate_2d_shower_model( centroid=(0.2, 0.0), width=0.05, length=0.15, psi='35d' ) image, sig, bg = toymodel.make_toymodel_shower_image( geom, model.pdf, intensity=1500, nsb_level_pe=3 ) # Apply image cleaning cleanmask = tailcuts_clean( geom, image, picture_thresh=10, boundary_thresh=5 )