Example #1
0
def _offset(ax, x, y):
    """Provide offset in pixels

    Parameters
    ----------
    x : int
      Offset in pixels for x
    y : int
      Offset in pixels for y

    Idea borrowed from
     http://www.scipy.org/Cookbook/Matplotlib/Transformations
    but then heavily extended to be compatible with many
    reincarnations of matplotlib
    """
    d = dir(mlt)
    if "offset_copy" in d:
        # tested with python-matplotlib 0.98.3-5
        # ??? if pukes, might need to replace 2nd parameter from
        #     ax to ax.get_figure()
        return mlt.offset_copy(ax.transData, ax, x=x, y=y, units="dots")
    elif "BlendedAffine2D" in d:
        # some newer versions of matplotlib
        return ax.transData + mlt.Affine2D().translate(x, y)
    elif "blend_xy_sep_transform" in d:
        trans = mlt.blend_xy_sep_transform(ax.transData, ax.transData)
        # Now we set the offset in pixels
        trans.set_offset((x, y), mlt.identity_transform())
        return trans
    else:
        raise RuntimeError, "Lacking needed functions in matplotlib.transform " "for _offset. Please upgrade"
Example #2
0
def _offset(ax, x, y):
    """Provide offset in pixels

    Parameters
    ----------
    x : int
      Offset in pixels for x
    y : int
      Offset in pixels for y

    Idea borrowed from
     http://www.scipy.org/Cookbook/Matplotlib/Transformations
    but then heavily extended to be compatible with many
    reincarnations of matplotlib
    """
    d = dir(mlt)
    if 'offset_copy' in d:
        # tested with python-matplotlib 0.98.3-5
        # ??? if pukes, might need to replace 2nd parameter from
        #     ax to ax.get_figure()
        return mlt.offset_copy(ax.transData, ax, x=x, y=y, units='dots')
    elif 'BlendedAffine2D' in d:
        # some newer versions of matplotlib
        return ax.transData + \
               mlt.Affine2D().translate(x,y)
    elif 'blend_xy_sep_transform' in d:
        trans = mlt.blend_xy_sep_transform(ax.transData, ax.transData)
        # Now we set the offset in pixels
        trans.set_offset((x, y), mlt.identity_transform())
        return trans
    else:
        raise RuntimeError, \
              "Lacking needed functions in matplotlib.transform " \
              "for _offset. Please upgrade"
Example #3
0
    def __init__(self, ax, line):
        self.ax = ax
        ax.set_title('drag polygon around to test clipping')
        self.canvas = ax.figure.canvas
        self.line = line
        self.poly = RegularPolygon(
            (200, 200), numVertices=10, radius=100,
            facecolor='yellow', alpha=0.25,
            transform=transforms.identity_transform())

        ax.add_patch(self.poly)
        self.canvas.mpl_connect('button_press_event', self.onpress)
        self.canvas.mpl_connect('button_release_event', self.onrelease)
        self.canvas.mpl_connect('motion_notify_event', self.onmove)
        self.x, self.y = None, None
Example #4
0
assert( a.xy_tup(pnt) == (8,17) )


# change num to 4 and make sure the affine product is still right
num.set(4)
assert( a1.xy_tup(pnt) == (12,16) )
assert( a.xy_tup(pnt) == (16,65) )

# test affines with arithemtic sums of lazy values
val = num*(one + two)
a1 = Affine(one, zero, zero, val, num, val)
assert(a1.xy_tup(pnt) == (7, 60))

x = rand(20)
y = rand(20)
transform = identity_transform()
xout, yout = transform.seq_x_y(x,y)
assert((x,y) == transform.seq_x_y(x,y))


# test bbox transforms; transform the unit coordinate system to
# "display coords"
bboxin = unit_bbox()
ll = Point( Value(10),  Value(10) )
ur = Point( Value(200), Value(40) )
bboxout = Bbox(ll, ur)

transform = get_bbox_transform(bboxin, bboxout)

assert( transform.xy_tup( (0,0) )==(10, 10))
assert( transform.xy_tup( (1,1) )==(200, 40))
Example #5
0
 def get_transoffset(self):
     if self._transOffset is None:
         self._transOffset = transforms.identity_transform()
     return self._transOffset
Example #6
0
    def __init__(
            self,
            segments,  # Can be None.
            linewidths=None,
            colors=None,
            antialiaseds=None,
            linestyle='solid',
            offsets=None,
            transOffset=None,  #transforms.identity_transform(),
            norm=None,
            cmap=None,
            pickradius=5,
            **kwargs):
        """
        segments is a sequence of ( line0, line1, line2), where
        linen = (x0, y0), (x1, y1), ... (xm, ym), or the
        equivalent numpy array with two columns.
        Each line can be a different length.

        colors must be a tuple of RGBA tuples (eg arbitrary color
        strings, etc, not allowed).

        antialiaseds must be a sequence of ones or zeros

        linestyles is a string or dash tuple. Legal string values are
          solid|dashed|dashdot|dotted.  The dash tuple is (offset, onoffseq)
          where onoffseq is an even length tuple of on and off ink in points.

        If linewidths, colors_, or antialiaseds is None, they default to
        their rc params setting, in sequence form.

        If offsets and transOffset are not None, then
        offsets are transformed by transOffset and applied after
        the segments have been transformed to display coordinates.

        If offsets is not None but transOffset is None, then the
        offsets are added to the segments before any transformation.
        In this case, a single offset can be specified as offsets=(xo,yo),
        and this value will be
        added cumulatively to each successive segment, so as
        to produce a set of successively offset curves.

        norm = None,  # optional for ScalarMappable
        cmap = None,  # ditto

        pickradius is the tolerance for mouse clicks picking a line.  The
        default is 5 pt.

        The use of ScalarMappable is optional.  If the ScalarMappable
        matrix _A is not None (ie a call to set_array has been made), at
        draw time a call to scalar mappable will be made to set the colors.
        """

        Collection.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)

        if linewidths is None:
            linewidths = (mpl.rcParams['lines.linewidth'], )

        if colors is None:
            colors = (mpl.rcParams['lines.color'], )
        if antialiaseds is None:
            antialiaseds = (mpl.rcParams['lines.antialiased'], )

        self._colors = _colors.colorConverter.to_rgba_list(colors)
        self._aa = self._get_value(antialiaseds)
        self._lw = self._get_value(linewidths)
        self.set_linestyle(linestyle)
        self._uniform_offsets = None
        if offsets is not None:
            offsets = npy.asarray(offsets)
            if len(offsets.shape) == 1:
                offsets = offsets[npy.newaxis, :]  # Make it Nx2.
        if transOffset is None:
            if offsets is not None:
                self._uniform_offsets = offsets
                offsets = None
            transOffset = transforms.identity_transform()
        self._offsets = offsets
        self._transOffset = transOffset
        self.set_segments(segments)
        self.pickradius = pickradius
        self.update(kwargs)
Example #7
0
 def offset(ax, x, y):
     # This trick makes a shallow copy of ax.transData (but fails for polar plots):
     trans = blend_xy_sep_transform(ax.transData, ax.transData)
     # Now we set the offset in pixels
     trans.set_offset((x, y), identity_transform())
     return trans
Example #8
0
assert (a1.xy_tup(pnt) == (6, 8))
assert (a.xy_tup(pnt) == (8, 17))

# change num to 4 and make sure the affine product is still right
num.set(4)
assert (a1.xy_tup(pnt) == (12, 16))
assert (a.xy_tup(pnt) == (16, 65))

# test affines with arithemtic sums of lazy values
val = num * (one + two)
a1 = Affine(one, zero, zero, val, num, val)
assert (a1.xy_tup(pnt) == (7, 60))

x = rand(20)
y = rand(20)
transform = identity_transform()
xout, yout = transform.seq_x_y(x, y)
assert ((x, y) == transform.seq_x_y(x, y))

# test bbox transforms; transform the unit coordinate system to
# "display coords"
bboxin = unit_bbox()
ll = Point(Value(10), Value(10))
ur = Point(Value(200), Value(40))
bboxout = Bbox(ll, ur)

transform = get_bbox_transform(bboxin, bboxout)

assert (transform.xy_tup((0, 0)) == (10, 10))
assert (transform.xy_tup((1, 1)) == (200, 40))
assert (transform.xy_tup((0.5, 0.5)) == (105, 25))
 def offset(ax, x, y):
     # This trick makes a shallow copy of ax.transData (but fails for polar plots):
     trans = blend_xy_sep_transform(ax.transData, ax.transData)
     # Now we set the offset in pixels
     trans.set_offset((x,y), identity_transform())
     return trans
Example #10
0
 def __init__(self):
     self._transform = identity_transform()
Example #11
0
 def get_transoffset(self):
     if self._transOffset is None:
         self._transOffset = transforms.identity_transform()
     return self._transOffset
