def display_telescope(calibrated_data,cam,tel_id,pdffilename): logger.info("Tel_ID %d\n"%tel_id) pp = PdfPages("%s"%pdffilename) global fig for event in calibrated_data: tels = list(event.dl0.tels_with_data) logger.debug(tels) # Select telescope if tel_id not in tels: continue fig.clear() # geom = cam['CameraTable_VersionFeb2016_TelID%s'%tel_id] geom = io.CameraGeometry.guess(*event.meta.pixel_pos[tel_id], event.meta.optical_foclen[tel_id]) # Select number of pads to display. It depends on the numberr of gains: nchan = event.dl0.tel[tel_id].num_channels plt.suptitle("EVENT {} {:.1e} TeV @({:.1f},{:.1f})deg @{:.1f} m".format( event.dl0.event_id, get_mc_shower_energy(), get_mc_shower_altitude(), get_mc_shower_azimuth(), np.sqrt(pow(get_mc_event_xcore(), 2) + pow(get_mc_event_ycore(), 2)))) print("\t draw cam {} (gains={})...".format(tel_id,nchan)) print("RUN/EVT:",event.dl0.run_id,event.dl0.event_id) ax=[] disp=[] signals=[] npads=0 for i in range(nchan): npads += 1 # Display the camera charge (HG/LG) ax.append(plt.subplot(nchan, 2, npads)) disp.append(visualization.CameraDisplay(geom, ax=ax[-1], title="CT{} [{} ADC cts]".format(tel_id,gain_label[i]))) disp[-1].pixels.set_antialiaseds(False) signals.append(event.dl0.tel[tel_id].adc_sums[i]) disp[-1].image = signals[-1] disp[-1].pixels.set_cmap(get_cmap(disp[-1].image)) disp[-1].add_colorbar(label=" [{} ADC cts]".format(gain_label[i])) # Display the camera charge for significant pixels (HG/LG) npads += 1 ax.append(plt.subplot(nchan, 2, npads)) disp.append(visualization.CameraDisplay(geom, ax=ax[-1], title="CT{} [{} ADC cts]".format(tel_id,gain_label[i]))) disp[-1].pixels.set_antialiaseds(False) signals.append(event.dl0.tel[tel_id].adc_sums[i]) m = (get_zero_sup_mode(tel_id) & 0x001) or (get_significant(tel_id) & 0x020) disp[-1].image = signals[-1]*(m/m.max()) disp[-1].pixels.set_cmap(get_cmap(disp[-1].image)) disp[-1].add_colorbar(label=" [{} ADC cts]".format(gain_label[i])) plt.pause(0.1) pp.savefig(fig) pp.close()
def display_var(hist, geom, title='Gain [ADC/p.e.]', index_var=1, limit_min=0., limit_max=10., bin_width=0.2): f, ax = plt.subplots(1, 2, figsize=(20, 7)) plt.subplot(1, 2, 1) vis_gain = visualization.CameraDisplay(geom, title='', norm='lin', cmap='viridis') vis_gain.add_colorbar() vis_gain.colorbar.set_label(title) h = np.copy(hist.fit_result[:, index_var, 0]) h_err = np.copy(hist.fit_result[:, index_var, 1]) h[np.isnan(h_err)] = limit_min h[h < limit_min] = limit_min h[h > limit_max] = limit_max vis_gain.image = h # plt.subplot(1,2,2) hh, bin_tmp = np.histogram(h, bins=np.arange(limit_min - bin_width / 2, limit_max + 1.5 * bin_width, bin_width)) hh_hist = histogram(data=hh.reshape(1, hh.shape[0]), bin_centers=np.arange(limit_min, limit_max + bin_width, bin_width), xlabel=title, ylabel='$\mathrm{N_{pixel}/%.2f}$' % bin_width, label='All pixels') hh_hist.show(which_hist=(0, ), axis=ax[1], show_fit=False) plt.show()
def draw_several_cams(geom): ncams = 4 cmaps = [plt.cm.jet, plt.cm.afmhot, plt.cm.terrain, plt.cm.autumn] fig, ax = plt.subplots(1, ncams, figsize=(15, 4), sharey=True, sharex=True) for ii in range(ncams): disp = visualization.CameraDisplay(geom, ax=ax[ii], title="CT{}".format(ii + 1)) disp.cmap = cmaps[ii] model = mock.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 = mock.make_mock_shower_image(geom, model.pdf, intensity=50, nsb_level_pe=1000) clean = image.copy() clean[image <= 3.0 * image.mean()] = 0.0 hillas = hillas_parameters(geom.pix_x.value, geom.pix_y.value, clean) disp.image = image 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), sharey=True, sharex=True) for ii in range(ncams): disp = visualization.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, ) clean = image.copy() clean[image <= 3.0 * image.mean()] = 0.0 hillas = hillas_parameters(geom.pix_x, geom.pix_y, clean) disp.image = image disp.add_colorbar(ax=axs[ii]) disp.set_limits_percent(95) disp.overlay_moments(hillas, linewidth=3, color='blue')
def _display_cam_animation(): plt.style.use("ggplot") fig, ax = plt.subplots() # load the camera geom = io.get_camera_geometry("hess", 1) disp = visualization.CameraDisplay(geom, ax=ax) 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 = mock.generate_2d_shower_model(centroid=centroid, width=width, length=length, psi=angle * u.deg) image, sig, bg = mock.make_mock_shower_image(geom, model.pdf, intensity=intens, nsb_level_pe=5000) image /= image.max() disp.image = image disp.set_limits_percent(100) anim = FuncAnimation(fig, update, interval=50) plt.show()
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 = visualization.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 get_camera_view(self, tel_id, image, axis): """ Create camera viewer for a given camera image Parameters ---------- tel_id: int Telescope ID number image: ndarray Array of calibrated pixel intensities axis: matplotlib axis Axis on which to draw plot Returns ------- Camera display """ #if tel_id not in self.cam_display: # Argh this is annoying, for some reason we cannot cahe the displays self.cam_display[tel_id] = visualization.CameraDisplay( self.geom[tel_id], title="CT{0}".format(tel_id)) self.cam_display[tel_id].add_colorbar() self.cam_display[tel_id].pixels.set_antialiaseds(False) self.cam_display[tel_id].autoupdate = True self.cam_display[tel_id].cmap = "viridis" self.cam_display[tel_id].ax = axis self.cam_display[tel_id].image = image self.cam_display[tel_id].set_limits_percent(95) return self.cam_display[tel_id]
def display_telescope(event, tel_id): global fig ntels = len(event.dl1.tels_with_data) fig.clear() plt.suptitle("EVENT {} {:.1e} TeV @({:.1f},{:.1f})deg @{:.1f} m".format( event.dl1.event_id, get_mc_shower_energy(), get_mc_shower_altitude(), get_mc_shower_azimuth(), np.sqrt(pow(get_mc_event_xcore(), 2) + pow(get_mc_event_ycore(), 2)))) print("\t draw cam {}...".format(tel_id)) x, y = event.meta.pixel_pos[tel_id] #geom = io.CameraGeometry.guess(x * u.m, y * u.m) geom = io.CameraGeometry.guess(x, y) npads = 1 # Only create two pads if there is timing information extracted # from the calibration if not event.dl1.tel[tel_id].tom is None: npads = 2 ax = plt.subplot(1, npads, npads - 1) disp = visualization.CameraDisplay(geom, ax=ax, title="CT{0}".format(tel_id)) disp.pixels.set_antialiaseds(False) disp.autoupdate = False disp.pixels.set_cmap('seismic') chan = 0 signals = event.dl1.tel[tel_id].pe_charge disp.image = signals disp.add_colorbar() if npads == 2: ax = plt.subplot(1, npads, npads) disp = visualization.CameraDisplay(geom, ax=ax, title="CT{0}".format(tel_id)) disp.pixels.set_antialiaseds(False) disp.autoupdate = False disp.pixels.set_cmap('gnuplot') chan = 0 disp.image = event.dl1.tel[tel_id].tom disp.add_colorbar() if __debug__: print("All sum = %.3f\n" % sum(event.dl1.tel[tel_id].pe_charge))
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 = io.CameraGeometry.from_name("hess", 1) disp = visualization.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 = cleaning.tailcuts_clean(geom, image, pedvars=80) for ii in range(3): cleaning.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 initialise_plots(self): # first load in a very nasty way the camera geometry pix_x, pix_y, pix_id = [], [], [] pixels = self.cts.camera.Pixels pixelspresent = list(self.cts.pixel_to_led['DC'].keys()) for pix in pixels: if pix.ID in pixelspresent: pix_x.append(pix.center[0]) pix_y.append(pix.center[1]) pix_id.append(pix.ID) else: pix_x.append(-200.) pix_y.append(-200.) pix_id.append(pix.ID) pix_x = list(pix_x) pix_y = list(pix_y) pix_id = list(pix_id) neighbors_pix = find_neighbor_pixels(pix_x, pix_y, 30.) geom = CameraGeometry(0, pix_id, pix_x * u.mm, pix_y * u.mm, np.ones((1296)) * 400., 'hexagonal', neighbors=neighbors_pix) plt.figure(0, figsize=(20, 6)) self.plots = [] plt.subplot(1, 2, 1) self.plots.append( visualization.CameraDisplay(geom, title='AC status', norm='lin', cmap='coolwarm')) self.plots[-1].add_colorbar() self.plots[-1].image = np.multiply(self.ac_status, self.ac_level) plt.subplot(1, 2, 2) self.plots.append( visualization.CameraDisplay(geom, title='DC status', norm='lin', cmap='coolwarm')) self.plots[-1].add_colorbar() self.plots[-1].image = np.multiply(self.dc_status, self.dc_level)
def display_fit_result(hist, geom=None, index_var=1, limits=[0., 10.], bin_width=0.2): """ A function to display a vaiable both as an histogram and as a camera view :param hist: the histogram holding the fit result (utils.histogram.Histogram) :param geom: the geometry. if None only display histogram (ctapipe.io.camera.CameraGeometry) :param title: the z-label in camera view, x-label in histogram view (str) :param index_var: the index of the variable in the fit_result array (int) :param limits: the minimal and maximal values for the variable (list(int)) :param bin_width: the bin width for the variable (float) :return: """ # Set the limits h = np.copy(hist.fit_result[:, index_var, 0]) h_err = np.copy(hist.fit_result[:, index_var, 1]) h[np.isnan(h_err)] = limits[0] h[h < limits[0]] = limits[0] h[h > limits[1]] = limits[1] f, ax = None, None if geom: f, ax = plt.subplots(1, 2, figsize=(20, 7)) plt.subplot(1, 2, 1) vis_gain = visualization.CameraDisplay(geom, title='', norm='lin', cmap='viridis') vis_gain.add_colorbar() vis_gain.colorbar.set_label(hist.fit_result_label[index_var]) vis_gain.image = h plt.subplot(1, 2, 2) else: f, ax = plt.subplots(1, 1, figsize=(10, 7)) plt.subplot(1, 1, 1) # Create the variable histogram hh, bin_tmp = np.histogram( h, bins=np.arange(limits[0] - bin_width / 2, limits[2] + 1.5 * bin_width, bin_width), ) plt.step(hh, axis=np.arange(limits[0], limits[1] + bin_width, bin_width), label='All pixels', color='k', lw='1') plt.errorbar(np.arange(limits[0], limits[1] + bin_width, hh, bin_width), yerr=np.sqrt(hh)) plt.xlabel(hist.fit_result_label[index_var]) plt.ylabel('$\mathrm{N_{pixel}/%.2f}$' % bin_width) plt.show()
def _display_cam_animation(self): plt.style.use("ggplot") fig = plt.figure(num="ctapipe Camera Demo", figsize=(7, 7)) ax = plt.subplot(111) # load the camera geom = io.CameraGeometry.from_name("hess", 1) disp = visualization.CameraDisplay(geom, ax=ax) 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 = mock.generate_2d_shower_model(centroid=centroid, width=width, length=length, psi=angle * u.deg) image, sig, bg = mock.make_mock_shower_image(geom, model.pdf, intensity=intens, nsb_level_pe=5000) # alternate between cleaned and raw images if self._counter > 20: plt.suptitle("Image Cleaning ON") cleanmask = reco.cleaning.tailcuts_clean(geom, image, pedvars=80) for ii in range(3): reco.cleaning.dilate(geom, cleanmask) image[cleanmask == 0] = 0 # zero noise pixels if self._counter >= 40: plt.suptitle("Image Cleaning OFF") self._counter = 0 disp.image = image disp.set_limits_percent(100) self._counter += 1 anim = FuncAnimation(fig, update, interval=100) plt.show()
import matplotlib.pylab as plt import numpy as np from astropy import units as u from ctapipe import io, visualization from ctapipe.image import toymodel from matplotlib.animation import FuncAnimation if __name__ == '__main__': plt.style.use("ggplot") fig, ax = plt.subplots() # load the camera geom = io.CameraGeometry.from_name("hess", 1) disp = visualization.CameraDisplay(geom, ax=ax) disp.cmap = plt.cm.terrain disp.add_colorbar(ax=ax) 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, )
disp = None print('SELECTING EVENTS FROM TELESCOPE {}'.format(args.tel)) print('=' * 70) for event in source: print('Scanning input file... count = {}'.format(event.count)) print(event.trig) print(event.mc) print(event.dl0) if disp is None: x, y = event.meta.pixel_pos[args.tel] geom = io.CameraGeometry.guess(x, y) disp = visualization.CameraDisplay(geom, title='CT%d' % args.tel) disp.enable_pixel_picker() disp.add_colorbar() plt.show(block=False) # display the event disp.axes.set_title('CT{:03d}, event {:010d}'.format( args.tel, event.dl0.event_id)) if args.show_samples: # display time-varying event data = event.dl0.tel[args.tel].adc_samples[args.channel] for ii in range(data.shape[1]): disp.image = apply_mc_calibration(data[:, ii], args.tel) disp.set_limits_percent(70) plt.pause(0.01) if args.write:
def display_event(event, calibrate = 0, max_tel = 4, cleaning=None): """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 = min(max_tel, len(event.dl0.tels_with_data)) fig.clear() plt.suptitle("EVENT {}".format(event.dl0.event_id)) disps = [] mc_sum = None all_moments = [] for ii, tel_id in enumerate(event.dl0.tels_with_data): if ii >= max_tel: break print("\t draw cam {}...".format(tel_id)) nn = int(ceil((ntels)**.5)) ax = plt.subplot(nn, 2*nn, 2*(ii+1)-1) x, y = event.inst.pixel_pos[tel_id] geom = io.CameraGeometry.guess(x, y, event.inst.optical_foclen[tel_id]) disp = visualization.CameraDisplay(geom, ax=ax, title="CT{0} DetectorResponse".format(tel_id)) disp.pixels.set_antialiaseds(False) disp.autoupdate = False disp.cmap = plt.cm.hot chan = 0 signals = event.dl0.tel[tel_id].adc_sums[chan].astype(float)[:] if calibrate: signals = apply_mc_calibration_ASTRI(event.dl0.tel[tel_id].adc_sums, tel_id) if cleaning == 'tailcut': mask = tailcuts_clean(geom, signals, 1,picture_thresh=10.,boundary_thresh=8.) dilate(geom, mask) signals[mask==False] = 0 moments = hillas_parameters_2(geom.pix_x, geom.pix_y, signals) disp.image = signals disp.overlay_moments(moments, color='seagreen', linewidth=3) disp.set_limits_percent(95) disp.add_colorbar() disps.append(disp) ax = plt.subplot(nn, 2*nn, 2*(ii+1)) geom = io.CameraGeometry.guess(x, y, event.inst.optical_foclen[tel_id]) disp = visualization.CameraDisplay(geom, ax=ax, title="CT{0} PhotoElectrons".format(tel_id)) disp.pixels.set_antialiaseds(False) disp.autoupdate = False disp.cmap = plt.cm.hot chan = 0 #print (event.mc.tel[tel_id].photo_electrons) for jj in range(len(event.mc.tel[tel_id].photo_electron_image)): event.dl0.tel[tel_id].adc_sums[chan][jj] = event.mc.tel[tel_id].photo_electron_image[jj] signals2 = event.dl0.tel[tel_id].adc_sums[chan].astype(float) moments2 = hillas_parameters_2(geom.pix_x, geom.pix_y, signals2) all_moments.append(moments2) if mc_sum is None: mc_sum = signals2 else: scale = 3 if tel_id == 37 else 1 for i, val in enumerate(signals2): mc_sum[i] += val/scale disp.image = mc_sum for moments2 in all_moments: disp.overlay_moments(moments2, color='seagreen', linewidth=2) disp.set_limits_percent(95) disp.add_colorbar() disps.append(disp) return disps
if datatype == 'MC': inputfile_reader = hessio_event_source(filename) else: inputfile_reader = zfits.zfits_event_source( url= "/data/datasets/CTA/[email protected]_0_000.36.fits.fz", data_type='r1', max_events=500) formatter = LogFormatter(10, labelOnlyBase=False) plt.figure(0) displayType = [] plt.subplot(2, 3, 1) displayType.append( visualization.CameraDisplay(geom, title='Pedestal Variation log', norm='lin', cmap='coolwarm')) displayType[-1].add_colorbar() plt.subplot(2, 3, 2) displayType.append( visualization.CameraDisplay(geom, title='Pedestals', norm='lin', cmap='coolwarm')) displayType[-1].add_colorbar() plt.subplot(2, 3, 3) displayType.append( visualization.CameraDisplay(geom, title='Pedestal With Low var', norm='lin', cmap='coolwarm'))
axis=0) inputfile_reader = zfits.zfits_event_source( url= "/data/datasets/CTA/[email protected]_0_000.36.fits.fz", data_type='r1', max_events=2130) if plotting: plt.figure(0) displayType = [] plt.subplot(1, 1, 1) displayType.append( visualization.CameraDisplay( geom, title='Integrated ADC over 200ns, pedestal subtracted', norm='lin', cmap='coolwarm')) neigh_mask = generate_neighbourg_masks() hollow_neigh_mask = generate_hollow_neighbourg_masks() min_evtcounter = 3383 - 3018 best_pix = -1 h, h1 = [], [] evt_counter = 0 cnt = 0 for event in inputfile_reader: evt_counter += 1 if evt_counter < min_evtcounter: continue for telid in event.r1.tels_with_data: