Пример #1
0
def create_sample_image(psi='-30d'):

    seed(10)

    # set up the sample image using a HESS camera geometry (since it's easy
    # to load)
    geom = CameraGeometry.from_name("HESS", 1)

    # make a toymodel shower model
    model = toymodel.generate_2d_shower_model(centroid=(0.2, 0.3),
                                              width=0.001,
                                              length=0.01,
                                              psi=psi)

    # generate toymodel image in camera for this shower model.
    image, signal, noise = toymodel.make_toymodel_shower_image(
        geom, model.pdf, intensity=50, nsb_level_pe=100)

    # denoise the image, so we can calculate hillas params
    clean_mask = tailcuts_clean(geom, image, 1, 10,
                                5)  # pedvars = 1 and core and boundary
    # threshold in pe
    image[~clean_mask] = 0

    # Pixel values in the camera
    pix_x = geom.pix_x.value
    pix_y = geom.pix_y.value

    return pix_x, pix_y, image
Пример #2
0
        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 > 20:
                plt.suptitle("Image Cleaning ON")
                cleanmask = cleaning.tailcuts_clean(geom, image, pedvars=80)
                for ii in range(3):
                    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
Пример #3
0
def create_sample_image():
    # set up the sample image using a HESS camera geometry (since it's easy
    # to load)
    geom = CameraGeometry.from_name("HESS", 1)

    # make a toymodel shower model
    model = toymodel.generate_2d_shower_model(centroid=(0.2, 0.3),
                                              width=0.001, length=0.01,
                                              psi='30d')

    # generate toymodel image in camera for this shower model.
    image, signal, noise = toymodel.make_toymodel_shower_image(geom, model.pdf,
                                                               intensity=50,
                                                               nsb_level_pe=100)

    # denoise the image, so we can calculate hillas params
    clean_mask = tailcuts_clean(geom, image, 1, 10,
                                5)  # pedvars = 1 and core and boundary
    # threshold in pe
    image[~clean_mask] = 0

    # Pixel values in the camera
    pix_x = geom.pix_x.value
    pix_y = geom.pix_y.value

    return pix_x, pix_y, image
Пример #4
0
        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 > 20:
                plt.suptitle("Image Cleaning ON")
                cleanmask = cleaning.tailcuts_clean(geom, image, pedvars=80)
                for ii in range(3):
                    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
Пример #5
0
def create_sample_image(psi='-30d'):

    seed(10)

    # set up the sample image using a HESS camera geometry (since it's easy
    # to load)
    geom = CameraGeometry.from_name("LSTCam")

    # make a toymodel shower model
    model = toymodel.generate_2d_shower_model(
        centroid=(0.2, 0.3),
        width=0.05,
        length=0.15,
        psi=psi,
    )

    # generate toymodel image in camera for this shower model.
    image, signal, noise = toymodel.make_toymodel_shower_image(
        geom,
        model.pdf,
        intensity=1500,
        nsb_level_pe=3,
    )

    # denoise the image, so we can calculate hillas params
    clean_mask = tailcuts_clean(geom, image, 10, 5)

    return geom, image, clean_mask
Пример #6
0
def test_convert_geometry(cam_id, rot):

    geom = CameraGeometry.from_name(cam_id)

    if geom.pix_type=='rectangular':
        return  # skip non-hexagonal cameras, since they don't need conversion

    model = generate_2d_shower_model(centroid=(0.4, 0), width=0.01, length=0.03,
                                     psi="25d")

    _,image,_ = make_toymodel_shower_image(geom, model.pdf,
                                           intensity=50,
                                           nsb_level_pe=100)

    hillas_0 = hillas_parameters(geom.pix_x, geom.pix_y, image)

    geom2d, image2d = convert_geometry_1d_to_2d(geom, image,
                                                 geom.cam_id+str(rot),
                                                 add_rot=-2)
    geom1d, image1d = convert_geometry_back(geom2d, image2d,
                                            geom.cam_id+str(rot),
                                            add_rot=rot)
    hillas_1 = hillas_parameters(geom1d.pix_x, geom1d.pix_y, image1d)

    if __name__ == "__main__":
        plot_cam(geom, geom2d, geom1d, image, image2d, image1d)

    assert np.abs(hillas_1.phi - hillas_0.phi).deg < 1.0
