def set_linewidth(self, w): GraphicsContextBase.set_linewidth(self, w) if w == 0: self.gdkGC.line_width = 0 else: pixels = self.renderer.points_to_pixels(w) self.gdkGC.line_width = max(1, int(round(pixels)))
def __init__(self, renderer): GraphicsContextBase.__init__(self) self.renderer = renderer self.ctx = cairo.Context() # default is 0.1, raise value to increase performance # (and lower quality) self.ctx.set_tolerance(0.5)
def __init__(self, im, renderer): """ Initialize with a gd image """ GraphicsContextBase.__init__(self) self.im = im self.renderer = renderer
def set_clip_rectangle(self, rectangle): GraphicsContextBase.set_clip_rectangle(self, rectangle) x,y,w,h = rectangle imw, imh = self.im.size() lb = int(x), imh-int(y) ur = int(x+w), imh-int(y+h) self.im.setClip(ur, lb)
def set_clip_rectangle(self, rectangle): GraphicsContextBase.set_clip_rectangle(self, rectangle) l, b, w, h = rectangle rectangle = (int(l), self.renderer.height - int(b + h) + 1, int(w), int(h)) # rectangle = (int(l), self.renderer.height-int(b+h), # int(w+1), int(h+2)) self.gdkGC.set_clip_rectangle(rectangle)
def set_clip_rectangle(self, rectangle): GraphicsContextBase.set_clip_rectangle(self, rectangle) if rectangle is None: return l,b,w,h = rectangle.bounds rectangle = (int(l), self.renderer.height-int(b+h)+1, int(w), int(h)) self.gdkGC.set_clip_rectangle(rectangle)
def set_linestyle(self, style): """ Set the linestyle to be one of ('solid', 'dashed', 'dashdot', 'dotted'). """ GraphicsContextBase.set_linestyle(self, style) offset, dashes = self._dashd[style] self.set_dashes(offset, dashes)
def set_foreground(self, fg, isRGB=None): """ Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. """ GraphicsContextBase.set_foreground(self, fg, isRGB) self.ctx.set_rgb_color(*self._rgb)
def set_alpha(self, alpha): GraphicsContextBase.set_alpha(self, alpha) _alpha = self.get_alpha() rgb = self._rgb if self.get_forced_alpha(): self.ctx.set_source_rgba(rgb[0], rgb[1], rgb[2], _alpha) else: self.ctx.set_source_rgba(rgb[0], rgb[1], rgb[2], rgb[3])
def set_dashes(self, dash_offset, dash_list): GraphicsContextBase.set_dashes(self, dash_offset, dash_list) # dash_list is a list with numbers denoting the number of points # in a dash and if it is on or off. if dash_list is not None: self.line['dash_list'] = dash_list if dash_offset is not None: self.line['dash_offset'] = int(dash_offset)
def set_dashes(self, dash_offset, dash_list): GraphicsContextBase.set_dashes(self, dash_offset, dash_list) if dash_list == None: self.gdkGC.line_style = gdk.LINE_SOLID else: pixels = self.renderer.points_to_pixels(npy.asarray(dash_list)) dl = [max(1, int(round(val))) for val in pixels] self.gdkGC.set_dashes(dash_offset, dl) self.gdkGC.line_style = gdk.LINE_ON_OFF_DASH
def set_capstyle(self, cs): """ Set the capstyle as a string in ('butt', 'round', 'projecting') """ DEBUG_MSG("set_capstyle()", 1, self) self.select() GraphicsContextBase.set_capstyle(self, cs) self._pen.SetCap(GraphicsContextWx._capd[self._capstyle]) self.gfx_ctx.SetPen(self._pen) self.unselect()
def set_joinstyle(self, js): """ Set the join style to be one of ('miter', 'round', 'bevel') """ DEBUG_MSG("set_joinstyle()", 1, self) self.select() GraphicsContextBase.set_joinstyle(self, js) self._pen.SetJoin(GraphicsContextWx._joind[self._joinstyle]) self.gfx_ctx.SetPen(self._pen) self.unselect()
def set_graylevel(self, frac): """ Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. """ DEBUG_MSG("set_graylevel()", 1, self) self.select() GraphicsContextBase.set_graylevel(self, frac) self._pen.SetColour(self.get_wxcolour(self.get_rgb())) self.gfx_ctx.SetPen(self._pen) self.unselect()
def set_linewidth(self, w): """ Set the line width. """ DEBUG_MSG("set_linewidth()", 1, self) self.select() if w>0 and w<1: w = 1 GraphicsContextBase.set_linewidth(self, w) lw = int(self.renderer.points_to_pixels(self._linewidth)) if lw==0: lw = 1 self._pen.SetWidth(lw) self.gfx_ctx.SetPen(self._pen) self.unselect()
def DISABLED_memleak( self ): """Test agg backend for memory leaks.""" fontname = '/usr/local/share/matplotlib/Vera.ttf' fname = self.outFile( "agg_memleak_%05d.png" ) N = 200 for i in range( N ): gc = GraphicsContextBase() gc.set_clip_rectangle( [20, 20, 20, 20] ) o = RendererAgg( 400, 400, 72 ) for j in range( 50 ): xs = [ 400*int(rand()) for k in range(8) ] ys = [ 400*int(rand()) for k in range(8) ] rgb = (1, 0, 0) pnts = zip( xs, ys ) o.draw_polygon( gc, rgb, pnts ) o.draw_polygon( gc, None, pnts ) for j in range( 50 ): x = [ 400*int(rand()) for k in range(4) ] y = [ 400*int(rand()) for k in range(4) ] o.draw_lines( gc, x, y ) for j in range( 50 ): args = [ 400*int(rand()) for k in range(4) ] rgb = (1, 0, 0) o.draw_rectangle( gc, rgb, *args ) if 1: # add text font = FT2Font( fontname ) font.clear() font.set_text( 'hi mom', 60 ) font.set_size( 12, 72 ) o.draw_text_image( font.get_image(), 30, 40, gc ) o.write_png( fname % i ) val = report_memory( i ) if i==1: start = val end = val avgMem = (end - start) / float(N) print 'Average memory consumed per loop: %1.4f\n' % (avgMem) #TODO: Verify the expected mem usage and approximate tolerance that should be used self.checkClose( 0.32, avgMem, absTol = 0.1 )
def set_clip_path(self, path): GraphicsContextBase.set_clip_path(self, path) if not path: return path = path.get_fully_transformed_path() for points, code in path.iter_segments(): if code == Path.MOVETO: self.moveto(points) elif code == Path.LINETO: self.lineto(points) elif code == Path.CURVE3: self.curve3(points) elif code == Path.CURVE4: self.curve4(points) elif code == Path.CLOSEPOLY: self.closepoly() self.clip_path()
def set_foreground(self, fg, isRGB=None): """ Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. """ # Implementation note: wxPython has a separate concept of pen and # brush - the brush fills any outline trace left by the pen. # Here we set both to the same colour - if a figure is not to be # filled, the renderer will set the brush to be transparent # Same goes for text foreground... DEBUG_MSG("set_foreground()", 1, self) self.select() GraphicsContextBase.set_foreground(self, fg, isRGB) self._pen.SetColour(self.get_wxcolour(self.get_rgb())) self.gfx_ctx.SetPen(self._pen) self.unselect()
def set_linestyle(self, ls): """ Set the line style to be one of """ DEBUG_MSG("set_linestyle()", 1, self) self.select() GraphicsContextBase.set_linestyle(self, ls) try: self._style = GraphicsContextWx._dashd_wx[ls] except KeyError: self._style = wx.LONG_DASH# Style not used elsewhere... # On MS Windows platform, only line width of 1 allowed for dash lines if wx.Platform == '__WXMSW__': self.set_linewidth(1) self._pen.SetStyle(self._style) self.gfx_ctx.SetPen(self._pen) self.unselect()
def __init__(self, bitmap, renderer): GraphicsContextBase.__init__(self) #assert self.Ok(), "wxMemoryDC not OK to use" DEBUG_MSG("__init__()", 1, self) dc, gfx_ctx = self._cache.get(bitmap, (None, None)) if dc is None: dc = wx.MemoryDC() dc.SelectObject(bitmap) gfx_ctx = wx.GraphicsContext.Create(dc) gfx_ctx._lastcliprect = None self._cache[bitmap] = dc, gfx_ctx self.bitmap = bitmap self.dc = dc self.gfx_ctx = gfx_ctx self._pen = wx.Pen('BLACK', 1, wx.SOLID) gfx_ctx.SetPen(self._pen) self._style = wx.SOLID self.renderer = renderer
def write_header(self, resolution=72): from matplotlib.backends.backend_agg import RendererAgg, Figure from matplotlib.backend_bases import GraphicsContextBase try: from matplotlib.transforms import Value except ImportError: dpi = resolution else: dpi = Value(resolution) self.renderer = RendererAgg(self.w, self.h, dpi) self.figure = Figure() self.gc = GraphicsContextBase() self.gc.set_linewidth(.2)
def __init__(self, renderer): GraphicsContextBase.__init__(self) self.renderer = renderer self.gdkGC = gtk.gdk.GC(renderer.gdkDrawable) self._cmap = renderer._cmap
def set_joinstyle(self, js): GraphicsContextBase.set_joinstyle(self, js) self.gdkGC.join_style = self._joind[self._joinstyle]
def set_clip_rectangle(self, box): GraphicsContextBase.set_clip_rectangle(self, box) if not box: return _macosx.GraphicsContext.set_clip_rectangle(self, box.bounds)
from matplotlib.ft2font import FT2Font from numpy.random import rand from matplotlib.backend_bases import GraphicsContextBase from matplotlib.backends._backend_agg import RendererAgg def report_memory(i): pid = os.getpid() a2 = os.popen('ps -p %d -o rss,sz' % pid).readlines() print(i, ' ', a2[1], end='') return int(a2[1].split()[0]) fname = '/usr/local/share/matplotlib/Vera.ttf' N = 200 for i in range(N): gc = GraphicsContextBase() gc.set_clip_rectangle( [20,20,20,20] ) o = RendererAgg(400,400, 72) for j in range(50): xs = [400*int(rand()) for k in range(8)] ys = [400*int(rand()) for k in range(8)] rgb = (1,0,0) pnts = zip(xs, ys) o.draw_polygon(gc, rgb, pnts) # no such method?? o.draw_polygon(gc, None, pnts) for j in range(50): x = [400*int(rand()) for k in range(4)] y = [400*int(rand()) for k in range(4)] o.draw_lines( gc, x, y)
def get_joinstyle(self): return {'miter': 0, 'round': 1, 'bevel': 2}[ GraphicsContextBase.get_joinstyle(self)]
class MyPNG(PNG): def __init__(self, atoms, rotation='', show_unit_cell=False, radii=None, bbox=None, colors=None, model=None, scale=20): self.numbers = atoms.get_atomic_numbers() self.colors = colors self.model = model if colors is None: self.colors = jmol_colors[self.numbers] if radii is None: radii = covalent_radii[self.numbers] elif type(radii) is float: radii = covalent_radii[self.numbers] * radii else: radii = np.array(radii) natoms = len(atoms) if isinstance(rotation, str): rotation = rotate(rotation) A = atoms.get_cell() if show_unit_cell > 0: L, T, D = self.cell_to_lines(A) C = np.empty((2, 2, 2, 3)) for c1 in range(2): for c2 in range(2): for c3 in range(2): C[c1, c2, c3] = np.dot([c1, c2, c3], A) C.shape = (8, 3) C = np.dot(C, rotation) # Unit cell vertices else: L = np.empty((0, 3)) T = None D = None C = None nlines = len(L) X = np.empty((natoms + nlines, 3)) R = atoms.get_positions() X[:natoms] = R X[natoms:] = L r2 = radii**2 for n in range(nlines): d = D[T[n]] if ((((R - L[n] - d)**2).sum(1) < r2) & (((R - L[n] + d)**2).sum(1) < r2)).any(): T[n] = -1 X = np.dot(X, rotation) R = X[:natoms] if bbox is None: X1 = (R - radii[:, None]).min(0) X2 = (R + radii[:, None]).max(0) if show_unit_cell == 2: X1 = np.minimum(X1, C.min(0)) X2 = np.maximum(X2, C.max(0)) M = (X1 + X2) / 2 S = 1.05 * (X2 - X1) w = scale * S[0] #if w > 500: #w = 500 #scale = w / S[0] h = scale * S[1] offset = np.array([scale * M[0] - w / 2, scale * M[1] - h / 2, 0]) else: w = (bbox[2] - bbox[0]) * scale h = (bbox[3] - bbox[1]) * scale offset = np.array([bbox[0], bbox[1], 0]) * scale self.w = w self.h = h X *= scale X -= offset if nlines > 0: D = np.dot(D, rotation)[:, :2] * scale if C is not None: C *= scale C -= offset A = np.dot(A, rotation) A *= scale self.A = A self.X = X self.D = D self.T = T self.C = C self.natoms = natoms self.d = 2 * scale * radii def write(self, filename, resolution=72): self.filename = filename self.write_header(resolution=resolution) self.write_info() self.write_body() self.write_trailer(resolution=resolution) def write_info(self): def latex_float(f): float_str = "{0:.2e}".format(f) if "e" in float_str: base, exponent = float_str.split("e") return r"{0} \times 10^{{{1}}}".format(base, int(exponent)) else: return float_str import matplotlib.text if self.model is not None: time = latex_float(self.model.base.get_kmc_time()) text = matplotlib.text.Text( .05 * self.w, .9 * self.h, r'$t = {time}\,{{\rm s}}$'.format(**locals()), fontsize=36, bbox={ 'facecolor': 'white', 'alpha': 0.5, 'ec': 'white', 'pad': 1, 'lw': 0 }, ) text.figure = self.figure text.draw(self.renderer) def write_header(self, resolution=72): from matplotlib.backends.backend_agg import RendererAgg, Figure from matplotlib.backend_bases import GraphicsContextBase try: from matplotlib.transforms import Value except ImportError: dpi = resolution else: dpi = Value(resolution) self.renderer = RendererAgg(self.w, self.h, dpi) self.figure = Figure() self.gc = GraphicsContextBase() self.gc.set_linewidth(.2) def write_trailer(self, resolution=72): renderer = self.renderer if hasattr(renderer._renderer, 'write_png'): # Old version of matplotlib: renderer._renderer.write_png(self.filename) else: from matplotlib import _png # buffer_rgba does not accept arguments from version 1.2.0 # https://github.com/matplotlib/matplotlib/commit/f4fee350f9fbc639853bee76472d8089a10b40bd import matplotlib if matplotlib.__version__ < '1.2.0': x = renderer._renderer.buffer_rgba(0, 0) _png.write_png(renderer._renderer.buffer_rgba(0, 0), renderer.width, renderer.height, self.filename, resolution) else: x = renderer._renderer.buffer_rgba() _png.write_png(renderer._renderer.buffer_rgba(), renderer.width, renderer.height, self.filename, resolution)
def set_graylevel(self, frac): """ Set the foreground color to be a gray level with frac frac """ GraphicsContextBase.set_graylevel(self, frac) self.gdkGC.foreground = self._get_gdk_color()
def set_foreground(self, fg, isRGBA=False): GraphicsContextBase.set_foreground(self, fg, isRGBA) rgb = self.get_rgb() _macosx.GraphicsContext.set_foreground(self, rgb)
def __init__(self): GraphicsContextBase.__init__(self) _macosx.GraphicsContext.__init__(self)
def set_linestyle(self, style): GraphicsContextBase.set_linestyle(self, style) offset, dashes = self._dashd[style] self.set_dashes(offset, dashes)
def set_graylevel(self, frac): GraphicsContextBase.set_graylevel(self, frac) self.gdkGC.foreground = self.rgb_to_gdk_color(self.get_rgb())
def set_foreground(self, fg, isRGB=False): GraphicsContextBase.set_foreground(self, fg, isRGB) self.gdkGC.foreground = self.rgb_to_gdk_color(self.get_rgb())
def set_capstyle(self, cs): GraphicsContextBase.set_capstyle(self, cs) self.gdkGC.cap_style = self._capd[self._capstyle]
def set_foreground(self, fg, isRGB=None): GraphicsContextBase.set_foreground(self, fg, isRGB) self.ctx.set_source_rgb(*self._rgb)
def set_linewidth(self, lw): GraphicsContextBase.set_linewidth(self, lw) pixels = self.renderer.points_to_pixels(lw) self.gdkGC.line_width = max(1, int(round(pixels)))
def __init__(self, gdkGC, renderer): GraphicsContextBase.__init__(self) self.gdkGC = gdkGC self.renderer = renderer
def set_alpha(self, alpha): GraphicsContextBase.set_alpha(self, alpha) _alpha = self.get_alpha() rgb = self._rgb self.ctx.set_source_rgba(rgb[0], rgb[1], rgb[2], _alpha)
def __init__(self, renderer, surface): GraphicsContextBase.__init__(self) self.renderer = renderer self.ctx = cairo.Context(surface)
def __init__(self, renderer): GraphicsContextBase.__init__(self) self.renderer = renderer
def get_capstyle(self): return {'butt': 0, 'round': 1, 'projecting': 2}[ GraphicsContextBase.get_capstyle(self)]
def set_alpha(self, alpha): GraphicsContextBase.set_alpha(self, alpha) _alpha = self.get_alpha() _macosx.GraphicsContext.set_alpha(self, _alpha)
def set_clip_path(self, path): GraphicsContextBase.set_clip_path(self, path) if not path: return path = path.get_fully_transformed_path() _macosx.GraphicsContext.set_clip_path(self, path)
def set_linestyle(self, style): GraphicsContextBase.set_linestyle(self, style) offset, dashes = self.dashd[style] self.set_dashes(offset, dashes)
def set_graylevel(self, fg): GraphicsContextBase.set_graylevel(self, fg) _macosx.GraphicsContext.set_graylevel(self, fg)
def set_joinstyle(self, js): """ Set the join style to be one of ('miter', 'round', 'bevel') """ GraphicsContextBase.set_joinstyle(self, js) self.gdkGC.join_style = self._joind[self._joinstyle]
def set_foreground(self, fg, isRGB=False): GraphicsContextBase.set_foreground(self, fg, isRGB) rgb = self.get_rgb() _macosx.GraphicsContext.set_foreground(self, rgb[:3])
def set_graylevel(self, frac): GraphicsContextBase.set_graylevel(self, frac) self.ctx.set_source_rgb(*self._rgb)
def set_linestyle(self, style): GraphicsContextBase.set_linestyle(self, style)
def set_linewidth(self, lw): GraphicsContextBase.set_linewidth(self, lw) pixels = self.renderer.points_to_pixels(lw) if pixels<1: pixels = 1 else: pixels = round(pixels) self.im.setThickness(pixels)
def set_capstyle(self, cs): """ Set the capstyle as a string in ('butt', 'round', 'projecting') """ GraphicsContextBase.set_capstyle(self, cs) self.gdkGC.cap_style = self._capd[self._capstyle]
def set_alpha(self, alpha): GraphicsContextBase.set_alpha(self, alpha) _alpha = self.get_alpha() _macosx.GraphicsContext.set_alpha(self, _alpha, self.get_forced_alpha()) rgb = self.get_rgb() _macosx.GraphicsContext.set_foreground(self, rgb)
def set_graylevel(self, frac): GraphicsContextBase.set_graylevel(self, frac) if len(self._rgb) == 3: self.ctx.set_source_rgb(*self._rgb) else: self.ctx.set_source_rgba(*self._rgb)
def set_foreground(self, fg, isRGBA=None): GraphicsContextBase.set_foreground(self, fg, isRGBA) if len(self._rgb) == 3: self.ctx.set_source_rgb(*self._rgb) else: self.ctx.set_source_rgba(*self._rgb)