示例#1
0
    def _draw_mathtext(self, gc, x, y, s, prop, angle):
        if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name())
       # mathtext using the gtk/gdk method

        if numx.which[0] == "numarray":
            warnings.warn("_draw_mathtext() currently works for numpy, but "
                          "not numarray")
            return

        if not HAVE_CAIRO_NUMPY:
            warnings.warn("cairo with Numeric support is required for "
                          "_draw_mathtext()")
            return

        size = prop.get_size_in_points()
        width, height, fonts = math_parse_s_ft2font(
            s, self.dpi.get(), size)

        if angle==90:
            width, height = height, width
            x -= width
        y -= height

        imw, imh, s = fonts[0].image_as_str()
        N = imw*imh

        # a numpixels by num fonts array
        Xall = numx.zeros((N,len(fonts)), typecode=numx.UInt8)

        for i, font in enumerate(fonts):
            if angle == 90:
                font.horiz_image_to_vert_image() # <-- Rotate
            imw, imh, s = font.image_as_str()
            Xall[:,i] = numx.fromstring(s, numx.UInt8)

        # get the max alpha at each pixel
        Xs = numx.mlab.max (Xall,1)

        # convert it to it's proper shape
        Xs.shape = imh, imw

        pa = numx.zeros(shape=(imh,imw,4), typecode=numx.UInt8)
        rgb = gc.get_rgb()
        pa[:,:,0] = int(rgb[0]*255)
        pa[:,:,1] = int(rgb[1]*255)
        pa[:,:,2] = int(rgb[2]*255)
        pa[:,:,3] = Xs

        # works for numpy pa, not a numarray pa
        surface = cairo.ImageSurface.create_for_array (pa)
        gc.ctx.set_source_surface (surface, x, y)
        gc.ctx.paint()
示例#2
0
    def _draw_mathtext(self, gc, x, y, s, prop, angle):
        if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name())
        # mathtext using the gtk/gdk method

        if numx.which[0] == "numarray":
            warnings.warn("_draw_mathtext() currently works for numpy, but "
                          "not numarray")
            return

        if not HAVE_CAIRO_NUMPY:
            warnings.warn("cairo with Numeric support is required for "
                          "_draw_mathtext()")
            return

        size = prop.get_size_in_points()
        width, height, fonts = math_parse_s_ft2font(s, self.dpi.get(), size)

        if angle == 90:
            width, height = height, width
            x -= width
        y -= height

        imw, imh, s = fonts[0].image_as_str()
        N = imw * imh

        # a numpixels by num fonts array
        Xall = numx.zeros((N, len(fonts)), typecode=numx.UInt8)

        for i, font in enumerate(fonts):
            if angle == 90:
                font.horiz_image_to_vert_image()  # <-- Rotate
            imw, imh, s = font.image_as_str()
            Xall[:, i] = numx.fromstring(s, numx.UInt8)

        # get the max alpha at each pixel
        Xs = numx.mlab.max(Xall, 1)

        # convert it to it's proper shape
        Xs.shape = imh, imw

        pa = numx.zeros(shape=(imh, imw, 4), typecode=numx.UInt8)
        rgb = gc.get_rgb()
        pa[:, :, 0] = int(rgb[0] * 255)
        pa[:, :, 1] = int(rgb[1] * 255)
        pa[:, :, 2] = int(rgb[2] * 255)
        pa[:, :, 3] = Xs

        # works for numpy pa, not a numarray pa
        surface = cairo.ImageSurface.create_for_array(pa)
        gc.ctx.set_source_surface(surface, x, y)
        gc.ctx.paint()
