Example #1
0
def visualize_sweeper(sweeper, nsite):
    import matplotlib.pyplot as plt
    dy = 0.3
    arr_dx = 0.3
    r = 0.1
    plt.scatter(arange(nsite), zeros(nsite), s=100, facecolor='k')
    ax = plt.gca()
    ax.set_ylim(-0.5, 1.)
    plt.axis('equal')
    for i, data in enumerate(sweeper):
        if i != 0:
            cc.remove()
            arr.remove()
        cc = plt.Circle((data[-1], dy), r)
        if len(data) == 3:
            if data[1] == '->':
                arr = plt.Arrow(data[-1] - arr_dx - r,
                                dy,
                                arr_dx,
                                0,
                                width=0.1)
            else:
                arr = plt.Arrow(data[-1] + arr_dx + r,
                                dy,
                                -arr_dx,
                                0,
                                width=0.1)
        ax.add_patch(cc)
        ax.add_patch(arr)
        plt.draw()
        plt.pause(0.3)
Example #2
0
def show(room,final, weights):
    
    pyplot.figure(figsize=(30.,30.))
    pyplot.title('MCL')
    
    pyplot.axis([0,COMP,0,LARGURA])
    pyplot.grid(b=True, color='0.75', linestyle='--')
    
    for particle in room:
        if weights[room.index(particle)] < .05:
            pyplot.gca().add_patch(pyplot.Circle((particle[0],particle[1]),1.5,facecolor='#ffb266',edgecolor='#994c00', alpha=0.5))
            pyplot.gca().add_patch(pyplot.Arrow(particle[0], particle[1], 3.0*m.cos(particle[2]), 3.0*m.sin(particle[2]), alpha=1., facecolor='#994c00', edgecolor='#994c00',width=1.5))
    
    
    
    pyplot.gca().add_patch(pyplot.Circle((final[0],final[1]),1.5,facecolor='#6666ff',edgecolor='#0000cc', alpha=0.5))
    pyplot.gca().add_patch(pyplot.Arrow(final[0], final[1], 3.0*m.cos(final[2]), 3.0*m.sin(final[2]), alpha=1., facecolor='#000000', edgecolor='#000000',width=1.5))
    
    global IMG_NR
    if IMG_NR == 0:
        shutil.rmtree('particles')
        os.mkdir('particles')
    IMG_NR += 1
    imagename = 'particles/Particles' + str(IMG_NR)                             
    pyplot.savefig(imagename)
Example #3
0
def animate(i):
	global force_arrow
	global net_force_arrow

	x = np.linspace(0, 10, 1000)
	y_data = [0,0,0,0,0,0]
	for y_idx in range(6):
		y_data[y_idx] = np.linspace(0, 0, 1000)

	for y_idx in range(6):
		for idx in range(i):
			y_data[y_idx][idx] = data[idx][y_idx]

	for y_idx in range(6):
		lines[y_idx].set_data(x, y_data[y_idx])


	mass_1.xy = (float(data[i][2])-0.5, 0)
	mass_2.xy = (float(data[i][5])-1.5, -3)

	if i > 0:
		ax_mass.patches.remove(force_arrow)
		ax_mass.patches.remove(net_force_arrow)

	force_arrow = plt.Arrow(float(data[i][2]), 1, float(data[i][1]) * 10, 0, color = 'r')
	net_force_arrow = plt.Arrow(float(data[i][2]), 2, float(data[i][4]) * 10, 0, color = 'g')
	ax_mass.add_patch(force_arrow)
	ax_mass.add_patch(net_force_arrow)


	fig_mass.canvas.draw()

	return lines[1], lines[2], lines[3], lines[4], lines[5],
