Example #1
0
def draw_pitch(ax,fill=True,numbers=True):
    # focus on only half of the pitch
    #Pitch Outline & Centre Line
    if fill:
        Pitch = pat.Rectangle([0,0], width = 60, height = 68, facecolor='green', edgecolor='white')
    else:
        Pitch = pat.Rectangle([0,0], width = 60, height = 68, fill=False)
    #Left, Right Penalty Area and midline
    goalline =pat.ConnectionPatch([10,0], [10,68], "data", "data",color='white',lw=4)
    tenline =pat.ConnectionPatch([20,0], [20,68], "data", "data",color='white')
    twentyline =pat.ConnectionPatch([30,0], [30,68], "data", "data",color='white')
    thirtyline =pat.ConnectionPatch([40,0], [40,68], "data", "data",color='white')
    fortyline =pat.ConnectionPatch([50,0], [50,68], "data", "data",color='red')
    midline = pat.ConnectionPatch([60,0], [60,68], "data", "data",color='white')
    
    #goalposts
    leftpost=pat.ConnectionPatch([10,30], [2,40],"data","data",color='white')
    rightpost=pat.ConnectionPatch([10,38], [2,48],"data","data",color='white')
    crossbar = pat.ConnectionPatch([7,33.65], [7,41.65],"data","data",color='white')
    thedot = pat.ConnectionPatch([7,37.5], [7,37.8],"data","data",color='black')


    element = [Pitch, goalline,tenline,twentyline,thirtyline,fortyline,midline,leftpost,rightpost,crossbar,thedot]
    for i in element:
        ax.add_patch(i)
    if numbers==True:     
        plt.text(18,10,'1',color='white',fontsize=17)
        plt.text(20,10,'0',color='white',fontsize=17)
        plt.text(27,10,'2',color='white',fontsize=17)
        plt.text(30,10,'0',color='white',fontsize=17)
        plt.text(37,10,'3',color='white',fontsize=17)
        plt.text(40,10,'0',color='white',fontsize=17)
        plt.text(47,10,'4',color='white',fontsize=17)
        plt.text(50,10,'0',color='white',fontsize=17)
Example #2
0
def test_connection_patch_fig(fig_test, fig_ref):
    # Test that connection patch can be added as figure artist, and that figure
    # pixels count negative values from the top right corner (this API may be
    # changed in the future).
    ax1, ax2 = fig_test.subplots(1, 2)
    con = mpatches.ConnectionPatch(xyA=(.3, .2),
                                   coordsA="data",
                                   axesA=ax1,
                                   xyB=(-30, -20),
                                   coordsB="figure pixels",
                                   arrowstyle="->",
                                   shrinkB=5)
    fig_test.add_artist(con)

    ax1, ax2 = fig_ref.subplots(1, 2)
    bb = fig_ref.bbox
    # Necessary so that pixel counts match on both sides.
    plt.rcParams["savefig.dpi"] = plt.rcParams["figure.dpi"]
    con = mpatches.ConnectionPatch(xyA=(.3, .2),
                                   coordsA="data",
                                   axesA=ax1,
                                   xyB=(bb.width - 30, bb.height - 20),
                                   coordsB="figure pixels",
                                   arrowstyle="->",
                                   shrinkB=5)
    fig_ref.add_artist(con)
Example #3
0
    def draw(self):
        '''Draw the funnel.'''
        shapes = []

        coordinates = np.array([
            [
                self.prev_position.x + self.prev_output_dim.x,
                self.prev_position.y + self.prev_output_dim.y
            ],
            [
                self.curr_position.x,
                self.curr_position.y + self.curr_output_dim.y
            ],
            [
                self.curr_position.x + self.curr_depth,
                self.curr_position.y + self.curr_depth + self.curr_output_dim.y
            ],
            [
                self.prev_position.x + self.prev_output_dim.x +
                self.prev_depth,
                self.prev_position.y + self.prev_output_dim.y + self.prev_depth
            ]
        ])

        # Draw Polyogong
        shapes = np.append(shapes, pat.Polygon(coordinates, alpha=0.2))

        # Draw dotted lines
        shapes = np.append(
            shapes,
            pat.ConnectionPatch(
                xyA=(self.prev_position.x + self.prev_output_dim.x,
                     self.prev_position.y + self.prev_output_dim.y),
                xyB=(self.curr_position.x,
                     self.curr_position.y + self.curr_output_dim.y),
                coordsA="data",
                color=self.color,
                linewidth=1,
                linestyle=':',
                arrowstyle='-'))
        shapes = np.append(
            shapes,
            pat.ConnectionPatch(xyA=(self.curr_position.x + self.curr_depth,
                                     self.curr_position.y + self.curr_depth +
                                     self.curr_output_dim.y),
                                xyB=(self.prev_position.x +
                                     self.prev_output_dim.x + self.prev_depth,
                                     self.prev_position.y +
                                     self.prev_output_dim.y + self.prev_depth),
                                coordsA="data",
                                color=self.color,
                                linewidth=1,
                                linestyle=':',
                                arrowstyle='-'))
        return shapes