示例#3
0
    def _draw_mathtext(self, gc, x, y, s, prop, angle):
        if DEBUG: print 'backend_cairo.RendererCairo.%s()' % _fn_name()
       # mathtext using the gtk/gdk method

        if numerix.which[0] == "numarray":
            warnings.warn("_draw_mathtext() currently works for numpy, but not numarray")
            return

        if not HAVE_CAIRO_NUMPY:
            warnings.warn("cairo.numpy module required for _draw_mathtext()")
            return

        size = prop.get_size_in_points()
        width, height, fonts = math_parse_s_ft2font(
            s, self.dpi.get(), size)

        if angle==90:
            width, height = height, width
            x -= width
        y -= height

        imw, imh, s = fonts[0].image_as_str()
        N = imw*imh

        # a numpixels by num fonts array
        Xall = zeros((N,len(fonts)), typecode=UInt8)

        for i, font in enumerate(fonts):
            if angle == 90:
                font.horiz_image_to_vert_image() # <-- Rotate
            imw, imh, s = font.image_as_str()
            Xall[:,i] = fromstring(s, UInt8)  

        # get the max alpha at each pixel
        Xs = numerix.mlab.max(Xall,1)

        # convert it to it's proper shape
        Xs.shape = imh, imw

        pa = zeros(shape=(imh,imw,4), typecode=UInt8)
        rgb = gc.get_rgb()
        pa[:,:,0] = int(rgb[0]*255)
        pa[:,:,1] = int(rgb[1]*255)
        pa[:,:,2] = int(rgb[2]*255)
        pa[:,:,3] = Xs

        # works for numpy pa, not a numarray pa
        surface = cairo.numpy.surface_create_for_array(pa)
        gc.ctx.translate (x,y)
        gc.ctx.show_surface (surface, imw, imh)
示例#4
0
 def _process_values(self, b=None):
     """
     Set the _boundaries and _values attributes based on
     the input boundaries and values.  Input boundaries can
     be self.boundaries or the argument b.
     """
     if b is None:
         b = self.boundaries
     if b is not None:
         self._boundaries = nx.array(b)
         if self.values is None:
             self._values = 0.5 * (self._boundaries[:-1] + self._boundaries[1:])
             if isinstance(self.norm, colors.no_norm):
                 self._values = (self._values + 0.00001).astype(nx.Int16)
             return
         self._values = nx.array(self.values)
         return
     if self.values is not None:
         self._values = nx.array(self.values)
         if self.boundaries is None:
             b = nx.zeros(len(self.values) + 1, "d")
             b[1:-1] = 0.5 * (self._values[:-1] - self._values[1:])
             b[0] = 2.0 * b[1] - b[2]
             b[-1] = 2.0 * b[-2] - b[-3]
             self._boundaries = b
             return
         self._boundaries = nx.array(self.boundaries)
         return
     if isinstance(self.norm, colors.no_norm):
         b = nx.arange(self.norm.vmin, self.norm.vmax + 2) - 0.5
     else:
         dv = self.norm.vmax - self.norm.vmin
         b = self.norm.vmin + dv * self._uniform_y(self.cmap.N + 1)
     self._process_values(b)
示例#5
0
 def _process_values(self, b=None):
     '''
     Set the _boundaries and _values attributes based on
     the input boundaries and values.  Input boundaries can
     be self.boundaries or the argument b.
     '''
     if b is None:
         b = self.boundaries
     if b is not None:
         self._boundaries = nx.array(b)
         if self.values is None:
             self._values = 0.5 * (self._boundaries[:-1] +
                                   self._boundaries[1:])
             if isinstance(self.norm, colors.no_norm):
                 self._values = (self._values + 0.00001).astype(nx.Int16)
             return
         self._values = nx.array(self.values)
         return
     if self.values is not None:
         self._values = nx.array(self.values)
         if self.boundaries is None:
             b = nx.zeros(len(self.values) + 1, 'd')
             b[1:-1] = 0.5 * (self._values[:-1] - self._values[1:])
             b[0] = 2.0 * b[1] - b[2]
             b[-1] = 2.0 * b[-2] - b[-3]
             self._boundaries = b
             return
         self._boundaries = nx.array(self.boundaries)
         return
     if isinstance(self.norm, colors.no_norm):
         b = nx.arange(self.norm.vmin, self.norm.vmax + 2) - 0.5
     else:
         dv = self.norm.vmax - self.norm.vmin
         b = self.norm.vmin + dv * self._uniform_y(self.cmap.N + 1)
     self._process_values(b)