Example #4
0
def visualization(robot, step, p, pr, weights):
    """ Visualization
    :param robot:   the current robot object
    :param step:    the current step
    :param p:       list with particles
    :param pr:      list of resampled particles
    :param weights: particle weights
    """

    plt.figure("Robot in the world", figsize=(15., 15.))
    plt.title('Particle filter, step ' + str(step))

    # draw coordinate grid for plotting
    grid = [0, world_size, 0, world_size]
    plt.axis(grid)
    plt.grid(b=True, which='major', color='0.75', linestyle='--')
    plt.xticks([i for i in range(0, int(world_size), 5)])
    plt.yticks([i for i in range(0, int(world_size), 5)])

    # draw particles
    for ind in range(len(p)):

        # particle
        circle = plt.Circle((p[ind].x, p[ind].y), 1., facecolor='#ffb266', edgecolor='#994c00', alpha=0.5)
        plt.gca().add_patch(circle)

        # particle's orientation
        arrow = plt.Arrow(p[ind].x, p[ind].y, 2*cos(p[ind].orientation), 2*sin(p[ind].orientation), alpha=1., facecolor='#994c00', edgecolor='#994c00')
        plt.gca().add_patch(arrow)


    # draw resampled particles
    for ind in range(len(pr)):

        # particle
        circle = plt.Circle((pr[ind].x, pr[ind].y), 1., facecolor='#66ff66', edgecolor='#009900', alpha=0.5)
        plt.gca().add_patch(circle)

        # particle's orientation
        arrow = plt.Arrow(pr[ind].x, pr[ind].y, 2*cos(pr[ind].orientation), 2*sin(pr[ind].orientation), alpha=1., facecolor='#006600', edgecolor='#006600')
        plt.gca().add_patch(arrow)

    # fixed landmarks of known locations
    for lm in landmarks:
        circle = plt.Circle((lm[0], lm[1]), 1., facecolor='#cc0000', edgecolor='#330000')
        plt.gca().add_patch(circle)

    # robot's location
    circle = plt.Circle((robot.x, robot.y), 1., facecolor='#6666ff', edgecolor='#0000cc')
    plt.gca().add_patch(circle)

    # robot's orientation
    arrow = plt.Arrow(robot.x, robot.y, 2*cos(robot.orientation), 2*sin(robot.orientation), alpha=0.5, facecolor='#000000', edgecolor='#000000')
    plt.gca().add_patch(arrow)

    plt.savefig("output/figure_" + str(step) + ".png")
    plt.close()
Example #5
0
def show_fixed(world, V, P):

    ax = plt.gca()

    # darken cliff
    cool = np.min(V) * 1.1
    for s in world.cliff_states:
        V[s.y, s.x] = cool

    im = ax.imshow(V, interpolation='nearest', origin='upper')
    plt.tick_params(axis='both', which='both', bottom='off', top='off',
                    labelbottom='off', right='off', left='off', labelleft='off')
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)

    plt.colorbar(im, cax=cax)

    ax.text(world.initial_state[1], world.initial_state[0], 'S', ha='center', va='center', fontsize=20)
    for s in world.goal_states:
        ax.text(s[1], s[0], 'G', ha='center', va='center', fontsize=20)
    for s in world.risky_goal_states:
        ax.text(s[1], s[0], 'R', ha='center', va='center', fontsize=20)

    for s in world.states():
        if s in world.cliff_states:
            continue
        if s in world.goal_states:
            continue
        if s in world.risky_goal_states:
            continue

        a = P[s.y, s.x]
        ax.add_patch(plt.Arrow(s.x + offsets[a][0], s.y + offsets[a][1], dirs[a][0], dirs[a][1], color='white'))

    plt.show()
