Beispiel #1
0
 def draw(self, renderer):
     with warnings.catch_warnings():
         warnings.simplefilter("ignore")
         xs3d, ys3d, zs3d = self._verts3d
         xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
         self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
         FancyArrowPatch.draw(self, renderer)
Beispiel #2
0
 def draw(self, renderer):
     #xs3d, ys3d, zs3d = self._verts3d
     for coords in self._verts3d:
         xs3d, ys3d, zs3d = coords[0], coords[1], coords[2]
         xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
         self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
         FancyArrowPatch.draw(self, renderer)
Beispiel #3
0
    def _render_on_subplot(self, subplot):
        """
        Render this arrow in a subplot.  This is the key function that
        defines how this arrow graphics primitive is rendered in
        matplotlib's library.

        EXAMPLES::

        This function implicitly ends up rendering this arrow on a matplotlib subplot:
            sage: arrow(path=[[(0,1), (2,-1), (4,5)]])
        """
        options = self.options()
        width = float(options['width'])
        head = options.pop('head')
        if head == 0: style = '<|-'
        elif head == 1: style = '-|>'
        elif head == 2: style = '<|-|>'
        else: raise KeyError('head parameter must be one of 0 (start), 1 (end) or 2 (both).')
        arrowsize = float(options.get('arrowsize',5))
        head_width=arrowsize
        head_length=arrowsize*2.0
        color = to_mpl_color(options['rgbcolor'])
        from matplotlib.patches import FancyArrowPatch
        from matplotlib.path import Path
        bpath = Path(self.vertices, self.codes)
        p = FancyArrowPatch(path=bpath,
                            lw=width, arrowstyle='%s,head_width=%s,head_length=%s'%(style,head_width, head_length), 
                            fc=color, ec=color, linestyle=options['linestyle'])
        p.set_zorder(options['zorder'])
        p.set_label(options['legend_label'])
        subplot.add_patch(p)
        return p
Beispiel #4
0
    def __init__(self, ax, transSky2Pix, loc,
                 arrow_fraction=0.15,
                 txt1="E", txt2="N",
                 delta_a1=0, delta_a2=0,
                 pad=0.1, borderpad=0.5, prop=None, frameon=False,
                 ):
        """
        Draw an arrows pointing the directions of E & N

        arrow_fraction : length of the arrow as a fraction of axes size

        pad, borderpad in fraction of the legend font size (or prop)
        """

        self._ax = ax
        self._transSky2Pix = transSky2Pix
        self._box = AuxTransformBox(ax.transData)
        self.delta_a1, self.delta_a2 = delta_a1, delta_a2
        self.arrow_fraction = arrow_fraction

        kwargs = dict(mutation_scale=11,
                      shrinkA=0,
                      shrinkB=5)

        self.arrow1 = FancyArrowPatch(posA=(0, 0), posB=(1, 1),
                                      arrowstyle="->",
                                      arrow_transmuter=None,
                                      connectionstyle="arc3",
                                      connector=None,
                                      **kwargs)
        self.arrow2 = FancyArrowPatch(posA=(0, 0), posB=(1, 1),
                                      arrowstyle="->",
                                      arrow_transmuter=None,
                                      connectionstyle="arc3",
                                      connector=None,
                                      **kwargs)


        x1t, y1t, x2t, y2t = 1, 1, 1, 1
        self.txt1 = Text(x1t, y1t, txt1, rotation=0,
                         rotation_mode="anchor",
                         va="center", ha="right")
        self.txt2 = Text(x2t, y2t, txt2, rotation=0,
                         rotation_mode="anchor",
                         va="bottom", ha="center")


        self._box.add_artist(self.arrow1)
        self._box.add_artist(self.arrow2)

        self._box.add_artist(self.txt1)
        self._box.add_artist(self.txt2)

        AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
                                   child=self._box,
                                   prop=prop,
                                   frameon=frameon)
Beispiel #5
0
    def draw(self, renderer):
        """

        :param renderer:
        """
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
        FancyArrowPatch.draw(self, renderer)
Beispiel #6
0
    def _render_on_subplot(self, subplot):
        """
        Render this arrow in a subplot.  This is the key function that
        defines how this arrow graphics primitive is rendered in
        matplotlib's library.

        EXAMPLES:

        This function implicitly ends up rendering this arrow on 
        a matplotlib subplot::

            sage: arrow((0,1), (2,-1))

        TESTS:

        The length of the ends (shrinkA and shrinkB) should not depend
        on the width of the arrow, because Matplotlib already takes
        this into account. See :trac:`12836`::

            sage: fig = Graphics().matplotlib()
            sage: sp = fig.add_subplot(1,1,1)
            sage: a = arrow((0,0), (1,1))
            sage: b = arrow((0,0), (1,1), width=20)
            sage: p1 = a[0]._render_on_subplot(sp)
            sage: p2 = b[0]._render_on_subplot(sp)
            sage: p1.shrinkA == p2.shrinkA
            True
            sage: p1.shrinkB == p2.shrinkB
            True

        """
        options = self.options()
        head = options.pop('head')
        if head == 0: style = '<|-'
        elif head == 1: style = '-|>'
        elif head == 2: style = '<|-|>'
        else: raise KeyError('head parameter must be one of 0 (start), 1 (end) or 2 (both).')
        width = float(options['width'])
        arrowshorten_end = float(options.get('arrowshorten',0))/2.0
        arrowsize = float(options.get('arrowsize',5))
        head_width=arrowsize
        head_length=arrowsize*2.0
        color = to_mpl_color(options['rgbcolor'])
        from matplotlib.patches import FancyArrowPatch
        p = FancyArrowPatch((self.xtail, self.ytail), (self.xhead, self.yhead),
                            lw=width, arrowstyle='%s,head_width=%s,head_length=%s'%(style,head_width, head_length), 
                            shrinkA=arrowshorten_end, shrinkB=arrowshorten_end,
                            fc=color, ec=color, linestyle=options['linestyle'])
        p.set_zorder(options['zorder'])
        p.set_label(options['legend_label'])
        subplot.add_patch(p)
        return p
Beispiel #7
0
  def __init__(self,xs,ys,zs,*args,**kwargs):
    '''                               
    arguments:             

      xs: the x coordinates of both sides of the arrow        

      ys: the y coordinates of both sides of the arrow      

      zs: the z coordinates of both sides of the arrow       

    '''
    FancyArrowPatch.__init__(self,(0,0),(0,0),*args,**kwargs)
    self.verts = xs,ys,zs
Beispiel #8
0
 def draw(self, renderer):
     """
     Draw the axis line.
      1) transform the path to the display cooridnate.
      2) extend the path to make a room for arrow
      3) update the path of the FancyArrowPatch.
      4) draw
     """
     path_in_disp = self._line_transform.transform_path(self._line_path)
     mutation_size = self.get_mutation_scale() #line_mutation_scale()
     extented_path = self._extend_path(path_in_disp,
                                       mutation_size=mutation_size)
     self._path_original = extented_path
     FancyArrowPatch.draw(self, renderer)
Beispiel #9
0
    def draw(self, renderer, rasterized=True):
        """
        Drawing actually happens here
        """
        # Draws only when the dragging finished
        if self.leftdown:
            return
        xs3d, ys3d, zs3d = self._verts3d
        for i in xrange(len(xs3d)):
            xs, ys, _ = proj3d.proj_transform(xs3d[i], ys3d[i], zs3d[i], renderer.M)
            self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
            self.set_color(self.colors[i])
            FancyArrowPatch.draw(self, renderer)

        self.leftdown = False
Beispiel #10
0
 def __init__(self, axis_artist, line_path, transform,
              line_mutation_scale):
     self._axis_artist = axis_artist
     self._line_transform = transform
     self._line_path = line_path
     self._line_mutation_scale = line_mutation_scale
     FancyArrowPatch.__init__(self,
                              path=self._line_path, 
                              arrowstyle="->",
                              arrow_transmuter=None,
                              patchA=None,
                              patchB=None,
                              shrinkA=0.,
                              shrinkB=0.,
                              mutation_scale=line_mutation_scale,
                              mutation_aspect=None,
                              transform=IdentityTransform(),
                              )
Beispiel #11
0
    def create_photon_legend(self, legend, orig_handle, 
                       xdescent, ydescent, width, height, fontsize,
                       trans):
        
            xdata, ydata = get_photon_data2D(width, 0.8*height, 3, 100)
            ydata += height*0.3
            legline = Line2D(xdata, ydata)

            self.update_prop(legline, orig_handle, legend)
            legline.set_drawstyle('default')
            legline.set_marker("")
            
            legline.set_transform(trans)
            
            yar = FancyArrowPatch((xdata[3],ydata[0]), (xdata[3]+0.3*width, ydata[0]), 
                                  mutation_scale=10,
                                  lw=1, arrowstyle="-|>", color='y')
            yar.set_transform(trans)
            return [legline, yar]
Beispiel #12
0
    def __init__(self, base, xs, ys, zs, colors, *args, **kwargs):
        """
        Init

        :Params xs: [[x0, x0+dx0], [x1, x1+dx1], ...]
        :Params ys: [[y0, y0+dy0], [y1, y1+dy1], ...]
        :Params zs: [[z0, z0+dz0], [z1, z1+dz1], ...]
        :Params colors: [[R0, G0, B0], [R1, G1, B1], ...]
        where R, G, B ranges (0,1)
        """
        FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
        self.leftdown = False
        self.t_click = 0
        self._verts3d = xs, ys, zs
        self.colors = colors
        self.base = base

        if base != None:
            # To turn the updating off during dragging
            base.canvas.mpl_connect('button_press_event', self.on_left_down)
            base.canvas.mpl_connect('button_release_event', self.on_left_up)
Beispiel #13
0
 def __init__(self, offsetbox, xy,
              xybox=None,
              xycoords='data',
              boxcoords=None,
              frameon=True, pad=0.4, # BboxPatch
              annotation_clip=None,
              box_alignment=(0.5, 0.5),
              bboxprops=None,
              arrowprops=None,
              fontsize=None,
              **kwargs):
     """
     *offsetbox* : OffsetBox instance
     *xycoords* : same as Annotation but can be a tuple of two
        strings which are interpreted as x and y coordinates.
     *boxcoords* : similar to textcoords as Annotation but can be a
        tuple of two strings which are interpreted as x and y
        coordinates.
     *box_alignment* : a tuple of two floats for a vertical and
        horizontal alignment of the offset box w.r.t. the *boxcoords*.
        The lower-left corner is (0.0) and upper-right corner is (1.1).
     other parameters are identical to that of Annotation.
     """
     self.offsetbox = offsetbox
     self.arrowprops = arrowprops
     self.set_fontsize(fontsize)
     if arrowprops is not None:
         self._arrow_relpos = self.arrowprops.pop("relpos", (0.5, 0.5))
         self.arrow_patch = FancyArrowPatch((0, 0), (1,1),
                                            **self.arrowprops)
     else:
         self._arrow_relpos = None
         self.arrow_patch = None
     _AnnotationBase.__init__(self,
                              xy, xytext=xybox,
                              xycoords=xycoords, textcoords=boxcoords,
                              annotation_clip=annotation_clip)
     martist.Artist.__init__(self, **kwargs)
     self._box_alignment = box_alignment
     self.patch = FancyBboxPatch(
         xy=(0.0, 0.0), width=1., height=1.,
         facecolor='w', edgecolor='k',
         mutation_scale=self.prop.get_size_in_points(),
         snap=True
         )
     self.patch.set_boxstyle("square",pad=pad)
     if bboxprops:
         self.patch.set(**bboxprops)
     self._drawFrame =  frameon
 def __init__(self, vl, room_shape, start_iter):
     super(EnvironmentReader,self).__init__(win_size=[700,700],
                                            win_loc=pos,
                                            title='Environment')
     self.vl = vl
     self.cur_iter = start_iter
     
     self.cur_i = 0
     self.max_iter = np.max(vl['Iter num'])
     self.maxx = room_shape[0][1]
     self.maxy = room_shape[1][1]
     self.cntr_x = np.mean(room_shape[0])
     self.cntr_y = np.mean(room_shape[1])
     
     self.x_hist = []; self.y_hist = []
     
     self.canvas.mpl_connect('resize_event',lambda x: self.update_background())
     
     self.pos, = self.ax.plot([],[],color='g',animated=True)
     self.vel = Arrow([0,0],[1,0],arrowstyle='-|>, head_length=3, head_width=3',
                      animated=True, linewidth=4)
     self.ax.add_patch(self.vel)
     #self.radius, = self.ax.plot([],[],color='r',animated=True)
     self.clockcounter = self.ax.text(self.maxx,room_shape[1][0],
                                      '',ha='right',size='large',
                                      animated=True)
     self.iters = self.ax.text(self.maxx-1, room_shape[1][0]+3,
                               '',ha='right',animated=True)
     self.target = Circle([0,0],0,animated=True,color='r')
     self.target.set_radius(11)
     self.ax.add_artist(self.target)
     
     self.ax.set_xlim(room_shape[0])
     self.ax.set_ylim(room_shape[1])
     
     self.draw_plc_flds()
     
     self.draw_HMM_sectors()
     self.predicted_counter = self.ax.text(self.maxx,room_shape[1][0]+10,'',
                                           ha='right',size='large',animated=True)
     self.prediction_hist = None
     #self.cur_sec = Rectangle([0,0],self.HMM.dx,self.HMM.dy,fill=True,
     #                         color='k',animated=True)
     #self.ax_env.add_patch(self.cur_sec)
     
     self.canvas.draw()
Beispiel #15
0
    def _render_on_subplot(self, subplot):
        """
        Render this arrow in a subplot.  This is the key function that
        defines how this arrow graphics primitive is rendered in
        matplotlib's library.

        EXAMPLES::

        This function implicitly ends up rendering this arrow on a matplotlib subplot:
            sage: arrow(path=[[(0,1), (2,-1), (4,5)]])
            Graphics object consisting of 1 graphics primitive
        """
        from sage.plot.misc import get_matplotlib_linestyle

        options = self.options()
        width = float(options["width"])
        head = options.pop("head")
        if head == 0:
            style = "<|-"
        elif head == 1:
            style = "-|>"
        elif head == 2:
            style = "<|-|>"
        else:
            raise KeyError("head parameter must be one of 0 (start), 1 (end) or 2 (both).")
        arrowsize = float(options.get("arrowsize", 5))
        head_width = arrowsize
        head_length = arrowsize * 2.0
        color = to_mpl_color(options["rgbcolor"])
        from matplotlib.patches import FancyArrowPatch
        from matplotlib.path import Path

        bpath = Path(self.vertices, self.codes)
        p = FancyArrowPatch(
            path=bpath,
            lw=width,
            arrowstyle="%s,head_width=%s,head_length=%s" % (style, head_width, head_length),
            fc=color,
            ec=color,
        )
        p.set_linestyle(get_matplotlib_linestyle(options["linestyle"], return_type="long"))
        p.set_zorder(options["zorder"])
        p.set_label(options["legend_label"])
        subplot.add_patch(p)
        return p
Beispiel #16
0
fig.gca().text(2.5, 1.6, 'Liquid Line', ha='center', va='center')

#Vapor return Line
fig.gca().plot([0.15, 0.85], [-1.5, -1.5], 'k', lw=6)
fig.gca().text(0.5, -1.4, 'Vapor Line', ha='center', va='center')

#################################################
##### Connect the components with lines #########
#################################################