Example #4
0
    def visualise_sample(mixture,
                         visualise_mean=True,
                         visualise_std=True,
                         visualise_var=True,
                         params_from_sample=True,
                         figsize=(18, 8)):
        plt.figure(figsize=figsize)
        for i in range(mixture.nb_gaussians):
            sample = mixture.samples[i]
            if params_from_sample:
                m, v, s = sample.mean(), sample.var(), sample.std()
            else:
                m, v, s = mixture.means[i], mixture.vars[i], mixture.stds[i]

            p = plt.scatter(range(len(sample)), sample, s=0.05)
            color = p.get_facecolor()[0]
            x = (i + 1) / (mixture.nb_gaussians + 1) * len(sample)

            if visualise_mean:
                plt.plot(
                    [-.025 * len(sample), len(sample)], [m] * 2,
                    c=color,
                    linewidth=MixturePlotter.MEAN_WIDTH)

            if visualise_std:
                std_plot = patches.ConnectionPatch(
                    (x, m - s), (x, m + s),
                    'data',
                    'data',
                    arrowstyle="|-|,widthA=1, widthB=1",
                    linestyle=MixturePlotter.STD_STYLE,
                    lw=MixturePlotter.STD_WIDTH,
                    color=color)
                p.axes.add_patch(std_plot)

            if visualise_var:
                ylim = p.axes.get_ylim()
                ylim = (min(ylim[0], m - v), max(ylim[1], m + v))
                p.axes.set_ylim(ylim[0], ylim[1])
                var_plot = patches.ConnectionPatch(
                    (x, m - v), (x, m + v),
                    'data',
                    'data',
                    arrowstyle="|-|,widthA=1, widthB=1",
                    linestyle=MixturePlotter.VAR_STYLE,
                    lw=MixturePlotter.VAR_WIDTH,
                    color=MixturePlotter.VAR_COLOR)
                p.axes.add_patch(var_plot)
Example #5
0
    def render_adjacency(self, A, team_id, ax, color='b', stepsize=1.0):
        A = A.copy()
        own_team_agents = [agent for agent in self.teams[team_id]]
        other_agents = [
            agent for other_team_id, team in self.teams.items()
            for agent in team if not team_id == other_team_id
        ]
        all_agents = own_team_agents + other_agents
        for agent_id, agent in enumerate(all_agents):
            for connected_agent_id in np.arange(len(A)):
                if A[agent_id][connected_agent_id] > 0:
                    current_agent_pose = agent.prev_pose + (
                        agent.pose - agent.prev_pose) * stepsize
                    other_agent = all_agents[connected_agent_id]
                    other_agent_pose = other_agent.prev_pose + (
                        other_agent.pose - other_agent.prev_pose) * stepsize
                    ax.add_patch(
                        patches.ConnectionPatch(
                            [current_agent_pose[X], current_agent_pose[Y]],
                            [other_agent_pose[X], other_agent_pose[Y]],
                            "data",
                            edgecolor='g',
                            facecolor='none',
                            lw=1,
                            ls=":"))

                    A[connected_agent_id][
                        agent_id] = 0  # don't draw same connection again
Example #6
0
def test_connection_patch():
    fig, (ax1, ax2) = plt.subplots(1, 2)

    con = mpatches.ConnectionPatch(xyA=(0.1, 0.1), xyB=(0.9, 0.9),
                                   coordsA='data', coordsB='data',
                                   axesA=ax2, axesB=ax1,
                                   arrowstyle="->")
    ax2.add_artist(con)

    xyA = (0.6, 1.0)  # in axes coordinates
    xyB = (0.0, 0.2)  # x in axes coordinates, y in data coordinates
    coordsA = "axes fraction"
    coordsB = ax2.get_yaxis_transform()
    con = mpatches.ConnectionPatch(xyA=xyA, xyB=xyB, coordsA=coordsA,
                                   coordsB=coordsB, arrowstyle="-")
    ax2.add_artist(con)