Пример #7
0
def test_convert_geometry(cam_id, rot):

    geom = CameraGeometry.from_name(cam_id)

    if geom.pix_type == 'rectangular':
        return  # skip non-hexagonal cameras, since they don't need conversion

    model = generate_2d_shower_model(centroid=(0.4, 0), width=0.01, length=0.03,
                                     psi="25d")

    _, image, _ = make_toymodel_shower_image(geom, model.pdf,
                                             intensity=50,
                                             nsb_level_pe=100)

    hillas_0 = hillas_parameters(geom.pix_x, geom.pix_y, image)

    geom2d, image2d = convert_geometry_1d_to_2d(geom, image,
                                                geom.cam_id + str(rot),
                                                add_rot=rot)
    geom1d, image1d = convert_geometry_back(geom2d, image2d,
                                            geom.cam_id + str(rot),
                                            add_rot=rot)

    hillas_1 = hillas_parameters(geom1d.pix_x, geom1d.pix_y, image1d)

    if __name__ == "__main__":
        plot_cam(geom, geom2d, geom1d, image, image2d, image1d)
        plt.tight_layout()
        plt.pause(.1)

    assert np.abs(hillas_1.phi - hillas_0.phi).deg < 1.0
Пример #8
0
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')
Пример #9
0
def test_ChaudhuriKunduRingFitter():

    geom = CameraGeometry.from_name('HESS-I')

    ring_rad = np.deg2rad(
        1. * u.deg) * 15.  # make sure this is in camera coordinates
    ring_width = np.deg2rad(0.05 * u.deg) * 15.
    geom_pixall = np.empty(geom.pix_x.shape + (2, ))
    geom_pixall[..., 0] = geom.pix_x.value
    geom_pixall[..., 1] = geom.pix_y.value

    # image = generate_muon_model(geom_pixall, ring_rad, ring_width, 0.3, 0.2)
    muon_model = partial(toymodel.generate_muon_model,
                         radius=ring_rad.value,
                         width=ring_width.value,
                         centre_x=-0.2,
                         centre_y=-0.3)

    toymodel_image, toy_signal, toy_noise = \
        toymodel.make_toymodel_shower_image(geom, muon_model)

    clean_toy_mask = tailcuts_clean(geom,
                                    toymodel_image,
                                    boundary_thresh=5,
                                    picture_thresh=10)

    # camera_coord = CameraFrame(x=x,y=y,z=np.zeros(x.shape)*u.m,
    # focal_length = event.inst.optical_foclen[telid], rotation=geom.pix_rotation)
    muonring = muon_ring_finder.ChaudhuriKunduRingFitter(None)

    x = np.rad2deg((geom.pix_x.value / 15.) * u.rad)  # .value
    y = np.rad2deg((geom.pix_y.value / 15.) * u.rad)  # .value

    muonringparam = muonring.fit(x, y, toymodel_image * clean_toy_mask)

    dist = np.sqrt(
        np.power(x - muonringparam.ring_center_x, 2) +
        np.power(y - muonringparam.ring_center_y, 2))
    ring_dist = np.abs(dist - muonringparam.ring_radius)
    muonringparam = muonring.fit(
        x, y, toymodel_image * (ring_dist < muonringparam.ring_radius * 0.4))

    dist = np.sqrt(
        np.power(x - muonringparam.ring_center_x, 2) +
        np.power(y - muonringparam.ring_center_y, 2))
    ring_dist = np.abs(dist - muonringparam.ring_radius)
    muonringparam = muonring.fit(
        x, y, toymodel_image * (ring_dist < muonringparam.ring_radius * 0.4))

    print('Fitted ring radius', muonringparam.ring_radius, 'c.f.', ring_rad)
    print('Fitted ring centre', muonringparam.ring_center_x,
          muonringparam.ring_center_y)

    assert muonringparam.ring_radius is not ring_rad  # .value
    assert muonringparam.ring_center_x is not -0.2
    assert muonringparam.ring_center_y is not -0.3