Example #6
0
    def __init__(self, world, V=None):
        if V is None:
            self.V = -1 * np.ones((world.height, world.width))
        else:
            self.V = V
        # darken cliff
        cool = np.min(self.V) * 1.1
        for s in world.cliff_states:
            self.V[s.y, s.x] = cool

        plt.ion()

        self.fig, self.ax = plt.subplots()

        im = self.ax.imshow(self.V, interpolation='nearest', origin='upper')
        plt.tick_params(axis='both', which='both', bottom='off', top='off',
                        labelbottom='off', right='off', left='off', labelleft='off')
        divider = make_axes_locatable(self.ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(im, cax=cax)

        self.ax.text(world.initial_state.x, world.initial_state.y, 'S', ha='center', va='center', fontsize=20)
        for s in world.goal_states:
            self.ax.text(s[1], s[0], 'G', ha='center', va='center', fontsize=20)
        for s in world.risky_goal_states:
            self.ax.text(s[1], s[0], 'R', ha='center', va='center', fontsize=20)

        self.arrow = self.ax.add_patch(plt.Arrow(0, 0, 1, 1, color='white'))
Example #7
0
def animate(i):
    patch = plt.Arrow(rp[0, i],
                      rp[1, i], (t / 20) * math.cos(rp[2, i]),
                      (t / 20) * math.sin(rp[2, i]),
                      width=(t / 30))
    ax_anim.add_patch(patch)
    return patch,
Example #8
0
def animate(i):
    global patch
    global isIn, xco, yco, count, T1, T, V, k
    plt.axis([-4, 4, -4, 4])
    c = 0
    for part in particle:
        ax.patches.remove(arrows[c])
        part[0] = part[0] + v * np.cos(part[2]) * 0.8
        part[1] = part[1] + v * np.sin(part[2]) * 0.8
        if (part[0] >= 0.999 and isIn[c] and abs(part[1]) <= 0.1):
            isIn[c] = 0
            V.append(k - 1)
            T2 = time.time()
            T.append((T2 - T1))
            k -= 1
        if (abs(part[1]) >= 0.999 and isIn[c]):
            part[1] = 0.999 * np.sign(np.sin(part[2]))
            part[2] = -part[2]
        if (abs(part[0]) >= 0.999 and isIn[c]):
            part[0] = 0.999 * np.sign(np.cos(part[2]))
            part[2] = np.pi - part[2]
        xco[c] = part[0]
        yco[c] = part[1]
        arrows[c] = plt.Arrow(part[0],
                              part[1],
                              np.cos(part[2]) / 8,
                              np.sin(part[2]) / 8,
                              width=0.2,
                              animated=True)
        ax.add_patch(arrows[c])
        c = c + 1
    line.set_data(xco, yco)
    count = count + 1
    print(count)
    return line
def init():
    #    line.set_data([], [])
    #    global line
    ax.patches.pop(0)
    line = plt.Arrow(0, 0, 0, 0)
    ax.add_patch(line)
    return (line, )
Example #10
0
        def animate(point):
            if len(ax.patches) > 0:
                ax.patches.pop(0)
            patch = plt.Arrow(0, 0, point[0], point[1], width=0.1, color='k')
            ax.add_patch(patch)

            return patch,
    def plot_callback(self, timer_event=None):
        if len(self.particles) == 0:
            return
# graph initialization
        for particle in self.particles:
            if particle.circle is not None:
                particle.circle.remove()
            particle.circle = plt.Circle((particle.x, particle.y),
                                         10.,
                                         facecolor='#66ff66',
                                         edgecolor='#009900',
                                         alpha=0.5)
            self.ax.add_patch(particle.circle)

            # particle's angle
            if particle.arrow is not None:
                particle.arrow.remove()
            particle.arrow = plt.Arrow(particle.x,
                                       particle.y,
                                       20 * np.cos(particle.angle),
                                       -20 * np.sin(particle.angle),
                                       width=5.0)
            self.ax.add_patch(particle.arrow)

        plt.draw()
Example #12
0
    def animate(self, i):
        if i % 50 == 49:
            print(f"Visualizing frame {i + 1}")

        self.time = self.timesteps[i]

        if i == len(self.playback) - 2:
            plt.close()

        to_del = []

        for agent in self.playback[self.time]:
            id, x, y, gx, gy, vx, vy, rot = agent

            rotx = np.cos(rot)
            roty = np.sin(rot)
            print(rot, rotx, roty)
            self.agents[agent[0]].center = (x, y)
            self.dirs[id] = plt.Arrow(x,
                                      y,
                                      vx,
                                      vy,
                                      color=COLORS[id % len(COLORS)],
                                      width=0.5)
            self.ax.add_patch(self.dirs[id])

        return ([self.agents[agent_id] for agent_id in self.agents] +
                [self.dirs[agent_id] for agent_id in self.dirs])
Example #13
0
def create_arrow_map(events: pd.DataFrame,
                     event_type: str = "Pass",
                     match: str = "an unknown match",
                     fig=None,
                     ax=None,
                     pitch_length: int = 120,
                     pitch_width: int = 80,
                     color: str = "blue"):
    """
    This functions creates a map of arrows between the start point and end point of an event.
    :param events: a data frame containing events
    :param event_type: a string describing the event type for which to plot arrows
    :param match: a string describing the match for which the events are plotted
    :param fig: a figure
    :param ax: a subplot of the figure on which to plot the arrows
    :param pitch_length: a integer describing the length of the pitch
    :param pitch_width: a integer describing the width of the pitch
    :param color: a string describing the color of the arrows
    :return fig, ax: a figure containing a pitch with event arrows
    """

    # Filter only relevant events
    temp_df = events[events.type_name == event_type]

    # Filter start and end locations
    locations = pd.DataFrame(temp_df.location.to_list(),
                             columns=['x_start', 'y_start'])
    locations[['x_end', 'y_end']] = pd.DataFrame(
        temp_df[f'{event_type.lower()}_end_location'].to_list())

    # Add delta_x and delta_y
    locations['dx'] = locations.x_end - locations.x_start
    locations['dy'] = locations.y_end - locations.y_start

    # Draw pitch
    fig, ax = create_pitch(pitch_length, pitch_width, fig, ax)

    # Draw arrows
    for i, event in locations.iterrows():
        x_start, y_start, x_end, y_end, dx, dy = list(event)
        pass_circle = plt.Circle((x_start, y_start), 2, color=color)
        pass_circle.set_alpha(0.2)
        pass_arrow = plt.Arrow(x_start,
                               y_start,
                               dx,
                               dy,
                               width=3,
                               color=color,
                               in_layout=True)
        ax.add_patch(pass_circle)
        ax.add_patch(pass_arrow)

    # Set limits
    plt.ylim(0, pitch_width)
    plt.xlim(0, pitch_length)

    plt.title(
        f"{event_type} map of {events.player_name.unique()[0]} during {match}")

    return fig, ax
def main():
    tf = 30
    N = 1000
    time = np.linspace(0, tf, N, retstep=True)

    t = time[0]
    dt = time[1]

    T = 10
    g = 9.81
    m = 2.5

    pos = np.zeros((2, N))
    vel = np.zeros((2, N))
    theta = np.zeros((1, N))

    # Euler Cromer Method
    for i in range(0, N):
        theta[1, i] = np.tan(pos[1, i] / pos[2, i])

        vel[:, i + 1] = v[:, i] + fNoSpring(theta, T, m, g) * dt
        pos[:, i + 1] = pos[:, i] + v[:, i + 1] * dt

    for i in range(0, N):
        plt.Circle(pos[0, i], pos[1, i])
        plt.Arrow(0, 20, pos[0, i], pos[1, i], width=2)
Example #15
0
def showImage(im, kp, imageId):

    classToColor = ['', 'red', 'yellow', 'blue', 'magenta']
    im = im[:, :, (2, 1, 0)]

    thresh = 0.5

    line = [[13, 14], [14, 4], [4, 5], [5, 6], [14, 1], [1, 2], [2, 3], \
            [14, 10], [10, 11], [11, 12], [14, 7], [7, 8], [8, 9]]

    c = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']


    fig, ax = plt.subplots(figsize=(12, 12))
    fig = ax.imshow(im, aspect='equal')
    plt.axis('off')
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)

    thresh = 0.01

    for j in range(14):
        x, y, p = kp[j * 3 : (j + 1) * 3]
        '''
        if p < thresh:
            continue
        '''            

        ax.add_patch(
                plt.Circle((x, y), 3,
                      fill=True,
                      color = c[1], 
                      linewidth=2.0)
            )

        '''
        ax.text(x, y - 2, '{:.3f}'.format(kp_scores[i, j]),
                bbox=dict(facecolor='blue', alpha=0.2),
                fontsize=8, color='white')
        '''

    for l in line:
        i0 = l[0] - 1
        p0 = kp[i0 * 3 : (i0 + 1) * 3] 

        i1 = l[1] - 1
        p1 = kp[i1 * 3 : (i1 + 1) * 3]

        '''
        if p0[2] < thresh or p1[2] < thresh:
            continue
        '''
        
        ax.add_patch(
                plt.Arrow(p0[0], p0[1], p1[0] - p0[0], p1[1] - p0[1], 
                color = c[2])
                )

    plt.savefig(str(imageId) + 'regRect' , bbox_inches='tight', pad_inches=0)