示例#6
0
    def get_rgba(self, tex, fontsize=10, dpi=80, rgb=(0,0,0)):
        """
        Return tex string as an rgba array
        """

        # dvipng assumes a constant background, whereas we want to
        # overlay these rasters with antialiasing over arbitrary
        # backgrounds that may have other figure elements under them.
        # When you set dvipng -bg Transparent, it actually makes the
        # alpha channel 1 and does the background compositing and
        # antialiasing itself and puts the blended data in the rgb
        # channels.  So what we do is extract the alpha information
        # from the red channel, which is a blend of the default dvipng
        # background (white) and foreground (black).  So the amount of
        # red (or green or blue for that matter since white and black
        # blend to a grayscale) is the alpha intensity.  Once we
        # extract the correct alpha information, we assign it to the
        # alpha channel properly and let the users pick their rgb.  In
        # this way, we can overlay tex strings on arbitrary
        # backgrounds with antialiasing
        #
        # red = alpha*red_foreground + (1-alpha)*red_background

        # Since the foreground is black (0) and the background is
        # white (1) this reduces to red = 1-alpha or alpha = 1-red
        
        # assuming standard 10pt design size space
        dpi = fontsize/10.0 * dpi
        
        r,g,b = rgb
        key = tex, dpi, tuple(rgb)
        Z = self.arrayd.get(key)
        
        if Z is None:
            # force=True to skip cacheing while debugging
            pngfile = self.make_png(tex, dpi, force=False) 
            X = readpng(pngfile)
            vers = self.get_dvipng_version()
            #print 'dvipng version', vers
            if vers<'1.6':
                # hack the alpha channel as described in comment above
                alpha = sqrt(1-X[:,:,0])
            else:
                # dvipng 1.6 and above handles the alpha channel
                # properly [JDH: for some reason I had square root in
                # here which isn't correct
                #alpha = sqrt(X[:,:,-1])
                alpha = X[:,:,-1]
            

            Z = zeros(X.shape, Float)
            Z[:,:,0] = r
            Z[:,:,1] = g
            Z[:,:,2] = b
            Z[:,:,3] = alpha
               
            self.arrayd[key] = Z

        return Z
def fill_below_intersection(x, S, Z):
    """
    fill the region below the intersection of S and Z
    """
    #find the intersection point
    ind = nx.nonzero( nx.absolute(S-Z)==min(nx.absolute(S-Z)))[0]
    # compute a new curve which we will fill below
    Y = nx.zeros(S.shape, typecode=nx.Float)
    Y[:ind] = S[:ind]  # Y is S up to the intersection
    Y[ind:] = Z[ind:]  # and Z beyond it
    p.fill(x, Y, facecolor='blue', alpha=0.5)
示例#8
0
def fill_below_intersection(x, S, Z):
    """
    fill the region below the intersection of S and Z
    """
    #find the intersection point
    ind = nx.nonzero(nx.absolute(S - Z) == min(nx.absolute(S - Z)))[0]
    # compute a new curve which we will fill below
    Y = nx.zeros(S.shape, typecode=nx.Float)
    Y[:ind] = S[:ind]  # Y is S up to the intersection
    Y[ind:] = Z[ind:]  # and Z beyond it
    p.fill(x, Y, facecolor='blue', alpha=0.5)
示例#9
0
 def _uniform_y(self, N):
     '''
     Return colorbar data coordinates for N uniformly
     spaced boundaries, plus ends if required.
     '''
     if self.extend == 'neither':
         y = linspace(0, 1, N)
     else:
         if self.extend == 'both':
             y = nx.zeros(N + 2, 'd')
             y[0] = -0.05
             y[-1] = 1.05
         elif self.extend == 'min':
             y = nx.zeros(N + 1, 'd')
             y[0] = -0.05
         else:
             y = nx.zeros(N + 1, 'd')
             y[-1] = 1.05
         y[self._inside] = linspace(0, 1, N)
     return y
