def plotUnitDiamond(alpha, fc, lw):
    # Plot unit diamond
    diagonal = np.sqrt(2)

    rect = patches.Rectangle((-1 / np.sqrt(2), -1 / np.sqrt(2)),
                             diagonal,
                             diagonal,
                             alpha=alpha,
                             fc=fc,
                             zorder=10)
    # Draw a non-transparent white edge to wipe the facecolor where they overlap
    r_wipe = patches.Rectangle((-1 / np.sqrt(2), -1 / np.sqrt(2)),
                               diagonal,
                               diagonal,
                               alpha=1.0,
                               ec='white',
                               fc='none',
                               lw=lw,
                               zorder=10)
    # Now draw only the edge
    r_edge = patches.Rectangle((-1 / np.sqrt(2), -1 / np.sqrt(2)),
                               diagonal,
                               diagonal,
                               fc='none',
                               ec='k',
                               lw=lw)
    t2 = mpl.transforms.Affine2D().rotate_deg(-45) + axes[1].transData
    rect_patch = PatchCollection([rect, r_wipe, r_edge],
                                 match_original=True,
                                 zorder=10)
    rect_patch.set_transform(t2)

    axes[1].add_artist(rect_patch)
Esempio n. 2
0
def DDMR(x,y,phi,i):

    patches = []

    # Robot Body
    circle = mpatches.Circle((x, y), 0.25,fc=colors[i])
    patches.append(circle)

    # Tire 1
    rect = mpatches.Rectangle([x-0.07, y+0.24-(0.025)], 0.14, 0.051, fc="black")
    patches.append(rect)

    # Tire 2
    rect = mpatches.Rectangle([x-0.07, y-0.24-(0.0245)], 0.14, 0.05, fc="black")
    patches.append(rect)

    # add a Polygon
    polygon = mpatches.Polygon(np.array([(x+0.1,y+0.05), (x+0.1,y-0.05), (x+0.2,y)]), color='black')
    patches.append(polygon)

    DDMR = PatchCollection(patches, match_original=True)

    rot = mpl.transforms.Affine2D().rotate_around(x,y,phi)+ plt.gca().transData

    DDMR.set_transform(rot)

    return DDMR
Esempio n. 3
0
def polar_line_circles(radii, theta, start_r=0):
    circles = [mpatches.Circle((0, 0), radii[0])]

    line_xfm = mxfms.Affine2D().translate(start_r, 0).rotate(theta)

    x = 0
    for ri in range(1, len(radii)):
        x += radii[ri - 1] + radii[ri]

        circles.append(mpatches.Circle((x, 0), radii[ri]))

    collection = PatchCollection(circles)
    collection.set_transform(line_xfm)

    return collection
Esempio n. 4
0
def polar_line_circles(radii, theta, start_r=0):
    circles = [ mpatches.Circle( (0,0), radii[0] ) ]
    
    line_xfm = mxfms.Affine2D().translate(start_r,0).rotate(theta)
    
    x = 0
    for ri in range(1, len(radii)):
        x += radii[ri-1] + radii[ri]
        
        circles.append(mpatches.Circle( (x,0), radii[ri] ))
        
    collection = PatchCollection(circles)
    collection.set_transform(line_xfm)
    
    return collection
Esempio n. 5
0
def spiral_trials(radii, x=0.0, y=0.0):
    radii = np.array(radii)
    circles = []

    if radii.size > 0:
        spiral = hex_pack(radii[0], len(radii))

        for i,radius in enumerate(radii):
            circles.append(mpatches.Circle((spiral[i][0], spiral[i][1]), radii[i]))
        
    pos_xfm = mxfms.Affine2D().translate(x,y)

    collection = PatchCollection(circles)
    collection.set_transform(pos_xfm)

    return collection
Esempio n. 6
0
def spiral_trials(radii, x=0.0, y=0.0):
    radii = np.array(radii)
    circles = []

    if radii.size > 0:
        spiral = hex_pack(radii[0], len(radii))

        for i,radius in enumerate(radii):
            circles.append(mpatches.Circle((spiral[i][0], spiral[i][1]), radii[i]))
        
    pos_xfm = mxfms.Affine2D().translate(x,y)

    collection = PatchCollection(circles)
    collection.set_transform(pos_xfm)

    return collection