Пример #10
0
def test_convert_geometry(cam_id, rot):

    geom = CameraGeometry.from_name(cam_id)

    model = generate_2d_shower_model(centroid=(0.4, 0),
                                     width=0.01,
                                     length=0.03,
                                     psi="25d")

    _, image, _ = make_toymodel_shower_image(geom,
                                             model.pdf,
                                             intensity=50,
                                             nsb_level_pe=100)

    hillas_0 = hillas_parameters(geom, image)

    if geom.pix_type == 'hexagonal':
        convert_geometry_1d_to_2d = convert_geometry_hex1d_to_rect2d
        convert_geometry_back = convert_geometry_rect2d_back_to_hexe1d

        geom2d, image2d = convert_geometry_1d_to_2d(geom,
                                                    image,
                                                    geom.cam_id + str(rot),
                                                    add_rot=rot)
        geom1d, image1d = convert_geometry_back(geom2d,
                                                image2d,
                                                geom.cam_id + str(rot),
                                                add_rot=rot)

    else:
        if geom.cam_id == "ASTRICam":
            convert_geometry_1d_to_2d = astri_to_2d_array
            convert_geometry_back = array_2d_to_astri
        elif geom.cam_id == "CHEC":
            convert_geometry_1d_to_2d = chec_to_2d_array
            convert_geometry_back = array_2d_to_chec
        else:
            print("camera {geom.cam_id} not implemented")
            return

        image2d = convert_geometry_1d_to_2d(image)
        image1d = convert_geometry_back(image2d)

    hillas_1 = hillas_parameters(geom, image1d)

    # if __name__ == "__main__":
    #     plot_cam(geom, geom2d, geom1d, image, image2d, image1d)
    #     plt.tight_layout()
    #     plt.pause(.1)

    assert np.abs(hillas_1.phi - hillas_0.phi).deg < 1.0
Пример #11
0
def test_ChaudhuriKunduRingFitter():

    geom = CameraGeometry.from_name('HESS-I')

    ring_rad = np.deg2rad(1. * u.deg) * 15.  # make sure this is in camera coordinates
    ring_width = np.deg2rad(0.05 * u.deg) * 15.
    geom_pixall = np.empty(geom.pix_x.shape + (2,))
    geom_pixall[..., 0] = geom.pix_x.value
    geom_pixall[..., 1] = geom.pix_y.value

    # image = generate_muon_model(geom_pixall, ring_rad, ring_width, 0.3, 0.2)
    muon_model = partial(toymodel.generate_muon_model, radius=ring_rad.value,
                         width=ring_width.value, centre_x=-0.2, centre_y=-0.3)

    toymodel_image, toy_signal, toy_noise = \
        toymodel.make_toymodel_shower_image(geom, muon_model)

    clean_toy_mask = tailcuts_clean(geom, toymodel_image,
                                    boundary_thresh=5, picture_thresh=10)

    muonring = muon_ring_finder.ChaudhuriKunduRingFitter(None)

    x = np.rad2deg((geom.pix_x.value / 15.) * u.rad)  # .value
    y = np.rad2deg((geom.pix_y.value / 15.) * u.rad)  # .value

    muonringparam = muonring.fit(x, y, toymodel_image * clean_toy_mask)

    dist = np.sqrt(np.power(x - muonringparam.ring_center_x, 2)
                   + np.power(y - muonringparam.ring_center_y, 2))
    ring_dist = np.abs(dist - muonringparam.ring_radius)
    muonringparam = muonring.fit(x, y, toymodel_image * (ring_dist <
                                                         muonringparam.ring_radius * 0.4))

    dist = np.sqrt(np.power(x - muonringparam.ring_center_x, 2) +
                   np.power(y - muonringparam.ring_center_y, 2))
    ring_dist = np.abs(dist - muonringparam.ring_radius)
    muonringparam = muonring.fit(x, y, toymodel_image * (ring_dist <
                                                         muonringparam.ring_radius * 0.4))

    print('Fitted ring radius', muonringparam.ring_radius, 'c.f.', ring_rad)
    print('Fitted ring centre', muonringparam.ring_center_x, muonringparam.ring_center_y)

    assert muonringparam.ring_radius is not ring_rad  # .value
    assert muonringparam.ring_center_x is not -0.2
    assert muonringparam.ring_center_y is not -0.3
