Exemplo n.º 1
0
def test_hillas_failure():
    geom, image = create_sample_image(psi='0d')
    blank_image = zeros_like(image)

    with pytest.raises(HillasParameterizationError):
        hillas_parameters_1(geom, blank_image)

    with pytest.raises(HillasParameterizationError):
        hillas_parameters_2(geom, blank_image)

    with pytest.raises(HillasParameterizationError):
        hillas_parameters_3(geom, blank_image)

    with pytest.raises(HillasParameterizationError):
        hillas_parameters_4(geom, blank_image)
Exemplo n.º 2
0
def do_test_hillas(withunits=True):
    """
    test all Hillas-parameter routines on a sample image and see if they
    agree with eachother and with the toy model (assuming the toy model code
    is correct)
    """

    # try all quadrants
    for psi_angle in ['30d', '120d', '-30d', '-120d']:

        px, py, image = create_sample_image(psi_angle)
        results = {}

        if withunits:
            px = px * u.cm
            py = py * u.cm

        results['v1'] = hillas_parameters_1(px, py, image)
        results['v2'] = hillas_parameters_2(px, py, image)
        results['v3'] = hillas_parameters_3(px, py, image)
        results['v4'] = hillas_parameters_4(px, py, image)
        # compare each method's output
        for aa in results:
            for bb in results:
                if aa is not bb:
                    print("comparing {} to {}".format(aa, bb))
                    compare_result(results[aa].length, results[bb].length)
                    compare_result(results[aa].width, results[bb].width)
                    compare_result(results[aa].r, results[bb].r)
                    compare_result(results[aa].phi.deg, results[bb].phi.deg)
                    compare_result(results[aa].psi.deg, results[bb].psi.deg)
                    compare_result(results[aa].miss, results[bb].miss)
                    compare_result(results[aa].skewness, results[bb].skewness)
Exemplo n.º 3
0
def test_hillas():
    """
    test all Hillas-parameter routines on a sample image and see if they
    agree with eachother and with the toy model (assuming the toy model code
    is correct)
    """

    px, py, image = create_sample_image()
    results = {}

    results['v1'] = hillas_parameters_1(px, py, image)
    results['v2'] = hillas_parameters_2(px, py, image)
    results['v3'] = hillas_parameters_3(px, py, image)
    results['v4'] = hillas_parameters_4(px, py, image)

    # compare each method's output
    for aa in results:
        for bb in results:
            if aa is not bb:
                print("comparing {} to {}".format(aa, bb))
                assert isclose(results[aa].length, results[bb].length)
                assert isclose(results[aa].width, results[bb].width)
                assert isclose(results[aa].r, results[bb].r)
                assert isclose(results[aa].phi.deg, results[bb].phi.deg)
                assert isclose(results[aa].psi.deg, results[bb].psi.deg)
                assert isclose(results[aa].miss, results[bb].miss)
                assert isclose(results[aa].skewness, results[bb].skewness)
Exemplo n.º 4
0
def do_test_hillas(withunits=True):
    """
    test all Hillas-parameter routines on a sample image and see if they
    agree with eachother and with the toy model (assuming the toy model code
    is correct)
    """

    px, py, image = create_sample_image()
    results = {}

    if withunits:
        px = px * u.cm
        py = py * u.cm

    results['v1'] = hillas_parameters_1(px, py, image)
    results['v2'] = hillas_parameters_2(px, py, image)
    results['v3'] = hillas_parameters_3(px, py, image)
    results['v4'] = hillas_parameters_4(px, py, image)

    # compare each method's output
    for aa in results:
        for bb in results:
            if aa is not bb:
                print("comparing {} to {}".format(aa,bb))
                compare_result(results[aa].length, results[bb].length)
                compare_result(results[aa].width, results[bb].width)
                compare_result(results[aa].r, results[bb].r)
                compare_result(results[aa].phi.deg, results[bb].phi.deg)
                compare_result(results[aa].psi.deg, results[bb].psi.deg)
                compare_result(results[aa].miss, results[bb].miss)
                compare_result(results[aa].skewness, results[bb].skewness)