# Condenser to Expansion Device
fig.gca().plot(np.r_[3, 3], np.r_[1.0, 1.5], 'k')
fig.gca().add_patch(
    FancyArrowPatch((3, 1.5), (1.625, 1.5),
                    arrowstyle='-|>',
                    mutation_scale=20,
                    fc='k',
                    ec='k',
                    lw=0.5))

# XV to Evaporator
fig.gca().plot(np.r_[1.375, 0], np.r_[1.5, 1.5], 'k')
fig.gca().add_patch(
    FancyArrowPatch((0, 1.5), (0, 1),
                    arrowstyle='-|>',
                    mutation_scale=20,
                    fc='k',
                    ec='k',
                    lw=0.5))

# Condenser to XV
fig.gca().plot(np.r_[0, 0], np.r_[-1, -1.5], 'k')
Beispiel #17
0
 def __init__(self, start, end, shrinkA=0.0, shrinkB=0.0, mutation_scale=20, arrowstyle="-|>", color='k', lw=1, *args, **kwargs):
     FancyArrowPatch.__init__(self, (0,0), (0,0), *args, shrinkA=shrinkA, shrinkB=shrinkB, mutation_scale=mutation_scale, arrowstyle=arrowstyle, color=color, lw=lw, **kwargs)
     self._verts3d = zip(start,end)
Beispiel #18
0
    def _render_on_subplot(self, subplot):
        r"""
        Render this arrow in a subplot.  This is the key function that
        defines how this arrow graphics primitive is rendered in
        matplotlib's library.

        EXAMPLES:

        This function implicitly ends up rendering this arrow on
        a matplotlib subplot::

            sage: arrow((0,1), (2,-1))
            Graphics object consisting of 1 graphics primitive

        TESTS:

        The length of the ends (shrinkA and shrinkB) should not depend
        on the width of the arrow, because Matplotlib already takes
        this into account. See :trac:`12836`::

            sage: fig = Graphics().matplotlib()
            sage: sp = fig.add_subplot(1,1,1, label='axis1')
            sage: a = arrow((0,0), (1,1))
            sage: b = arrow((0,0), (1,1), width=20)
            sage: p1 = a[0]._render_on_subplot(sp)
            sage: p2 = b[0]._render_on_subplot(sp)
            sage: p1.shrinkA == p2.shrinkA
            True
            sage: p1.shrinkB == p2.shrinkB
            True

        Dashed arrows should have solid arrowheads,
        :trac:`12852`. This test saves the plot of a dashed arrow to
        an EPS file. Within the EPS file, ``stroke`` will be called
        twice: once to draw the line, and again to draw the
        arrowhead. We check that both calls do not occur while the
        dashed line style is enabled::

            sage: a = arrow((0,0), (1,1), linestyle='dashed')
            sage: filename = tmp_filename(ext='.eps')
            sage: a.save(filename=filename)
            sage: with open(filename, 'r') as f:
            ....:     contents = f.read().replace('\n', ' ')
            sage: two_stroke_pattern = r'setdash.*stroke.*stroke.*setdash.*setdash'
            sage: import re
            sage: two_stroke_re = re.compile(two_stroke_pattern)
            sage: two_stroke_re.search(contents) is None
            True
        """
        from sage.plot.misc import get_matplotlib_linestyle

        options = self.options()
        head = options.pop('head')
        if head == 0: style = '<|-'
        elif head == 1: style = '-|>'
        elif head == 2: style = '<|-|>'
        else:
            raise KeyError(
                'head parameter must be one of 0 (start), 1 (end) or 2 (both).'
            )
        width = float(options['width'])
        arrowshorten_end = float(options.get('arrowshorten', 0)) / 2.0
        arrowsize = float(options.get('arrowsize', 5))
        head_width = arrowsize
        head_length = arrowsize * 2.0
        color = to_mpl_color(options['rgbcolor'])
        from matplotlib.patches import FancyArrowPatch
        p = FancyArrowPatch(
            (self.xtail, self.ytail), (self.xhead, self.yhead),
            lw=width,
            arrowstyle='%s,head_width=%s,head_length=%s' %
            (style, head_width, head_length),
            shrinkA=arrowshorten_end,
            shrinkB=arrowshorten_end,
            fc=color,
            ec=color,
            linestyle=get_matplotlib_linestyle(options['linestyle'],
                                               return_type='long'))
        p.set_zorder(options['zorder'])
        p.set_label(options['legend_label'])

        if options['linestyle'] != 'solid':
            # The next few lines work around a design issue in matplotlib.
            # Currently, the specified linestyle is used to draw both the path
            # and the arrowhead.  If linestyle is 'dashed', this looks really
            # odd. This code is from Jae-Joon Lee in response to a post to the
            # matplotlib mailing list.
            # See http://sourceforge.net/mailarchive/forum.php?thread_name=CAG%3DuJ%2Bnw2dE05P9TOXTz_zp-mGP3cY801vMH7yt6vgP9_WzU8w%40mail.gmail.com&forum_name=matplotlib-users

            import matplotlib.patheffects as pe

            class CheckNthSubPath(object):
                def __init__(self, patch, n):
                    """
                    creates an callable object that returns True if the
                    provided path is the n-th path from the patch.
                    """
                    self._patch = patch
                    self._n = n

                def get_paths(self, renderer):
                    self._patch.set_dpi_cor(renderer.points_to_pixels(1.))
                    paths, fillables = self._patch.get_path_in_displaycoord()
                    return paths

                def __call__(self, renderer, gc, tpath, affine, rgbFace):
                    path = self.get_paths(renderer)[self._n]
                    vert1, code1 = path.vertices, path.codes
                    import numpy as np

                    return np.array_equal(vert1,
                                          tpath.vertices) and np.array_equal(
                                              code1, tpath.codes)

            class ConditionalStroke(pe.RendererBase):
                def __init__(self, condition_func, pe_list):
                    """
                    path effect that is only applied when the condition_func
                    returns True.
                    """
                    super(ConditionalStroke, self).__init__()
                    self._pe_list = pe_list
                    self._condition_func = condition_func

                def draw_path(self, renderer, gc, tpath, affine, rgbFace):

                    if self._condition_func(renderer, gc, tpath, affine,
                                            rgbFace):
                        for pe1 in self._pe_list:
                            pe1.draw_path(renderer, gc, tpath, affine, rgbFace)

            pe1 = ConditionalStroke(CheckNthSubPath(p, 0), [pe.Stroke()])
            pe2 = ConditionalStroke(
                CheckNthSubPath(p, 1),
                [pe.Stroke(dashes={
                    'dash_offset': 0,
                    'dash_list': None
                })])
            p.set_path_effects([pe1, pe2])

        subplot.add_patch(p)
        return p
Beispiel #19
0
    def asteroids_plot(self,
                       image_path=None,
                       ra=None,
                       dec=None,
                       odate=None,
                       time_travel=1,
                       radi=6,
                       max_mag=20.0,
                       circle_color='yellow',
                       arrow_color='red'):

        """
        Source plot module.
        @param image_path: data part of the FITS image
        @type image_path: numpy array
        @param ra: RA coordinate of target area.
        @type ra: str in "HH MM SS"
        @param dec: DEC coordinate of target area
        @type dec: str in "+DD MM SS"
        @param radi: Radius in arcmin.
        @type radi: float
        @param odate: Ephemeris date of observation in date
        @type odate: "2017-08-15T19:50:00.95" format in str
        @param time_travel: Jump into time after given date (in hour).
        @type time_travel: float
        @param max_mag: Limit magnitude to be queried object(s)
        @type max_mag: float
        @param circle_color: Color of the asteroids marks
        @type circle_color: str
        @param arrow_color: Color of the asteroids direction marks
        @type arrow_color: str
        @returns: boolean
        """

        from .catalog import Query

        # filename = get_pkg_data_filename(image_path)
        rcParams['figure.figsize'] = [15., 12.]
        # rcParams.update({'font.size': 10})

        if image_path:
            hdu = fits.open(image_path)[0]
        elif not image_path and ra and dec and odate:
            co = coordinates.SkyCoord('{0} {1}'.format(ra, dec),
                                      unit=(u.hourangle, u.deg),
                                      frame='icrs')
            print('Target Coordinates:',
                  co.to_string(style='hmsdms', sep=':'),
                  'in {0} arcmin'.format(radi))
            try:
                server_img = SkyView.get_images(position=co,
                                                survey=['DSS'],
                                                radius=radi * u.arcmin)
                hdu = server_img[0][0]
            except Exception as e:
                print("SkyView could not get the image from DSS server.")
                print(e)
                raise SystemExit

        wcs = WCS(hdu.header)

        data = hdu.data.astype(float)

        bkg = sep.Background(data)
        # bkg_image = bkg.back()
        # bkg_rms = bkg.rms()
        data_sub = data - bkg
        m, s = np.mean(data_sub), np.std(data_sub)

        ax = plt.subplot(projection=wcs)

        plt.imshow(data_sub, interpolation='nearest',
                   cmap='gray', vmin=m - s, vmax=m + s, origin='lower')
        ax.coords.grid(True, color='white', ls='solid')
        ax.coords[0].set_axislabel('Galactic Longitude')
        ax.coords[1].set_axislabel('Galactic Latitude')

        overlay = ax.get_coords_overlay('icrs')
        overlay.grid(color='white', ls='dotted')
        overlay[0].set_axislabel('Right Ascension (ICRS)')
        overlay[1].set_axislabel('Declination (ICRS)')

        sb = Query()
        ac = AstCalc()
        if image_path:
            fo = FitsOps(image_path)
            if not odate:
                odate = fo.get_header('date-obs')
            else:
                odate = odate
            ra_dec = ac.center_finder(image_path, wcs_ref=True)
        elif not image_path and ra and dec and odate:
            odate = odate
            ra_dec = [co.ra, co.dec]

        request0 = sb.find_skybot_objects(odate,
                                          ra_dec[0].degree,
                                          ra_dec[1].degree,
                                          radius=radi)

        if request0[0]:
            asteroids = request0[1]
        elif request0[0] is False:
            print(request0[1])
            raise SystemExit

        request1 = sb.find_skybot_objects(odate,
                                          ra_dec[0].degree,
                                          ra_dec[1].degree,
                                          radius=float(radi),
                                          time_travel=time_travel)

        if request1[0]:
            asteroids_after = request1[1]
        elif request1[0] is False:
            print(request1[1])
            raise SystemExit

        for i in range(len(asteroids)):
            if float(asteroids['m_v'][i]) <= max_mag:
                c = coordinates.SkyCoord('{0} {1}'.format(
                    asteroids['ra(h)'][i],
                    asteroids['dec(deg)'][i]),
                    unit=(u.hourangle, u.deg),
                    frame='icrs')

                c_after = coordinates.SkyCoord('{0} {1}'.format(
                    asteroids_after['ra(h)'][i],
                    asteroids_after['dec(deg)'][i]),
                    unit=(u.hourangle, u.deg),
                    frame='icrs')

                r = FancyArrowPatch(
                    (c.ra.degree, c.dec.degree),
                    (c_after.ra.degree, c_after.dec.degree),
                    arrowstyle='->',
                    mutation_scale=10,
                    transform=ax.get_transform('icrs'))

                p = Circle((c.ra.degree, c.dec.degree), 0.005,
                           edgecolor=circle_color,
                           facecolor='none',
                           transform=ax.get_transform('icrs'))
                ax.text(c.ra.degree,
                        c.dec.degree - 0.007,
                        asteroids['name'][i],
                        size=12,
                        color='black',
                        ha='center',
                        va='center',
                        transform=ax.get_transform('icrs'))

                r.set_facecolor('none')
                r.set_edgecolor(arrow_color)
                ax.add_patch(p)
                ax.add_patch(r)
        # plt.gca().invert_xaxis()
        plt.gca().invert_yaxis()
        plt.show()
        print(asteroids)
        return True
Beispiel #20
0
 def __init__(self, posA, posB, *args, **kwargs):
     FancyArrowPatch.__init__(self, posA, posB, *args, **kwargs)
Beispiel #21
0
 def draw(self, renderer):
     xs3d, ys3d, zs3d = self._verts3d
     x_s, y_s, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
     self.set_positions((x_s[0], y_s[0]), (x_s[1], y_s[1]))
     FancyArrowPatch.draw(self, renderer)
Beispiel #22
0
 def __init__(self, xs, ys, zs, *args, **kwargs):
     """Create arrow."""
     FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
     self._verts3d = xs, ys, zs
Beispiel #23
0
def _as_dendrogram_line(start, end, color):
    return FancyArrowPatch(start, end, arrowstyle='-', color=color, lw=2, shrinkA=0, shrinkB=0)
Beispiel #24
0
def draw_network(env_graph, pos, ax, sg=None, periodicity_vectors=None):
    """

    Args:
        env_graph ():
        pos ():
        ax ():
        sg ():
        periodicity_vectors ():

    Returns:

    """
    for n in env_graph:
        c = Circle(pos[n], radius=0.02, alpha=0.5)
        ax.add_patch(c)
        env_graph.node[n]["patch"] = c
        x, y = pos[n]
        ax.annotate(str(n), pos[n], ha="center", va="center", xycoords="data")
    seen = {}
    e = None
    for (u, v, d) in env_graph.edges(data=True):
        n1 = env_graph.node[u]["patch"]
        n2 = env_graph.node[v]["patch"]
        rad = 0.1
        if (u, v) in seen:
            rad = seen.get((u, v))
            rad = (rad + np.sign(rad) * 0.1) * -1
        alpha = 0.5
        color = "k"
        periodic_color = "r"

        delta = get_delta(u, v, d)

        # center = get_center_of_arc(n1.center, n2.center, rad)
        n1center = np.array(n1.center)
        n2center = np.array(n2.center)
        midpoint = (n1center + n2center) / 2
        dist = np.sqrt(
            np.power(n2.center[0] - n1.center[0], 2) +
            np.power(n2.center[1] - n1.center[1], 2))
        n1c_to_n2c = n2center - n1center
        vv = np.cross(
            np.array([n1c_to_n2c[0], n1c_to_n2c[1], 0], np.float),
            np.array([0, 0, 1], np.float),
        )
        vv /= np.linalg.norm(vv)
        midarc = midpoint + rad * dist * np.array([vv[0], vv[1]], np.float)
        xytext_offset = 0.1 * dist * np.array([vv[0], vv[1]], np.float)

        if periodicity_vectors is not None and len(periodicity_vectors) == 1:
            if np.all(np.array(delta) == np.array(
                    periodicity_vectors[0])) or np.all(
                        np.array(delta) == -np.array(periodicity_vectors[0])):
                e = FancyArrowPatch(
                    n1center,
                    n2center,
                    patchA=n1,
                    patchB=n2,
                    arrowstyle="-|>",
                    connectionstyle="arc3,rad=%s" % rad,
                    mutation_scale=15.0,
                    lw=2,
                    alpha=alpha,
                    color="r",
                    linestyle="dashed",
                )
            else:
                e = FancyArrowPatch(
                    n1center,
                    n2center,
                    patchA=n1,
                    patchB=n2,
                    arrowstyle="-|>",
                    connectionstyle="arc3,rad=%s" % rad,
                    mutation_scale=10.0,
                    lw=2,
                    alpha=alpha,
                    color=color,
                )
        else:
            ecolor = (color if np.allclose(np.array(delta), np.zeros(3)) else
                      periodic_color)
            e = FancyArrowPatch(
                n1center,
                n2center,
                patchA=n1,
                patchB=n2,
                arrowstyle="-|>",
                connectionstyle="arc3,rad=%s" % rad,
                mutation_scale=10.0,
                lw=2,
                alpha=alpha,
                color=ecolor,
            )
        ax.annotate(
            delta,
            midarc,
            ha="center",
            va="center",
            xycoords="data",
            xytext=xytext_offset,
            textcoords="offset points",
        )
        seen[(u, v)] = rad
        ax.add_patch(e)

    return e