Example #12
0
    def __init__(self, segments,     # Can be None.
                 linewidths    = None,
                 colors       = None,
                 antialiaseds  = None,
                 linestyle = 'solid',
                 offsets = None,
                 transOffset = None,#transforms.identity_transform(),
                 norm = None,
                 cmap = None,
                 pickradius = 5,
                 **kwargs
                 ):
        """
        segments is a sequence of ( line0, line1, line2), where
        linen = (x0, y0), (x1, y1), ... (xm, ym), or the
        equivalent numpy array with two columns.
        Each line can be a different length.

        colors must be a tuple of RGBA tuples (eg arbitrary color
        strings, etc, not allowed).

        antialiaseds must be a sequence of ones or zeros

        linestyles is a string or dash tuple. Legal string values are
          solid|dashed|dashdot|dotted.  The dash tuple is (offset, onoffseq)
          where onoffseq is an even length tuple of on and off ink in points.

        If linewidths, colors_, or antialiaseds is None, they default to
        their rc params setting, in sequence form.

        If offsets and transOffset are not None, then
        offsets are transformed by transOffset and applied after
        the segments have been transformed to display coordinates.

        If offsets is not None but transOffset is None, then the
        offsets are added to the segments before any transformation.
        In this case, a single offset can be specified as offsets=(xo,yo),
        and this value will be
        added cumulatively to each successive segment, so as
        to produce a set of successively offset curves.

        norm = None,  # optional for ScalarMappable
        cmap = None,  # ditto

        pickradius is the tolerance for mouse clicks picking a line.  The
        default is 5 pt.

        The use of ScalarMappable is optional.  If the ScalarMappable
        matrix _A is not None (ie a call to set_array has been made), at
        draw time a call to scalar mappable will be made to set the colors.
        """

        Collection.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)

        if linewidths is None   :
            linewidths   = (mpl.rcParams['lines.linewidth'], )

        if colors is None       :
            colors       = (mpl.rcParams['lines.color'],)
        if antialiaseds is None :
            antialiaseds = (mpl.rcParams['lines.antialiased'], )

        self._colors = _colors.colorConverter.to_rgba_list(colors)
        self._aa = self._get_value(antialiaseds)
        self._lw = self._get_value(linewidths)
        self.set_linestyle(linestyle)
        self._uniform_offsets = None
        if offsets is not None:
            offsets = npy.asarray(offsets)
            if len(offsets.shape) == 1:
                offsets = offsets[npy.newaxis,:]  # Make it Nx2.
        if transOffset is None:
            if offsets is not None:
                self._uniform_offsets = offsets
                offsets = None
            transOffset = transforms.identity_transform()
        self._offsets = offsets
        self._transOffset = transOffset
        self.set_segments(segments)
        self.pickradius = pickradius
        self.update(kwargs)