Example #16
0
    def step(self, s, a):

        self.arrow.remove()
        arrow = plt.Arrow(s.x + offsets[a][0], s.y + offsets[a][1], dirs[a][0], dirs[a][1], color='white')
        self.arrow = self.ax.add_patch(arrow)

        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
Example #17
0
def showImage(im, boxes, keypoints, kpType):
    classToColor = ['', 'red', 'yellow', 'blue', 'magenta']
    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    fig = ax.imshow(im, aspect='equal')
    plt.axis('off')
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)

    thresh = 0.7

    line = [[13, 14], [14, 4], [4, 5], [5, 6], [14, 1], [1, 2], [2, 3], \
            [14, 10], [10, 11], [11, 12], [14, 7], [7, 8], [8, 9]]

    c = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']


    for i in xrange(boxes.shape[0]):

            bbox = boxes[i]

            '''
            ax.add_patch(
                    plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False,
                          edgecolor= c[i], linewidth=2.0)
                )
            ax.text(bbox[0], bbox[1] - 2,
                    '{:d}, {:d}'.format(int(bbox[2] - bbox[0]), 
                    int(bbox[3] - bbox[1])),
                    bbox=dict(facecolor='blue', alpha=0.2),
                    fontsize=8, color='white')
            '''

            keypoint = keypoints[i]
            for j in range(14):
                if keypoint[j * 3 + 2] <= kpType:
                    x, y, z = keypoint[j * 3 : (j + 1) * 3]
                    ax.add_patch(
                            plt.Circle((x, y), 3,
                                  fill=True,
                                  color = c[i%8], 
                                  linewidth=2.0)
                        )

            for l in line:
                i0 = l[0] - 1
                p0 = keypoint[i0 * 3 : (i0 + 1) * 3] 
                i1 = l[1] - 1
                p1 = keypoint[i1 * 3 : (i1 + 1) * 3]
                if p0[2] <= kpType and p1[2] <= kpType:
                    ax.add_patch(
                            plt.Arrow(p0[0], p0[1], 
                            float(p1[0]) - p0[0], float(p1[1]) - p0[1], 
                            color = c[i%8])
                            )