Example #7
0
def draw_geodesic(a, b, c, ax, c1=None, c2=None, verbose=False, width=.02):
   
    cent = get_circle_center(a,b,c)  
    radius = euclid_dist(a, cent)
    t1 = get_angles(cent, b)
    t2 = get_angles(cent, a)

    mask = np.logical_or(np.logical_and(t2 > t1, t2 - t1 < 180), np.logical_and(t1 > t2, t1 - t2 >= 180))

    theta1 = np.where(mask, t1, t2)
    theta2 = np.where(mask, t2, t1)
    
    collinear_mask = collinear(a, b, c)
    mask_ = np.logical_or(collinear_mask, np.abs(t1 - t2) < 10)
    
    coordsA = "data"
    coordsB = "data"

    for ma_, a_, b_, c_, cent_, radius_, theta1_, theta2_ in zip(mask_, a, b, c, cent, radius, theta1, theta2):
        if ma_:
            e = patches.ConnectionPatch(a_, b_, coordsA, coordsB, 
                linewidth=width, 
                zorder=0, 
                )
        else:
            e = patches.Arc((cent_[0], cent_[1]), 2*radius_, 2*radius_,
                             theta1=theta1_, theta2=theta2_, linewidth=width, fill=False, zorder=0)
        ax.add_patch(e)
Example #8
0
def draw_node(state, color, radius_scale=1., dim=2, face=False):
    if dim == 2:
        facecolor = 'none'
        if face:
            facecolor = color
        circle = patches.Circle(tuple(state + 1.0),
                                radius=0.02 * radius_scale,
                                edgecolor=color,
                                facecolor=facecolor)
        plt.gca().add_patch(circle)

    elif dim == 3:
        a, b = MazeEnv._end_points(state)
        plt.gca().add_patch(
            patches.ConnectionPatch(a + 1.0,
                                    b + 1.0,
                                    'data',
                                    arrowstyle="-",
                                    linewidth=2,
                                    color=color))
        plt.gca().add_patch(
            patches.Circle(a + 1.0,
                           radius=0.02 * radius_scale,
                           edgecolor=color,
                           facecolor=color))
Example #9
0
def draw_edge(state0, state1, color, dim=2, style='-'):
    path = patches.ConnectionPatch(tuple(state0[:2] + 1.0),
                                   tuple(state1[:2] + 1.0),
                                   'data',
                                   arrowstyle=style,
                                   color=color)
    plt.gca().add_patch(path)
def drawMatch(match, finalLabels, autoLabels):
    randCmap = np.random.rand(256, 3)
    randCmap[0, :] = 0
    cmap = mc.ListedColormap(randCmap)
    f, ax = plt.subplots(1, 2, sharex=True, sharey=True)
    ax[1].set_title('truth')
    ax[1].imshow(finalLabels, cmap=cmap)
    ax[0].set_title('auto')
    ax[0].imshow(autoLabels, cmap=cmap)
    for a, b in match.items():
        #print a,b
        xya = np.mean(np.where(finalLabels == a), axis=1)
        xyb = np.mean(np.where(autoLabels == b), axis=1)
        #print xya,xyb
        coordsA = "data"
        coordsB = "data"
        con = mpatches.ConnectionPatch(xyA=xya[::-1],
                                       xyB=xyb[::-1],
                                       coordsA=coordsA,
                                       coordsB=coordsB,
                                       axesA=ax[1],
                                       axesB=ax[0],
                                       arrowstyle="->",
                                       shrinkB=5,
                                       color=cmap(a))
        ax[1].add_artist(con)
    return f, ax
Example #11
0
def plot_region_line(tx, coords, _c, _plt):
    #
    i = 0
    first_ploted = False
    #
    coord_line = []
    #
    for x in coords:
        #
        if i == len(coords) - 1:
            pass
        else:
            #
            if _plt:
                #
                _p = mpatches.ConnectionPatch(
                    x,
                    coords[i + 1],
                    "data",
                    lw=1,
                    arrowstyle='->,head_width=.15,head_length=.15',
                    shrinkB=7,
                    color=_c,
                    label='Label')
                tx.add_patch(_p)
                #
            #
        #
        coord_line.append(x)
        #
        i = i + 1
        #
    #
    #
    return coord_line