Esempio n. 7
0
def Toby(x,y,phi):
    
    patches = []
    
    body= mpatches.Ellipse((x,y), 0.35, 0.7, fc='#0033cc')
    patches.append(body)
    head  = mpatches.Circle((0.15+x,y),0.15, zorder=10, fc='#0066ff')
    patches.append(head)

    Toby = PatchCollection(patches, match_original=True)

    rot = mpl.transforms.Affine2D().rotate_around(x,y,phi)+ plt.gca().transData

    Toby.set_transform(rot)

    return Toby
Esempio n. 8
0
 def _get_fpt_ell_collection(dm, fpts, T_data, alpha, edgecolor):
     ell_patches = []
     for (x, y, a, c, d) in fpts:  # Manually Calculated sqrtm(inv(A))
         with catch_warnings():
             simplefilter("ignore")
             aIS = 1 / sqrt(a)
             cIS = (c / sqrt(a) - c / sqrt(d)) / (a - d + eps(1))
             dIS = 1 / sqrt(d)
         transEll = Affine2D([(aIS, 0, x), (cIS, dIS, y), (0, 0, 1)])
         unitCirc1 = Circle((0, 0), 1, transform=transEll)
         ell_patches = [unitCirc1] + ell_patches
     ellipse_collection = PatchCollection(ell_patches)
     ellipse_collection.set_facecolor("none")
     ellipse_collection.set_transform(T_data)
     ellipse_collection.set_alpha(alpha)
     ellipse_collection.set_edgecolor(edgecolor)
     return ellipse_collection
Esempio n. 9
0
def visualize_planning_result(filename: str, obstacle_idx: int,
                              states: np.ndarray, goal: np.ndarray):
    obs_center = load_obstacles(obstacle_idx)
    obstacles = [Rectangle((xy[0] - 4, xy[1] - 4), 8, 8) for xy in obs_center]
    obstacles = PatchCollection(obstacles, facecolor="gray", edgecolor="black")

    car = PatchCollection(
        [Rectangle((-1, -0.5), 2, 1),
         Arrow(0, 0, 2, 0, width=1.0)],
        facecolor="blue",
        edgecolor="blue")

    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.subplots()
    ax.set_aspect('equal', 'box')
    ax.set_xlim([-25, 25])
    ax.set_ylim([-35, 35])

    canvas.draw()
    image = np.array(canvas.buffer_rgba())
    H, W, _ = image.shape
    writer = cv2.VideoWriter(filename, cv2.VideoWriter_fourcc(*'mp4v'), 30.,
                             (W, H), True)

    T = states.shape[0]
    for t in range(T):
        # obstacles
        ax.add_collection(obstacles)
        # target
        ax.scatter(goal[0], goal[1], marker='*', c="red")
        # current position
        transform = Affine2D().rotate(states[t, 2]).translate(
            states[t, 0], states[t, 1])
        car.set_transform(transform + ax.transData)
        ax.add_collection(car)
        # plot
        canvas.draw()
        image = np.array(canvas.buffer_rgba())[:, :, :3]
        writer.write(image)
        ax.clear()

    writer.release()
    h264_converter(filename)
Esempio n. 10
0
    def _draw_sample(self, ax, sample, perspective, view_size):
        sample_class = sample.__class__

        if sample_class not in self.sample_draw_methods:
            return

        method = self.sample_draw_methods[sample_class]

        patches = method(sample, perspective, view_size)
        col = PatchCollection(patches, match_original=True)

        if perspective is Perspective.YZ:
            trans = Affine2D().rotate_around(0, 0, sample.tilt_rad)
        else:
            trans = Affine2D().scale(sx=1, sy=1 + tan(abs(sample.tilt_rad)))

        trans += ax.transData
        col.set_transform(trans)

        ax.add_collection(col)