Example #18
0
def showImage(im, box, score, kp, imageIdx, boxIdx):
    print(box)
    print(kp)

    classToColor = ['', 'red', 'yellow', 'blue', 'magenta']
    im = im[:, :, (2, 1, 0)]

    thresh = 0.5

    line = [[13, 14], [14, 4], [4, 5], [5, 6], [14, 1], [1, 2], [2, 3], \
            [14, 10], [10, 11], [11, 12], [14, 7], [7, 8], [8, 9]]

    c = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']

    fig, ax = plt.subplots(figsize=(12, 12))
    fig = ax.imshow(im, aspect='equal')
    plt.axis('off')
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)

    ax.add_patch(
        plt.Rectangle((box[0], box[1]),
                      box[2] - box[0],
                      box[3] - box[1],
                      fill=False,
                      edgecolor='r',
                      linewidth=2.0))

    prob = sum(kp[2::3]) / 14

    ax.text(box[0],
            box[1] - 2,
            '{:.3f} {:.3f}'.format(score, prob),
            bbox=dict(facecolor='blue', alpha=0.2),
            fontsize=8,
            color='white')

    for j in range(14):
        x, y, p = kp[j * 3:(j + 1) * 3]

        ax.add_patch(
            plt.Circle((x, y), 3, fill=True, color=c[1], linewidth=2.0))

    for l in line:
        i0 = l[0] - 1
        p0 = kp[i0 * 3:(i0 + 1) * 3]

        i1 = l[1] - 1
        p1 = kp[i1 * 3:(i1 + 1) * 3]

        ax.add_patch(
            plt.Arrow(p0[0], p0[1], p1[0] - p0[0], p1[1] - p0[1], color=c[2]))

    plt.savefig('{}_{}_repoolRect.png'.format(imageIdx, boxIdx),
                bbox_inches='tight',
                pad_inches=0)