Beispiel #25
0
x2 = -wE / 2.0 + rE + rE * np.cos(t)
y2 = hE / 2.0 - rE + rE * np.sin(t) + y0E
t = np.linspace(np.pi, 3.0 * np.pi / 2.0, 100)
x3 = -wE / 2.0 + rE + rE * np.cos(t)
y3 = -hE / 2.0 + rE + rE * np.sin(t) + y0E
t = np.linspace(3.0 * np.pi / 2.0, 2 * np.pi, 100)
x4 = wE / 2.0 - rE + rE * np.cos(t)
y4 = -hE / 2.0 + rE + rE * np.sin(t) + y0E
pylab.plot(np.r_[x1, x2, x3, x4, x1[0]], np.r_[y1, y2, y3, y4, y1[0]], 'k')

#Length labels
pylab.gca().add_patch(
    FancyArrowPatch((wE / 2.0 + 0.08, -w / 2.0 * sin(phi)),
                    (wE / 2.0 + 0.08, 1),
                    arrowstyle='<|-|>',
                    fc='k',
                    ec='k',
                    mutation_scale=20,
                    lw=0.8))
pylab.text(wE / 2.0 + 0.1, y0E, '$L$', ha='left', va='center', size=20)
pylab.gca().add_patch(
    FancyArrowPatch((-w / 2.0, y0E + hE / 2.0 + 0.06),
                    (w / 2.0, y0E + hE / 2.0 + 0.06),
                    arrowstyle='<|-|>',
                    fc='k',
                    ec='k',
                    mutation_scale=20,
                    lw=0.8))
pylab.text(0, y0E + hE / 2.0 + 0.08, '$B$', ha='center', va='bottom', size=20)

pylab.gca().add_patch(
Beispiel #26
0
def draw_network(env_graph, pos, ax, sg=None, periodicity_vectors=None):
    """Draw network of environments in a matplotlib figure axes.

    Args:
        env_graph: Graph of environments.
        pos: Positions of the nodes of the environments in the 2D figure.
        ax: Axes object in which the network should be drawn.
        sg: Not used currently (drawing of supergraphs).
        periodicity_vectors: List of periodicity vectors that should be drawn.

    Returns: None

    """
    for n in env_graph:
        c = Circle(pos[n], radius=0.02, alpha=0.5)
        ax.add_patch(c)
        env_graph.node[n]["patch"] = c
        x, y = pos[n]
        ax.annotate(str(n), pos[n], ha="center", va="center", xycoords="data")
    seen = {}
    e = None
    for (u, v, d) in env_graph.edges(data=True):
        n1 = env_graph.node[u]["patch"]
        n2 = env_graph.node[v]["patch"]
        rad = 0.1
        if (u, v) in seen:
            rad = seen.get((u, v))
            rad = (rad + np.sign(rad) * 0.1) * -1
        alpha = 0.5
        color = "k"
        periodic_color = "r"

        delta = get_delta(u, v, d)

        # center = get_center_of_arc(n1.center, n2.center, rad)
        n1center = np.array(n1.center)
        n2center = np.array(n2.center)
        midpoint = (n1center + n2center) / 2
        dist = np.sqrt(np.power(n2.center[0] - n1.center[0], 2) + np.power(n2.center[1] - n1.center[1], 2))
        n1c_to_n2c = n2center - n1center
        vv = np.cross(
            np.array([n1c_to_n2c[0], n1c_to_n2c[1], 0], np.float_),
            np.array([0, 0, 1], np.float_),
        )
        vv /= np.linalg.norm(vv)
        midarc = midpoint + rad * dist * np.array([vv[0], vv[1]], np.float_)
        xytext_offset = 0.1 * dist * np.array([vv[0], vv[1]], np.float_)

        if periodicity_vectors is not None and len(periodicity_vectors) == 1:
            if np.all(np.array(delta) == np.array(periodicity_vectors[0])) or np.all(
                np.array(delta) == -np.array(periodicity_vectors[0])
            ):
                e = FancyArrowPatch(
                    n1center,
                    n2center,
                    patchA=n1,
                    patchB=n2,
                    arrowstyle="-|>",
                    connectionstyle="arc3,rad=%s" % rad,
                    mutation_scale=15.0,
                    lw=2,
                    alpha=alpha,
                    color="r",
                    linestyle="dashed",
                )
            else:
                e = FancyArrowPatch(
                    n1center,
                    n2center,
                    patchA=n1,
                    patchB=n2,
                    arrowstyle="-|>",
                    connectionstyle="arc3,rad=%s" % rad,
                    mutation_scale=10.0,
                    lw=2,
                    alpha=alpha,
                    color=color,
                )
        else:
            ecolor = color if np.allclose(np.array(delta), np.zeros(3)) else periodic_color
            e = FancyArrowPatch(
                n1center,
                n2center,
                patchA=n1,
                patchB=n2,
                arrowstyle="-|>",
                connectionstyle="arc3,rad=%s" % rad,
                mutation_scale=10.0,
                lw=2,
                alpha=alpha,
                color=ecolor,
            )
        ax.annotate(
            delta,
            midarc,
            ha="center",
            va="center",
            xycoords="data",
            xytext=xytext_offset,
            textcoords="offset points",
        )
        seen[(u, v)] = rad
        ax.add_patch(e)
Beispiel #27
0
import matplotlib,pylab, numpy as np
from matplotlib.patches import FancyArrowPatch

wC=0.1
hC=1.0
h=1
Nc=6

fig=pylab.figure(figsize=(6.5,6))
ax=fig.add_axes((0,0,1,1))
for i in range(Nc):
    #The cold channel
    x0=wC*(2*i)
    y0=hC/2
    x=[x0+wC/2,x0+wC/2,x0-wC/2,x0-wC/2,x0+wC/2]
    y=[y0-hC/2,y0+hC/2,y0+hC/2,y0-hC/2,y0-hC/2]
    pylab.fill(x,y,'c')
    pylab.gca().add_patch(FancyArrowPatch((x0,y0-0.3*hC),(x0,y0+0.3*hC),arrowstyle='-|>',fc='k',ec='k',mutation_scale=20,lw=0.8))
    
    #The cold channel
    x0=wC*(2*i+1)
    y0=hC/2
    x=[x0+wC/2,x0+wC/2,x0-wC/2,x0-wC/2,x0+wC/2]
    y=[y0-hC/2,y0+hC/2,y0+hC/2,y0-hC/2,y0-hC/2]
    pylab.fill(x,y,'r')
    pylab.gca().add_patch(FancyArrowPatch((x0,y0+0.3*hC),(x0,y0-0.3*hC),arrowstyle='-|>',fc='k',ec='k',mutation_scale=20,lw=0.8))
    
ax.axis('equal')    
ax.axis('off')

pylab.show()
Beispiel #28
0
	def __init__(self, angleX, angleY, angleZ, *args, **kwargs):
		FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
		self.set_verts3d(angleX, angleY, angleZ)
Beispiel #29
0
 def draw(self, renderer):
     xs3d, ys3d, zs3d = self._verts3d
     xs, ys, zs = proj3d.proj_transform(xs3d, yd3d, zs3d, renderer.M)
     FancyArrowPatch.draw(self, renderer)
Beispiel #30
0
    def init_artists(self):
        main_arrow_props = {
            "alpha": 0.5 if self.active else 0.2,
            "animated": True,
            "arrowstyle": "->,head_length=10,head_width=7",
            "color": self.color,
            "linestyle": "solid",
        }

        opp_arrow_props = {
            "alpha": 0.3 if self.active else 0.1,
            "animated": True,
            "arrowstyle": "->,head_length=10,head_width=7",
            "color": self.color,
            "linestyle": "dashed",
        }

        right_props = {
            "alpha": 0.2 if self.active else 0.1,
            "animated": True,
            "color": self.color,
            "linestyle": "dashed",
            "linewidth": 1,
        }

        line_props = {
            "alpha": 0.7 if self.active else 0.3,
            "animated": True,
            "color": self.color,
            "linestyle": "",
            "marker": "x",
            "markerfacecolor": self.color,
            "markersize": 8,
            "markevery": [1],
        }

        cx, cy = self.cxy
        wx, wy = self.wxy
        dx, dy = wx - cx, wy - cy
        rx, ry = self._calc_right_delta()

        # main arrow
        main_arrow = FancyArrowPatch(posA=self.cxy, posB=self.wxy, **main_arrow_props)
        self.artists["main_arrow"] = main_arrow
        self.axes.add_patch(main_arrow)

        # opposite arrow
        opp_arrow = FancyArrowPatch(
            posA=self.cxy, posB=(cx - dx, cy - dy), **opp_arrow_props
        )
        self.artists["opp_arrow"] = opp_arrow
        self.axes.add_patch(opp_arrow)

        # cross line
        (right,) = self.axes.plot(
            [cx - rx, cx, cx + rx], [cy - ry, cy, cy + ry], **right_props
        )
        self.artists["right"] = right
        self.axes.add_line(right)

        # line
        (line,) = self.axes.plot(
            [cx - dx, cx, cx + dx], [cy - dy, cy, cy + dy], **line_props
        )
        self.artists["line"] = line
        self.axes.add_line(line)
Beispiel #31
0
def draw_networkx_edges(G,
                        pos,
                        edgelist=None,
                        width=1.0,
                        edge_color='k',
                        style='solid',
                        alpha=1.0,
                        arrowstyle='-|>',
                        arrowsize=10,
                        edge_cmap=None,
                        edge_vmin=None,
                        edge_vmax=None,
                        ax=None,
                        arrows=True,
                        label=None,
                        node_size=300,
                        nodelist=None,
                        node_shape="o",
                        **kwds):
    """Draw the edges of the graph G.

    This draws only the edges of the graph G.

    Parameters
    ----------
    G : graph
       A networkx graph

    pos : dictionary
       A dictionary with nodes as keys and positions as values.
       Positions should be sequences of length 2.

    edgelist : collection of edge tuples
       Draw only specified edges(default=G.edges())

    width : float, or array of floats
       Line width of edges (default=1.0)

    edge_color : color string, or array of floats
       Edge color. Can be a single color format string (default='r'),
       or a sequence of colors with the same length as edgelist.
       If numeric values are specified they will be mapped to
       colors using the edge_cmap and edge_vmin,edge_vmax parameters.

    style : string
       Edge line style (default='solid') (solid|dashed|dotted,dashdot)

    alpha : float
       The edge transparency (default=1.0)

    edge_ cmap : Matplotlib colormap
       Colormap for mapping intensities of edges (default=None)

    edge_vmin,edge_vmax : floats
       Minimum and maximum for edge colormap scaling (default=None)

    ax : Matplotlib Axes object, optional
       Draw the graph in the specified Matplotlib axes.

    arrows : bool, optional (default=True)
       For directed graphs, if True draw arrowheads.
       Note: Arrows will be the same color as edges.

    arrowstyle : str, optional (default='-|>')
       For directed graphs, choose the style of the arrow heads.
       See :py:class: `matplotlib.patches.ArrowStyle` for more
       options.

    arrowsize : int, optional (default=10)
       For directed graphs, choose the size of the arrow head head's length and
       width. See :py:class: `matplotlib.patches.FancyArrowPatch` for attribute
       `mutation_scale` for more info.

    label : [None| string]
       Label for legend

    Returns
    -------
    matplotlib.collection.LineCollection
        `LineCollection` of the edges

    list of matplotlib.patches.FancyArrowPatch
        `FancyArrowPatch` instances of the directed edges

    Depending whether the drawing includes arrows or not.

    Notes
    -----
    For directed graphs, arrows are drawn at the head end.  Arrows can be
    turned off with keyword arrows=False. Be sure to include `node_size` as a
    keyword argument; arrows are drawn considering the size of nodes.

    Examples
    --------
    >>> G = nx.dodecahedral_graph()
    >>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))

    >>> G = nx.DiGraph()
    >>> G.add_edges_from([(1, 2), (1, 3), (2, 3)])
    >>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
    >>> alphas = [0.3, 0.4, 0.5]
    >>> for i, arc in enumerate(arcs):  # change alpha values of arcs
    ...     arc.set_alpha(alphas[i])

    Also see the NetworkX drawing examples at
    https://networkx.github.io/documentation/latest/auto_examples/index.html

    See Also
    --------
    draw()
    draw_networkx()
    draw_networkx_nodes()
    draw_networkx_labels()
    draw_networkx_edge_labels()
    """
    try:
        import matplotlib
        import matplotlib.pyplot as plt
        import matplotlib.cbook as cb
        from matplotlib.colors import colorConverter, Colormap, Normalize
        from matplotlib.collections import LineCollection
        from matplotlib.patches import FancyArrowPatch
        import numpy as np
    except ImportError:
        raise ImportError("Matplotlib required for draw()")
    except RuntimeError:
        print("Matplotlib unable to open display")
        raise

    if ax is None:
        ax = plt.gca()

    if edgelist is None:
        edgelist = list(G.edges())

    if not edgelist or len(edgelist) == 0:  # no edges!
        return None

    if nodelist is None:
        nodelist = list(G.nodes())

    # set edge positions
    edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])

    if not cb.iterable(width):
        lw = (width, )
    else:
        lw = width

    if not is_string_like(edge_color) \
            and cb.iterable(edge_color) \
            and len(edge_color) == len(edge_pos):
        if np.alltrue([is_string_like(c) for c in edge_color]):
            # (should check ALL elements)
            # list of color letters such as ['k','r','k',...]
            edge_colors = tuple(
                [colorConverter.to_rgba(c, alpha) for c in edge_color])
        elif np.alltrue([not is_string_like(c) for c in edge_color]):
            # If color specs are given as (rgb) or (rgba) tuples, we're OK
            if np.alltrue(
                [cb.iterable(c) and len(c) in (3, 4) for c in edge_color]):
                edge_colors = tuple(edge_color)
            else:
                # numbers (which are going to be mapped with a colormap)
                edge_colors = None
        else:
            raise ValueError('edge_color must contain color names or numbers')
    else:
        if is_string_like(edge_color) or len(edge_color) == 1:
            edge_colors = (colorConverter.to_rgba(edge_color, alpha), )
        else:
            msg = 'edge_color must be a color or list of one color per edge'
            raise ValueError(msg)

    if (not G.is_directed() or not arrows):
        edge_collection = LineCollection(
            edge_pos,
            colors=edge_colors,
            linewidths=lw,
            antialiaseds=(1, ),
            linestyle=style,
            transOffset=ax.transData,
        )

        edge_collection.set_zorder(1)  # edges go behind nodes
        edge_collection.set_label(label)
        ax.add_collection(edge_collection)

        # Note: there was a bug in mpl regarding the handling of alpha values
        # for each line in a LineCollection. It was fixed in matplotlib by
        # r7184 and r7189 (June 6 2009). We should then not set the alpha
        # value globally, since the user can instead provide per-edge alphas
        # now.  Only set it globally if provided as a scalar.
        #if cb.is_numlike(alpha):
        #   edge_collection.set_alpha(alpha)

        if edge_colors is None:
            if edge_cmap is not None:
                assert (isinstance(edge_cmap, Colormap))
            edge_collection.set_array(np.asarray(edge_color))
            edge_collection.set_cmap(edge_cmap)
            if edge_vmin is not None or edge_vmax is not None:
                edge_collection.set_clim(edge_vmin, edge_vmax)
            else:
                edge_collection.autoscale()
        return edge_collection

    arrow_collection = None

    if G.is_directed() and arrows:
        # Note: Waiting for someone to implement arrow to intersection with
        # marker.  Meanwhile, this works well for polygons with more than 4
        # sides and circle.

        def to_marker_edge(marker_size, marker):
            if marker in "s^>v<d":  # `large` markers need extra space
                return np.sqrt(2 * marker_size) / 2
            else:
                return np.sqrt(marker_size) / 2

        # Draw arrows with `matplotlib.patches.FancyarrowPatch`
        arrow_collection = []
        mutation_scale = arrowsize  # scale factor of arrow head
        arrow_colors = edge_colors
        if arrow_colors is None:
            if edge_cmap is not None:
                assert (isinstance(edge_cmap, Colormap))
            else:
                edge_cmap = plt.get_cmap()  # default matplotlib colormap
            if edge_vmin is None:
                edge_vmin = min(edge_color)
            if edge_vmax is None:
                edge_vmax = max(edge_color)
            color_normal = Normalize(vmin=edge_vmin, vmax=edge_vmax)

        for i, (src, dst) in enumerate(edge_pos):
            x1, y1 = src
            x2, y2 = dst
            arrow_color = None
            line_width = None
            shrink_source = 0  # space from source to tail
            shrink_target = 0  # space from  head to target
            if cb.iterable(node_size):  # many node sizes
                src_node, dst_node = edgelist[i]
                index_node = nodelist.index(dst_node)
                marker_size = node_size[index_node]
                shrink_target = to_marker_edge(marker_size, node_shape)
            else:
                shrink_target = to_marker_edge(node_size, node_shape)
            if arrow_colors is None:
                arrow_color = edge_cmap(color_normal(edge_color[i]))
            elif len(arrow_colors) > 1:
                arrow_color = arrow_colors[i]
            else:
                arrow_color = arrow_colors[0]
            if len(lw) > 1:
                line_width = lw[i]
            else:
                line_width = lw[0]
            arrow = FancyArrowPatch((x1, y1), (x2, y2),
                                    arrowstyle=arrowstyle,
                                    shrinkA=shrink_source,
                                    shrinkB=shrink_target,
                                    mutation_scale=mutation_scale,
                                    color=arrow_color,
                                    linewidth=line_width,
                                    zorder=1)  # arrows go behind nodes

            # There seems to be a bug in matplotlib to make collections of
            # FancyArrowPatch instances. Until fixed, the patches are added
            # individually to the axes instance.
            arrow_collection.append(arrow)
            ax.add_patch(arrow)

    # update view
    minx = np.amin(np.ravel(edge_pos[:, :, 0]))
    maxx = np.amax(np.ravel(edge_pos[:, :, 0]))
    miny = np.amin(np.ravel(edge_pos[:, :, 1]))
    maxy = np.amax(np.ravel(edge_pos[:, :, 1]))

    w = maxx - minx
    h = maxy - miny
    padx, pady = 0.05 * w, 0.05 * h
    corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady)
    ax.update_datalim(corners)
    ax.autoscale_view()

    return arrow_collection