Esempio n. 11
0
 def _get_fpt_ell_collection(dm, fpts, T_data, alpha, edgecolor):
     ell_patches = []
     for (x,y,a,c,d) in fpts: # Manually Calculated sqrtm(inv(A))
         with catch_warnings():
             simplefilter("ignore")
             aIS = 1/sqrt(a)
             cIS = (c/sqrt(a) - c/sqrt(d))/(a - d + eps(1))
             dIS = 1/sqrt(d)
         transEll = Affine2D([\
                 ( aIS,   0,   x),\
                 ( cIS, dIS,   y),\
                 (   0,   0,   1)])
         unitCirc1 = Circle((0,0),1,transform=transEll)
         ell_patches = [unitCirc1] + ell_patches
     ellipse_collection = PatchCollection(ell_patches)
     ellipse_collection.set_facecolor('none')
     ellipse_collection.set_transform(T_data)
     ellipse_collection.set_alpha(alpha)
     ellipse_collection.set_edgecolor(edgecolor)
     return ellipse_collection
Esempio n. 12
0
def plot_covariance(ax, cov, n_std=3.0, **kwargs):
    ax.set_aspect('equal')

    eigval, eigvec = np.linalg.eig(cov)
    width, height = np.sqrt(eigval) * n_std
    ellipse = Ellipse((0, 0), width, height, fill=False, color='b'**kwargs)
    axis_x = FancyArrowPatch((0, 0), (width, 0),
                             mutation_scale=0.1 * width,
                             color='r')
    axis_y = FancyArrowPatch((0, 0), (0, height),
                             mutation_scale=0.1 * height,
                             color='g')
    patches = PatchCollection([ellipse, axis_x, axis_y])

    Ab = np.eye(3)
    Ab[:2, :2] = eigvec
    transf = transforms.Affine2D(matrix=Ab)

    patches.set_transform(transf + ax.transData)
    ax.set_xlim(-width * 1.1, width * 1.1)
    ax.set_ylim(-height * 1.1, height * 1.1)
    return ax.add_collection(patches)
Esempio n. 13
0
class SteeringWheel(object):
    def __init__(self, ax, diameter=1):
        thickness_horizontal = 0.22
        thickness_vertical = 0.15
        thickness_ring = 0.2
        diameter_center = .4
        epsilon = thickness_horizontal / 5.
        bmw_diameter = .12

        patches = [
            Circle((0, 0), diameter_center, color='k'),  # Full circle
            Wedge((0, 0), 1., 0, 360, width=thickness_ring, color='k'),
            Polygon([[thickness_horizontal, 0],
                     [thickness_horizontal, -1 + epsilon],
                     [-thickness_horizontal, -1 + epsilon],
                     [-thickness_horizontal, 0]],
                    closed=True,
                    color='k'),
            Polygon([[-1 + epsilon, thickness_vertical],
                     [1 - epsilon, thickness_vertical],
                     [1 - epsilon, -thickness_vertical],
                     [-1 + epsilon, -thickness_vertical]],
                    closed=True,
                    color='k'),
            Wedge((0, 0), bmw_diameter, 0, 360, color='white'),
            Wedge((0, 0), bmw_diameter, 90, 180, color='blue'),
            Wedge((0, 0), bmw_diameter, 270, 360, color='blue')
        ]

        self.p = PatchCollection(patches, match_original=True)
        tf = transforms.Affine2D().scale(diameter) + ax.transData
        self.p.set_transform(tf)
        ax.add_collection(self.p)

    def update_pose(self, x, y, angle):
        tf = transforms.Affine2D().rotate(angle).translate(x, y) + ax.transData
        self.p.set_transform(tf)
