From: <ef...@us...> - 2009-01-20 03:22:09
|
Revision: 6811 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6811&view=rev Author: efiring Date: 2009-01-20 02:03:42 +0000 (Tue, 20 Jan 2009) Log Message: ----------- Fix bug in quiver argument handling. Modified Paths: -------------- branches/v0_98_5_maint/CHANGELOG branches/v0_98_5_maint/lib/matplotlib/quiver.py Modified: branches/v0_98_5_maint/CHANGELOG =================================================================== --- branches/v0_98_5_maint/CHANGELOG 2009-01-19 18:11:35 UTC (rev 6810) +++ branches/v0_98_5_maint/CHANGELOG 2009-01-20 02:03:42 UTC (rev 6811) @@ -1,3 +1,5 @@ +2009-01-19 Fix bug in quiver argument handling. - EF + 2009-01-19 Fix bug in backend_gtk: don't delete nonexistent toolbar. - EF 2009-01-16 Fix bug in is_string_like so it doesn't raise an Modified: branches/v0_98_5_maint/lib/matplotlib/quiver.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/quiver.py 2009-01-19 18:11:35 UTC (rev 6810) +++ branches/v0_98_5_maint/lib/matplotlib/quiver.py 2009-01-20 02:03:42 UTC (rev 6811) @@ -386,14 +386,13 @@ X, Y, U, V, C = [None]*5 args = list(args) if len(args) == 3 or len(args) == 5: - C = ma.asarray(args.pop(-1)).ravel() + C = ma.asarray(args.pop(-1)) V = ma.asarray(args.pop(-1)) U = ma.asarray(args.pop(-1)) - nn = np.shape(U) - nc = nn[0] - nr = 1 - if len(nn) > 1: - nr = nn[1] + if U.ndim == 1: + nr, nc = 1, U.shape[0] + else: + nr, nc = U.shape if len(args) == 2: # remaining after removing U,V,C X, Y = [np.array(a).ravel() for a in args] if len(X) == nc and len(Y) == nr: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2009-01-26 14:32:47
|
Revision: 6827 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6827&view=rev Author: mdboom Date: 2009-01-26 14:32:42 +0000 (Mon, 26 Jan 2009) Log Message: ----------- Make curves and NaNs play nice together Modified Paths: -------------- branches/v0_98_5_maint/CHANGELOG branches/v0_98_5_maint/lib/matplotlib/patches.py branches/v0_98_5_maint/lib/matplotlib/path.py branches/v0_98_5_maint/src/agg_py_path_iterator.h Modified: branches/v0_98_5_maint/CHANGELOG =================================================================== --- branches/v0_98_5_maint/CHANGELOG 2009-01-25 14:38:48 UTC (rev 6826) +++ branches/v0_98_5_maint/CHANGELOG 2009-01-26 14:32:42 UTC (rev 6827) @@ -1,3 +1,5 @@ +2009-01-26 Make curves and NaNs play nice together - MGD + 2009-01-19 Fix bug in quiver argument handling. - EF 2009-01-19 Fix bug in backend_gtk: don't delete nonexistent toolbar. - EF Modified: branches/v0_98_5_maint/lib/matplotlib/patches.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/patches.py 2009-01-25 14:38:48 UTC (rev 6826) +++ branches/v0_98_5_maint/lib/matplotlib/patches.py 2009-01-26 14:32:42 UTC (rev 6827) @@ -298,8 +298,7 @@ tpath = transform.transform_path_non_affine(path) affine = transform.get_affine() - if not np.isnan(tpath.vertices).any(): - renderer.draw_path(gc, tpath, affine, rgbFace) + renderer.draw_path(gc, tpath, affine, rgbFace) #renderer.close_group('patch') Modified: branches/v0_98_5_maint/lib/matplotlib/path.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/path.py 2009-01-25 14:38:48 UTC (rev 6826) +++ branches/v0_98_5_maint/lib/matplotlib/path.py 2009-01-26 14:32:42 UTC (rev 6827) @@ -214,7 +214,8 @@ if not isfinite(curr_vertices).all(): was_nan = True elif was_nan: - yield curr_vertices[-2:], MOVETO + yield curr_vertices[:2], MOVETO + yield curr_vertices, code was_nan = False else: yield curr_vertices, code Modified: branches/v0_98_5_maint/src/agg_py_path_iterator.h =================================================================== --- branches/v0_98_5_maint/src/agg_py_path_iterator.h 2009-01-25 14:38:48 UTC (rev 6826) +++ branches/v0_98_5_maint/src/agg_py_path_iterator.h 2009-01-26 14:32:42 UTC (rev 6827) @@ -15,7 +15,10 @@ PyArrayObject* m_codes; size_t m_iterator; size_t m_total_vertices; + size_t m_ok; bool m_should_simplify; + static const unsigned char num_extra_points_map[16]; + static const unsigned code_map[]; public: PathIterator(const Py::Object& path_obj) : @@ -41,6 +44,7 @@ throw Py::ValueError("Invalid codes array."); if (PyArray_DIM(m_codes, 0) != PyArray_DIM(m_vertices, 0)) throw Py::ValueError("Codes array is wrong length"); + m_ok = 0; } m_should_simplify = should_simplify_obj.isTrue(); @@ -53,8 +57,6 @@ Py_XDECREF(m_codes); } - static const unsigned code_map[]; - private: inline void vertex(const unsigned idx, double* x, double* y) { @@ -82,20 +84,86 @@ if (m_iterator >= m_total_vertices) return agg::path_cmd_stop; unsigned code = vertex_with_code(m_iterator++, x, y); - if (MPL_notisfinite64(*x) || MPL_notisfinite64(*y)) - { - do + if (!m_codes) { + // This is the fast path for when we know we have no curves + if (MPL_notisfinite64(*x) || MPL_notisfinite64(*y)) { - if (m_iterator < m_total_vertices) + do { - vertex(m_iterator++, x, y); + if (m_iterator < m_total_vertices) + { + vertex(m_iterator++, x, y); + } + else + { + return agg::path_cmd_stop; + } + } while (MPL_notisfinite64(*x) || MPL_notisfinite64(*y)); + return agg::path_cmd_move_to; + } + } + else + { + // This is the slow method for when there might be curves. + + /* If m_ok is 0, we look ahead to see if the next curve + segment has any NaNs. If it does, we skip the whole + thing and return a move_to to the first point of the + next curve segment. This move_to may include NaNs, + which is ok, since in that case, it will always be + followed by another non-NaN move_to before any other + curves are actually drawn. If the current curve + segment doesn't have NaNs, we set the m_ok counter to + the number of points in the curve segment, which will + skip this check for the next N points. + */ + if (m_ok == 0) { + if (code == agg::path_cmd_stop || + code == (agg::path_cmd_end_poly | agg::path_flags_close)) + { + return code; } - else + + size_t num_extra_points = num_extra_points_map[code & 0xF]; + bool has_nan = (MPL_notisfinite64(*x) || MPL_notisfinite64(*y)); + for (size_t i = 0; !has_nan && i < num_extra_points; ++i) { - return agg::path_cmd_stop; + double x0, y0; + vertex(m_iterator + i, &x0, &y0); + has_nan = (MPL_notisfinite64(x0) || MPL_notisfinite64(y0)); } - } while (MPL_notisfinite64(*x) || MPL_notisfinite64(*y)); - return agg::path_cmd_move_to; + + if (has_nan) + { + m_iterator += num_extra_points; + if (m_iterator < m_total_vertices) + { + code = vertex_with_code(m_iterator, x, y); + if (code == agg::path_cmd_stop || + code == (agg::path_cmd_end_poly | agg::path_flags_close)) + { + return code; + } + else + { + return agg::path_cmd_move_to; + } + } + else + { + return agg::path_cmd_stop; + } + } + else /* !has_nan */ + { + m_ok = num_extra_points; + return code; + } + } + else /* m_ok != 0 */ + { + m_ok--; + } } return code; @@ -127,6 +195,12 @@ agg::path_cmd_end_poly | agg::path_flags_close }; +const unsigned char PathIterator::num_extra_points_map[] = + {0, 0, 0, 1, + 2, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0}; + #define DEBUG_SIMPLIFY 0 template<class VertexSource> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2009-01-29 22:46:08
|
Revision: 6854 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6854&view=rev Author: mdboom Date: 2009-01-29 21:36:54 +0000 (Thu, 29 Jan 2009) Log Message: ----------- Document the 'resolution' kwarg to polar plots. Modified Paths: -------------- branches/v0_98_5_maint/CHANGELOG branches/v0_98_5_maint/lib/matplotlib/projections/polar.py branches/v0_98_5_maint/lib/matplotlib/pyplot.py Modified: branches/v0_98_5_maint/CHANGELOG =================================================================== --- branches/v0_98_5_maint/CHANGELOG 2009-01-29 21:01:45 UTC (rev 6853) +++ branches/v0_98_5_maint/CHANGELOG 2009-01-29 21:36:54 UTC (rev 6854) @@ -1,3 +1,6 @@ +2009-01-29 Document 'resolution' kwarg for polar plots. Support it + when using pyplot.polar, not just Figure.add_axes. - MGD + 2009-01-26 Make curves and NaNs play nice together - MGD 2009-01-19 Fix bug in quiver argument handling. - EF Modified: branches/v0_98_5_maint/lib/matplotlib/projections/polar.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/projections/polar.py 2009-01-29 21:01:45 UTC (rev 6853) +++ branches/v0_98_5_maint/lib/matplotlib/projections/polar.py 2009-01-29 21:36:54 UTC (rev 6854) @@ -182,10 +182,18 @@ def __init__(self, *args, **kwargs): """ Create a new Polar Axes for a polar plot. + + The following optional kwargs are supported: + + - *resolution*: The number of points of interpolation between + each pair of data points. Set to 1 to disable + interpolation. """ self._rpad = 0.05 - self.resolution = kwargs.pop('resolution', self.RESOLUTION) + self.resolution = kwargs.pop('resolution', None) + if self.resolution is None: + self.resolution = self.RESOLUTION Axes.__init__(self, *args, **kwargs) self.set_aspect('equal', adjustable='box', anchor='C') self.cla() Modified: branches/v0_98_5_maint/lib/matplotlib/pyplot.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/pyplot.py 2009-01-29 21:01:45 UTC (rev 6853) +++ branches/v0_98_5_maint/lib/matplotlib/pyplot.py 2009-01-29 21:36:54 UTC (rev 6854) @@ -1406,8 +1406,13 @@ Make a polar plot. Multiple *theta*, *r* arguments are supported, with format strings, as in :func:`~matplotlib.pyplot.plot`. + + An optional kwarg *resolution* sets the number of vertices to + interpolate between each pair of points. Set to 1 to disable + interpolation. """ - ax = gca(polar=True) + resolution = kwargs.pop('resolution', None) + ax = gca(polar=True, resolution=resolution) ret = ax.plot(*args, **kwargs) draw_if_interactive() return ret This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2009-01-30 16:19:53
|
Revision: 6859 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6859&view=rev Author: jdh2358 Date: 2009-01-30 16:19:49 +0000 (Fri, 30 Jan 2009) Log Message: ----------- purge pyexcelerator refs from docstrings, etc Modified Paths: -------------- branches/v0_98_5_maint/examples/pylab_examples/loadrec.py branches/v0_98_5_maint/lib/mpl_toolkits/exceltools.py branches/v0_98_5_maint/lib/mpl_toolkits/gtktools.py Modified: branches/v0_98_5_maint/examples/pylab_examples/loadrec.py =================================================================== --- branches/v0_98_5_maint/examples/pylab_examples/loadrec.py 2009-01-30 16:19:24 UTC (rev 6858) +++ branches/v0_98_5_maint/examples/pylab_examples/loadrec.py 2009-01-30 16:19:49 UTC (rev 6859) @@ -10,7 +10,7 @@ ax.plot(a.date, a.adj_close, '-') fig.autofmt_xdate() -# if you have pyExcelerator installed, you can output excel +# if you have xlwt installed, you can output excel #import mpl_toolkits.exceltools as exceltools #exceltools.rec2excel(a, 'test.xls', colnum=4) show() Modified: branches/v0_98_5_maint/lib/mpl_toolkits/exceltools.py =================================================================== --- branches/v0_98_5_maint/lib/mpl_toolkits/exceltools.py 2009-01-30 16:19:24 UTC (rev 6858) +++ branches/v0_98_5_maint/lib/mpl_toolkits/exceltools.py 2009-01-30 16:19:49 UTC (rev 6859) @@ -1,5 +1,5 @@ """ -Some io tools for excel -- requires pypyExcelerator +Some io tools for excel -- requires xlwt Example usage: @@ -22,13 +22,7 @@ import copy import numpy as np -try: - import xlwt as excel -except ImportError: - try: - import pyExcelerator as excel - except ImportError: - raise ImportError('You must install xlwt or pyExcelterator to use the exceltools') +import xlwt as excel import matplotlib.cbook as cbook import matplotlib.mlab as mlab @@ -65,7 +59,7 @@ def rec2excel(r, ws, formatd=None, rownum=0, colnum=0, nanstr='NaN', infstr='Inf'): """ - save record array r to excel pyExcelerator worksheet ws + save record array r to excel xlwt worksheet ws starting at rownum. if ws is string like, assume it is a filename and save to it Modified: branches/v0_98_5_maint/lib/mpl_toolkits/gtktools.py =================================================================== --- branches/v0_98_5_maint/lib/mpl_toolkits/gtktools.py 2009-01-30 16:19:24 UTC (rev 6858) +++ branches/v0_98_5_maint/lib/mpl_toolkits/gtktools.py 2009-01-30 16:19:49 UTC (rev 6859) @@ -298,10 +298,6 @@ def rec2gtk(r, formatd=None, rownum=0, autowin=True): """ - save record array r to excel pyExcelerator worksheet ws - starting at rownum. if ws is string like, assume it is a - filename and save to it - formatd is a dictionary mapping dtype name -> mlab.Format instances This function creates a SortedStringsScrolledWindow (derived This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2009-02-04 13:22:39
|
Revision: 6873 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6873&view=rev Author: mdboom Date: 2009-02-04 13:22:35 +0000 (Wed, 04 Feb 2009) Log Message: ----------- Fix bug in mathtext related to \dots and \ldots (Thanks, Fernando Perez) Modified Paths: -------------- branches/v0_98_5_maint/CHANGELOG branches/v0_98_5_maint/examples/pylab_examples/mathtext_examples.py branches/v0_98_5_maint/lib/matplotlib/_mathtext_data.py branches/v0_98_5_maint/lib/matplotlib/mathtext.py Modified: branches/v0_98_5_maint/CHANGELOG =================================================================== --- branches/v0_98_5_maint/CHANGELOG 2009-02-03 22:29:30 UTC (rev 6872) +++ branches/v0_98_5_maint/CHANGELOG 2009-02-04 13:22:35 UTC (rev 6873) @@ -1,3 +1,5 @@ +2009-02-04 Fix bug in mathtext related to \dots and \ldots - MGD + 2009-01-29 Document 'resolution' kwarg for polar plots. Support it when using pyplot.polar, not just Figure.add_axes. - MGD Modified: branches/v0_98_5_maint/examples/pylab_examples/mathtext_examples.py =================================================================== --- branches/v0_98_5_maint/examples/pylab_examples/mathtext_examples.py 2009-02-03 22:29:30 UTC (rev 6872) +++ branches/v0_98_5_maint/examples/pylab_examples/mathtext_examples.py 2009-02-04 13:22:35 UTC (rev 6873) @@ -5,6 +5,7 @@ import gc stests = [ + r'$a+b+\dots+\dot{s}+\ldots$', r'$x \doteq y$', r'\$100.00 $\alpha \_$', r'$\frac{\$100.00}{y}$', Modified: branches/v0_98_5_maint/lib/matplotlib/_mathtext_data.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/_mathtext_data.py 2009-02-03 22:29:30 UTC (rev 6872) +++ branches/v0_98_5_maint/lib/matplotlib/_mathtext_data.py 2009-02-04 13:22:35 UTC (rev 6873) @@ -1805,7 +1805,7 @@ 'Game': 0x2141, 'hbar': 0x0127, 'hslash': 0x210f, -'ldots': 0x22ef, +'ldots': 0x2026, 'vdots': 0x22ee, 'doteqdot': 0x2251, 'doteq': 8784, @@ -2100,7 +2100,7 @@ 'propto': 8733, 'pi': 960, 'pm': 177, -'dots': 8230, +'dots': 0x2026, 'nrightarrow': 8603, 'textasciiacute': 180, 'Doteq': 8785, Modified: branches/v0_98_5_maint/lib/matplotlib/mathtext.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/mathtext.py 2009-02-03 22:29:30 UTC (rev 6872) +++ branches/v0_98_5_maint/lib/matplotlib/mathtext.py 2009-02-04 13:22:35 UTC (rev 6873) @@ -2035,7 +2035,7 @@ \sqsubset \sqsupset \neq \smile \sqsubseteq \sqsupseteq \doteq \frown \in \ni \propto - \vdash \dashv'''.split()) + \vdash \dashv \dots'''.split()) _arrow_symbols = set(r''' \leftarrow \longleftarrow \uparrow @@ -2178,9 +2178,9 @@ + (group | Error("Expected \sqrt{value}")) ).setParseAction(self.sqrt).setName("sqrt") - placeable <<(accent - ^ function + placeable <<(function ^ (c_over_c | symbol) + ^ accent ^ group ^ frac ^ sqrt This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2009-02-16 14:12:18
|
Revision: 6915 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6915&view=rev Author: mdboom Date: 2009-02-16 14:12:13 +0000 (Mon, 16 Feb 2009) Log Message: ----------- Move the mathmpl Sphinx extension to the installed tree so that other projects can take advantage of it. Modified Paths: -------------- branches/v0_98_5_maint/doc/conf.py branches/v0_98_5_maint/setup.py Added Paths: ----------- branches/v0_98_5_maint/lib/matplotlib/sphinxext/ branches/v0_98_5_maint/lib/matplotlib/sphinxext/__init__.py branches/v0_98_5_maint/lib/matplotlib/sphinxext/mathmpl.py branches/v0_98_5_maint/lib/matplotlib/sphinxext/only_directives.py Removed Paths: ------------- branches/v0_98_5_maint/doc/sphinxext/mathmpl.py branches/v0_98_5_maint/doc/sphinxext/only_directives.py Modified: branches/v0_98_5_maint/doc/conf.py =================================================================== --- branches/v0_98_5_maint/doc/conf.py 2009-02-15 00:12:19 UTC (rev 6914) +++ branches/v0_98_5_maint/doc/conf.py 2009-02-16 14:12:13 UTC (rev 6915) @@ -27,9 +27,9 @@ # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['mathmpl', 'math_symbol_table', 'sphinx.ext.autodoc', - 'only_directives', 'plot_directive', 'inheritance_diagram', - 'gen_gallery', 'gen_rst'] +extensions = ['matplotlib.sphinxext.mathmpl', 'math_symbol_table', + 'sphinx.ext.autodoc', 'matplotlib.sphinxext.only_directives', + 'plot_directive', 'inheritance_diagram', 'gen_gallery', 'gen_rst'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] Deleted: branches/v0_98_5_maint/doc/sphinxext/mathmpl.py =================================================================== --- branches/v0_98_5_maint/doc/sphinxext/mathmpl.py 2009-02-15 00:12:19 UTC (rev 6914) +++ branches/v0_98_5_maint/doc/sphinxext/mathmpl.py 2009-02-16 14:12:13 UTC (rev 6915) @@ -1,119 +0,0 @@ -import os -import sys -try: - from hashlib import md5 -except ImportError: - from md5 import md5 - -from docutils import nodes -from docutils.parsers.rst import directives -import warnings - -from matplotlib import rcParams -from matplotlib.mathtext import MathTextParser -rcParams['mathtext.fontset'] = 'cm' -mathtext_parser = MathTextParser("Bitmap") - -# Define LaTeX math node: -class latex_math(nodes.General, nodes.Element): - pass - -def fontset_choice(arg): - return directives.choice(arg, ['cm', 'stix', 'stixsans']) - -options_spec = {'fontset': fontset_choice} - -def math_role(role, rawtext, text, lineno, inliner, - options={}, content=[]): - i = rawtext.find('`') - latex = rawtext[i+1:-1] - node = latex_math(rawtext) - node['latex'] = latex - node['fontset'] = options.get('fontset', 'cm') - return [node], [] -math_role.options = options_spec - -def math_directive(name, arguments, options, content, lineno, - content_offset, block_text, state, state_machine): - latex = ''.join(content) - node = latex_math(block_text) - node['latex'] = latex - node['fontset'] = options.get('fontset', 'cm') - return [node] - -# This uses mathtext to render the expression -def latex2png(latex, filename, fontset='cm'): - latex = "$%s$" % latex - orig_fontset = rcParams['mathtext.fontset'] - rcParams['mathtext.fontset'] = fontset - if os.path.exists(filename): - depth = mathtext_parser.get_depth(latex, dpi=100) - else: - try: - depth = mathtext_parser.to_png(filename, latex, dpi=100) - except: - warnings.warn("Could not render math expression %s" % latex, - Warning) - depth = 0 - rcParams['mathtext.fontset'] = orig_fontset - sys.stdout.write("#") - sys.stdout.flush() - return depth - -# LaTeX to HTML translation stuff: -def latex2html(node, source): - inline = isinstance(node.parent, nodes.TextElement) - latex = node['latex'] - name = 'math-%s' % md5(latex).hexdigest()[-10:] - - destdir = os.path.join(setup.app.builder.outdir, '_images', 'mathmpl') - if not os.path.exists(destdir): - os.makedirs(destdir) - dest = os.path.join(destdir, '%s.png' % name) - path = os.path.join(setup.app.builder.imgpath, 'mathmpl') - - depth = latex2png(latex, dest, node['fontset']) - - if inline: - cls = '' - else: - cls = 'class="center" ' - if inline and depth != 0: - style = 'style="position: relative; bottom: -%dpx"' % (depth + 1) - else: - style = '' - - return '<img src="%s/%s.png" %s%s/>' % (path, name, cls, style) - -def setup(app): - setup.app = app - - app.add_node(latex_math) - app.add_role('math', math_role) - - # Add visit/depart methods to HTML-Translator: - def visit_latex_math_html(self, node): - source = self.document.attributes['source'] - self.body.append(latex2html(node, source)) - def depart_latex_math_html(self, node): - pass - - # Add visit/depart methods to LaTeX-Translator: - def visit_latex_math_latex(self, node): - inline = isinstance(node.parent, nodes.TextElement) - if inline: - self.body.append('$%s$' % node['latex']) - else: - self.body.extend(['\\begin{equation}', - node['latex'], - '\\end{equation}']) - def depart_latex_math_latex(self, node): - pass - - app.add_node(latex_math, html=(visit_latex_math_html, - depart_latex_math_html)) - app.add_node(latex_math, latex=(visit_latex_math_latex, - depart_latex_math_latex)) - app.add_role('math', math_role) - app.add_directive('math', math_directive, - True, (0, 0, 0), **options_spec) Deleted: branches/v0_98_5_maint/doc/sphinxext/only_directives.py =================================================================== --- branches/v0_98_5_maint/doc/sphinxext/only_directives.py 2009-02-15 00:12:19 UTC (rev 6914) +++ branches/v0_98_5_maint/doc/sphinxext/only_directives.py 2009-02-16 14:12:13 UTC (rev 6915) @@ -1,63 +0,0 @@ -# -# A pair of directives for inserting content that will only appear in -# either html or latex. -# - -from docutils.nodes import Body, Element -from docutils.parsers.rst import directives - -class only_base(Body, Element): - def dont_traverse(self, *args, **kwargs): - return [] - -class html_only(only_base): - pass - -class latex_only(only_base): - pass - -def run(content, node_class, state, content_offset): - text = '\n'.join(content) - node = node_class(text) - state.nested_parse(content, content_offset, node) - return [node] - -def html_only_directive(name, arguments, options, content, lineno, - content_offset, block_text, state, state_machine): - return run(content, html_only, state, content_offset) - -def latex_only_directive(name, arguments, options, content, lineno, - content_offset, block_text, state, state_machine): - return run(content, latex_only, state, content_offset) - -def builder_inited(app): - if app.builder.name == 'html': - latex_only.traverse = only_base.dont_traverse - else: - html_only.traverse = only_base.dont_traverse - -def setup(app): - app.add_directive('htmlonly', html_only_directive, True, (0, 0, 0)) - app.add_directive('latexonly', latex_only_directive, True, (0, 0, 0)) - app.add_node(html_only) - app.add_node(latex_only) - - # This will *really* never see the light of day As it turns out, - # this results in "broken" image nodes since they never get - # processed, so best not to do this. - # app.connect('builder-inited', builder_inited) - - # Add visit/depart methods to HTML-Translator: - def visit_perform(self, node): - pass - def depart_perform(self, node): - pass - def visit_ignore(self, node): - node.children = [] - def depart_ignore(self, node): - node.children = [] - - app.add_node(html_only, html=(visit_perform, depart_perform)) - app.add_node(html_only, latex=(visit_ignore, depart_ignore)) - app.add_node(latex_only, latex=(visit_perform, depart_perform)) - app.add_node(latex_only, html=(visit_ignore, depart_ignore)) Added: branches/v0_98_5_maint/lib/matplotlib/sphinxext/__init__.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/sphinxext/__init__.py (rev 0) +++ branches/v0_98_5_maint/lib/matplotlib/sphinxext/__init__.py 2009-02-16 14:12:13 UTC (rev 6915) @@ -0,0 +1 @@ + Copied: branches/v0_98_5_maint/lib/matplotlib/sphinxext/mathmpl.py (from rev 6843, branches/v0_98_5_maint/doc/sphinxext/mathmpl.py) =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/sphinxext/mathmpl.py (rev 0) +++ branches/v0_98_5_maint/lib/matplotlib/sphinxext/mathmpl.py 2009-02-16 14:12:13 UTC (rev 6915) @@ -0,0 +1,119 @@ +import os +import sys +try: + from hashlib import md5 +except ImportError: + from md5 import md5 + +from docutils import nodes +from docutils.parsers.rst import directives +import warnings + +from matplotlib import rcParams +from matplotlib.mathtext import MathTextParser +rcParams['mathtext.fontset'] = 'cm' +mathtext_parser = MathTextParser("Bitmap") + +# Define LaTeX math node: +class latex_math(nodes.General, nodes.Element): + pass + +def fontset_choice(arg): + return directives.choice(arg, ['cm', 'stix', 'stixsans']) + +options_spec = {'fontset': fontset_choice} + +def math_role(role, rawtext, text, lineno, inliner, + options={}, content=[]): + i = rawtext.find('`') + latex = rawtext[i+1:-1] + node = latex_math(rawtext) + node['latex'] = latex + node['fontset'] = options.get('fontset', 'cm') + return [node], [] +math_role.options = options_spec + +def math_directive(name, arguments, options, content, lineno, + content_offset, block_text, state, state_machine): + latex = ''.join(content) + node = latex_math(block_text) + node['latex'] = latex + node['fontset'] = options.get('fontset', 'cm') + return [node] + +# This uses mathtext to render the expression +def latex2png(latex, filename, fontset='cm'): + latex = "$%s$" % latex + orig_fontset = rcParams['mathtext.fontset'] + rcParams['mathtext.fontset'] = fontset + if os.path.exists(filename): + depth = mathtext_parser.get_depth(latex, dpi=100) + else: + try: + depth = mathtext_parser.to_png(filename, latex, dpi=100) + except: + warnings.warn("Could not render math expression %s" % latex, + Warning) + depth = 0 + rcParams['mathtext.fontset'] = orig_fontset + sys.stdout.write("#") + sys.stdout.flush() + return depth + +# LaTeX to HTML translation stuff: +def latex2html(node, source): + inline = isinstance(node.parent, nodes.TextElement) + latex = node['latex'] + name = 'math-%s' % md5(latex).hexdigest()[-10:] + + destdir = os.path.join(setup.app.builder.outdir, '_images', 'mathmpl') + if not os.path.exists(destdir): + os.makedirs(destdir) + dest = os.path.join(destdir, '%s.png' % name) + path = os.path.join(setup.app.builder.imgpath, 'mathmpl') + + depth = latex2png(latex, dest, node['fontset']) + + if inline: + cls = '' + else: + cls = 'class="center" ' + if inline and depth != 0: + style = 'style="position: relative; bottom: -%dpx"' % (depth + 1) + else: + style = '' + + return '<img src="%s/%s.png" %s%s/>' % (path, name, cls, style) + +def setup(app): + setup.app = app + + app.add_node(latex_math) + app.add_role('math', math_role) + + # Add visit/depart methods to HTML-Translator: + def visit_latex_math_html(self, node): + source = self.document.attributes['source'] + self.body.append(latex2html(node, source)) + def depart_latex_math_html(self, node): + pass + + # Add visit/depart methods to LaTeX-Translator: + def visit_latex_math_latex(self, node): + inline = isinstance(node.parent, nodes.TextElement) + if inline: + self.body.append('$%s$' % node['latex']) + else: + self.body.extend(['\\begin{equation}', + node['latex'], + '\\end{equation}']) + def depart_latex_math_latex(self, node): + pass + + app.add_node(latex_math, html=(visit_latex_math_html, + depart_latex_math_html)) + app.add_node(latex_math, latex=(visit_latex_math_latex, + depart_latex_math_latex)) + app.add_role('math', math_role) + app.add_directive('math', math_directive, + True, (0, 0, 0), **options_spec) Property changes on: branches/v0_98_5_maint/lib/matplotlib/sphinxext/mathmpl.py ___________________________________________________________________ Added: svn:mergeinfo + /branches/v0_91_maint/doc/sphinxext/mathmpl.py:5753-5771 Copied: branches/v0_98_5_maint/lib/matplotlib/sphinxext/only_directives.py (from rev 6843, branches/v0_98_5_maint/doc/sphinxext/only_directives.py) =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/sphinxext/only_directives.py (rev 0) +++ branches/v0_98_5_maint/lib/matplotlib/sphinxext/only_directives.py 2009-02-16 14:12:13 UTC (rev 6915) @@ -0,0 +1,63 @@ +# +# A pair of directives for inserting content that will only appear in +# either html or latex. +# + +from docutils.nodes import Body, Element +from docutils.parsers.rst import directives + +class only_base(Body, Element): + def dont_traverse(self, *args, **kwargs): + return [] + +class html_only(only_base): + pass + +class latex_only(only_base): + pass + +def run(content, node_class, state, content_offset): + text = '\n'.join(content) + node = node_class(text) + state.nested_parse(content, content_offset, node) + return [node] + +def html_only_directive(name, arguments, options, content, lineno, + content_offset, block_text, state, state_machine): + return run(content, html_only, state, content_offset) + +def latex_only_directive(name, arguments, options, content, lineno, + content_offset, block_text, state, state_machine): + return run(content, latex_only, state, content_offset) + +def builder_inited(app): + if app.builder.name == 'html': + latex_only.traverse = only_base.dont_traverse + else: + html_only.traverse = only_base.dont_traverse + +def setup(app): + app.add_directive('htmlonly', html_only_directive, True, (0, 0, 0)) + app.add_directive('latexonly', latex_only_directive, True, (0, 0, 0)) + app.add_node(html_only) + app.add_node(latex_only) + + # This will *really* never see the light of day As it turns out, + # this results in "broken" image nodes since they never get + # processed, so best not to do this. + # app.connect('builder-inited', builder_inited) + + # Add visit/depart methods to HTML-Translator: + def visit_perform(self, node): + pass + def depart_perform(self, node): + pass + def visit_ignore(self, node): + node.children = [] + def depart_ignore(self, node): + node.children = [] + + app.add_node(html_only, html=(visit_perform, depart_perform)) + app.add_node(html_only, latex=(visit_ignore, depart_ignore)) + app.add_node(latex_only, latex=(visit_perform, depart_perform)) + app.add_node(latex_only, html=(visit_ignore, depart_ignore)) Property changes on: branches/v0_98_5_maint/lib/matplotlib/sphinxext/only_directives.py ___________________________________________________________________ Added: svn:mergeinfo + /branches/v0_91_maint/doc/sphinxext/only_directives.py:5753-5771 Modified: branches/v0_98_5_maint/setup.py =================================================================== --- branches/v0_98_5_maint/setup.py 2009-02-15 00:12:19 UTC (rev 6914) +++ branches/v0_98_5_maint/setup.py 2009-02-16 14:12:13 UTC (rev 6915) @@ -58,7 +58,8 @@ 'matplotlib.numerix.npyma', 'matplotlib.numerix.linear_algebra', 'matplotlib.numerix.random_array', - 'matplotlib.numerix.fft' + 'matplotlib.numerix.fft', + 'matplotlib.sphinxext' ] py_modules = ['pylab'] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2009-02-16 15:23:29
|
Revision: 6918 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6918&view=rev Author: mdboom Date: 2009-02-16 15:23:25 +0000 (Mon, 16 Feb 2009) Log Message: ----------- Move plot_directive to installed source tree. Add support for inline code. Modified Paths: -------------- branches/v0_98_5_maint/CHANGELOG branches/v0_98_5_maint/doc/conf.py Added Paths: ----------- branches/v0_98_5_maint/lib/matplotlib/sphinxext/plot_directive.py Removed Paths: ------------- branches/v0_98_5_maint/doc/sphinxext/plot_directive.py Modified: branches/v0_98_5_maint/CHANGELOG =================================================================== --- branches/v0_98_5_maint/CHANGELOG 2009-02-16 14:24:56 UTC (rev 6917) +++ branches/v0_98_5_maint/CHANGELOG 2009-02-16 15:23:25 UTC (rev 6918) @@ -1,3 +1,6 @@ +2009-02-16 Move plot_directive.py to the installed source tree. Add + support for inline code content - MGD + 2009-02-16 Move mathmpl.py to the installed source tree so it is available to other projects. - MGD Modified: branches/v0_98_5_maint/doc/conf.py =================================================================== --- branches/v0_98_5_maint/doc/conf.py 2009-02-16 14:24:56 UTC (rev 6917) +++ branches/v0_98_5_maint/doc/conf.py 2009-02-16 15:23:25 UTC (rev 6918) @@ -28,8 +28,9 @@ # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['matplotlib.sphinxext.mathmpl', 'math_symbol_table', - 'sphinx.ext.autodoc', 'matplotlib.sphinxext.only_directives', - 'plot_directive', 'inheritance_diagram', 'gen_gallery', 'gen_rst'] + 'sphinx.ext.autodoc', # 'matplotlib.sphinxext.only_directives', + 'matplotlib.sphinxext.plot_directive', 'inheritance_diagram', + 'gen_gallery', 'gen_rst'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] Deleted: branches/v0_98_5_maint/doc/sphinxext/plot_directive.py =================================================================== --- branches/v0_98_5_maint/doc/sphinxext/plot_directive.py 2009-02-16 14:24:56 UTC (rev 6917) +++ branches/v0_98_5_maint/doc/sphinxext/plot_directive.py 2009-02-16 15:23:25 UTC (rev 6918) @@ -1,303 +0,0 @@ -"""A special directive for including a matplotlib plot. - -Given a path to a .py file, it includes the source code inline, then: - -- On HTML, will include a .png with a link to a high-res .png. - -- On LaTeX, will include a .pdf - -This directive supports all of the options of the `image` directive, -except for `target` (since plot will add its own target). - -Additionally, if the :include-source: option is provided, the literal -source will be included inline, as well as a link to the source. - -The set of file formats to generate can be specified with the -plot_formats configuration variable. -""" - -import sys, os, glob, shutil, imp, warnings, cStringIO -from docutils.parsers.rst import directives -try: - # docutils 0.4 - from docutils.parsers.rst.directives.images import align -except ImportError: - # docutils 0.5 - from docutils.parsers.rst.directives.images import Image - align = Image.align -from docutils import nodes - -import matplotlib -import matplotlib.cbook as cbook -matplotlib.use('Agg') -import matplotlib.pyplot as plt -import matplotlib.image as image -from matplotlib import _pylab_helpers - -if hasattr(os.path, 'relpath'): - relpath = os.path.relpath -else: - def relpath(target, base=os.curdir): - """ - Return a relative path to the target from either the current dir or an optional base dir. - Base can be a directory specified either as absolute or relative to current dir. - """ - - if not os.path.exists(target): - raise OSError, 'Target does not exist: '+target - - if not os.path.isdir(base): - raise OSError, 'Base is not a directory or does not exist: '+base - - base_list = (os.path.abspath(base)).split(os.sep) - target_list = (os.path.abspath(target)).split(os.sep) - - # On the windows platform the target may be on a completely different drive from the base. - if os.name in ['nt','dos','os2'] and base_list[0] <> target_list[0]: - raise OSError, 'Target is on a different drive to base. Target: '+target_list[0].upper()+', base: '+base_list[0].upper() - - # Starting from the filepath root, work out how much of the filepath is - # shared by base and target. - for i in range(min(len(base_list), len(target_list))): - if base_list[i] <> target_list[i]: break - else: - # If we broke out of the loop, i is pointing to the first differing path elements. - # If we didn't break out of the loop, i is pointing to identical path elements. - # Increment i so that in all cases it points to the first differing path elements. - i+=1 - - rel_list = [os.pardir] * (len(base_list)-i) + target_list[i:] - return os.path.join(*rel_list) - -def write_char(s): - sys.stdout.write(s) - sys.stdout.flush() - -options = {'alt': directives.unchanged, - 'height': directives.length_or_unitless, - 'width': directives.length_or_percentage_or_unitless, - 'scale': directives.nonnegative_int, - 'align': align, - 'class': directives.class_option, - 'include-source': directives.flag } - -template = """ -.. htmlonly:: - - [%(links)s] - - .. image:: %(tmpdir)s/%(outname)s.png - %(options)s - -.. latexonly:: - .. image:: %(tmpdir)s/%(outname)s.pdf - %(options)s -""" - -exception_template = """ -.. htmlonly:: - - [`source code <%(linkdir)s/%(basename)s.py>`__] - -Exception occurred rendering plot. - -""" - -def out_of_date(original, derived): - """ - Returns True if derivative is out-of-date wrt original, - both of which are full file paths. - """ - return (not os.path.exists(derived)) - # or os.stat(derived).st_mtime < os.stat(original).st_mtime) - -def runfile(fullpath): - """ - Import a Python module from a path. - """ - # Change the working directory to the directory of the example, so - # it can get at its data files, if any. - pwd = os.getcwd() - path, fname = os.path.split(fullpath) - sys.path.insert(0, os.path.abspath(path)) - stdout = sys.stdout - sys.stdout = cStringIO.StringIO() - os.chdir(path) - try: - fd = open(fname) - module = imp.load_module("__main__", fd, fname, ('py', 'r', imp.PY_SOURCE)) - except: - raise - finally: - del sys.path[0] - os.chdir(pwd) - sys.stdout = stdout - return module - -def makefig(fullpath, outdir): - """ - run a pyplot script and save the low and high res PNGs and a PDF in _static - """ - formats = [('png', 80), ('hires.png', 200), ('pdf', 50)] - - fullpath = str(fullpath) # todo, why is unicode breaking this - - basedir, fname = os.path.split(fullpath) - basename, ext = os.path.splitext(fname) - all_exists = True - - # Look for single-figure output files first - for format, dpi in formats: - outname = os.path.join(outdir, '%s.%s' % (basename, format)) - if out_of_date(fullpath, outname): - all_exists = False - break - - if all_exists: - write_char('.' * len(formats)) - return 1 - - # Then look for multi-figure output files, assuming - # if we have some we have all... - i = 0 - while True: - all_exists = True - for format, dpi in formats: - outname = os.path.join(outdir, '%s_%02d.%s' % (basename, i, format)) - if out_of_date(fullpath, outname): - all_exists = False - break - if all_exists: - i += 1 - else: - break - - if i != 0: - write_char('.' * i * len(formats)) - return i - - # We didn't find the files, so build them - - plt.close('all') # we need to clear between runs - matplotlib.rcdefaults() - # Set a figure size that doesn't overflow typical browser windows - matplotlib.rcParams['figure.figsize'] = (5.5, 4.5) - - try: - runfile(fullpath) - except: - s = cbook.exception_to_str("Exception running plot %s" % fullpath) - warnings.warn(s) - return 0 - - fig_managers = _pylab_helpers.Gcf.get_all_fig_managers() - for i, figman in enumerate(fig_managers): - for format, dpi in formats: - if len(fig_managers) == 1: - outname = basename - else: - outname = "%s_%02d" % (basename, i) - outpath = os.path.join(outdir, '%s.%s' % (outname, format)) - try: - figman.canvas.figure.savefig(outpath, dpi=dpi) - except: - s = cbook.exception_to_str("Exception running plot %s" % fullpath) - warnings.warn(s) - return 0 - - write_char('*') - - return len(fig_managers) - -def plot_directive(name, arguments, options, content, lineno, - content_offset, block_text, state, state_machine): - """ - Handle the plot directive. - """ - formats = setup.config.plot_formats - if type(formats) == str: - formats = eval(formats) - - reference = directives.uri(arguments[0]) - basedir, fname = os.path.split(reference) - basename, ext = os.path.splitext(fname) - basedir = relpath(basedir, setup.app.builder.srcdir) - - # Get the directory of the rst file, and determine the relative - # path from the resulting html file to the plot_directive links - # (linkdir). This relative path is used for html links *only*, - # and not the embedded image. That is given an absolute path to - # the temporary directory, and then sphinx moves the file to - # build/html/_images for us later. - rstdir, rstfile = os.path.split(state_machine.document.attributes['source']) - reldir = rstdir[len(setup.confdir)+1:] - relparts = [p for p in os.path.split(reldir) if p.strip()] - nparts = len(relparts) - outdir = os.path.join('plot_directive', basedir) - linkdir = ('../' * nparts) + outdir - - # tmpdir is where we build all the output files. This way the - # plots won't have to be redone when generating latex after html. - tmpdir = os.path.abspath(os.path.join('build', outdir)) - if not os.path.exists(tmpdir): - cbook.mkdirs(tmpdir) - - # destdir is the directory within the output to store files - # that we'll be linking to -- not the embedded images. - destdir = os.path.abspath(os.path.join(setup.app.builder.outdir, outdir)) - if not os.path.exists(destdir): - cbook.mkdirs(destdir) - - # Generate the figures, and return the number of them - num_figs = makefig(reference, tmpdir) - - if options.has_key('include-source'): - contents = open(reference, 'r').read() - lines = ['::', ''] + [' %s'%row.rstrip() for row in contents.split('\n')] - del options['include-source'] - else: - lines = [] - - if num_figs > 0: - options = [' :%s: %s' % (key, val) for key, val in - options.items()] - options = "\n".join(options) - shutil.copyfile(reference, os.path.join(destdir, fname)) - - for i in range(num_figs): - if num_figs == 1: - outname = basename - else: - outname = "%s_%02d" % (basename, i) - - # Copy the linked-to files to the destination within the build tree, - # and add a link for them - links = ['`source code <%(linkdir)s/%(basename)s.py>`__'] - for format in formats[1:]: - shutil.copyfile(os.path.join(tmpdir, outname + "." + format), - os.path.join(destdir, outname + "." + format)) - links.append('`%s <%s/%s.%s>`__' % (format, linkdir, outname, format)) - links = ', '.join(links) % locals() - - # Output the resulting reST - lines.extend((template % locals()).split('\n')) - else: - lines.extend((exception_template % locals()).split('\n')) - - if len(lines): - state_machine.insert_input( - lines, state_machine.input_lines.source(0)) - - return [] - -def setup(app): - setup.app = app - setup.config = app.config - setup.confdir = app.confdir - - app.add_directive('plot', plot_directive, False, (1, 0, 1), **options) - app.add_config_value( - 'plot_formats', - ['png', 'hires.png', 'pdf'], - True) - Copied: branches/v0_98_5_maint/lib/matplotlib/sphinxext/plot_directive.py (from rev 6915, branches/v0_98_5_maint/doc/sphinxext/plot_directive.py) =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/sphinxext/plot_directive.py (rev 0) +++ branches/v0_98_5_maint/lib/matplotlib/sphinxext/plot_directive.py 2009-02-16 15:23:25 UTC (rev 6918) @@ -0,0 +1,331 @@ +"""A special directive for including a matplotlib plot. + +Given a path to a .py file, it includes the source code inline, then: + +- On HTML, will include a .png with a link to a high-res .png. + +- On LaTeX, will include a .pdf + +This directive supports all of the options of the `image` directive, +except for `target` (since plot will add its own target). + +Additionally, if the :include-source: option is provided, the literal +source will be included inline, as well as a link to the source. + +The set of file formats to generate can be specified with the +plot_formats configuration variable. +""" + +import sys, os, glob, shutil, hashlib, imp, warnings, cStringIO +try: + from hashlib import md5 +except ImportError: + from md5 import md5 +from docutils.parsers.rst import directives +try: + # docutils 0.4 + from docutils.parsers.rst.directives.images import align +except ImportError: + # docutils 0.5 + from docutils.parsers.rst.directives.images import Image + align = Image.align +from docutils import nodes + +import matplotlib +import matplotlib.cbook as cbook +matplotlib.use('Agg') +import matplotlib.pyplot as plt +import matplotlib.image as image +from matplotlib import _pylab_helpers + +import only_directives + +if hasattr(os.path, 'relpath'): + relpath = os.path.relpath +else: + def relpath(target, base=os.curdir): + """ + Return a relative path to the target from either the current dir or an optional base dir. + Base can be a directory specified either as absolute or relative to current dir. + """ + + if not os.path.exists(target): + raise OSError, 'Target does not exist: '+target + + if not os.path.isdir(base): + raise OSError, 'Base is not a directory or does not exist: '+base + + base_list = (os.path.abspath(base)).split(os.sep) + target_list = (os.path.abspath(target)).split(os.sep) + + # On the windows platform the target may be on a completely different drive from the base. + if os.name in ['nt','dos','os2'] and base_list[0] <> target_list[0]: + raise OSError, 'Target is on a different drive to base. Target: '+target_list[0].upper()+', base: '+base_list[0].upper() + + # Starting from the filepath root, work out how much of the filepath is + # shared by base and target. + for i in range(min(len(base_list), len(target_list))): + if base_list[i] <> target_list[i]: break + else: + # If we broke out of the loop, i is pointing to the first differing path elements. + # If we didn't break out of the loop, i is pointing to identical path elements. + # Increment i so that in all cases it points to the first differing path elements. + i+=1 + + rel_list = [os.pardir] * (len(base_list)-i) + target_list[i:] + return os.path.join(*rel_list) + +def write_char(s): + sys.stdout.write(s) + sys.stdout.flush() + +options = {'alt': directives.unchanged, + 'height': directives.length_or_unitless, + 'width': directives.length_or_percentage_or_unitless, + 'scale': directives.nonnegative_int, + 'align': align, + 'class': directives.class_option, + 'include-source': directives.flag } + +template = """ +.. htmlonly:: + + [%(links)s] + + .. image:: %(tmpdir)s/%(outname)s.png + %(options)s + +.. latexonly:: + .. image:: %(tmpdir)s/%(outname)s.pdf + %(options)s +""" + +exception_template = """ +.. htmlonly:: + + [`source code <%(linkdir)s/%(basename)s.py>`__] + +Exception occurred rendering plot. + +""" + +def out_of_date(original, derived): + """ + Returns True if derivative is out-of-date wrt original, + both of which are full file paths. + """ + return (not os.path.exists(derived)) + # or os.stat(derived).st_mtime < os.stat(original).st_mtime) + +def runfile(fullpath): + """ + Import a Python module from a path. + """ + # Change the working directory to the directory of the example, so + # it can get at its data files, if any. + pwd = os.getcwd() + path, fname = os.path.split(fullpath) + sys.path.insert(0, os.path.abspath(path)) + stdout = sys.stdout + sys.stdout = cStringIO.StringIO() + os.chdir(path) + try: + fd = open(fname) + module = imp.load_module("__main__", fd, fname, ('py', 'r', imp.PY_SOURCE)) + except: + raise + finally: + del sys.path[0] + os.chdir(pwd) + sys.stdout = stdout + return module + +def makefig(fullpath, code, outdir): + """ + run a pyplot script and save the low and high res PNGs and a PDF in _static + """ + formats = [('png', 80), ('hires.png', 200), ('pdf', 50)] + + fullpath = str(fullpath) # todo, why is unicode breaking this + basedir, fname = os.path.split(fullpath) + basename, ext = os.path.splitext(fname) + + if str(basename) == "None": + import pdb + pdb.set_trace() + + all_exists = True + + # Look for single-figure output files first + for format, dpi in formats: + outname = os.path.join(outdir, '%s.%s' % (basename, format)) + if out_of_date(fullpath, outname): + all_exists = False + break + + if all_exists: + write_char('.' * len(formats)) + return 1 + + # Then look for multi-figure output files, assuming + # if we have some we have all... + i = 0 + while True: + all_exists = True + for format, dpi in formats: + outname = os.path.join(outdir, '%s_%02d.%s' % (basename, i, format)) + if out_of_date(fullpath, outname): + all_exists = False + break + if all_exists: + i += 1 + else: + break + + if i != 0: + write_char('.' * i * len(formats)) + return i + + # We didn't find the files, so build them + + plt.close('all') # we need to clear between runs + matplotlib.rcdefaults() + # Set a figure size that doesn't overflow typical browser windows + matplotlib.rcParams['figure.figsize'] = (5.5, 4.5) + + if code is not None: + exec(code) + else: + try: + runfile(fullpath) + except: + s = cbook.exception_to_str("Exception running plot %s" % fullpath) + warnings.warn(s) + return 0 + + fig_managers = _pylab_helpers.Gcf.get_all_fig_managers() + for i, figman in enumerate(fig_managers): + for format, dpi in formats: + if len(fig_managers) == 1: + outname = basename + else: + outname = "%s_%02d" % (basename, i) + outpath = os.path.join(outdir, '%s.%s' % (outname, format)) + try: + figman.canvas.figure.savefig(outpath, dpi=dpi) + except: + s = cbook.exception_to_str("Exception running plot %s" % fullpath) + warnings.warn(s) + return 0 + + write_char('*') + + return len(fig_managers) + +def plot_directive(name, arguments, options, content, lineno, + content_offset, block_text, state, state_machine): + """ + Handle the plot directive. + """ + formats = setup.config.plot_formats + if type(formats) == str: + formats = eval(formats) + + # The user may provide a filename *or* Python code content, but not both + if len(arguments) == 1: + reference = directives.uri(arguments[0]) + basedir, fname = os.path.split(reference) + basename, ext = os.path.splitext(fname) + basedir = relpath(basedir, setup.app.builder.srcdir) + if len(content): + raise ValueError("plot directive may not specify both a filename and inline content") + content = None + else: + basedir = "inline" + content = '\n'.join(content) + # Since we don't have a filename, use a hash based on the content + reference = basename = md5(content).hexdigest()[-10:] + fname = None + + # Get the directory of the rst file, and determine the relative + # path from the resulting html file to the plot_directive links + # (linkdir). This relative path is used for html links *only*, + # and not the embedded image. That is given an absolute path to + # the temporary directory, and then sphinx moves the file to + # build/html/_images for us later. + rstdir, rstfile = os.path.split(state_machine.document.attributes['source']) + reldir = rstdir[len(setup.confdir)+1:] + relparts = [p for p in os.path.split(reldir) if p.strip()] + nparts = len(relparts) + outdir = os.path.join('plot_directive', basedir) + linkdir = ('../' * nparts) + outdir + + # tmpdir is where we build all the output files. This way the + # plots won't have to be redone when generating latex after html. + tmpdir = os.path.abspath(os.path.join('build', outdir)) + if not os.path.exists(tmpdir): + cbook.mkdirs(tmpdir) + + # destdir is the directory within the output to store files + # that we'll be linking to -- not the embedded images. + destdir = os.path.abspath(os.path.join(setup.app.builder.outdir, outdir)) + if not os.path.exists(destdir): + cbook.mkdirs(destdir) + + # Generate the figures, and return the number of them + num_figs = makefig(reference, content, tmpdir) + + if options.has_key('include-source'): + if content is None: + content = open(reference, 'r').read() + lines = ['::', ''] + [' %s'%row.rstrip() for row in content.split('\n')] + del options['include-source'] + else: + lines = [] + + if num_figs > 0: + options = [' :%s: %s' % (key, val) for key, val in + options.items()] + options = "\n".join(options) + if fname is not None: + shutil.copyfile(reference, os.path.join(destdir, fname)) + + for i in range(num_figs): + if num_figs == 1: + outname = basename + else: + outname = "%s_%02d" % (basename, i) + + # Copy the linked-to files to the destination within the build tree, + # and add a link for them + links = [] + if fname is not None: + links.append('`source code <%(linkdir)s/%(basename)s.py>`__') + for format in formats[1:]: + shutil.copyfile(os.path.join(tmpdir, outname + "." + format), + os.path.join(destdir, outname + "." + format)) + links.append('`%s <%s/%s.%s>`__' % (format, linkdir, outname, format)) + links = ', '.join(links) % locals() + + # Output the resulting reST + lines.extend((template % locals()).split('\n')) + else: + lines.extend((exception_template % locals()).split('\n')) + + if len(lines): + state_machine.insert_input( + lines, state_machine.input_lines.source(0)) + + return [] + +def setup(app): + setup.app = app + setup.config = app.config + setup.confdir = app.confdir + + app.add_directive('plot', plot_directive, True, (0, 1, 0), **options) + app.add_config_value( + 'plot_formats', + ['png', 'hires.png', 'pdf'], + True) + Property changes on: branches/v0_98_5_maint/lib/matplotlib/sphinxext/plot_directive.py ___________________________________________________________________ Added: svn:mergeinfo + /branches/v0_91_maint/doc/sphinxext/plot_directive.py:5753-5771 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2009-02-23 17:38:38
|
Revision: 6928 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6928&view=rev Author: mdboom Date: 2009-02-23 17:38:35 +0000 (Mon, 23 Feb 2009) Log Message: ----------- C++ standards compliance for use with Sun C++ compiler. These should be equivalent to what was there before on gcc. Modified Paths: -------------- branches/v0_98_5_maint/CXX/Extensions.hxx branches/v0_98_5_maint/agg24/include/agg_alpha_mask_u8.h Modified: branches/v0_98_5_maint/CXX/Extensions.hxx =================================================================== --- branches/v0_98_5_maint/CXX/Extensions.hxx 2009-02-23 17:30:07 UTC (rev 6927) +++ branches/v0_98_5_maint/CXX/Extensions.hxx 2009-02-23 17:38:35 UTC (rev 6928) @@ -61,7 +61,7 @@ namespace Py { class ExtensionModuleBase; - + // Make an Exception Type for use in raising custom exceptions class ExtensionExceptionType : public Object { @@ -74,44 +74,44 @@ void init( ExtensionModuleBase &module, const std::string& name ); }; - - class MethodTable + + class MethodTable { public: MethodTable(); virtual ~MethodTable(); - + void add(const char* method_name, PyCFunction f, const char* doc="", int flag=1); PyMethodDef* table(); - + protected: std::vector<PyMethodDef> t; // accumulator of PyMethodDef's PyMethodDef *mt; // Actual method table produced when full - + static PyMethodDef method (const char* method_name, PyCFunction f, int flags = 1, const char* doc=""); - + private: // // prevent the compiler generating these unwanted functions // MethodTable(const MethodTable& m); //unimplemented void operator=(const MethodTable& m); //unimplemented - + }; // end class MethodTable - + extern "C" { typedef PyObject *(*method_varargs_call_handler_t)( PyObject *_self, PyObject *_args ); typedef PyObject *(*method_keyword_call_handler_t)( PyObject *_self, PyObject *_args, PyObject *_dict ); - }; - + } + template<class T> class MethodDefExt : public PyMethodDef { public: typedef Object (T::*method_varargs_function_t)( const Tuple &args ); typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws ); - + MethodDefExt ( const char *_name, @@ -124,11 +124,11 @@ ext_meth_def.ml_meth = _handler; ext_meth_def.ml_flags = METH_VARARGS; ext_meth_def.ml_doc = const_cast<char *>(_doc); - + ext_varargs_function = _function; ext_keyword_function = NULL; } - + MethodDefExt ( const char *_name, @@ -141,57 +141,57 @@ ext_meth_def.ml_meth = method_varargs_call_handler_t( _handler ); ext_meth_def.ml_flags = METH_VARARGS|METH_KEYWORDS; ext_meth_def.ml_doc = const_cast<char *>(_doc); - + ext_varargs_function = NULL; ext_keyword_function = _function; } - + ~MethodDefExt() {} - + PyMethodDef ext_meth_def; - method_varargs_function_t ext_varargs_function; - method_keyword_function_t ext_keyword_function; + method_varargs_function_t ext_varargs_function; + method_keyword_function_t ext_keyword_function; }; - + class ExtensionModuleBase { public: ExtensionModuleBase( const char *name ); virtual ~ExtensionModuleBase(); - + Module module(void) const; // only valid after initialize() has been called Dict moduleDictionary(void) const; // only valid after initialize() has been called - + virtual Object invoke_method_keyword( const std::string &_name, const Tuple &_args, const Dict &_keywords ) = 0; virtual Object invoke_method_varargs( const std::string &_name, const Tuple &_args ) = 0; - + const std::string &name() const; const std::string &fullName() const; - + protected: // Initialize the module void initialize( const char *module_doc ); - + const std::string module_name; const std::string full_module_name; MethodTable method_table; - + private: - + // // prevent the compiler generating these unwanted functions // ExtensionModuleBase( const ExtensionModuleBase & ); //unimplemented void operator=( const ExtensionModuleBase & ); //unimplemented - + }; - + extern "C" PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords ); extern "C" PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args ); extern "C" void do_not_dealloc( void * ); - - + + template<TEMPLATE_TYPENAME T> class ExtensionModule : public ExtensionModuleBase { @@ -201,16 +201,16 @@ {} virtual ~ExtensionModule() {} - + protected: typedef Object (T::*method_varargs_function_t)( const Tuple &args ); typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws ); typedef std::map<std::string,MethodDefExt<T> *> method_map_t; - + static void add_varargs_method( const char *name, method_varargs_function_t function, const char *doc="" ) { method_map_t &mm = methods(); - + MethodDefExt<T> *method_definition = new MethodDefExt<T> ( name, @@ -218,14 +218,14 @@ method_varargs_call_handler, doc ); - + mm[std::string( name )] = method_definition; } - + static void add_keyword_method( const char *name, method_keyword_function_t function, const char *doc="" ) { method_map_t &mm = methods(); - + MethodDefExt<T> *method_definition = new MethodDefExt<T> ( name, @@ -233,7 +233,7 @@ method_keyword_call_handler, doc ); - + mm[std::string( name )] = method_definition; } @@ -241,46 +241,46 @@ { ExtensionModuleBase::initialize( module_doc ); Dict dict( moduleDictionary() ); - + // // put each of the methods into the modules dictionary // so that we get called back at the function in T. // method_map_t &mm = methods(); EXPLICIT_TYPENAME method_map_t::iterator i; - + for( i=mm.begin(); i != mm.end(); ++i ) { MethodDefExt<T> *method_definition = (*i).second; - + static PyObject *self = PyCObject_FromVoidPtr( this, do_not_dealloc ); - + Tuple args( 2 ); args[0] = Object( self ); args[1] = String( (*i).first ); - + PyObject *func = PyCFunction_New ( &method_definition->ext_meth_def, new_reference_to( args ) ); - + dict[ (*i).first ] = Object( func ); } } - + protected: // Tom Malcolmson reports that derived classes need access to these - + static method_map_t &methods(void) { static method_map_t *map_of_methods = NULL; if( map_of_methods == NULL ) map_of_methods = new method_map_t; - + return *map_of_methods; } - - + + // this invoke function must be called from within a try catch block virtual Object invoke_method_keyword( const std::string &name, const Tuple &args, const Dict &keywords ) { @@ -292,13 +292,13 @@ error_msg += name; throw RuntimeError( error_msg ); } - + // cast up to the derived class T *self = static_cast<T *>(this); - + return (self->*meth_def->ext_keyword_function)( args, keywords ); } - + // this invoke function must be called from within a try catch block virtual Object invoke_method_varargs( const std::string &name, const Tuple &args ) { @@ -310,13 +310,13 @@ error_msg += name; throw RuntimeError( error_msg ); } - + // cast up to the derived class T *self = static_cast<T *>(this); - + return (self->*meth_def->ext_varargs_function)( args ); } - + private: // // prevent the compiler generating these unwanted functions @@ -324,17 +324,17 @@ ExtensionModule( const ExtensionModule<T> & ); //unimplemented void operator=( const ExtensionModule<T> & ); //unimplemented }; - - + + class PythonType { public: - // if you define one sequence method you must define + // if you define one sequence method you must define // all of them except the assigns - + PythonType (size_t base_size, int itemsize, const char *default_name ); virtual ~PythonType (); - + const char *getName () const; const char *getDoc () const; @@ -342,7 +342,7 @@ PythonType & name (const char* nam); PythonType & doc (const char* d); PythonType & dealloc(void (*f)(PyObject*)); - + PythonType & supportPrint(void); PythonType & supportGetattr(void); PythonType & supportSetattr(void); @@ -354,61 +354,61 @@ PythonType & supportHash(void); PythonType & supportCall(void); PythonType & supportIter(void); - + PythonType & supportSequenceType(void); PythonType & supportMappingType(void); PythonType & supportNumberType(void); PythonType & supportBufferType(void); - + protected: PyTypeObject *table; PySequenceMethods *sequence_table; PyMappingMethods *mapping_table; PyNumberMethods *number_table; PyBufferProcs *buffer_table; - + void init_sequence(); void init_mapping(); void init_number(); void init_buffer(); - + private: // // prevent the compiler generating these unwanted functions // PythonType (const PythonType& tb); // unimplemented void operator=(const PythonType& t); // unimplemented - + }; // end of PythonType - - - + + + // Class PythonExtension is what you inherit from to create // a new Python extension type. You give your class itself // as the template paramter. - + // There are two ways that extension objects can get destroyed. // 1. Their reference count goes to zero // 2. Someone does an explicit delete on a pointer. - // In (1) the problem is to get the destructor called + // In (1) the problem is to get the destructor called // We register a special deallocator in the Python type object // (see behaviors()) to do this. // In (2) there is no problem, the dtor gets called. - - // PythonExtension does not use the usual Python heap allocator, + + // PythonExtension does not use the usual Python heap allocator, // instead using new/delete. We do the setting of the type object - // and reference count, usually done by PyObject_New, in the + // and reference count, usually done by PyObject_New, in the // base class ctor. - + // This special deallocator does a delete on the pointer. - - + + class PythonExtensionBase : public PyObject { public: PythonExtensionBase(); virtual ~PythonExtensionBase(); - + public: virtual int print( FILE *, int ); virtual Object getattr( const char * ) = 0; @@ -422,7 +422,7 @@ virtual Object call( const Object &, const Object & ); virtual Object iter(); virtual PyObject* iternext(); - + // Sequence methods virtual int sequence_length(); virtual Object sequence_concat( const Object & ); @@ -431,12 +431,12 @@ virtual Object sequence_slice( Py_ssize_t, Py_ssize_t ); virtual int sequence_ass_item( Py_ssize_t, const Object & ); virtual int sequence_ass_slice( Py_ssize_t, Py_ssize_t, const Object & ); - + // Mapping virtual int mapping_length(); virtual Object mapping_subscript( const Object & ); virtual int mapping_ass_subscript( const Object &, const Object & ); - + // Number virtual int number_nonzero(); virtual Object number_negative(); @@ -460,38 +460,38 @@ virtual Object number_xor( const Object & ); virtual Object number_or( const Object & ); virtual Object number_power( const Object &, const Object & ); - + // Buffer virtual Py_ssize_t buffer_getreadbuffer( Py_ssize_t, void** ); virtual Py_ssize_t buffer_getwritebuffer( Py_ssize_t, void** ); virtual Py_ssize_t buffer_getsegcount( Py_ssize_t* ); - + private: void missing_method( void ); static PyObject *method_call_handler( PyObject *self, PyObject *args ); }; - + template<TEMPLATE_TYPENAME T> - class PythonExtension: public PythonExtensionBase + class PythonExtension: public PythonExtensionBase { public: - static PyTypeObject* type_object() + static PyTypeObject* type_object() { return behaviors().type_object(); } - + static int check( PyObject *p ) { // is p like me? return p->ob_type == type_object(); } - + static int check( const Object& ob ) { return check( ob.ptr()); } - - + + // // every object needs getattr implemented // to support methods @@ -500,7 +500,7 @@ { return getattr_methods( name ); } - + protected: explicit PythonExtension() : PythonExtensionBase() @@ -511,18 +511,18 @@ ob_refcnt = 1; ob_type = type_object(); #endif - + // every object must support getattr behaviors().supportGetattr(); } - + virtual ~PythonExtension() - {} - + {} + static PythonType &behaviors() { static PythonType* p; - if( p == NULL ) + if( p == NULL ) { #if defined( _CPPRTTI ) || defined(__GNUG__) const char *default_name = (typeid ( T )).name(); @@ -532,15 +532,15 @@ p = new PythonType( sizeof( T ), 0, default_name ); p->dealloc( extension_object_deallocator ); } - + return *p; } - - + + typedef Object (T::*method_varargs_function_t)( const Tuple &args ); typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws ); typedef std::map<std::string,MethodDefExt<T> *> method_map_t; - + // support the default attributes, __name__, __doc__ and methods virtual Object getattr_default( const char *_name ) { @@ -576,39 +576,39 @@ virtual Object getattr_methods( const char *_name ) { std::string name( _name ); - + method_map_t &mm = methods(); - + if( name == "__methods__" ) { List methods; - + for( EXPLICIT_TYPENAME method_map_t::iterator i = mm.begin(); i != mm.end(); ++i ) methods.append( String( (*i).first ) ); - + return methods; } - + // see if name exists if( mm.find( name ) == mm.end() ) throw AttributeError( name ); - + Tuple self( 2 ); - + self[0] = Object( this ); self[1] = String( name ); - + MethodDefExt<T> *method_definition = mm[ name ]; - + PyObject *func = PyCFunction_New( &method_definition->ext_meth_def, self.ptr() ); - + return Object(func, true); } - + static void add_varargs_method( const char *name, method_varargs_function_t function, const char *doc="" ) { method_map_t &mm = methods(); - + MethodDefExt<T> *method_definition = new MethodDefExt<T> ( name, @@ -616,14 +616,14 @@ method_varargs_call_handler, doc ); - + mm[std::string( name )] = method_definition; } - + static void add_keyword_method( const char *name, method_keyword_function_t function, const char *doc="" ) { method_map_t &mm = methods(); - + MethodDefExt<T> *method_definition = new MethodDefExt<T> ( name, @@ -631,45 +631,45 @@ method_keyword_call_handler, doc ); - + mm[std::string( name )] = method_definition; } - + private: static method_map_t &methods(void) { static method_map_t *map_of_methods = NULL; if( map_of_methods == NULL ) map_of_methods = new method_map_t; - + return *map_of_methods; } - + static PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords ) { try { Tuple self_and_name_tuple( _self_and_name_tuple ); - + PyObject *self_in_cobject = self_and_name_tuple[0].ptr(); T *self = static_cast<T *>( self_in_cobject ); - + String name( self_and_name_tuple[1] ); - + method_map_t &mm = methods(); MethodDefExt<T> *meth_def = mm[ name ]; if( meth_def == NULL ) return 0; - + Tuple args( _args ); // _keywords may be NULL so be careful about the way the dict is created Dict keywords; if( _keywords != NULL ) keywords = Dict( _keywords ); - + Object result( (self->*meth_def->ext_keyword_function)( args, keywords ) ); - + return new_reference_to( result.ptr() ); } catch( Exception & ) @@ -677,27 +677,27 @@ return 0; } } - + static PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args ) { try { Tuple self_and_name_tuple( _self_and_name_tuple ); - + PyObject *self_in_cobject = self_and_name_tuple[0].ptr(); T *self = static_cast<T *>( self_in_cobject ); - + String name( self_and_name_tuple[1] ); - + method_map_t &mm = methods(); MethodDefExt<T> *meth_def = mm[ name ]; if( meth_def == NULL ) return 0; - + Tuple args( _args ); - + Object result; - + // TMM: 7Jun'01 - Adding try & catch in case of STL debug-mode exceptions. #ifdef _STLP_DEBUG try @@ -712,7 +712,7 @@ #else result = (self->*meth_def->ext_varargs_function)( args ); #endif // _STLP_DEBUG - + return new_reference_to( result.ptr() ); } catch( Exception & ) @@ -720,19 +720,19 @@ return 0; } } - + static void extension_object_deallocator ( PyObject* t ) { delete (T *)( t ); } - + // // prevent the compiler generating these unwanted functions // explicit PythonExtension( const PythonExtension<T>& other ); void operator=( const PythonExtension<T>& rhs ); }; - + // // ExtensionObject<T> is an Object that will accept only T's. // @@ -740,30 +740,30 @@ class ExtensionObject: public Object { public: - + explicit ExtensionObject ( PyObject *pyob ) : Object( pyob ) { validate(); } - + ExtensionObject( const ExtensionObject<T>& other ) : Object( *other ) { validate(); } - + ExtensionObject( const Object& other ) : Object( *other ) { validate(); } - + ExtensionObject& operator= ( const Object& rhs ) { return (*this = *rhs ); } - + ExtensionObject& operator= ( PyObject* rhsp ) { if( ptr() == rhsp ) @@ -771,12 +771,12 @@ set( rhsp ); return *this; } - + virtual bool accepts ( PyObject *pyob ) const { return ( pyob && T::check( pyob )); - } - + } + // // Obtain a pointer to the PythonExtension object // @@ -785,7 +785,7 @@ return static_cast<T *>( ptr() ); } }; - + } // Namespace Py // End of CXX_Extensions.h #endif Modified: branches/v0_98_5_maint/agg24/include/agg_alpha_mask_u8.h =================================================================== --- branches/v0_98_5_maint/agg24/include/agg_alpha_mask_u8.h 2009-02-23 17:30:07 UTC (rev 6927) +++ branches/v0_98_5_maint/agg24/include/agg_alpha_mask_u8.h 2009-02-23 17:38:35 UTC (rev 6928) @@ -2,8 +2,8 @@ // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // -// Permission to copy, use, modify, sell and distribute this software -// is granted provided this copyright notice appears in all copies. +// Permission to copy, use, modify, sell and distribute this software +// is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // @@ -30,15 +30,15 @@ { static unsigned calculate(const int8u* p) { return *p; } }; - + //=====================================================rgb_to_gray_mask_u8 template<unsigned R, unsigned G, unsigned B> struct rgb_to_gray_mask_u8 { - static unsigned calculate(const int8u* p) - { - return (p[R]*77 + p[G]*150 + p[B]*29) >> 8; + static unsigned calculate(const int8u* p) + { + return (p[R]*77 + p[G]*150 + p[B]*29) >> 8; } }; @@ -50,7 +50,7 @@ typedef int8u cover_type; typedef alpha_mask_u8<Step, Offset, MaskF> self_type; enum cover_scale_e - { + { cover_shift = 8, cover_none = 0, cover_full = 255 @@ -64,12 +64,12 @@ MaskF& mask_function() { return m_mask_function; } const MaskF& mask_function() const { return m_mask_function; } - + //-------------------------------------------------------------------- cover_type pixel(int x, int y) const { - if(x >= 0 && y >= 0 && - x < (int)m_rbuf->width() && + if(x >= 0 && y >= 0 && + x < (int)m_rbuf->width() && y < (int)m_rbuf->height()) { return (cover_type)m_mask_function.calculate( @@ -81,13 +81,13 @@ //-------------------------------------------------------------------- cover_type combine_pixel(int x, int y, cover_type val) const { - if(x >= 0 && y >= 0 && - x < (int)m_rbuf->width() && + if(x >= 0 && y >= 0 && + x < (int)m_rbuf->width() && y < (int)m_rbuf->height()) { - return (cover_type)((cover_full + val * + return (cover_type)((cover_full + val * m_mask_function.calculate( - m_rbuf->row_ptr(y) + x * Step + Offset)) >> + m_rbuf->row_ptr(y) + x * Step + Offset)) >> cover_shift); } return 0; @@ -112,7 +112,7 @@ if(x < 0) { count += x; - if(count <= 0) + if(count <= 0) { memset(dst, 0, num_pix * sizeof(cover_type)); return; @@ -126,7 +126,7 @@ { int rest = x + count - xmax - 1; count -= rest; - if(count <= 0) + if(count <= 0) { memset(dst, 0, num_pix * sizeof(cover_type)); return; @@ -162,7 +162,7 @@ if(x < 0) { count += x; - if(count <= 0) + if(count <= 0) { memset(dst, 0, num_pix * sizeof(cover_type)); return; @@ -176,7 +176,7 @@ { int rest = x + count - xmax - 1; count -= rest; - if(count <= 0) + if(count <= 0) { memset(dst, 0, num_pix * sizeof(cover_type)); return; @@ -187,8 +187,8 @@ const int8u* mask = m_rbuf->row_ptr(y) + x * Step + Offset; do { - *covers = (cover_type)((cover_full + (*covers) * - m_mask_function.calculate(mask)) >> + *covers = (cover_type)((cover_full + (*covers) * + m_mask_function.calculate(mask)) >> cover_shift); ++covers; mask += Step; @@ -214,7 +214,7 @@ if(y < 0) { count += y; - if(count <= 0) + if(count <= 0) { memset(dst, 0, num_pix * sizeof(cover_type)); return; @@ -228,7 +228,7 @@ { int rest = y + count - ymax - 1; count -= rest; - if(count <= 0) + if(count <= 0) { memset(dst, 0, num_pix * sizeof(cover_type)); return; @@ -263,7 +263,7 @@ if(y < 0) { count += y; - if(count <= 0) + if(count <= 0) { memset(dst, 0, num_pix * sizeof(cover_type)); return; @@ -277,7 +277,7 @@ { int rest = y + count - ymax - 1; count -= rest; - if(count <= 0) + if(count <= 0) { memset(dst, 0, num_pix * sizeof(cover_type)); return; @@ -288,8 +288,8 @@ const int8u* mask = m_rbuf->row_ptr(y) + x * Step + Offset; do { - *covers = (cover_type)((cover_full + (*covers) * - m_mask_function.calculate(mask)) >> + *covers = (cover_type)((cover_full + (*covers) * + m_mask_function.calculate(mask)) >> cover_shift); ++covers; mask += m_rbuf->stride(); @@ -302,11 +302,11 @@ alpha_mask_u8(const self_type&); const self_type& operator = (const self_type&); - rendering_buffer* m_rbuf; + agg::rendering_buffer* m_rbuf; MaskF m_mask_function; }; - + typedef alpha_mask_u8<1, 0> alpha_mask_gray8; //----alpha_mask_gray8 typedef alpha_mask_u8<3, 0> alpha_mask_rgb24r; //----alpha_mask_rgb24r @@ -354,7 +354,7 @@ typedef int8u cover_type; typedef amask_no_clip_u8<Step, Offset, MaskF> self_type; enum cover_scale_e - { + { cover_shift = 8, cover_none = 0, cover_full = 255 @@ -376,13 +376,13 @@ m_rbuf->row_ptr(y) + x * Step + Offset); } - + //-------------------------------------------------------------------- cover_type combine_pixel(int x, int y, cover_type val) const { - return (cover_type)((cover_full + val * + return (cover_type)((cover_full + val * m_mask_function.calculate( - m_rbuf->row_ptr(y) + x * Step + Offset)) >> + m_rbuf->row_ptr(y) + x * Step + Offset)) >> cover_shift); } @@ -407,8 +407,8 @@ const int8u* mask = m_rbuf->row_ptr(y) + x * Step + Offset; do { - *dst = (cover_type)((cover_full + (*dst) * - m_mask_function.calculate(mask)) >> + *dst = (cover_type)((cover_full + (*dst) * + m_mask_function.calculate(mask)) >> cover_shift); ++dst; mask += Step; @@ -436,8 +436,8 @@ const int8u* mask = m_rbuf->row_ptr(y) + x * Step + Offset; do { - *dst = (cover_type)((cover_full + (*dst) * - m_mask_function.calculate(mask)) >> + *dst = (cover_type)((cover_full + (*dst) * + m_mask_function.calculate(mask)) >> cover_shift); ++dst; mask += m_rbuf->stride(); @@ -449,11 +449,11 @@ amask_no_clip_u8(const self_type&); const self_type& operator = (const self_type&); - rendering_buffer* m_rbuf; + agg::rendering_buffer* m_rbuf; MaskF m_mask_function; }; - + typedef amask_no_clip_u8<1, 0> amask_no_clip_gray8; //----amask_no_clip_gray8 typedef amask_no_clip_u8<3, 0> amask_no_clip_rgb24r; //----amask_no_clip_rgb24r This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jo...@us...> - 2009-02-26 19:54:58
|
Revision: 6938 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6938&view=rev Author: jouni Date: 2009-02-26 19:54:48 +0000 (Thu, 26 Feb 2009) Log Message: ----------- Support image clipping in the pdf backend Modified Paths: -------------- branches/v0_98_5_maint/CHANGELOG branches/v0_98_5_maint/lib/matplotlib/backends/backend_pdf.py Modified: branches/v0_98_5_maint/CHANGELOG =================================================================== --- branches/v0_98_5_maint/CHANGELOG 2009-02-26 19:44:30 UTC (rev 6937) +++ branches/v0_98_5_maint/CHANGELOG 2009-02-26 19:54:48 UTC (rev 6938) @@ -1,3 +1,5 @@ +2009-02-26 Support image clipping in pdf backend. - JKS + 2009-02-16 Move plot_directive.py to the installed source tree. Add support for inline code content - MGD Modified: branches/v0_98_5_maint/lib/matplotlib/backends/backend_pdf.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/backends/backend_pdf.py 2009-02-26 19:44:30 UTC (rev 6937) +++ branches/v0_98_5_maint/lib/matplotlib/backends/backend_pdf.py 2009-02-26 19:54:48 UTC (rev 6938) @@ -39,7 +39,7 @@ from matplotlib.ft2font import FT2Font, FIXED_WIDTH, ITALIC, LOAD_NO_SCALE, \ LOAD_NO_HINTING, KERNING_UNFITTED from matplotlib.mathtext import MathTextParser -from matplotlib.transforms import Affine2D, Bbox, BboxBase +from matplotlib.transforms import Affine2D, Bbox, BboxBase, TransformedPath from matplotlib.path import Path from matplotlib import ttconv @@ -1235,10 +1235,12 @@ return self.image_dpi/72.0 def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None): - # MGDTODO: Support clippath here gc = self.new_gc() if bbox is not None: gc.set_clip_rectangle(bbox) + if clippath is not None: + clippath = TransformedPath(clippath, clippath_trans) + gc.set_clip_path(clippath) self.check_gc(gc) h, w = im.get_size_out() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2009-03-07 19:19:46
|
Revision: 6960 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6960&view=rev Author: efiring Date: 2009-03-07 19:19:40 +0000 (Sat, 07 Mar 2009) Log Message: ----------- Remove references to handle graphics; it is registered trademark of Mathworks, and the pyplot resemblance is only superficial. Modified Paths: -------------- branches/v0_98_5_maint/doc/_templates/index.html branches/v0_98_5_maint/doc/pyplots/tex_demo.png branches/v0_98_5_maint/doc/users/pyplot_tutorial.rst branches/v0_98_5_maint/examples/pylab_examples/axes_props.py branches/v0_98_5_maint/lib/matplotlib/pylab.py branches/v0_98_5_maint/lib/matplotlib/pyplot.py Modified: branches/v0_98_5_maint/doc/_templates/index.html =================================================================== --- branches/v0_98_5_maint/doc/_templates/index.html 2009-03-06 19:14:30 UTC (rev 6959) +++ branches/v0_98_5_maint/doc/_templates/index.html 2009-03-07 19:19:40 UTC (rev 6960) @@ -35,7 +35,7 @@ <p>For the power user, you have full control of line styles, font properties, axes properties, etc, via an object oriented interface - or via a handle graphics interface familiar to Matlab® users. + or via a set of functions familiar to Matlab® users. The pylab mode provides all of the <a href="api/pyplot_api.html">pyplot</a> plotting functions listed below, as well as non-plotting functions from <a href="http://scipy.org/Numpy_Example_List_With_Doc">numpy</a> and @@ -473,7 +473,7 @@ </th> <td align="left"> - get a handle graphics property + get a graphics property </td> </tr> @@ -781,7 +781,7 @@ </th> <td align="left"> - set a handle graphics property + set a graphics property </td> </tr> Modified: branches/v0_98_5_maint/doc/pyplots/tex_demo.png =================================================================== (Binary files differ) Modified: branches/v0_98_5_maint/doc/users/pyplot_tutorial.rst =================================================================== --- branches/v0_98_5_maint/doc/users/pyplot_tutorial.rst 2009-03-06 19:14:30 UTC (rev 6959) +++ branches/v0_98_5_maint/doc/users/pyplot_tutorial.rst 2009-03-07 19:19:40 UTC (rev 6960) @@ -78,10 +78,10 @@ line.set_antialiased(False) # turn off antialising * Use the :func:`~matplotlib.pyplot.setp` command. The example below - uses matlab handle graphics style command to set multiple properties + uses a Matlab-style command to set multiple properties on a list of lines. ``setp`` works transparently with a list of objects or a single object. You can either use python keyword arguments or - matlab-style string/value pairs:: + Matlab-style string/value pairs:: lines = plt.plot(x1, y1, x2, y2) # use keyword args Modified: branches/v0_98_5_maint/examples/pylab_examples/axes_props.py =================================================================== --- branches/v0_98_5_maint/examples/pylab_examples/axes_props.py 2009-03-06 19:14:30 UTC (rev 6959) +++ branches/v0_98_5_maint/examples/pylab_examples/axes_props.py 2009-03-07 19:19:40 UTC (rev 6960) @@ -10,7 +10,7 @@ plot(t, s) grid(True) -# matlab handle graphics style +# matlab style xticklines = getp(gca(), 'xticklines') yticklines = getp(gca(), 'yticklines') xgridlines = getp(gca(), 'xgridlines') Modified: branches/v0_98_5_maint/lib/matplotlib/pylab.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/pylab.py 2009-03-06 19:14:30 UTC (rev 6959) +++ branches/v0_98_5_maint/lib/matplotlib/pylab.py 2009-03-07 19:19:40 UTC (rev 6960) @@ -42,7 +42,7 @@ gca - return the current axes gcf - return the current figure gci - get the current image, or None - getp - get a handle graphics property + getp - get a graphics property grid - set whether gridding is on hist - make a histogram hold - set the axes hold state @@ -69,7 +69,7 @@ rgrids - customize the radial grids and labels for polar savefig - save the current figure scatter - make a scatter plot - setp - set a handle graphics property + setp - set a graphics property semilogx - log x axis semilogy - log y axis show - show the figures Modified: branches/v0_98_5_maint/lib/matplotlib/pyplot.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/pyplot.py 2009-03-06 19:14:30 UTC (rev 6959) +++ branches/v0_98_5_maint/lib/matplotlib/pyplot.py 2009-03-07 19:19:40 UTC (rev 6960) @@ -193,7 +193,7 @@ *number* attribute holding this number. If *num* is an integer, and ``figure(num)`` already exists, make it - active and return the handle to it. If ``figure(num)`` does not exist + active and return a reference to it. If ``figure(num)`` does not exist it will be created. Numbering starts at 1, matlab style:: figure(1) @@ -264,7 +264,7 @@ return figManager.canvas.figure def gcf(): - "Return a handle to the current figure." + "Return a reference to the current figure." figManager = _pylab_helpers.Gcf.get_active() if figManager is not None: @@ -1166,7 +1166,7 @@ gca return the current axes gcf return the current figure gci get the current image, or None - getp get a handle graphics property + getp get a graphics property hist make a histogram hold set the hold state on current axes legend add a legend to the axes @@ -1182,7 +1182,7 @@ rc control the default params savefig save the current figure scatter make a scatter plot - setp set a handle graphics property + setp set a graphics property semilogx log x axis semilogy log y axis show show the figures @@ -1229,7 +1229,7 @@ def colors(): """ - This is a do nothing function to provide you with help on how + This is a do-nothing function to provide you with help on how matplotlib handles colors. Commands which take color arguments can use several formats to This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2009-03-11 19:37:06
|
Revision: 6972 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6972&view=rev Author: efiring Date: 2009-03-11 19:36:22 +0000 (Wed, 11 Mar 2009) Log Message: ----------- Ensure wx version >= 2.8; Sandro Tosi patch plus change to backend Modified Paths: -------------- branches/v0_98_5_maint/CHANGELOG branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx2.py branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx3.py branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx4.py branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx5.py branches/v0_98_5_maint/lib/matplotlib/backends/backend_wx.py branches/v0_98_5_maint/lib/matplotlib/backends/backend_wxagg.py Modified: branches/v0_98_5_maint/CHANGELOG =================================================================== --- branches/v0_98_5_maint/CHANGELOG 2009-03-10 20:45:44 UTC (rev 6971) +++ branches/v0_98_5_maint/CHANGELOG 2009-03-11 19:36:22 UTC (rev 6972) @@ -1,3 +1,6 @@ +2009-03-11 Ensure wx version >= 2.8; thanks to Sandro Tosi and + Chris Barker. - EF + 2009-02-26 Support image clipping in pdf backend. - JKS 2009-02-16 Move plot_directive.py to the installed source tree. Add Modified: branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx2.py =================================================================== --- branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx2.py 2009-03-10 20:45:44 UTC (rev 6971) +++ branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx2.py 2009-03-11 19:36:22 UTC (rev 6972) @@ -4,6 +4,10 @@ toolbar - comment out the setA_toolbar line for no toolbar """ +# Used to guarantee to use at least Wx2.8 +import wxversion +wxversion.ensureMinimal('2.8') + from numpy import arange, sin, pi import matplotlib @@ -20,15 +24,15 @@ from matplotlib.figure import Figure -from wx import * +import wx -class CanvasFrame(Frame): +class CanvasFrame(wx.Frame): def __init__(self): - Frame.__init__(self,None,-1, + wx.Frame.__init__(self,None,-1, 'CanvasFrame',size=(550,350)) - self.SetBackgroundColour(NamedColor("WHITE")) + self.SetBackgroundColour(wx.NamedColor("WHITE")) self.figure = Figure() self.axes = self.figure.add_subplot(111) @@ -38,8 +42,8 @@ self.axes.plot(t,s) self.canvas = FigureCanvas(self, -1, self.figure) - self.sizer = BoxSizer(VERTICAL) - self.sizer.Add(self.canvas, 1, LEFT | TOP | GROW) + self.sizer = wx.BoxSizer(wx.VERTICAL) + self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.sizer) self.Fit() @@ -49,7 +53,7 @@ def add_toolbar(self): self.toolbar = NavigationToolbar2Wx(self.canvas) self.toolbar.Realize() - if Platform == '__WXMAC__': + if wx.Platform == '__WXMAC__': # Mac platform (OSX 10.3, MacPython) does not seem to cope with # having a toolbar in a sizer. This work-around gets the buttons # back, but at the expense of having the toolbar at the top @@ -62,8 +66,8 @@ # By adding toolbar in sizer, we are able to put it at the bottom # of the frame - so appearance is closer to GTK version. # As noted above, doesn't work for Mac. - self.toolbar.SetSize(Size(fw, th)) - self.sizer.Add(self.toolbar, 0, LEFT | EXPAND) + self.toolbar.SetSize(wx.Size(fw, th)) + self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) # update the axes menu on the toolbar self.toolbar.update() @@ -71,7 +75,7 @@ def OnPaint(self, event): self.canvas.draw() -class App(App): +class App(wx.App): def OnInit(self): 'Create the main window and insert the custom frame' Modified: branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx3.py =================================================================== --- branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx3.py 2009-03-10 20:45:44 UTC (rev 6971) +++ branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx3.py 2009-03-11 19:36:22 UTC (rev 6972) @@ -18,6 +18,11 @@ Thanks to matplotlib and wx teams for creating such great software! """ + +# Used to guarantee to use at least Wx2.8 +import wxversion +wxversion.ensureMinimal('2.8') + import sys, time, os, gc import matplotlib matplotlib.use('WXAgg') @@ -26,18 +31,18 @@ from matplotlib.figure import Figure import numpy as npy -from wx import * -from wx.xrc import * +import wx +import wx.xrc as xrc ERR_TOL = 1e-5 # floating point slop for peak-detection matplotlib.rc('image', origin='lower') -class PlotPanel(Panel): +class PlotPanel(wx.Panel): def __init__(self, parent): - Panel.__init__(self, parent, -1) + wx.Panel.__init__(self, parent, -1) self.fig = Figure((5,4), 75) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) @@ -46,11 +51,11 @@ #self.toolbar.set_active([0,1]) # Now put all into a sizer - sizer = BoxSizer(VERTICAL) + sizer = wx.BoxSizer(wx.VERTICAL) # This way of adding to sizer allows resizing - sizer.Add(self.canvas, 1, LEFT|TOP|GROW) + sizer.Add(self.canvas, 1, wx.LEFT|wx.TOP|wx.GROW) # Best to allow the toolbar to resize! - sizer.Add(self.toolbar, 0, GROW) + sizer.Add(self.toolbar, 0, wx.GROW) self.SetSizer(sizer) self.Fit() @@ -94,43 +99,43 @@ # this is supposed to prevent redraw flicker on some X servers... pass -class MyApp(App): +class MyApp(wx.App): def OnInit(self): xrcfile = os.path.join(os.path.dirname(__file__),"..","data", "embedding_in_wx3.xrc") - self.res = XmlResource(xrcfile) + self.res = xrc.XmlResource(xrcfile) # main frame and panel --------- self.frame = self.res.LoadFrame(None,"MainFrame") - self.panel = XRCCTRL(self.frame,"MainPanel") + self.panel = xrc.XRCCTRL(self.frame,"MainPanel") # matplotlib panel ------------- # container for matplotlib panel (I like to make a container # panel for our panel so I know where it'll go when in XRCed.) - plot_container = XRCCTRL(self.frame,"plot_container_panel") - sizer = BoxSizer(VERTICAL) + plot_container = xrc.XRCCTRL(self.frame,"plot_container_panel") + sizer = wx.BoxSizer(wx.VERTICAL) # matplotlib panel itself self.plotpanel = PlotPanel(plot_container) self.plotpanel.init_plot_data() # wx boilerplate - sizer.Add(self.plotpanel, 1, EXPAND) + sizer.Add(self.plotpanel, 1, wx.EXPAND) plot_container.SetSizer(sizer) # whiz button ------------------ - whiz_button = XRCCTRL(self.frame,"whiz_button") - EVT_BUTTON(whiz_button, whiz_button.GetId(), - self.plotpanel.OnWhiz) + whiz_button = xrc.XRCCTRL(self.frame,"whiz_button") + wx.EVT_BUTTON(whiz_button, whiz_button.GetId(), + self.plotpanel.OnWhiz) # bang button ------------------ - bang_button = XRCCTRL(self.frame,"bang_button") - EVT_BUTTON(bang_button, bang_button.GetId(), - self.OnBang) + bang_button = xrc.XRCCTRL(self.frame,"bang_button") + wx.EVT_BUTTON(bang_button, bang_button.GetId(), + self.OnBang) # final setup ------------------ Modified: branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx4.py =================================================================== --- branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx4.py 2009-03-10 20:45:44 UTC (rev 6971) +++ branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx4.py 2009-03-11 19:36:22 UTC (rev 6972) @@ -4,6 +4,10 @@ toolbar """ +# Used to guarantee to use at least Wx2.8 +import wxversion +wxversion.ensureMinimal('2.8') + from numpy import arange, sin, pi import matplotlib @@ -16,13 +20,13 @@ from matplotlib.figure import Figure from numpy.random import rand -from wx import * +import wx class MyNavigationToolbar(NavigationToolbar2WxAgg): """ Extend the default wx toolbar with your own event handlers """ - ON_CUSTOM = NewId() + ON_CUSTOM = wx.NewId() def __init__(self, canvas, cankill): NavigationToolbar2WxAgg.__init__(self, canvas) @@ -30,7 +34,7 @@ # probably want to add your own. self.AddSimpleTool(self.ON_CUSTOM, _load_bitmap('stock_left.xpm'), 'Click me', 'Activate custom contol') - EVT_TOOL(self, self.ON_CUSTOM, self._on_custom) + wx.EVT_TOOL(self, self.ON_CUSTOM, self._on_custom) def _on_custom(self, evt): # add some text to the axes in a random location in axes (0,1) @@ -51,13 +55,13 @@ evt.Skip() -class CanvasFrame(Frame): +class CanvasFrame(wx.Frame): def __init__(self): - Frame.__init__(self,None,-1, + wx.Frame.__init__(self,None,-1, 'CanvasFrame',size=(550,350)) - self.SetBackgroundColour(NamedColor("WHITE")) + self.SetBackgroundColour(wx.NamedColor("WHITE")) self.figure = Figure(figsize=(5,4), dpi=100) self.axes = self.figure.add_subplot(111) @@ -68,14 +72,14 @@ self.canvas = FigureCanvas(self, -1, self.figure) - self.sizer = BoxSizer(VERTICAL) - self.sizer.Add(self.canvas, 1, TOP | LEFT | EXPAND) + self.sizer = wx.BoxSizer(wx.VERTICAL) + self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND) # Capture the paint message - EVT_PAINT(self, self.OnPaint) + wx.EVT_PAINT(self, self.OnPaint) self.toolbar = MyNavigationToolbar(self.canvas, True) self.toolbar.Realize() - if Platform == '__WXMAC__': + if wx.Platform == '__WXMAC__': # Mac platform (OSX 10.3, MacPython) does not seem to cope with # having a toolbar in a sizer. This work-around gets the buttons # back, but at the expense of having the toolbar at the top @@ -88,8 +92,8 @@ # By adding toolbar in sizer, we are able to put it at the bottom # of the frame - so appearance is closer to GTK version. # As noted above, doesn't work for Mac. - self.toolbar.SetSize(Size(fw, th)) - self.sizer.Add(self.toolbar, 0, LEFT | EXPAND) + self.toolbar.SetSize(wx.Size(fw, th)) + self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) # update the axes menu on the toolbar self.toolbar.update() @@ -101,7 +105,7 @@ self.canvas.draw() event.Skip() -class App(App): +class App(wx.App): def OnInit(self): 'Create the main window and insert the custom frame' Modified: branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx5.py =================================================================== --- branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx5.py 2009-03-10 20:45:44 UTC (rev 6971) +++ branches/v0_98_5_maint/examples/user_interfaces/embedding_in_wx5.py 2009-03-11 19:36:22 UTC (rev 6972) @@ -1,3 +1,7 @@ +# Used to guarantee to use at least Wx2.8 +import wxversion +wxversion.ensureMinimal('2.8') + import wx import wx.aui import matplotlib as mpl Modified: branches/v0_98_5_maint/lib/matplotlib/backends/backend_wx.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/backends/backend_wx.py 2009-03-10 20:45:44 UTC (rev 6971) +++ branches/v0_98_5_maint/lib/matplotlib/backends/backend_wx.py 2009-03-11 19:36:22 UTC (rev 6972) @@ -108,12 +108,23 @@ import traceback, pdb _DEBUG_lvls = {1 : 'Low ', 2 : 'Med ', 3 : 'High', 4 : 'Error' } +missingwx = "Matplotlib backend_wx and backend_wxagg require wxPython >=2.8" try: + import wxversion +except ImportError: + raise ImportError(missingwx) + +try: + wxversion.ensureMinimal('2.8') +except wxversion.AlreadyImportedError: + pass + +try: import wx backend_version = wx.VERSION_STRING -except: - raise ImportError("Matplotlib backend_wx requires wxPython be installed") +except ImportError: + raise ImportError(missingwx) #!!! this is the call that is causing the exception swallowing !!! #wx.InitAllImageHandlers() Modified: branches/v0_98_5_maint/lib/matplotlib/backends/backend_wxagg.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/backends/backend_wxagg.py 2009-03-10 20:45:44 UTC (rev 6971) +++ branches/v0_98_5_maint/lib/matplotlib/backends/backend_wxagg.py 2009-03-11 19:36:22 UTC (rev 6972) @@ -16,17 +16,16 @@ """ -import wx import matplotlib from matplotlib.figure import Figure from backend_agg import FigureCanvasAgg -import backend_wx +import backend_wx # already uses wxversion.ensureMinimal('2.8') from backend_wx import FigureManager, FigureManagerWx, FigureCanvasWx, \ FigureFrameWx, DEBUG_MSG, NavigationToolbar2Wx, error_msg_wx, \ draw_if_interactive, show, Toolbar, backend_version +import wx - class FigureFrameWxAgg(FigureFrameWx): def get_canvas(self, fig): return FigureCanvasWxAgg(self, -1, fig) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ef...@us...> - 2009-03-17 19:34:45
|
Revision: 6985 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6985&view=rev Author: efiring Date: 2009-03-17 19:34:27 +0000 (Tue, 17 Mar 2009) Log Message: ----------- In contourf, don't accidentally set the edgecolor. Modified Paths: -------------- branches/v0_98_5_maint/CHANGELOG branches/v0_98_5_maint/lib/matplotlib/contour.py Modified: branches/v0_98_5_maint/CHANGELOG =================================================================== --- branches/v0_98_5_maint/CHANGELOG 2009-03-17 19:15:01 UTC (rev 6984) +++ branches/v0_98_5_maint/CHANGELOG 2009-03-17 19:34:27 UTC (rev 6985) @@ -1,3 +1,6 @@ +2009-03-17 Fix bugs in edge color handling by contourf, found + by Jae-Joon Lee. - EF + 2009-03-11 Ensure wx version >= 2.8; thanks to Sandro Tosi and Chris Barker. - EF Modified: branches/v0_98_5_maint/lib/matplotlib/contour.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/contour.py 2009-03-17 19:15:01 UTC (rev 6984) +++ branches/v0_98_5_maint/lib/matplotlib/contour.py 2009-03-17 19:34:27 UTC (rev 6985) @@ -629,8 +629,10 @@ self.to_rgba(self.cvalues, alpha=self.alpha)] self.tcolors = tcolors for color, collection in zip(tcolors, self.collections): - collection.set_alpha(self.alpha) - collection.set_color(color) + if self.filled: + collection.set_facecolor(color) + else: + collection.set_color(color) for label, cv in zip(self.labelTexts, self.labelCValues): label.set_alpha(self.alpha) label.set_color(self.labelMappable.to_rgba(cv)) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jo...@us...> - 2009-04-06 17:03:16
|
Revision: 7033 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7033&view=rev Author: jouni Date: 2009-04-06 17:03:09 +0000 (Mon, 06 Apr 2009) Log Message: ----------- texmanager.make_dvi now raises an error if LaTeX failed to create an output file Modified Paths: -------------- branches/v0_98_5_maint/CHANGELOG branches/v0_98_5_maint/lib/matplotlib/texmanager.py Modified: branches/v0_98_5_maint/CHANGELOG =================================================================== --- branches/v0_98_5_maint/CHANGELOG 2009-04-06 01:52:45 UTC (rev 7032) +++ branches/v0_98_5_maint/CHANGELOG 2009-04-06 17:03:09 UTC (rev 7033) @@ -1,3 +1,7 @@ +2009-04-06 texmanager.make_dvi now raises an error if LaTeX failed to + create an output file. Thanks to Joao Luis Silva for reporting + this. - JKS + 2009-04-05 _png.read_png() reads 12 bit PNGs (patch from Tobias Wood) - ADS Modified: branches/v0_98_5_maint/lib/matplotlib/texmanager.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/texmanager.py 2009-04-06 01:52:45 UTC (rev 7032) +++ branches/v0_98_5_maint/lib/matplotlib/texmanager.py 2009-04-06 17:03:09 UTC (rev 7033) @@ -285,7 +285,12 @@ fh.close() except IOError: report = 'No latex error report available.' - if exit_status: + try: + os.stat(dvifile) + exists = True + except OSError: + exists = False + if exit_status or not exists: 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') This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jo...@us...> - 2009-04-06 18:59:49
|
Revision: 7035 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7035&view=rev Author: jouni Date: 2009-04-06 18:59:47 +0000 (Mon, 06 Apr 2009) Log Message: ----------- The pdf backend now escapes newlines and linefeeds in strings - fixes #2708559 Modified Paths: -------------- branches/v0_98_5_maint/CHANGELOG branches/v0_98_5_maint/examples/pylab_examples/usetex_demo.py branches/v0_98_5_maint/lib/matplotlib/backends/backend_pdf.py Modified: branches/v0_98_5_maint/CHANGELOG =================================================================== --- branches/v0_98_5_maint/CHANGELOG 2009-04-06 17:12:37 UTC (rev 7034) +++ branches/v0_98_5_maint/CHANGELOG 2009-04-06 18:59:47 UTC (rev 7035) @@ -1,3 +1,6 @@ +2009-04-06 The pdf backend now escapes newlines and linefeeds in strings. + Fixes sf bug #2708559; thanks to Tiago Pereira for the report. + 2009-04-06 texmanager.make_dvi now raises an error if LaTeX failed to create an output file. Thanks to Joao Luis Silva for reporting this. - JKS Modified: branches/v0_98_5_maint/examples/pylab_examples/usetex_demo.py =================================================================== --- branches/v0_98_5_maint/examples/pylab_examples/usetex_demo.py 2009-04-06 17:12:37 UTC (rev 7034) +++ branches/v0_98_5_maint/examples/pylab_examples/usetex_demo.py 2009-04-06 18:59:47 UTC (rev 7035) @@ -56,4 +56,8 @@ ## phase field equations pylab.text(0.2, 0.15, r'$\mathcal{F} = \int f\left( \phi, c \right) dV,$ \newline $ \frac{ \partial \phi } { \partial t } = -M_{ \phi } \frac{ \delta \mathcal{F} } { \delta \phi }$', {'color' : 'b', 'fontsize' : 20}) +## these went wrong in pdf in a previous version +pylab.text(-.9,.42,r'gamma: $\gamma$', {'color': 'r', 'fontsize': 20}) +pylab.text(-.9,.36,r'Omega: $\Omega$', {'color': 'b', 'fontsize': 20}) + pylab.show() Modified: branches/v0_98_5_maint/lib/matplotlib/backends/backend_pdf.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/backends/backend_pdf.py 2009-04-06 17:12:37 UTC (rev 7034) +++ branches/v0_98_5_maint/lib/matplotlib/backends/backend_pdf.py 2009-04-06 18:59:47 UTC (rev 7035) @@ -112,7 +112,20 @@ result.append(' '.join(strings[lasti:])) return '\n'.join(result) -_string_escape_regex = re.compile(r'([\\()])') +# PDF strings are supposed to be able to include any eight-bit data, +# except that unbalanced parens and backslashes must be escaped by a +# backslash. However, sf bug #2708559 shows that the carriage return +# character may get read as a newline; these characters correspond to +# \gamma and \Omega in TeX's math font encoding. Escaping them fixes +# the bug. +_string_escape_regex = re.compile(r'([\\()\r\n])') +def _string_escape(match): + m = match.group(0) + if m in r'\()': return '\\' + m + elif m == '\n': return r'\n' + elif m == '\r': return r'\r' + assert False + def pdfRepr(obj): """Map Python objects to PDF syntax.""" @@ -138,7 +151,7 @@ # simpler to escape them all. TODO: cut long strings into lines; # I believe there is some maximum line length in PDF. elif is_string_like(obj): - return '(' + _string_escape_regex.sub(r'\\\1', obj) + ')' + return '(' + _string_escape_regex.sub(_string_escape, obj) + ')' # Dictionaries. The keys must be PDF names, so if we find strings # there, we make Name objects from them. The values may be This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2009-04-13 02:56:27
|
Revision: 7039 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7039&view=rev Author: jdh2358 Date: 2009-04-13 02:56:11 +0000 (Mon, 13 Apr 2009) Log Message: ----------- fixed csv2rec bug referenced in sf bug 2745173 Modified Paths: -------------- branches/v0_98_5_maint/doc/matplotlibrc branches/v0_98_5_maint/lib/matplotlib/mlab.py Modified: branches/v0_98_5_maint/doc/matplotlibrc =================================================================== --- branches/v0_98_5_maint/doc/matplotlibrc 2009-04-13 02:22:30 UTC (rev 7038) +++ branches/v0_98_5_maint/doc/matplotlibrc 2009-04-13 02:56:11 UTC (rev 7039) @@ -27,7 +27,6 @@ # the default backend; one of GTK GTKAgg GTKCairo FltkAgg QtAgg TkAgg # WX WXAgg Agg Cairo GD GDK Paint PS PDF SVG Template backend : Agg -numerix : numpy # numpy, Numeric or numarray #maskedarray : False # True to use external maskedarray module # instead of numpy.ma; this is a temporary # setting for testing maskedarray. Modified: branches/v0_98_5_maint/lib/matplotlib/mlab.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/mlab.py 2009-04-13 02:22:30 UTC (rev 7038) +++ branches/v0_98_5_maint/lib/matplotlib/mlab.py 2009-04-13 02:56:11 UTC (rev 7039) @@ -2532,8 +2532,14 @@ fh.seek(0) reader = csv.reader(fh, delimiter=delimiter) process_skiprows(reader) + if needheader: - skipheader = reader.next() + while 1: + # skip past any comments and consume one line of column header + row = reader.next() + if len(row) and row[0].startswith(comments): + continue + break # iterate over the remaining rows and convert the data to date # objects, ints, or floats as approriate This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lee...@us...> - 2009-05-04 20:05:59
|
Revision: 7082 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7082&view=rev Author: leejjoon Date: 2009-05-04 20:05:57 +0000 (Mon, 04 May 2009) Log Message: ----------- Fix bug that Text.Annotation is still drawn while set to not visible Modified Paths: -------------- branches/v0_98_5_maint/CHANGELOG branches/v0_98_5_maint/lib/matplotlib/text.py Modified: branches/v0_98_5_maint/CHANGELOG =================================================================== --- branches/v0_98_5_maint/CHANGELOG 2009-05-04 19:07:43 UTC (rev 7081) +++ branches/v0_98_5_maint/CHANGELOG 2009-05-04 20:05:57 UTC (rev 7082) @@ -1,4 +1,7 @@ ====================================================================== +2009-05-04 Fix bug that Text.Annotation is still drawn while set to + not visible.-JJL + 2008-04-12 Release 0.98.5.3 at r7038 2009-04-06 The pdf backend now escapes newlines and linefeeds in strings. Modified: branches/v0_98_5_maint/lib/matplotlib/text.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/text.py 2009-05-04 19:07:43 UTC (rev 7081) +++ branches/v0_98_5_maint/lib/matplotlib/text.py 2009-05-04 20:05:57 UTC (rev 7082) @@ -1602,6 +1602,11 @@ """ Draw the :class:`Annotation` object to the given *renderer*. """ + + if renderer is not None: + self._renderer = renderer + if not self.get_visible(): return + self.update_positions(renderer) self.update_bbox_position_size(renderer) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lee...@us...> - 2009-05-17 22:04:49
|
Revision: 7115 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7115&view=rev Author: leejjoon Date: 2009-05-17 22:04:38 +0000 (Sun, 17 May 2009) Log Message: ----------- Fix bug(#2749174) that some properties of minor ticks are not conserved. Modified Paths: -------------- branches/v0_98_5_maint/CHANGELOG branches/v0_98_5_maint/lib/matplotlib/axis.py Modified: branches/v0_98_5_maint/CHANGELOG =================================================================== --- branches/v0_98_5_maint/CHANGELOG 2009-05-17 21:36:34 UTC (rev 7114) +++ branches/v0_98_5_maint/CHANGELOG 2009-05-17 22:04:38 UTC (rev 7115) @@ -1,3 +1,6 @@ +2009-05-17 Fix bug(#2749174) that some properties of minor ticks are + not conserved -JJL + ====================================================================== 2008-05-17 Release 0.98.5.3 at r7107 Modified: branches/v0_98_5_maint/lib/matplotlib/axis.py =================================================================== --- branches/v0_98_5_maint/lib/matplotlib/axis.py 2009-05-17 21:36:34 UTC (rev 7114) +++ branches/v0_98_5_maint/lib/matplotlib/axis.py 2009-05-17 22:04:38 UTC (rev 7115) @@ -1273,8 +1273,12 @@ assert position in ('top', 'bottom', 'both', 'default', 'none') - ticks = list( self.get_major_ticks() ) # a copy - ticks.extend( self.get_minor_ticks() ) + # The first ticks of major & minor ticks should always be + # included, otherwise, the information can be lost. Thus, use + # majorTicks instead of get_major_ticks() which may return + # empty list. + ticks = list( self.majorTicks ) # a copy + ticks.extend( self.minorTicks ) if position == 'top': for t in ticks: @@ -1514,8 +1518,12 @@ """ assert position in ('left', 'right', 'both', 'default', 'none') - ticks = list( self.get_major_ticks() ) # a copy - ticks.extend( self.get_minor_ticks() ) + # The first ticks of major & minor ticks should always be + # included, otherwise, the information can be lost. Thus, use + # majorTicks instead of get_major_ticks() which may return + # empty list. + ticks = list( self.majorTicks ) # a copy + ticks.extend( self.minorTicks ) if position == 'right': self.set_offset_position('right') This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |