Example #1
0
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
Example #2
0
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()
Example #3
0
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()
Example #4
0
class ImagePlotter(Component):
    """ Plotter for camera images """

    display = Bool(
        True,
        help="Display the photoelectron images on-screen as they are produced."
    ).tag(config=True)
    output_path = traits.Path(
        directory_ok=False,
        help=("Output path for the pdf containing all the images."
              " Set to None for no saved output."),
    ).tag(config=True)

    def __init__(self, subarray, 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_peak_time = None
        self.cb_intensity = None
        self.cb_peak_time = None
        self.pdf = None
        self.subarray = subarray

        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_peak_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)

    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 finish(self):
        if self.pdf is not None:
            self.log.info("Closing PDF")
            self.pdf.close()
Example #5
0
    def start(self):

        # Get first event information
        first_event = self.reader.get_event(0)
        n_pixels = first_event.inst.num_pixels[0]
        n_samples = first_event.r0.tel[0].num_samples
        pos = first_event.inst.pixel_pos[0]
        foclen = first_event.inst.optical_foclen[0]
        geom = CameraGeometry.guess(*pos, foclen)

        # Setup Output
        output_dir = self.reader.output_directory
        title = self.reader.filename
        title = title[:title.find("_")]
        # Prepare Output
        if not exists(output_dir):
            self.log.info("Creating directory: {}".format(output_dir))
            makedirs(output_dir)
        output_path = join(output_dir, title + "_events.pdf")

        # Setup plot
        fig = plt.figure(figsize=(10, 10))
        ax_camera = fig.add_subplot(1, 1, 1)
        fig.patch.set_visible(False)
        ax_camera.axis('off')
        camera = CameraDisplay(geom,
                               ax=ax_camera,
                               image=np.zeros(2048),
                               cmap='viridis')
        camera.add_colorbar()
        cb = camera.colorbar
        camera.colorbar.set_label("Amplitude (p.e.)")
        fig.suptitle(title)

        source = self.reader.read()
        desc = "Looping through file"
        with PdfPages(output_path) as pdf:
            for event in tqdm(source, desc=desc):
                ev = event.count
                event_id = event.r0.event_id
                self.r1.calibrate(event)
                self.dl0.reduce(event)
                self.dl1.calibrate(event)
                for t in event.r0.tels_with_data:
                    dl1 = event.dl1.tel[t].image[0]

                    # Cleaning
                    tc = tailcuts_clean(geom, dl1, 20, 10)
                    if not tc.any():
                        continue
                    cleaned_dl1 = np.ma.masked_array(dl1, mask=~tc)

                    try:
                        # hillas = hillas_parameters(*pos, cleaned_tc)
                        hillas = hillas_parameters_4(*pos, cleaned_dl1)
                    except HillasParameterizationError:
                        continue

                    ax_camera.cla()
                    camera = CameraDisplay(geom,
                                           ax=ax_camera,
                                           image=np.zeros(2048),
                                           cmap='viridis')
                    camera.colorbar = cb
                    camera.image = dl1
                    max_ = cleaned_dl1.max()  # np.percentile(dl1, 99.9)
                    min_ = np.percentile(dl1, 0.1)
                    camera.set_limits_minmax(min_, max_)
                    camera.highlight_pixels(tc, 'white')
                    camera.overlay_moments(hillas, color='red')
                    camera.update(True)
                    ax_camera.set_title("Event: {}".format(event_id))
                    ax_camera.axis('off')

                    pdf.savefig(fig)

        self.log.info("Created images: {}".format(output_path))
Example #6
0
class ImagePlotter(Component):
    """ Plotter for camera images """

    display = Bool(
        True,
        help="Display the photoelectron images on-screen as they are produced."
    ).tag(config=True)
    output_path = traits.Path(
        directory_ok=False,
        help=("Output path for the pdf containing all the images."
              " Set to None for no saved output."),
    ).tag(config=True)

    def __init__(self, subarray, 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_peak_time = None
        self.cb_intensity = None
        self.cb_peak_time = None
        self.pdf = None
        self.subarray = subarray

        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_peak_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)

    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 finish(self):
        if self.pdf is not None:
            self.log.info("Closing PDF")
            self.pdf.close()