示例#10
0
 def _uniform_y(self, N):
     """
     Return colorbar data coordinates for N uniformly
     spaced boundaries, plus ends if required.
     """
     if self.extend == "neither":
         y = linspace(0, 1, N)
     else:
         if self.extend == "both":
             y = nx.zeros(N + 2, "d")
             y[0] = -0.05
             y[-1] = 1.05
         elif self.extend == "min":
             y = nx.zeros(N + 1, "d")
             y[0] = -0.05
         else:
             y = nx.zeros(N + 1, "d")
             y[-1] = 1.05
         y[self._inside] = linspace(0, 1, N)
     return y
示例#11
0
    def _draw_mathtext(self, gc, x, y, s, prop, angle):
        size = prop.get_size_in_points()
        width, height, fonts = math_parse_s_ft2font(s, self.dpi.get(), size)

        if angle == 90:
            width, height = height, width
            x -= width
        y -= height

        imw, imh, image_str = fonts[0].image_as_str()
        N = imw * imh

        # a numpixels by num fonts array
        Xall = zeros((N, len(fonts)), typecode=UInt8)

        for i, font in enumerate(fonts):
            if angle == 90:
                font.horiz_image_to_vert_image()  # <-- Rotate
            imw, imh, image_str = font.image_as_str()
            Xall[:, i] = fromstring(image_str, UInt8)

        # get the max alpha at each pixel
        Xs = numerix.mlab.max(Xall, 1)

        # convert it to it's proper shape
        Xs.shape = imh, imw

        pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,
                                has_alpha=True,
                                bits_per_sample=8,
                                width=imw,
                                height=imh)

        array = pixbuf_get_pixels_array(pixbuf)

        rgb = gc.get_rgb()
        array[:, :, 0] = int(rgb[0] * 255)
        array[:, :, 1] = int(rgb[1] * 255)
        array[:, :, 2] = int(rgb[2] * 255)
        array[:, :, 3] = Xs

        try:  # new in 2.2
            # can use None instead of gc.gdkGC, if don't need clipping
            self.gdkDrawable.draw_pixbuf(gc.gdkGC, pixbuf, 0, 0, int(x),
                                         int(y), imw, imh, gdk.RGB_DITHER_NONE,
                                         0, 0)
        except AttributeError:
            # deprecated in 2.2
            pixbuf.render_to_drawable(self.gdkDrawable, gc.gdkGC, 0, 0, int(x),
                                      int(y), imw, imh, gdk.RGB_DITHER_NONE, 0,
                                      0)
示例#12
0
    def get_rgba(self, tex, fontsize=None, dpi=None, rgb=(0, 0, 0)):
        """
        Return tex string as an rgba array
        """
        # dvipng assumes a constant background, whereas we want to
        # overlay these rasters with antialiasing over arbitrary
        # backgrounds that may have other figure elements under them.
        # When you set dvipng -bg Transparent, it actually makes the
        # alpha channel 1 and does the background compositing and
        # antialiasing itself and puts the blended data in the rgb
        # channels.  So what we do is extract the alpha information
        # from the red channel, which is a blend of the default dvipng
        # background (white) and foreground (black).  So the amount of
        # red (or green or blue for that matter since white and black
        # blend to a grayscale) is the alpha intensity.  Once we
        # extract the correct alpha information, we assign it to the
        # alpha channel properly and let the users pick their rgb.  In
        # this way, we can overlay tex strings on arbitrary
        # backgrounds with antialiasing
        #
        # red = alpha*red_foreground + (1-alpha)*red_background
        #
        # Since the foreground is black (0) and the background is
        # white (1) this reduces to red = 1-alpha or alpha = 1-red
        if not fontsize: fontsize = rcParams['font.size']
        if not dpi: dpi = rcParams['savefig.dpi']
        r, g, b = rgb
        key = tex, fontsize, dpi, tuple(rgb)
        Z = self.arrayd.get(key)

        if Z is None:
            # force=True to skip cacheing while debugging
            pngfile = self.make_png(tex, fontsize, dpi, force=False)
            X = readpng(os.path.join(self.texcache, pngfile))

            if (self.dvipngVersion < '1.6') or rcParams['text.dvipnghack']:
                # hack the alpha channel as described in comment above
                alpha = sqrt(1 - X[:, :, 0])
            else:
                alpha = X[:, :, -1]

            Z = zeros(X.shape, Float)
            Z[:, :, 0] = r
            Z[:, :, 1] = g
            Z[:, :, 2] = b
            Z[:, :, 3] = alpha
            self.arrayd[key] = Z

        return Z