Example #13
0
 def __init__(self):
     self._transform = identity_transform()
    def __init__(self, annotated_box_ls, y=0, width=0.001, linewidths = None, box_line_widths = None,
        colors = None,
        antialiaseds = None,
        linestyle = 'solid',
        offsets = None,
        transOffset = None,#transforms.identity_transform(),
        norm = None,
        cmap = None,
        picker=False, pickradius=5, alpha=None, strand=None, facecolors=None, edgecolors=None, rotate_xy=False, \
        **kwargs):
        """
		2008-10-01
			block_type='exon' has both facecolor and edgecolor red.
			block_type='intron' has no facecolor and black edgecolor.
			arguments edgecolors and facecolors in __init__() could overwrite the ones that generated based on the box_type.
		2008-10-01
			the annotated_box_ls is a list of (start, stop, box_type, is_translated, ...)
			box_type = 'exon' or 'intron' and is_translated= 0 or 1. They are optional. Default is box_type ='intron', is_translated=0.
		2008-09-26
			linewidths controls the width of lines connecting exons or the arrow line, could be a list of floats of just one float.
			box_line_widths controls the width of the boundaries of exon boxes
		"""
        #handle parameters for LineCollection
        if linewidths is None:
            linewidths = (mpl.rcParams['lines.linewidth'], )
        if box_line_widths is None:
            box_line_widths = (mpl.rcParams['lines.linewidth'], )
        if colors is None:
            colors = (mpl.rcParams['lines.color'], )
        if antialiaseds is None:
            antialiaseds = (mpl.rcParams['lines.antialiased'], )

        self._colors = [
            _colors.colorConverter.to_rgba(color, alpha) for color in colors
        ]  #2008-10-26 use to_rgba() instead of to_rgba_list() because the latter is not present in matplotlib 0.98.3
        self._aa = self._get_value(antialiaseds)
        self._lw = self._get_value(linewidths)
        self.set_linestyle(linestyle)
        self._uniform_offsets = None
        if offsets is not None:
            offsets = asarray(offsets)
            if len(offsets.shape) == 1:
                offsets = offsets[numpy.newaxis, :]  # Make it Nx2.
        if transOffset is None:
            if offsets is not None:
                self._uniform_offsets = offsets
                offsets = None
            if hasattr(transforms, 'identity_transform'):
                transOffset = transforms.identity_transform(
                )  #matplotlib 0.91.2
            elif hasattr(transforms, 'IdentityTransform'):
                transOffset = transforms.IdentityTransform(
                )  #matplotlib 0.98.3
        self._offsets = offsets
        self._transOffset = transOffset
        self.pickradius = pickradius

        #handle parameters for PolyCollection
        verts_ls = []
        segment_ls = []
        no_of_blocks = len(annotated_box_ls)
        verts_colors = []
        _edgecolors = []
        for i in range(no_of_blocks):
            this_block = annotated_box_ls[i]
            block_start, block_end = this_block[:2]
            block_type = 'intron'
            is_translated = 0
            if len(this_block) >= 3:
                block_type = this_block[2]
            if len(this_block) >= 4:
                is_translated = int(this_block[3])
            if block_type == 'exon':
                verts = [[block_start, width / 2.0 + y],
                         [block_start, -width / 2.0 + y],
                         [block_end, -width / 2.0 + y],
                         [block_end, width / 2.0 + y]]
                if rotate_xy:
                    verts = [[row[1], row[0]] for row in verts]
                verts_ls.append(verts)
                if is_translated == 1:
                    verts_colors.append('r')
                    _edgecolors.append('r')  #same edge color
                else:
                    verts_colors.append('w')  #no face color
                    _edgecolors.append('k')
            else:
                if rotate_xy:
                    segment_ls.append([(y, block_start), (y, block_end)])
                else:
                    segment_ls.append([(block_start, y), (block_end, y)])
        if not facecolors:
            facecolors = verts_colors
        if not edgecolors:
            edgecolors = _edgecolors
        #add an arrow
        box_start = annotated_box_ls[0][0]
        box_end = annotated_box_ls[-1][1]
        if strand is not None:
            arrow_length = abs(box_start - box_end) / 4
            try:
                strand = int(strand)
            except:
                pass
            if strand == 1 or strand == 'plus':
                arrow_offset = -arrow_length
                arrow_end = box_end
            elif strand == -1 or strand == 'minus':
                arrow_offset = arrow_length
                arrow_end = box_start
            else:  #can't tell which strand
                arrow_offset = 0
                arrow_end = box_end
            if rotate_xy:
                segment_ls.append([(y + width, arrow_end + arrow_offset),
                                   (y + width / 2.0, arrow_end)])
            else:
                segment_ls.append([(arrow_end + arrow_offset, y + width),
                                   (arrow_end, y + width / 2.0)])
        self._segments = segment_ls
        self.set_segments(segment_ls)
        self._verts = verts
        #self.set_alpha(alpha)
        PolyCollection.__init__(self,
                                verts_ls,
                                linewidths=box_line_widths,
                                antialiaseds=antialiaseds,
                                edgecolors=edgecolors,
                                **kwargs)
        self._facecolors = [
            _colors.colorConverter.to_rgba(facecolor, alpha=alpha)
            for facecolor in facecolors
        ]  #in PolyCollection.__init__(), it doesn't handle alpha
        self._picker = picker  #to enable picker_event. PolyCollection's ancestor PatchCollection (collection.py) defines a method 'contains()'.
        #Artist.pick() (in artist.py) calls pickable(), which checks self._picker, first to see whether this artist is pickable. then it calls picker() or contains().
        self.update(kwargs)