def plot_ellipse_shower_on_image_meter(axis, image_array, pixels_position):

    xx, yy = pixels_position[0], pixels_position[1]

    hillas = hillas_parameters_2(xx.flatten(), # * u.meter,
                                 yy.flatten(), # * u.meter,
                                 image_array.flatten())

    centroid = (hillas.cen_x, hillas.cen_y)
    length = hillas.length
    width = hillas.width
    angle = hillas.psi.to(u.rad).value # - np.pi/2.   # TODO

    print("centroid:", centroid)
    print("length:",   length)
    print("width:",    width)
    print("angle:",    angle)

    #print("DEBUG:", hillas[7].value, angle, np.degrees(angle))

    ellipse = Ellipse(xy=centroid, width=length, height=width, angle=np.degrees(angle), fill=False, color='red', lw=2)
    axis.axes.add_patch(ellipse)

    title = axis.axes.get_title()
    axis.axes.set_title("{} ({:.2f}°)".format(title, np.degrees(angle)))

    # Plot centroid

    axis.scatter(*centroid)

    # Plot shower axis

    #axis.arrow(0, 0,  0.1, 0, head_width=0.001, head_length=0.005, fc='k', ec='k')
    #axis.arrow(0, 0,  0, 0.1, head_width=0.001, head_length=0.005, fc='k', ec='k')

    p1_x = centroid[0]
    p1_y = centroid[1]

    p2_x = p1_x + math.cos(angle)
    p2_y = p1_y + math.sin(angle)
    #p2_x = p1_x + (length / 2.) * math.cos(angle)
    #p2_y = p1_y + (length / 2.) * math.sin(angle)


    #print(math.cos(math.pi/2.))
    #print(math.sin(math.pi/2.))
    #p2_x = p1_x + (length / 2.) * math.cos(math.pi/2.)
    #p2_y = p1_y + (length / 2.) * math.sin(math.pi/2.)
    #print(p1_x, p2_x)
    #print(p1_y, p2_x)


    axis.arrow(p1_x, p1_y,  p2_x, p2_y, head_width=0.001, head_length=0.005, fc='r', ec='r')

    p3_x = p1_x + math.cos(angle + math.pi/2.)
    p3_y = p1_y + math.sin(angle + math.pi/2.)
    #p3_x = p1_x + (width / 2.) * math.cos(angle + math.pi/2.)
    #p3_y = p1_y + (width / 2.) * math.sin(angle + math.pi/2.)

    axis.arrow(p1_x, p1_y, p3_x, p3_y, head_width=0.001, head_length=0.005, fc='g', ec='g')
def plot_ellipse_shower_on_image(axis, image_array):
    """Based on Fabio's notebook."""

    x = np.arange(0, np.shape(image_array)[0], 1)
    y = np.arange(0, np.shape(image_array)[1], 1)
    xx, yy = np.meshgrid(x, y)

    hillas = hillas_parameters_2(xx.flatten(), # * u.meter,
                                 yy.flatten(), # * u.meter,
                                 image_array.flatten())

    centroid = (hillas.cen_x.value, hillas.cen_y.value)
    length = hillas.length.value
    width = hillas.width.value
    angle = hillas.psi.to(u.rad).value # - np.pi/2.    # TODO

    print("centroid:", centroid)
    print("length:",   length)
    print("width:",    width)
    print("angle:",    angle)

    #print("DEBUG:", hillas[7].value, angle, np.degrees(angle))

    ellipse = Ellipse(xy=centroid, width=width, height=length, angle=np.degrees(angle), fill=False, color='red', lw=2)
    axis.axes.add_patch(ellipse)

    title = axis.axes.get_title()
    axis.axes.set_title("{} ({:.2f}°)".format(title, np.degrees(angle)))

    # Plot centroid

    axis.scatter(*centroid)

    # Plot shower axis

    ellipse = Ellipse(xy=centroid, width=width, height=0, angle=np.degrees(angle), fill=False, color='blue', lw=2)
    axis.axes.add_patch(ellipse)

    ellipse = Ellipse(xy=centroid, width=0, height=length, angle=np.degrees(angle), fill=False, color='blue', lw=2)
    axis.axes.add_patch(ellipse)

    # Plot origin axis

    ellipse = Ellipse(xy=centroid, width=10, height=0, angle=0, fill=False, color='black', lw=2)
    axis.axes.add_patch(ellipse)