Example #12
0
def make_connection(
    x1: float,
    y1: float,
    x2: float,
    y2: float,
    color: str,
    opacity: float = 1.,
    linewidth: float = 1.,
    arrow_style: m_patches.ArrowStyle = m_patches.ArrowStyle.Curve()):
    """
    Makes a line (with a particular arrow style) between (x1, y1) and (x2, y2)

    Parameters
    ----------
    x1
    y1
    x2
    y2
    arrow_style
    color
    opacity
    linewidth

    Returns
    -------
    matplotlib patch
    """
    return m_patches.ConnectionPatch((x1, y1), (x2, y2),
                                     "data",
                                     "data",
                                     arrowstyle=arrow_style,
                                     edgecolor=color,
                                     alpha=opacity,
                                     linewidth=linewidth)
Example #13
0
def connect_rectangles(Rectangle_1, Rectangle_2, LeftorRight, ax):
    x1 = Rectangle_1[0] + Rectangle_1[2] / 2
    y1 = Rectangle_1[1]

    x2 = Rectangle_2[0] + Rectangle_2[2] / 2
    y2 = Rectangle_2[1] + Rectangle_2[3]

    if LeftorRight == "left":
        text = "yes"
        p = -1
    else:
        text = "no"
        p = 1
    coordsA = "data"
    coordsB = "data"
    con = mpatch.ConnectionPatch(xyA=(x1, y1),
                                 xyB=(x2, y2),
                                 coordsA=coordsA,
                                 coordsB=coordsB,
                                 arrowstyle="-")
    ax.add_artist(con)
    ax.annotate(
        text,
        ((x1 + x2) / 2 + p, (y1 + y2) / 2),
        color="b",
        weight="bold",
        fontsize=10,
        ha="center",
        va="center",
    )
Example #14
0
def plot_region_line(tx, coords, _c):
    #
    i = 0
    #
    for x in coords:
        #
        if i < len(coords) - 1:
            #
            _p = mpatches.ConnectionPatch(
                x[1],
                coords[i + 1][1],
                "data",
                lw=1,
                arrowstyle='->,head_width=.15,head_length=.15',
                shrinkB=5,
                color=_c,
                label='Label')
            tx.add_patch(_p)
            #
            _midpoint = midpoint(x[1], coords[i + 1][1])
            myradians = angle(x[1], coords[i + 1][1])
            #
            label(_midpoint, myradians, tx)
            #
        i = i + 1
