示例#1
0
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 make_camera_binary_image(image, sigma, clean_bound, death_pixel_ids_list):
    fig, ax = plt.subplots(1, 2, figsize=(14, 7))

    geom = CameraGeometry.from_name('LSTCam-003')
    disp0 = CameraDisplay(geom, ax=ax[0])
    disp0.image = image
    disp0.cmap = plt.cm.gnuplot2
    disp0.add_colorbar(ax=ax[0])
    ax[0].set_title(
        "Cleaning threshold from interleaved pedestal. \n sigma = {}".format(
            sigma),
        fontsize=15)

    disp1 = CameraDisplay(geom, ax=ax[1])
    disp1.image = image
    cmap = matplotlib.colors.ListedColormap(['black', 'red'])
    bounds = [0, clean_bound, 2 * clean_bound]
    norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N)
    disp1.cmap = cmap
    disp1.add_colorbar(norm=norm,
                       boundaries=bounds,
                       ticks=[0, clean_bound, 2 * clean_bound])
    disp1.set_limits_minmax(0, 2 * clean_bound)
    disp1.highlight_pixels(death_pixel_ids_list, linewidth=3)
    ax[1].set_title("Red pixels - above cleaning tailcut threshold",
                    fontsize=15)
    plt.tight_layout()
    plt.show()
示例#3
0
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_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 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)
示例#6
0
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()
示例#7
0
    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)
示例#8
0
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
示例#9
0
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()
示例#10
0
def test_camera_display_multiple():
    """ create a figure with 2 subplots, each with a CameraDisplay """
    from ..mpl_camera import CameraDisplay

    geom = CameraGeometry.from_name("LSTCam")
    fig, ax = plt.subplots(2, 1)

    d1 = CameraDisplay(geom, ax=ax[0])
    d2 = CameraDisplay(geom, ax=ax[1])

    image = np.ones(len(geom.pix_x), dtype=float)
    d1.image = image
    d2.image = image
示例#11
0
    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)
示例#12
0
    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)
示例#13
0
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
示例#14
0
def plot_muon_event(ax, geom, image, centroid, ringrad_camcoord, 
                    ringrad_inner, ringrad_outer, event_id):
    """
    

    Paramenters
    ---------
    ax:               `matplotlib.pyplot.axis`
    geom:             CameraGeometry  
    centroid:         `float` centroid of the muon ring
    ringrad_camcoord: `float` ring radius in camera coordinates
    ringrad_inner:    `float` inner ring radius in camera coordinates
    ringrad_outer:    `float` outer ring radius in camera coordinates
    event_id:         `int` id of the analyzed event

    Returns
    ---------
    ax:               `matplotlib.pyplot.axis`
    """

    disp0 = CameraDisplay(geom, ax=ax)
    disp0.image = image
    disp0.cmap = 'viridis'
    disp0.add_colorbar(ax=ax)
    disp0.add_ellipse(centroid, ringrad_camcoord.value,
                  ringrad_camcoord.value, 0., 0., color="red")
    disp0.add_ellipse(centroid, ringrad_inner.value,
                                    ringrad_inner.value, 0., 0.,
                                    color="magenta")
    disp0.add_ellipse(centroid, ringrad_outer.value,
                                    ringrad_outer.value, 0., 0.,
                                    color="magenta")
    ax.set_title(f"Event {event_id}")

    return ax
示例#15
0
    def start(self):
        geom = None
        imsum = None
        disp = None

        for data in hessio_event_source(self.infile,
                                        allowed_tels=self._selected_tels,
                                        max_events=None):
            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.r0.tels_with_data) <= 2:
                continue

            imsum[:] = 0
            for telid in data.r0.tels_with_data:
                imsum += data.r0.tel[telid].adc_sums[0]

            self.log.info("event={} ntels={} energy={}" \
                          .format(data.r0.event_id,
                                  len(data.r0.tels_with_data),
                                  data.mc.energy))
            disp.image = imsum
            plt.pause(0.1)
示例#16
0
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
示例#17
0
def test_camera_display_single():
    """ test CameraDisplay functionality """
    from ..mpl_camera import CameraDisplay

    geom = CameraGeometry.from_name("LSTCam")
    disp = CameraDisplay(geom)
    image = np.random.normal(size=len(geom.pix_x))
    disp.image = image
    disp.add_colorbar()
    disp.cmap = "nipy_spectral"
    disp.set_limits_minmax(0, 10)
    disp.set_limits_percent(95)
    disp.enable_pixel_picker()
    disp.highlight_pixels([1, 2, 3, 4, 5])
    disp.norm = "log"
    disp.norm = "symlog"
    disp.cmap = "rainbow"

    with pytest.raises(ValueError):
        disp.image = np.ones(10)

    with pytest.raises(ValueError):
        disp.add_colorbar()

    disp.add_ellipse(centroid=(0, 0), width=0.1, length=0.1, angle=0.1)
    disp.clear_overlays()
示例#18
0
    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

            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 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()
示例#20
0
    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
示例#21
0
    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)
示例#22
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
示例#23
0
    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()
示例#24
0
def Simple_CamPlot(image, geom, pix_ids, title=""):
    disp1 = CameraDisplay(geom, title=title)
    disp1.add_colorbar()
    disp1.set_limits_minmax(zmin=image.min() * 0.98, zmax=image.max() * 1.02)
    blankam1 = np.zeros(1855)
    blankam1[pix_ids] = image
    disp1.image = blankam1
    plt.show()
示例#25
0
 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 make_camera_image(image):
    plt.figure(figsize=(6, 6))
    geom = CameraGeometry.from_name('LSTCam-003')
    disp = CameraDisplay(geom)
    disp.image = image
    disp.cmap = plt.cm.gnuplot2
    disp.add_colorbar()
    plt.show()
示例#27
0
    def plot_event_with_shower_position_seperate_events(self, event1, event2):
        
        x, y, alt, az = self.transform_to_telescope_xy_altaz_from_event(event1)
        
        x = x.to_value(u.m)
        y = y.to_value(u.m)
        
        # Cameras
        m1_cam = copy.deepcopy(event1.inst.subarray.tel[1].camera)
        m2_cam = copy.deepcopy(event2.inst.subarray.tel[2].camera)

        m1_cam.rotate(-19.1*u.deg)#(-90+70.9)
        m2_cam.rotate((-90+70.9)*u.deg)

        # Charge images
        m1_event_image = event1.dl1.tel[1].image
        m2_event_image = event2.dl1.tel[2].image

        # Peak position maps
        #m1_event_times = b5["M1"].dl1.tel[1].peakpos
        #m2_event_times = b5["M2"].dl1.tel[2].peakpos

        fig1, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15,10))

        # M1 charge map
        disp1 = CameraDisplay(m1_cam, m1_event_image, ax=ax1, title="MAGIC 1 image")
        disp1.add_colorbar(ax=ax1)

        # M2 charge map
        disp2 = CameraDisplay(m2_cam, m2_event_image,  ax=ax2, title="MAGIC 2 image")
        disp2.add_colorbar(ax=ax2)

        ax1.plot(x, y, marker='*', color='red')
        ax1.annotate(
            s="Peter", xy=(x, y), xytext=(5, 5),
            textcoords='offset points', color='red',

        )
        #ax1.scatter(cam.pix_x, cam.pix_y, marker="o", s=10, c='red')

        ax2.plot(x, y, marker='*', color='red')
        ax2.annotate(
            s="Peter", xy=(x, y), xytext=(5, 5),
            textcoords='offset points', color='red',
        )
示例#28
0
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)
示例#29
0
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 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()