desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Create a metadata provider from a zipimporter'
def __init__(self, importer):
self.zipinfo = zipimport._zip_directory_cache[importer.archive] self.zip_pre = (importer.archive + os.sep) self.loader = importer if importer.prefix: self.module_path = os.path.join(importer.archive, importer.prefix) else: self.module_path = importer.archive self._setup_prefix()
'Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1,extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional'
def parse(cls, src, dist=None):
try: attrs = extras = () (name, value) = src.split('=', 1) if ('[' in value): (value, extras) = value.split('[', 1) req = Requirement.parse(('x[' + extras)) if req.specs: raise ValueError extras = req.extras if (':' in value): (value, attrs) = value.split(':', 1) if (not MODULE(attrs.rstrip())): raise ValueError attrs = attrs.rstrip().split('.') except ValueError: raise ValueError("EntryPoint must be in 'name=module:attrs [extras]' format", src) else: return cls(name.strip(), value.strip(), attrs, extras, dist)
'Parse an entry point group'
def parse_group(cls, group, lines, dist=None):
if (not MODULE(group)): raise ValueError('Invalid group name', group) this = {} for line in yield_lines(lines): ep = cls.parse(line, dist) if (ep.name in this): raise ValueError('Duplicate entry point', group, ep.name) this[ep.name] = ep return this
'Parse a map of entry point groups'
def parse_map(cls, data, dist=None):
if isinstance(data, dict): data = data.items() else: data = split_sections(data) maps = {} for (group, lines) in data: if (group is None): if (not lines): continue raise ValueError('Entry points must be listed in groups') group = group.strip() if (group in maps): raise ValueError('Duplicate group name', group) maps[group] = cls.parse_group(group, lines, dist) return maps
'List of Requirements needed for this distro if `extras` are used'
def requires(self, extras=()):
dm = self._dep_map deps = [] deps.extend(dm.get(None, ())) for ext in extras: try: deps.extend(dm[safe_extra(ext)]) except KeyError: raise UnknownExtra(('%s has no such extra feature %r' % (self, ext))) return deps
'Ensure distribution is importable on `path` (default=sys.path)'
def activate(self, path=None):
if (path is None): path = sys.path self.insert_on(path) if (path is sys.path): fixup_namespace_packages(self.location) map(declare_namespace, self._get_metadata('namespace_packages.txt'))
'Return what this distribution\'s standard .egg filename should be'
def egg_name(self):
filename = ('%s-%s-py%s' % (to_filename(self.project_name), to_filename(self.version), (self.py_version or PY_MAJOR))) if self.platform: filename += ('-' + self.platform) return filename
'Delegate all unrecognized public attributes to .metadata provider'
def __getattr__(self, attr):
if attr.startswith('_'): raise AttributeError, attr return getattr(self._provider, attr)
'Return a ``Requirement`` that matches this distribution exactly'
def as_requirement(self):
return Requirement.parse(('%s==%s' % (self.project_name, self.version)))
'Return the `name` entry point of `group` or raise ImportError'
def load_entry_point(self, group, name):
ep = self.get_entry_info(group, name) if (ep is None): raise ImportError(('Entry point %r not found' % ((group, name),))) return ep.load()
'Return the entry point map for `group`, or the full entry map'
def get_entry_map(self, group=None):
try: ep_map = self._ep_map except AttributeError: ep_map = self._ep_map = EntryPoint.parse_map(self._get_metadata('entry_points.txt'), self) if (group is not None): return ep_map.get(group, {}) return ep_map
'Return the EntryPoint object for `group`+`name`, or ``None``'
def get_entry_info(self, group, name):
return self.get_entry_map(group).get(name)
'Insert self.location in path before its nearest parent directory'
def insert_on(self, path, loc=None):
loc = (loc or self.location) if (not loc): return if (path is sys.path): self.check_version_conflict() nloc = _normalize_cached(loc) bdir = os.path.dirname(nloc) npath = map(_normalize_cached, path) bp = None for (p, item) in enumerate(npath): if (item == nloc): break elif ((item == bdir) and (self.precedence == EGG_DIST)): path.insert(p, loc) npath.insert(p, nloc) break else: path.append(loc) return while 1: try: np = npath.index(nloc, (p + 1)) except ValueError: break else: del npath[np], path[np] p = np return
'Copy this distribution, substituting in any changed keyword args'
def clone(self, **kw):
for attr in ('project_name', 'version', 'py_version', 'platform', 'location', 'precedence'): kw.setdefault(attr, getattr(self, attr, None)) kw.setdefault('metadata', self._provider) return self.__class__(**kw)
'DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!'
def __init__(self, project_name, specs, extras):
(self.unsafe_name, project_name) = (project_name, safe_name(project_name)) (self.project_name, self.key) = (project_name, project_name.lower()) index = [(parse_version(v), state_machine[op], op, v) for (op, v) in specs] index.sort() self.specs = [(op, ver) for (parsed, trans, op, ver) in index] (self.index, self.extras) = (index, tuple(map(safe_extra, extras))) self.hashCmp = (self.key, tuple([(op, parsed) for (parsed, trans, op, ver) in index]), frozenset(self.extras)) self.__hash = hash(self.hashCmp)
'call signature:: clabel(cs, **kwargs) adds labels to line contours in *cs*, where *cs* is a :class:`~matplotlib.contour.ContourSet` object returned by contour. clabel(cs, v, **kwargs) only labels contours listed in *v*. Optional keyword arguments: *fontsize*: See http://matplotlib.sf.net/fonts.html *colors*: - if *None*, the color of each label matches the color of the corresponding contour - if one string color, e.g. *colors* = \'r\' or *colors* = \'red\', all labels will be plotted in this color - if a tuple of matplotlib color args (string, float, rgb, etc), different labels will be plotted in different colors in the order specified *inline*: controls whether the underlying contour is removed or not. Default is *True*. *inline_spacing*: space in pixels to leave on each side of label when placing inline. Defaults to 5. This spacing will be exact for labels at locations where the contour is straight, less so for labels on curved contours. *fmt*: a format string for the label. Default is \'%1.3f\' Alternatively, this can be a dictionary matching contour levels with arbitrary strings to use for each contour level (i.e., fmt[level]=string) *manual*: if *True*, contour labels will be placed manually using mouse clicks. Click the first button near a contour to add a label, click the second button (or potentially both mouse buttons at once) to finish adding labels. The third button can be used to remove the last label added, but only if labels are not inline. Alternatively, the keyboard can be used to select label locations (enter to end label placement, delete or backspace act like the third mouse button, and any other key will select a label location). .. plot:: mpl_examples/pylab_examples/contour_demo.py'
def clabel(self, *args, **kwargs):
'\n NOTES on how this all works:\n\n clabel basically takes the input arguments and uses them to\n add a list of "label specific" attributes to the ContourSet\n object. These attributes are all of the form label* and names\n should be fairly self explanatory.\n\n Once these attributes are set, clabel passes control to the\n labels method (case of automatic label placement) or\n BlockingContourLabeler (case of manual label placement).\n ' fontsize = kwargs.get('fontsize', None) inline = kwargs.get('inline', 1) inline_spacing = kwargs.get('inline_spacing', 5) self.labelFmt = kwargs.get('fmt', '%1.3f') _colors = kwargs.get('colors', None) self.labelManual = kwargs.get('manual', False) if (len(args) == 0): levels = self.levels indices = range(len(self.levels)) elif (len(args) == 1): levlabs = list(args[0]) (indices, levels) = ([], []) for (i, lev) in enumerate(self.levels): if (lev in levlabs): indices.append(i) levels.append(lev) if (len(levels) < len(levlabs)): msg = ('Specified levels ' + str(levlabs)) msg += "\n don't match available levels " msg += str(self.levels) raise ValueError(msg) else: raise TypeError('Illegal arguments to clabel, see help(clabel)') self.labelLevelList = levels self.labelIndiceList = indices self.labelFontProps = font_manager.FontProperties() if (fontsize == None): font_size = int(self.labelFontProps.get_size_in_points()) elif (type(fontsize) not in [int, float, str]): raise TypeError('Font size must be an integer number.') elif (type(fontsize) == str): font_size = int(self.labelFontProps.get_size_in_points()) else: self.labelFontProps.set_size(fontsize) font_size = fontsize self.labelFontSizeList = ([font_size] * len(levels)) if (_colors == None): self.labelMappable = self self.labelCValueList = np.take(self.cvalues, self.labelIndiceList) else: cmap = colors.ListedColormap(_colors, N=len(self.labelLevelList)) self.labelCValueList = range(len(self.labelLevelList)) self.labelMappable = cm.ScalarMappable(cmap=cmap, norm=colors.NoNorm()) self.labelXYs = [] if self.labelManual: print 'Select label locations manually using first mouse button.' print 'End manual selection with second mouse button.' if (not inline): print 'Remove last label by clicking third mouse button.' blocking_contour_labeler = BlockingContourLabeler(self) blocking_contour_labeler(inline, inline_spacing) else: self.labels(inline, inline_spacing) self.cl = self.labelTexts self.cl_xy = self.labelXYs self.cl_cvalues = self.labelCValues self.labelTextsList = cbook.silent_list('text.Text', self.labelTexts) return self.labelTextsList
'if contours are too short, don\'t plot a label'
def print_label(self, linecontour, labelwidth):
lcsize = len(linecontour) if (lcsize > (10 * labelwidth)): return 1 xmax = np.amax(linecontour[:, 0]) xmin = np.amin(linecontour[:, 0]) ymax = np.amax(linecontour[:, 1]) ymin = np.amin(linecontour[:, 1]) lw = labelwidth if (((xmax - xmin) > (1.2 * lw)) or ((ymax - ymin) > (1.2 * lw))): return 1 else: return 0
'if there\'s a label already nearby, find a better place'
def too_close(self, x, y, lw):
if (self.labelXYs != []): dist = [np.sqrt((((x - loc[0]) ** 2) + ((y - loc[1]) ** 2))) for loc in self.labelXYs] for d in dist: if (d < (1.2 * lw)): return 1 else: return 0 else: return 0
'labels are ploted at a location with the smallest dispersion of the contour from a straight line unless there\'s another label nearby, in which case the second best place on the contour is picked up if there\'s no good place a label isplotted at the beginning of the contour'
def get_label_coords(self, distances, XX, YY, ysize, lw):
hysize = int((ysize / 2)) adist = np.argsort(distances) for ind in adist: (x, y) = (XX[ind][hysize], YY[ind][hysize]) if self.too_close(x, y, lw): continue else: return (x, y, ind) ind = adist[0] (x, y) = (XX[ind][hysize], YY[ind][hysize]) return (x, y, ind)
'get the width of the label in points'
def get_label_width(self, lev, fmt, fsize):
if cbook.is_string_like(lev): lw = (len(lev) * fsize) else: lw = (len(self.get_text(lev, fmt)) * fsize) return lw
'This computes actual onscreen label width. This uses some black magic to determine onscreen extent of non-drawn label. This magic may not be very robust.'
def get_real_label_width(self, lev, fmt, fsize):
xx = np.mean(np.asarray(self.ax.axis()).reshape(2, 2), axis=1) t = text.Text(xx[0], xx[1]) self.set_label_props(t, self.get_text(lev, fmt), 'k') bbox = t.get_window_extent(renderer=self.ax.figure.canvas.renderer) lw = np.diff(bbox.corners()[0::2, 0])[0] return lw
'set the label properties - color, fontsize, text'
def set_label_props(self, label, text, color):
label.set_text(text) label.set_color(color) label.set_fontproperties(self.labelFontProps) label.set_clip_box(self.ax.bbox)
'get the text of the label'
def get_text(self, lev, fmt):
if cbook.is_string_like(lev): return lev elif isinstance(fmt, dict): return fmt[lev] else: return (fmt % lev)
'find a good place to plot a label (relatively flat part of the contour) and the angle of rotation for the text object'
def locate_label(self, linecontour, labelwidth):
nsize = len(linecontour) if (labelwidth > 1): xsize = int(np.ceil((nsize / labelwidth))) else: xsize = 1 if (xsize == 1): ysize = nsize else: ysize = labelwidth XX = np.resize(linecontour[:, 0], (xsize, ysize)) YY = np.resize(linecontour[:, 1], (xsize, ysize)) yfirst = YY[:, 0].reshape(xsize, 1) ylast = YY[:, (-1)].reshape(xsize, 1) xfirst = XX[:, 0].reshape(xsize, 1) xlast = XX[:, (-1)].reshape(xsize, 1) s = (((yfirst - YY) * (xlast - xfirst)) - ((xfirst - XX) * (ylast - yfirst))) L = np.sqrt((((xlast - xfirst) ** 2) + ((ylast - yfirst) ** 2))).ravel() dist = np.add.reduce([(abs(s)[i] / L[i]) for i in range(xsize)], (-1)) (x, y, ind) = self.get_label_coords(dist, XX, YY, ysize, labelwidth) lc = [tuple(l) for l in linecontour] dind = lc.index((x, y)) return (x, y, dind)
'This function calculates the appropriate label rotation given the linecontour coordinates in screen units, the index of the label location and the label width. It will also break contour and calculate inlining if *lc* is not empty (lc defaults to the empty list if None). *spacing* is the space around the label in pixels to leave empty. Do both of these tasks at once to avoid calling mlab.path_length multiple times, which is relatively costly. The method used here involves calculating the path length along the contour in pixel coordinates and then looking approximately label width / 2 away from central point to determine rotation and then to break contour if desired.'
def calc_label_rot_and_inline(self, slc, ind, lw, lc=None, spacing=5):
if (lc is None): lc = [] hlw = (lw / 2.0) closed = mlab.is_closed_polygon(slc) if closed: slc = np.r_[(slc[ind:(-1)], slc[:(ind + 1)])] if len(lc): lc = np.r_[(lc[ind:(-1)], lc[:(ind + 1)])] ind = 0 pl = mlab.path_length(slc) pl = (pl - pl[ind]) xi = np.array([(- hlw), hlw]) if closed: dp = np.array([pl[(-1)], 0]) else: dp = np.zeros_like(xi) ll = mlab.less_simple_linear_interpolation(pl, slc, (dp + xi), extrap=True) dd = np.diff(ll, axis=0).ravel() if np.all((dd == 0)): rotation = 0.0 else: rotation = ((np.arctan2(dd[1], dd[0]) * 180.0) / np.pi) if (rotation > 90): rotation = (rotation - 180.0) if (rotation < (-90)): rotation = (180.0 + rotation) nlc = [] if len(lc): xi = ((dp + xi) + np.array([(- spacing), spacing])) I = mlab.less_simple_linear_interpolation(pl, np.arange(len(pl)), xi, extrap=False) if ((not np.isnan(I[0])) and (int(I[0]) != I[0])): xy1 = mlab.less_simple_linear_interpolation(pl, lc, [xi[0]]) if ((not np.isnan(I[1])) and (int(I[1]) != I[1])): xy2 = mlab.less_simple_linear_interpolation(pl, lc, [xi[1]]) I = [np.floor(I[0]), np.ceil(I[1])] if closed: if np.all((~ np.isnan(I))): nlc.append(np.r_[(xy2, lc[I[1]:(I[0] + 1)], xy1)]) else: if (not np.isnan(I[0])): nlc.append(np.r_[(lc[:(I[0] + 1)], xy1)]) if (not np.isnan(I[1])): nlc.append(np.r_[(xy2, lc[I[1]:])]) return (rotation, nlc)
'Defaults to removing last label, but any index can be supplied'
def pop_label(self, index=(-1)):
self.labelCValues.pop(index) t = self.labelTexts.pop(index) t.remove()
'Draw contour lines or filled regions, depending on whether keyword arg \'filled\' is False (default) or True. The first argument of the initializer must be an axes object. The remaining arguments and keyword arguments are described in ContourSet.contour_doc.'
def __init__(self, ax, *args, **kwargs):
self.ax = ax self.levels = kwargs.get('levels', None) self.filled = kwargs.get('filled', False) self.linewidths = kwargs.get('linewidths', None) self.linestyles = kwargs.get('linestyles', 'solid') self.alpha = kwargs.get('alpha', 1.0) self.origin = kwargs.get('origin', None) self.extent = kwargs.get('extent', None) cmap = kwargs.get('cmap', None) self.colors = kwargs.get('colors', None) norm = kwargs.get('norm', None) self.extend = kwargs.get('extend', 'neither') self.antialiased = kwargs.get('antialiased', True) self.nchunk = kwargs.get('nchunk', 0) self.locator = kwargs.get('locator', None) if (isinstance(norm, colors.LogNorm) or isinstance(self.locator, ticker.LogLocator)): self.logscale = True if (norm is None): norm = colors.LogNorm() if (self.extend is not 'neither'): raise ValueError('extend kwarg does not work yet with log scale') else: self.logscale = False if (self.origin is not None): assert (self.origin in ['lower', 'upper', 'image']) if (self.extent is not None): assert (len(self.extent) == 4) if (cmap is not None): assert isinstance(cmap, colors.Colormap) if ((self.colors is not None) and (cmap is not None)): raise ValueError('Either colors or cmap must be None') if (self.origin == 'image'): self.origin = mpl.rcParams['image.origin'] (x, y, z) = self._contour_args(*args) if (self.colors is not None): cmap = colors.ListedColormap(self.colors, N=len(self.layers)) if self.filled: self.collections = cbook.silent_list('collections.PolyCollection') else: self.collections = cbook.silent_list('collections.LineCollection') self.labelTexts = [] self.labelCValues = [] kw = {'cmap': cmap} if (norm is not None): kw['norm'] = norm cm.ScalarMappable.__init__(self, **kw) self._process_colors() _mask = ma.getmask(z) if (_mask is ma.nomask): _mask = None if self.filled: if (self.linewidths is not None): warnings.warn('linewidths is ignored by contourf') C = _cntr.Cntr(x, y, z.filled(), _mask) lowers = self._levels[:(-1)] uppers = self._levels[1:] for (level, level_upper) in zip(lowers, uppers): nlist = C.trace(level, level_upper, points=0, nchunk=self.nchunk) col = collections.PolyCollection(nlist, antialiaseds=(self.antialiased,), edgecolors='none', alpha=self.alpha) self.ax.add_collection(col) self.collections.append(col) else: tlinewidths = self._process_linewidths() self.tlinewidths = tlinewidths tlinestyles = self._process_linestyles() C = _cntr.Cntr(x, y, z.filled(), _mask) for (level, width, lstyle) in zip(self.levels, tlinewidths, tlinestyles): nlist = C.trace(level, points=0) col = collections.LineCollection(nlist, linewidths=width, linestyle=lstyle, alpha=self.alpha) if ((level < 0.0) and self.monochrome): ls = mpl.rcParams['contour.negative_linestyle'] col.set_linestyle(ls) col.set_label('_nolegend_') self.ax.add_collection(col, False) self.collections.append(col) self.changed() x0 = ma.minimum(x) x1 = ma.maximum(x) y0 = ma.minimum(y) y1 = ma.maximum(y) self.ax.update_datalim([(x0, y0), (x1, y1)]) self.ax.autoscale_view()
'Select contour levels to span the data. We need two more levels for filled contours than for line contours, because for the latter we need to specify the lower and upper boundary of each range. For example, a single contour boundary, say at z = 0, requires only one contour line, but two filled regions, and therefore three levels to provide boundaries for both regions.'
def _autolev(self, z, N):
if (self.locator is None): if self.logscale: self.locator = ticker.LogLocator() else: self.locator = ticker.MaxNLocator((N + 1)) self.locator.create_dummy_axis() zmax = self.zmax zmin = self.zmin self.locator.set_bounds(zmin, zmax) lev = self.locator() zmargin = ((zmax - zmin) * 1e-06) if (zmax >= lev[(-1)]): lev[(-1)] += zmargin if (zmin <= lev[0]): if self.logscale: lev[0] = (0.99 * zmin) else: lev[0] -= zmargin self._auto = True if self.filled: return lev return lev[1:(-1)]
'Return X, Y arrays such that contour(Z) will match imshow(Z) if origin is not None. The center of pixel Z[i,j] depends on origin: if origin is None, x = j, y = i; if origin is \'lower\', x = j + 0.5, y = i + 0.5; if origin is \'upper\', x = j + 0.5, y = Nrows - i - 0.5 If extent is not None, x and y will be scaled to match, as in imshow. If origin is None and extent is not None, then extent will give the minimum and maximum values of x and y.'
def _initialize_x_y(self, z):
if (z.ndim != 2): raise TypeError('Input must be a 2D array.') else: (Ny, Nx) = z.shape if (self.origin is None): if (self.extent is None): return np.meshgrid(np.arange(Nx), np.arange(Ny)) else: (x0, x1, y0, y1) = self.extent x = np.linspace(x0, x1, Nx) y = np.linspace(y0, y1, Ny) return np.meshgrid(x, y) if (self.extent is None): (x0, x1, y0, y1) = (0, Nx, 0, Ny) else: (x0, x1, y0, y1) = self.extent dx = (float((x1 - x0)) / Nx) dy = (float((y1 - y0)) / Ny) x = (x0 + ((np.arange(Nx) + 0.5) * dx)) y = (y0 + ((np.arange(Ny) + 0.5) * dy)) if (self.origin == 'upper'): y = y[::(-1)] return np.meshgrid(x, y)
'For functions like contour, check that the dimensions of the input arrays match; if x and y are 1D, convert them to 2D using meshgrid. Possible change: I think we should make and use an ArgumentError Exception class (here and elsewhere).'
def _check_xyz(self, args):
x = self.ax.convert_xunits(args[0]) y = self.ax.convert_yunits(args[1]) x = np.asarray(x, dtype=np.float64) y = np.asarray(y, dtype=np.float64) z = ma.asarray(args[2], dtype=np.float64) if (z.ndim != 2): raise TypeError('Input z must be a 2D array.') else: (Ny, Nx) = z.shape if ((x.shape == z.shape) and (y.shape == z.shape)): return (x, y, z) if ((x.ndim != 1) or (y.ndim != 1)): raise TypeError('Inputs x and y must be 1D or 2D.') (nx,) = x.shape (ny,) = y.shape if ((nx != Nx) or (ny != Ny)): raise TypeError(('Length of x must be number of columns in z,\n' + 'and length of y must be number of rows.')) (x, y) = np.meshgrid(x, y) return (x, y, z)
'Color argument processing for contouring. Note that we base the color mapping on the contour levels, not on the actual range of the Z values. This means we don\'t have to worry about bad values in Z, and we always have the full dynamic range available for the selected levels. The color is based on the midpoint of the layer, except for an extended end layers.'
def _process_colors(self):
self.monochrome = self.cmap.monochrome if (self.colors is not None): (i0, i1) = (0, len(self.layers)) if (self.extend in ('both', 'min')): i0 = (-1) if (self.extend in ('both', 'max')): i1 = (i1 + 1) self.cvalues = range(i0, i1) self.set_norm(colors.NoNorm()) else: self.cvalues = self.layers if (not self.norm.scaled()): self.set_clim(self.vmin, self.vmax) if (self.extend in ('both', 'max', 'min')): self.norm.clip = False self.set_array(self.layers)
'returns alpha to be applied to all ContourSet artists'
def get_alpha(self):
return self.alpha
'sets alpha for all ContourSet artists'
def set_alpha(self, alpha):
self.alpha = alpha self.changed()
'Finds contour that is closest to a point. Defaults to measuring distance in pixels (screen space - useful for manual contour labeling), but this can be controlled via a keyword argument. Returns a tuple containing the contour, segment, index of segment, x & y of segment point and distance to minimum point. Call signature:: conmin,segmin,imin,xmin,ymin,dmin = find_nearest_contour( self, x, y, indices=None, pixel=True ) Optional keyword arguments:: *indices*: Indexes of contour levels to consider when looking for nearest point. Defaults to using all levels. *pixel*: If *True*, measure distance in pixel space, if not, measure distance in axes space. Defaults to *True*.'
def find_nearest_contour(self, x, y, indices=None, pixel=True):
if (indices == None): indices = range(len(self.levels)) dmin = 10000000000.0 conmin = None segmin = None xmin = None ymin = None for icon in indices: con = self.collections[icon] paths = con.get_paths() for (segNum, linepath) in enumerate(paths): lc = linepath.vertices if pixel: lc = self.ax.transData.transform(lc) ds = (((lc[:, 0] - x) ** 2) + ((lc[:, 1] - y) ** 2)) d = min(ds) if (d < dmin): dmin = d conmin = icon segmin = segNum imin = mpl.mlab.find((ds == d))[0] xmin = lc[(imin, 0)] ymin = lc[(imin, 1)] return (conmin, segmin, imin, xmin, ymin, dmin)
'returns a filename based on a hash of the string, fontsize, and dpi'
def get_basefile(self, tex, fontsize, dpi=None):
s = ''.join([tex, self.get_font_config(), ('%f' % fontsize), self.get_custom_preamble(), str((dpi or ''))]) bytes = unicode(s).encode('utf-8') return os.path.join(self.texcache, md5(bytes).hexdigest())
'Reinitializes self if relevant rcParams on have changed.'
def get_font_config(self):
if (self._rc_cache is None): self._rc_cache = dict([(k, None) for k in self._rc_cache_keys]) changed = [par for par in self._rc_cache_keys if (rcParams[par] != self._rc_cache[par])] if changed: if DEBUG: print 'DEBUG following keys changed:', changed for k in changed: if DEBUG: print ('DEBUG %-20s: %-10s -> %-10s' % (k, self._rc_cache[k], rcParams[k])) self._rc_cache[k] = copy.deepcopy(rcParams[k]) if DEBUG: print 'DEBUG RE-INIT\nold fontconfig:', self._fontconfig self.__init__() if DEBUG: print 'DEBUG fontconfig:', self._fontconfig return self._fontconfig
'returns a string containing font configuration for the tex preamble'
def get_font_preamble(self):
return self._font_preamble
'returns a string containing user additions to the tex preamble'
def get_custom_preamble(self):
return '\n'.join(rcParams['text.latex.preamble'])
'On windows, changing directories can be complicated by the presence of multiple drives. get_shell_cmd deals with this issue.'
def _get_shell_cmd(self, *args):
if (sys.platform == 'win32'): command = [('%s' % os.path.splitdrive(self.texcache)[0])] else: command = [] command.extend(args) return ' && '.join(command)
'Generate a tex file to render the tex string at a specific font size returns the file name'
def make_tex(self, tex, fontsize):
basefile = self.get_basefile(tex, fontsize) texfile = ('%s.tex' % basefile) fh = file(texfile, 'w') custom_preamble = self.get_custom_preamble() fontcmd = {'sans-serif': '{\\sffamily %s}', 'monospace': '{\\ttfamily %s}'}.get(self.font_family, '{\\rmfamily %s}') tex = (fontcmd % tex) if rcParams['text.latex.unicode']: unicode_preamble = '\\usepackage{ucs}\n\\usepackage[utf8x]{inputenc}' else: unicode_preamble = '' s = ('\\documentclass{article}\n%s\n%s\n%s\n\\usepackage[papersize={72in,72in}, body={70in,70in}, margin={1in,1in}]{geometry}\n\\pagestyle{empty}\n\\begin{document}\n\\fontsize{%f}{%f}%s\n\\end{document}\n' % (self._font_preamble, unicode_preamble, custom_preamble, fontsize, (fontsize * 1.25), tex)) if rcParams['text.latex.unicode']: fh.write(s.encode('utf8')) else: try: fh.write(s) except UnicodeEncodeError as err: mpl.verbose.report("You are using unicode and latex, but have not enabled the matplotlib 'text.latex.unicode' rcParam.", 'helpful') raise fh.close() return texfile
'generates a dvi file containing latex\'s layout of tex string returns the file name'
def make_dvi(self, tex, fontsize):
basefile = self.get_basefile(tex, fontsize) dvifile = ('%s.dvi' % basefile) if (DEBUG or (not os.path.exists(dvifile))): texfile = self.make_tex(tex, fontsize) outfile = (basefile + '.output') command = self._get_shell_cmd(('cd "%s"' % self.texcache), ('latex -interaction=nonstopmode %s > "%s"' % (os.path.split(texfile)[(-1)], outfile))) mpl.verbose.report(command, 'debug') exit_status = os.system(command) try: fh = file(outfile) report = fh.read() fh.close() except IOError: report = 'No latex error report available.' if exit_status: raise RuntimeError((('LaTeX was not able to process the following string:\n%s\nHere is the full report generated by LaTeX: \n\n' % repr(tex)) + report)) else: mpl.verbose.report(report, 'debug') for fname in glob.glob((basefile + '*')): if fname.endswith('dvi'): pass elif fname.endswith('tex'): pass else: try: os.remove(fname) except OSError: pass return dvifile
'generates a png file containing latex\'s rendering of tex string returns the filename'
def make_png(self, tex, fontsize, dpi):
basefile = self.get_basefile(tex, fontsize, dpi) pngfile = ('%s.png' % basefile) if (DEBUG or (not os.path.exists(pngfile))): dvifile = self.make_dvi(tex, fontsize) outfile = (basefile + '.output') command = self._get_shell_cmd(('cd "%s"' % self.texcache), ('dvipng -bg Transparent -D %s -T tight -o "%s" "%s" > "%s"' % (dpi, os.path.split(pngfile)[(-1)], os.path.split(dvifile)[(-1)], outfile))) mpl.verbose.report(command, 'debug') exit_status = os.system(command) try: fh = file(outfile) report = fh.read() fh.close() except IOError: report = 'No dvipng error report available.' if exit_status: raise RuntimeError((('dvipng was not able to process the flowing file:\n%s\nHere is the full report generated by dvipng: \n\n' % dvifile) + report)) else: mpl.verbose.report(report, 'debug') try: os.remove(outfile) except OSError: pass return pngfile
'generates a postscript file containing latex\'s rendering of tex string returns the file name'
def make_ps(self, tex, fontsize):
basefile = self.get_basefile(tex, fontsize) psfile = ('%s.epsf' % basefile) if (DEBUG or (not os.path.exists(psfile))): dvifile = self.make_dvi(tex, fontsize) outfile = (basefile + '.output') command = self._get_shell_cmd(('cd "%s"' % self.texcache), ('dvips -q -E -o "%s" "%s" > "%s"' % (os.path.split(psfile)[(-1)], os.path.split(dvifile)[(-1)], outfile))) mpl.verbose.report(command, 'debug') exit_status = os.system(command) fh = file(outfile) if exit_status: raise RuntimeError((('dvipng was not able to process the flowing file:\n%s\nHere is the full report generated by dvipng: \n\n' % dvifile) + fh.read())) else: mpl.verbose.report(fh.read(), 'debug') fh.close() os.remove(outfile) return psfile
'returns a list containing the postscript bounding box for latex\'s rendering of the tex string'
def get_ps_bbox(self, tex, fontsize):
psfile = self.make_ps(tex, fontsize) ps = file(psfile) for line in ps: if line.startswith('%%BoundingBox:'): return [int(val) for val in line.split()[1:]] raise RuntimeError(('Could not parse %s' % psfile))
'returns the alpha channel'
def get_grey(self, tex, fontsize=None, dpi=None):
key = (tex, self.get_font_config(), fontsize, dpi) alpha = self.grey_arrayd.get(key) if (alpha is None): pngfile = self.make_png(tex, fontsize, dpi) X = read_png(os.path.join(self.texcache, pngfile)) if (rcParams['text.dvipnghack'] is not None): hack = rcParams['text.dvipnghack'] else: hack = self._dvipng_hack_alpha if hack: alpha = (1 - X[:, :, 0]) else: alpha = X[:, :, (-1)] self.grey_arrayd[key] = alpha return alpha
'Returns latex\'s rendering of the tex string as an rgba array'
def get_rgba(self, tex, fontsize=None, dpi=None, rgb=(0, 0, 0)):
if (not fontsize): fontsize = rcParams['font.size'] if (not dpi): dpi = rcParams['savefig.dpi'] (r, g, b) = rgb key = (tex, self.get_font_config(), fontsize, dpi, tuple(rgb)) Z = self.rgba_arrayd.get(key) if (Z is None): alpha = self.get_grey(tex, fontsize, dpi) Z = np.zeros((alpha.shape[0], alpha.shape[1], 4), np.float) Z[:, :, 0] = r Z[:, :, 1] = g Z[:, :, 2] = b Z[:, :, 3] = alpha self.rgba_arrayd[key] = Z return Z
'Return the cell Text intance'
def get_text(self):
return self._text
'Return the cell fontsize'
def get_fontsize(self):
return self._text.get_fontsize()
'Shrink font size until text fits.'
def auto_set_font_size(self, renderer):
fontsize = self.get_fontsize() required = self.get_required_width(renderer) while ((fontsize > 1) and (required > self.get_width())): fontsize -= 1 self.set_fontsize(fontsize) required = self.get_required_width(renderer) return fontsize
'Set text up so it draws in the right place. Currently support \'left\', \'center\' and \'right\''
def _set_text_position(self, renderer):
bbox = self.get_window_extent(renderer) (l, b, w, h) = bbox.bounds self._text.set_verticalalignment('center') y = (b + (h / 2.0)) if (self._loc == 'center'): self._text.set_horizontalalignment('center') x = (l + (w / 2.0)) elif (self._loc == 'left'): self._text.set_horizontalalignment('left') x = (l + (w * self.PAD)) else: self._text.set_horizontalalignment('right') x = (l + (w * (1.0 - self.PAD))) self._text.set_position((x, y))
'Get text bounds in axes co-ordinates.'
def get_text_bounds(self, renderer):
bbox = self._text.get_window_extent(renderer) bboxa = bbox.inverse_transformed(self.get_data_transform()) return bboxa.bounds
'Get width required for this cell.'
def get_required_width(self, renderer):
(l, b, w, h) = self.get_text_bounds(renderer) return (w * (1.0 + (2.0 * self.PAD)))
'update the text properties with kwargs'
def set_text_props(self, **kwargs):
self._text.update(kwargs)
'Add a cell to the table.'
def add_cell(self, row, col, *args, **kwargs):
xy = (0, 0) cell = Cell(xy, *args, **kwargs) cell.set_figure(self.figure) cell.set_transform(self.get_transform()) cell.set_clip_on(False) self._cells[(row, col)] = cell
'Get a bbox, in axes co-ordinates for the cells. Only include those in the range (0,0) to (maxRow, maxCol)'
def _get_grid_bbox(self, renderer):
boxes = [self._cells[pos].get_window_extent(renderer) for pos in self._cells.keys() if ((pos[0] >= 0) and (pos[1] >= 0))] bbox = Bbox.union(boxes) return bbox.inverse_transformed(self.get_transform())
'Test whether the mouse event occurred in the table. Returns T/F, {}'
def contains(self, mouseevent):
if callable(self._contains): return self._contains(self, mouseevent) if (self._cachedRenderer is not None): boxes = [self._cells[pos].get_window_extent(self._cachedRenderer) for pos in self._cells.keys() if ((pos[0] >= 0) and (pos[1] >= 0))] bbox = bbox_all(boxes) return (bbox.contains(mouseevent.x, mouseevent.y), {}) else: return (False, {})
'Return the Artists contained by the table'
def get_children(self):
return self._cells.values()
'Return the bounding box of the table in window coords'
def get_window_extent(self, renderer):
boxes = [c.get_window_extent(renderer) for c in self._cells] return bbox_all(boxes)
'Calculate row heights and column widths. Position cells accordingly.'
def _do_cell_alignment(self):
widths = {} heights = {} for ((row, col), cell) in self._cells.iteritems(): height = heights.setdefault(row, 0.0) heights[row] = max(height, cell.get_height()) width = widths.setdefault(col, 0.0) widths[col] = max(width, cell.get_width()) xpos = 0 lefts = {} cols = widths.keys() cols.sort() for col in cols: lefts[col] = xpos xpos += widths[col] ypos = 0 bottoms = {} rows = heights.keys() rows.sort() rows.reverse() for row in rows: bottoms[row] = ypos ypos += heights[row] for ((row, col), cell) in self._cells.iteritems(): cell.set_x(lefts[col]) cell.set_y(bottoms[row])
'Automagically set width for column.'
def _auto_set_column_width(self, col, renderer):
cells = [key for key in self._cells if (key[1] == col)] width = 0 for cell in cells: c = self._cells[cell] width = max(c.get_required_width(renderer), width) for cell in cells: self._cells[cell].set_width(width)
'Automatically set font size.'
def auto_set_font_size(self, value=True):
self._autoFontsize = value
'Scale column widths by xscale and row heights by yscale.'
def scale(self, xscale, yscale):
for c in self._cells.itervalues(): c.set_width((c.get_width() * xscale)) c.set_height((c.get_height() * yscale))
'Set the fontsize of the cell text ACCEPTS: a float in points'
def set_fontsize(self, size):
for cell in self._cells.itervalues(): cell.set_fontsize(size)
'Move all the artists by ox,oy (axes coords)'
def _offset(self, ox, oy):
for c in self._cells.itervalues(): (x, y) = (c.get_x(), c.get_y()) c.set_x((x + ox)) c.set_y((y + oy))
'return a dict of cells in the table'
def get_celld(self):
return self._cells
'Generate index array that picks out unique x,y points. This appears to be required by the underlying delaunay triangulation code.'
def _collapse_duplicate_points(self):
j_sorted = np.lexsort(keys=(self.x, self.y)) mask_unique = np.hstack([True, ((np.diff(self.x[j_sorted]) != 0) | (np.diff(self.y[j_sorted]) != 0))]) return j_sorted[mask_unique]
'Extract the convex hull from the triangulation information. The output will be a list of point_id\'s in counter-clockwise order forming the convex hull of the data set.'
def _compute_convex_hull(self):
border = (self.triangle_neighbors == (-1)) edges = {} edges.update(dict(zip(self.triangle_nodes[border[:, 0]][:, 1], self.triangle_nodes[border[:, 0]][:, 2]))) edges.update(dict(zip(self.triangle_nodes[border[:, 1]][:, 2], self.triangle_nodes[border[:, 1]][:, 0]))) edges.update(dict(zip(self.triangle_nodes[border[:, 2]][:, 0], self.triangle_nodes[border[:, 2]][:, 1]))) hull = list(edges.popitem()) while edges: hull.append(edges.pop(hull[(-1)])) hull.pop() return hull
'Get an object which can interpolate within the convex hull by assigning a plane to each triangle. z -- an array of floats giving the known function values at each point in the triangulation.'
def linear_interpolator(self, z, default_value=np.nan):
z = np.asarray(z, dtype=np.float64) if (z.shape != self.old_shape): raise ValueError('z must be the same shape as x and y') if (self.j_unique is not None): z = z[self.j_unique] return LinearInterpolator(self, z, default_value)
'Get an object which can interpolate within the convex hull by the natural neighbors method. z -- an array of floats giving the known function values at each point in the triangulation.'
def nn_interpolator(self, z, default_value=np.nan):
z = np.asarray(z, dtype=np.float64) if (z.shape != self.old_shape): raise ValueError('z must be the same shape as x and y') if (self.j_unique is not None): z = z[self.j_unique] return NNInterpolator(self, z, default_value)
'Return a graph of node_id\'s pointing to node_id\'s. The arcs of the graph correspond to the edges in the triangulation. {node_id: set([node_id, ...]), ...}'
def node_graph(self):
g = {} for (i, j) in self.edge_db: s = g.setdefault(i, set()) s.add(j) s = g.setdefault(j, set()) s.add(i) return g
'Initialise a wxWindows renderer instance.'
def __init__(self, bitmap, dpi):
DEBUG_MSG('__init__()', 1, self) if (wx.VERSION_STRING < '2.8'): raise RuntimeError('matplotlib no longer supports wxPython < 2.8 for the Wx backend.\nYou may, however, use the WxAgg backend.') self.width = bitmap.GetWidth() self.height = bitmap.GetHeight() self.bitmap = bitmap self.fontd = {} self.dpi = dpi self.gc = None
'get the width and height in display coords of the string s with FontPropertry prop'
def get_text_width_height_descent(self, s, prop, ismath):
if ismath: s = self.strip_math(s) if (self.gc is None): gc = self.new_gc() else: gc = self.gc gfx_ctx = gc.gfx_ctx font = self.get_wx_font(s, prop) gfx_ctx.SetFont(font, wx.BLACK) (w, h, descent, leading) = gfx_ctx.GetFullTextExtent(s) return (w, h, descent)
'return the canvas width and height in display coords'
def get_canvas_width_height(self):
return (self.width, self.height)
'Render the matplotlib.text.Text instance None)'
def draw_text(self, gc, x, y, s, prop, angle, ismath):
if ismath: s = self.strip_math(s) DEBUG_MSG('draw_text()', 1, self) gc.select() self.handle_clip_rectangle(gc) gfx_ctx = gc.gfx_ctx font = self.get_wx_font(s, prop) color = gc.get_wxcolour(gc.get_rgb()) gfx_ctx.SetFont(font, color) (w, h, d) = self.get_text_width_height_descent(s, prop, ismath) x = int(x) y = int((y - h)) if (angle == 0.0): gfx_ctx.DrawText(s, x, y) else: rads = ((angle / 180.0) * math.pi) xo = (h * math.sin(rads)) yo = (h * math.cos(rads)) gfx_ctx.DrawRotatedText(s, (x - xo), (y - yo), rads) gc.unselect()
'Return an instance of a GraphicsContextWx, and sets the current gc copy'
def new_gc(self):
DEBUG_MSG('new_gc()', 2, self) self.gc = GraphicsContextWx(self.bitmap, self) self.gc.select() self.gc.unselect() return self.gc
'Fetch the locally cached gc.'
def get_gc(self):
assert (self.gc != None), 'gc must be defined' return self.gc
'Return a wx font. Cache instances in a font dictionary for efficiency'
def get_wx_font(self, s, prop):
DEBUG_MSG('get_wx_font()', 1, self) key = hash(prop) fontprop = prop fontname = fontprop.get_name() font = self.fontd.get(key) if (font is not None): return font wxFontname = self.fontnames.get(fontname, wx.ROMAN) wxFacename = '' size = self.points_to_pixels(fontprop.get_size_in_points()) font = wx.Font(int((size + 0.5)), wxFontname, self.fontangles[fontprop.get_style()], self.fontweights[fontprop.get_weight()], False, wxFacename) self.fontd[key] = font return font
'convert point measures to pixes using dpi and the pixels per inch of the display'
def points_to_pixels(self, points):
return (points * (((PIXELS_PER_INCH / 72.0) * self.dpi) / 72.0))
'Select the current bitmap into this wxDC instance'
def select(self):
if (sys.platform == 'win32'): self.dc.SelectObject(self.bitmap) self.IsSelected = True
'Select a Null bitmasp into this wxDC instance'
def unselect(self):
if (sys.platform == 'win32'): self.dc.SelectObject(wx.NullBitmap) self.IsSelected = False
'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.'
def set_foreground(self, fg, isRGB=None):
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()
'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.'
def set_graylevel(self, frac):
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()
'Set the line width.'
def set_linewidth(self, w):
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()
'Set the capstyle as a string in (\'butt\', \'round\', \'projecting\')'
def set_capstyle(self, cs):
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()
'Set the join style to be one of (\'miter\', \'round\', \'bevel\')'
def set_joinstyle(self, js):
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()
'Set the line style to be one of'
def set_linestyle(self, ls):
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 if (wx.Platform == '__WXMSW__'): self.set_linewidth(1) self._pen.SetStyle(self._style) self.gfx_ctx.SetPen(self._pen) self.unselect()
'return a wx.Colour from RGB format'
def get_wxcolour(self, color):
DEBUG_MSG('get_wx_color()', 1, self) if (len(color) == 3): (r, g, b) = color r *= 255 g *= 255 b *= 255 return wx.Colour(red=int(r), green=int(g), blue=int(b)) else: (r, g, b, a) = color r *= 255 g *= 255 b *= 255 a *= 255 return wx.Colour(red=int(r), green=int(g), blue=int(b), alpha=int(a))
'Initialise a FigureWx instance. - Initialise the FigureCanvasBase and wxPanel parents. - Set event handlers for: EVT_SIZE (Resize event) EVT_PAINT (Paint event)'
def __init__(self, parent, id, figure):
FigureCanvasBase.__init__(self, figure) (l, b, w, h) = figure.bbox.bounds w = int(math.ceil(w)) h = int(math.ceil(h)) wx.Panel.__init__(self, parent, id, size=wx.Size(w, h)) def do_nothing(*args, **kwargs): warnings.warn(('could not find a setinitialsize function for backend_wx; please report your wxpython version=%s to the matplotlib developers list' % backend_version)) pass try: getattr(self, 'SetInitialSize') except AttributeError: self.SetInitialSize = getattr(self, 'SetBestFittingSize', do_nothing) if (not hasattr(self, 'IsShownOnScreen')): self.IsShownOnScreen = getattr(self, 'IsVisible', (lambda *args: True)) self.bitmap = wx.EmptyBitmap(w, h) DEBUG_MSG(('__init__() - bitmap w:%d h:%d' % (w, h)), 2, self) self._isDrawn = False bind(self, wx.EVT_SIZE, self._onSize) bind(self, wx.EVT_PAINT, self._onPaint) bind(self, wx.EVT_ERASE_BACKGROUND, self._onEraseBackground) bind(self, wx.EVT_KEY_DOWN, self._onKeyDown) bind(self, wx.EVT_KEY_UP, self._onKeyUp) bind(self, wx.EVT_RIGHT_DOWN, self._onRightButtonDown) bind(self, wx.EVT_RIGHT_DCLICK, self._onRightButtonDown) bind(self, wx.EVT_RIGHT_UP, self._onRightButtonUp) bind(self, wx.EVT_MOUSEWHEEL, self._onMouseWheel) bind(self, wx.EVT_LEFT_DOWN, self._onLeftButtonDown) bind(self, wx.EVT_LEFT_DCLICK, self._onLeftButtonDown) bind(self, wx.EVT_LEFT_UP, self._onLeftButtonUp) bind(self, wx.EVT_MOTION, self._onMotion) bind(self, wx.EVT_LEAVE_WINDOW, self._onLeave) bind(self, wx.EVT_ENTER_WINDOW, self._onEnter) bind(self, wx.EVT_IDLE, self._onIdle) self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM) self.macros = {} self.Printer_Init()
'copy bitmap of canvas to system clipboard'
def Copy_to_Clipboard(self, event=None):
bmp_obj = wx.BitmapDataObject() bmp_obj.SetBitmap(self.bitmap) wx.TheClipboard.Open() wx.TheClipboard.SetData(bmp_obj) wx.TheClipboard.Close()
'initialize printer settings using wx methods'
def Printer_Init(self):
self.printerData = wx.PrintData() self.printerData.SetPaperId(wx.PAPER_LETTER) self.printerData.SetPrintMode(wx.PRINT_MODE_PRINTER) self.printerPageData = wx.PageSetupDialogData() self.printerPageData.SetMarginBottomRight((25, 25)) self.printerPageData.SetMarginTopLeft((25, 25)) self.printerPageData.SetPrintData(self.printerData) self.printer_width = 5.5 self.printer_margin = 0.5
'set up figure for printing. The standard wx Printer Setup Dialog seems to die easily. Therefore, this setup simply asks for image width and margin for printing.'
def Printer_Setup(self, event=None):
dmsg = 'Width of output figure in inches.\nThe current aspect ration will be kept.' dlg = wx.Dialog(self, (-1), 'Page Setup for Printing', ((-1), (-1))) df = dlg.GetFont() df.SetWeight(wx.NORMAL) df.SetPointSize(11) dlg.SetFont(df) x_wid = wx.TextCtrl(dlg, (-1), value=('%.2f' % self.printer_width), size=(70, (-1))) x_mrg = wx.TextCtrl(dlg, (-1), value=('%.2f' % self.printer_margin), size=(70, (-1))) sizerAll = wx.BoxSizer(wx.VERTICAL) sizerAll.Add(wx.StaticText(dlg, (-1), dmsg), 0, (wx.ALL | wx.EXPAND), 5) sizer = wx.FlexGridSizer(0, 3) sizerAll.Add(sizer, 0, (wx.ALL | wx.EXPAND), 5) sizer.Add(wx.StaticText(dlg, (-1), 'Figure Width'), 1, (wx.ALIGN_LEFT | wx.ALL), 2) sizer.Add(x_wid, 1, (wx.ALIGN_LEFT | wx.ALL), 2) sizer.Add(wx.StaticText(dlg, (-1), 'in'), 1, (wx.ALIGN_LEFT | wx.ALL), 2) sizer.Add(wx.StaticText(dlg, (-1), 'Margin'), 1, (wx.ALIGN_LEFT | wx.ALL), 2) sizer.Add(x_mrg, 1, (wx.ALIGN_LEFT | wx.ALL), 2) sizer.Add(wx.StaticText(dlg, (-1), 'in'), 1, (wx.ALIGN_LEFT | wx.ALL), 2) btn = wx.Button(dlg, wx.ID_OK, ' OK ') btn.SetDefault() sizer.Add(btn, 1, wx.ALIGN_LEFT, 5) btn = wx.Button(dlg, wx.ID_CANCEL, ' CANCEL ') sizer.Add(btn, 1, wx.ALIGN_LEFT, 5) dlg.SetSizer(sizerAll) dlg.SetAutoLayout(True) sizerAll.Fit(dlg) if (dlg.ShowModal() == wx.ID_OK): try: self.printer_width = float(x_wid.GetValue()) self.printer_margin = float(x_mrg.GetValue()) except: pass if ((self.printer_width + self.printer_margin) > 7.5): self.printerData.SetOrientation(wx.LANDSCAPE) else: self.printerData.SetOrientation(wx.PORTRAIT) dlg.Destroy() return
'set up figure for printing. Using the standard wx Printer Setup Dialog.'
def Printer_Setup2(self, event=None):
if hasattr(self, 'printerData'): data = wx.PageSetupDialogData() data.SetPrintData(self.printerData) else: data = wx.PageSetupDialogData() data.SetMarginTopLeft((15, 15)) data.SetMarginBottomRight((15, 15)) dlg = wx.PageSetupDialog(self, data) if (dlg.ShowModal() == wx.ID_OK): data = dlg.GetPageSetupData() tl = data.GetMarginTopLeft() br = data.GetMarginBottomRight() self.printerData = wx.PrintData(data.GetPrintData()) dlg.Destroy()
'generate Print Preview with wx Print mechanism'
def Printer_Preview(self, event=None):
po1 = PrintoutWx(self, width=self.printer_width, margin=self.printer_margin) po2 = PrintoutWx(self, width=self.printer_width, margin=self.printer_margin) self.preview = wx.PrintPreview(po1, po2, self.printerData) if (not self.preview.Ok()): print 'error with preview' self.preview.SetZoom(50) frameInst = self while (not isinstance(frameInst, wx.Frame)): frameInst = frameInst.GetParent() frame = wx.PreviewFrame(self.preview, frameInst, 'Preview') frame.Initialize() frame.SetPosition(self.GetPosition()) frame.SetSize((850, 650)) frame.Centre(wx.BOTH) frame.Show(True) self.gui_repaint()
'Print figure using wx Print mechanism'
def Printer_Print(self, event=None):
pdd = wx.PrintDialogData() pdd.SetPrintData(self.printerData) pdd.SetToPage(1) printer = wx.Printer(pdd) printout = PrintoutWx(self, width=int(self.printer_width), margin=int(self.printer_margin)) print_ok = printer.Print(self, printout, True) if (wx.VERSION_STRING >= '2.5'): if ((not print_ok) and (not (printer.GetLastError() == wx.PRINTER_CANCELLED))): wx.MessageBox('There was a problem printing.\n Perhaps your current printer is not set correctly?', 'Printing', wx.OK) elif (not print_ok): wx.MessageBox('There was a problem printing.\n Perhaps your current printer is not set correctly?', 'Printing', wx.OK) printout.Destroy() self.gui_repaint()
'Delay rendering until the GUI is idle.'
def draw_idle(self):
DEBUG_MSG('draw_idle()', 1, self) self._isDrawn = False if hasattr(self, '_idletimer'): self._idletimer.Restart(IDLE_DELAY) else: self._idletimer = wx.FutureCall(IDLE_DELAY, self._onDrawIdle)
'Render the figure using RendererWx instance renderer, or using a previously defined renderer if none is specified.'
def draw(self, drawDC=None):
DEBUG_MSG('draw()', 1, self) self.renderer = RendererWx(self.bitmap, self.figure.dpi) self.figure.draw(self.renderer) self._isDrawn = True self.gui_repaint(drawDC=drawDC)
'Start an event loop. This is used to start a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This should not be confused with the main GUI event loop, which is always running and has nothing to do with this. Call signature:: start_event_loop(self,timeout=0) This call blocks until a callback function triggers stop_event_loop() or *timeout* is reached. If *timeout* is <=0, never timeout. Raises RuntimeError if event loop is already running.'
def start_event_loop(self, timeout=0):
if hasattr(self, '_event_loop'): raise RuntimeError('Event loop already running') id = wx.NewId() timer = wx.Timer(self, id=id) if (timeout > 0): timer.Start((timeout * 1000), oneShot=True) bind(self, wx.EVT_TIMER, self.stop_event_loop, id=id) self._event_loop = wx.EventLoop() self._event_loop.Run() timer.Stop()
'Stop an event loop. This is used to stop a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. Call signature:: stop_event_loop_default(self)'
def stop_event_loop(self, event=None):
if hasattr(self, '_event_loop'): if self._event_loop.IsRunning(): self._event_loop.Exit() del self._event_loop
'return the wildcard string for the filesave dialog'
def _get_imagesave_wildcards(self):
default_filetype = self.get_default_filetype() filetypes = self.get_supported_filetypes_grouped() sorted_filetypes = filetypes.items() sorted_filetypes.sort() wildcards = [] extensions = [] filter_index = 0 for (i, (name, exts)) in enumerate(sorted_filetypes): ext_list = ';'.join([('*.%s' % ext) for ext in exts]) extensions.append(exts[0]) wildcard = ('%s (%s)|%s' % (name, ext_list, ext_list)) if (default_filetype in exts): filter_index = i wildcards.append(wildcard) wildcards = '|'.join(wildcards) return (wildcards, extensions, filter_index)
'Performs update of the displayed image on the GUI canvas, using the supplied device context. If drawDC is None, a ClientDC will be used to redraw the image.'
def gui_repaint(self, drawDC=None):
DEBUG_MSG('gui_repaint()', 1, self) if self.IsShownOnScreen(): if (drawDC is None): drawDC = wx.ClientDC(self) drawDC.BeginDrawing() drawDC.DrawBitmap(self.bitmap, 0, 0) drawDC.EndDrawing() else: pass