Example #15
0
def test_patch_str():
    """
    Check that patches have nice and working `str` representation.

    Note that the logic is that `__str__` is defined such that:
    str(eval(str(p))) == str(p)
    """
    p = mpatches.Circle(xy=(1, 2), radius=3)
    assert str(p) == 'Circle(xy=(1, 2), radius=3)'

    p = mpatches.Ellipse(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Ellipse(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Rectangle(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Rectangle(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)
    assert str(p) == 'Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)'

    p = mpatches.Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)
    expected = 'Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)'
    assert str(p) == expected

    p = mpatches.Annulus(xy=(1, 2), r=(3, 4), width=1, angle=2)
    expected = "Annulus(xy=(1, 2), r=(3, 4), width=1, angle=2)"
    assert str(p) == expected

    p = mpatches.RegularPolygon((1, 2), 20, radius=5)
    assert str(p) == "RegularPolygon((1, 2), 20, radius=5, orientation=0)"

    p = mpatches.CirclePolygon(xy=(1, 2), radius=5, resolution=20)
    assert str(p) == "CirclePolygon((1, 2), radius=5, resolution=20)"

    p = mpatches.FancyBboxPatch((1, 2), width=3, height=4)
    assert str(p) == "FancyBboxPatch((1, 2), width=3, height=4)"

    # Further nice __str__ which cannot be `eval`uated:
    path = mpath.Path([(1, 2), (2, 2), (1, 2)], closed=True)
    p = mpatches.PathPatch(path)
    assert str(p) == "PathPatch3((1, 2) ...)"

    p = mpatches.Polygon(np.empty((0, 2)))
    assert str(p) == "Polygon0()"

    data = [[1, 2], [2, 2], [1, 2]]
    p = mpatches.Polygon(data)
    assert str(p) == "Polygon3((1, 2) ...)"

    p = mpatches.FancyArrowPatch(path=path)
    assert str(p)[:27] == "FancyArrowPatch(Path(array("

    p = mpatches.FancyArrowPatch((1, 2), (3, 4))
    assert str(p) == "FancyArrowPatch((1, 2)->(3, 4))"

    p = mpatches.ConnectionPatch((1, 2), (3, 4), 'data')
    assert str(p) == "ConnectionPatch((1, 2), (3, 4))"

    s = mpatches.Shadow(p, 1, 1)
    assert str(s) == "Shadow(ConnectionPatch((1, 2), (3, 4)))"
def test_connection_patch():
    fig, (ax1, ax2) = plt.subplots(1, 2)

    con = mpatches.ConnectionPatch(xyA=(0.1, 0.1), xyB=(0.9, 0.9),
                                   coordsA='data', coordsB='data',
                                   axesA=ax2, axesB=ax1,
                                   arrowstyle="->")
    ax2.add_artist(con)
Example #17
0
def test_patch_str():
    """
    Check that patches have nice and working `str` representation.

    Note that the logic is that `__str__` is defined such that:
    str(eval(str(p))) == str(p)
    """
    p = mpatches.Circle(xy=(1, 2), radius=3)
    assert str(p) == 'Circle(xy=(1, 2), radius=3)'

    p = mpatches.Ellipse(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Ellipse(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Rectangle(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Rectangle(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)
    assert str(p) == 'Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)'

    p = mpatches.Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)
    expected = 'Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)'
    assert str(p) == expected

    p = mpatches.RegularPolygon((1, 2), 20, radius=5)
    assert str(p) == "RegularPolygon((1, 2), 20, radius=5, orientation=0)"

    p = mpatches.CirclePolygon(xy=(1, 2), radius=5, resolution=20)
    assert str(p) == "CirclePolygon((1, 2), radius=5, resolution=20)"

    p = mpatches.FancyBboxPatch((1, 2), width=3, height=4)
    assert str(p) == "FancyBboxPatch((1, 2), width=3, height=4)"

    # Further nice __str__ which cannot be `eval`uated:
    path_data = [([1, 2], mpath.Path.MOVETO), ([2, 2], mpath.Path.LINETO),
                 ([1, 2], mpath.Path.CLOSEPOLY)]
    p = mpatches.PathPatch(mpath.Path(*zip(*path_data)))
    assert str(p) == "PathPatch3((1, 2) ...)"

    data = [[1, 2], [2, 2], [1, 2]]
    p = mpatches.Polygon(data)
    assert str(p) == "Polygon3((1, 2) ...)"

    p = mpatches.FancyArrowPatch(path=mpath.Path(*zip(*path_data)))
    assert str(p)[:27] == "FancyArrowPatch(Path(array("

    p = mpatches.FancyArrowPatch((1, 2), (3, 4))
    assert str(p) == "FancyArrowPatch((1, 2)->(3, 4))"

    p = mpatches.ConnectionPatch((1, 2), (3, 4), 'data')
    assert str(p) == "ConnectionPatch((1, 2), (3, 4))"

    s = mpatches.Shadow(p, 1, 1)
    assert str(s) == "Shadow(ConnectionPatch((1, 2), (3, 4)))"

    with pytest.warns(MatplotlibDeprecationWarning):
        p = mpatches.YAArrow(plt.gcf(), (1, 0), (2, 1), width=0.1)
        assert str(p) == "YAArrow()"
Example #18
0
def test_connection_patch_fig():
    # Test that connection patch can be added as figure artist
    fig, (ax1, ax2) = plt.subplots(1, 2)
    xy = (0.3, 0.2)
    con = mpatches.ConnectionPatch(xyA=xy, xyB=xy,
                                   coordsA="data", coordsB="data",
                                   axesA=ax1, axesB=ax2,
                                   arrowstyle="->", shrinkB=5)
    fig.add_artist(con)
    fig.canvas.draw()
Example #19
0
def plot_region_line(tx, coords, _c, scp):
	#
	'''
	Draw lines only for points that are in sequence.
	'''
	#
	i = 0
	first_ploted = False
	#
	coord_line = []
	#
	for x in coords:
		#
		if i < len(coords) -1:
			#
			#
			srt_num = x[3]
			end_num = coords[i][3]
			next_num = coords[i+1][3]
			#
			if srt_num in scp:
				#
				if i > 0 and first_ploted == False: # if the first line has not been ploted
					#
					pass
					#
				else:
					#
					if end_num+1 == next_num: # if the first line is in series
						#
						if i == 0:
							#
							first_ploted = True
							#
						#
						_p = mpatches.ConnectionPatch(x[1],coords[i+1][1],"data", lw=1, arrowstyle='->,head_width=.15,head_length=.15', shrinkB=5, color=_c,label='Label')
						tx.add_patch(_p)
						#
						#
						_midpoint = midpoint(x[1],coords[i+1][1])
						_degs = angle(x[1],coords[i+1][1])
						#
						label(_midpoint, _degs, tx)
						#
						coord_line.append(x)
						#
			#
		i = i + 1
		#
	#
	print("COORD LINE")
	#
	print(coord_line)
	#
	return coord_line
Example #20
0
def plot_linked_points(ax, points, color='green'):
    points = list(points)
    for a, b in zip(points[:-1], points[1:]):
        color = 'green' if 'ln_color' not in a else a['ln_color']
        ax.add_patch(
            patches.ConnectionPatch(a['xy'],
                                    b['xy'],
                                    'data',
                                    lw=1,
                                    color=color))
    return ax
Example #21
0
def set_layout(tree, ax=None, w=dims[0] / 2000, h=dims[0] / 2000):
    if ax is None: ax = plt.gca()
    ax = make_shape(ax, tree, w, h)
    if len(tree.children) != 0:
        for child in tree.children:
            ax.scatter([tree.x, child.x],
                       [-tree.y - w / 2.0, -child.y + w / 2.0],
                       color="white")
            s = mpatch.ConnectionPatch([tree.x, -tree.y - w / 2.0],
                                       [child.x, -child.y + w / 2.0], "data")
            ax.add_patch(s)
            set_layout(child, ax=ax)
    return set_limits(ax, get_xrange(tree, w), get_yrange(tree, h))
Example #22
0
def make_ct(to_ct, cen_c, ax):
	#
	perps = []
	#
	for coords in to_ct:
		#
		x = coords[0]
		y = coords[1]
		#
		_perp = getPerpCoord(cen_c[0], cen_c[1], x, y, 10000)
		#
		_perp_virtual = getPerpCoord(cen_c[0], cen_c[1], x, y, 50)
		#
		pp1 = mpatches.ConnectionPatch(cen_c,[x,y],"data", lw=0.5, color="g")
		ax.add_patch(pp1)
		#
		prp1 = mpatches.ConnectionPatch([_perp_virtual[0],_perp_virtual[1]],[_perp_virtual[2],_perp_virtual[3]],"data",arrowstyle='<->,head_width=.15,head_length=.15', lw=0.5, color="g")
		prp1.set_linestyle((0, (8,2)))
		ax.add_patch(prp1)
		#
		perps.append([[_perp[0],_perp[1]],[_perp[2],_perp[3]]])
	#
	return perps
Example #23
0
    def _draw_3D_lattice(self, a=2.0, pbc=True):
        all_links = []
        for z in range(self.L[2]):
            for y in range(self.L[1]):
                for x in range(self.L[0]):
                    links = self._get_drawing_links([x * a, y * a, z * a], a)
                    for l in links:
                        all_links.append([[x * a, l[0]], [y * a, l[1]],
                                          [z * a, l[2]]])
                        if (len(all_links) - 1) == 100:
                            self.ax.plot(*all_links[-1], color='red')
                        else:
                            # self.ax.plot(*all_links[-1],
                            #         color='black',
                            #         # color='#a3a2a2',
                            #         lw=1.5,
                            #         zorder=10-a*y
                            # )

                            xx, yy = zip(*all_links[-1])
                            xx = np.array(xx)
                            yy = np.array(yy)

                            ind = {'x': 0, 'y': 1, 'z': 2}
                            for c, d in [[[0, 1], 'z'], [[0, 2], 'y'],
                                         [[1, 2], 'x']]:
                                con = mpatches.ConnectionPatch(
                                    xyA=xx[c],
                                    coordsA=self.ax.transData,
                                    xyB=yy[c],
                                    color='#555555')
                                con.set_linewidth(2.5)
                                shadow = mpatches.Shadow(con,
                                                         1,
                                                         -1,
                                                         props=dict(
                                                             fc="black",
                                                             ec="0.7",
                                                             lw=1,
                                                             capstyle='round'))
                                self.ax.add_patch(con)
                                self.ax.add_patch(shadow)
                                art3d.pathpatch_2d_to_3d(shadow,
                                                         z=xx[ind[d]],
                                                         zdir=d)
                                art3d.pathpatch_2d_to_3d(con,
                                                         z=xx[ind[d]],
                                                         zdir=d)

        return all_links
Example #24
0
def draw_geodesic(a, b, c, ax, verbose=False):
    if verbose:
        print("Geodesic points are ", a, "\n", b, "\n", c, "\n")

    is_collinear = False
    if collinear(a, b, c):
        is_collinear = True
    else:
        cent = get_circle_center(a, b, c)
        radius = euclid_dist(a, cent)
        t1 = get_angles(cent, b)
        t2 = get_angles(cent, a)

        if verbose:
            print("\ncenter at ", cent)
            print("radius is ", radius)
            print("angles are ", t1, " ", t2)
            print("dist(a,center) = ", euclid_dist(cent, a))
            print("dist(b,center) = ", euclid_dist(cent, b))
            print("dist(c,center) = ", euclid_dist(cent, c))

    # if the angle is really tiny, a line is a good approximation
    if is_collinear or (np.abs(t1 - t2) < 2):
        coordsA = "data"
        coordsB = "data"
        e = patches.ConnectionPatch(a, b, coordsA, coordsB, linewidth=2)
    else:
        if verbose:
            print("angles are theta_1 = ", t1, " theta_2 = ", t2)
        if (t2 > t1 and t2 - t1 < 180) or (t1 > t2 and t1 - t2 >= 180):
            e = patches.Arc((cent[0], cent[1]),
                            2 * radius,
                            2 * radius,
                            theta1=t1,
                            theta2=t2,
                            linewidth=2,
                            fill=False,
                            zorder=2)
        else:
            e = patches.Arc((cent[0], cent[1]),
                            2 * radius,
                            2 * radius,
                            theta1=t2,
                            theta2=t1,
                            linewidth=2,
                            fill=False,
                            zorder=2)
    ax.add_patch(e)
    ax.plot(a[0], a[1], "o")
    ax.plot(b[0], b[1], "o")
Example #25
0
def animate(i):
    global clients, companies
    #clear figure at each iteration
    fig.clf()
    p = []
    for k in districts:
        #https://matplotlib.org/api/_as_gen/matplotlib.patches.Circle.html#matplotlib.patches.Circle package explanation
        #these are supposed to be the location (each district)
        p += [
            patches.Circle((districts[k][0], districts[k][1]),
                           radius=0.01,
                           transform=fig.transFigure,
                           figure=fig)
        ]

    for d in districts_connections:
        #https://matplotlib.org/api/_as_gen/matplotlib.patches.ConnectionPatch.html#matplotlib.patches.ConnectionPatch package explanation
        p += [
            patches.ConnectionPatch(xyA=districts[d[0]],
                                    xyB=districts[d[1]],
                                    coordsA='figure fraction',
                                    coordsB='figure fraction',
                                    arrowstyle="-",
                                    transform=fig.transFigure,
                                    figure=fig)
        ]

    #moving between Setubal and Evora ####### this is just a demo (a point moving) TODO: implement the movement of the trucks #######
    print(world_set.step(clients, companies))

    #https://matplotlib.org/api/_as_gen/matplotlib.patches.RegularPolygon.html#matplotlib.patches.RegularPolygon package explanation
    for c in companies:
        trucks = c.getTrucksOnTheMove()
        for t in trucks:
            #print("Truck ", t.getID(), " is at ", t.getCoordinates(), " with destination ", t.getDestination())
            p += [
                patches.RegularPolygon(t.getCoordinates(),
                                       4,
                                       radius=0.01,
                                       color='r',
                                       transform=fig.transFigure,
                                       figure=fig)
            ]

    #Add the objects updated to the figure
    fig.patches.extend(p)

    return fig
Example #26
0
def draw_pitch(axes):
    # focus on only half of the pitch
    # pitch Outline & Centre Line
    pitch = mp.Rectangle([0, 0], width=120, height=80, fill=False)
    # Left, Right Penalty Area and midline
    left_penalty = mp.Rectangle([0, 22.3], width=14.6, height=35.3, fill=False)
    right_penalty = mp.Rectangle([105.4, 22.3],
                                 width=14.6,
                                 height=35.3,
                                 fill=False)
    midline = mp.ConnectionPatch([60, 0], [60, 80], "data", "data")

    # Left, Right 6-yard Box
    left_six_yard = mp.Rectangle([0, 32], width=4.9, height=16, fill=False)
    right_six_yard = mp.Rectangle([115.1, 32],
                                  width=4.9,
                                  height=16,
                                  fill=False)

    # Prepare Circles
    centre_circle = plt.Circle((60, 40), 8.1, color="black", fill=False)
    centre_spot = plt.Circle((60, 40), 0.71, color="black")
    # Penalty spots and Arcs around penalty boxes
    left_pen_spot = plt.Circle((9.7, 40), 0.71, color="black")
    right_pen_spot = plt.Circle((110.3, 40), 0.71, color="black")
    left_arc = mp.Arc((9.7, 40),
                      height=16.2,
                      width=16.2,
                      angle=0,
                      theta1=310,
                      theta2=50,
                      color="black")
    right_arc = mp.Arc((110.3, 40),
                       height=16.2,
                       width=16.2,
                       angle=0,
                       theta1=130,
                       theta2=230,
                       color="black")

    element = [
        pitch, left_penalty, right_penalty, midline, left_six_yard,
        right_six_yard, centre_circle, centre_spot, right_pen_spot,
        left_pen_spot, left_arc, right_arc
    ]
    for j in element:
        axes.add_patch(j)
Example #27
0
def setup_bg(model):
    # Plot lines for calendar
    for i in range(1, 13):
        color = (0, 1, 0, i / 12)  #(r, g, b, a)
        linewidth = .5
        # 20th of each month is close to equinox/solstice
        time = ts.utc(year, i, 20)
        ex, ey, ez = model.earthPosition(time)
        line_obj = mpatches.ConnectionPatch((0, 0), (ex, ey),
                                            "data",
                                            color=color,
                                            linewidth=linewidth)
        ax.add_patch(line_obj)

    sun_obj = mpatches.Circle((0, 0), model.sun_rad, color='y')
    ax.add_patch(sun_obj)
    ax2.add_patch(mpatches.Circle((0, 0), 0.5, color='0.1'))
Example #28
0
def main(left, right):
    """
    Accepts two images -- left, right views of the same object.
    Detects FAST corners.
    Computes BRIEF descriptors.
    Plots matching features.
    """

    assert os.path.isabs(
        left), "Please provide the absolute path; it's a CV2 thing."
    assert os.path.isabs(
        right), "Please provide the absolute path; it's a CV2 thing."

    i1 = load_image(left)
    i2 = load_image(right)

    kps1, corners1 = get_fast_corners(i1)
    plt.figure(figsize=(10, 10))
    plt.imshow(corners1)
    plt.show()

    kps2, corners2 = get_fast_corners(i2)
    plt.figure(figsize=(10, 10))
    plt.imshow(corners2)
    plt.show()

    bdescr1 = get_brief_descriptors(i1, kps1, zip(p1, p2))
    bdescr2 = get_brief_descriptors(i2, kps2, zip(p1, p2))

    # Plot matching descriptors.
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10))

    ax1.imshow(corners1)
    ax2.imshow(corners2)

    for one, two in matcher(bdescr1, bdescr2, threshold=0.82):
        conpatch = patches.ConnectionPatch(xyA=two,
                                           xyB=one,
                                           coordsA="data",
                                           coordsB="data",
                                           color='green',
                                           axesA=ax2,
                                           axesB=ax1)
        ax2.add_artist(conpatch)
    plt.show()
Example #29
0
def box_connected_two_axes(small_ax, big_ax, box_corner, box_dims, color='blue') :
    # draw boxes
    for ax in [small_ax, big_ax] :
        ax.add_patch(patches.Rectangle(box_corner, box_dims[0], box_dims[1], fill=False, color=color))
    # link them up
    for i0 in range(2) :
        for j0 in range(2) :
            corner_coordinates = (box_corner[0] + box_dims[0] * i0, box_corner[1] + box_dims[1] * j0)
            a = big_ax.add_artist(patches.ConnectionPatch(
                xyA=corner_coordinates
                , xyB=corner_coordinates
                , coordsA="data"
                , coordsB="data"
                , axesA=big_ax
                , axesB=small_ax
                , color=color
                ))
            a.set_in_layout(
                False)  # otherwise matplotlib tries to stretch the plot to "fit" the lines in, and the imshow maps become tiny
Example #30
0
def draw_connect(axA, axB, q, r, qp, x):
    color = 'red' if qp ==0 else \
            'orange' if qp == 1 or qp == 4 else \
            'green'
    f = interp1d(list(r.keys()), list(r.values()))
    x1 = 0 if x != 0 else 1
    x2 = f(q[qp]) if x != 0 else 0
    print(q[qp], x2)

    axA.add_artist(
        patches.ConnectionPatch(xyA=(x1, q[qp]),
                                xyB=(x2, q[qp]),
                                coordsA="data",
                                coordsB="data",
                                axesA=axA,
                                axesB=axB,
                                color=color,
                                zorder=1000,
                                linestyle='--'))