Example #19
0
def makeArtist(node, pos=np.array([0, 0]), rot=0):
    "Creates an artist object from node"

    nodePos = np.matmul(rotMat(rot), node.pos) + pos
    circle = plt.Circle(nodePos, node.r, fill=False)
    arrowbase = nodePos + node.r * np.array([0.5 * node.o, 0.5])
    arrowdelta = node.r * np.array([-node.o, 0])
    arrow = plt.Arrow(*arrowbase, *arrowdelta, node.r / 2, color="r")

    return [circle, arrow]
Example #20
0
def show(room, final):

    pyplot.figure(figsize=(30., 30.))
    pyplot.title('MCL')

    pyplot.axis([0, COMP, 0, LARGURA])
    pyplot.grid(b=True, color='0.75', linestyle='--')

    for particle in room:
        pyplot.gca().add_patch(
            pyplot.Circle((particle[0], particle[1]),
                          15.,
                          facecolor='#ffb266',
                          edgecolor='#994c00',
                          alpha=0.5))
        pyplot.gca().add_patch(
            pyplot.Arrow(particle[0],
                         particle[1],
                         30 * m.cos(particle[2]),
                         30 * m.sin(particle[2]),
                         alpha=1.,
                         facecolor='#994c00',
                         edgecolor='#994c00',
                         width=15))

    pyplot.gca().add_patch(
        pyplot.Circle((final[0], final[1]),
                      15.,
                      facecolor='#6666ff',
                      edgecolor='#0000cc',
                      alpha=0.5))
    pyplot.gca().add_patch(
        pyplot.Arrow(final[0],
                     final[1],
                     30 * m.cos(final[2]),
                     30 * m.sin(final[2]),
                     alpha=1.,
                     facecolor='#000000',
                     edgecolor='#000000',
                     width=15))

    #IMG_COUNT = IMG_COUNT + 1
    pyplot.savefig('Particles')