Пример #12
0
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')
Пример #13
0
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')
Пример #14
0
def create_mock_image(geom):
    '''
    creates a mock image, which parameters are adapted to the camera size
    '''

    camera_r = np.max(np.sqrt(geom.pix_x**2 + geom.pix_y**2))
    model = generate_2d_shower_model(centroid=(0.3 * camera_r.value, 0),
                                     width=0.03 * camera_r.value,
                                     length=0.10 * camera_r.value,
                                     psi="25d")

    _, image, _ = make_toymodel_shower_image(
        geom,
        model.pdf,
        intensity=0.5 * geom.n_pixels,
        nsb_level_pe=3,
    )
    return image
Пример #15
0
        def update(frame):

            self.log.debug("Frame=", frame)
            centroid = np.random.uniform(-fov, fov, size=2) * scale
            width = np.random.uniform(0, maxwid) * scale
            length = np.random.uniform(0, maxlen) * scale + width
            angle = np.random.uniform(0, 360)
            intens = np.random.exponential(2) * 50
            model = toymodel.generate_2d_shower_model(centroid=centroid,
                                                      width=width,
                                                      length=length,
                                                      psi=angle * u.deg)
            image, sig, bg = toymodel.make_toymodel_shower_image(
                geom, 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,
            ]
Пример #16
0
def create_mock_image(geom):
    '''
    creates a mock image, which parameters are adapted to the camera size
    '''

    camera_r = np.max(np.sqrt(geom.pix_x**2 + geom.pix_y**2))
    model = generate_2d_shower_model(
        centroid=(0.3 * camera_r.value, 0),
        width=0.03 * camera_r.value,
        length=0.10 * camera_r.value,
        psi="25d"
    )

    _, image, _ = make_toymodel_shower_image(
        geom, model.pdf,
        intensity=0.5 * geom.n_pixels,
        nsb_level_pe=3,
    )
    return image
Пример #17
0
 def update(frame):
     centroid = np.random.uniform(-fov, fov, size=2) * scale
     width = np.random.uniform(0, maxwid) * scale
     length = np.random.uniform(0, maxlen) * scale + width
     angle = np.random.uniform(0, 360)
     intens = np.random.exponential(2) * 50
     model = toymodel.generate_2d_shower_model(
         centroid=centroid,
         width=width,
         length=length,
         psi=angle * u.deg,
     )
     image, sig, bg = toymodel.make_toymodel_shower_image(
         geom, model.pdf,
         intensity=intens,
         nsb_level_pe=5000,
     )
     image /= image.max()
     disp.image = image
Пример #18
0
def test_with_toy():
    np.random.seed(42)

    geom = CameraGeometry.from_name('LSTCam')

    width = 0.03
    length = 0.15
    intensity = 500

    xs = (0.5, 0.5, -0.5, -0.5)
    ys = (0.5, -0.5, 0.5, -0.5)
    psis = Angle([-90, -45, 0, 45, 90], unit='deg')

    for x, y in zip(xs, ys):
        for psi in psis:

            # make a toymodel shower model
            model = toymodel.generate_2d_shower_model(
                centroid=(x, y),
                width=width,
                length=length,
                psi=psi,
            )

            image, signal, noise = toymodel.make_toymodel_shower_image(
                geom,
                model.pdf,
                intensity=intensity,
                nsb_level_pe=5,
            )

            result = hillas_parameters(geom, signal)

            assert result.x.to_value(u.m) == approx(x, rel=0.1)
            assert result.y.to_value(u.m) == approx(y, rel=0.1)

            assert result.width.to_value(u.m) == approx(width, rel=0.1)
            assert result.length.to_value(u.m) == approx(length, rel=0.1)
            assert ((result.psi.to_value(u.deg) == approx(psi.deg, abs=2))
                    or abs(result.psi.to_value(u.deg) - psi.deg) == approx(
                        180.0, abs=2))

            assert signal.sum() == result.intensity
Пример #19
0
 def update(frame):
     centroid = np.random.uniform(-fov, fov, size=2) * scale
     width = np.random.uniform(0, maxwid) * scale
     length = np.random.uniform(0, maxlen) * scale + width
     angle = np.random.uniform(0, 360)
     intens = np.random.exponential(2) * 50
     model = toymodel.generate_2d_shower_model(
         centroid=centroid,
         width=width,
         length=length,
         psi=angle * u.deg,
     )
     image, sig, bg = toymodel.make_toymodel_shower_image(
         geom, model.pdf,
         intensity=intens,
         nsb_level_pe=5000,
     )
     image /= image.max()
     disp.image = image