Beispiel #32
0
def dsscut(name, time, ra, dec, radius, fol):

    plt.rc('text', usetex=False)
    plt.rc('font', family='serif')
    #
    # basic parameters, can be changed in principle
    #
    size = 10  # [arcmin] the size of the retrieved and saved image
    size1 = 10  # [arcmin] the size of the image used for the FC
    pix = 1.008  # approx pixel scale
    #
    # get the cutout image from the ESO archive
    #
    ra1, dec1 = (float(ra), float(dec))
    raS = ra.replace(':', '%3A')
    decS = dec.replace(':', '%3A')
    ra_dec = coord.SkyCoord(ra + ' ' + dec, unit=(u.deg, u.deg))
    ra_hms = '%02.f:%02.f:%05.2f' % (ra_dec.ra.hms)
    dec_dms = '%02.f:%02.f:%05.2f' % (ra_dec.dec.dms[0], abs(
        ra_dec.dec.dms[1]), abs(ra_dec.dec.dms[2]))
    #### size /arcminutes
    link = 'http://archive.eso.org/dss/dss/image?ra=' + raS + '&dec=' + decS + '&equinox=J2000&name=&x=' + str(
        size) + '&y=' + str(
            size
        ) + '&Sky-Survey=DSS2-red&mime-type=download-fits&statsmode=WEBFORM'
    outf_path = fol + '/' + name + '/' + name + '_dss_red.fits'
    csv_outf = fol + '/' + name + '/' + name + '.csv'
    try:
        #with urllib.request.urlopen(link) as response, open(outf, 'wb') as outf:
        response, outf = urllib.request.urlopen(link), open(outf_path, 'wb')
        shutil.copyfileobj(response, outf)
        print('\t... image saved to:', outf_path)

        #
        # load image and make a FC
        #
        fh = fits.open(outf_path)
        fim = fh[0].data
        fhe = fh[0].header

        #
        # cut image and apply scale
        #
        imsize_list = [
            10,
        ]
        if (float(radius) * 120 < 3):
            imsize_list.append(3)
        for imsize in imsize_list:
            size1 = imsize
            x1 = int(30 * (size - size1))
            x2 = int(30 * (size + size1))
            y1 = int(30 * (size - size1))
            y2 = int(30 * (size + size1))
            fim = fim[y1:y2, x1:x2]

            fim[np.isnan(fim)] = 0.0
            transform = AsinhStretch() + PercentileInterval(99.7)
            bfim = transform(fim)

            with warnings.catch_warnings(
            ):  #because there are deprecated keywords in the header, no need to write it out
                warnings.simplefilter("ignore")
                global wcs
                wcs = WCS(fhe)

            #
            # produce and save the FC
            #
            fig = plt.figure(2, figsize=(5, 5))
            fig1 = fig.add_subplot(111, aspect='equal')
            plt.imshow(bfim, cmap='gray_r', origin='lower')
            s_world = wcs.wcs_world2pix(np.array([
                [float(ra), float(dec)],
            ]), 1)[0]
            theta = np.linspace(0, 2 * np.pi, 8000)
            x, y = s_world[0] - x1 + np.cos(theta) * float(
                radius) * 3600, s_world[1] - y1 + np.sin(theta) * float(
                    radius) * 3600
            fig1.plot(x, y, color='red', linewidth=0.5)
            try:
                os.system(
                    'wget -nd -nc "https://catalogs.mast.stsci.edu/api/v0.1/panstarrs/dr1/mean?ra='
                    + str(raS) + '&amp;dec=' + str(decS) + '&radius=' +
                    str((size) / 120.) +
                    '&nDetections.gte=1&amp&pagesize=50001&format=csv"  ')
                os.system(
                    'mv ./mean\?ra\=' + str(raS) + '\&amp\;dec\=' + str(decS) +
                    '\&radius\=' + str(size / 120.) +
                    '\&nDetections.gte\=1\&amp\&pagesize\=50001\&format\=csv  ./'
                    + str(csv_outf))
                print('1')
                db_data = rdb(csv_outf)
                print('2')
                sextab = make_asc_runsex(outf_path)
                print(len(db_data))
                for i in db_data:
                    db_ra = i[1]
                    db_dec = i[2]
                    db_mag = format(i[3], '0.2f')
                    db_world = wcs.wcs_world2pix(
                        np.array([
                            [float(db_ra), float(db_dec)],
                        ]), 1)[0]
                    fig1.text(db_world[0] - x1,
                              db_world[1] - y1,
                              str(db_mag),
                              color='green',
                              fontsize=7)
                    #print(db_world)
                    #fig1.plot(db_world[0], db_world[1], color='red', linewidth=0.5)
                    #fig.text(db_world[0]/(size*60.),db_world[1]/(size*60.),str(format(db_mag, '0.2f')),fontsize=5,color='green')
                #txtb=fig.text(0.06, 0.06, mm, fontsize=10, color='black')
                #txtb.set_path_effects([PathEffects.withStroke(linewidth=0.1, foreground='k')])
            except:
                try:
                    os.system(
                        'wget -nd -nc "http://skymapper.anu.edu.au/sm-cone/public/query?RA='
                        + str(raS) + '&DEC=' + str(decS) + '&SR=' +
                        str((size) / 120.) + '&format=csv"  ')
                    os.system('mv ./query\?RA\=' + str(raS) + '\&DEC\=' +
                              str(decS) + '\&SR\=' + str(size / 120.) +
                              '\&format\=csv  ./' + str(csv_outf))
                    #skymapper keys
                    globals()['ram'] = 'raj2000'
                    globals()['ra_err'] = 'e_raj2000'
                    globals()['decm'] = 'dej2000'
                    globals()['dec_err'] = 'e_dej2000'
                    # u g r i z
                    globals()['mm'] = 'r_psf'
                    globals()['mm_err'] = 'e_r_psf'
                    print('1')
                    db_data = rdb(csv_outf)
                    print('2')
                    sextab = make_asc_runsex(outf_path)
                    print(len(db_data))
                    for i in db_data:
                        db_ra = i[1]
                        db_dec = i[2]
                        db_mag = format(i[3], '0.2f')
                        db_world = wcs.wcs_world2pix(
                            np.array([
                                [float(db_ra), float(db_dec)],
                            ]), 1)[0]
                        fig1.text(db_world[0] - x1,
                                  db_world[1] - y1,
                                  str(db_mag),
                                  color='green',
                                  fontsize=7)
                except:
                    txtb = fig.text(0.45,
                                    0.06,
                                    'NO Panstarrs AND skymapper',
                                    fontsize=10,
                                    color='black')
            fig2 = plt.axes([0.0, 0.0, 0.4, 0.12])
            fig2.set_facecolor('w')
            txta = fig.text(0.02,
                            0.08,
                            'GRB' + time + '  DSS ' + str(imsize) + '\' x ' +
                            str(imsize) + '\'',
                            fontsize=7,
                            color='black')
            txta = fig.text(0.5, 0.95, 'N', fontsize=18, color='black')
            txta = fig.text(0.01, 0.5, 'E', fontsize=18, color='black')
            txta = fig.text(0.02,
                            0.05,
                            'GRB   ra = ' + ra_hms + ' (' + raS + ')',
                            fontsize=7,
                            color='black')
            txta = fig.text(0.02,
                            0.02,
                            'GRB dec = ' + dec_dms + ' (' + decS + ')',
                            fontsize=7,
                            color='black')
            #txta.set_path_effects([PathEffects.withStroke(linewidth=0.1, foreground='k')])
            #txtb=fig.text(0.9,0.95,'DSS',fontsize=10,color='black')
            #txtb.set_path_effects([PathEffects.withStroke(linewidth=0.1, foreground='k')])
            fig1.add_patch(
                FancyArrowPatch((size1 * 60 - 70 - 10, 20),
                                (size1 * 60 - 10, 20),
                                arrowstyle='-',
                                color='k',
                                linewidth=1.5))
            #fig1.add_patch(FancyArrowPatch((size1*60-15/pix-10,20),(size1*60-10,20),arrowstyle='-',color='black',linewidth=2.0))
            txtc = fig.text(0.9, 0.06, '60\'\'', fontsize=10, color='black')
            txtc.set_path_effects(
                [PathEffects.withStroke(linewidth=0.1, foreground='k')])
            #plt.gca().xaxis.set_major_locator(plt.NullLocator())
            #plt.gca().yaxis.set_major_locator(plt.NullLocator())
            #fig2=plt.axes([0.0, 0.64, 0.1, 0.65])
            #lena = mpimg.imread('a.jpg')
            #lena.shape #(512, 512, 3)
            #plt.imshow(lena)
            plt.gca().xaxis.set_major_locator(plt.NullLocator())
            plt.gca().yaxis.set_major_locator(plt.NullLocator())
            plt.subplots_adjust(top=1,
                                bottom=0,
                                left=0,
                                right=1,
                                hspace=0,
                                wspace=0)
            globals()['fname' + str(imsize)] = name + str(imsize) + '_dss.png'
            plt.savefig(fol + '/' + name + '/' +
                        globals()['fname' + str(imsize)],
                        dpi=300,
                        format='PNG')
            fig.clear()

        if (float(radius) * 120 < 3):
            return {
                'pngname10': fol + '/' + name + '/' + globals()['fname10'],
                'pngname3': fol + '/' + name + '/' + globals()['fname3'],
                'dssname': outf_path,
                'dsslink': link
            }
        else:
            return {
                'pngname10': fol + '/' + name + '/' + globals()['fname10'],
                'dssname': outf_path,
                'dsslink': link
            }

    except Exception as e:
        print(str(e))
        return {'dss_err': '-99', 'dsslink': link}
Beispiel #33
0
 def __init__(self, xs, ys, zs, *args, **kwargs):
     arrow_prop_dict = dict(mutation_scale=20, arrowstyle='-|>', color='k', shrinkA=0, shrinkB=0) # default parameters
     for key in kwargs :
         arrow_prop_dict[key] = kwargs[key] # overwrite the default values if there is a conflict
     FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **arrow_prop_dict)
     self._verts3d = xs, ys, zs
 def __init__(self, xs, ys, zs, *args, **kwargs):
     FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
     self._verts3d = xs, ys, zs
Beispiel #35
0
def draw_network(G, pos, node_color=None, ax=None,
                 radius=1.4, node_alpha=0.5, edge_alpha=0.25,
                 fontsize=12, only_nodes = None):
    """Improved drawing of directed graphs in NetworkX.

    Modified from http://groups.google.com/group/networkx-discuss/
    browse_thread/thread/170624d22c4b0ee6?pli=1.

    Author of original: Stefan van der Walt

    Parameters
    ----------
    pos : dictionary
      A dictionary with nodes as keys and positions as values.

    node_color : string or array of floats
      A single color format string, or a sequence of colors with an entry
      for each node in G.
    """
    if ax is None:
        f, ax = plt.subplots()

    if only_nodes is None:
        only_nodes = set(G.nodes())
        

    only_nodes = set(only_nodes) if not isinstance(only_nodes, set) else \
                 only_nodes

    # Find the set of all the nodes connected to the ones we want to highlight
    connected = set()
    for n in only_nodes:
        connected.update(G.predecessors(n) + G.successors(n))

    # Walk and draw nodes
    for i, n in enumerate(G.nodes()):
        if node_color is None:
            color = (0, 0, 0)
        else:
            color = node_color[n]
        #if node_color is None or cmap is None:
        #    color = (0,0,0)
        #else:
        #    color = cmap(node_color[n])

        # Selectively de-highlight nodes not being shown
        if n in only_nodes:
            t_alpha = 1.0
            n_alpha = node_alpha
            zorder = 2.2
        elif n in connected:
            t_alpha = n_alpha = 0.6*node_alpha
            zorder = 2.0
        else:
            t_alpha = n_alpha = 0.15*node_alpha
            zorder = 1.8

        c = Circle(pos[n],radius=radius,
                   alpha=n_alpha,
                   color=color,ec='k')
        x, y = pos[n]
        t = plt.text(x, y, n, horizontalalignment='center',
                     verticalalignment='center', color='k', fontsize=fontsize,
                     weight='bold', alpha=t_alpha)
        t.set_zorder(zorder+0.1)
        c = ax.add_patch(c)
        c.set_zorder(zorder)
        G.node[n]['patch']=c
        x,y=pos[n]

    # Walk and draw edges. Keep track of edges already seen to offset
    # multiedges and merge u<->v edges into one.
    
    seen={}
    for (u,v) in G.edges(data=False):
        if not (u in only_nodes or v in only_nodes):
            continue
        
        n1 = G.node[u]['patch']
        n2 = G.node[v]['patch']
        rad=0.1
        color = 'k'
    
        if (u,v) in seen:
            # For multiedges, offset new ones
            rad=seen.get((u,v))
            rad=(rad + np.sign(rad)*0.1)*-1

        # If the opposite edge had already been drawn, draw on the same line to
        # reduce clutter.
        if (v,u) in seen:
            arrowstyle = '<|-'
            c1, c2, pA, pB = n2.center, n1.center, n2, n1
        else:
            arrowstyle = '-|>'
            c1, c2, pA, pB = n1.center, n2.center, n1, n2
            
        e = FancyArrowPatch(c1, c2, patchA=pA, patchB=pB,
                            arrowstyle=arrowstyle,
                            connectionstyle='arc3,rad=%s'%rad,
                            mutation_scale=15.0, lw=2,
                            alpha=edge_alpha, color=color)
        seen[(u,v)] = rad
        # Ensure nedges are drawn below nodes
        e = ax.add_patch(e)
        e.set_zorder(0.5)

    ax.autoscale()
    plt.axis('tight')
    return ax