Example #15
0
	def __init__(self, annotated_box_ls, y=0, width=0.001, linewidths = None, box_line_widths = None,
				 colors	= None,
				 antialiaseds = None,
				 linestyle = 'solid',
				 offsets = None,
				 transOffset = None,#transforms.identity_transform(),
				 norm = None,
				 cmap = None,
				 picker=False, pickradius=5, alpha=None, strand=None, facecolors=None, edgecolors=None, rotate_xy=False, \
				 **kwargs):
		"""
		2008-10-01
			block_type='exon' has both facecolor and edgecolor red.
			block_type='intron' has no facecolor and black edgecolor.
			arguments edgecolors and facecolors in __init__() could overwrite the ones that generated based on the box_type.
		2008-10-01
			the annotated_box_ls is a list of (start, stop, box_type, is_translated, ...)
			box_type = 'exon' or 'intron' and is_translated= 0 or 1. They are optional. Default is box_type ='intron', is_translated=0.
		2008-09-26
			linewidths controls the width of lines connecting exons or the arrow line, could be a list of floats of just one float.
			box_line_widths controls the width of the boundaries of exon boxes
		"""
		#handle parameters for LineCollection
		if linewidths is None   :
			linewidths   = (mpl.rcParams['lines.linewidth'], )
		if box_line_widths is None   :
			box_line_widths   = (mpl.rcParams['lines.linewidth'], )
		if colors is None	   :
			colors	   = (mpl.rcParams['lines.color'],)
		if antialiaseds is None :
			antialiaseds = (mpl.rcParams['lines.antialiased'], )
		
		self._colors = [_colors.colorConverter.to_rgba(color, alpha) for color in colors]	#2008-10-26 use to_rgba() instead of to_rgba_list() because the latter is not present in matplotlib 0.98.3
		self._aa = self._get_value(antialiaseds)
		self._lw = self._get_value(linewidths)
		self.set_linestyle(linestyle)
		self._uniform_offsets = None
		if offsets is not None:
			offsets = npy.asarray(offsets)
			if len(offsets.shape) == 1:
				offsets = offsets[npy.newaxis,:]  # Make it Nx2.
		if transOffset is None:
			if offsets is not None:
				self._uniform_offsets = offsets
				offsets = None
			if hasattr(transforms, 'identity_transform'):
				transOffset = transforms.identity_transform()	#matplotlib 0.91.2
			elif hasattr(transforms, 'IdentityTransform'):
				transOffset = transforms.IdentityTransform()	#matplotlib 0.98.3
		self._offsets = offsets
		self._transOffset = transOffset
		self.pickradius = pickradius
		
		#handle parameters for PolyCollection
		verts_ls = []
		segment_ls = []
		no_of_blocks = len(annotated_box_ls)
		verts_colors = []
		_edgecolors = []
		for i in range(no_of_blocks):
			this_block = annotated_box_ls[i]
			block_start, block_end = this_block[:2]
			block_type = 'intron'
			is_translated = 0
			if len(this_block)>=3:
				block_type = this_block[2]
			if len(this_block)>=4:
				is_translated = int(this_block[3])
			if block_type=='exon':
				verts = [[block_start, width/2.0+y], [block_start, -width/2.0+y], [block_end, -width/2.0+y], [block_end, width/2.0+y]]
				if rotate_xy:
					verts = [[row[1], row[0]] for row in verts]
				verts_ls.append(verts)
				if is_translated==1:
					verts_colors.append('r')
					_edgecolors.append('r')	#same edge color
				else:
					verts_colors.append('w')	#no face color
					_edgecolors.append('k')
			else:
				if rotate_xy:
					segment_ls.append([(y, block_start), (y, block_end)])
				else:
					segment_ls.append([(block_start, y), (block_end,y)])
		if not facecolors:
			facecolors = verts_colors
		if not edgecolors:
			edgecolors = _edgecolors
		#add an arrow
		box_start = annotated_box_ls[0][0]
		box_end = annotated_box_ls[-1][1]
		if strand is not None:
			arrow_length = abs(box_start-box_end)/4
			try:
				strand = int(strand)
			except:
				pass
			if strand==1 or strand=='plus':
				arrow_offset = -arrow_length
				arrow_end = box_end
			elif strand==-1 or strand=='minus':
				arrow_offset = arrow_length
				arrow_end = box_start
			else:	#can't tell which strand
				arrow_offset = 0
				arrow_end = box_end
			if rotate_xy:
				segment_ls.append([( y+width, arrow_end+arrow_offset), (y+width/2.0, arrow_end)])
			else:
				segment_ls.append([(arrow_end+arrow_offset, y+width), (arrow_end,y+width/2.0)])
		self._segments = segment_ls
		self.set_segments(segment_ls)
		self._verts = verts
		#self.set_alpha(alpha)
		PolyCollection.__init__(self, verts_ls, linewidths=box_line_widths, antialiaseds=antialiaseds, edgecolors=edgecolors, **kwargs)
		self._facecolors  = [_colors.colorConverter.to_rgba(facecolor, alpha=alpha) for facecolor in facecolors]	#in PolyCollection.__init__(), it doesn't handle alpha
		self._picker = picker	#to enable picker_event. PolyCollection's ancestor PatchCollection (collection.py) defines a method 'contains()'.
			#Artist.pick() (in artist.py) calls pickable(), which checks self._picker, first to see whether this artist is pickable. then it calls picker() or contains().
		self.update(kwargs)