Пример #20
0
        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,]
Пример #21
0
    def update(frame):
        centroid = 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.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=5,
        )
        disp.image = image
Пример #22
0
def test_convert_geometry_mock(cam_id, rot):
    """here we use a different key for the back conversion to trigger the mock conversion
    """

    geom = CameraGeometry.from_name(cam_id)

    model = generate_2d_shower_model(centroid=(0.4, 0),
                                     width=0.01,
                                     length=0.03,
                                     psi="25d")

    _, image, _ = make_toymodel_shower_image(geom,
                                             model.pdf,
                                             intensity=50,
                                             nsb_level_pe=100)

    hillas_0 = hillas_parameters(geom, image)

    if geom.pix_type == 'hexagonal':
        convert_geometry_1d_to_2d = convert_geometry_hex1d_to_rect2d
        convert_geometry_back = convert_geometry_rect2d_back_to_hexe1d

        geom2d, image2d = convert_geometry_1d_to_2d(geom,
                                                    image,
                                                    key=None,
                                                    add_rot=rot)
        geom1d, image1d = convert_geometry_back(
            geom2d,
            image2d,
            "_".join([geom.cam_id, str(rot), "mock"]),
            add_rot=rot)
    else:
        # originally rectangular geometries don't need a buffer and therefore no mock
        # conversion
        return

    hillas_1 = hillas_parameters(geom, image1d)
    assert np.abs(hillas_1.phi - hillas_0.phi).deg < 1.0
Пример #23
0
from ctapipe.instrument import CameraGeometry
from ctapipe.visualization import CameraDisplay

if __name__ == '__main__':

    plt.style.use('ggplot')

    fig = plt.figure(figsize=(12, 8))
    ax = fig.add_subplot(1, 1, 1)

    geom = CameraGeometry.from_name('NectarCam')
    disp = CameraDisplay(geom, ax=ax)
    disp.add_colorbar()

    model = toymodel.generate_2d_shower_model(centroid=(0.05, 0.0),
                                              width=0.005,
                                              length=0.025,
                                              psi='35d')

    image, sig, bg = toymodel.make_toymodel_shower_image(geom,
                                                         model.pdf,
                                                         intensity=50,
                                                         nsb_level_pe=20)

    disp.image = image

    mask = disp.image > 15
    disp.highlight_pixels(mask, linewidth=3)

    plt.show()
Пример #24
0
def toymodel_event_source(geoms,
                          max_events=100,
                          single_tel=False,
                          n_channels=1,
                          n_samples=25,
                          p_trigger=0.3):
    """
    An event source that produces array
    Parameters
    ----------
    geoms : list of CameraGeometry instances
        Geometries for the telescopes to simulate
    max_events : int, default: 100
        maximum number of events to create
    n_channels : int
        how many channels per telescope
    n_samples : int
        how many adc samples per pixel
    p_trigger : float
        mean trigger probability for the telescopes
    """
    n_telescopes = len(geoms)
    container = DataContainer()
    container.meta['toymodel__max_events'] = max_events
    container.meta['source'] = "toymodel"
    tel_ids = np.arange(n_telescopes)

    for event_id in range(max_events):

        n_triggered = np.random.poisson(n_telescopes * 0.3)
        if n_triggered > n_telescopes:
            n_triggered = n_telescopes

        triggered_tels = np.random.choice(tel_ids, n_triggered, replace=False)

        container.r0.event_id = event_id
        container.r0.tels_with_data = triggered_tels
        container.count = event_id

        # handle single-telescope case (ignore others:
        if single_tel:
            if single_tel not in container.r0.tels_with_data:
                continue
            container.r0.tels_with_data = [
                single_tel,
            ]

        container.r0.tel.reset()  # clear the previous telescopes
        t = np.arange(n_samples)

        for tel_id in container.r0.tels_with_data:
            geom = geoms[tel_id]

            # fill pixel position dictionary, if not already done:
            if tel_id not in container.inst.pixel_pos:
                container.inst.pixel_pos[tel_id] = (
                    geom.pix_x.value,
                    geom.pix_y.value,
                )

            centroid = np.random.uniform(geom.pix_x.min(), geom.pix_y.max(), 2)
            length = np.random.uniform(0.02, 0.2)
            width = np.random.uniform(0.01, length)
            psi = np.random.randint(0, 360)
            intensity = np.random.poisson(int(10000 * width * length))
            model = toymodel.generate_2d_shower_model(centroid, width, length,
                                                      '{}d'.format(psi))
            image, _, _ = toymodel.make_toymodel_shower_image(
                geom,
                model.pdf,
                intensity,
            )

            # container.r0.tel[tel_id] = R0CameraContainer()
            container.inst.num_channels[tel_id] = n_channels
            n_pix = len(geom.pix_id)
            means = np.random.normal(15, 1, (n_pix, 1))
            stds = np.random.uniform(3, 6, (n_pix, 1))
            samples = image[:, np.newaxis] * norm.pdf(t, means, stds)

            for chan in range(n_channels):
                container.r0.tel[tel_id].waveform[chan] = samples
                container.r0.tel[tel_id].image[chan] = image

        yield container