Esempio n. 14
0
def CLMR(x,y,phi,dlt):

    l_1 = 0.4

    patches=[]
           
    line_1 = mpatches.FancyArrowPatch((x,y),(x+l_1,y), arrowstyle='-')
    line_2 = mpatches.FancyArrowPatch((x,y-0.15),(x,y+0.15), arrowstyle='-')
    line_3 = mpatches.FancyArrowPatch((x+l_1,y-0.15),(x+l_1,y+0.15), arrowstyle='-')

    line_4 = mpatches.FancyArrowPatch((x-0.1,y+0.15),(x+0.1,y+0.15), arrowstyle='-')
    line_5 = mpatches.FancyArrowPatch((x-0.1,y-0.15),(x+0.1,y-0.15), arrowstyle='-')

    line_6 = mpatches.FancyArrowPatch((x+l_1-0.1,y+0.15),(x+l_1+0.1,y+0.15), arrowstyle='-')
    line_7 = mpatches.FancyArrowPatch((x+l_1-0.1,y-0.15),(x+l_1+0.1,y-0.15), arrowstyle='-')
    
    rot_1 = mpl.transforms.Affine2D().rotate_around(x,y,phi)+ plt.gca().transData
    rot_2 = mpl.transforms.Affine2D().rotate_around(x+l_1,y+0.15,dlt)
    rot_3 = mpl.transforms.Affine2D().rotate_around(x+l_1,y-0.15,dlt)

    line_6. set_transform(rot_2)
    line_7. set_transform(rot_3)

    patches.append(line_1)
    patches.append(line_2)
    patches.append(line_3)
    patches.append(line_4)
    patches.append(line_5)
    patches.append(line_6)
    patches.append(line_7)    

    CLMR = PatchCollection(patches, match_original=True)

    CLMR.set_transform(rot_1)

    return CLMR
Esempio n. 15
0
fig.colorbar(p, ax=ax)

plt.show()


# 2 rectangle
import matplotlib.pyplot as plt

# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)


ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
Esempio n. 16
0
def set_wdirs_multibody(B, s, mA, yA, debug=False):
    """
    set_wdirs_multibody: identifies the orientations of the devices and the relative angles based on the
                        wave directions to be analysed, the directional spreading, and the yaw angle span
                        of the machine

    Args:
        B (nunpy.ndarray): [rad] wave direction vector from scatter diagram
        s (float): [-] spreading parameter from scatter diagram
        mA (float): [rad] main angle
        yA (float): [rad] yawing semi-span

    Optional args:
        debug (boolean): debug flag

    Returns:
        B_new (list): list of orientations and associated angles to be analysed in the array.
                        The associated angles are placed into a tuple that contains at the minimum the orientation itself
                       The output is structured as follow:
                        [ orientation_i, (angles_j)_i ]
    """

    # if not all(x<y for x, y in zip(B, B[1:])):
    #    B.sort()
    if len(set([x for x in B if B.tolist().count(x) > 1])):
        errStr = ('Repeated elements in the wave angle vector')
        raise IOError(errStr)

    # s parameter from metocean
    # assuming s=1 distribution 90° and s=30 distribution 5°, a linear relation is used
    # dir_spr = s*0.0989-0.011636
    dir_spr = -0.0512 * s + 1.621
    if dir_spr > np.pi / 2:
        dir_spr = np.pi
    if dir_spr < np.pi / 36 - 0.001 or s <= 0:
        dir_spr = 0

    # rotate the B vector in agreement with the main angle
    rot_B = anglewrap(B[:] - mA, 'r2r')
    # identify the set of feasibel/unfeasible orientations
    yaw_ind = np.logical_or(rot_B >= anglewrap(-(yA + 0.0001), 'r2r'),
                            rot_B <= yA)
    yaw_angles = B[yaw_ind]
    notyaw_angles = B[np.logical_not(yaw_ind)]

    if not np.any(yaw_angles):
        tuple_angles = tuple(B)
        if dir_spr:
            tuple_angles += tuple([
                anglewrap(el - dir_spr / 3. * 2, 'r2r') for el in tuple_angles
            ]) + tuple([
                anglewrap(el + dir_spr / 3. * 2, 'r2r') for el in tuple_angles
            ])
        B_new = [mA, tuple_angles]
    else:
        if not notyaw_angles.shape[
                0] == 0:  # check if the machine can rotate in the whole circle
            # define the min and max angles, those are used as reference for all the angles outised the yaw range
            plusBound = np.argmin(
                np.abs(anglewrap(yaw_angles - mA, 'r2r') - yA))
            minusBound = np.argmin(
                np.abs(
                    anglewrap(yaw_angles - mA, 'r2r') - anglewrap(-yA, 'r2r')))

            # distribute the unfeasible orientations between the lower and higher bounds
            ang_distr = anglewrap(notyaw_angles - (mA + np.pi), 'r2r')
            if yaw_angles.shape[
                    0] == 1:  # one orientation case--> set the unfeasible orientations to the feasible one
                max_range = tuple(
                    [anglewrap(el + mA + np.pi, 'r2r') for el in ang_distr])
            else:
                max_range = tuple([
                    anglewrap(el + mA + np.pi, 'r2r') for el in ang_distr
                    if el >= np.pi
                ])

            # upper bound
            tuple_angles = (yaw_angles[plusBound], ) + max_range
            if dir_spr:
                tuple_angles += tuple([
                    anglewrap(el - dir_spr / 3. * 2, 'r2r')
                    for el in tuple_angles
                ]) + tuple([
                    anglewrap(el + dir_spr / 3. * 2, 'r2r')
                    for el in tuple_angles
                ])
            B_new = [yaw_angles[plusBound], tuple_angles]

            # lower bound
            if not yaw_angles.shape[0] == 1:
                min_range = tuple([
                    anglewrap(el + mA + np.pi, 'r2r') for el in ang_distr
                    if el < np.pi
                ])
                tuple_angles = (yaw_angles[minusBound], ) + min_range
                if dir_spr:
                    tuple_angles += tuple([
                        anglewrap(el - dir_spr / 3. * 2, 'r2r')
                        for el in tuple_angles
                    ]) + tuple([
                        anglewrap(el + dir_spr / 3. * 2, 'r2r')
                        for el in tuple_angles
                    ])
                B_new += [yaw_angles[minusBound], tuple_angles]

            # inside elements
            mask = np.ones(yaw_angles.size, 'bool')
            mask[[plusBound, minusBound]] = False
        else:
            B_new = []
            mask = np.ones(yaw_angles.size, 'bool')

        for elA in yaw_angles[mask]:
            tuple_angles = (elA, )
            if dir_spr:
                tuple_angles += tuple([
                    anglewrap(el - dir_spr / 3. * 2, 'r2r')
                    for el in tuple_angles
                ]) + tuple([
                    anglewrap(el + dir_spr / 3. * 2, 'r2r')
                    for el in tuple_angles
                ])
            B_new += [elA, tuple_angles]

    if debug:
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        import matplotlib.colors as colors
        import matplotlib
        from matplotlib.patches import Wedge
        from matplotlib.collections import PatchCollection

        col = colors.cnames
        f = plt.figure()
        ax = f.add_subplot(111)

        MA_x = [0, np.cos((mA))]
        MA_y = [0, np.sin((mA))]
        mA_x = [0, np.cos((mA + np.pi))]
        mA_y = [0, np.sin((mA + np.pi))]
        yA_x = [0, np.cos((mA - yA))]
        yA_y = [0, np.sin((mA - yA))]
        YA_x = [0, np.cos((mA + yA))]
        YA_y = [0, np.sin(mA + yA)]

        # add a wedge for the angle span
        patches = []
        t = mpl.transforms.Affine2D().rotate_deg(
            mA * 180 / np.pi) + ax.transData

        # add a wedge for the upper angle range
        patches += [
            Wedge([0, 0],
                  0.5,
                  -yA * 180 / np.pi,
                  yA * 180 / np.pi,
                  ec="none",
                  alpha=0.3)
        ]

        if np.any(yaw_angles) and not notyaw_angles.shape[0] == 0:
            if yaw_angles.shape[0] == 1:
                patches += [
                    Wedge((0, 0),
                          1.2, (yaw_angles[plusBound] - mA) * 180 / np.pi,
                          (np.pi) * 180 / np.pi,
                          width=0.10)
                ]
            else:
                patches += [
                    Wedge((0, 0),
                          1.2, (yaw_angles[plusBound] - mA) * 180 / np.pi,
                          (np.pi) * 180 / np.pi,
                          width=0.10),
                    Wedge((0, 0),
                          1.2, (np.pi) * 180 / np.pi,
                          (yaw_angles[minusBound] - mA) * 180 / np.pi,
                          width=0.10)
                ]

        colors = 100 * np.random.rand(len(patches))
        p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)
        p.set_array(np.array(colors))
        p.set_transform(t)
        ax.add_collection(p)

        ax.plot(mA_x, mA_y, '-.', color='#999999')
        ax.plot(MA_x, MA_y, color='#999999')
        ax.plot(yA_x, yA_y, '--', color='#aaaaaa')
        ax.plot(YA_x, YA_y, '--', color='#aaaaaa')

        for ang in B.copy():
            ax.plot([0.9 * np.cos(ang), 1. * np.cos(ang)],
                    [0.9 * np.sin(ang), 1. * np.sin(ang)],
                    'k',
                    lw=5)

        for i, e in enumerate(B_new):
            if not i % 2:
                ax.plot([0.8 * np.cos(e), 1.1 * np.cos(e)],
                        [0.8 * np.sin(e), 1.1 * np.sin(e)],
                        color=col[col.keys()[i]],
                        lw=3)
            else:
                for eA in e:
                    ax.plot([0.6 * np.cos(eA), 0.7 * np.cos(eA)],
                            [0.6 * np.sin(eA), 0.7 * np.sin(eA)],
                            color=col[col.keys()[i - 1]],
                            lw=2)

        plt.axis('equal')
        plt.show()

    return B_new
    def plot_beamspot(self, Directory=None, depth=["60cm"], PdfPages=False):
        self.log.info(
            'plot the beamspot The function is alternative to the function Plot_Beam_profile_2d'
        )
        subdirectory = "beamspot/"
        for d in depth:
            filename = Directory + subdirectory + d + "/beamspot_" + d + ".h5"
            with tb.open_file(filename, 'r') as in_file:
                data = in_file.root.beamspot[:]

            # Calibration Factor
            Factor = 9.81  # diode B
            #  Factor = 9.76 # diode A
            Background = 5.7 * 10**(-9)  # 5 nA
            data = (data - Background) * Factor * 10**9

            # OF module
            mod_length = 84.975 / 10.0
            mod_width = 15.4 / 10.0

            # DHP
            dhp_length = 4.2 / 10.0
            dhp_width = 3.28 / 10.0

            # DCD
            dcd_length = 5.13 / 10.0
            dcd_width = 3.41 / 10.0

            # Switcher
            sw_length = 3.6 / 10.0
            sw_width = 1.89 / 10.0
            sw_locs = [8.96, 9.92, 10.88, 10.88, 10.88, 9.235, 19.338]

            # module collection
            mod_color = "black"
            # module outline
            mod_patches = [
                Rectangle((0, 0),
                          mod_length,
                          mod_width,
                          fill=False,
                          color=mod_color,
                          linewidth=2)
            ]
            # dhps
            for i in range(4):
                mod_patches.append(
                    Rectangle((mod_length - 1.3494 - dhp_length / 2,
                               mod_width - 0.2759 - dhp_width / 2 - 0.35 * i),
                              dhp_length,
                              dhp_width,
                              fill=False,
                              color=mod_color,
                              linewidth=1.5))
            # dcds
            for i in range(4):
                mod_patches.append(
                    Rectangle((mod_length - 1.9338 - sw_length / 2,
                               mod_width - 0.2759 - dcd_width / 2 - 0.35 * i),
                              dcd_length,
                              dcd_width,
                              fill=False,
                              color=mod_color,
                              linewidth=1.5))
            # switchers
            for i in range(6):
                mod_patches.append(
                    Rectangle(
                        (mod_length - sum(sw_locs[:-i - 3:-1]) / 10.0 -
                         sw_length / 2, mod_width - 0.1278 - sw_width / 2),
                        sw_length,
                        sw_width,
                        fill=False,
                        color=mod_color,
                        linewidth=1.5))
            a_x1 = -mod_length / 2 - 1.0 + 1.3494 - dhp_length / 2
            a_x2 = +mod_length / 2 - 1.0
            a_y1 = -mod_width / 2  # - 1.0
            a_y2 = +mod_width / 2  # - 1.0
            mod_trans_a = mpl.transforms.Affine2D().translate(
                -mod_length / 2,
                -mod_width / 2) + mpl.transforms.Affine2D().rotate_deg(
                    180) + mpl.transforms.Affine2D().translate(-1.0, 0)
            p_mod = PatchCollection(mod_patches, match_original=True)

            nullfmt = NullFormatter()  # no labels

            # definitions for the axes
            left, width = 0.1, 0.60
            bottom, height = 0.1, 0.60
            bottom_p = bottom + height + 0.02
            left_p = left + width + 0.02

            rect_spot = [left, bottom, width, height]
            rect_projx = [left, bottom_p, width, 0.2]
            rect_projy = [left_p, bottom, 0.2, height]

            # start with a rectangular Figure
            plt.figure()  # 1, figsize=(8, 8))

            axSpot = plt.axes(rect_spot)
            axProjx = plt.axes(rect_projx)
            axProjy = plt.axes(rect_projy)

            # no labels
            axProjx.xaxis.set_major_formatter(nullfmt)
            axProjy.yaxis.set_major_formatter(nullfmt)

            # the scatter plot:
            im_spot = axSpot.imshow(data,
                                    origin="upper",
                                    interpolation="None",
                                    aspect="auto",
                                    extent=(-6.5, +6.5, +6.5, -6.5))

            axSpot.plot((-6.5, +6.5), (0, 0), color="white", lw=1)
            axSpot.plot((0, 0), (-6.5, +6.5), color="white", lw=1)
            p_mod.set_transform(mod_trans_a + axSpot.transData)
            axSpot.add_collection(p_mod)
            axSpot.set_xlabel("x [cm]")
            axSpot.set_ylabel("z [cm]")
            axrange = np.arange(-6, +6.5, 0.5)

            axProjx.bar(x=axrange,
                        height=data[12, :].astype(np.float),
                        width=0.3)
            axProjx.set_ylabel("dose rate [krad/h]")
            axProjx.axvline(a_x1, color=mod_color)
            axProjx.axvline(a_x2, color=mod_color)

            axProjy.barh(y=axrange,
                         width=data[:, 12].astype(np.float),
                         height=0.3)
            axProjy.axhline(a_y1, color=mod_color)
            axProjy.axhline(a_y2, color=mod_color)
            axProjy.set_xlabel("dose rate [krad/h]")

            axProjx.set_xlim(axSpot.get_xlim())
            axProjy.set_ylim(axSpot.get_ylim())

            axProjy.set_xlim(axProjx.get_ylim())

            textleft = 'PXD outer forward module'
            props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
            axSpot.text(0.05,
                        0.95,
                        textleft,
                        transform=axSpot.transAxes,
                        fontsize=8,
                        verticalalignment='top',
                        bbox=props)

            cbar = plt.colorbar(im_spot)
            cbar.set_label("dose rate [krad/h]")

            plt.suptitle(
                "beamspot at distance 60 cm, tube parameter: 40 kV, 50 mA, no filter"
            )

            plt.savefig(filename[:-3] + ".png")
            plt.savefig(filename[:-3] + ".pdf")
            PdfPages.savefig()