Exemplo n.º 7
0
def display_event(event, calibrate = 0, max_tel = 4, cleaning=None):
    """an extremely inefficient display. It creates new instances of
    CameraDisplay for every event and every camera, and also new axes
    for each event. It's hacked, but it works
    """
    print("Displaying... please wait (this is an inefficient implementation)")
    global fig
    ntels = min(max_tel, len(event.dl0.tels_with_data))
    fig.clear()

    plt.suptitle("EVENT {}".format(event.dl0.event_id))

    disps = []

    mc_sum = None
    all_moments = []

    for ii, tel_id in enumerate(event.dl0.tels_with_data):
        if ii >= max_tel: break
        print("\t draw cam {}...".format(tel_id))
        nn = int(ceil((ntels)**.5))
        ax = plt.subplot(nn, 2*nn, 2*(ii+1)-1)

        x, y = event.inst.pixel_pos[tel_id]
        geom = io.CameraGeometry.guess(x, y, event.inst.optical_foclen[tel_id])
        disp = visualization.CameraDisplay(geom, ax=ax,
                                           title="CT{0} DetectorResponse".format(tel_id))

        disp.pixels.set_antialiaseds(False)
        disp.autoupdate = False
        disp.cmap = plt.cm.hot
        chan = 0
        signals = event.dl0.tel[tel_id].adc_sums[chan].astype(float)[:]
        if calibrate:
            signals = apply_mc_calibration_ASTRI(event.dl0.tel[tel_id].adc_sums, tel_id)
        if cleaning == 'tailcut':
            mask = tailcuts_clean(geom, signals, 1,picture_thresh=10.,boundary_thresh=8.)
            dilate(geom, mask)
            signals[mask==False] = 0

        moments = hillas_parameters_2(geom.pix_x,
                                      geom.pix_y,
                                      signals)

        disp.image = signals
        disp.overlay_moments(moments, color='seagreen', linewidth=3)
        disp.set_limits_percent(95)
        disp.add_colorbar()
        disps.append(disp)


        ax = plt.subplot(nn, 2*nn, 2*(ii+1))

        geom = io.CameraGeometry.guess(x, y, event.inst.optical_foclen[tel_id])
        disp = visualization.CameraDisplay(geom, ax=ax,
                                           title="CT{0} PhotoElectrons".format(tel_id))
        disp.pixels.set_antialiaseds(False)
        disp.autoupdate = False
        disp.cmap = plt.cm.hot
        chan = 0


        #print (event.mc.tel[tel_id].photo_electrons)
        for jj in range(len(event.mc.tel[tel_id].photo_electron_image)):
            event.dl0.tel[tel_id].adc_sums[chan][jj] = event.mc.tel[tel_id].photo_electron_image[jj]
        signals2 = event.dl0.tel[tel_id].adc_sums[chan].astype(float)
        moments2 = hillas_parameters_2(geom.pix_x,
                                       geom.pix_y,
                                       signals2)
        all_moments.append(moments2)
        if mc_sum is None:
            mc_sum = signals2
        else:
            scale = 3 if tel_id == 37 else 1
            for i, val in enumerate(signals2):
                mc_sum[i] += val/scale

        disp.image = mc_sum
        for moments2 in all_moments:
            disp.overlay_moments(moments2, color='seagreen', linewidth=2)
        disp.set_limits_percent(95)
        disp.add_colorbar()
        disps.append(disp)


    return disps
Exemplo n.º 8
0
def get_hillas_parameters(geom: CameraGeometry, image, implementation=4):
    r"""Return Hillas parameters [hillas]_ of the given ``image``.

    Short description of Hillas parameters:
    * x:         x position of the ellipse's center (in meter)
    * y:         y position of the ellipse's center (in meter)
    * length:    measure of the RMS extent along the major axis (in meter) (length >= width)
    * width:     measure of the RMS extent along the minor axis (in meter) (length >= width)
    * intensity: the number of photoelectrons in the image (in PE)         (size = np.sum(image))
    * psi:       angle of the shower (in radian)
    * phi:       polar coordinate of centroid (in radian)
    * r:         radial coordinate of centroid (in meter)
    * kurtosis:  Kurtosis is a measure of whether the data are heavy-tailed or light-tailed
                 relative to a normal distribution.
                 That is, data sets with high kurtosis tend to have heavy tails, or outliers.
                 Data sets with low kurtosis tend to have light tails, or lack of outliers.
                 See http://www.itl.nist.gov/div898/handbook/eda/section3/eda35b.htm
    * skewness:  Skewness is a measure of symmetry, or more precisely, the lack of symmetry.
                 A distribution, or data set, is symmetric if it looks the same to the left
                 and right of the center point. See http://www.itl.nist.gov/div898/handbook/eda/section3/eda35b.htm

    See https://github.com/cta-observatory/ctapipe/blob/master/ctapipe/image/hillas.py#L83
    for more information.

    Parameters
    ----------
    geom : CameraGeomatry
        The geometry of the image to parametrize

    image : Numpy array
        The image to parametrize

    implementation : integer
        Tell which ctapipe's implementation to use (1 or 2).

    Returns
    -------
    namedtuple
        Hillas parameters for the given ``image``

    References
    ----------
    .. [hillas] Appendix of the Whipple Crab paper Weekes et al. (1998)
       http://adsabs.harvard.edu/abs/1989ApJ...342..379W
    """

    # Copy image to prevent tricky bugs
    image = image.copy()

    if implementation == 1:
        params = hillas_parameters_1(geom, image)
    elif implementation == 2:
        params = hillas_parameters_2(geom, image)
    elif implementation == 3:
        params = hillas_parameters_3(geom, image)
    elif implementation == 4:
        params = hillas_parameters_4(geom, image)
    else:
        raise ValueError("Wrong Hillas implementation ID.")

    return params