Пример #25
0
"""Example how to make a toymodel shower image and plot it.
"""
import matplotlib.pyplot as plt
from ctapipe.io.camera import make_rectangular_camera_geometry
from ctapipe.image.toymodel import generate_2d_shower_model, make_toymodel_shower_image

NX = 40
NY = 40

geom = make_rectangular_camera_geometry(NX, NY)

showermodel = generate_2d_shower_model(centroid=[0.25, 0.0], length=0.1,
                                       width=0.02, psi='40d')

image, signal, noise = make_toymodel_shower_image(geom, showermodel.pdf,
                                                  intensity=20, nsb_level_pe=30)

# make them into 2D arrays so we can plot them with imshow
image.shape = (NX, NY)
signal.shape = (NX, NY)
noise.shape = (NX, NY)

# here we just plot the images using imshow().  For a more general
# case, one should use a ctapipe.visualization.CameraDisplay
plt.figure(figsize=(10, 3))
plt.subplot(1, 3, 1)
plt.imshow(signal, interpolation='nearest', origin='lower')
plt.title("Signal")
plt.colorbar()
plt.subplot(1, 3, 2)
plt.imshow(noise, interpolation='nearest', origin='lower')
Пример #26
0
if __name__ == '__main__':

    # Load the camera
    geom = CameraGeometry.from_name("LSTCam")
    disp = CameraDisplay(geom)
    disp.set_limits_minmax(0, 300)
    disp.add_colorbar()

    # Create a fake camera image to display:
    model = toymodel.generate_2d_shower_model(centroid=(0.2, 0.0),
                                              width=0.01,
                                              length=0.1,
                                              psi='35d')

    image, sig, bg = toymodel.make_toymodel_shower_image(geom, model.pdf,
                                                         intensity=50,
                                                         nsb_level_pe=1000)

    # Apply image cleaning
    cleanmask = tailcuts_clean(geom, image, picture_thresh=200,
                               boundary_thresh=100)
    clean = image.copy()
    clean[~cleanmask] = 0.0

    # Calculate image parameters
    hillas = hillas_parameters(geom.pix_x, geom.pix_y, clean)
    print(hillas)

    # Show the camera image and overlay Hillas ellipse and clean pixels
    disp.image = image
    disp.cmap = 'PuOr'