Example #21
0
def showImage(im, kps, gt_boxes, gt_kps):

    oks, oks_full = compute_oks(kps, gt_boxes, gt_kps)

    classToColor = ['', 'red', 'yellow', 'blue', 'magenta']
    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    fig = ax.imshow(im, aspect='equal')
    plt.axis('off')
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)

    thresh = 0.7

    line = [[13, 14], [14, 4], [4, 5], [5, 6], [14, 1], [1, 2], [2, 3], \
            [14, 10], [10, 11], [11, 12], [14, 7], [7, 8], [8, 9]]


    b = 'b'
    r = 'r'
    g = 'g'
    c = [b, b, b, r, r, r, b, b, b, r, r, r, g, g]
    c2 = [g, r, r, r, b, b, b, r, r, r, b, b, b]

    for i, kp in enumerate(kps):

        for j in range(14):
            if kp[j * 3 + 2] == 3:
                continue
            x, y, z = kp[j * 3 : (j + 1) * 3]
            ax.add_patch(
                    plt.Circle((x, y), 3,
                          fill=True,
                          color = c[j], 
                          linewidth=2.0)
                )
            ax.text(x, y - 2, '{:3f}'.format(oks_full[i,j]), 
                    bbox=dict(facecolor='blue', alpha=0.2),
                    fontsize=8, color='white')

        for j, l in enumerate(line):
            i0 = l[0] - 1
            p0 = kp[i0 * 3 : (i0 + 1) * 3] 

            i1 = l[1] - 1
            p1 = kp[i1 * 3 : (i1 + 1) * 3]

            if p0[2] == 3 or p1[2] == 3:
                continue
            
            ax.add_patch(
                    plt.Arrow(p0[0], p0[1], 
                    float(p1[0]) - p0[0], float(p1[1]) - p0[1], 
                    color = c2[j])
                    )
    def Connect_points(self, startp, nextp):
        spx = startp[0][0]
        spy = startp[0][1]
        npx = nextp[0][0]
        npy = nextp[0][1]

        #as shown in sample py file, we need manhattan distance between the 2 points to draw an arrow connecting them
        l1 = npx - spx
        l2 = npy - spy
        connect = plt.Arrow(spx, spy, l1, l2, width=0.1, color='black')
        return connect
Example #23
0
    def show_board(self, move=[], arrow_color='green', ax=None):
        '''
        Display board with pieces

        If move is given, depict an arrow showing move from move[0] to move[1]
        '''
        if ax is None:
            fig, ax = plt.subplots()

        for i in range(self.board_size):
            for j in range(self.board_size):
                if (i + j) % 2 == 0:
                    square_color = 'grey'
                else:
                    square_color = 'white'

                ax.add_artist(plt.Rectangle((i, j), 1, 1, color=square_color))

                if (i, j) in move:
                    ax.add_artist(
                        plt.Circle((i + .5, j + .5),
                                   0.4,
                                   color='green',
                                   fill=False))

                if self.board[i, j] > 0:
                    color = 'red'
                elif self.board[i, j] < 0:
                    color = 'black'
                else:
                    continue
                #print i,j
                ax.add_artist(plt.Circle((i + .5, j + .5), 0.2, color=color))
                if abs(self.board[i, j]) > 1:
                    ###This piece is a king
                    ax.add_artist(
                        plt.Circle((i + .5, j + .5),
                                   0.3,
                                   color=color,
                                   fill=False))

        if len(move) == 2:
            ax.add_artist(
                plt.Arrow(move[0][0] + .5,
                          move[0][1] + .5, (move[1][0] - move[0][0]),
                          (move[1][1] - move[0][1]),
                          color=arrow_color,
                          width=.5))

        plt.xlim(0, self.board_size)
        plt.ylim(0, self.board_size)

        plt.show()
Example #24
0
def test_arrow():
    import matplotlib.pyplot as plt
    g = imgutils.galaxy()

    stack = FigureStack()
    fig, ax = stack.add_subplots()

    ax.imshow(g)

    patch = plt.Arrow(50, 50, 20, 30, width=10)
    ax.add_patch(patch)

    stack.show()