Esempio n. 18
0
"""
mod_left_edge = -mod_length/2-1.0
mod_top_edge = -mod_width/2-1.0
mod_rect = Rectangle((mod_left_edge, mod_top_edge), mod_length, mod_width, fill=False, color="red", linewidth=2)
dhp1_rect = Rectangle((mod_left_edge+1.3494-dhp_length/2, mod_top_edge+0.2759-dhp_width/2), dhp_length, dhp_width, fill=False, color="red", linewidth=1.5)
dhp2_rect = Rectangle((mod_left_edge+1.3494-dhp_length/2, mod_top_edge+0.2759-dhp_width/2+0.35), dhp_length, dhp_width, fill=False, color="red", linewidth=1.5)
dhp3_rect = Rectangle((mod_left_edge+1.3494-dhp_length/2, mod_top_edge+0.2759-dhp_width/2+0.35*2), dhp_length, dhp_width, fill=False, color="red", linewidth=1.5)
dhp4_rect = Rectangle((mod_left_edge+1.3494-dhp_length/2, mod_top_edge+0.2759-dhp_width/2+0.35*3), dhp_length, dhp_width, fill=False, color="red", linewidth=1.5)
patches = [mod_rect, dhp1_rect, dhp2_rect, dhp3_rect, dhp4_rect]
p = PatchCollection(patches, match_original=True)
"""