示例#13
0
    def get_rgba(self, tex, fontsize=None, dpi=None, rgb=(0,0,0)):
        """
        Return tex string as an rgba array
        """
        # dvipng assumes a constant background, whereas we want to
        # overlay these rasters with antialiasing over arbitrary
        # backgrounds that may have other figure elements under them.
        # When you set dvipng -bg Transparent, it actually makes the
        # alpha channel 1 and does the background compositing and
        # antialiasing itself and puts the blended data in the rgb
        # channels.  So what we do is extract the alpha information
        # from the red channel, which is a blend of the default dvipng
        # background (white) and foreground (black).  So the amount of
        # red (or green or blue for that matter since white and black
        # blend to a grayscale) is the alpha intensity.  Once we
        # extract the correct alpha information, we assign it to the
        # alpha channel properly and let the users pick their rgb.  In
        # this way, we can overlay tex strings on arbitrary
        # backgrounds with antialiasing
        #
        # red = alpha*red_foreground + (1-alpha)*red_background
        #
        # Since the foreground is black (0) and the background is
        # white (1) this reduces to red = 1-alpha or alpha = 1-red
        if not fontsize: fontsize = rcParams['font.size']
        if not dpi: dpi = rcParams['savefig.dpi']
        r,g,b = rgb
        key = tex, fontsize, dpi, tuple(rgb)
        Z = self.arrayd.get(key)

        if Z is None:
            # force=True to skip cacheing while debugging
            pngfile = self.make_png(tex, fontsize, dpi, force=False)
            X = readpng(os.path.join(self.texcache, pngfile))

            if (self.dvipngVersion < '1.6') or rcParams['text.dvipnghack']:
                # hack the alpha channel as described in comment above
                alpha = sqrt(1-X[:,:,0])
            else:
                alpha = X[:,:,-1]

            Z = zeros(X.shape, Float)
            Z[:,:,0] = r
            Z[:,:,1] = g
            Z[:,:,2] = b
            Z[:,:,3] = alpha
            self.arrayd[key] = Z

        return Z
示例#14
0
    def _draw_mathtext(self, gc, x, y, s, prop, angle):
        size = prop.get_size_in_points()
        width, height, fonts = math_parse_s_ft2font(
            s, self.dpi.get(), size)

        if angle==90:
            width, height = height, width
            x -= width
        y -= height
        
        imw, imh, image_str = fonts[0].image_as_str()
        N = imw*imh

        # a numpixels by num fonts array
        Xall = zeros((N,len(fonts)), typecode=UInt8)

        for i, font in enumerate(fonts):
            if angle == 90:
                font.horiz_image_to_vert_image() # <-- Rotate
            imw, imh, image_str = font.image_as_str()
            Xall[:,i] = fromstring(image_str, UInt8)  

        # get the max alpha at each pixel
        Xs = numerix.mlab.max(Xall,1)

        # convert it to it's proper shape
        Xs.shape = imh, imw

        pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, has_alpha=True,
                                bits_per_sample=8, width=imw, height=imh)

        array = pixbuf_get_pixels_array(pixbuf)

        rgb = gc.get_rgb()
        array[:,:,0]=int(rgb[0]*255)
        array[:,:,1]=int(rgb[1]*255)
        array[:,:,2]=int(rgb[2]*255)
        array[:,:,3]=Xs

        try: # new in 2.2
            # can use None instead of gc.gdkGC, if don't need clipping
            self.gdkDrawable.draw_pixbuf (gc.gdkGC, pixbuf, 0, 0,
                                          int(x), int(y), imw, imh,
                                          gdk.RGB_DITHER_NONE, 0, 0)
        except AttributeError:
            # deprecated in 2.2
            pixbuf.render_to_drawable(self.gdkDrawable, gc.gdkGC, 0, 0,
                                  int(x), int(y), imw, imh,
                                  gdk.RGB_DITHER_NONE, 0, 0)