Beispiel #36
0
 def draw(self, renderer):
     """Draw the arrow."""
     xs3d, ys3d, zs3d = self._verts3d
     xs, ys, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
     self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
     FancyArrowPatch.draw(self, renderer)
Beispiel #37
0
 def addarrow(self, x, y, vx, vy, arrowstyle = '->', lw = 1, mutation_scale = 7, mutation_aspect = None):
     self.graph.add_patch(FancyArrowPatch(posA = (x, y), posB = (x+vx, y+vy),
                                          arrowstyle = arrowstyle, lw = lw, 
                                          mutation_scale = mutation_scale, mutation_aspect = mutation_aspect))
Beispiel #38
0
def Arrow(xi,
          yi,
          xf,
          yf,
          sc=20,
          fc='#a2e3a2',
          ec='black',
          zo=0,
          st='simple',
          label=None,
          lbHa='left',
          lbVa='center',
          lbPos='cen',
          lbFs=10,
          lbRot=0,
          lbDx=0,
          lbDy=0,
          *args,
          **kwargs):
    """
    Draw arrow
    ==========
    default arguments:
        mutation_scale = sc
        fc             = fc
        ec             = ec
        zorder         = zo
        arrowstyle     = st
        lbPos          = {'cen', 'tip', 'tail'}
    styles:
        Curve           -        None
        CurveB          ->       head_length=0.4,head_width=0.2
        BracketB        -[       widthB=1.0,lengthB=0.2,angleB=None
        CurveFilledB    -|>      head_length=0.4,head_width=0.2
        CurveA          <-       head_length=0.4,head_width=0.2
        CurveAB         <->      head_length=0.4,head_width=0.2
        CurveFilledA    <|-      head_length=0.4,head_width=0.2
        CurveFilledAB   <|-|>    head_length=0.4,head_width=0.2
        BracketA        ]-       widthA=1.0,lengthA=0.2,angleA=None
        BracketAB       ]-[      widthA=1.0,lengthA=0.2,angleA=None,widthB=1.0,lengthB=0.2,angleB=None
        Fancy           fancy    head_length=0.4,head_width=0.4,tail_width=0.4
        Simple          simple   head_length=0.5,head_width=0.5,tail_width=0.2
        Wedge           wedge    tail_width=0.3,shrink_factor=0.5
        BarAB           |-|      widthA=1.0,angleA=None,widthB=1.0,angleB=None
    """
    if not 'mutation_scale' in kwargs: kwargs['mutation_scale'] = sc
    if not 'fc' in kwargs: kwargs['fc'] = fc
    if not 'ec' in kwargs: kwargs['ec'] = ec
    if not 'zorder' in kwargs: kwargs['zorder'] = zo
    if not 'arrowstyle' in kwargs: kwargs['arrowstyle'] = st
    if True:  # makes arrow tips sharper
        fa = FancyArrowPatch((xi, yi), (xf, yf),
                             shrinkA=False,
                             shrinkB=False,
                             path_effects=[Stroke(joinstyle='miter')],
                             *args,
                             **kwargs)
    else:
        fa = FancyArrowPatch((xi, yi), (xf, yf),
                             shrinkA=False,
                             shrinkB=False,
                             *args,
                             **kwargs)
    gca().add_patch(fa)
    if label:
        if lbPos == 'cen':
            xm = (xi + xf) / 2.0
            ym = (yi + yf) / 2.0
        if lbPos == 'tip':
            xm, ym = xf, yf
        if lbPos == 'tail':
            xm, ym = xi, yi
        gca().text(xm + lbDx,
                   ym + lbDy,
                   label,
                   ha=lbHa,
                   va=lbVa,
                   fontsize=lbFs,
                   rotation=lbRot)
    return fa
Beispiel #39
0
        if (j + 1) % 2 == 0:
            x2 = j + 1
            y2 = i
        else:
            x2 = j + 1
            y2 = i + offset

        pylab.plot(np.r_[x1, x2], np.r_[y1, y2], 'k')

## Inlet and outlet arrows for air stream
for i in range(2 * nR):
    pylab.gca().add_patch(
        FancyArrowPatch((-1, i * 0.5), (-0.5, i * 0.5),
                        arrowstyle='-|>',
                        fc='k',
                        ec='k',
                        mutation_scale=20,
                        lw=0.8))
    pylab.gca().add_patch(
        FancyArrowPatch((nC - 0.5, i * 0.5), (nC, i * 0.5),
                        arrowstyle='-|>',
                        fc='k',
                        ec='k',
                        mutation_scale=20,
                        lw=0.8))
    pylab.gca().text(-1.25, nR / 2, 'Air Inlet', rotation=90)
    pylab.gca().text(nC + 0.25, nR / 2, 'Air Outlet', rotation=90)

## "Header" for inlet and outlet of refrigerant
pylab.plot(np.r_[nC - 1.4, nC - 0.6, nC - 0.6, nC - 1.4, nC - 1.4],
           np.r_[-0.25, -0.25, nR, nR, -0.25], 'k--')
Beispiel #40
0
  def ScatterGraph(self):
    AnnotatedArtists = []

    #
    # Compute the scatter plot for this cluster
    #
    NumberOfFrames  = self.Data.GetNumberOfFrames()
    NumberOfObjects = self.Data.GetNumberOfObjects()
    FirstObject     = self.Data.GetFirstObject() - 2 # Include filtered and noise
    LastObject      = self.Data.GetLastObject()
    TasksPerFrame   = self.Data.GetTasksPerFrame()

    SelectedFrame   = self.GUI.GetSelectedFrame()
    SelectedCluster  = self.GUI.GetSelectedCluster()
    SelectedMetricX = self.GUI.GetSelectedMetricX()
    SelectedMetricY = self.GUI.GetSelectedMetricY()
    if self.GUI.in_3D():
      SelectedMetricZ = self.GUI.GetSelectedMetricZ()

#    cursor = Cursor(self.ScatterPlotAxes, useblit=True, color='black', linewidth=1 )

    for current_frame in range(1, NumberOfFrames+1):

      for current_object in range(FirstObject, LastObject+1):
        (r, g, b) = Decorations.RGBColor0_1(current_object)

        # 
        # Compute the scatter plot for this cluster
        # 
        xdata = self.Data.GetClusterData( current_frame, current_object, SelectedMetricX )
        ydata = self.Data.GetClusterData( current_frame, current_object, SelectedMetricY )
        if (len(xdata) == 0) or (len(ydata) == 0):
          continue
        if self.GUI.in_3D():
          zdata = self.Data.GetClusterData( current_frame, current_object, SelectedMetricZ )
          if (len(zdata) == 0):
            continue

        if (self.GUI.in_Trajectory_View()):
          if self.GUI.RatioX():
            xdata = xdata * TasksPerFrame[current_frame-1]
          if self.GUI.RatioY():
            ydata = ydata * TasksPerFrame[current_frame-1]
          if self.GUI.in_3D() and self.GUI.RatioZ():
            zdata = zdata * TasksPerFrame[current_frame-1]

        if self.GUI.in_3D():
          scatter = self.ScatterPlotAxes.scatter( xdata, ydata, zdata, color=(r, g, b), zorder=2, s=50, marker=Decorations.ChooseMarker(current_object), picker=True )
        else:
          scatter = self.ScatterPlotAxes.scatter( xdata, ydata, color=(r, g, b), zorder=2, s=50, marker=Decorations.ChooseMarker(current_object), picker=True )
        thumb = self.GUI.GetThumbAxes(current_frame).scatter( xdata, ydata, color=(r, g, b), zorder=2, s=100, marker=Decorations.ChooseMarker(current_object))
        thumb.set_visible( False )
        self.Thumbs[(current_object, current_frame)] = thumb

        scatter.set_gid( self.Data.PrettyCluster(current_object) )
        scatter.set_visible( False )
        self.Scatters[(current_object, current_frame)] = scatter
        AnnotatedArtists.append( scatter )

        # 
        # Compute the centroid for this cluster
        # 
        centroid_x = nanmean( xdata )
        centroid_y = nanmean( ydata )
        if self.GUI.in_3D():
          centroid_z = nanmean( zdata )
          centroid = self.ScatterPlotAxes.scatter( centroid_x, centroid_y, centroid_z, s=50, color=(r, g, b), edgecolor="black", marker="o", zorder=3, picker=True )
          self.Trajectories[(current_object, current_frame)] = (centroid_x, centroid_y, centroid_z)
        else:
          centroid = self.ScatterPlotAxes.scatter( centroid_x, centroid_y, s=50, color=(r, g, b), edgecolor="black", marker="o", zorder=3, picker=True)
          self.Trajectories[(current_object, current_frame)] = (centroid_x, centroid_y)

        centroid.set_gid( self.Data.PrettyCluster(current_object) )
        centroid.set_visible(False)
        self.Centroids[(current_object, current_frame)] = centroid
        AnnotatedArtists.append( centroid )

        # 
        # Compute the convex hull for this cluster
        # 
        if (AvailableHulls) and self.GUI.in_2D():
          points = np.array( zip(xdata, ydata) )
          if (len(points) < 3):
            continue

          try:
            hull     = ConvexHull( points, qhull_options='Pp' )
            vertices = hull.vertices
          except:
            vertices = []
 
          if (len(vertices) > 0):
            polygon_points = []
            for vertice in vertices:
              polygon_points.append( (points[vertice][0], points[vertice][1]) )
           
            hull_polygon = Polygon(polygon_points, closed=True, alpha=0.5, color=Decorations.RGBColor0_1(current_object), zorder=4, lw=10)
            hull_polygon.set_gid( self.Data.PrettyCluster(current_object) )
            hull_polygon.set_visible(False)
            self.Hulls[(current_object, current_frame)] = hull_polygon
            self.ScatterPlotAxes.add_artist( hull_polygon )
            AnnotatedArtists.append( hull_polygon )

    # Compute the arrows for the trajectories
    for current_object in range(FirstObject, LastObject+1):
      (r, g, b) = Decorations.RGBColor0_1(current_object)
      from_frame = 1
      to_frame   = from_frame + 1
      while (to_frame <= NumberOfFrames):
        tail = (current_object, from_frame)
        head = (current_object, to_frame)

        if not tail in self.Trajectories:
          from_frame = to_frame
          to_frame   = from_frame +1
          continue
        else:
          if not head in self.Trajectories:
            to_frame = to_frame + 1
            continue

        from_x = self.Trajectories[tail][0]
        from_y = self.Trajectories[tail][1]
        to_x   = self.Trajectories[head][0]
        to_y   = self.Trajectories[head][1]
        if self.GUI.in_3D():
          from_z = self.Trajectories[tail][2]
          to_z   = self.Trajectories[head][2]

        if ((to_x - from_x != 0) or (to_y - from_y != 0) or (self.GUI.in_3D() and (to_z - from_z != 0))):
          if (not (math.isnan(from_x) or math.isnan(from_y) or math.isnan(to_x) or math.isnan(to_y))):
            if (self.GUI.in_3D() and (not (math.isnan(from_z) or math.isnan(to_z)))):
              arrow = Arrow3D((from_x,to_x), (from_y, to_y), (from_z, to_z), arrowstyle='-|>', mutation_scale=20, color=(r, g, b), linewidth=1)
            else:
              arrow = FancyArrowPatch((from_x,from_y), (to_x,to_y), arrowstyle='-|>', mutation_scale=20, color=(r, g, b), linewidth=1)
            arrow.set_visible(False)
            self.Arrows[current_object].append(arrow)
            self.ScatterPlotAxes.add_artist(arrow)

        from_frame = to_frame
        to_frame   = from_frame +1

    self.Annotations = DataCursor(AnnotatedArtists)