def plot_ellipse_shower_on_image(axis, image_array):
    """Based on Fabio's notebook."""

    x = np.arange(0, np.shape(image_array)[0], 1)
    y = np.arange(0, np.shape(image_array)[1], 1)
    xx, yy = np.meshgrid(x, y)

    hillas = hillas_parameters_2(
        xx.flatten(),  # * u.meter,
        yy.flatten(),  # * u.meter,
        image_array.flatten())

    centroid = (hillas.x.value, hillas.y.value)
    length = hillas.length.value
    width = hillas.width.value
    angle = hillas.psi.to(u.rad).value  # - np.pi/2.    # TODO

    print("centroid:", centroid)
    print("length:", length)
    print("width:", width)
    print("angle:", angle)

    #print("DEBUG:", hillas[7].value, angle, np.degrees(angle))

    ellipse = Ellipse(xy=centroid,
                      width=width,
                      height=length,
                      angle=np.degrees(angle),
                      fill=False,
                      color='red',
                      lw=2)
    axis.axes.add_patch(ellipse)

    title = axis.axes.get_title()
    axis.axes.set_title("{} ({:.2f}°)".format(title, np.degrees(angle)))

    # Plot centroid

    axis.scatter(*centroid)

    # Plot shower axis

    ellipse = Ellipse(xy=centroid,
                      width=width,
                      height=0,
                      angle=np.degrees(angle),
                      fill=False,
                      color='blue',
                      lw=2)
    axis.axes.add_patch(ellipse)

    ellipse = Ellipse(xy=centroid,
                      width=0,
                      height=length,
                      angle=np.degrees(angle),
                      fill=False,
                      color='blue',
                      lw=2)
    axis.axes.add_patch(ellipse)

    # Plot origin axis

    ellipse = Ellipse(xy=centroid,
                      width=10,
                      height=0,
                      angle=0,
                      fill=False,
                      color='black',
                      lw=2)
    axis.axes.add_patch(ellipse)
def plot_ellipse_shower_on_image_meter(axis, image_array, pixels_position):

    xx, yy = pixels_position[0], pixels_position[1]

    hillas = hillas_parameters_2(
        xx.flatten(),  # * u.meter,
        yy.flatten(),  # * u.meter,
        image_array.flatten())

    centroid = (hillas.x, hillas.y)
    length = hillas.length
    width = hillas.width
    angle = hillas.psi.to(u.rad).value  # - np.pi/2.   # TODO

    print("centroid:", centroid)
    print("length:", length)
    print("width:", width)
    print("angle:", angle)

    #print("DEBUG:", hillas[7].value, angle, np.degrees(angle))

    ellipse = Ellipse(xy=centroid,
                      width=length,
                      height=width,
                      angle=np.degrees(angle),
                      fill=False,
                      color='red',
                      lw=2)
    axis.axes.add_patch(ellipse)

    title = axis.axes.get_title()
    axis.axes.set_title("{} ({:.2f}°)".format(title, np.degrees(angle)))

    # Plot centroid

    axis.scatter(*centroid)

    # Plot shower axis

    #axis.arrow(0, 0,  0.1, 0, head_width=0.001, head_length=0.005, fc='k', ec='k')
    #axis.arrow(0, 0,  0, 0.1, head_width=0.001, head_length=0.005, fc='k', ec='k')

    p1_x = centroid[0]
    p1_y = centroid[1]

    p2_x = p1_x + math.cos(angle)
    p2_y = p1_y + math.sin(angle)
    #p2_x = p1_x + (length / 2.) * math.cos(angle)
    #p2_y = p1_y + (length / 2.) * math.sin(angle)

    #print(math.cos(math.pi/2.))
    #print(math.sin(math.pi/2.))
    #p2_x = p1_x + (length / 2.) * math.cos(math.pi/2.)
    #p2_y = p1_y + (length / 2.) * math.sin(math.pi/2.)
    #print(p1_x, p2_x)
    #print(p1_y, p2_x)

    axis.arrow(p1_x,
               p1_y,
               p2_x,
               p2_y,
               head_width=0.001,
               head_length=0.005,
               fc='r',
               ec='r')

    p3_x = p1_x + math.cos(angle + math.pi / 2.)
    p3_y = p1_y + math.sin(angle + math.pi / 2.)
    #p3_x = p1_x + (width / 2.) * math.cos(angle + math.pi/2.)
    #p3_y = p1_y + (width / 2.) * math.sin(angle + math.pi/2.)

    axis.arrow(p1_x,
               p1_y,
               p3_x,
               p3_y,
               head_width=0.001,
               head_length=0.005,
               fc='g',
               ec='g')