示例#15
0
 def _init(self):
     if not self._initialized:
         self._set_transform()
         _pivot = self.Q.pivot
         self.Q.pivot = self.pivot[self.labelpos]
         self.verts = self.Q._make_verts(nx.array([self.U]), nx.zeros((1,)))
         self.Q.pivot = _pivot
         kw = self.Q.polykw
         kw.update(self.kw)
         self.vector = PolyCollection(self.verts,
                                      offsets=[(self.X,self.Y)],
                                      transOffset=self.get_transform(),
                                      **kw)
         if self.color is not None:
             self.vector.set_color(self.color)
         self.vector.set_transform(self.Q.get_transform())
         self._initialized = True
示例#16
0
    def draw_mathtext(self, gc, x, y, s, prop, angle):

        size = prop.get_size_in_points()
        width, height, fonts = math_parse_s_ft2font(s, self.dpi.get(), size)

        if angle == 90:
            width, height = height, width
        x = int(x)
        y = int(y)

        rgb = gc.get_rgb()
        #rgba = (rgb[0], rgb[1], rgb[2], gc.get_alpha())

        imw, imh, s = fonts[0].image_as_str()
        N = imw * imh

        # a numpixels by num fonts array
        Xall = zeros((N, len(fonts)), typecode=UInt8)

        for i, font in enumerate(fonts):
            if angle == 90:
                font.horiz_image_to_vert_image()  # <-- Rotate
            imw, imh, s = font.image_as_str()
            Xall[:, i] = fromstring(s, UInt8)

        # get the max alpha at each pixel
        Xs = numerix.max(Xall, 1)

        # convert it to it's proper shape

        Xs.shape = imh, imw

        pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,
                            has_alpha=1,
                            bits_per_sample=8,
                            width=imw,
                            height=imh)

        try:
            pa = pb.get_pixels_array()
        except AttributeError:
            pa = pb.pixel_array
        except RuntimeError, exc:  #  pygtk was not compiled with Numeric Python support
            print >> sys.stderr, 'Error:', exc
            return
示例#17
0
    def _draw_mathtext(self, gc, x, y, s, prop, angle):
        size = prop.get_size_in_points()
        width, height, fonts = math_parse_s_ft2font(s, self.dpi.get(), size)

        if angle == 90:
            width, height = height, width
            x -= width
        y -= height

        imw, imh, s = fonts[0].image_as_str()
        N = imw * imh

        # a numpixels by num fonts array
        Xall = zeros((N, len(fonts)), typecode=UInt8)

        for i, font in enumerate(fonts):
            if angle == 90:
                font.horiz_image_to_vert_image()  # <-- Rotate
            imw, imh, s = font.image_as_str()
            Xall[:, i] = fromstring(s, UInt8)

        # get the max alpha at each pixel
        Xs = numerix.max(Xall, 1)

        # convert it to it's proper shape
        Xs.shape = imh, imw

        pb = gtk.gdk.Pixbuf(
            gtk.gdk.COLORSPACE_RGB,
            #has_alpha=1, bits_per_sample=8, width=imw, height=imh)
            has_alpha=True,
            bits_per_sample=8,
            width=imw,
            height=imh)

        try:
            pa = pb.get_pixels_array()
        except AttributeError:
            pa = pb.pixel_array
        except RuntimeError, exc:  #  'pygtk was not compiled with Numeric Python support'
            verbose.report_error('mathtext not supported: %s' % exc)
            return