# t1 = mpl.transforms.Affine2D().rotate_deg(-90) + mpl.transforms.Affine2D().translate(0, -1) + axSpot.transData
# p.set_transform(t1)
# axSpot.add_collection(p)
p_mod.set_transform(mod_trans_a + axSpot.transData)
axSpot.add_collection(p_mod)
"""
axSpot.add_patch(mod_rect)
axSpot.add_patch(dhp1_rect)
axSpot.add_patch(dhp2_rect)
axSpot.add_patch(dhp3_rect)
axSpot.add_patch(dhp4_rect)
"""
axSpot.set_xlabel("x [cm]")
axSpot.set_ylabel("z [cm]")

axrange = np.arange(-6, +6.5, 0.5)
print data
print data[:, 12]
print data[12, :]
Esempio n. 19
0
def visualize_global_map(filename: str, obstacle_idx: int,
                         observations: torch.Tensor,
                         predictions: torch.Tensor):
    observations = observations[:, 3 * 64 * 64:].cpu().numpy()
    observations = observations * np.array(
        [25.0, 35.0, np.pi, 25.0, 35.0, np.pi], dtype=np.float32) * 2.0

    predictions = predictions[:, 3 * 64 * 64:].cpu().numpy()
    predictions = predictions * np.array(
        [25.0, 35.0, np.pi, 25.0, 35.0, np.pi], dtype=np.float32) * 2.0

    obs_center = load_obstacles(obstacle_idx)
    obstacles = [Rectangle((xy[0] - 4, xy[1] - 4), 8, 8) for xy in obs_center]
    obstacles = PatchCollection(obstacles, facecolor="gray", edgecolor="black")

    car_observation = PatchCollection(
        [Rectangle((-1, -0.5), 2, 1),
         Arrow(0, 0, 2, 0, width=1.0)],
        facecolor="blue",
        edgecolor="blue")
    car_prediction = PatchCollection(
        [Rectangle((-1, -0.5), 2, 1),
         Arrow(0, 0, 2, 0, width=1.0)],
        facecolor="yellow",
        edgecolor="yellow")

    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.subplots()
    ax.set_aspect('equal', 'box')
    ax.set_xlim([-25, 25])
    ax.set_ylim([-35, 35])

    canvas.draw()
    image = np.array(canvas.buffer_rgba())
    H, W, _ = image.shape
    writer = cv2.VideoWriter(filename, cv2.VideoWriter_fourcc(*'mp4v'), 30.,
                             (W, H), True)

    T = observations.shape[0]
    for t in range(T):
        # obstacles
        ax.add_collection(obstacles)
        # target
        ax.scatter(observations[-1, 3],
                   observations[-1, 4],
                   marker='*',
                   c="red")
        # current position
        transform = Affine2D().rotate(observations[t, 2]).translate(
            observations[t, 0], observations[t, 1])
        car_observation.set_transform(transform + ax.transData)
        ax.add_collection(car_observation)
        # predicted position
        transform = Affine2D().rotate(predictions[t, 2]).translate(
            predictions[t, 0], predictions[t, 1])
        car_prediction.set_transform(transform + ax.transData)
        ax.add_collection(car_prediction)
        # plot
        ax.set_xlim([-25, 25])
        ax.set_ylim([-35, 35])
        canvas.draw()
        image = np.array(canvas.buffer_rgba())[:, :, :3]
        writer.write(image)
        ax.clear()

    writer.release()
    h264_converter(filename)