Beispiel #41
0
    def _render_on_subplot(self, subplot):
        r"""
        Render this arrow in a subplot.  This is the key function that
        defines how this arrow graphics primitive is rendered in
        matplotlib's library.

        EXAMPLES:

        This function implicitly ends up rendering this arrow on
        a matplotlib subplot::

            sage: arrow((0,1), (2,-1))

        TESTS:

        The length of the ends (shrinkA and shrinkB) should not depend
        on the width of the arrow, because Matplotlib already takes
        this into account. See :trac:`12836`::

            sage: fig = Graphics().matplotlib()
            sage: sp = fig.add_subplot(1,1,1)
            sage: a = arrow((0,0), (1,1))
            sage: b = arrow((0,0), (1,1), width=20)
            sage: p1 = a[0]._render_on_subplot(sp)
            sage: p2 = b[0]._render_on_subplot(sp)
            sage: p1.shrinkA == p2.shrinkA
            True
            sage: p1.shrinkB == p2.shrinkB
            True

        Dashed arrows should have solid arrowheads,
        :trac:`12852`. This test saves the plot of a dashed arrow to
        an EPS file. Within the EPS file, ``stroke`` will be called
        twice: once to draw the line, and again to draw the
        arrowhead. We check that both calls do not occur while the
        dashed line style is enabled::

            sage: a = arrow((0,0), (1,1), linestyle='dashed')
            sage: filename = tmp_filename(ext='.eps')
            sage: a.save(filename=filename)
            sage: with open(filename, 'r') as f:
            ....:     contents = f.read().replace('\n', ' ')
            sage: two_stroke_pattern = r'setdash.*stroke.*stroke.*setdash'
            sage: import re
            sage: two_stroke_re = re.compile(two_stroke_pattern)
            sage: two_stroke_re.search(contents) is None
            True
        """
        options = self.options()
        head = options.pop('head')
        if head == 0: style = '<|-'
        elif head == 1: style = '-|>'
        elif head == 2: style = '<|-|>'
        else: raise KeyError('head parameter must be one of 0 (start), 1 (end) or 2 (both).')
        width = float(options['width'])
        arrowshorten_end = float(options.get('arrowshorten',0))/2.0
        arrowsize = float(options.get('arrowsize',5))
        head_width=arrowsize
        head_length=arrowsize*2.0
        color = to_mpl_color(options['rgbcolor'])
        from matplotlib.patches import FancyArrowPatch
        p = FancyArrowPatch((self.xtail, self.ytail), (self.xhead, self.yhead),
                            lw=width, arrowstyle='%s,head_width=%s,head_length=%s'%(style,head_width, head_length),
                            shrinkA=arrowshorten_end, shrinkB=arrowshorten_end,
                            fc=color, ec=color, linestyle=options['linestyle'])
        p.set_zorder(options['zorder'])
        p.set_label(options['legend_label'])

        if options['linestyle']!='solid':
            # The next few lines work around a design issue in matplotlib. Currently, the specified
            # linestyle is used to draw both the path and the arrowhead.  If linestyle is 'dashed', this
            # looks really odd.  This code is from Jae-Joon Lee in response to a post to the matplotlib mailing
            # list.  See http://sourceforge.net/mailarchive/forum.php?thread_name=CAG%3DuJ%2Bnw2dE05P9TOXTz_zp-mGP3cY801vMH7yt6vgP9_WzU8w%40mail.gmail.com&forum_name=matplotlib-users

            import matplotlib.patheffects as pe
            class CheckNthSubPath(object):
                def __init__(self, patch, n):
                    """
                    creates an callable object that returns True if the provided
                    path is the n-th path from the patch.
                    """
                    self._patch = patch
                    self._n = n

                def get_paths(self, renderer):
                    self._patch.set_dpi_cor(renderer.points_to_pixels(1.))
                    paths, fillables = self._patch.get_path_in_displaycoord()
                    return paths

                def __call__(self, renderer, gc, tpath, affine, rgbFace):
                    path = self.get_paths(renderer)[self._n]
                    vert1, code1 = path.vertices, path.codes
                    import numpy as np

                    if np.all(vert1 == tpath.vertices) and np.all(code1 == tpath.codes):
                        return True
                    else:
                        return False


            class ConditionalStroke(pe._Base):

                def __init__(self, condition_func, pe_list):
                    """
                    path effect that is only applied when the condition_func
                    returns True.
                    """
                    super(ConditionalStroke, self).__init__()
                    self._pe_list = pe_list
                    self._condition_func = condition_func

                def draw_path(self, renderer, gc, tpath, affine, rgbFace):

                    if self._condition_func(renderer, gc, tpath, affine, rgbFace):
                        for pe1 in self._pe_list:
                            pe1.draw_path(renderer, gc, tpath, affine, rgbFace)

            pe1 = ConditionalStroke(CheckNthSubPath(p, 0),[pe.Stroke()])
            pe2 = ConditionalStroke(CheckNthSubPath(p, 1),[pe.Stroke(linestyle="solid")])
            p.set_path_effects([pe1, pe2])

        subplot.add_patch(p)
        return p
 def __init__(self, xs, ys, zs, *args, **kwargs):
     """Create arrow."""
     FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
     self._verts3d = xs, ys, zs
Beispiel #43
0
 def __init__(self, pt1, pt2, *args, **kwargs):
     FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
     x = [pt1[0, 0], pt2[0, 0]]
     y = [pt1[1, 0], pt2[1, 0]]
     z = [pt1[2, 0], pt2[2, 0]]
     self._verts3d = x, y, z
Beispiel #44
0
 def __init__(self, xs, ys, zs, *args, **kwargs):
     kwargs.update(dict(mutation_scale=20, lw=1, arrowstyle='-|>'))
     FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
     self._verts3d = xs, ys, zs
Beispiel #45
0
class AnnotationBbox(martist.Artist, _AnnotationBase):
    """
    Annotation-like class, but with offsetbox instead of Text.
    """

    zorder = 3

    def __str__(self):
        return "AnnotationBbox(%g,%g)"%(self.xy[0],self.xy[1])
    @docstring.dedent_interpd
    def __init__(self, offsetbox, xy,
                 xybox=None,
                 xycoords='data',
                 boxcoords=None,
                 frameon=True, pad=0.4, # BboxPatch
                 annotation_clip=None,
                 box_alignment=(0.5, 0.5),
                 bboxprops=None,
                 arrowprops=None,
                 fontsize=None,
                 **kwargs):
        """
        *offsetbox* : OffsetBox instance

        *xycoords* : same as Annotation but can be a tuple of two
           strings which are interpreted as x and y coordinates.

        *boxcoords* : similar to textcoords as Annotation but can be a
           tuple of two strings which are interpreted as x and y
           coordinates.

        *box_alignment* : a tuple of two floats for a vertical and
           horizontal alignment of the offset box w.r.t. the *boxcoords*.
           The lower-left corner is (0.0) and upper-right corner is (1.1).

        other parameters are identical to that of Annotation.
        """
        self.offsetbox = offsetbox

        self.arrowprops = arrowprops

        self.set_fontsize(fontsize)


        if arrowprops is not None:
            self._arrow_relpos = self.arrowprops.pop("relpos", (0.5, 0.5))
            self.arrow_patch = FancyArrowPatch((0, 0), (1,1),
                                               **self.arrowprops)
        else:
            self._arrow_relpos = None
            self.arrow_patch = None

        _AnnotationBase.__init__(self,
                                 xy, xytext=xybox,
                                 xycoords=xycoords, textcoords=boxcoords,
                                 annotation_clip=annotation_clip)

        martist.Artist.__init__(self, **kwargs)

        #self._fw, self._fh = 0., 0. # for alignment
        self._box_alignment = box_alignment

        # frame
        self.patch = FancyBboxPatch(
            xy=(0.0, 0.0), width=1., height=1.,
            facecolor='w', edgecolor='k',
            mutation_scale=self.prop.get_size_in_points(),
            snap=True
            )
        self.patch.set_boxstyle("square",pad=pad)
        if bboxprops:
            self.patch.set(**bboxprops)
        self._drawFrame =  frameon


    def contains(self,event):
        t,tinfo = self.offsetbox.contains(event)
        #if self.arrow_patch is not None:
        #    a,ainfo=self.arrow_patch.contains(event)
        #    t = t or a

        # self.arrow_patch is currently not checked as this can be a line - JJ

        return t,tinfo


    def get_children(self):
        children = [self.offsetbox, self.patch]
        if self.arrow_patch:
            children.append(self.arrow_patch)
        return children

    def set_figure(self, fig):

        if self.arrow_patch is not None:
            self.arrow_patch.set_figure(fig)
        self.offsetbox.set_figure(fig)
        martist.Artist.set_figure(self, fig)

    def set_fontsize(self, s=None):
        """
        set fontsize in points
        """
        if s is None:
            s = rcParams["legend.fontsize"]

        self.prop=FontProperties(size=s)

    def get_fontsize(self, s=None):
        """
        return fontsize in points
        """
        return self.prop.get_size_in_points()

    def update_positions(self, renderer):
        "Update the pixel positions of the annotated point and the text."
        xy_pixel = self._get_position_xy(renderer)
        self._update_position_xybox(renderer, xy_pixel)

        mutation_scale = renderer.points_to_pixels(self.get_fontsize())
        self.patch.set_mutation_scale(mutation_scale)

        if self.arrow_patch:
            self.arrow_patch.set_mutation_scale(mutation_scale)


    def _update_position_xybox(self, renderer, xy_pixel):
        "Update the pixel positions of the annotation text and the arrow patch."

        x, y = self.xytext
        if isinstance(self.textcoords, tuple):
            xcoord, ycoord = self.textcoords
            x1, y1 = self._get_xy(renderer, x, y, xcoord)
            x2, y2 = self._get_xy(renderer, x, y, ycoord)
            ox0, oy0 = x1, y2
        else:
            ox0, oy0 = self._get_xy(renderer, x, y, self.textcoords)

        w, h, xd, yd = self.offsetbox.get_extent(renderer)

        _fw, _fh = self._box_alignment
        self.offsetbox.set_offset((ox0-_fw*w+xd, oy0-_fh*h+yd))

        # update patch position
        bbox = self.offsetbox.get_window_extent(renderer)
        #self.offsetbox.set_offset((ox0-_fw*w, oy0-_fh*h))
        self.patch.set_bounds(bbox.x0, bbox.y0,
                              bbox.width, bbox.height)

        x, y = xy_pixel

        ox1, oy1 = x, y

        if self.arrowprops:
            x0, y0 = x, y

            d = self.arrowprops.copy()

            # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.

            # adjust the starting point of the arrow relative to
            # the textbox.
            # TODO : Rotation needs to be accounted.
            relpos = self._arrow_relpos

            ox0 = bbox.x0 + bbox.width * relpos[0]
            oy0 = bbox.y0 + bbox.height * relpos[1]

            # The arrow will be drawn from (ox0, oy0) to (ox1,
            # oy1). It will be first clipped by patchA and patchB.
            # Then it will be shrinked by shirnkA and shrinkB
            # (in points). If patch A is not set, self.bbox_patch
            # is used.

            self.arrow_patch.set_positions((ox0, oy0), (ox1,oy1))
            fs = self.prop.get_size_in_points()
            mutation_scale = d.pop("mutation_scale", fs)
            mutation_scale = renderer.points_to_pixels(mutation_scale)
            self.arrow_patch.set_mutation_scale(mutation_scale)

            patchA = d.pop("patchA", self.patch)
            self.arrow_patch.set_patchA(patchA)



    def draw(self, renderer):
        """
        Draw the :class:`Annotation` object to the given *renderer*.
        """

        if renderer is not None:
            self._renderer = renderer
        if not self.get_visible(): return

        xy_pixel = self._get_position_xy(renderer)

        if not self._check_xy(renderer, xy_pixel):
            return

        self.update_positions(renderer)

        if self.arrow_patch is not None:
            if self.arrow_patch.figure is None and self.figure is not None:
                self.arrow_patch.figure = self.figure
            self.arrow_patch.draw(renderer)

        if self._drawFrame:
            self.patch.draw(renderer)

        self.offsetbox.draw(renderer)