Пример #27
0
def toymodel_event_source(geoms, max_events=100, single_tel=False, n_channels=1,
                          n_samples=25, p_trigger=0.3):
    """
    An event source that produces array
    Parameters
    ----------
    geoms : list of CameraGeometry instances
        Geometries for the telescopes to simulate
    max_events : int, default: 100
        maximum number of events to create
    n_channels : int
        how many channels per telescope
    n_samples : int
        how many adc samples per pixel
    p_trigger : float
        mean trigger probability for the telescopes
    """
    n_telescopes = len(geoms)
    container = DataContainer()
    container.meta['toymodel__max_events'] = max_events
    container.meta['source'] = "toymodel"
    tel_ids = np.arange(n_telescopes)

    for event_id in range(max_events):

        n_triggered = np.random.poisson(n_telescopes * 0.3)
        if n_triggered > n_telescopes:
            n_triggered = n_telescopes

        triggered_tels = np.random.choice(tel_ids, n_triggered, replace=False)

        container.r0.event_id = event_id
        container.r0.tels_with_data = triggered_tels
        container.count = event_id

        # handle single-telescope case (ignore others:
        if single_tel:
            if single_tel not in container.r0.tels_with_data:
                continue
            container.r0.tels_with_data = [single_tel, ]

        container.r0.tel.reset()  # clear the previous telescopes
        t = np.arange(n_samples)

        for tel_id in container.r0.tels_with_data:
            geom = geoms[tel_id]

            # fill pixel position dictionary, if not already done:
            if tel_id not in container.inst.pixel_pos:
                container.inst.pixel_pos[tel_id] = (
                    geom.pix_x.value,
                    geom.pix_y.value,
                )

            centroid = np.random.uniform(geom.pix_x.min(), geom.pix_y.max(), 2)
            length = np.random.uniform(0.02, 0.2)
            width = np.random.uniform(0.01, length)
            psi = np.random.randint(0, 360)
            intensity = np.random.poisson(int(10000 * width * length))
            model = toymodel.generate_2d_shower_model(
                centroid,
                width,
                length,
                '{}d'.format(psi)
            )
            image, _, _ = toymodel.make_toymodel_shower_image(
                geom,
                model.pdf,
                intensity,
            )

            # container.r0.tel[tel_id] = R0CameraContainer()
            container.inst.num_channels[tel_id] = n_channels
            n_pix = len(geom.pix_id)
            samples = np.empty((n_pix, n_samples))
            means = np.random.normal(15, 1, (n_pix, 1))
            stds = np.random.uniform(3, 6, (n_pix, 1))
            samples = image[:, np.newaxis] * norm.pdf(t, means, stds)

            for chan in range(n_channels):
                container.r0.tel[tel_id].adc_samples[chan] = samples
                container.r0.tel[tel_id].adc_sums[chan] = image

        yield container
Пример #28
0
if __name__ == '__main__':

    # Prepare the camera geometry
    geom = io.CameraGeometry.from_name('hess', 1)
    disp = visualization.CameraDisplay(geom)
    disp.set_limits_minmax(0, 350)
    disp.add_colorbar()

    # make a toymodel shower model
    model = toymodel.generate_2d_shower_model(centroid=(0.2, 0.3),
                                              width=0.01,
                                              length=0.1,
                                              psi='30d')

    # generate toymodel image in camera for this shower model.
    image, signal, noise = toymodel.make_toymodel_shower_image(
        geom, model.pdf, intensity=50, nsb_level_pe=100)

    #Image cleaning
    clean_mask = tailcuts_clean(
        geom, image, 1, 10,
        5)  #pedvars = 1 and core and boundary threshold in pe
    image[~clean_mask] = 0

    #Pixel values in the camera
    pix_x = geom.pix_x.value
    pix_y = geom.pix_y.value

    # Hillas parameters
    hillas = hillas_parameters(pix_x, pix_y, image)
    print(hillas)
Пример #29
0
        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,
            ]
Пример #30
0
        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, ]
Пример #31
0
import matplotlib.pyplot as plt
from ctapipe.io.camera import make_rectangular_camera_geometry
from ctapipe.image.toymodel import generate_2d_shower_model, make_toymodel_shower_image

NX = 40
NY = 40

geom = make_rectangular_camera_geometry(NX, NY)

showermodel = generate_2d_shower_model(centroid=[0.25, 0.0],
                                       length=0.1,
                                       width=0.02,
                                       psi='40d')

image, signal, noise = make_toymodel_shower_image(geom,
                                                  showermodel.pdf,
                                                  intensity=20,
                                                  nsb_level_pe=30)

# make them into 2D arrays so we can plot them with imshow
image.shape = (NX, NY)
signal.shape = (NX, NY)
noise.shape = (NX, NY)

# here we just plot the images using imshow().  For a more general
# case, one should use a ctapipe.visualization.CameraDisplay
plt.figure(figsize=(10, 3))
plt.subplot(1, 3, 1)
plt.imshow(signal, interpolation='nearest', origin='lower')
plt.title("Signal")
plt.colorbar()
plt.subplot(1, 3, 2)