Example #25
0
def create_arrows(markers: Iterable[Marker], color: Any,
                  width: float) -> List[plt.Arrow]:
    """Creates an arrow on each marker that represents the marker orientation and returns them."""
    arrows = []
    for m in markers:
        x = m.position.x
        y = m.position.y
        dx = m.radius * scipy.cos(m.orientation)
        dy = m.radius * scipy.sin(m.orientation)
        arrows.append(
            plt.Arrow(x - dx, y - dy, 2 * dx, 2 * dy, color=color,
                      width=width))
    return arrows
Example #26
0
def LeftDrag(event):
    global data_index
    if data_index is None: return
    X[data_index] = [event.xdata,event.ydata]
    x,n = PiolaTransform()
    edge_plot.set_xdata(X[[0,1,2,0],0])
    edge_plot.set_ydata(X[[0,1,2,0],1])
    vert_plot.set_xdata(X[:,0])
    vert_plot.set_ydata(X[:,1])
    ax.patches.pop(0)
    norm_plot = plt.Arrow(x[0],x[1],n[0],n[1],width=0.2,lw=0.1,color='r')
    ax.add_patch(norm_plot)
    fig.canvas.draw_idle()
Example #27
0
def showImage(im, keypoints):

    classToColor = ['', 'red', 'yellow', 'blue', 'magenta']
    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    fig = ax.imshow(im, aspect='equal')
    plt.axis('off')
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)

    thresh = 0.7

    line = [[13, 14], [14, 4], [4, 5], [5, 6], [14, 1], [1, 2], [2, 3], \
            [14, 10], [10, 11], [11, 12], [14, 7], [7, 8], [8, 9]]

    c = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']

    i = 0
    for key in keypoints:
        
        keypoint = keypoints[key]
        for j in range(14):
            if keypoint[j * 3 + 2] == 3:
                continue

            x, y, z = keypoint[j * 3 : (j + 1) * 3]


            ax.add_patch(
                    plt.Circle((x, y), 3,
                          fill=True,
                          color = c[i], 
                          linewidth=2.0)
                )
        for l in line:
            i0 = l[0] - 1
            p0 = keypoint[i0 * 3 : (i0 + 1) * 3] 

            i1 = l[1] - 1
            p1 = keypoint[i1 * 3 : (i1 + 1) * 3]


            if p0[2] == 3 or p1[2] == 3:
                continue
            
            ax.add_patch(
                    plt.Arrow(p0[0], p0[1], 
                    float(p1[0]) - p0[0], float(p1[1]) - p0[1], 
                    color = c[i])
                    )
        i += 1
def draw_observed(state=0, state_label=0):
    radius = 0.5
    x = state * delta
    y = -2
    pos_circle = plt.Circle((x, y), radius=radius, fill=False, color='g', lw=2)
    plt.gca().add_patch(pos_circle)
    plt.text(x,
             y,
             '$X_{%s}$' % (str(state_label)),
             fontsize=12,
             horizontalalignment='center',
             verticalalignment='center')
    arrow = plt.Arrow(x, -radius, 0, -2 + 2 * radius, width=0.25)
    plt.gca().add_patch(arrow)
Example #29
0
def animate(t):
    # animate arrow
    if ax1.patches:
        ax1.patches.pop(0)
    patch = plt.Arrow(states[t, 0],
                      states[t, 1],
                      arrow_len * np.sin(states[t, 4]),
                      arrow_len * np.cos(states[t, 4]),
                      width=0.1)
    ax1.add_patch(patch)
    # animate bar graph
    for j, b in enumerate(bar_plot):
        b.set_height(saliency[t, j])
    return patch,
Example #30
0
    def plotter(self, start_pos, end_pos, color="black"):
        x_s = start_pos[0]
        y_s = start_pos[1]
        theta = start_pos[2]

        x_f = end_pos[0]
        y_f = end_pos[1]

        dx = x_f - x_s
        dy = y_f - y_s
        # head_width=0.5,length_includes_head=True, head_length=0.5,
        arrow = plt.Arrow(x_s, y_s, dx, dy, color=color)

        return arrow