示例#18
0
    def draw_tex(self, gc, x, y, s, prop, angle):
        # todo, handle props, angle, origins
        rgb = gc.get_rgb()
        size = prop.get_size_in_points()
        dpi = self.dpi.get()

        flip = angle == 90
        w, h = self.get_text_width_height(s, prop, 'TeX', rgb)
        if flip:
            w, h = h, w
            x -= w

        texmanager = self.get_texmanager()
        key = s, size, dpi, rgb, angle, texmanager.get_font_config()
        im = self.texd.get(key)
        if im is None:
            Z = texmanager.get_rgba(s, size, dpi, rgb)
            if flip:
                r = Z[:, :, 0]
                g = Z[:, :, 1]
                b = Z[:, :, 2]
                a = Z[:, :, 3]
                m, n, tmp = Z.shape

                def func(x):
                    return transpose(fliplr(x))

                Z = zeros((n, m, 4), typecode=Float)
                Z[:, :, 0] = func(r)
                Z[:, :, 1] = func(g)
                Z[:, :, 2] = func(b)
                Z[:, :, 3] = func(a)
            im = fromarray(Z, 1)
            im.flipud_out()
            self.texd[key] = im

        cliprect = gc.get_clip_rectangle()
        if cliprect is None: bbox = None
        else: bbox = lbwh_to_bbox(*cliprect)
        self.draw_image(x, self.height - y, im, bbox)
示例#19
0
    def draw_tex(self, gc, x, y, s, prop, angle):
        # todo, handle props, angle, origins
        rgb = gc.get_rgb()
        size = prop.get_size_in_points()
        dpi = self.dpi.get()

        flip = angle==90
        w,h = self.get_text_width_height(s, prop, 'TeX', rgb)
        if flip:
            w,h = h,w
            x -= w

        key = s, size, dpi, rgb, angle
        im = self.texd.get(key)
        if im is None:
            Z = self.texmanager.get_rgba(s, size, dpi, rgb)
            if flip:
                r = Z[:,:,0]
                g = Z[:,:,1]
                b = Z[:,:,2]
                a = Z[:,:,3]
                m,n,tmp = Z.shape

                def func(x):
                    return transpose(fliplr(x))

                Z = zeros((n,m,4), typecode=Float)
                Z[:,:,0] = func(r)
                Z[:,:,1] = func(g)
                Z[:,:,2] = func(b)
                Z[:,:,3] = func(a)
            im = fromarray(Z, 1)
            im.flipud_out()
            self.texd[key] = im

        cliprect = gc.get_clip_rectangle()
        if cliprect is None: bbox = None
        else: bbox = lbwh_to_bbox(*cliprect)
        self.draw_image(x, self.height-y, im, bbox)
示例#20
0
    def _draw_mathtext(self, gc, x, y, s, prop, angle):
        size = prop.get_size_in_points()
        width, height, fonts = math_parse_s_ft2font(
            s, self.dpi.get(), size)

        if angle==90:
            width, height = height, width
            x -= width
        y -= height
        
        imw, imh, s = fonts[0].image_as_str()
        N = imw*imh

        # a numpixels by num fonts array
        Xall = zeros((N,len(fonts)), typecode=UInt8)

        for i, font in enumerate(fonts):
            if angle == 90:
                font.horiz_image_to_vert_image() # <-- Rotate
            imw, imh, s = font.image_as_str()
            Xall[:,i] = fromstring(s, UInt8)  

        # get the max alpha at each pixel
        Xs = numerix.mlab.max(Xall,1)

        # convert it to it's proper shape
        Xs.shape = imh, imw

        pb=gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,
                          #has_alpha=1, bits_per_sample=8, width=imw, height=imh)
                          has_alpha=True, bits_per_sample=8, width=imw, height=imh)

        try:
            pa = pb.get_pixels_array()
        except AttributeError:
            pa = pb.pixel_array
        except RuntimeError, exc: #  'pygtk was not compiled with Numeric Python support'
            verbose.report_error('mathtext not supported: %s' % exc)
            return        