Beispiel #46
0
def draw_network(G, pos, ax, sg=None):

    for n in G:
        print nodes[n]

        c = None
        if (nodes[n][0] == hidden_layers + 1):  #this is the output node
            c = Circle(pos[n],radius=0.25,alpha=0.5, color='#540351')
        elif (nodes[n][1] >= nodes_per_layer):      #this is a recurrent node
            c = Circle(pos[n],radius=0.25,alpha=0.10 * (nodes[n][1] // nodes_per_layer), color='#B53BB1')
        elif (nodes[n][0] == 0):                    #this is a input node
            c = Circle(pos[n],radius=0.25,alpha=0.5, color='#1420CD')
        else:                                       #this is a hidden node
            c = Circle(pos[n],radius=0.25,alpha=0.5, color='#339540')

        if (nodes[n][0] == hidden_layers + 1):
            label(pos[n], node_identifiers[ nodes[n] ], -1)
        elif (nodes[n][0] == 0):
            label(pos[n], node_identifiers[ nodes[n] ],  1)

        ax.add_patch(c)
        G.node[n]['patch'] = c
        x,y = pos[n]

    seen={}

    for (u,v,d) in G.edges(data=True):
        print "node:",u,v,d
        print "node1: ", nodes[u]
        print "node2: ", nodes[v]

        n1=G.node[u]['patch']
        n2=G.node[v]['patch']
        rad=0.3
        if (u,v) in seen:
            rad=seen.get((u,v))
            rad=(rad+np.sign(rad)*0.1)*-1
        alpha = 0.5
        #alpha = abs( d['weight'] )
        color='k'

        e = None

        if (nodes[v][0] == nodes[u][0]):
            print("drawing curved line to recurrent!")
            e = FancyArrowPatch(n1.center,n2.center,patchA=n1,patchB=n2,
                                arrowstyle='-|>',
                                connectionstyle='arc3,rad=%s'%-rad,
                                mutation_scale=10.0,
                                lw=2,
                                alpha=alpha,
                                color=color)

        else:
            #print("drawing straight line!")
            e = FancyArrowPatch(n1.center,n2.center,patchA=n1,patchB=n2,
                                arrowstyle='-|>',
                                connectionstyle='arc3,rad=0',
                                mutation_scale=10.0,
                                lw=2,
                                alpha=alpha,
                                color=color)

        seen[(u,v)]=rad
        ax.add_patch(e)


    print "recurrent_depth: %d"%(recurrent_depth)

    for i in range(1, recurrent_depth):
        identifier = str("recurrent layer %d"%(i))
        label( (0, (i * nodes_per_layer) + (nodes_per_layer - 1) / 2.0), identifier, 1)

    plt.text(-0.5, -1, "nodes: %d, edges: %d, recurrent edges: %d"%(n_nodes, n_edges, n_recurrent_edges), ha="left", family='sans-serif', size=12)


    return e
Beispiel #47
0
 def draw(self,renderer):
   xp,yp,zp = proj3d.proj_transform(*self.verts,M=renderer.M)
   self.set_positions((xp[0],yp[0]),(xp[1],yp[1]))
   FancyArrowPatch.draw(self,renderer)
Beispiel #48
0
    return a * x**2 + b * x + c, 2 * a * x + b


x = np.linspace(0, 10, 100)
y, _ = y_wire(x)
plt.plot(x, y, 'b-')

# Add the bead to the wire
x = 3
y, dy_dx = y_wire(x)
plt.plot(x, y, 'ro', ms=10)

# Draw and label the gravity vector
gvec = FancyArrowPatch((x, y), (x, y - 2),
                       arrowstyle='->',
                       mutation_scale=10,
                       linewidth=LW,
                       color='k')
lv_line = plt.Line2D((x, x), (y, y - 2), visible=False)  # Local vertical
ax.add_patch(gvec)
plt.text(x - 0.5, y - 1, 'g')

# Draw and label the velocity vector
dx = 2
dy = dy_dx * dx
vvec = FancyArrowPatch((x, y), (x + dx, y + dy),
                       arrowstyle='->',
                       mutation_scale=10,
                       linewidth=LW,
                       color='k')
ax.add_patch(vvec)
Beispiel #49
0
    def init_artists(self):
        main_arrow_props: Dict[str, Any] = {
            "alpha": 0.5 if self.active else 0.2,
            "animated": True,
            "arrowstyle": "->,head_length=10,head_width=7",
            "color": self.color,
            "linestyle": "solid",
        }

        line_props: Dict[str, Any] = {
            "alpha": 0.7 if self.active else 0.3,
            "animated": True,
            "color": self.color,
            "linestyle": "",
            "marker": "x",
            "markerfacecolor": self.color,
            "markersize": 8,
        }

        arc_props: Dict[str, Any] = {
            "alpha": 0.5 if self.active else 0.3,
            "animated": True,
            "color": self.color,
            "linestyle": "dashed",
        }

        prong_props: Dict[str, Any] = {
            "alpha": 0.5 if self.active else 0.2,
            "animated": True,
            "color": self.color,
            "linestyle": "dashed",
            "linewidth": 1,
        }

        cx, cy = self.cxy
        wx, wy = self.wxy
        dx, dy = wx - cx, wy - cy
        r, angle = cart2pol(dx, dy)
        hspan = self.span / 2

        ex, ey = pol2cart(r + self.stickout, angle)

        # main arrow
        main_arrow = FancyArrowPatch(
            posA=self.cxy, posB=(ex + cx, ey + cy), **main_arrow_props
        )
        self.artists["main_arrow"] = main_arrow
        self.axes.add_patch(main_arrow)

        # line
        (line,) = self.axes.plot([cx, wx], [cy, wy], **line_props)
        self.artists["line"] = line
        self.axes.add_line(line)

        # arc
        arc = Arc(
            xy=self.cxy,
            width=2 * r,
            height=2 * r,
            angle=angle,
            theta1=-hspan,
            theta2=hspan,
            **arc_props
        )
        self.artists["arc"] = arc
        self.axes.add_patch(arc)

        # prongs
        r_ext = r + self.stickout
        p1_angle = angle - hspan
        p1 = {"tail": pol2cart(r, p1_angle), "head": pol2cart(r_ext, p1_angle)}
        (prong1,) = self.axes.plot(
            [cx + p1["tail"][0], cx + p1["head"][0]],
            [cy + p1["tail"][1], cy + p1["head"][1]],
            **prong_props
        )
        self.artists["prong1"] = prong1
        self.axes.add_line(prong1)

        p2_angle = angle + hspan
        p2 = {"tail": pol2cart(r, p2_angle), "head": pol2cart(r_ext, p2_angle)}
        (prong2,) = self.axes.plot(
            [cx + p2["tail"][0], cx + p2["head"][0]],
            [cy + p2["tail"][1], cy + p2["head"][1]],
            **prong_props
        )
        self.artists["prong2"] = prong2
        self.axes.add_line(prong2)
Beispiel #50
0
class AnchoredCompass(AnchoredOffsetbox):
    def __init__(self, ax, transSky2Pix, loc,
                 arrow_fraction=0.15,
                 txt1="E", txt2="N",
                 delta_a1=0, delta_a2=0,
                 pad=0.1, borderpad=0.5, prop=None, frameon=False,
                 ):
        """
        Draw an arrows pointing the directions of E & N

        arrow_fraction : length of the arrow as a fraction of axes size

        pad, borderpad in fraction of the legend font size (or prop)
        """

        self._ax = ax
        self._transSky2Pix = transSky2Pix
        self._box = AuxTransformBox(ax.transData)
        self.delta_a1, self.delta_a2 = delta_a1, delta_a2
        self.arrow_fraction = arrow_fraction

        kwargs = dict(mutation_scale=11,
                      shrinkA=0,
                      shrinkB=5)

        self.arrow1 = FancyArrowPatch(posA=(0, 0), posB=(1, 1),
                                      arrowstyle="->",
                                      arrow_transmuter=None,
                                      connectionstyle="arc3",
                                      connector=None,
                                      **kwargs)
        self.arrow2 = FancyArrowPatch(posA=(0, 0), posB=(1, 1),
                                      arrowstyle="->",
                                      arrow_transmuter=None,
                                      connectionstyle="arc3",
                                      connector=None,
                                      **kwargs)


        x1t, y1t, x2t, y2t = 1, 1, 1, 1
        self.txt1 = Text(x1t, y1t, txt1, rotation=0,
                         rotation_mode="anchor",
                         va="center", ha="right")
        self.txt2 = Text(x2t, y2t, txt2, rotation=0,
                         rotation_mode="anchor",
                         va="bottom", ha="center")


        self._box.add_artist(self.arrow1)
        self._box.add_artist(self.arrow2)

        self._box.add_artist(self.txt1)
        self._box.add_artist(self.txt2)

        AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
                                   child=self._box,
                                   prop=prop,
                                   frameon=frameon)

    def set_path_effects(self, path_effects):
        for a in [self.arrow1, self.arrow2, self.txt1, self.txt2]:
            a.set_path_effects(path_effects)

    def _update_arrow(self, renderer):
        ax = self._ax

        x0, y0 = ax.viewLim.x0, ax.viewLim.y0
        a1, a2 = estimate_angle(self._transSky2Pix, x0, y0)
        a1, a2 = a1+self.delta_a1, a2+self.delta_a2

        D = min(ax.viewLim.width, ax.viewLim.height)
        d = D * self.arrow_fraction
        x1, y1 = x0+d*np.cos(a1/180.*np.pi), y0+d*np.sin(a1/180.*np.pi)
        x2, y2 = x0+d*np.cos(a2/180.*np.pi), y0+d*np.sin(a2/180.*np.pi)

        self.arrow1.set_positions((x0, y0), (x1, y1))
        self.arrow2.set_positions((x0, y0), (x2, y2))

        d2 = d
        x1t, y1t = x0+d2*np.cos(a1/180.*np.pi), y0+d2*np.sin(a1/180.*np.pi)
        x2t, y2t = x0+d2*np.cos(a2/180.*np.pi), y0+d2*np.sin(a2/180.*np.pi)

        self.txt1.set_position((x1t, y1t))
        self.txt1.set_rotation(a1-180)
        self.txt2.set_position((x2t, y2t))
        self.txt2.set_rotation(a2-90)


    def draw(self, renderer):
        self._update_arrow(renderer)
        super(AnchoredCompass, self).draw(renderer)
class EnvironmentReader(Reader):
    def __init__(self, vl, room_shape, start_iter):
        super(EnvironmentReader,self).__init__(win_size=[700,700],
                                               win_loc=pos,
                                               title='Environment')
        self.vl = vl
        self.cur_iter = start_iter
        
        self.cur_i = 0
        self.max_iter = np.max(vl['Iter num'])
        self.maxx = room_shape[0][1]
        self.maxy = room_shape[1][1]
        self.cntr_x = np.mean(room_shape[0])
        self.cntr_y = np.mean(room_shape[1])
        
        self.x_hist = []; self.y_hist = []
        
        self.canvas.mpl_connect('resize_event',lambda x: self.update_background())
        
        self.pos, = self.ax.plot([],[],color='g',animated=True)
        self.vel = Arrow([0,0],[1,0],arrowstyle='-|>, head_length=3, head_width=3',
                         animated=True, linewidth=4)
        self.ax.add_patch(self.vel)
        #self.radius, = self.ax.plot([],[],color='r',animated=True)
        self.clockcounter = self.ax.text(self.maxx,room_shape[1][0],
                                         '',ha='right',size='large',
                                         animated=True)
        self.iters = self.ax.text(self.maxx-1, room_shape[1][0]+3,
                                  '',ha='right',animated=True)
        self.target = Circle([0,0],0,animated=True,color='r')
        self.target.set_radius(11)
        self.ax.add_artist(self.target)
        
        self.ax.set_xlim(room_shape[0])
        self.ax.set_ylim(room_shape[1])
        
        self.draw_plc_flds()
        
        self.draw_HMM_sectors()
        self.predicted_counter = self.ax.text(self.maxx,room_shape[1][0]+10,'',
                                              ha='right',size='large',animated=True)
        self.prediction_hist = None
        #self.cur_sec = Rectangle([0,0],self.HMM.dx,self.HMM.dy,fill=True,
        #                         color='k',animated=True)
        #self.ax_env.add_patch(self.cur_sec)
        
        self.canvas.draw()
        
    def read(self, iteration=None):
        ''' Return the environment data corresponding to
            the next iteration.
            
            Note that 0 or multiple data points can be
            associated with a single iteration number.
            
            All of the environment data before self.cur_i
            has already been recorded.'''
        if iteration is not None: self.cur_iter = iteration
        try:
            cur_j = 1+self.cur_i+ np.nonzero(self.vl['Iter num'][self.cur_i:] == self.cur_iter)[0][-1]
        except:
            # There is no iteration with that value
            self.cur_iter += 1
            return [np.NAN, np.NAN, np.NAN, np.NAN]
        cur_x = self.vl['xs'][self.cur_i:cur_j]
        cur_y = self.vl['ys'][self.cur_i:cur_j]
        cur_vx = self.vl['vxs'][self.cur_i:cur_j]
        cur_vy = self.vl['vys'][self.cur_i:cur_j]
        self.cur_iter += 1
        self.cur_i = cur_j

        return (cur_x, cur_y, cur_vx, cur_vy)
    
    def draw_HMM_sectors(self):
        return
        for i in range(self.HMM.cll_p_sd):
            curx = self.HMM.xrange[0]+i*self.HMM.dx
            cury = self.HMM.yrange[0]+i*self.HMM.dy
            self.ax_env.plot([curx,curx],[0,self.maxy],'k')
            self.ax_env.plot([0,self.maxx],[cury,cury], 'k')

        
    def draw_plc_flds(self):
        return
        clrs = ['b','g']
        legend_widgets = []
        for i, plc_flds in zip(range(len(self.WR.contexts)),self.WR.contexts.values()):
            added = False
            for plc_fld in plc_flds:
                circ = Circle([plc_fld.x,plc_fld.y], plc_fld.r, color=clrs[i])
                self.ax_env.add_patch(circ)
                
                if not added:
                    legend_widgets.append(circ)
                    added=True
        self.ax.legend(legend_widgets, ('counterclockwise','clockwise'),'lower right')
    
    def draw(self, xs,ys,vxs,vys):
        ''' Display the environment data to the window.
        
            The environment data are inputs. '''
        
        if np.any(np.isnan(xs)):
            return
        
        # Display how far along in the animation we are
        self.iters.set_text('%i/%i'%(self.cur_iter,self.max_iter))
        
        # Begin the drawing process
        self.canvas.restore_region(self.background)
        
        # Calculate and draw rat's physical position
        x = xs[-1]; y=ys[-1]; vx=vxs[-1]; vy=vys[-1]
        self.x_hist.extend(xs)
        self.y_hist.extend(ys)
        self.pos.set_data(self.x_hist,self.y_hist)
        
        # Adjust velocity vector
        if vx != 0 or vy != 0: 
            self.vel.set_positions([x, y], [x+vx,y+vy])

        # Adjust radius line
        #self.radius.set_data([self.cntr_x,x],[self.cntr_y,y])

        # Calculate physical orientation, display it, and compare with
        #  virmenLog's orientatino assessment
        cur_orientation = self.is_clockwise(x,y,vx,vy)
        if  cur_orientation == 1:
            self.clockcounter.set_text('Clockwise')
        else:
            self.clockcounter.set_text('Counterclockwise')

        # Adjust the location  of the rat's chased target
        target_x = self.vl['txs'][self.cur_i]
        target_y = self.vl['tys'][self.cur_i]
        self.target.center = [target_x,target_y]

        # Make a context prediction
        try:
            self._make_prediction(self.is_clockwise(x,y,vx,vy))
        except:
            pass
            #logging.warning('Make prediction failed.')

        # Update the drawing window
        for itm in [self.pos, self.vel, #self.radius,
                    self.clockcounter,self.iters, 
                    self.predicted_counter, self.target]:
            self.ax.draw_artist(itm)
        self.canvas.blit(self.ax.bbox)

    def is_clockwise(self,x,y,vx,vy):
        ''' Determines if motion is clockwise around the center
            of the room, which is [0, MAXX] x [0, MAXY] 
            
            Output mapped to {-1,1} to conform with vl['Task'] labels.'''
        cross_prod = (x-self.cntr_x)*vy - (y-self.cntr_y)*vx
        clockwise = 2*(cross_prod>0)-1
        return clockwise
Beispiel #52
0
def draw_networkx_edges(G,
                        pos,
                        edgelist=None,
                        width=1.0,
                        edge_color="k",
                        style="solid",
                        alpha=None,
                        arrowstyle="-|>",
                        arrowsize=10,
                        edge_cmap=None,
                        edge_vmin=None,
                        edge_vmax=None,
                        ax=None,
                        arrows=True,
                        label=None,
                        node_size=300,
                        nodelist=None,
                        node_shape="o",
                        connectionstyle=None,
                        **kwds):
    """Draw the edges of the graph G.

    This draws only the edges of the graph G.

    Parameters
    ----------
    G : graph
       A networkx graph

    pos : dictionary
       A dictionary with nodes as keys and positions as values.
       Positions should be sequences of length 2.

    edgelist : collection of edge tuples
       Draw only specified edges(default=G.edges())

    width : float, or array of floats
       Line width of edges (default=1.0)

    edge_color : color or array of colors (default='k')
       Edge color. Can be a single color or a sequence of colors with the same
       length as edgelist. Color can be string, or rgb (or rgba) tuple of
       floats from 0-1. If numeric values are specified they will be
       mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.

    style : string
       Edge line style (default='solid') (solid|dashed|dotted,dashdot)

    alpha : float
       The edge transparency (default=None)

    edge_ cmap : Matplotlib colormap
       Colormap for mapping intensities of edges (default=None)

    edge_vmin,edge_vmax : floats
       Minimum and maximum for edge colormap scaling (default=None)

    ax : Matplotlib Axes object, optional
       Draw the graph in the specified Matplotlib axes.

    arrows : bool, optional (default=True)
       For directed graphs, if True draw arrowheads.
       Note: Arrows will be the same color as edges.

    arrowstyle : str, optional (default='-|>')
       For directed graphs, choose the style of the arrow heads.
       See :py:class: `matplotlib.patches.ArrowStyle` for more
       options.

    arrowsize : int, optional (default=10)
       For directed graphs, choose the size of the arrow head head's length and
       width. See :py:class: `matplotlib.patches.FancyArrowPatch` for attribute
       `mutation_scale` for more info.

    connectionstyle : str, optional (default=None)
       Pass the connectionstyle parameter to create curved arc of rounding
       radius rad. For example, connectionstyle='arc3,rad=0.2'.
       See :py:class: `matplotlib.patches.ConnectionStyle` and
       :py:class: `matplotlib.patches.FancyArrowPatch` for more info.

    label : [None| string]
       Label for legend

    Returns
    -------
    matplotlib.collection.LineCollection
        `LineCollection` of the edges

    list of matplotlib.patches.FancyArrowPatch
        `FancyArrowPatch` instances of the directed edges

    Depending whether the drawing includes arrows or not.

    Notes
    -----
    For directed graphs, arrows are drawn at the head end.  Arrows can be
    turned off with keyword arrows=False. Be sure to include `node_size` as a
    keyword argument; arrows are drawn considering the size of nodes.

    Examples
    --------
    >>> G = nx.dodecahedral_graph()
    >>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))

    >>> G = nx.DiGraph()
    >>> G.add_edges_from([(1, 2), (1, 3), (2, 3)])
    >>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
    >>> alphas = [0.3, 0.4, 0.5]
    >>> for i, arc in enumerate(arcs):  # change alpha values of arcs
    ...     arc.set_alpha(alphas[i])

    Also see the NetworkX drawing examples at
    https://networkx.github.io/documentation/latest/auto_examples/index.html

    See Also
    --------
    draw()
    draw_networkx()
    draw_networkx_nodes()
    draw_networkx_labels()
    draw_networkx_edge_labels()
    """
    try:
        import matplotlib
        import matplotlib.pyplot as plt
        import matplotlib.cbook as cb
        from matplotlib.colors import colorConverter, Colormap, Normalize
        from matplotlib.collections import LineCollection
        from matplotlib.patches import FancyArrowPatch
        import numpy as np
    except ImportError:
        raise ImportError("Matplotlib required for draw()")
    except RuntimeError:
        print("Matplotlib unable to open display")
        raise

    if ax is None:
        ax = plt.gca()

    if edgelist is None:
        edgelist = list(G.edges())

    if not edgelist or len(edgelist) == 0:  # no edges!
        return None

    if nodelist is None:
        nodelist = list(G.nodes())

    # FancyArrowPatch handles color=None different from LineCollection
    if edge_color is None:
        edge_color = "k"

    # set edge positions
    edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])

    # Check if edge_color is an array of floats and map to edge_cmap.
    # This is the only case handled differently from matplotlib
    if (cb.iterable(edge_color) and (len(edge_color) == len(edge_pos))
            and np.alltrue([isinstance(c, Number) for c in edge_color])):
        if edge_cmap is not None:
            assert isinstance(edge_cmap, Colormap)
        else:
            edge_cmap = plt.get_cmap()
        if edge_vmin is None:
            edge_vmin = min(edge_color)
        if edge_vmax is None:
            edge_vmax = max(edge_color)
        color_normal = Normalize(vmin=edge_vmin, vmax=edge_vmax)
        edge_color = [edge_cmap(color_normal(e)) for e in edge_color]

    if not G.is_directed() or not arrows:
        edge_collection = LineCollection(
            edge_pos,
            colors=edge_color,
            linewidths=width,
            antialiaseds=(1, ),
            linestyle=style,
            transOffset=ax.transData,
            alpha=alpha,
        )

        edge_collection.set_zorder(1)  # edges go behind nodes
        edge_collection.set_label(label)
        ax.add_collection(edge_collection)

        return edge_collection

    arrow_collection = None

    if G.is_directed() and arrows:
        # Note: Waiting for someone to implement arrow to intersection with
        # marker.  Meanwhile, this works well for polygons with more than 4
        # sides and circle.

        def to_marker_edge(marker_size, marker):
            if marker in "s^>v<d":  # `large` markers need extra space
                return np.sqrt(2 * marker_size) / 2
            else:
                return np.sqrt(marker_size) / 2

        # Draw arrows with `matplotlib.patches.FancyarrowPatch`
        arrow_collection = []
        mutation_scale = arrowsize  # scale factor of arrow head

        # FancyArrowPatch doesn't handle color strings
        arrow_colors = colorConverter.to_rgba_array(edge_color, alpha)
        for i, (src, dst) in enumerate(edge_pos):
            x1, y1 = src
            x2, y2 = dst
            shrink_source = 0  # space from source to tail
            shrink_target = 0  # space from  head to target
            if cb.iterable(node_size):  # many node sizes
                src_node, dst_node = edgelist[i][:2]
                index_node = nodelist.index(dst_node)
                marker_size = node_size[index_node]
                shrink_target = to_marker_edge(marker_size, node_shape)
            else:
                shrink_target = to_marker_edge(node_size, node_shape)

            if cb.iterable(arrow_colors):
                if len(arrow_colors) == len(edge_pos):
                    arrow_color = arrow_colors[i]
                elif len(arrow_colors) == 1:
                    arrow_color = arrow_colors[0]
                else:  # Cycle through colors
                    arrow_color = arrow_colors[i % len(arrow_colors)]
            else:
                arrow_color = edge_color

            if cb.iterable(width):
                if len(width) == len(edge_pos):
                    line_width = width[i]
                else:
                    line_width = width[i % len(width)]
            else:
                line_width = width

            arrow = FancyArrowPatch(
                (x1, y1),
                (x2, y2),
                arrowstyle=arrowstyle,
                shrinkA=shrink_source,
                shrinkB=shrink_target,
                mutation_scale=mutation_scale,
                color=arrow_color,
                linewidth=line_width,
                connectionstyle=connectionstyle,
                zorder=1,
            )  # arrows go behind nodes

            # There seems to be a bug in matplotlib to make collections of
            # FancyArrowPatch instances. Until fixed, the patches are added
            # individually to the axes instance.
            arrow_collection.append(arrow)
            ax.add_patch(arrow)

    # update view
    minx = np.amin(np.ravel(edge_pos[:, :, 0]))
    maxx = np.amax(np.ravel(edge_pos[:, :, 0]))
    miny = np.amin(np.ravel(edge_pos[:, :, 1]))
    maxy = np.amax(np.ravel(edge_pos[:, :, 1]))

    w = maxx - minx
    h = maxy - miny
    padx, pady = 0.05 * w, 0.05 * h
    corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady)
    ax.update_datalim(corners)
    ax.autoscale_view()

    plt.tick_params(
        axis="both",
        which="both",
        bottom=False,
        left=False,
        labelbottom=False,
        labelleft=False,
    )

    return arrow_collection