示例#21
0
    def draw_tex(self, gc, x, y, s, prop, angle):
        # todo, handle props, angle, origins
        rgb = gc.get_rgb()
        size = prop.get_size_in_points()
        dpi = self.dpi.get()

        flip = angle == 90
        w, h = self.get_text_width_height(s, prop, 'TeX', rgb)
        if flip:
            w, h = h, w
            x -= w

        key = s, size, dpi, rgb
        im = self.texd.get(key)

        if im is None:
            Z = self.texmanager.get_rgba(s, size, dpi, rgb)
            if flip:
                r = Z[:, :, 0]
                g = Z[:, :, 1]
                b = Z[:, :, 2]
                a = Z[:, :, 3]
                m, n, tmp = Z.shape

                def func(x):
                    return transpose(fliplr(x))

                Z = zeros((n, m, 4), typecode=Float)
                Z[:, :, 0] = func(r)
                Z[:, :, 1] = func(g)
                Z[:, :, 2] = func(b)
                Z[:, :, 3] = func(a)
            im = fromarray(Z, 1)
            self.texd[key] = im

        self.draw_image(x, y - h, im, 'upper', self.bbox)
示例#22
0
tlon = N.concatenate((tlon, tlon + 360), 1)
tlat = N.concatenate((tlat, tlat), 1)
temp = MA.concatenate((temp, temp), 1)
tlon = tlon - 360.

pl.figure(figsize=(8.5, 11))
pl.subplot(2, 1, 1)
# subplot 1 just shows POP grid cells.
map = Basemap(projection='merc', lat_ts=20, llcrnrlon=-180, \
      urcrnrlon=180, llcrnrlat=-84, urcrnrlat=84, resolution='c')

map.drawcoastlines()
map.fillcontinents(color='white')

x, y = map(tlon, tlat)
im = map.pcolor(x,y,MA.masked_array(N.zeros(temp.shape,'f'), temp.mask),\
                shading='faceted',cmap=pl.cm.cool,vmin=0,vmax=0)
# disclaimer:  these are not really the grid cells because of the
# way pcolor interprets the x and y args.
pl.title('(A) CCSM POP Grid Cells')

# subplot 2 is a contour plot of surface temperature from the
# CCSM ocean model.
pl.subplot(2, 1, 2)
map.drawcoastlines()
map.fillcontinents(color='white')

CS1 = map.contourf(x, y, temp, 15)
CS2 = map.contour(x, y, temp, 15, colors='black', linewidths=0.5)
pl.title('(B) Surface Temp contours on POP Grid')
示例#23
0
tlon = N.concatenate((tlon,tlon+360),1)
tlat = N.concatenate((tlat,tlat),1)
temp = MA.concatenate((temp,temp),1)
tlon = tlon-360.

pl.figure(figsize=(8.5,11))
pl.subplot(2,1,1)
# subplot 1 just shows POP grid cells.
map = Basemap(projection='merc', lat_ts=20, llcrnrlon=-180, \
      urcrnrlon=180, llcrnrlat=-84, urcrnrlat=84, resolution='c')

map.drawcoastlines()
map.fillcontinents(color='white')

x, y = map(tlon,tlat)
im = map.pcolor(x,y,MA.masked_array(N.zeros(temp.shape,'f'), temp.mask),\
                shading='faceted',cmap=pl.cm.cool,vmin=0,vmax=0)
# disclaimer:  these are not really the grid cells because of the
# way pcolor interprets the x and y args.
pl.title('(A) CCSM POP Grid Cells')

# subplot 2 is a contour plot of surface temperature from the
# CCSM ocean model.
pl.subplot(2,1,2)
map.drawcoastlines()
map.fillcontinents(color='white')

CS1 = map.contourf(x,y,temp,15)
CS2 = map.contour(x,y,temp,15,colors='black',linewidths=0.5)
pl.title('(B) Surface Temp contours on POP Grid')