Beispiel #53
0
    def asteroids_plot(self,
                       image_path=None,
                       ra=None,
                       dec=None,
                       odate=None,
                       time_travel=1,
                       radi=6,
                       max_mag=20.0,
                       circle_color='yellow',
                       arrow_color='red',
                       invert_yaxis="True"):
        """
        Source plot module.
        @param image_path: data part of the FITS image
        @type image_path: numpy array
        @param ra: RA coordinate of target area.
        @type ra: str in "HH MM SS"
        @param dec: DEC coordinate of target area
        @type dec: str in "+DD MM SS"
        @param radi: Radius in arcmin.
        @type radi: float
        @param odate: Ephemeris date of observation in date
        @type odate: "2017-08-15T19:50:00.95" format in str
        @param time_travel: Jump into time after given date (in hour).
        @type time_travel: float
        @param max_mag: Limit magnitude to be queried object(s)
        @type max_mag: float
        @param circle_color: Color of the asteroids marks
        @type circle_color: str
        @param arrow_color: Color of the asteroids direction marks
        @type arrow_color: str
        @param invert_yaxis: invert y axis or not.
        @type invert_yaxis: bool
        @returns: boolean
        """

        from .catalog import Query

        # filename = get_pkg_data_filename(image_path)
        rcParams['figure.figsize'] = [10., 8.]
        # rcParams.update({'font.size': 10})

        if image_path:
            hdu = fits.open(image_path)[0]
        elif not image_path and ra and dec and odate:
            co = coordinates.SkyCoord('{0} {1}'.format(ra, dec),
                                      unit=(u.hourangle, u.deg),
                                      frame='icrs')
            print('Target Coordinates:', co.to_string(style='hmsdms', sep=':'),
                  'in {0} arcmin'.format(radi))
            try:
                server_img = SkyView.get_images(position=co,
                                                survey=['DSS'],
                                                radius=radi * u.arcmin)
                hdu = server_img[0][0]
            except Exception as e:
                print("SkyView could not get the image from DSS server.")
                print(e)
                raise SystemExit

        wcs = WCS(hdu.header)

        data = hdu.data.astype(float)

        bkg = sep.Background(data)
        # bkg_image = bkg.back()
        # bkg_rms = bkg.rms()
        data_sub = data - bkg
        m, s = np.mean(data_sub), np.std(data_sub)

        ax = plt.subplot(projection=wcs)

        plt.imshow(data_sub,
                   interpolation='nearest',
                   cmap='gray',
                   vmin=m - s,
                   vmax=m + s,
                   origin='lower')
        ax.coords.grid(True, color='white', ls='solid')
        ax.coords[0].set_axislabel('Galactic Longitude')
        ax.coords[1].set_axislabel('Galactic Latitude')

        overlay = ax.get_coords_overlay('icrs')
        overlay.grid(color='white', ls='dotted')
        overlay[0].set_axislabel('Right Ascension (ICRS)')
        overlay[1].set_axislabel('Declination (ICRS)')

        sb = Query()
        ac = AstCalc()
        if image_path:
            fo = FitsOps(image_path)
            if not odate:
                odate = fo.get_header('date-obs')
            else:
                odate = odate
            ra_dec = ac.center_finder(image_path, wcs_ref=True)
        elif not image_path and ra and dec and odate:
            odate = odate
            ra_dec = [co.ra, co.dec]

        request0 = sb.find_skybot_objects(odate,
                                          ra_dec[0].degree,
                                          ra_dec[1].degree,
                                          radius=radi)

        if request0[0]:
            asteroids = request0[1]
        elif request0[0] is False:
            print(request0[1])
            raise SystemExit

        request1 = sb.find_skybot_objects(odate,
                                          ra_dec[0].degree,
                                          ra_dec[1].degree,
                                          radius=float(radi),
                                          time_travel=time_travel)

        if request1[0]:
            asteroids_after = request1[1]
        elif request1[0] is False:
            print(request1[1])
            raise SystemExit

        for i in range(len(asteroids)):
            if float(asteroids['m_v'][i]) <= max_mag:
                c = coordinates.SkyCoord('{0} {1}'.format(
                    asteroids['ra(h)'][i], asteroids['dec(deg)'][i]),
                                         unit=(u.hourangle, u.deg),
                                         frame='icrs')

                c_after = coordinates.SkyCoord('{0} {1}'.format(
                    asteroids_after['ra(h)'][i],
                    asteroids_after['dec(deg)'][i]),
                                               unit=(u.hourangle, u.deg),
                                               frame='icrs')

                r = FancyArrowPatch((c.ra.degree, c.dec.degree),
                                    (c_after.ra.degree, c_after.dec.degree),
                                    arrowstyle='->',
                                    mutation_scale=10,
                                    transform=ax.get_transform('icrs'))

                p = Circle((c.ra.degree, c.dec.degree),
                           0.005,
                           edgecolor=circle_color,
                           facecolor='none',
                           transform=ax.get_transform('icrs'))
                ax.text(c.ra.degree,
                        c.dec.degree - 0.007,
                        asteroids['name'][i],
                        size=12,
                        color='black',
                        ha='center',
                        va='center',
                        transform=ax.get_transform('icrs'))

                r.set_facecolor('none')
                r.set_edgecolor(arrow_color)
                ax.add_patch(p)
                ax.add_patch(r)
        # plt.gca().invert_xaxis()
        if invert_yaxis == "True":
            plt.gca().invert_yaxis()
        plt.show()
        print(asteroids)
        return True
Beispiel #54
0
 def __init__(self, xs, ys, zs, *args, **kwargs):
     FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
     self._verts3d = xs, ys, zs
def display_bicycle_wheels(rear_wheel, front_wheel, theta):               
    # Initialize figure
    fig = plt.figure(figsize=(5, 5))
    ax = plt.gca()
    ax.set_xlim([0,4])
    ax.set_ylim([0,4])
    ax.tick_params(axis='both', which='major', labelsize=7)
    plt.title('Overhead View')
    plt.xlabel('X (m)',weight='bold')
    plt.ylabel('Y (m)',weight='bold')

    ax.plot(0,0)
  
    rear_wheel_x = FancyArrowPatch((0,0), (0.4,0),
                                        mutation_scale=8,color='red')
    rear_wheel_y = FancyArrowPatch((0,0), (0,0.4),
                                        mutation_scale=8,color='red')

    front_wheel_x = FancyArrowPatch((0,0), (0.4,0),
                                        mutation_scale=8,color='blue') 
    front_wheel_y = FancyArrowPatch((0,0), (0,0.4),
                                        mutation_scale=8,color='blue')

    custom_lines = [Line2D([0], [0], color='red', lw=4),
                    Line2D([0], [0], color='blue', lw=4)]
    
    # Apply translation and rotation as specified by current robot state
    cos_theta, sin_theta = np.cos(theta), np.sin(theta)
    Tw_rear = np.eye(3)
    Tw_rear[0:2,2] = rear_wheel
    Tw_rear[0:2,0:2] = [[cos_theta,-sin_theta],[sin_theta,cos_theta]]
    Tw_rear_obj = transforms.Affine2D(Tw_rear)

    Tw_front = np.eye(3)
    Tw_front[0:2,2] = front_wheel
    Tw_front[0:2,0:2] = [[cos_theta,-sin_theta],[sin_theta,cos_theta]]
    Tw_front_obj = transforms.Affine2D(Tw_front)

    ax_trans = ax.transData
    
    rear_wheel_x.set_transform(Tw_rear_obj+ax_trans)
    rear_wheel_y.set_transform(rear_wheel_x.get_transform())
    ax.add_patch(rear_wheel_x)
    ax.add_patch(rear_wheel_y)

    front_wheel_x.set_transform(Tw_front_obj+ax_trans)
    front_wheel_y.set_transform(front_wheel_x.get_transform())
    ax.add_patch(front_wheel_x)
    ax.add_patch(front_wheel_y)

    ax.legend(custom_lines, ['Rear Wheel', 'Front Wheel']) 
        
Beispiel #56
0
class GraphArrow:
    def __init__(self,
                 angleA,
                 angleB,
                 r=1,
                 inner=False,
                 outer=False,
                 stretch_inner=0.8,
                 stretch_outer=1.1,
                 shrinkA=20,
                 shrinkB=20,
                 arrowstyle='-|>',
                 head_length=3,
                 head_width=2,
                 connectionstyle="arc3,rad=0.3",
                 outer_connectionstyle="arc3,rad=-0.3",
                 edgewidth=1,
                 edgecolor='k',
                 ax=None,
                 label=None,
                 labelpos=0.5,
                 label_facecolor='white',
                 label_edgecolor='white',
                 label_color='k',
                 xytext=None,
                 fontname='DejaVu Sans',
                 fontsize=10):
        self.angleA = angleA
        self.angleB = angleB
        self.r = r
        self.posA = np.array([np.cos(self.angleA), np.sin(self.angleA)])
        self.posB = np.array([np.cos(self.angleB), np.sin(self.angleB)])
        self.outer = outer
        self.stretch_outer = stretch_outer
        self.shrinkA = shrinkA
        self.shrinkB = shrinkB
        self.arrowstyle = arrowstyle
        self.head_length = head_length
        self.head_width = head_width
        self.connectionstyle = connectionstyle
        self.outer_connectionstyle = outer_connectionstyle
        self.edgewidth = edgewidth
        self.edgecolor = edgecolor
        self.ax = ax
        self.label = label
        self.labelpos = labelpos
        self.label_facecolor = label_facecolor
        self.label_edgecolor = label_edgecolor
        self.label_color = label_color
        self.inner = inner
        self.stretch_inner = stretch_inner
        self.xytext = xytext
        self.fontname = fontname
        self.fontsize = fontsize

    def draw(self, ax=None):
        self.ax = ax or self.ax or plt.gca()
        self.arrow = FancyArrowPatch(
            posA=(self.posA if not self.outer else
                  (self.posA * self.stretch_outer)) * self.r,
            posB=(self.posB if not self.outer else
                  (self.posB * self.stretch_outer)) * self.r,
            arrowstyle=ArrowStyle(self.arrowstyle,
                                  head_length=self.head_length,
                                  head_width=self.head_width),
            shrinkA=(self.shrinkA *
                     (self.stretch_outer**2 if self.outer else 1)),
            shrinkB=(self.shrinkB *
                     (self.stretch_outer**2 if self.outer else 1)),
            connectionstyle=self.connectionstyle
            if not self.outer else self.outer_connectionstyle,
            linewidth=self.edgewidth,
            color=self.edgecolor)
        self.ax.add_patch(self.arrow)

        if self.label:
            verts = self.arrow.get_path().vertices
            point = verts[1]
            norm = np.linalg.norm(point)
            self.ax.text(
                *((self.xytext if self.xytext is not None else point) *
                  (self.stretch_inner if self.inner else 1.12)),
                self.label,
                horizontalalignment='center',
                verticalalignment='center',
                bbox=dict(facecolor=self.label_facecolor,
                          edgecolor=self.label_edgecolor,
                          alpha=0),
                color=self.label_color,
                fontname=self.fontname,
                fontsize=self.fontsize)
Beispiel #57
0
 def __init__(self, xs, ys, zs, *args, **kwargs):
     FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
     self._verts3d = []
     for x, y, z in zip(xs, ys, zs):
         self._verts3d.append([[0, x], [0, y], [0, z]])