From: <jd...@us...> - 2008-12-08 21:06:52
|
Revision: 6517 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6517&view=rev Author: jdh2358 Date: 2008-12-08 21:06:49 +0000 (Mon, 08 Dec 2008) Log Message: ----------- fixed inaxes event bug Modified Paths: -------------- trunk/matplotlib/doc/_templates/gallery.html trunk/matplotlib/doc/users/mathtext.rst trunk/matplotlib/lib/matplotlib/backend_bases.py trunk/matplotlib/lib/matplotlib/patches.py Modified: trunk/matplotlib/doc/_templates/gallery.html =================================================================== --- trunk/matplotlib/doc/_templates/gallery.html 2008-12-08 20:21:33 UTC (rev 6516) +++ trunk/matplotlib/doc/_templates/gallery.html 2008-12-08 21:06:49 UTC (rev 6517) @@ -53,6 +53,8 @@ <a href="examples/api/two_scales.html"><img src="_static/plot_directive/mpl_examples/api/thumbnails/two_scales.png" border="0" alt="two_scales"/></a> +<a href="examples/api/unicode_minus.html"><img src="_static/plot_directive/mpl_examples/api/thumbnails/unicode_minus.png" border="0" alt="unicode_minus"/></a> + <a href="examples/api/watermark_image.html"><img src="_static/plot_directive/mpl_examples/api/thumbnails/watermark_image.png" border="0" alt="watermark_image"/></a> <a href="examples/api/watermark_text.html"><img src="_static/plot_directive/mpl_examples/api/thumbnails/watermark_text.png" border="0" alt="watermark_text"/></a> @@ -217,8 +219,12 @@ <a href="examples/pylab_examples/errorbar_limits.html"><img src="_static/plot_directive/mpl_examples/pylab_examples/thumbnails/errorbar_limits_01.png" border="0" alt="errorbar_limits"/></a> +<a href="examples/pylab_examples/fancyarrow_demo.html"><img src="_static/plot_directive/mpl_examples/pylab_examples/thumbnails/fancyarrow_demo.png" border="0" alt="fancyarrow_demo"/></a> + <a href="examples/pylab_examples/fancybox_demo.html"><img src="_static/plot_directive/mpl_examples/pylab_examples/thumbnails/fancybox_demo.png" border="0" alt="fancybox_demo"/></a> +<a href="examples/pylab_examples/fancybox_demo2.html"><img src="_static/plot_directive/mpl_examples/pylab_examples/thumbnails/fancybox_demo2.png" border="0" alt="fancybox_demo2"/></a> + <a href="examples/pylab_examples/fancytextbox_demo.html"><img src="_static/plot_directive/mpl_examples/pylab_examples/thumbnails/fancytextbox_demo.png" border="0" alt="fancytextbox_demo"/></a> <a href="examples/pylab_examples/figimage_demo.html"><img src="_static/plot_directive/mpl_examples/pylab_examples/thumbnails/figimage_demo.png" border="0" alt="figimage_demo"/></a> @@ -333,6 +339,8 @@ <a href="examples/pylab_examples/legend_demo2.html"><img src="_static/plot_directive/mpl_examples/pylab_examples/thumbnails/legend_demo2.png" border="0" alt="legend_demo2"/></a> +<a href="examples/pylab_examples/legend_demo3.html"><img src="_static/plot_directive/mpl_examples/pylab_examples/thumbnails/legend_demo3.png" border="0" alt="legend_demo3"/></a> + <a href="examples/pylab_examples/legend_scatter.html"><img src="_static/plot_directive/mpl_examples/pylab_examples/thumbnails/legend_scatter.png" border="0" alt="legend_scatter"/></a> <a href="examples/pylab_examples/line_collection.html"><img src="_static/plot_directive/mpl_examples/pylab_examples/thumbnails/line_collection.png" border="0" alt="line_collection"/></a> Modified: trunk/matplotlib/doc/users/mathtext.rst =================================================================== --- trunk/matplotlib/doc/users/mathtext.rst 2008-12-08 20:21:33 UTC (rev 6516) +++ trunk/matplotlib/doc/users/mathtext.rst 2008-12-08 21:06:49 UTC (rev 6517) @@ -143,8 +143,16 @@ s(t) = \mathcal{A}\sin(2 \omega t) Here "s" and "t" are variable in italics font (default), "sin" is in -Roman font, and the amplitude "A" is in calligraphy font. +Roman font, and the amplitude "A" is in calligraphy font. Note in the +example above the caligraphy ``A`` is squished into the ``sin``. You +can use a spacing command to add a little whitespace between them:: + s(t) = \mathcal{A}\/\sin(2 \omega t) + +.. math:: + + s(t) = \mathcal{A}\/\sin(2 \omega t) + The choices available with all fonts are: ============================ ================================== @@ -159,7 +167,7 @@ .. role:: math-stix(math) :fontset: stix -When using the STIX fonts, you also have the choice of: +When using the `STIX <http://www.aip.org/stixfonts/>`_ fonts, you also have the choice of: ====================================== ========================================= Command Result Modified: trunk/matplotlib/lib/matplotlib/backend_bases.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-12-08 20:21:33 UTC (rev 6516) +++ trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-12-08 21:06:49 UTC (rev 6517) @@ -758,7 +758,7 @@ if x is None or y is None: # cannot check if event was in axes if no x,y info - self.inaxes = False + self.inaxes = None self._update_enter_leave() return Modified: trunk/matplotlib/lib/matplotlib/patches.py =================================================================== --- trunk/matplotlib/lib/matplotlib/patches.py 2008-12-08 20:21:33 UTC (rev 6516) +++ trunk/matplotlib/lib/matplotlib/patches.py 2008-12-08 21:06:49 UTC (rev 6517) @@ -1382,9 +1382,9 @@ for row in _table: for column, cell in zip(columns, row): column.append(cell) - - + + col_len = [max([len(cell) for cell in column]) for column in columns] lines = [] @@ -1394,10 +1394,10 @@ lines.append(table_formatstr) lines.append(pad + ' '.join([cell.ljust(cl) for cell, cl in zip(_table[0], col_len)])) lines.append(table_formatstr) - + lines.extend([(pad + ' '.join([cell.ljust(cl) for cell, cl in zip(row, col_len)])) for row in _table[1:]]) - + lines.append(table_formatstr) lines.append('') return "\n".join(lines) @@ -1427,10 +1427,10 @@ for argname, argdefault in zip(args[1:], defaults)] else: args = [] - + _table.append([cls.__name__, name, ",".join([("%s=%s" % (an, av)) for an, av in args])]) - + return _pprint_table(_table) @@ -1448,7 +1448,7 @@ # the "class" should have the _style_list attribute, which is # a dictionary of stylname, style class paie. - + _list = stylename.replace(" ","").split(",") _name = _list[0].lower() try: @@ -1492,20 +1492,20 @@ BoxStyle.Round(pad=0.2) - or + or BoxStyle("Round", pad=0.2) or - + BoxStyle("Round, pad=0.2") Following boxstyle classes are defined. - + %(AvailableBoxstyles)s An instance of any boxstyle class is an callable object, - whose call signature is + whose call signature is:: __call__(self, x0, y0, width, height, mutation_size, aspect_ratio=1.) @@ -1517,7 +1517,7 @@ the mutation. """ - + _style_list = {} @@ -1593,7 +1593,7 @@ *pad* amount of padding """ - + self.pad = pad super(BoxStyle.Square, self).__init__() @@ -1653,7 +1653,7 @@ dxx = dx*.5 # adjust x0. 1.4 <- sqrt(2) x0 = x0 + pad / 1.4 - + cp = [(x0+dxx, y0), (x1, y0), (x1, y1), (x0+dxx, y1), (x0+dxx, y1+dxx), (x0-dx, y0+dx), (x0+dxx, y0-dxx), # arrow (x0+dxx, y0), (x0+dxx, y0)] @@ -1687,7 +1687,7 @@ return p - + _style_list["rarrow"] = RArrow @@ -1770,7 +1770,7 @@ *rounding_size* rounding size of edges. *pad* if None """ - + self.pad = pad self.rounding_size = rounding_size super(BoxStyle.Round4, self).__init__() @@ -2038,8 +2038,8 @@ self._bbox_transmuter = boxstyle else: self._bbox_transmuter = BoxStyle(boxstyle, **kw) - + kwdoc = dict() kwdoc["AvailableBoxstyles"]=_pprint_styles(BoxStyle._style_list) kwdoc.update(artist.kwdocd) @@ -2180,12 +2180,12 @@ ConnectionStyle.Arc3(rad=0.2) - or + or ConnectionStyle("Arc3", rad=0.2) or - + ConnectionStyle("Arc3, rad=0.2") Following classes are defined @@ -2194,7 +2194,7 @@ An instance of any connection style class is an callable object, - whose call signature is + whose call signature is:: __call__(self, posA, posB, patchA=None, patchB=None, shrinkA=2., shrinkB=2.) @@ -2204,17 +2204,17 @@ (or end) from the boundary of the patch. The path is further shrinked by *shrinkA* (or *shrinkB*) which is given in points. """ - + _style_list = {} class _Base(object): """ A base class for connectionstyle classes. The dervided needs - to implement a *connect* methods whose call signature is + to implement a *connect* methods whose call signature is:: connect(posA, posB) - + where posA and posB are tuples of x, y coordinates to be connected. The methods needs to return a path connecting two points. This base class defines a __call__ method, and few @@ -2289,7 +2289,7 @@ Calls the *connect* method to create a path between *posA* and *posB*. The path is clipped and shrinked. """ - + path = self.connect(posA, posB) clipped_path = self._clip(path, patchA, patchB) @@ -2334,8 +2334,8 @@ return Path(vertices, codes) _style_list["arc3"] = Arc3 - + class Angle3(_Base): """ Creates a simple quadratic bezier curve between two @@ -2448,16 +2448,16 @@ def __init__(self, angleA=0, angleB=0, armA=None, armB=None, rad=0.): """ *angleA* : - starting angle of the path + starting angle of the path *angleB* : - ending angle of the path + ending angle of the path *armA* : - length of the starting arm + length of the starting arm *armB* : - length of the ending arm + length of the ending arm *rad* : rounding radius of the edges @@ -2531,9 +2531,9 @@ __doc__ = cbook.dedent(__doc__) % \ {"AvailableConnectorstyles": _pprint_styles(_style_list)} - + class ArrowStyle(_Style): """ :class:`ArrowStyle` is a container class which defines several @@ -2543,12 +2543,12 @@ A arrowstyle object can be either created as ArrowStyle.Fancy(head_length=.4, head_width=.4, tail_width=.4) - or + or ArrowStyle("Fancy", head_length=.4, head_width=.4, tail_width=.4) or - + ArrowStyle("Fancy, head_length=.4, head_width=.4, tail_width=.4") Following classes are defined @@ -2557,7 +2557,7 @@ An instance of any arrow style class is an callable object, - whose call signature is + whose call signature is:: __call__(self, path, mutation_size, linewidth, aspect_ratio=1.) @@ -2795,14 +2795,14 @@ class CurveA(_Curve): """ - An arrow with a head at its begin point. + An arrow with a head at its begin point. """ def __init__(self, head_length=.4, head_width=.2): """ *head_length* length of the arrow head - + *head_width* width of the arrow head """ @@ -2816,14 +2816,14 @@ class CurveB(_Curve): """ - An arrow with a head at its end point. + An arrow with a head at its end point. """ def __init__(self, head_length=.4, head_width=.2): """ *head_length* length of the arrow head - + *head_width* width of the arrow head """ @@ -2837,14 +2837,14 @@ class CurveAB(_Curve): """ - An arrow with heads both at the begin and the end point. + An arrow with heads both at the begin and the end point. """ def __init__(self, head_length=.4, head_width=.2): """ *head_length* length of the arrow head - + *head_width* width of the arrow head """ @@ -2859,7 +2859,7 @@ class _Bracket(_Base): def __init__(self, bracketA=None, bracketB=None, - widthA=1., widthB=1., + widthA=1., widthB=1., lengthA=0.2, lengthB=0.2, angleA=None, angleB=None, scaleA=None, scaleB=None @@ -2870,8 +2870,8 @@ self.angleA, self.angleB = angleA, angleB self.scaleA, self.scaleB= scaleA, scaleB - def _get_bracket(self, x0, y0, - cos_t, sin_t, width, length, + def _get_bracket(self, x0, y0, + cos_t, sin_t, width, length, ): # arrow from x0, y0 to x1, y1 @@ -2949,10 +2949,10 @@ """ *widthB* width of the bracket - + *lengthB* length of the bracket - + *angleB* angle between the bracket and the line """ @@ -2975,12 +2975,12 @@ *head_with* width of the arrow head - + *tail_width* width of the arrow tail """ - + self.head_length, self.head_width, self.tail_width = \ head_length, head_width, tail_width super(ArrowStyle.Simple, self).__init__() @@ -3043,7 +3043,7 @@ *head_with* width of the arrow head - + *tail_width* width of the arrow tail @@ -3140,7 +3140,7 @@ Wedge(?) shape. Only wokrs with a quadratic bezier curve. The begin point has a width of the tail_width and the end point has a width of 0. At the middle, the width is shrink_factor*tail_width. - + """ def __init__(self, tail_width=.3, shrink_factor=0.5): @@ -3151,7 +3151,7 @@ *shrink_factor* fraction of the arrow width at the middle point """ - + self.tail_width = tail_width self.shrink_factor = shrink_factor super(ArrowStyle.Wedge, self).__init__() @@ -3191,7 +3191,7 @@ A fancy arrow patch. It draws an arrow using the :class:ArrowStyle. """ - + def __str__(self): return self.__class__.__name__ \ + "FancyArrowPatch(%g,%g,%g,%g,%g,%g)" % tuple(self._q_bezier) @@ -3340,8 +3340,8 @@ self._connector = connectionstyle else: self._connector = ConnectionStyle(connectionstyle, **kw) - + def get_connectionstyle(self): """ Return the ConnectionStyle instance This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ry...@us...> - 2008-12-08 21:23:09
|
Revision: 6520 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6520&view=rev Author: ryanmay Date: 2008-12-08 21:23:04 +0000 (Mon, 08 Dec 2008) Log Message: ----------- Update CHANGELOG and api_changes for the changes to psd and friends. Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/doc/api/api_changes.rst Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-12-08 21:16:04 UTC (rev 6519) +++ trunk/matplotlib/CHANGELOG 2008-12-08 21:23:04 UTC (rev 6520) @@ -1,3 +1,8 @@ +2008-12-08 Updated spectral methods (psd, csd, etc.) to scale one-sided + densities by a factor of 2 and, optionally, scale all densities + by the sampling frequency. This gives better MatLab + compatibility. -RM + 2008-12-08 Fixed alignment of ticks in colorbars. -MGD 2008-12-07 drop the deprecated "new" keyword of np.histogram() for Modified: trunk/matplotlib/doc/api/api_changes.rst =================================================================== --- trunk/matplotlib/doc/api/api_changes.rst 2008-12-08 21:16:04 UTC (rev 6519) +++ trunk/matplotlib/doc/api/api_changes.rst 2008-12-08 21:23:04 UTC (rev 6520) @@ -9,6 +9,15 @@ Changes for 0.98.x ================== +* Modified :func:`matplotlib.mlab.psd`, :func:`matplotlib.mlab.csd`, + :func:`matplotlib.mlab.cohere`, and :func:`matplotlib.mlab.specgram` + to scale one-sided densities by a factor of 2. Also, optionally + scale the densities by the sampling frequency, which gives true values + of densities that can be integrated by the returned frequency values. + This also gives better MatLab compatibility. The corresponding + :class:`matplotlib.axes.Axes` methods and :mod:`matplotlib.pyplot` + functions were updated as well. + * Font lookup now uses a nearest-neighbor approach rather than an exact match. Some fonts may be different in plots, but should be closer to what was requested. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-12-08 23:29:06
|
Revision: 6526 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6526&view=rev Author: jdh2358 Date: 2008-12-08 23:28:55 +0000 (Mon, 08 Dec 2008) Log Message: ----------- add support for docstring.hardcopy to format the docstrings less verbosesly for interactive use Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/doc/matplotlibrc trunk/matplotlib/lib/matplotlib/artist.py trunk/matplotlib/lib/matplotlib/rcsetup.py trunk/matplotlib/matplotlibrc.template Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-12-08 23:27:08 UTC (rev 6525) +++ trunk/matplotlib/CHANGELOG 2008-12-08 23:28:55 UTC (rev 6526) @@ -1,3 +1,13 @@ +2008-12-08 Some of the changes Michael made to improve the output of + the property tables in the rest docs broke of made + difficult to use some of the interactive doc helpers, eg + setp and getp. Having all the rest markup in the ipython + shell also confused the docstrings. I added a new rc param + docstring.harcopy, to format the docstrings differently for + hardcopy and other use. Ther ArtistInspector could use a + little refactoring now since there is duplication of effort + between the rest out put and the non-rest output - JDH + 2008-12-08 Updated spectral methods (psd, csd, etc.) to scale one-sided densities by a factor of 2 and, optionally, scale all densities by the sampling frequency. This gives better MatLab Modified: trunk/matplotlib/doc/matplotlibrc =================================================================== --- trunk/matplotlib/doc/matplotlibrc 2008-12-08 23:27:08 UTC (rev 6525) +++ trunk/matplotlib/doc/matplotlibrc 2008-12-08 23:28:55 UTC (rev 6526) @@ -294,6 +294,9 @@ #svg.image_noscale : False # suppress scaling of raster data embedded in SVG #svg.embed_chars : True # embed character outlines in the SVG file +# docstring params +docstring.hardcopy = True # set this when you want to generate hardcopy docstring + # Set the verbose flags. This controls how much information # matplotlib gives you at runtime and where it goes. The verbosity # levels are: silent, helpful, debug, debug-annoying. Any level is @@ -311,5 +314,6 @@ # # You can access the verbose instance in your code # from matplotlib import verbose. + #verbose.level : silent # one of silent, helpful, debug, debug-annoying #verbose.fileo : sys.stdout # a log filename, sys.stdout or sys.stderr Modified: trunk/matplotlib/lib/matplotlib/artist.py =================================================================== --- trunk/matplotlib/lib/matplotlib/artist.py 2008-12-08 23:27:08 UTC (rev 6525) +++ trunk/matplotlib/lib/matplotlib/artist.py 2008-12-08 23:28:55 UTC (rev 6526) @@ -1,5 +1,6 @@ from __future__ import division import re, warnings +import matplotlib import matplotlib.cbook as cbook from transforms import Bbox, IdentityTransform, TransformedBbox, TransformedPath from path import Path @@ -640,9 +641,12 @@ type) and it is your responsibility to make sure this is so. """ if cbook.iterable(o) and len(o): o = o[0] + + self.oorig = o if not isinstance(o, type): o = type(o) self.o = o + self.aliasd = self.get_aliases() def get_aliases(self): @@ -735,7 +739,7 @@ if ds is None: return False return ds.startswith('alias for ') - def aliased_name(self, s, target): + def aliased_name(self, s): """ return 'PROPNAME or alias' if *s* has an alias, else return PROPNAME. @@ -746,11 +750,28 @@ """ if s in self.aliasd: + return s + ''.join([' or %s' % x for x in self.aliasd[s].keys()]) + else: + return s + + + def aliased_name_rest(self, s, target): + """ + return 'PROPNAME or alias' if *s* has an alias, else return + PROPNAME formatted for ReST + + E.g. for the line markerfacecolor property, which has an + alias, return 'markerfacecolor or mfc' and for the transform + property, which does not, return 'transform' + """ + + if s in self.aliasd: aliases = ''.join([' or %s' % x for x in self.aliasd[s].keys()]) else: aliases = '' return ':meth:`%s <%s>`%s' % (s, target, aliases) + def pprint_setters(self, prop=None, leadingspace=2): """ If *prop* is *None*, return a list of strings of all settable properies @@ -772,8 +793,36 @@ attrs.sort() lines = [] + for prop, path in attrs: + accepts = self.get_valid_values(prop) + name = self.aliased_name(prop) + + lines.append('%s%s: %s' %(pad, name, accepts)) + return lines + + def pprint_setters_rest(self, prop=None, leadingspace=2): + """ + If *prop* is *None*, return a list of strings of all settable properies + and their valid values. Format the output for ReST + + If *prop* is not *None*, it is a valid property name and that + property will be returned as a string of property : valid + values. + """ + if leadingspace: + pad = ' '*leadingspace + else: + pad = '' + if prop is not None: + accepts = self.get_valid_values(prop) + return '%s%s: %s' %(pad, prop, accepts) + + attrs = self._get_setters_and_targets() + attrs.sort() + lines = [] + ######## - names = [self.aliased_name(prop, target) for prop, target in attrs] + names = [self.aliased_name_rest(prop, target) for prop, target in attrs] accepts = [self.get_valid_values(prop) for prop, target in attrs] col0_len = max([len(n) for n in names]) @@ -796,7 +845,7 @@ for prop, path in attrs: accepts = self.get_valid_values(prop) - name = self.aliased_name(prop, path) + name = self.aliased_name_rest(prop, path) lines.append('%s%s: %s' %(pad, name, accepts)) return lines @@ -805,20 +854,27 @@ """ Return the getters and actual values as list of strings. """ - getters = [name for name in dir(self.o) + + o = self.oorig + getters = [name for name in dir(o) if name.startswith('get_') - and callable(getattr(self.o, name))] + and callable(getattr(o, name))] + #print getters getters.sort() lines = [] for name in getters: - func = getattr(self.o, name) + func = getattr(o, name) if self.is_alias(func): continue + try: val = func() except: continue if getattr(val, 'shape', ()) != () and len(val)>6: s = str(val[:6]) + '...' else: s = str(val) + s = s.replace('\n', ' ') + if len(s)>50: + s = s[:50] + '...' name = self.aliased_name(name[4:]) lines.append(' %s = %s' %(name, s)) return lines @@ -898,17 +954,17 @@ insp = ArtistInspector(o) if property is None: - print '\n'.join(insp.pprint_getters()) + ret = insp.pprint_getters() + print '\n'.join(ret) return func = getattr(o, 'get_' + property) + return func() -def get(o, *args, **kwargs): - return getp(o, *args, **kwargs) -get.__doc__ = getp.__doc__ +# alias +get = getp - def setp(h, *args, **kwargs): """ matplotlib supports the use of :func:`setp` ("set property") and @@ -984,7 +1040,11 @@ return [x for x in cbook.flatten(ret)] def kwdoc(a): - return '\n'.join(ArtistInspector(a).pprint_setters(leadingspace=2)) + hardcopy = matplotlib.rcParams['docstring.hardcopy'] + if hardcopy: + return '\n'.join(ArtistInspector(a).pprint_setters_rest(leadingspace=2)) + else: + return '\n'.join(ArtistInspector(a).pprint_setters(leadingspace=2)) kwdocd = dict() kwdocd['Artist'] = kwdoc(Artist) Modified: trunk/matplotlib/lib/matplotlib/rcsetup.py =================================================================== --- trunk/matplotlib/lib/matplotlib/rcsetup.py 2008-12-08 23:27:08 UTC (rev 6525) +++ trunk/matplotlib/lib/matplotlib/rcsetup.py 2008-12-08 23:28:55 UTC (rev 6526) @@ -511,6 +511,8 @@ 'svg.image_inline' : [True, validate_bool], # write raster image data directly into the svg file 'svg.image_noscale' : [False, validate_bool], # suppress scaling of raster data embedded in SVG 'svg.embed_char_paths' : [True, validate_bool], # True to save all characters as paths in the SVG + + 'docstring.hardcopy' : [False, validate_bool], # set this when you want to generate hardcopy docstring 'plugins.directory' : ['.matplotlib_plugins', str], # where plugin directory is locate 'path.simplify' : [False, validate_bool], Modified: trunk/matplotlib/matplotlibrc.template =================================================================== --- trunk/matplotlib/matplotlibrc.template 2008-12-08 23:27:08 UTC (rev 6525) +++ trunk/matplotlib/matplotlibrc.template 2008-12-08 23:28:55 UTC (rev 6526) @@ -323,6 +323,9 @@ #svg.image_noscale : False # suppress scaling of raster data embedded in SVG #svg.embed_char_paths : True # embed character outlines in the SVG file +# docstring params +#docstring.hardcopy = False # set this when you want to generate hardcopy docstring + # Set the verbose flags. This controls how much information # matplotlib gives you at runtime and where it goes. The verbosity # levels are: silent, helpful, debug, debug-annoying. Any level is This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-12-09 03:34:02
|
Revision: 6528 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6528&view=rev Author: jdh2358 Date: 2008-12-09 03:33:57 +0000 (Tue, 09 Dec 2008) Log Message: ----------- tweaks to backend driver list Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/examples/tests/backend_driver.py trunk/matplotlib/lib/matplotlib/patches.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-12-09 03:24:44 UTC (rev 6527) +++ trunk/matplotlib/CHANGELOG 2008-12-09 03:33:57 UTC (rev 6528) @@ -1,3 +1,6 @@ +2008-12-08 Removed the prints in the set_*style commands. Return the + list of pprinted strings instead + 2008-12-08 Some of the changes Michael made to improve the output of the property tables in the rest docs broke of made difficult to use some of the interactive doc helpers, eg Modified: trunk/matplotlib/examples/tests/backend_driver.py =================================================================== --- trunk/matplotlib/examples/tests/backend_driver.py 2008-12-09 03:24:44 UTC (rev 6527) +++ trunk/matplotlib/examples/tests/backend_driver.py 2008-12-09 03:33:57 UTC (rev 6528) @@ -25,8 +25,8 @@ pylab_dir = os.path.join('..', 'pylab_examples') pylab_files = [ - 'two_scales.py', + 'accented_text.py', 'alignment_test.py', 'annotation_demo.py', @@ -191,10 +191,8 @@ 'unicode_demo.py', 'vertical_ticklabels.py', 'vline_demo.py', - 'webapp_demo.py', 'xcorr_demo.py', 'zorder_demo.py', - ] @@ -202,13 +200,16 @@ api_files = [ 'agg_oo.py', 'barchart_demo.py', + 'bbox_intersect.py', 'collections_demo.py', + 'color_cycle.py', + 'colorbar_only.py', 'custom_projection_example.py', 'custom_scale_example.py', 'date_demo.py', 'date_index_formatter.py', + 'donut_demo.py', 'font_family_rc.py', - 'font_file.py', 'histogram_demo.py', 'image_zcoord.py', 'legend_demo.py', @@ -216,19 +217,14 @@ 'logo2.py', 'mathtext_asarray.py', 'patch_collection.py', + 'path_patch_demo.py', + 'quad_bezier.py', 'scatter_piecharts.py', 'span_regions.py', + 'two_scales.py' 'unicode_minus.py', 'watermark_image.py', 'watermark_text.py', - - 'bbox_intersect.py', - 'colorbar_only.py', - 'color_cycle.py', - 'donut_demo.py', - 'path_patch_demo.py', - 'quad_bezier.py', - 'two_scales.py' ] units_dir = os.path.join('..', 'units') Modified: trunk/matplotlib/lib/matplotlib/patches.py =================================================================== --- trunk/matplotlib/lib/matplotlib/patches.py 2008-12-09 03:24:44 UTC (rev 6527) +++ trunk/matplotlib/lib/matplotlib/patches.py 2008-12-09 03:33:57 UTC (rev 6528) @@ -1494,19 +1494,19 @@ :class:`BoxStyle` is a container class which defines several boxstyle classes, which are used for :class:`FancyBoxPatch`. - A style object can be created as + A style object can be created as:: BoxStyle.Round(pad=0.2) - or + or:: BoxStyle("Round", pad=0.2) - or + or:: BoxStyle("Round, pad=0.2") - Following boxstyle classes are defined. + The following boxstyle classes are defined. %(AvailableBoxstyles)s @@ -2026,7 +2026,7 @@ Old attrs simply are forgotten. - Without argument (or with *boxstyle* = None), it prints out + Without argument (or with *boxstyle* = None), it returns available box styles. ACCEPTS: [ %(AvailableBoxstyles)s ] @@ -2034,10 +2034,7 @@ """ if boxstyle==None: - # print out available boxstyles and return. - print "Following box styles are available:" - print BoxStyle.pprint_styles() - return + return BoxStyle.pprint_styles() if isinstance(boxstyle, BoxStyle._Base): self._bbox_transmuter = boxstyle @@ -2097,7 +2094,7 @@ return _path - # Followong methods are borrowed from the Rectangle class. + # Following methods are borrowed from the Rectangle class. def get_x(self): "Return the left coord of the rectangle" @@ -2183,19 +2180,19 @@ between two points. These are mainly used with :class:`FancyArrowPatch`. - A connectionstyle object can be either created as + A connectionstyle object can be either created as:: ConnectionStyle.Arc3(rad=0.2) - or + or:: ConnectionStyle("Arc3", rad=0.2) - or + or:: ConnectionStyle("Arc3, rad=0.2") - Following classes are defined + The following classes are defined %(AvailableConnectorstyles)s @@ -2205,11 +2202,13 @@ __call__(self, posA, posB, patchA=None, patchB=None, shrinkA=2., shrinkB=2.) - and it returns a :class:`Path` instance. *posA* and *posB are tuples - of x,y coordinates of the two points to be connected. *patchA* (or - $patchB*) is given, the returned path is clipped so that it start - (or end) from the boundary of the patch. The path is further - shrinked by *shrinkA* (or *shrinkB*) which is given in points. + and it returns a :class:`Path` instance. *posA* and *posB* are + tuples of x,y coordinates of the two points to be + connected. *patchA* (or *patchB*) is given, the returned path is + clipped so that it start (or end) from the boundary of the + patch. The path is further shrunk by *shrinkA* (or *shrinkB*) + which is given in points. + """ _style_list = {} @@ -2547,18 +2546,18 @@ arrowstyle classes, which is used to create an arrow path along a given path. These are mainly used with :class:`FancyArrowPatch`. - A arrowstyle object can be either created as + A arrowstyle object can be either created as:: ArrowStyle.Fancy(head_length=.4, head_width=.4, tail_width=.4) - or + or:: ArrowStyle("Fancy", head_length=.4, head_width=.4, tail_width=.4) - or + or:: ArrowStyle("Fancy, head_length=.4, head_width=.4, tail_width=.4") - Following classes are defined + The following classes are defined %(AvailableArrowstyles)s @@ -3232,7 +3231,7 @@ connected. It can be an instance of the ConnectionStyle class (matplotlib.patches.ConnectionStlye) or a string of the connectionstyle name, with optional comma-separated - attributes. Following connection styles are available. + attributes. The following connection styles are available. %(AvailableConnectorstyles)s @@ -3241,7 +3240,7 @@ drawn. It can be string of the available arrowstyle names, with optional comma-separated attributes, or one of the ArrowStyle instance. The optional attributes are meant to be - scaled with the *mutation_scale*. Following arrow styles are + scaled with the *mutation_scale*. The following arrow styles are available. %(AvailableArrowstyles)s @@ -3334,14 +3333,12 @@ Old attrs simply are forgotten. - Without argument (or with connectionstyle=None), it prints out - available styles. + Without argument (or with connectionstyle=None), return + available styles as a list of strings. """ if connectionstyle==None: - # print out available styles and return. - print "Following styles are available:" - print ConnectionStyle.pprint_styles() + return ConnectionStyle.pprint_styles() if isinstance(connectionstyle, ConnectionStyle._Base): self._connector = connectionstyle @@ -3372,14 +3369,12 @@ Old attrs simply are forgotten. - Without argument (or with arrowstyle=None), it prints out - available box styles. + Without argument (or with arrowstyle=None), return + available box styles as a list of strings. """ if arrowstyle==None: - # print out available styles and return. - print "Following styles are available:" - print ArrowStyle.pprint_styles() + return ArrowStyle.pprint_styles() if isinstance(arrowstyle, ConnectionStyle._Base): self._arrow_transmuter = arrowstyle This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-12-09 03:49:15
|
Revision: 6530 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6530&view=rev Author: jdh2358 Date: 2008-12-09 03:49:11 +0000 (Tue, 09 Dec 2008) Log Message: ----------- added mdehoon's native macosx patch Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/mathtext.py trunk/matplotlib/lib/matplotlib/rcsetup.py trunk/matplotlib/matplotlibrc.template trunk/matplotlib/setup.cfg.template trunk/matplotlib/setup.py trunk/matplotlib/setupext.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-12-09 03:37:16 UTC (rev 6529) +++ trunk/matplotlib/CHANGELOG 2008-12-09 03:49:11 UTC (rev 6530) @@ -1,3 +1,5 @@ +2008-12-08 Added mdehoon's native maxosx backend from sf patch 2179017 + 2008-12-08 Removed the prints in the set_*style commands. Return the list of pprinted strings instead Modified: trunk/matplotlib/lib/matplotlib/mathtext.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mathtext.py 2008-12-09 03:37:16 UTC (rev 6529) +++ trunk/matplotlib/lib/matplotlib/mathtext.py 2008-12-09 03:49:11 UTC (rev 6530) @@ -2749,7 +2749,8 @@ 'ps' : MathtextBackendPs, 'pdf' : MathtextBackendPdf, 'svg' : MathtextBackendSvg, - 'cairo' : MathtextBackendCairo + 'cairo' : MathtextBackendCairo, + 'macosx': MathtextBackendAgg, } _font_type_mapping = { Modified: trunk/matplotlib/lib/matplotlib/rcsetup.py =================================================================== --- trunk/matplotlib/lib/matplotlib/rcsetup.py 2008-12-09 03:37:16 UTC (rev 6529) +++ trunk/matplotlib/lib/matplotlib/rcsetup.py 2008-12-09 03:49:11 UTC (rev 6530) @@ -23,8 +23,8 @@ # The capitalized forms are needed for ipython at present; this may # change for later versions. -interactive_bk = ['GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'QtAgg', 'Qt4Agg', - 'TkAgg', 'WX', 'WXAgg', 'CocoaAgg'] +interactive_bk = ['GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'MacOSX', + 'QtAgg', 'Qt4Agg', 'TkAgg', 'WX', 'WXAgg', 'CocoaAgg'] non_interactive_bk = ['agg', 'cairo', 'emf', 'gdk', Modified: trunk/matplotlib/matplotlibrc.template =================================================================== --- trunk/matplotlib/matplotlibrc.template 2008-12-09 03:37:16 UTC (rev 6529) +++ trunk/matplotlib/matplotlibrc.template 2008-12-09 03:49:11 UTC (rev 6530) @@ -24,9 +24,9 @@ #### CONFIGURATION BEGINS HERE # the default backend; one of GTK GTKAgg GTKCairo CocoaAgg FltkAgg -# QtAgg Qt4Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG Template You -# can also deploy your own backend outside of matplotlib by referring -# to the module name (which must be in the PYTHONPATH) as +# MacOSX QtAgg Qt4Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG Template +# You can also deploy your own backend outside of matplotlib by +# referring to the module name (which must be in the PYTHONPATH) as # 'module://my_backend' backend : %(backend)s Modified: trunk/matplotlib/setup.cfg.template =================================================================== --- trunk/matplotlib/setup.cfg.template 2008-12-09 03:37:16 UTC (rev 6529) +++ trunk/matplotlib/setup.cfg.template 2008-12-09 03:49:11 UTC (rev 6530) @@ -32,9 +32,9 @@ [gui_support] # Matplotlib supports multiple GUI toolkits, including Cocoa, -# GTK, Fltk, Qt, Qt4, Tk, and WX. Support for many of these -# toolkits requires AGG, the Anti-Grain Geometry library, which -# is provided by matplotlib and built by default. +# GTK, Fltk, MacOSX, Qt, Qt4, Tk, and WX. Support for many of +# these toolkits requires AGG, the Anti-Grain Geometry library, +# which is provided by matplotlib and built by default. # # Some backends are written in pure Python, and others require # extension code to be compiled. By default, matplotlib checks @@ -59,16 +59,17 @@ #gtkagg = False #tkagg = False #wxagg = False +#macosx = False [rc_options] # User-configurable options # -# Default backend, one of: Agg, Cairo, CocoaAgg, GTK, GTKAgg, -# GTKCairo, FltkAgg, Pdf, Ps, QtAgg, Qt4Agg, SVG, TkAgg, WX, WXAgg. +# Default backend, one of: Agg, Cairo, CocoaAgg, GTK, GTKAgg, GTKCairo, +# FltkAgg, MacOSX, Pdf, Ps, QtAgg, Qt4Agg, SVG, TkAgg, WX, WXAgg. # # The Agg, Ps, Pdf and SVG backends do not require external -# dependencies. Do not choose GTK, GTKAgg, GTKCairo, TkAgg or WXAgg if -# you have disabled the relevent extension modules. Agg will be used +# dependencies. Do not choose GTK, GTKAgg, GTKCairo, MacOSX, TkAgg or WXAgg +# if you have disabled the relevent extension modules. Agg will be used # by default. # #backend = Agg Modified: trunk/matplotlib/setup.py =================================================================== --- trunk/matplotlib/setup.py 2008-12-09 03:37:16 UTC (rev 6529) +++ trunk/matplotlib/setup.py 2008-12-09 03:49:11 UTC (rev 6530) @@ -26,15 +26,15 @@ import glob from distutils.core import setup from setupext import build_agg, build_gtkagg, build_tkagg, build_wxagg,\ - build_ft2font, build_image, build_windowing, build_path, \ + build_macosx, build_ft2font, build_image, build_windowing, build_path, \ build_contour, build_delaunay, build_nxutils, build_traits, build_gdk, \ build_ttconv, print_line, print_status, print_message, \ print_raw, check_for_freetype, check_for_libpng, check_for_gtk, \ - check_for_tk, check_for_wx, check_for_numpy, check_for_qt, check_for_qt4, \ - check_for_cairo, check_provide_traits, check_provide_pytz, \ - check_provide_dateutil, check_provide_configobj, check_for_dvipng, \ - check_for_ghostscript, check_for_latex, check_for_pdftops, \ - check_for_datetime, options, build_png + check_for_tk, check_for_wx, check_for_macosx, check_for_numpy, \ + check_for_qt, check_for_qt4, check_for_cairo, check_provide_traits, \ + check_provide_pytz, check_provide_dateutil, check_provide_configobj, \ + check_for_dvipng, check_for_ghostscript, check_for_latex, \ + check_for_pdftops, check_for_datetime, options, build_png #import distutils.sysconfig # jdh @@ -149,6 +149,11 @@ build_gtkagg(ext_modules, packages) rc['backend'] = 'GTKAgg' +if options['build_macosx']: + if check_for_macosx() or (options['build_macosx'] is True): + build_macosx(ext_modules, packages) + rc['backend'] = 'MacOSX' + # These are informational only. We don't build any extensions for them. check_for_qt() check_for_qt4() Modified: trunk/matplotlib/setupext.py =================================================================== --- trunk/matplotlib/setupext.py 2008-12-09 03:37:16 UTC (rev 6529) +++ trunk/matplotlib/setupext.py 2008-12-09 03:49:11 UTC (rev 6530) @@ -76,6 +76,7 @@ BUILT_TTCONV = False BUILT_GTKAGG = False BUILT_IMAGE = False +BUILT_MACOSX = False BUILT_TKAGG = False BUILT_WXAGG = False BUILT_WINDOWING = False @@ -105,6 +106,7 @@ 'build_gtkagg': 'auto', 'build_tkagg': 'auto', 'build_wxagg': 'auto', + 'build_macosx': 'auto', 'build_image': True, 'build_windowing': True, 'backend': None, @@ -867,6 +869,17 @@ print_message(explanation) return gotit +def check_for_macosx(): + gotit = False + import sys + if sys.platform=='darwin': + gotit = True + if gotit: + print_status("Mac OS X native", "yes") + else: + print_status("Mac OS X native", "no") + return gotit + def query_tcltk(): """Tries to open a Tk window in order to query the Tk object about its library paths. This should never be called more than once by the same process, as Tk intricacies @@ -1214,6 +1227,19 @@ ext_modules.append(module) BUILT_WXAGG = True + +def build_macosx(ext_modules, packages): + global BUILT_MACOSX + if BUILT_MACOSX: return # only build it if you you haven't already + module = Extension('matplotlib.backends._macosx', + ['src/_macosx.m'], + extra_link_args = ['-framework','Cocoa'], + ) + add_numpy_flags(module) + ext_modules.append(module) + BUILT_MACOSX = True + + def build_png(ext_modules, packages): global BUILT_PNG if BUILT_PNG: return # only build it if you you haven't already This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-12-09 03:51:40
|
Revision: 6531 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6531&view=rev Author: jdh2358 Date: 2008-12-09 03:51:35 +0000 (Tue, 09 Dec 2008) Log Message: ----------- added mdehoon's native macosx patch Modified Paths: -------------- trunk/matplotlib/CHANGELOG Added Paths: ----------- trunk/matplotlib/lib/matplotlib/backends/backend_macosx.py trunk/matplotlib/src/_macosx.m Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-12-09 03:49:11 UTC (rev 6530) +++ trunk/matplotlib/CHANGELOG 2008-12-09 03:51:35 UTC (rev 6531) @@ -1,4 +1,4 @@ -2008-12-08 Added mdehoon's native maxosx backend from sf patch 2179017 +2008-12-08 Added mdehoon's native macosx backend from sf patch 2179017 2008-12-08 Removed the prints in the set_*style commands. Return the list of pprinted strings instead Added: trunk/matplotlib/lib/matplotlib/backends/backend_macosx.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backends/backend_macosx.py (rev 0) +++ trunk/matplotlib/lib/matplotlib/backends/backend_macosx.py 2008-12-09 03:51:35 UTC (rev 6531) @@ -0,0 +1,415 @@ +from __future__ import division + +import os +import numpy + +from matplotlib._pylab_helpers import Gcf +from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\ + FigureManagerBase, FigureCanvasBase, NavigationToolbar2 +from matplotlib.cbook import maxdict +from matplotlib.figure import Figure +from matplotlib.path import Path +from matplotlib.mathtext import MathTextParser + + + +from matplotlib.widgets import SubplotTool + +import matplotlib +from matplotlib.backends import _macosx + +def show(): + """Show all the figures and enter the Cocoa mainloop. + This function will not return until all windows are closed or + the interpreter exits.""" + # Having a Python-level function "show" wrapping the built-in + # function "show" in the _macosx extension module allows us to + # to add attributes to "show". This is something ipython does. + _macosx.show() + +class RendererMac(RendererBase): + """ + The renderer handles drawing/rendering operations. Most of the renderer's + methods forwards the command to the renderer's graphics context. The + renderer does not wrap a C object and is written in pure Python. + """ + + texd = maxdict(50) # a cache of tex image rasters + + def __init__(self, dpi, width, height): + RendererBase.__init__(self) + self.dpi = dpi + self.width = width + self.height = height + self.gc = GraphicsContextMac() + self.mathtext_parser = MathTextParser('MacOSX') + + def set_width_height (self, width, height): + self.width, self.height = width, height + + def draw_path(self, gc, path, transform, rgbFace=None): + path = transform.transform_path(path) + for points, code in path.iter_segments(): + if code == Path.MOVETO: + gc.moveto(points) + elif code == Path.LINETO: + gc.lineto(points) + elif code == Path.CURVE3: + gc.curve3(points) + elif code == Path.CURVE4: + gc.curve4(points) + elif code == Path.CLOSEPOLY: + gc.closepoly() + if rgbFace is not None: + rgbFace = tuple(rgbFace) + gc.stroke(rgbFace) + + def new_gc(self): + self.gc.reset() + return self.gc + + def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None): + self.gc.set_clip_rectangle(bbox) + im.flipud_out() + nrows, ncols, data = im.as_rgba_str() + self.gc.draw_image(x, y, nrows, ncols, data) + im.flipud_out() + + def draw_tex(self, gc, x, y, s, prop, angle): + # todo, handle props, angle, origins + size = prop.get_size_in_points() + texmanager = self.get_texmanager() + key = s, size, self.dpi, angle, texmanager.get_font_config() + im = self.texd.get(key) # Not sure what this does; just copied from backend_agg.py + if im is None: + Z = texmanager.get_grey(s, size, self.dpi) + Z = numpy.array(255.0 - Z * 255.0, numpy.uint8) + + gc.draw_mathtext(x, y, angle, Z) + + def _draw_mathtext(self, gc, x, y, s, prop, angle): + size = prop.get_size_in_points() + ox, oy, width, height, descent, image, used_characters = \ + self.mathtext_parser.parse(s, self.dpi, prop) + gc.draw_mathtext(x, y, angle, 255 - image.as_array()) + + def draw_text(self, gc, x, y, s, prop, angle, ismath=False): + if ismath: + self._draw_mathtext(gc, x, y, s, prop, angle) + else: + family = prop.get_family() + size = prop.get_size_in_points() + weight = prop.get_weight() + style = prop.get_style() + gc.draw_text(x, y, unicode(s), family, size, weight, style, angle) + + def get_text_width_height_descent(self, s, prop, ismath): + if ismath=='TeX': + # TODO: handle props + size = prop.get_size_in_points() + texmanager = self.get_texmanager() + Z = texmanager.get_grey(s, size, self.dpi) + m,n = Z.shape + # TODO: handle descent; This is based on backend_agg.py + return n, m, 0 + if ismath: + ox, oy, width, height, descent, fonts, used_characters = \ + self.mathtext_parser.parse(s, self.dpi, prop) + return width, height, descent + family = prop.get_family() + size = prop.get_size_in_points() + weight = prop.get_weight() + style = prop.get_style() + return self.gc.get_text_width_height_descent(unicode(s), family, size, weight, style) + + def flipy(self): + return False + + def points_to_pixels(self, points): + return points/72.0 * self.dpi + + def option_image_nocomposite(self): + return True + +class GraphicsContextMac(_macosx.GraphicsContext, GraphicsContextBase): + """ + The GraphicsContext wraps a Quartz graphics context. All methods + are implemented at the C-level in macosx.GraphicsContext. These + methods set drawing properties such as the line style, fill color, + etc. The actual drawing is done by the Renderer, which draws into + the GraphicsContext. + """ + def __init__(self): + GraphicsContextBase.__init__(self) + _macosx.GraphicsContext.__init__(self) + + def set_clip_rectangle(self, box): + GraphicsContextBase.set_clip_rectangle(self, box) + if not box: return + _macosx.GraphicsContext.set_clip_rectangle(self, box.bounds) + + def set_clip_path(self, path): + GraphicsContextBase.set_clip_path(self, path) + if not path: return + path = path.get_fully_transformed_path() + for points, code in path.iter_segments(): + if code == Path.MOVETO: + self.moveto(points) + elif code == Path.LINETO: + self.lineto(points) + elif code == Path.CURVE3: + self.curve3(points) + elif code == Path.CURVE4: + self.curve4(points) + elif code == Path.CLOSEPOLY: + self.closepoly() + self.clip_path() + + +######################################################################## +# +# The following functions and classes are for pylab and implement +# window/figure managers, etc... +# +######################################################################## + +def draw_if_interactive(): + """ + For performance reasons, we don't want to redraw the figure after + each draw command. Instead, we mark the figure as invalid, so that + it will be redrawn as soon as the event loop resumes via PyOS_InputHook. + This function should be called after each draw event, even if + matplotlib is not running interactively. + """ + figManager = Gcf.get_active() + if figManager is not None: + figManager.canvas.invalidate() + +def new_figure_manager(num, *args, **kwargs): + """ + Create a new figure manager instance + """ + FigureClass = kwargs.pop('FigureClass', Figure) + figure = FigureClass(*args, **kwargs) + canvas = FigureCanvasMac(figure) + manager = FigureManagerMac(canvas, num) + return manager + +class FigureCanvasMac(_macosx.FigureCanvas, FigureCanvasBase): + """ + The canvas the figure renders into. Calls the draw and print fig + methods, creates the renderers, etc... + + Public attribute + + figure - A Figure instance + + Events such as button presses, mouse movements, and key presses + are handled in the C code and the base class methods + button_press_event, button_release_event, motion_notify_event, + key_press_event, and key_release_event are called from there. + """ + + def __init__(self, figure): + FigureCanvasBase.__init__(self, figure) + width, height = self.get_width_height() + self.renderer = RendererMac(figure.dpi, width, height) + _macosx.FigureCanvas.__init__(self, width, height) + + def resize(self, width, height): + self.renderer.set_width_height(width, height) + dpi = self.figure.dpi + width /= dpi + height /= dpi + self.figure.set_size_inches(width, height) + + def print_figure(self, filename, dpi=None, facecolor='w', edgecolor='w', + orientation='portrait', **kwargs): + if dpi is None: dpi = matplotlib.rcParams['savefig.dpi'] + filename = unicode(filename) + root, ext = os.path.splitext(filename) + ext = ext[1:].lower() + if not ext: + ext = "png" + filename = root + "." + ext + if ext=="jpg": ext = "jpeg" + + # save the figure settings + origfacecolor = self.figure.get_facecolor() + origedgecolor = self.figure.get_edgecolor() + + # set the new parameters + self.figure.set_facecolor(facecolor) + self.figure.set_edgecolor(edgecolor) + + if ext in ('jpeg', 'png', 'tiff', 'gif', 'bmp'): + width, height = self.figure.get_size_inches() + width, height = width*dpi, height*dpi + self.write_bitmap(filename, width, height) + elif ext == 'pdf': + self.write_pdf(filename) + elif ext in ('ps', 'eps'): + from backend_ps import FigureCanvasPS + # Postscript backend changes figure.dpi, but doesn't change it back + origDPI = self.figure.dpi + fc = self.switch_backends(FigureCanvasPS) + fc.print_figure(filename, dpi, facecolor, edgecolor, + orientation, **kwargs) + self.figure.dpi = origDPI + self.figure.set_canvas(self) + elif ext=='svg': + from backend_svg import FigureCanvasSVG + fc = self.switch_backends(FigureCanvasSVG) + fc.print_figure(filename, dpi, facecolor, edgecolor, + orientation, **kwargs) + self.figure.set_canvas(self) + else: + raise ValueError("Figure format not available (extension %s)" % ext) + + # restore original figure settings + self.figure.set_facecolor(origfacecolor) + self.figure.set_edgecolor(origedgecolor) + + + +class FigureManagerMac(_macosx.FigureManager, FigureManagerBase): + """ + Wrap everything up into a window for the pylab interface + """ + def __init__(self, canvas, num): + FigureManagerBase.__init__(self, canvas, num) + title = "Figure %d" % num + _macosx.FigureManager.__init__(self, canvas, title) + if matplotlib.rcParams['toolbar']=='classic': + self.toolbar = NavigationToolbarMac(canvas) + elif matplotlib.rcParams['toolbar']=='toolbar2': + self.toolbar = NavigationToolbar2Mac(canvas) + else: + self.toolbar = None + if self.toolbar is not None: + self.toolbar.update() + + def notify_axes_change(fig): + 'this will be called whenever the current axes is changed' + if self.toolbar != None: self.toolbar.update() + self.canvas.figure.add_axobserver(notify_axes_change) + + # This is ugly, but this is what tkagg and gtk are doing. + # It is needed to get ginput() working. + self.canvas.figure.show = lambda *args: self.show() + + def show(self): + self.canvas.draw() + + def close(self): + Gcf.destroy(self.num) + +class NavigationToolbarMac(_macosx.NavigationToolbar): + + def __init__(self, canvas): + self.canvas = canvas + basedir = os.path.join(matplotlib.rcParams['datapath'], "images") + images = {} + for imagename in ("stock_left", + "stock_right", + "stock_up", + "stock_down", + "stock_zoom-in", + "stock_zoom-out", + "stock_save_as"): + filename = os.path.join(basedir, imagename+".ppm") + images[imagename] = self._read_ppm_image(filename) + _macosx.NavigationToolbar.__init__(self, images) + self.message = None + + def _read_ppm_image(self, filename): + data = "" + imagefile = open(filename) + for line in imagefile: + if "#" in line: + i = line.index("#") + line = line[:i] + "\n" + data += line + imagefile.close() + magic, width, height, maxcolor, imagedata = data.split(None, 4) + width, height = int(width), int(height) + assert magic=="P6" + assert len(imagedata)==width*height*3 # 3 colors in RGB + return (width, height, imagedata) + + def panx(self, direction): + axes = self.canvas.figure.axes + selected = self.get_active() + for i in selected: + axes[i].xaxis.pan(direction) + self.canvas.invalidate() + + def pany(self, direction): + axes = self.canvas.figure.axes + selected = self.get_active() + for i in selected: + axes[i].yaxis.pan(direction) + self.canvas.invalidate() + + def zoomx(self, direction): + axes = self.canvas.figure.axes + selected = self.get_active() + for i in selected: + axes[i].xaxis.zoom(direction) + self.canvas.invalidate() + + def zoomy(self, direction): + axes = self.canvas.figure.axes + selected = self.get_active() + for i in selected: + axes[i].yaxis.zoom(direction) + self.canvas.invalidate() + + def save_figure(self): + filename = _macosx.choose_save_file('Save the figure') + if filename is None: # Cancel + return + self.canvas.print_figure(filename) + +class NavigationToolbar2Mac(_macosx.NavigationToolbar2, NavigationToolbar2): + + def __init__(self, canvas): + NavigationToolbar2.__init__(self, canvas) + + def _init_toolbar(self): + basedir = os.path.join(matplotlib.rcParams['datapath'], "images") + _macosx.NavigationToolbar2.__init__(self, basedir) + + def draw_rubberband(self, event, x0, y0, x1, y1): + self.canvas.set_rubberband(x0, y0, x1, y1) + + def release(self, event): + self.canvas.remove_rubberband() + + def set_cursor(self, cursor): + _macosx.set_cursor(cursor) + + def save_figure(self): + filename = _macosx.choose_save_file('Save the figure') + if filename is None: # Cancel + return + self.canvas.print_figure(filename) + + def prepare_configure_subplots(self): + toolfig = Figure(figsize=(6,3)) + canvas = FigureCanvasMac(toolfig) + toolfig.subplots_adjust(top=0.9) + tool = SubplotTool(self.canvas.figure, toolfig) + return canvas + + def set_message(self, message): + _macosx.NavigationToolbar2.set_message(self, message.encode('utf-8')) + +######################################################################## +# +# Now just provide the standard names that backend.__init__ is expecting +# +######################################################################## + + +FigureManager = FigureManagerMac Added: trunk/matplotlib/src/_macosx.m =================================================================== --- trunk/matplotlib/src/_macosx.m (rev 0) +++ trunk/matplotlib/src/_macosx.m 2008-12-09 03:51:35 UTC (rev 6531) @@ -0,0 +1,3773 @@ +#include <Cocoa/Cocoa.h> +#include <ApplicationServices/ApplicationServices.h> +#include <sys/socket.h> +#include <Python.h> +#include "numpy/arrayobject.h" + +static int nwin = 0; + + +/* Varius NSApplicationDefined event subtypes */ +#define STDIN_READY 0 +#define SIGINT_CALLED 1 +#define STOP_EVENT_LOOP 2 +#define WINDOW_CLOSING 3 + +/* -------------------------- Helper function ---------------------------- */ + +static void stdin_ready(CFReadStreamRef readStream, CFStreamEventType eventType, void* context) +{ + NSEvent* event = [NSEvent otherEventWithType: NSApplicationDefined + location: NSZeroPoint + modifierFlags: 0 + timestamp: 0.0 + windowNumber: 0 + context: nil + subtype: STDIN_READY + data1: 0 + data2: 0]; + [NSApp postEvent: event atStart: true]; +} + +static int sigint_fd = -1; + +static void _sigint_handler(int sig) +{ + const char c = 'i'; + write(sigint_fd, &c, 1); +} + +static void _callback(CFSocketRef s, + CFSocketCallBackType type, + CFDataRef address, + const void * data, + void *info) +{ + char c; + CFSocketNativeHandle handle = CFSocketGetNative(s); + read(handle, &c, 1); + NSEvent* event = [NSEvent otherEventWithType: NSApplicationDefined + location: NSZeroPoint + modifierFlags: 0 + timestamp: 0.0 + windowNumber: 0 + context: nil + subtype: SIGINT_CALLED + data1: 0 + data2: 0]; + [NSApp postEvent: event atStart: true]; +} + +static int wait_for_stdin(void) +{ + const UInt8 buffer[] = "/dev/fd/0"; + const CFIndex n = (CFIndex)strlen((char*)buffer); + CFRunLoopRef runloop = CFRunLoopGetCurrent(); + CFURLRef url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, + buffer, + n, + false); + CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, + url); + CFRelease(url); + + CFReadStreamOpen(stream); + if (!CFReadStreamHasBytesAvailable(stream)) + /* This is possible because of how PyOS_InputHook is called from Python */ + { + int error; + int interrupted = 0; + int channel[2]; + CFSocketRef sigint_socket = NULL; + PyOS_sighandler_t py_sigint_handler = NULL; + CFStreamClientContext clientContext = {0, NULL, NULL, NULL, NULL}; + CFReadStreamSetClient(stream, + kCFStreamEventHasBytesAvailable, + stdin_ready, + &clientContext); + CFReadStreamScheduleWithRunLoop(stream, runloop, kCFRunLoopCommonModes); + error = pipe(channel); + if (error==0) + { + fcntl(channel[1], F_SETFL, O_WRONLY | O_NONBLOCK); + + sigint_socket = CFSocketCreateWithNative(kCFAllocatorDefault, + channel[0], + kCFSocketReadCallBack, + _callback, + NULL); + if (sigint_socket) + { + CFRunLoopSourceRef source; + source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, + sigint_socket, + 0); + CFRelease(sigint_socket); + if (source) + { + CFRunLoopAddSource(runloop, source, kCFRunLoopDefaultMode); + CFRelease(source); + sigint_fd = channel[1]; + py_sigint_handler = PyOS_setsig(SIGINT, _sigint_handler); + } + } + else + close(channel[0]); + } + + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + NSDate* date = [NSDate distantFuture]; + while (true) + { NSEvent* event = [NSApp nextEventMatchingMask: NSAnyEventMask + untilDate: date + inMode: NSDefaultRunLoopMode + dequeue: YES]; + if (!event) break; /* No windows open */ + if ([event type]==NSApplicationDefined) + { short subtype = [event subtype]; + if (subtype==STDIN_READY) break; + if (subtype==SIGINT_CALLED) + { interrupted = true; + break; + } + } + [NSApp sendEvent: event]; + } + [pool release]; + + if (py_sigint_handler) PyOS_setsig(SIGINT, py_sigint_handler); + CFReadStreamUnscheduleFromRunLoop(stream, + runloop, + kCFRunLoopCommonModes); + if (sigint_socket) CFSocketInvalidate(sigint_socket); + if (error==0) close(channel[1]); + if (interrupted) raise(SIGINT); + } + CFReadStreamClose(stream); + return 1; +} + +static char show__doc__[] = "Show all the figures and enter the main loop.\nThis function does not return until all Matplotlib windows are closed,\nand is normally not needed in interactive sessions."; + +/* ---------------------------- Cocoa classes ---------------------------- */ + + +@interface Window : NSWindow +{ PyObject* manager; +} +- (Window*)initWithContentRect:(NSRect)rect styleMask:(unsigned int)mask backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation withManager: (PyObject*)theManager; +- (BOOL)closeButtonPressed; +- (void)close; +- (void)dealloc; +@end + +@interface ToolWindow : NSWindow +{ +} +- (ToolWindow*)initWithContentRect:(NSRect)rect master:(NSWindow*)window; +- (void)masterCloses:(NSNotification*)notification; +- (void)close; +@end + +@interface View : NSView +{ PyObject* canvas; + NSRect rubberband; +} +- (void)dealloc; +- (void)drawRect:(NSRect)rect; +- (void)windowDidResize:(NSNotification*)notification; +- (View*)initWithFrame:(NSRect)rect canvas:(PyObject*)fc; +- (BOOL)windowShouldClose:(NSNotification*)notification; +- (BOOL)isFlipped; +- (void)mouseDown:(NSEvent*)event; +- (void)mouseUp:(NSEvent*)event; +- (void)mouseDragged:(NSEvent*)event; +- (void)mouseMoved:(NSEvent*)event; +- (void)setRubberband:(NSRect)rect; +- (void)removeRubberband; +- (const char*)convertKeyEvent:(NSEvent*)event; +- (void)keyDown:(NSEvent*)event; +- (void)keyUp:(NSEvent*)event; +- (void)scrollWheel:(NSEvent *)event; +- (void)flagsChanged:(NSEvent*)event; +@end + +@interface ScrollableButton : NSButton +{ + SEL scrollWheelUpAction; + SEL scrollWheelDownAction; +} +- (void)setScrollWheelUpAction:(SEL)action; +- (void)setScrollWheelDownAction:(SEL)action; +- (void)scrollWheel:(NSEvent *)event; +@end + +@interface MenuItem: NSMenuItem +{ int index; +} ++ (MenuItem*)menuItemWithTitle:(NSString*)title; ++ (MenuItem*)menuItemSelectAll; ++ (MenuItem*)menuItemInvertAll; ++ (MenuItem*)menuItemForAxis:(int)i; +- (void)toggle:(id)sender; +- (void)selectAll:(id)sender; +- (void)invertAll:(id)sender; +- (int)index; +@end + +/* ---------------------------- Python classes ---------------------------- */ + +typedef struct { + PyObject_HEAD + CGContextRef cr; + PyObject* converter; /* Convert color specifications to r,g,b triples */ + CGPatternRef pattern; /* For drawing hatches */ + ATSUStyle style; /* For drawing Unicode strings with ATSUI */ + ATSUTextLayout layout; /* For drawing Unicode strings with ATSUI */ +} GraphicsContext; + +static PyObject* +GraphicsContext_new(PyTypeObject* type, PyObject *args, PyObject *kwds) +{ + OSStatus status; + + GraphicsContext* self = (GraphicsContext*)type->tp_alloc(type, 0); + if (!self) return NULL; + self->cr = NULL; + PyObject* module = PyImport_AddModule("matplotlib.colors"); + if (!module) return NULL; + PyObject* dict = PyObject_GetAttrString(module, "__dict__"); + if (!dict) return NULL; + PyObject* colorConverter = PyDict_GetItemString(dict, "colorConverter"); + Py_DECREF(dict); + if (!colorConverter) + { + PyErr_SetString(PyExc_KeyError, + "failed to find colorConverter in matplotlib.colors"); + return NULL; + } + self->converter = PyObject_GetAttrString(colorConverter, "to_rgb"); + if (!self->converter) return NULL; + + self->pattern = NULL; + + status = ATSUCreateStyle(&self->style); + if (status!=noErr) + { + Py_DECREF(self->converter); + PyErr_SetString(PyExc_RuntimeError, "ATSUCreateStyle failed"); + return NULL; + } + + status = ATSUCreateTextLayout(&self->layout); + if (status!=noErr) + { + Py_DECREF(self->converter); + status = ATSUDisposeStyle(self->style); + if (status!=noErr) + PyErr_WarnEx(PyExc_RuntimeWarning, "ATSUDisposeStyle failed", 1); + PyErr_SetString(PyExc_RuntimeError, "ATSUCreateTextLayout failed"); + return NULL; + } + + return (PyObject*) self; +} + +static void +GraphicsContext_dealloc(GraphicsContext *self) +{ + Py_DECREF(self->converter); + + if (self->pattern) CGPatternRelease(self->pattern); + + OSStatus status; + + status = ATSUDisposeStyle(self->style); + if (status!=noErr) + PyErr_WarnEx(PyExc_RuntimeWarning, "ATSUDisposeStyle failed", 1); + + status = ATSUDisposeTextLayout(self->layout); + if (status!=noErr) + PyErr_WarnEx(PyExc_RuntimeWarning, "ATSUDisposeTextLayout failed", 1); + + self->ob_type->tp_free((PyObject*)self); +} + +static PyObject* +GraphicsContext_repr(GraphicsContext* self) +{ + return PyString_FromFormat("GraphicsContext object %p wrapping the Quartz 2D graphics context %p", self, self->cr); +} + +static PyObject* +GraphicsContext_reset (GraphicsContext* self) +{ + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + CGContextRestoreGState(cr); + CGContextSaveGState(cr); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_set_alpha (GraphicsContext* self, PyObject* args) +{ + float alpha; + if (!PyArg_ParseTuple(args, "f", &alpha)) return NULL; + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + CGContextSetAlpha(cr, alpha); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_set_antialiased (GraphicsContext* self, PyObject* args) +{ + int shouldAntialias; + if (!PyArg_ParseTuple(args, "i", &shouldAntialias)) return NULL; + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + CGContextSetShouldAntialias(cr, shouldAntialias); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_set_capstyle (GraphicsContext* self, PyObject* args) +{ + char* string; + CGLineCap cap; + + if (!PyArg_ParseTuple(args, "s", &string)) return NULL; + + if (!strcmp(string, "butt")) cap = kCGLineCapButt; + else if (!strcmp(string, "round")) cap = kCGLineCapRound; + else if (!strcmp(string, "projecting")) cap = kCGLineCapSquare; + else + { + PyErr_SetString(PyExc_ValueError, + "capstyle should be 'butt', 'round', or 'projecting'"); + return NULL; + } + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + CGContextSetLineCap(cr, cap); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_set_clip_rectangle (GraphicsContext* self, PyObject* args) +{ + CGRect rect; + float x, y, width, height; + if (!PyArg_ParseTuple(args, "(ffff)", &x, &y, &width, &height)) return NULL; + + rect.origin.x = x; + rect.origin.y = y; + rect.size.width = width; + rect.size.height = height; + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + CGContextClipToRect(cr, rect); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_clip_path (GraphicsContext* self) +{ + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + CGContextRestoreGState(cr); + CGContextSaveGState(cr); + CGContextClip(cr); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_set_dashes (GraphicsContext* self, PyObject* args) +{ + float phase = 0.0; + PyObject* offset; + PyObject* dashes; + + if (!PyArg_ParseTuple(args, "OO", &offset, &dashes)) return NULL; + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + if (offset!=Py_None) + { + if (PyFloat_Check(offset)) phase = PyFloat_AsDouble(offset); + else if (PyInt_Check(offset)) phase = PyInt_AsLong(offset); + else + { + PyErr_SetString(PyExc_TypeError, + "offset should be a floating point value"); + return NULL; + } + } + + if (dashes!=Py_None) + { + if (PyList_Check(dashes)) dashes = PyList_AsTuple(dashes); + else if (PyTuple_Check(dashes)) Py_INCREF(dashes); + else + { + PyErr_SetString(PyExc_TypeError, + "dashes should be a tuple or a list"); + return NULL; + } + int n = PyTuple_GET_SIZE(dashes); + int i; + float* lengths = malloc(n*sizeof(float)); + if(!lengths) + { + PyErr_SetString(PyExc_MemoryError, "Failed to store dashes"); + Py_DECREF(dashes); + return NULL; + } + for (i = 0; i < n; i++) + { + PyObject* value = PyTuple_GET_ITEM(dashes, i); + if (PyFloat_Check(value)) + lengths[i] = (float) PyFloat_AS_DOUBLE(value); + else if (PyInt_Check(value)) + lengths[i] = (float) PyInt_AS_LONG(value); + else break; + } + Py_DECREF(dashes); + if (i < n) /* break encountered */ + { + free(lengths); + PyErr_SetString(PyExc_TypeError, "Failed to read dashes"); + return NULL; + } + CGContextSetLineDash(cr, phase, lengths, n); + free(lengths); + } + else + CGContextSetLineDash(cr, phase, NULL, 0); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_set_foreground(GraphicsContext* self, PyObject* args, PyObject* keywords) +{ float r, g, b; + PyObject* fg; + int isRGB = 0; + static char* kwlist[] = {"fg", "isRGB", NULL}; + if(!PyArg_ParseTupleAndKeywords(args, keywords, "O|i", kwlist, + &fg, &isRGB)) return NULL; + if (isRGB) + { + if(!PyArg_ParseTuple(fg, "fff", &r, &g, &b)) return NULL; + } + else + { fg = PyObject_CallFunctionObjArgs(self->converter, fg, NULL); + if(!fg) return NULL; + if(!PyArg_ParseTuple(fg, "fff", &r, &g, &b)) return NULL; + Py_DECREF(fg); + } + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + CGContextSetRGBStrokeColor(cr, r, g, b, 1.0); + CGContextSetRGBFillColor(cr, r, g, b, 1.0); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_set_graylevel(GraphicsContext* self, PyObject* args) +{ float gray; + if(!PyArg_ParseTuple(args, "f", &gray)) return NULL; + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + CGContextSetGrayStrokeColor(cr, gray, 1.0); + CGContextSetGrayFillColor(cr, gray, 1.0); + Py_INCREF(Py_None); + return Py_None; +} + +static void drawHatch (void *info, CGContextRef cr) +{ + int i; + + PyObject* string = (PyObject*)info; + char* hatches = PyString_AS_STRING(string); + + int frequency[4] = {0, 0, 0, 0}; + float position, distance; + + const float size = 12.0; + const int n = strlen(hatches); + + for (i = 0; i < n; i++) + { + switch(hatches[i]) + { + case '/': frequency[3]++; break; + case '\\': frequency[2]++; break; + case '|': frequency[1]++; break; + case '-': frequency[0]++; break; + case '+': frequency[0]++; frequency[1]++; break; + case 'x': frequency[2]++; frequency[3]++; break; + } + } + + distance = size / frequency[0]; + position = distance / 2.0; + for (i = 0; i < frequency[0]; i++, position += distance) + { + CGContextMoveToPoint(cr, 0.0, position); + CGContextAddLineToPoint(cr, size, position); + } + distance = size / frequency[1]; + position = distance / 2.0; + for (i = 0; i < frequency[1]; i++, position += distance) + { + CGContextMoveToPoint(cr, position, 0.0); + CGContextAddLineToPoint(cr, position, size); + } + distance = size / frequency[2]; + position = distance / 2.0; + for (i = 0; i < frequency[2]; i++, position += distance) + { + CGContextMoveToPoint(cr, position, 0.0); + CGContextAddLineToPoint(cr, 0.0, position); + CGContextMoveToPoint(cr, position, size); + CGContextAddLineToPoint(cr, size, position); + } + distance = size / frequency[3]; + position = distance / 2.0; + for (i = 0; i < frequency[3]; i++, position += distance) + { + CGContextMoveToPoint(cr, position, 0.0); + CGContextAddLineToPoint(cr, size, size-position); + CGContextMoveToPoint(cr, position, size); + CGContextAddLineToPoint(cr, 0.0, size-position); + } + CGContextSetLineWidth(cr, 2.0); + CGContextSetLineCap(cr, kCGLineCapSquare); + CGContextStrokePath(cr); + + Py_DECREF(string); +} + +static PyObject* +GraphicsContext_set_hatch(GraphicsContext* self, PyObject* args) +{ PyObject* hatches; + + const float size = 12.0; + static const CGPatternCallbacks callbacks = {0, &drawHatch, NULL}; + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + if(!PyArg_ParseTuple(args, "O", &hatches)) return NULL; + if(!PyString_Check(hatches)) return NULL; + + Py_INCREF(hatches); + + CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB(); + CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(baseSpace); + CGColorSpaceRelease(baseSpace); + CGContextSetFillColorSpace(cr, patternSpace); + CGColorSpaceRelease(patternSpace); + + self->pattern = CGPatternCreate((void*)hatches, + CGRectMake(0, 0, size, size), + CGAffineTransformIdentity, size, size, + kCGPatternTilingNoDistortion, + false, + &callbacks); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_set_linewidth (GraphicsContext* self, PyObject* args) +{ + float width; + if (!PyArg_ParseTuple(args, "f", &width)) return NULL; + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + CGContextSetLineWidth(cr, width); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_set_joinstyle(GraphicsContext* self, PyObject* args) +{ char* string; + CGLineJoin join; + + if (!PyArg_ParseTuple(args, "s", &string)) return NULL; + + if (!strcmp(string, "miter")) join = kCGLineJoinMiter; + else if (!strcmp(string, "round")) join = kCGLineJoinRound; + else if (!strcmp(string, "bevel")) join = kCGLineJoinBevel; + else + { + PyErr_SetString(PyExc_ValueError, + "joinstyle should be 'miter', 'round', or 'bevel'"); + return NULL; + } + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + CGContextSetLineJoin(cr, join); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_moveto(GraphicsContext* self, PyObject* args) +{ + float x; + float y; + + if(!PyArg_ParseTuple(args, "(ff)", &x, &y)) return NULL; + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + CGContextMoveToPoint(cr, x, y); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_lineto(GraphicsContext* self, PyObject* args) +{ + float x; + float y; + + if(!PyArg_ParseTuple(args, "(ff)", &x, &y)) return NULL; + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + CGContextAddLineToPoint(cr, x, y); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_curve3(GraphicsContext* self, PyObject* args) +{ + float cpx; + float cpy; + float x; + float y; + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + if(!PyArg_ParseTuple(args, "(ffff)", &cpx, + &cpy, + &x, + &y)) return NULL; + + CGContextAddQuadCurveToPoint(cr, cpx, cpy, x, y); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_curve4 (GraphicsContext* self, PyObject* args) +{ + float cp1x; + float cp1y; + float cp2x; + float cp2y; + float x; + float y; + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + if(!PyArg_ParseTuple(args, "(ffffff)", &cp1x, + &cp1y, + &cp2x, + &cp2y, + &x, + &y)) return NULL; + + CGContextAddCurveToPoint(cr, cp1x, cp1y, cp2x, cp2y, x, y); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_closepoly (GraphicsContext* self) +{ + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + CGContextClosePath(cr); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_stroke (GraphicsContext* self, PyObject* args) +{ + PyObject* color; + CGContextRef cr = self->cr; + + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + if(!PyArg_ParseTuple(args, "O", &color)) return NULL; + + if(color!=Py_None) + { + float r, g, b; + if(!PyArg_ParseTuple(color, "fff", &r, &g, &b)) return NULL; + if(self->pattern) + { + float components[4]; + components[0] = r; + components[1] = g; + components[2] = b; + components[3] = 1.0; + CGContextSetFillPattern(cr, self->pattern, components); + CGPatternRelease (self->pattern); + self->pattern = nil; + } + else CGContextSetRGBFillColor(cr, r, g, b, 1.0); + CGContextDrawPath(cr, kCGPathFillStroke); + } + else CGContextStrokePath(cr); + + Py_INCREF(Py_None); + return Py_None; +} + +static ATSFontRef +setfont(CGContextRef cr, PyObject* family, float size, const char weight[], + const char style[]) +{ +#define NMAP 40 +#define NFONT 31 + int i, j, n; + const char* temp; + const char* name = "Times-Roman"; + CFStringRef string; + ATSFontRef atsfont = 0; + + const int k = (strcmp(style, "italic") ? 0 : 2) + + (strcmp(weight, "bold") ? 0 : 1); + + struct {char* name; int index;} map[NMAP] = { + {"New Century Schoolbook", 0}, + {"Century Schoolbook L", 0}, + {"Utopia", 1}, + {"ITC Bookman", 2}, + {"Bookman", 2}, + {"Bitstream Vera Serif", 3}, + {"Nimbus Roman No9 L", 4}, + {"Times New Roman", 5}, + {"Times", 6}, + {"Palatino", 7}, + {"Charter", 8}, + {"serif", 0}, + {"Lucida Grande", 9}, + {"Verdana", 10}, + {"Geneva", 11}, + {"Lucida", 12}, + {"Bitstream Vera Sans", 13}, + {"Arial", 14}, + {"Helvetica", 15}, + {"Avant Garde", 16}, + {"sans-serif", 10}, + {"Apple Chancery", 17}, + {"Textile", 18}, + {"Zapf Chancery", 19}, + {"Sand", 20}, + {"cursive", 17}, + {"Comic Sans MS", 21}, + {"Chicago", 22}, + {"Charcoal", 23}, + {"Impact", 24}, + {"Western", 25}, + {"fantasy", 21}, + {"Andale Mono", 26}, + {"Bitstream Vera Sans Mono", 27}, + {"Nimbus Mono L", 28}, + {"Courier", 29}, + {"Courier New", 30}, + {"Fixed", 30}, + {"Terminal", 30}, + {"monospace", 30}, + }; + + const char* psnames[NFONT][4] = { + {"CenturySchoolbook", /* 0 */ + "CenturySchoolbook-Bold", + "CenturySchoolbook-Italic", + "CenturySchoolbook-BoldItalic"}, + {"Utopia", /* 1 */ + "Utopia-Bold", + "Utopia-Italic", + "Utopia-BoldItalic"}, + {"Bookman-Light", /* 2 */ + "Bookman-Bold", + "Bookman-LightItalic", + "Bookman-BoldItalic"}, + {"BitstreamVeraSerif-Roman", /* 3 */ + "BitstreamVeraSerif-Bold", + "", + ""}, + {"NimbusRomNo9L-Reg", /* 4 */ + "NimbusRomNo9T-Bol", + "NimbusRomNo9L-RegIta", + "NimbusRomNo9T-BolIta"}, + {"TimesNewRomanPSMT", /* 5 */ + "TimesNewRomanPS-BoldMT", + "TimesNewRomanPS-ItalicMT", + "TimesNewRomanPS-BoldItalicMT"}, + {"Times-Roman", /* 6 */ + "Times-Bold", + "Times-Italic", + "Times-BoldItalic"}, + {"Palatino-Roman", /* 7 */ + "Palatino-Bold", + "Palatino-Italic", + "Palatino-BoldItalic"}, + {"CharterBT-Roman", /* 8 */ + "CharterBT-Bold", + "CharterBT-Italic", + "CharterBT-BoldItalic"}, + {"LucidaGrande", /* 9 */ + "LucidaGrande-Bold", + "", + ""}, + {"Verdana", /* 10 */ + "Verdana-Bold", + "Verdana-Italic", + "Verdana-BoldItalic"}, + {"Geneva", /* 11 */ + "", + "", + ""}, + {"LucidaSans", /* 12 */ + "LucidaSans-Demi", + "LucidaSans-Italic", + "LucidaSans-DemiItalic"}, + {"BitstreamVeraSans-Roman", /* 13 */ + "BitstreamVeraSans-Bold", + "BitstreamVeraSans-Oblique", + "BitstreamVeraSans-BoldOblique"}, + {"ArialMT", /* 14 */ + "Arial-BoldMT", + "Arial-ItalicMT", + "Arial-BoldItalicMT"}, + {"Helvetica", /* 15 */ + "Helvetica-Bold", + "", + ""}, + {"AvantGardeITC-Book", /* 16 */ + "AvantGardeITC-Demi", + "AvantGardeITC-BookOblique", + "AvantGardeITC-DemiOblique"}, + {"Apple-Chancery", /* 17 */ + "", + "", + ""}, + {"TextileRegular", /* 18 */ + "", + "", + ""}, + {"ZapfChancery-Roman", /* 19 */ + "ZapfChancery-Bold", + "ZapfChancery-Italic", + "ZapfChancery-MediumItalic"}, + {"SandRegular", /* 20 */ + "", + "", + ""}, + {"ComicSansMS", /* 21 */ + "ComicSansMS-Bold", + "", + ""}, + {"Chicago", /* 22 */ + "", + "", + ""}, + {"Charcoal", /* 23 */ + "", + "", + ""}, + {"Impact", /* 24 */ + "", + "", + ""}, + {"Playbill", /* 25 */ + "", + "", + ""}, + {"AndaleMono", /* 26 */ + "", + "", + ""}, + {"BitstreamVeraSansMono-Roman", /* 27 */ + "BitstreamVeraSansMono-Bold", + "BitstreamVeraSansMono-Oblique", + "BitstreamVeraSansMono-BoldOb"}, + {"NimbusMonL-Reg", /* 28 */ + "NimbusMonL-Bol", + "NimbusMonL-RegObl", + "NimbusMonL-BolObl"}, + {"Courier", /* 29 */ + "Courier-Bold", + "", + ""}, + {"CourierNewPS", /* 30 */ + "CourierNewPS-BoldMT", + "CourierNewPS-ItalicMT", + "CourierNewPS-Bold-ItalicMT"}, + }; + + if(!PyList_Check(family)) return 0; + n = PyList_GET_SIZE(family); + + for (i = 0; i < n; i++) + { + PyObject* item = PyList_GET_ITEM(family, i); + if(!PyString_Check(item)) return 0; + temp = PyString_AS_STRING(item); + for (j = 0; j < NMAP; j++) + { if (!strcmp(map[j].name, temp)) + { temp = psnames[map[j].index][k]; + break; + } + } + /* If the font name is not found in mapping, we assume */ + /* that the user specified the Postscript name directly */ + + /* Check if this font can be found on the system */ + string = CFStringCreateWithCString(kCFAllocatorDefault, + temp, + kCFStringEncodingMacRoman); + atsfont = ATSFontFindFromPostScriptName(string, kATSOptionFlagsDefault); + CFRelease(string); + + if(atsfont) + { + name = temp; + break; + } + } + if(!atsfont) + { string = CFStringCreateWithCString(kCFAllocatorDefault, + name, + kCFStringEncodingMacRoman); + atsfont = ATSFontFindFromPostScriptName(string, kATSOptionFlagsDefault); + CFRelease(string); + } + CGContextSelectFont(cr, name, size, kCGEncodingMacRoman); + return atsfont; +} + +static PyObject* +GraphicsContext_draw_text (GraphicsContext* self, PyObject* args) +{ + float x; + float y; + const UniChar* text; + int n; + PyObject* family; + float size; + const char* weight; + const char* style; + float angle; + ATSFontRef atsfont; + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + if(!PyArg_ParseTuple(args, "ffu#Ofssf", + &x, + &y, + &text, + &n, + &family, + &size, + &weight, + &style, + &angle)) return NULL; + + atsfont = setfont(cr, family, size, weight, style); + + OSStatus status; + + ATSUAttributeTag tags[] = {kATSUFontTag, kATSUSizeTag, kATSUQDBoldfaceTag}; + ByteCount sizes[] = {sizeof(ATSUFontID), sizeof(Fixed), sizeof(Boolean)}; + Fixed atsuSize = Long2Fix(size); + Boolean isBold = FALSE; /* setfont takes care of this */ + + ATSUAttributeValuePtr values[] = {&atsfont, &atsuSize, &isBold}; + status = ATSUSetAttributes(self->style, 3, tags, sizes, values); + if (status!=noErr) + { + PyErr_SetString(PyExc_RuntimeError, "ATSUSetAttributes failed"); + return NULL; + } + + status = ATSUSetTextPointerLocation(self->layout, + text, + kATSUFromTextBeginning, // offset from beginning + kATSUToTextEnd, // length of text range + n); // length of text buffer + if (status!=noErr) + { + PyErr_SetString(PyExc_RuntimeError, + "ATSUCreateTextLayoutWithTextPtr failed"); + return NULL; + } + + status = ATSUSetRunStyle(self->layout, + self->style, + kATSUFromTextBeginning, + kATSUToTextEnd); + if (status!=noErr) + { + PyErr_SetString(PyExc_RuntimeError, "ATSUSetRunStyle failed"); + return NULL; + } + + Fixed atsuAngle = X2Fix(angle); + ATSUAttributeTag tags2[] = {kATSUCGContextTag, kATSULineRotationTag}; + ByteCount sizes2[] = {sizeof (CGContextRef), sizeof(Fixed)}; + ATSUAttributeValuePtr values2[] = {&cr, &atsuAngle}; + status = ATSUSetLayoutControls(self->layout, 2, tags2, sizes2, values2); + if (status!=noErr) + { + PyErr_SetString(PyExc_RuntimeError, "ATSUSetLayoutControls failed"); + return NULL; + } + + status = ATSUDrawText(self->layout, + kATSUFromTextBeginning, + kATSUToTextEnd, + X2Fix(x), + X2Fix(y)); + if (status!=noErr) + { + PyErr_SetString(PyExc_RuntimeError, "ATSUDrawText failed"); + return NULL; + } + + Py_INCREF(Py_None); + return Py_None; +} + +static void _data_provider_release(void* info, const void* data, size_t size) +{ + PyObject* image = (PyObject*)info; + Py_DECREF(image); +} + +static PyObject* +GraphicsContext_draw_mathtext(GraphicsContext* self, PyObject* args) +{ + float x, y, angle; + npy_intp nrows, ncols; + int n; + + PyObject* object; + PyArrayObject* image; + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + if(!PyArg_ParseTuple(args, "fffO", &x, &y, &angle, &object)) return NULL; + + /* ------------- Check the image ---------------------------- */ + if(!PyArray_Check (object)) + { + PyErr_SetString(PyExc_TypeError, "image should be a NumPy array."); + return NULL; + } + image = (PyArrayObject*) object; + if(PyArray_NDIM(image) != 2) + { + PyErr_Format(PyExc_TypeError, + "image has incorrect rank (%d expected 2)", + PyArray_NDIM(image)); + return NULL; + } + if (PyArray_TYPE(image) != NPY_UBYTE) + { + PyErr_SetString(PyExc_TypeError, + "image has incorrect type (should be uint8)"); + return NULL; + } + if (!PyArray_ISCONTIGUOUS(image)) + { + PyErr_SetString(PyExc_TypeError, "image array is not contiguous"); + return NULL; + } + + nrows = PyArray_DIM(image, 0); + ncols = PyArray_DIM(image, 1); + if (nrows != (int) nrows || ncols != (int) ncols) + { + PyErr_SetString(PyExc_RuntimeError, "bitmap image too large"); + return NULL; + } + n = nrows * ncols; + Py_INCREF(object); + + const size_t bytesPerComponent = 1; + const size_t bitsPerComponent = 8 * bytesPerComponent; + const size_t nComponents = 1; /* gray */ + const size_t bitsPerPixel = bitsPerComponent * nComponents; + const size_t bytesPerRow = nComponents * bytesPerComponent * ncols; + CGDataProviderRef provider = CGDataProviderCreateWithData(object, + PyArray_DATA(image), + n, + _data_provider_release); + CGImageRef bitmap = CGImageMaskCreate ((int) ncols, + (int) nrows, + bitsPerComponent, + bitsPerPixel, + bytesPerRow, + provider, + NULL, + false); + CGDataProviderRelease(provider); + + if(!bitmap) + { + PyErr_SetString(PyExc_RuntimeError, "CGImageMaskCreate failed"); + return NULL; + } + + if (angle==0.0) + { + CGContextDrawImage(cr, CGRectMake(x,y,ncols,nrows), bitmap); + } + else + { + CGContextSaveGState(cr); + CGContextTranslateCTM(cr, x, y); + CGContextRotateCTM(cr, angle*M_PI/180); + CGContextDrawImage(cr, CGRectMake(0,0,ncols,nrows), bitmap); + CGContextRestoreGState(cr); + } + CGImageRelease(bitmap); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject* +GraphicsContext_get_text_width_height_descent(GraphicsContext* self, PyObject* args) +{ + const UniChar* text; + int n; + PyObject* family; + float size; + const char* weight; + const char* style; + + ATSFontRef atsfont; + + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + if(!PyArg_ParseTuple(args, "u#Ofss", &text, &n, &family, &size, &weight, &style)) return NULL; + + atsfont = setfont(cr, family, size, weight, style); + + OSStatus status = noErr; + ATSUAttributeTag tags[] = {kATSUFontTag, + kATSUSizeTag, + kATSUQDBoldfaceTag, + kATSUQDItalicTag}; + ByteCount sizes[] = {sizeof(ATSUFontID), + sizeof(Fixed), + sizeof(Boolean), + sizeof(Boolean)}; + Fixed atsuSize = Long2Fix(size); + Boolean isBold = FALSE; /* setfont takes care of this */ + Boolean isItalic = FALSE; /* setfont takes care of this */ + ATSUAttributeValuePtr values[] = {&atsfont, &atsuSize, &isBold, &isItalic}; + + status = ATSUSetAttributes(self->style, 4, tags, sizes, values); + if (status!=noErr) + { + PyErr_SetString(PyExc_RuntimeError, "ATSUSetAttributes failed"); + return NULL; + } + + status = ATSUSetTextPointerLocation(self->layout, + text, + kATSUFromTextBeginning, // offset from beginning + kATSUToTextEnd, // length of text range + n); // length of text buffer + if (status!=noErr) + { + PyErr_SetString(PyExc_RuntimeError, + "ATSUCreateTextLayoutWithTextPtr failed"); + return NULL; + } + + status = ATSUSetRunStyle(self->layout, + self->style, + kATSUFromTextBeginning, + kATSUToTextEnd); + if (status!=noErr) + { + PyErr_SetString(PyExc_RuntimeError, "ATSUSetRunStyle failed"); + return NULL; + } + + ATSUAttributeTag tag = kATSUCGContextTag; + ByteCount bc = sizeof (CGContextRef); + ATSUAttributeValuePtr value = &cr; + status = ATSUSetLayoutControls(self->layout, 1, &tag, &bc, &value); + if (status!=noErr) + { + PyErr_SetString(PyExc_RuntimeError, "ATSUSetLayoutControls failed"); + return NULL; + } + + ATSUTextMeasurement before; + ATSUTextMeasurement after; + ATSUTextMeasurement ascent; + ATSUTextMeasurement descent; + status = ATSUGetUnjustifiedBounds(self->layout, + kATSUFromTextBeginning, kATSUToTextEnd, + &before, &after, &ascent, &descent); + if (status!=noErr) + { + PyErr_SetString(PyExc_RuntimeError, "ATSUGetUnjustifiedBounds failed"); + return NULL; + } + + const float width = FixedToFloat(after-before); + const float height = FixedToFloat(ascent-descent); + + return Py_BuildValue("fff", width, height, FixedToFloat(descent)); +} + +static PyObject* +GraphicsContext_draw_image(GraphicsContext* self, PyObject* args) +{ + float x, y; + int nrows, ncols; + const char* data; + int n; + PyObject* image; + CGContextRef cr = self->cr; + if (!cr) + { + PyErr_SetString(PyExc_RuntimeError, "CGContextRef is NULL"); + return NULL; + } + + if(!PyArg_ParseTuple(args, "ffiiO", &x, + &y, + &nrows, + &ncols, + &image)) return NULL; + + if (!PyString_Check(image)) + { + PyErr_SetString(PyExc_RuntimeError, "image is not a string"); + return NULL; + } + + const size_t bytesPerComponent = 1; + const size_t bitsPerComponent = 8 * bytesPerComponent; + const size_t nComponents = 4; /* red, green, blue, alpha */ + const size_t bitsPerPixel = bitsPerComponent * nComponents; + const size_t bytesPerRow = nComponents * bytesPerComponent * ncols; + CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB(); + + Py_INCREF(image); + n = PyString_GET_SIZE(image); + data = PyString_AsString(image); + + CGDataProviderRef provider = CGDataProviderCreateWithData(image, + data, + n, + _data_provider_release); + CGImageRef bitmap = CGImageCreate (ncols, + nrows, + bitsPerComponent, + bitsPerPixel, + bytesPerRow, + colorspace, + kCGImageAlphaLast, + provider, + ... [truncated message content] |
From: <jd...@us...> - 2008-12-09 12:27:55
|
Revision: 6535 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6535&view=rev Author: jdh2358 Date: 2008-12-09 12:27:51 +0000 (Tue, 09 Dec 2008) Log Message: ----------- removed extraneous savefig calls from examples Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/examples/api/barchart_demo.py trunk/matplotlib/examples/api/histogram_demo.py trunk/matplotlib/examples/api/logo2.py trunk/matplotlib/examples/api/watermark_image.py trunk/matplotlib/examples/api/watermark_text.py trunk/matplotlib/examples/pylab_examples/agg_buffer_to_array.py trunk/matplotlib/examples/pylab_examples/alignment_test.py trunk/matplotlib/examples/pylab_examples/annotation_demo.py trunk/matplotlib/examples/pylab_examples/annotation_demo2.py trunk/matplotlib/examples/pylab_examples/arctest.py trunk/matplotlib/examples/pylab_examples/arrow_demo.py trunk/matplotlib/examples/pylab_examples/axes_demo.py trunk/matplotlib/examples/pylab_examples/axes_props.py trunk/matplotlib/examples/pylab_examples/barchart_demo.py trunk/matplotlib/examples/pylab_examples/barcode_demo.py trunk/matplotlib/examples/pylab_examples/boxplot_demo.py trunk/matplotlib/examples/pylab_examples/broken_barh.py trunk/matplotlib/examples/pylab_examples/contour_demo.py trunk/matplotlib/examples/pylab_examples/contour_image.py trunk/matplotlib/examples/pylab_examples/contourf_demo.py trunk/matplotlib/examples/pylab_examples/custom_figure_class.py trunk/matplotlib/examples/pylab_examples/customize_rc.py trunk/matplotlib/examples/pylab_examples/dannys_example.py trunk/matplotlib/examples/pylab_examples/dash_control.py trunk/matplotlib/examples/pylab_examples/dashpointlabel.py trunk/matplotlib/examples/pylab_examples/date_demo2.py trunk/matplotlib/examples/pylab_examples/date_demo_rrule.py trunk/matplotlib/examples/pylab_examples/ellipse_demo.py trunk/matplotlib/examples/pylab_examples/equal_aspect_ratio.py trunk/matplotlib/examples/pylab_examples/errorbar_demo.py trunk/matplotlib/examples/pylab_examples/figimage_demo.py trunk/matplotlib/examples/pylab_examples/figure_title.py trunk/matplotlib/examples/pylab_examples/fonts_demo.py trunk/matplotlib/examples/pylab_examples/fonts_demo_kw.py trunk/matplotlib/examples/pylab_examples/hline_demo.py trunk/matplotlib/examples/pylab_examples/image_demo2.py trunk/matplotlib/examples/pylab_examples/image_demo3.py trunk/matplotlib/examples/pylab_examples/image_interp.py trunk/matplotlib/examples/pylab_examples/image_origin.py trunk/matplotlib/examples/pylab_examples/integral_demo.py trunk/matplotlib/examples/pylab_examples/layer_images.py trunk/matplotlib/examples/pylab_examples/legend_demo.py trunk/matplotlib/examples/pylab_examples/legend_demo2.py trunk/matplotlib/examples/pylab_examples/legend_demo3.py trunk/matplotlib/examples/pylab_examples/logo.py trunk/matplotlib/examples/pylab_examples/manual_axis.py trunk/matplotlib/examples/pylab_examples/mathtext_demo.py trunk/matplotlib/examples/pylab_examples/matplotlib_icon.py trunk/matplotlib/examples/pylab_examples/mri_demo.py trunk/matplotlib/examples/pylab_examples/multiline.py trunk/matplotlib/examples/pylab_examples/multiple_figs_demo.py trunk/matplotlib/examples/pylab_examples/pcolor_demo.py trunk/matplotlib/examples/pylab_examples/pcolor_demo2.py trunk/matplotlib/examples/pylab_examples/pcolor_log.py trunk/matplotlib/examples/pylab_examples/polar_legend.py trunk/matplotlib/examples/pylab_examples/polar_scatter.py trunk/matplotlib/examples/pylab_examples/poormans_contour.py trunk/matplotlib/examples/pylab_examples/pstest.py trunk/matplotlib/examples/pylab_examples/quadmesh_demo.py trunk/matplotlib/examples/pylab_examples/scatter_demo.py trunk/matplotlib/examples/pylab_examples/scatter_profile.py trunk/matplotlib/examples/pylab_examples/simple_plot_fps.py trunk/matplotlib/examples/pylab_examples/stock_demo.py trunk/matplotlib/examples/pylab_examples/symlog_demo.py trunk/matplotlib/examples/pylab_examples/table_demo.py trunk/matplotlib/examples/pylab_examples/tex_demo.py trunk/matplotlib/examples/pylab_examples/tex_unicode_demo.py trunk/matplotlib/examples/pylab_examples/text_themes.py trunk/matplotlib/examples/pylab_examples/toggle_images.py trunk/matplotlib/examples/pylab_examples/unicode_demo.py trunk/matplotlib/examples/pylab_examples/webapp_demo.py trunk/matplotlib/examples/tests/backend_driver.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/CHANGELOG 2008-12-09 12:27:51 UTC (rev 6535) @@ -1,7 +1,7 @@ -2008-12-08 Added mdehoon's native macosx backend from sf patch 2179017 +2008-12-08 Added mdehoon's native macosx backend from sf patch 2179017 - JDH 2008-12-08 Removed the prints in the set_*style commands. Return the - list of pprinted strings instead + list of pprinted strings instead - JDH 2008-12-08 Some of the changes Michael made to improve the output of the property tables in the rest docs broke of made Modified: trunk/matplotlib/examples/api/barchart_demo.py =================================================================== --- trunk/matplotlib/examples/api/barchart_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/api/barchart_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -36,5 +36,5 @@ autolabel(rects1) autolabel(rects2) -#fig.savefig('barchart_demo') + plt.show() Modified: trunk/matplotlib/examples/api/histogram_demo.py =================================================================== --- trunk/matplotlib/examples/api/histogram_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/api/histogram_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -31,5 +31,4 @@ ax.set_ylim(0, 0.03) ax.grid(True) -#fig.savefig('histogram_demo',dpi=72) plt.show() Modified: trunk/matplotlib/examples/api/logo2.py =================================================================== --- trunk/matplotlib/examples/api/logo2.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/api/logo2.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -67,10 +67,10 @@ for line in ax.get_ygridlines() + ax.get_xgridlines(): line.set_lw(0.8) - line.set_alpha(0.9) + line.set_alpha(0.9) line.set_ls('-') line.set_color('0.5') - + ax.set_yticks(np.arange(1, 9, 2)) ax.set_rmax(9) @@ -78,7 +78,6 @@ main_axes = add_math_background() add_polar_bar() add_matplotlib_text(main_axes) - fig.savefig('logo2.png', facecolor=figcolor, edgecolor=figcolor, dpi=dpi) plt.show() Modified: trunk/matplotlib/examples/api/watermark_image.py =================================================================== --- trunk/matplotlib/examples/api/watermark_image.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/api/watermark_image.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -18,6 +18,4 @@ ax.grid() fig.figimage(im, 10, 10) -#fig.savefig('watermarked', transparent=True) - plt.show() Modified: trunk/matplotlib/examples/api/watermark_text.py =================================================================== --- trunk/matplotlib/examples/api/watermark_text.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/api/watermark_text.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -18,7 +18,4 @@ fontsize=50, color='gray', ha='right', va='bottom', alpha=0.5) -#fig.savefig('watermarked_text', transparent=True) - - plt.show() Modified: trunk/matplotlib/examples/pylab_examples/agg_buffer_to_array.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/agg_buffer_to_array.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/agg_buffer_to_array.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -20,5 +20,4 @@ fig2 = figure() ax2 = fig2.add_subplot(111, frameon=False) ax2.imshow(X) -fig2.savefig('simple.png') show() Modified: trunk/matplotlib/examples/pylab_examples/alignment_test.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/alignment_test.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/alignment_test.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -78,5 +78,5 @@ transform=ax.transAxes) axis('off') -#savefig('alignment_test', dpi=100) + show() Modified: trunk/matplotlib/examples/pylab_examples/annotation_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/annotation_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/annotation_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -82,7 +82,6 @@ horizontalalignment='right', verticalalignment='bottom', fontsize=20) - #fig.savefig('annotation_coords') if 1: # you can specify the xypoint and the xytext in different @@ -111,8 +110,8 @@ horizontalalignment='left', verticalalignment='bottom', ) - #fig.savefig('annotation_polar') + if 1: # You can also use polar notation on a catesian axes. Here the # native coordinate system ('data') is cartesian, so you need to @@ -138,9 +137,5 @@ ax.set_xlim(-20, 20) ax.set_ylim(-20, 20) - #fig.savefig('annotation_ellipse') - - -#fig.savefig('annotation_demo.png') show() Modified: trunk/matplotlib/examples/pylab_examples/annotation_demo2.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/annotation_demo2.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/annotation_demo2.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -72,9 +72,7 @@ - #fig.savefig('annotation_connection') - if 1: fig = figure(2) fig.clf() @@ -146,6 +144,4 @@ ) ) - #fig.savefig('annotation_arrowstyle') - show() Modified: trunk/matplotlib/examples/pylab_examples/arctest.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/arctest.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/arctest.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -13,6 +13,6 @@ l = plot(t1, f(t1), 'ro') setp(l, 'markersize', 30) setp(l, 'markerfacecolor', 'b') -#savefig('arctest', dpi=150) + show() Modified: trunk/matplotlib/examples/pylab_examples/arrow_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/arrow_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/arrow_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -308,6 +308,5 @@ normalize_data=scaled, head_starts_at_zero=True, size=size) draw() - #savefig('arrows.png') - #print 'Example saved to file "arrows.png"' + show() Modified: trunk/matplotlib/examples/pylab_examples/axes_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/axes_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/axes_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -28,6 +28,5 @@ title('Impulse response') setp(a, xlim=(0,.2), xticks=[], yticks=[]) -#savefig('../figures/axes_demo.eps') -#savefig('../figures/axes_demo.png') + show() Modified: trunk/matplotlib/examples/pylab_examples/axes_props.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/axes_props.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/axes_props.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -26,7 +26,7 @@ setp(xticklabels, 'color', 'r', fontsize='medium') -#savefig('axprops_demo') + show() @@ -57,7 +57,6 @@ label.set_color('r') label.set_fontsize('medium') -#savefig('axprops_demo') show() """ Modified: trunk/matplotlib/examples/pylab_examples/barchart_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/barchart_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/barchart_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -34,5 +34,5 @@ autolabel(rects1) autolabel(rects2) -#savefig('barchart_demo') + plt.show() Modified: trunk/matplotlib/examples/pylab_examples/barcode_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/barcode_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/barcode_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -21,6 +21,6 @@ ax = fig.add_axes([0.3, 0.1, 0.6, 0.1], **axprops) ax.imshow(x, **barprops) -#fig.savefig('barcode.png', dpi=100) + show() Modified: trunk/matplotlib/examples/pylab_examples/boxplot_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/boxplot_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/boxplot_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -15,32 +15,26 @@ # basic plot boxplot(data) -#savefig('box1') # notched plot figure() boxplot(data,1) -#savefig('box2') # change outlier point symbols figure() boxplot(data,0,'gD') -#savefig('box3') # don't show outlier points figure() boxplot(data,0,'') -#savefig('box4') # horizontal boxes figure() boxplot(data,0,'rs',0) -#savefig('box5') # change whisker length figure() boxplot(data,0,'rs',0,0.75) -#savefig('box6') # fake up some more data spread= rand(50) * 100 @@ -59,7 +53,6 @@ # multiple box plots on one figure figure() boxplot(data) -#savefig('box7') show() Modified: trunk/matplotlib/examples/pylab_examples/broken_barh.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/broken_barh.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/broken_barh.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -20,5 +20,4 @@ fontsize=16, horizontalalignment='right', verticalalignment='top') -#fig.savefig('broken_barh', dpi=100) plt.show() Modified: trunk/matplotlib/examples/pylab_examples/contour_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/contour_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/contour_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -101,5 +101,4 @@ CB.ax.set_position([ll, b+0.1*h, ww, h*0.8]) -#savefig('contour_demo') plt.show() Modified: trunk/matplotlib/examples/pylab_examples/contour_image.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/contour_image.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/contour_image.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -98,6 +98,5 @@ setp(gca(), ylim=ylim[::-1]) title("Image, origin from rc, reversed y-axis") colorbar(im) -#savefig('contour_image') show() Modified: trunk/matplotlib/examples/pylab_examples/contourf_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/contourf_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/contourf_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -76,6 +76,5 @@ clabel(CS4, fmt = '%2.1f', colors = 'w', fontsize=14) colorbar(CS3) -#savefig('contourf_demo') show() Modified: trunk/matplotlib/examples/pylab_examples/custom_figure_class.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/custom_figure_class.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/custom_figure_class.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -16,7 +16,6 @@ fig = figure(FigureClass=MyFigure, figtitle='my title') ax = fig.add_subplot(111) ax.plot([1,2,3]) -fig.savefig('test.png') -fig.savefig('test.ps') + show() Modified: trunk/matplotlib/examples/pylab_examples/customize_rc.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/customize_rc.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/customize_rc.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -1,4 +1,4 @@ -#!/usr/bin/env python + """ I'm not trying to make a good liking figure here, but just to show some examples of customizing rc params on the fly @@ -13,7 +13,7 @@ rc('tick', labelsize=15) # tick labels bigger rc('lines', lw=1, color='k') # thicker black lines (no budget for color!) rc('grid', c='0.5', ls='-', lw=0.5) # solid gray grid lines - rc('#savefig', dpi=300) # higher res outputs + rc('savefig', dpi=300) # higher res outputs @@ -22,7 +22,7 @@ >>> set_pub() >>> subplot(111) >>> plot([1,2,3]) ->>> #savefig('myfig') +>>> savefig('myfig') >>> rcdefaults() # restore the defaults """ Modified: trunk/matplotlib/examples/pylab_examples/dannys_example.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/dannys_example.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/dannys_example.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -56,5 +56,4 @@ 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}) -pylab.savefig('pfm-lsm.png') pylab.show() Modified: trunk/matplotlib/examples/pylab_examples/dash_control.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/dash_control.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/dash_control.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -10,5 +10,5 @@ l, = plot(arange(20), '--') l.set_dashes(dashes) -savefig('dash_control') + show() Modified: trunk/matplotlib/examples/pylab_examples/dashpointlabel.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/dashpointlabel.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/dashpointlabel.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -35,7 +35,6 @@ ax.set_xlim((0.0, 5.0)) ax.set_ylim((0.0, 5.0)) -#if save: -# pylab.savefig('dashpointlabel') + pylab.show() Modified: trunk/matplotlib/examples/pylab_examples/date_demo2.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/date_demo2.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/date_demo2.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -43,5 +43,4 @@ fig.autofmt_xdate() -#fig.savefig('date_demo2') show() Modified: trunk/matplotlib/examples/pylab_examples/date_demo_rrule.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/date_demo_rrule.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/date_demo_rrule.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -28,5 +28,4 @@ labels = ax.get_xticklabels() setp(labels, rotation=30, fontsize=10) -savefig('date_demo_rrule') show() Modified: trunk/matplotlib/examples/pylab_examples/ellipse_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/ellipse_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/ellipse_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -17,7 +17,4 @@ ax.set_xlim(0, 10) ax.set_ylim(0, 10) -#fig.savefig('ellipse_demo.eps') -#fig.savefig('ellipse_demo.png') - show() Modified: trunk/matplotlib/examples/pylab_examples/equal_aspect_ratio.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/equal_aspect_ratio.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/equal_aspect_ratio.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -17,7 +17,4 @@ axes().set_aspect('equal', 'datalim') -#savefig('simple_plot.png') -savefig('equal_aspect') - show() Modified: trunk/matplotlib/examples/pylab_examples/errorbar_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/errorbar_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/errorbar_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -43,5 +43,4 @@ ax.set_yscale('log') errorbar(t, s+2, e, f, fmt='o') # both symmetric -#savefig('errorbar_demo') show() Modified: trunk/matplotlib/examples/pylab_examples/figimage_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/figimage_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/figimage_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -15,9 +15,6 @@ im1 = plt.figimage(Z, xo=50, yo=0, cmap=cm.jet, origin='lower') im2 = plt.figimage(Z, xo=100, yo=100, alpha=.8, cmap=cm.jet, origin='lower') -#fig.savefig('figimage_demo.png') -#fig.savefig('figimage_demo.svg') -#fig.savefig('figimage_demo.pdf') plt.show() Modified: trunk/matplotlib/examples/pylab_examples/figure_title.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/figure_title.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/figure_title.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -25,6 +25,5 @@ title('subplot 2') ylabel('Undamped') -#savefig('figtext') show() Modified: trunk/matplotlib/examples/pylab_examples/fonts_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/fonts_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/fonts_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -111,5 +111,5 @@ **alignment) axis([-1,1,0,1]) -#savefig('fonts_demo') + show() Modified: trunk/matplotlib/examples/pylab_examples/fonts_demo_kw.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/fonts_demo_kw.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/fonts_demo_kw.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -80,5 +80,5 @@ **alignment) axis([-1, 1, 0, 1]) -#savefig('fonts_demo_kw') + show() Modified: trunk/matplotlib/examples/pylab_examples/hline_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/hline_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/hline_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -17,7 +17,7 @@ plt.hlines(t, [0], s, lw=2) plt.xlabel('time (s)') plt.title('Comparison of model with data') -plt.savefig('test') + plt.xlim(xmin=0) plt.show() Modified: trunk/matplotlib/examples/pylab_examples/image_demo2.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/image_demo2.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/image_demo2.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -28,6 +28,5 @@ ylabel('density') setp(gca(), 'xticklabels', []) -#savefig('image_demo2') show() Modified: trunk/matplotlib/examples/pylab_examples/image_demo3.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/image_demo3.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/image_demo3.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -14,6 +14,5 @@ ax.set_axis_off() im = imshow(lena, origin='lower') -#savefig('image_demo3') show() Modified: trunk/matplotlib/examples/pylab_examples/image_interp.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/image_interp.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/image_interp.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -50,17 +50,14 @@ A = rand(5,5) figure(1) imshow(A, interpolation='nearest') -savefig('agg_nearest') grid(True) figure(2) imshow(A, interpolation='bilinear') -savefig('agg_bilinear') grid(True) figure(3) imshow(A, interpolation='bicubic') -savefig('agg_bicubic') grid(True) show() Modified: trunk/matplotlib/examples/pylab_examples/image_origin.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/image_origin.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/image_origin.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -21,5 +21,4 @@ title('blue should be down') imshow(x, origin='lower', interpolation=interp) #axis(lim) -savefig('image_origin') show() Modified: trunk/matplotlib/examples/pylab_examples/integral_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/integral_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/integral_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -31,5 +31,4 @@ ax.set_xticks((a,b)) ax.set_xticklabels(('a','b')) ax.set_yticks([]) -#savefig('integral_demo') show() Modified: trunk/matplotlib/examples/pylab_examples/layer_images.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/layer_images.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/layer_images.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -38,11 +38,6 @@ extent=extent) #axis([xmin, xmax, ymin, ymax]) - -savefig('layer_images.png') -savefig('layer_images.svg') -savefig('layer_images.pdf') - show() Modified: trunk/matplotlib/examples/pylab_examples/legend_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/legend_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/legend_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -39,7 +39,6 @@ plt.setp(ltext, fontsize='small') # the legend text fontsize plt.setp(llines, linewidth=1.5) # the legend linewidth #leg.draw_frame(False) # don't draw the legend frame -#plt.savefig('legend_demo') plt.show() Modified: trunk/matplotlib/examples/pylab_examples/legend_demo2.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/legend_demo2.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/legend_demo2.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -17,7 +17,6 @@ xlabel('time') ylabel('volts') title('Damped oscillation') -#savefig('legend_demo2') #axis([0,2,-1,1]) show() Modified: trunk/matplotlib/examples/pylab_examples/legend_demo3.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/legend_demo3.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/legend_demo3.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -31,6 +31,5 @@ plt.draw() plt.show() -#plt.savefig("legend_demo3") Modified: trunk/matplotlib/examples/pylab_examples/logo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/logo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/logo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -20,5 +20,5 @@ axis([1, 1.72,-60, 10]) setp(gca(), 'xticklabels', []) setp(gca(), 'yticklabels', []) -#savefig('logo2.png', dpi=300) + show() Modified: trunk/matplotlib/examples/pylab_examples/manual_axis.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/manual_axis.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/manual_axis.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -52,6 +52,6 @@ ax.set_ylim(-1.5, 1.5) make_xaxis(ax, 0, offset=0.1, **props) make_yaxis(ax, 0, offset=5, **props) -#fig.savefig('manual_axis.png', dpi=100, facecolor='white', edgecolor='white') + show() Modified: trunk/matplotlib/examples/pylab_examples/mathtext_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/mathtext_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/mathtext_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -23,7 +23,7 @@ ax.legend([r"$\sqrt{x^2}$"]) ax.set_title(r'$\Delta_i^j \hspace{0.4} \mathrm{versus} \hspace{0.4} \Delta_{i+1}^j$', fontsize=20) -fig.savefig('mathtext_demo') + show() Modified: trunk/matplotlib/examples/pylab_examples/matplotlib_icon.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/matplotlib_icon.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/matplotlib_icon.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -17,5 +17,5 @@ # grid(True) setp(gca(), xticklabels=[], yticklabels=[]) -savefig('matplotlib.svg', facecolor='0.75') +savefig('matplotlib', facecolor='0.75') Modified: trunk/matplotlib/examples/pylab_examples/mri_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/mri_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/mri_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -9,5 +9,5 @@ #imshow(im, ColormapJet(256)) imshow(im, cmap=cm.jet) axis('off') -#savefig('mri_demo') + show() Modified: trunk/matplotlib/examples/pylab_examples/multiline.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/multiline.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/multiline.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -10,6 +10,6 @@ horizontalalignment = 'center', verticalalignment = 'top', multialignment = 'center') -#savefig('multiline') + grid(True) show() Modified: trunk/matplotlib/examples/pylab_examples/multiple_figs_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/multiple_figs_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/multiple_figs_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -21,9 +21,9 @@ plot(t,s2, 'gs') setp(gca(), 'xticklabels', []) -#figure(1) -#savefig('fig1') -#figure(2) -#savefig('fig2') +figure(1) +savefig('fig1') +figure(2) +savefig('fig2') show() Modified: trunk/matplotlib/examples/pylab_examples/pcolor_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/pcolor_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/pcolor_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -22,7 +22,7 @@ pcolor(X, Y, Z) colorbar() axis([-3,3,-3,3]) -savefig('pcolor_demo') + show() Modified: trunk/matplotlib/examples/pylab_examples/pcolor_demo2.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/pcolor_demo2.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/pcolor_demo2.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -25,7 +25,7 @@ #im.set_interpolation('bicubic') im.set_interpolation('bilinear') #ax.set_image_extent(-3, 3, -3, 3) -#savefig('pcolor_demo2') + show() Modified: trunk/matplotlib/examples/pylab_examples/pcolor_log.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/pcolor_log.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/pcolor_log.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -24,4 +24,4 @@ show() -#savefig('pcolor_log.png') + Modified: trunk/matplotlib/examples/pylab_examples/polar_legend.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/polar_legend.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/polar_legend.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -17,5 +17,5 @@ ax.plot(theta, r, color='#ee8d18', lw=3, label='a line') ax.plot(0.5*theta, r, color='blue', ls='--', lw=3, label='another line') ax.legend() -fig.savefig('polar_legend') + show() Modified: trunk/matplotlib/examples/pylab_examples/polar_scatter.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/polar_scatter.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/polar_scatter.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -14,5 +14,5 @@ c = scatter(theta, r, c=colors, s=area) c.set_alpha(0.75) -#savefig('polar_test2') + show() Modified: trunk/matplotlib/examples/pylab_examples/poormans_contour.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/poormans_contour.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/poormans_contour.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -23,6 +23,6 @@ im = imshow(Z, cmap=cmap, interpolation='bilinear') axis('off') colorbar() -#savefig('test') + show() Modified: trunk/matplotlib/examples/pylab_examples/pstest.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/pstest.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/pstest.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -25,6 +25,6 @@ ylabel('Signal 2', fontsize=12) xlabel('time (s)', fontsize=12) -#savefig('pstest') + show() Modified: trunk/matplotlib/examples/pylab_examples/quadmesh_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/quadmesh_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/quadmesh_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -42,5 +42,4 @@ ax.set_title('With masked values') -savefig("quadmesh_demo") show() Modified: trunk/matplotlib/examples/pylab_examples/scatter_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/scatter_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/scatter_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -6,6 +6,5 @@ y = 0.9*rand(N) area = pi*(10 * rand(N))**2 # 0 to 10 point radiuses scatter(x,y,s=area, marker='^', c='r') -savefig('test.ps') -savefig('test.pdf') + show() Modified: trunk/matplotlib/examples/pylab_examples/scatter_profile.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/scatter_profile.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/scatter_profile.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -19,5 +19,4 @@ y = 0.9*rand(N) s = 20*rand(N) scatter(x,y,s) - #savefig('scatter_demo') print '%d symbols in %1.2f s' % (N, time.time()-tstart) Modified: trunk/matplotlib/examples/pylab_examples/simple_plot_fps.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/simple_plot_fps.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/simple_plot_fps.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -17,9 +17,6 @@ title('About as simple as it gets, folks') grid(True) -#savefig('simple_plot.png') -#savefig('simple_plot') - import time frames = 100.0 Modified: trunk/matplotlib/examples/pylab_examples/stock_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/stock_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/stock_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -15,5 +15,5 @@ title('INTC vs AAPL') legend( ('INTC', 'AAPL') ) -#savefig('stock_demo') + show() Modified: trunk/matplotlib/examples/pylab_examples/symlog_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/symlog_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/symlog_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -25,5 +25,4 @@ grid(True) ylabel('symlog both') -savefig('symlog_demo') show() Modified: trunk/matplotlib/examples/pylab_examples/table_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/table_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/table_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -88,7 +88,5 @@ yticks(vals*1000, ['%d' % val for val in vals]) xticks([]) title('Loss by Disaster') -#savefig('table_demo_small', dpi=75) -#savefig('table_demo_large', dpi=300) show() Modified: trunk/matplotlib/examples/pylab_examples/tex_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/tex_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/tex_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -29,7 +29,5 @@ title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!", fontsize=16, color='r') grid(True) -savefig('tex_demo') - show() Modified: trunk/matplotlib/examples/pylab_examples/tex_unicode_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/tex_unicode_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/tex_unicode_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -22,7 +22,4 @@ title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!", fontsize=16, color='r') grid(True) -savefig('tex_demo') - - show() Modified: trunk/matplotlib/examples/pylab_examples/text_themes.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/text_themes.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/text_themes.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -21,5 +21,4 @@ xlabel('time (s)', font, style='italic') ylabel('voltage (mV)', font) -#savefig('text_themes') show() Modified: trunk/matplotlib/examples/pylab_examples/toggle_images.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/toggle_images.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/toggle_images.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -40,5 +40,5 @@ draw() connect('key_press_event', toggle_images) -#savefig('toggle_images') + show() Modified: trunk/matplotlib/examples/pylab_examples/unicode_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/unicode_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/unicode_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -9,5 +9,4 @@ text( 0.5, 2.5, u'Institut für Festkörperphysik', rotation=45) text( 1, 1.5, u'AVA (check kerning)') -savefig('test') show() Modified: trunk/matplotlib/examples/pylab_examples/webapp_demo.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/webapp_demo.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/pylab_examples/webapp_demo.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -61,6 +61,6 @@ l.set_fontsize(12) canvas = FigureCanvasAgg(fig) - canvas.print_figure('webapp.png', dpi=150) + canvas.print_figure('webapp', dpi=150) make_fig() Modified: trunk/matplotlib/examples/tests/backend_driver.py =================================================================== --- trunk/matplotlib/examples/tests/backend_driver.py 2008-12-09 10:23:53 UTC (rev 6534) +++ trunk/matplotlib/examples/tests/backend_driver.py 2008-12-09 12:27:51 UTC (rev 6535) @@ -123,7 +123,6 @@ 'legend_demo.py', 'legend_demo2.py', 'legend_demo3.py', - 'legend_demo3.py', 'legend_scatter.py', 'line_collection.py', 'line_collection2.py', This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cm...@us...> - 2008-12-10 01:59:08
|
Revision: 6536 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6536&view=rev Author: cmoad Date: 2008-12-10 01:59:04 +0000 (Wed, 10 Dec 2008) Log Message: ----------- minor rev bump Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/__init__.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-12-09 12:27:51 UTC (rev 6535) +++ trunk/matplotlib/CHANGELOG 2008-12-10 01:59:04 UTC (rev 6536) @@ -1,3 +1,5 @@ +================================================================= 2008-12-09 Released 0.98.4 at svn r6536 + 2008-12-08 Added mdehoon's native macosx backend from sf patch 2179017 - JDH 2008-12-08 Removed the prints in the set_*style commands. Return the Modified: trunk/matplotlib/lib/matplotlib/__init__.py =================================================================== --- trunk/matplotlib/lib/matplotlib/__init__.py 2008-12-09 12:27:51 UTC (rev 6535) +++ trunk/matplotlib/lib/matplotlib/__init__.py 2008-12-10 01:59:04 UTC (rev 6536) @@ -89,7 +89,7 @@ """ from __future__ import generators -__version__ = '0.98.3' +__version__ = '0.98.4' __revision__ = '$Revision$' __date__ = '$Date$' This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-12-10 14:35:53
|
Revision: 6545 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6545&view=rev Author: jdh2358 Date: 2008-12-10 14:35:49 +0000 (Wed, 10 Dec 2008) Log Message: ----------- added nose tests Modified Paths: -------------- trunk/matplotlib/examples/tests/backend_driver.py Added Paths: ----------- trunk/matplotlib/unit/nose_tests.py Modified: trunk/matplotlib/examples/tests/backend_driver.py =================================================================== --- trunk/matplotlib/examples/tests/backend_driver.py 2008-12-10 12:56:09 UTC (rev 6544) +++ trunk/matplotlib/examples/tests/backend_driver.py 2008-12-10 14:35:49 UTC (rev 6545) @@ -167,7 +167,7 @@ 'scatter_masked.py', 'scatter_profile.py', 'scatter_star_poly.py', - 'set_and_get.py', + #'set_and_get.py', 'shared_axis_across_figures.py', 'shared_axis_demo.py', 'simple_plot.py', Added: trunk/matplotlib/unit/nose_tests.py =================================================================== --- trunk/matplotlib/unit/nose_tests.py (rev 0) +++ trunk/matplotlib/unit/nose_tests.py 2008-12-10 14:35:49 UTC (rev 6545) @@ -0,0 +1,17 @@ +import nose, nose.tools as nt +import numpy.testing as nptest + +import matplotlib +matplotlib.use('Agg') +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.axes as maxes + +def test_create_subplot_object(): + fig = plt.figure() + ax = maxes.Subplot(fig, 1, 1, 1) + fig.add_subplot(ax) + +if __name__=='__main__': + nose.runmodule(argv=['-s','--with-doctest'], exit=False) + pass This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-12-10 16:39:06
|
Revision: 6550 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6550&view=rev Author: jdh2358 Date: 2008-12-10 16:39:01 +0000 (Wed, 10 Dec 2008) Log Message: ----------- updates to doc Modified Paths: -------------- trunk/matplotlib/doc/api/artist_api.rst trunk/matplotlib/doc/devel/coding_guide.rst trunk/matplotlib/doc/users/whats_new.rst trunk/matplotlib/examples/pylab_examples/psd_demo2.py trunk/matplotlib/examples/pylab_examples/psd_demo3.py trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/legend.py trunk/matplotlib/lib/matplotlib/patches.py Added Paths: ----------- trunk/matplotlib/doc/pyplots/whats_new_98_4_fancy.py trunk/matplotlib/doc/pyplots/whats_new_98_4_fill_between.py trunk/matplotlib/doc/pyplots/whats_new_98_4_legend.py Modified: trunk/matplotlib/doc/api/artist_api.rst =================================================================== --- trunk/matplotlib/doc/api/artist_api.rst 2008-12-10 15:22:03 UTC (rev 6549) +++ trunk/matplotlib/doc/api/artist_api.rst 2008-12-10 16:39:01 UTC (rev 6550) @@ -15,6 +15,14 @@ :undoc-members: :show-inheritance: +:mod:`matplotlib.legend` +============================= + +.. automodule:: matplotlib.legend + :members: + :undoc-members: + :show-inheritance: + :mod:`matplotlib.lines` ============================= Modified: trunk/matplotlib/doc/devel/coding_guide.rst =================================================================== --- trunk/matplotlib/doc/devel/coding_guide.rst 2008-12-10 15:22:03 UTC (rev 6549) +++ trunk/matplotlib/doc/devel/coding_guide.rst 2008-12-10 16:39:01 UTC (rev 6550) @@ -27,6 +27,12 @@ svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/\ v0_91_maint mpl91 --username=youruser --password=yourpass +The current release of the trunk is in the 0.98.4 maintenance branch:: + + svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/\ + v0_98_4_maint mpl98.4 --username=youruser --password=yourpass + + Committing changes ------------------ Added: trunk/matplotlib/doc/pyplots/whats_new_98_4_fancy.py =================================================================== --- trunk/matplotlib/doc/pyplots/whats_new_98_4_fancy.py (rev 0) +++ trunk/matplotlib/doc/pyplots/whats_new_98_4_fancy.py 2008-12-10 16:39:01 UTC (rev 6550) @@ -0,0 +1,54 @@ +import matplotlib.patches as mpatch +import matplotlib.pyplot as plt + +figheight = 8 +fig = plt.figure(1, figsize=(9, figheight), dpi=80) +fontsize = 0.4 * fig.dpi + +def make_boxstyles(ax): + styles = mpatch.BoxStyle.get_styles() + + for i, (stylename, styleclass) in enumerate(styles.items()): + ax.text(0.5, (float(len(styles)) - 0.5 - i)/len(styles), stylename, + ha="center", + size=fontsize, + transform=ax.transAxes, + bbox=dict(boxstyle=stylename, fc="w", ec="k")) + +def make_arrowstyles(ax): + styles = mpatch.ArrowStyle.get_styles() + + ax.set_xlim(0, 4) + ax.set_ylim(0, figheight) + + for i, (stylename, styleclass) in enumerate(sorted(styles.items())): + y = (float(len(styles)) -0.25 - i) # /figheight + p = mpatch.Circle((3.2, y), 0.2, fc="w") + ax.add_patch(p) + + ax.annotate(stylename, (3.2, y), + (2., y), + #xycoords="figure fraction", textcoords="figure fraction", + ha="right", va="center", + size=fontsize, + arrowprops=dict(arrowstyle=stylename, + patchB=p, + shrinkA=5, + shrinkB=5, + fc="w", ec="k", + connectionstyle="arc3,rad=-0.05", + ), + bbox=dict(boxstyle="square", fc="w")) + + ax.xaxis.set_visible(False) + ax.yaxis.set_visible(False) + + +ax1 = fig.add_subplot(121, frameon=False, xticks=[], yticks=[]) +make_boxstyles(ax1) + +ax2 = fig.add_subplot(122, frameon=False, xticks=[], yticks=[]) +make_arrowstyles(ax2) + + +plt.show() Added: trunk/matplotlib/doc/pyplots/whats_new_98_4_fill_between.py =================================================================== --- trunk/matplotlib/doc/pyplots/whats_new_98_4_fill_between.py (rev 0) +++ trunk/matplotlib/doc/pyplots/whats_new_98_4_fill_between.py 2008-12-10 16:39:01 UTC (rev 6550) @@ -0,0 +1,17 @@ +#!/usr/bin/env python +import matplotlib.mlab as mlab +from pylab import figure, show +import numpy as np + +x = np.arange(0.0, 2, 0.01) +y1 = np.sin(2*np.pi*x) +y2 = 1.2*np.sin(4*np.pi*x) + +fig = figure() +ax = fig.add_subplot(111) +ax.plot(x, y1, x, y2, color='black') +ax.fill_between(x, y1, y2, where=y2>y1, facecolor='green') +ax.fill_between(x, y1, y2, where=y2<=y1, facecolor='red') +ax.set_title('fill between where') + +show() Added: trunk/matplotlib/doc/pyplots/whats_new_98_4_legend.py =================================================================== --- trunk/matplotlib/doc/pyplots/whats_new_98_4_legend.py (rev 0) +++ trunk/matplotlib/doc/pyplots/whats_new_98_4_legend.py 2008-12-10 16:39:01 UTC (rev 6550) @@ -0,0 +1,18 @@ +import matplotlib.pyplot as plt +import numpy as np +import matplotlib.pyplot as plt + + +ax = plt.subplot(111) +t1 = np.arange(0.0, 1.0, 0.1) +for n in [1, 2, 3, 4]: + plt.plot(t1, t1**n, label="n=%d"%(n,)) + +leg = plt.legend(loc='best', ncol=4, mode="expand", shadow=True, fancybox=True) +leg.get_frame().set_alpha(0.7) + + +plt.show() + + + Modified: trunk/matplotlib/doc/users/whats_new.rst =================================================================== --- trunk/matplotlib/doc/users/whats_new.rst 2008-12-10 15:22:03 UTC (rev 6549) +++ trunk/matplotlib/doc/users/whats_new.rst 2008-12-10 16:39:01 UTC (rev 6550) @@ -19,8 +19,10 @@ Jae-Joon has rewritten the legend class, and added support for multiple columns and rows, as well as fancy box drawing. See -:ref:`pylab_examples-legend_demo3`. +:func:`~matplotlib.pyplot.legend` and +:class:`matplotlib.legend.Legend`. +.. plot:: pyplots/whats_new_98_4_legend.py .. _fancy-annotations: @@ -29,9 +31,13 @@ Jae-Joon has added lot's of support to annotations for drawing fancy boxes and connectors in annotations. See -:ref:`pylab_examples-annotation_demo2` and -:ref:`pylab_examples-fancyarrow_demo`. +:func:`~matplotlib.pyplot.annotate` and +:class:`~matplotlib.patches.BoxStyle`, +:class:`~matplotlib.patches.ArrowStyle`, and +:class:`~matplotlib.patches.ConnectionStyle`. +.. plot:: pyplots/whats_new_98_4_fancy.py + .. _psd-amplitude: psd amplitude scaling @@ -49,9 +55,13 @@ ------------------ Added a :func:`~matplotlib.pyplot.fill_between` function to make it -easier to do shaded region plots in the presence of masked data. See -:ref:`pylab_examples-fill_between`. +easier to do shaded region plots in the presence of masked data. You +can pass an *x* array and a *ylower* and *yupper* array to fill +betweem, and an optional *where* argument which is a logical mask +where you want to do the filling. +.. plot:: pyplots/whats_new_98_4_fill_between.py + Lots more ----------- Modified: trunk/matplotlib/examples/pylab_examples/psd_demo2.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/psd_demo2.py 2008-12-10 15:22:03 UTC (rev 6549) +++ trunk/matplotlib/examples/pylab_examples/psd_demo2.py 2008-12-10 16:39:01 UTC (rev 6550) @@ -10,6 +10,7 @@ #Plot the raw time series fig = plt.figure() +fig.subplots_adjust(hspace=0.45, wspace=0.3) ax = fig.add_subplot(2, 1, 1) ax.plot(t, y) @@ -19,7 +20,7 @@ ax2.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs) ax2.psd(y, NFFT=len(t), pad_to=len(t)*2, Fs=fs) ax2.psd(y, NFFT=len(t), pad_to=len(t)*4, Fs=fs) -plt.title('Effect of zero padding') +plt.title('zero padding') #Plot the PSD with different block sizes, Zero pad to the length of the orignal #data sequence. @@ -27,13 +28,15 @@ ax3.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs) ax3.psd(y, NFFT=len(t)//2, pad_to=len(t), Fs=fs) ax3.psd(y, NFFT=len(t)//4, pad_to=len(t), Fs=fs) -plt.title('Effect of block size') +ax3.set_ylabel('') +plt.title('block size') #Plot the PSD with different amounts of overlap between blocks ax4 = fig.add_subplot(2, 3, 6, sharex=ax2, sharey=ax2) ax4.psd(y, NFFT=len(t)//2, pad_to=len(t), noverlap=0, Fs=fs) ax4.psd(y, NFFT=len(t)//2, pad_to=len(t), noverlap=int(0.05*len(t)/2.), Fs=fs) ax4.psd(y, NFFT=len(t)//2, pad_to=len(t), noverlap=int(0.2*len(t)/2.), Fs=fs) -plt.title('Effect of overlap') +ax4.set_ylabel('') +plt.title('overlap') plt.show() Modified: trunk/matplotlib/examples/pylab_examples/psd_demo3.py =================================================================== --- trunk/matplotlib/examples/pylab_examples/psd_demo3.py 2008-12-10 15:22:03 UTC (rev 6549) +++ trunk/matplotlib/examples/pylab_examples/psd_demo3.py 2008-12-10 16:39:01 UTC (rev 6550) @@ -14,11 +14,12 @@ yticks = np.arange(-50, 30, 10) xticks = np.arange(0,550,100) +plt.subplots_adjust(hspace=0.45, wspace=0.3) +plt.subplot(1,2,1) -plt.subplot(1,2,1) plt.psd(xn, NFFT=301, Fs=fs, window=mlab.window_none, pad_to=1024, scale_by_freq=True) -plt.title('Periodogram PSD Estimate') +plt.title('Periodogram') plt.yticks(yticks) plt.xticks(xticks) plt.grid(True) @@ -26,9 +27,10 @@ plt.subplot(1,2,2) plt.psd(xn, NFFT=150, Fs=fs, window=mlab.window_none, noverlap=75, pad_to=512, scale_by_freq=True) -plt.title('Welch Method PSD Estimate') +plt.title('Welch') plt.xticks(xticks) plt.yticks(yticks) +plt.ylabel('') plt.grid(True) plt.show() Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2008-12-10 15:22:03 UTC (rev 6549) +++ trunk/matplotlib/lib/matplotlib/axes.py 2008-12-10 16:39:01 UTC (rev 6550) @@ -2742,6 +2742,8 @@ Keyword arguments: %(Annotation)s + + .. plot:: mpl_examples/pylab_examples/annotation_demo2.py """ a = mtext.Annotation(*args, **kwargs) a.set_transform(mtransforms.IdentityTransform()) @@ -5587,14 +5589,11 @@ *kwargs* keyword args passed on to the :class:`PolyCollection` - .. seealso:: - :file:`examples/pylab_examples/fill_between.py`: - For more examples. - kwargs control the Polygon properties: %(PolyCollection)s + .. plot:: mpl_examples/pylab_examples/fill_between.py """ # Handle united data, such as dates self._process_unit_info(xdata=x, ydata=y1, kwargs=kwargs) Modified: trunk/matplotlib/lib/matplotlib/legend.py =================================================================== --- trunk/matplotlib/lib/matplotlib/legend.py 2008-12-10 15:22:03 UTC (rev 6549) +++ trunk/matplotlib/lib/matplotlib/legend.py 2008-12-10 16:39:01 UTC (rev 6550) @@ -47,7 +47,7 @@ sequence of strings and loc can be a string or an integer specifying the legend location - The location codes are + The location codes are:: 'best' : 0, (only implemented for axis legends) 'upper right' : 1, Modified: trunk/matplotlib/lib/matplotlib/patches.py =================================================================== --- trunk/matplotlib/lib/matplotlib/patches.py 2008-12-10 15:22:03 UTC (rev 6549) +++ trunk/matplotlib/lib/matplotlib/patches.py 2008-12-10 16:39:01 UTC (rev 6550) @@ -1522,6 +1522,7 @@ the fancy box). *mutation_aspect* determines the aspect-ratio of the mutation. + .. plot:: mpl_examples/pylab_examples/fancybox_demo2.py """ _style_list = {} @@ -2574,6 +2575,8 @@ stroked. This is meant to be used to correct the location of the head so that it does not overshoot the destination point, but not all classes support it. + + .. plot:: mpl_examples/pylab_examples/fancyarrow_demo.py """ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-12-10 21:02:51
|
Revision: 6553 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6553&view=rev Author: jdh2358 Date: 2008-12-10 21:02:44 +0000 (Wed, 10 Dec 2008) Log Message: ----------- added some docs for linestyles and markers Modified Paths: -------------- trunk/matplotlib/doc/devel/coding_guide.rst trunk/matplotlib/doc/matplotlibrc trunk/matplotlib/doc/pyplots/whats_new_98_4_legend.py trunk/matplotlib/lib/matplotlib/lines.py Modified: trunk/matplotlib/doc/devel/coding_guide.rst =================================================================== --- trunk/matplotlib/doc/devel/coding_guide.rst 2008-12-10 17:29:21 UTC (rev 6552) +++ trunk/matplotlib/doc/devel/coding_guide.rst 2008-12-10 21:02:44 UTC (rev 6553) @@ -62,45 +62,12 @@ :file:`MANIFEST.in`. This file determines what goes into the source distribution of the mpl build. -* Keep the maintenance branch and trunk in sync where it makes sense. - If there is a bug on both that needs fixing, use `svnmerge.py +* Keep the maintenance branch (0.91) the latest release branch (eg + 0.98.4) and trunk in sync where it makes sense. If there is a bug + on both that needs fixing, use `svnmerge.py <http://www.orcaware.com/svn/wiki/Svnmerge.py>`_ to keep them in - sync. The basic procedure is: + sync. See :ref:`svn-merge` below. - * install ``svnmerge.py`` in your PATH:: - - > wget http://svn.collab.net/repos/svn/trunk/contrib/client-side/\ - svnmerge/svnmerge.py - - * get a svn copy of the maintenance branch and the trunk (see above) - - * Michael advises making the change on the branch and committing - it. Make sure you svn upped on the trunk and have no local - modifications, and then from the svn trunk do:: - - > svnmerge.py merge - - If you wish to merge only specific revisions (in an unusual - situation), do:: - - > svnmerge.py merge -rNNN1-NNN2 - - where the ``NNN`` are the revision numbers. Ranges are also - acceptable. - - The merge may have found some conflicts (code that must be - manually resolved). Correct those conflicts, build matplotlib and - test your choices. If you have resolved any conflicts, you can - let svn clean up the conflict files for you:: - - > svn -R resolved . - - ``svnmerge.py`` automatically creates a file containing the commit - messages, so you are ready to make the commit:: - - > svn commit -F svnmerge-commit-message.txt - - .. _style-guide: Style guide @@ -385,10 +352,84 @@ > python simple_plot.py -d module://my_backend +.. _svn-merge: +Using svn-merge +================ +The basic procedure is: +* install ``svnmerge.py`` in your PATH:: + > wget http://svn.collab.net/repos/svn/trunk/contrib/client-side/\ + svnmerge/svnmerge.py + +* get a svn copy of the maintenance branch and the trunk (see above) + +* Michael advises making the change on the branch and committing it. + Make sure you svn upped on the trunk and have no local + modifications, and then from the svn trunk do:: + + svnmerge.py merge + + If you wish to merge only specific revisions (in an unusual + situation), do:: + + > svnmerge.py merge -rNNN1-NNN2 + + where the ``NNN`` are the revision numbers. Ranges are also + acceptable. + + The merge may have found some conflicts (code that must be manually + resolved). Correct those conflicts, build matplotlib and test your + choices. If you have resolved any conflicts, you can let svn clean + up the conflict files for you:: + + > svn -R resolved . + + ``svnmerge.py`` automatically creates a file containing the commit + messages, so you are ready to make the commit:: + + > svn commit -F svnmerge-commit-message.txt + + +* You can add a new branch for the trunk to "track" using + "svnmerge.py init", e.g., from a working copy of the trunk:: + + > svnmerge.py init https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_98_4_maint + property 'svnmerge-integrated' set on '.' + + After doing a "svn commit" on this, this merge tracking is available + to everyone, so there's no need for anyone else to do the "svnmerge + init". I'll go ahead and commit this now. + + Now, the trunk is tracking two branches for merges, 0.91.x and + 0.98.4. This means that when doing a merge, one must manually + specify which branch to merge from using the "-S" parameter. You + can see which branches are available for merge using "svnmerge.py + avail":: + + > svnmerge.py avail + svnmerge: multiple sources found. Explicit source argument (-S/--source) required. + The merge sources available are: + /branches/v0_91_maint + /branches/v0_98_4_maint + + So to merge from 0.98.4, one would type:: + + > svnmerge.py --source v0_98_4_maint merge + + (rather than the "svnmerge.py merge" we used to do). + +* The tracking for 0.98.4 can be removed with the "svnmerge.py + uninit" command, e.g.:: + + > svnmerge.py --source v0_9_4_maint uninit + + This will make merging slightly easier, (since the -S parameter is + not required), and it is generally good practice in the long run to + not keep extra branches lying around. + .. _license-discussion: Licenses Modified: trunk/matplotlib/doc/matplotlibrc =================================================================== --- trunk/matplotlib/doc/matplotlibrc 2008-12-10 17:29:21 UTC (rev 6552) +++ trunk/matplotlib/doc/matplotlibrc 2008-12-10 21:02:44 UTC (rev 6553) @@ -43,7 +43,7 @@ ### LINES # See http://matplotlib.sourceforge.net/matplotlib.lines.html for more # information on line properties. -#lines.linewidth : 1.0 # line width in points +lines.linewidth : 1.5 # line width in points #lines.linestyle : - # solid line #lines.color : blue #lines.marker : None # the default marker Modified: trunk/matplotlib/doc/pyplots/whats_new_98_4_legend.py =================================================================== --- trunk/matplotlib/doc/pyplots/whats_new_98_4_legend.py 2008-12-10 17:29:21 UTC (rev 6552) +++ trunk/matplotlib/doc/pyplots/whats_new_98_4_legend.py 2008-12-10 21:02:44 UTC (rev 6553) @@ -4,12 +4,12 @@ ax = plt.subplot(111) -t1 = np.arange(0.0, 1.0, 0.1) +t1 = np.arange(0.0, 1.0, 0.01) for n in [1, 2, 3, 4]: plt.plot(t1, t1**n, label="n=%d"%(n,)) -leg = plt.legend(loc='best', ncol=4, mode="expand", shadow=True, fancybox=True) -leg.get_frame().set_alpha(0.7) +leg = plt.legend(loc='best', nncol=2, mode="expand", shadow=True, fancybox=True) +leg.get_frame().set_alpha(0.5) plt.show() Modified: trunk/matplotlib/lib/matplotlib/lines.py =================================================================== --- trunk/matplotlib/lib/matplotlib/lines.py 2008-12-10 17:29:21 UTC (rev 6552) +++ trunk/matplotlib/lib/matplotlib/lines.py 2008-12-10 21:02:44 UTC (rev 6553) @@ -313,7 +313,7 @@ 'return the pick radius used for containment tests' return self.pickradius - def set_pickradius(self,d): + def setpickradius(self,d): """Sets the pick radius used for containment tests ACCEPTS: float distance in points @@ -689,6 +689,7 @@ '' nothing ========= ========================== + ACCEPTS: [ '+' | '*' | ',' | '.' | '1' | '2' | '3' | '4' | '<' | '>' | 'D' | 'H' | '^' | '_' | 'd' | 'h' | 'o' | 'p' | 's' | 'v' | 'x' | '|' This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-12-11 01:10:47
|
Revision: 6559 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6559&view=rev Author: jdh2358 Date: 2008-12-11 01:10:35 +0000 (Thu, 11 Dec 2008) Log Message: ----------- figure/subplot and font_manager bugfixes Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/__init__.py trunk/matplotlib/lib/matplotlib/figure.py trunk/matplotlib/lib/matplotlib/font_manager.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-12-10 23:40:00 UTC (rev 6558) +++ trunk/matplotlib/CHANGELOG 2008-12-11 01:10:35 UTC (rev 6559) @@ -1,3 +1,6 @@ +2008-12-10 Added Michael's font_manager fix and Jae-Joon's + figure/subplot fix. Bumped version number to 0.98.5 - JDH + ================================================================= 2008-12-09 Released 0.98.4 at svn r6536 2008-12-08 Added mdehoon's native macosx backend from sf patch 2179017 - JDH Modified: trunk/matplotlib/lib/matplotlib/__init__.py =================================================================== --- trunk/matplotlib/lib/matplotlib/__init__.py 2008-12-10 23:40:00 UTC (rev 6558) +++ trunk/matplotlib/lib/matplotlib/__init__.py 2008-12-11 01:10:35 UTC (rev 6559) @@ -89,7 +89,7 @@ """ from __future__ import generators -__version__ = '0.98.4' +__version__ = '0.98.5rc' __revision__ = '$Revision$' __date__ = '$Date$' Modified: trunk/matplotlib/lib/matplotlib/figure.py =================================================================== --- trunk/matplotlib/lib/matplotlib/figure.py 2008-12-10 23:40:00 UTC (rev 6558) +++ trunk/matplotlib/lib/matplotlib/figure.py 2008-12-11 01:10:35 UTC (rev 6559) @@ -676,21 +676,21 @@ projection_class = get_projection_class(projection) - key = self._make_key(*args, **kwargs) - if key in self._seen: - ax = self._seen[key] - if isinstance(ax, projection_class): - self.sca(ax) - return ax - else: - self.axes.remove(ax) - self._axstack.remove(ax) + key = self._make_key(*args, **kwargs) + if key in self._seen: + ax = self._seen[key] + if isinstance(ax, projection_class): + self.sca(ax) + return ax + else: + self.axes.remove(ax) + self._axstack.remove(ax) - a = subplot_class_factory(projection_class)(self, *args, **kwargs) + a = subplot_class_factory(projection_class)(self, *args, **kwargs) + self._seen[key] = a self.axes.append(a) self._axstack.push(a) self.sca(a) - self._seen[key] = a return a add_subplot.__doc__ = dedent(add_subplot.__doc__) % { 'list': ", ".join(get_projection_names()), Modified: trunk/matplotlib/lib/matplotlib/font_manager.py =================================================================== --- trunk/matplotlib/lib/matplotlib/font_manager.py 2008-12-10 23:40:00 UTC (rev 6558) +++ trunk/matplotlib/lib/matplotlib/font_manager.py 2008-12-11 01:10:35 UTC (rev 6559) @@ -1068,7 +1068,7 @@ options = rcParams['font.' + family1] if family2 in options: idx = options.index(family2) - return 0.1 + return 0.1 * (float(idx) / len(options)) elif family1.lower() == family2.lower(): return 0.0 return 1.0 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jd...@us...> - 2008-12-11 03:05:08
|
Revision: 6560 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6560&view=rev Author: jdh2358 Date: 2008-12-11 03:04:59 +0000 (Thu, 11 Dec 2008) Log Message: ----------- added support for xlwt in exceltools Modified Paths: -------------- trunk/matplotlib/doc/devel/release_guide.rst trunk/matplotlib/lib/mpl_toolkits/exceltools.py Modified: trunk/matplotlib/doc/devel/release_guide.rst =================================================================== --- trunk/matplotlib/doc/devel/release_guide.rst 2008-12-11 01:10:35 UTC (rev 6559) +++ trunk/matplotlib/doc/devel/release_guide.rst 2008-12-11 03:04:59 UTC (rev 6560) @@ -46,6 +46,12 @@ * on windows, unix2dos the rc file +* make a branch of the svn revision that is released, in case we need + to do a bug fix release. Eg, from the top level of the mpl svn + tree, the one which has "branches", "tags" and "trunk", do:: + + > svn copy trunk/matplotlib branches/v0_98_4_maint + .. _release-uploading: Uploading Modified: trunk/matplotlib/lib/mpl_toolkits/exceltools.py =================================================================== --- trunk/matplotlib/lib/mpl_toolkits/exceltools.py 2008-12-11 01:10:35 UTC (rev 6559) +++ trunk/matplotlib/lib/mpl_toolkits/exceltools.py 2008-12-11 03:04:59 UTC (rev 6560) @@ -21,7 +21,15 @@ """ import copy import numpy as np -import pyExcelerator as excel + +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 matplotlib.cbook as cbook import matplotlib.mlab as mlab This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jo...@us...> - 2008-12-11 20:32:08
|
Revision: 6565 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6565&view=rev Author: jouni Date: 2008-12-11 20:32:04 +0000 (Thu, 11 Dec 2008) Log Message: ----------- Use subprocess.Popen instead of os.popen in dviread (Windows problem reported by Jorgen Stenarson) Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/dviread.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-12-11 18:59:00 UTC (rev 6564) +++ trunk/matplotlib/CHANGELOG 2008-12-11 20:32:04 UTC (rev 6565) @@ -1,3 +1,6 @@ +2008-12-11 Use subprocess.Popen instead of os.popen in dviread + (Windows problem reported by Jorgen Stenarson) - JKS + 2008-12-10 Added Michael's font_manager fix and Jae-Joon's figure/subplot fix. Bumped version number to 0.98.5 - JDH Modified: trunk/matplotlib/lib/matplotlib/dviread.py =================================================================== --- trunk/matplotlib/lib/matplotlib/dviread.py 2008-12-11 18:59:00 UTC (rev 6564) +++ trunk/matplotlib/lib/matplotlib/dviread.py 2008-12-11 20:32:04 UTC (rev 6565) @@ -21,8 +21,8 @@ import matplotlib import matplotlib.cbook as mpl_cbook import numpy as np -import os import struct +import subprocess _dvistate = mpl_cbook.Bunch(pre=0, outer=1, inpage=2, post_post=3, finale=4) @@ -742,25 +742,15 @@ doesn't use kpathsea, so what do we do? (TODO) """ - cmd = 'kpsewhich ' + cmd = ['kpsewhich'] if format is not None: - assert "'" not in format - cmd += "--format='" + format + "' " - assert "'" not in filename - cmd += "'" + filename + "'" - + cmd += ['--format=' + format] + cmd += [filename] + matplotlib.verbose.report('find_tex_file(%s): %s' \ % (filename,cmd), 'debug') - pipe = os.popen(cmd, 'r') - result = "" - while True: - data = _read_nointr(pipe) - if data == "": - break - result += data - pipe.close() - result = result.rstrip() - + pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE) + result = pipe.communicate()[0].rstrip() matplotlib.verbose.report('find_tex_file result: %s' % result, 'debug') return result This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2008-12-11 20:44:57
|
Revision: 6570 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6570&view=rev Author: mdboom Date: 2008-12-11 20:44:51 +0000 (Thu, 11 Dec 2008) Log Message: ----------- Add snap parameter to gc object and pass it all the way to Agg. Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/backend_bases.py trunk/matplotlib/src/_backend_agg.cpp trunk/matplotlib/src/_backend_agg.h Modified: trunk/matplotlib/lib/matplotlib/backend_bases.py =================================================================== --- trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-12-11 20:44:40 UTC (rev 6569) +++ trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-12-11 20:44:51 UTC (rev 6570) @@ -452,6 +452,7 @@ self._rgb = gc._rgb self._hatch = gc._hatch self._url = gc._url + self._snap = gc._snap def get_alpha(self): """ @@ -533,6 +534,19 @@ """ return self._url + def get_snap(self): + """ + returns the snap setting which may be: + + * True: snap vertices to the nearest pixel center + + * False: leave vertices as-is + + * None: (auto) If the path contains only rectilinear line + segments, round to the nearest pixel center + """ + return self._snap + def set_alpha(self, alpha): """ Set the alpha value used for blending - not supported on @@ -639,6 +653,19 @@ """ self._url = url + def set_snap(self, snap): + """ + Sets the snap setting which may be: + + * True: snap vertices to the nearest pixel center + + * False: leave vertices as-is + + * None: (auto) If the path contains only rectilinear line + segments, round to the nearest pixel center + """ + self._snap = snap + def set_hatch(self, hatch): """ Sets the hatch style for filling Modified: trunk/matplotlib/src/_backend_agg.cpp =================================================================== --- trunk/matplotlib/src/_backend_agg.cpp 2008-12-11 20:44:40 UTC (rev 6569) +++ trunk/matplotlib/src/_backend_agg.cpp 2008-12-11 20:44:51 UTC (rev 6570) @@ -148,6 +148,7 @@ _set_dashes(gc); _set_clip_rectangle(gc); _set_clip_path(gc); + _set_snap(gc); } GCAgg::GCAgg(double dpi) : @@ -254,6 +255,24 @@ } } +void +GCAgg::_set_snap( const Py::Object& gc) { + //set the snap setting + + _VERBOSE("GCAgg::_set_snap"); + + Py::Object method_obj = gc.getAttr("get_snap"); + Py::Callable method(method_obj); + Py::Object py_snap = method.apply(Py::Tuple()); + if (py_snap.isNone()) { + snap = SNAP_AUTO; + } else if (py_snap.isTrue()) { + snap = SNAP_TRUE; + } else { + snap = SNAP_FALSE; + } +} + const size_t RendererAgg::PIXELS_PER_INCH(96); @@ -336,43 +355,51 @@ } template<class Path> -bool should_snap(Path& path, const agg::trans_affine& trans) { +bool should_snap(const GCAgg& gc, Path& path, const agg::trans_affine& trans) { // If this contains only straight horizontal or vertical lines, it should be // quantized to the nearest pixels double x0, y0, x1, y1; unsigned code; - if (path.total_vertices() > 15) - return false; + switch (gc.snap) { + case GCAgg::SNAP_AUTO: + if (path.total_vertices() > 15) + return false; - code = path.vertex(&x0, &y0); - if (code == agg::path_cmd_stop) { - path.rewind(0); - return false; - } - trans.transform(&x0, &y0); + code = path.vertex(&x0, &y0); + if (code == agg::path_cmd_stop) { + path.rewind(0); + return false; + } + trans.transform(&x0, &y0); - while ((code = path.vertex(&x1, &y1)) != agg::path_cmd_stop) { - trans.transform(&x1, &y1); + while ((code = path.vertex(&x1, &y1)) != agg::path_cmd_stop) { + trans.transform(&x1, &y1); - switch (code) { - case agg::path_cmd_curve3: - case agg::path_cmd_curve4: - path.rewind(0); - return false; - case agg::path_cmd_line_to: - if (!(fabs(x0 - x1) < 1e-4 || fabs(y0 - y1) < 1e-4)) { - path.rewind(0); - return false; + switch (code) { + case agg::path_cmd_curve3: + case agg::path_cmd_curve4: + path.rewind(0); + return false; + case agg::path_cmd_line_to: + if (!(fabs(x0 - x1) < 1e-4 || fabs(y0 - y1) < 1e-4)) { + path.rewind(0); + return false; + } } + + x0 = x1; + y0 = y1; } - x0 = x1; - y0 = y1; + path.rewind(0); + return true; + case GCAgg::SNAP_FALSE: + return false; + case GCAgg::SNAP_TRUE: + return true; } - - path.rewind(0); - return true; + return false; } Py::Object @@ -487,6 +514,8 @@ if (args.size() == 6) face_obj = args[5]; + GCAgg gc = GCAgg(gc_obj, dpi); + // Deal with the difference in y-axis direction marker_trans *= agg::trans_affine_scaling(1.0, -1.0); trans *= agg::trans_affine_scaling(1.0, -1.0); @@ -497,14 +526,13 @@ // unfortunately, it can cause really small things to disappear. // Disabling for now to revisit at a later date. // const bool marker_snap = true; - bool marker_snap = should_snap(marker_path, marker_trans); + bool marker_snap = should_snap(gc, marker_path, marker_trans); transformed_path_t marker_path_transformed(marker_path, marker_trans); simplify_t marker_path_simplified(marker_path_transformed, marker_snap, false, width, height); curve_t marker_path_curve(marker_path_simplified); PathIterator path(path_obj); transformed_path_t path_transformed(path, trans); - GCAgg gc = GCAgg(gc_obj, dpi); path_transformed.rewind(0); facepair_t face = _get_rgba_face(face_obj, gc.alpha); @@ -934,7 +962,7 @@ trans *= agg::trans_affine_scaling(1.0, -1.0); trans *= agg::trans_affine_translation(0.0, (double)height); - bool snap = should_snap(path, trans); + bool snap = should_snap(gc, path, trans); bool simplify = path.should_simplify() && !face.first; transformed_path_t tpath(path, trans); @@ -1098,7 +1126,7 @@ } if (check_snap) { - snap = should_snap(path, trans); + snap = should_snap(gc, path, trans); if (snap) gc.isaa = false; else Modified: trunk/matplotlib/src/_backend_agg.h =================================================================== --- trunk/matplotlib/src/_backend_agg.h 2008-12-11 20:44:40 UTC (rev 6569) +++ trunk/matplotlib/src/_backend_agg.h 2008-12-11 20:44:51 UTC (rev 6570) @@ -110,7 +110,6 @@ agg::line_cap_e cap; agg::line_join_e join; - double linewidth; double alpha; agg::rgba color; @@ -124,6 +123,12 @@ double dashOffset; dash_t dashes; + enum { + SNAP_AUTO, + SNAP_FALSE, + SNAP_TRUE + } snap; + protected: agg::rgba get_color(const Py::Object& gc); double points_to_pixels( const Py::Object& points); @@ -133,6 +138,7 @@ void _set_clip_rectangle( const Py::Object& gc); void _set_clip_path( const Py::Object& gc); void _set_antialiased( const Py::Object& gc); + void _set_snap( const Py::Object& gc); }; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2008-12-11 20:45:16
|
Revision: 6571 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6571&view=rev Author: mdboom Date: 2008-12-11 20:45:12 +0000 (Thu, 11 Dec 2008) Log Message: ----------- More progress on programmatic snapping. Applied to markers (to prevent them from disappearing), and legend boxes. Modified Paths: -------------- trunk/matplotlib/lib/matplotlib/artist.py trunk/matplotlib/lib/matplotlib/legend.py trunk/matplotlib/lib/matplotlib/lines.py trunk/matplotlib/lib/matplotlib/patches.py trunk/matplotlib/src/_backend_agg.cpp Modified: trunk/matplotlib/lib/matplotlib/artist.py =================================================================== --- trunk/matplotlib/lib/matplotlib/artist.py 2008-12-11 20:44:51 UTC (rev 6570) +++ trunk/matplotlib/lib/matplotlib/artist.py 2008-12-11 20:45:12 UTC (rev 6571) @@ -54,6 +54,7 @@ self._url = None self.x_isdata = True # False to avoid updating Axes.dataLim with x self.y_isdata = True # with y + self._snap = None def remove(self): """ @@ -329,6 +330,32 @@ """ self._url = url + def get_snap(self): + """ + Returns the snap setting which may be: + + * True: snap vertices to the nearest pixel center + + * False: leave vertices as-is + + * None: (auto) If the path contains only rectilinear line + segments, round to the nearest pixel center + """ + return self._snap + + def set_snap(self, snap): + """ + Sets the snap setting which may be: + + * True: snap vertices to the nearest pixel center + + * False: leave vertices as-is + + * None: (auto) If the path contains only rectilinear line + segments, round to the nearest pixel center + """ + self._snap = snap + def get_figure(self): """ Return the :class:`~matplotlib.figure.Figure` instance the Modified: trunk/matplotlib/lib/matplotlib/legend.py =================================================================== --- trunk/matplotlib/lib/matplotlib/legend.py 2008-12-11 20:44:51 UTC (rev 6570) +++ trunk/matplotlib/lib/matplotlib/legend.py 2008-12-11 20:45:12 UTC (rev 6571) @@ -254,6 +254,7 @@ xy=(0.0, 0.0), width=1., height=1., facecolor='w', edgecolor='k', mutation_scale=self.fontsize, + snap=True ) # The width and height of the legendPatch will be set (in the Modified: trunk/matplotlib/lib/matplotlib/lines.py =================================================================== --- trunk/matplotlib/lib/matplotlib/lines.py 2008-12-11 20:44:51 UTC (rev 6570) +++ trunk/matplotlib/lib/matplotlib/lines.py 2008-12-11 20:45:12 UTC (rev 6571) @@ -453,6 +453,7 @@ join = self._solidjoinstyle gc.set_joinstyle(join) gc.set_capstyle(cap) + gc.set_snap(self.get_snap()) funcname = self._lineStyles.get(self._linestyle, '_draw_nothing') if funcname != '_draw_nothing': @@ -845,6 +846,7 @@ def _draw_point(self, renderer, gc, path, path_trans): w = renderer.points_to_pixels(self._markersize) * \ self._point_size_reduction * 0.5 + gc.set_snap(renderer.points_to_pixels(self._markersize) > 3.0) rgbFace = self._get_rgb_face() transform = Affine2D().scale(w) renderer.draw_markers( @@ -854,6 +856,7 @@ _draw_pixel_transform = Affine2D().translate(-0.5, -0.5) def _draw_pixel(self, renderer, gc, path, path_trans): rgbFace = self._get_rgb_face() + gc.set_snap(False) renderer.draw_markers(gc, Path.unit_rectangle(), self._draw_pixel_transform, path, path_trans, rgbFace) @@ -861,6 +864,7 @@ def _draw_circle(self, renderer, gc, path, path_trans): w = renderer.points_to_pixels(self._markersize) * 0.5 + gc.set_snap(renderer.points_to_pixels(self._markersize) > 3.0) rgbFace = self._get_rgb_face() transform = Affine2D().scale(w, w) renderer.draw_markers( @@ -870,6 +874,7 @@ _triangle_path = Path([[0.0, 1.0], [-1.0, -1.0], [1.0, -1.0], [0.0, 1.0]]) def _draw_triangle_up(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 5.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset, offset) rgbFace = self._get_rgb_face() @@ -878,6 +883,7 @@ def _draw_triangle_down(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 5.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset, -offset) rgbFace = self._get_rgb_face() @@ -886,6 +892,7 @@ def _draw_triangle_left(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 5.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset, offset).rotate_deg(90) rgbFace = self._get_rgb_face() @@ -894,6 +901,7 @@ def _draw_triangle_right(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 5.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset, offset).rotate_deg(-90) rgbFace = self._get_rgb_face() @@ -902,6 +910,7 @@ def _draw_square(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 2.0) side = renderer.points_to_pixels(self._markersize) transform = Affine2D().translate(-0.5, -0.5).scale(side) rgbFace = self._get_rgb_face() @@ -910,6 +919,7 @@ def _draw_diamond(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 5.0) side = renderer.points_to_pixels(self._markersize) transform = Affine2D().translate(-0.5, -0.5).rotate_deg(45).scale(side) rgbFace = self._get_rgb_face() @@ -918,6 +928,7 @@ def _draw_thin_diamond(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 3.0) offset = renderer.points_to_pixels(self._markersize) transform = Affine2D().translate(-0.5, -0.5) \ .rotate_deg(45).scale(offset * 0.6, offset) @@ -927,6 +938,7 @@ def _draw_pentagon(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 5.0) offset = 0.5 * renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset) rgbFace = self._get_rgb_face() @@ -934,6 +946,7 @@ path, path_trans, rgbFace) def _draw_star(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 5.0) offset = 0.5 * renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset) rgbFace = self._get_rgb_face() @@ -943,6 +956,7 @@ def _draw_hexagon1(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 5.0) offset = 0.5 * renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset) rgbFace = self._get_rgb_face() @@ -951,6 +965,7 @@ def _draw_hexagon2(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 5.0) offset = 0.5 * renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset).rotate_deg(30) rgbFace = self._get_rgb_face() @@ -960,6 +975,7 @@ _line_marker_path = Path([[0.0, -1.0], [0.0, 1.0]]) def _draw_vline(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 1.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset) renderer.draw_markers(gc, self._line_marker_path, transform, @@ -967,6 +983,7 @@ def _draw_hline(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 1.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset).rotate_deg(90) renderer.draw_markers(gc, self._line_marker_path, transform, @@ -975,6 +992,7 @@ _tickhoriz_path = Path([[0.0, 0.0], [1.0, 0.0]]) def _draw_tickleft(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 1.0) offset = renderer.points_to_pixels(self._markersize) marker_transform = Affine2D().scale(-offset, 1.0) renderer.draw_markers(gc, self._tickhoriz_path, marker_transform, @@ -982,6 +1000,7 @@ def _draw_tickright(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 1.0) offset = renderer.points_to_pixels(self._markersize) marker_transform = Affine2D().scale(offset, 1.0) renderer.draw_markers(gc, self._tickhoriz_path, marker_transform, @@ -990,6 +1009,7 @@ _tickvert_path = Path([[-0.0, 0.0], [-0.0, 1.0]]) def _draw_tickup(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 1.0) offset = renderer.points_to_pixels(self._markersize) marker_transform = Affine2D().scale(1.0, offset) renderer.draw_markers(gc, self._tickvert_path, marker_transform, @@ -997,6 +1017,7 @@ def _draw_tickdown(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 1.0) offset = renderer.points_to_pixels(self._markersize) marker_transform = Affine2D().scale(1.0, -offset) renderer.draw_markers(gc, self._tickvert_path, marker_transform, @@ -1008,6 +1029,7 @@ [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO]) def _draw_plus(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 3.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset) renderer.draw_markers(gc, self._plus_path, transform, @@ -1021,6 +1043,7 @@ Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO]) def _draw_tri_down(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 5.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset) renderer.draw_markers(gc, self._tri_path, transform, @@ -1028,6 +1051,7 @@ def _draw_tri_up(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 5.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset).rotate_deg(180) renderer.draw_markers(gc, self._tri_path, transform, @@ -1035,6 +1059,7 @@ def _draw_tri_left(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 5.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset).rotate_deg(90) renderer.draw_markers(gc, self._tri_path, transform, @@ -1042,6 +1067,7 @@ def _draw_tri_right(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 5.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset).rotate_deg(270) renderer.draw_markers(gc, self._tri_path, transform, @@ -1050,6 +1076,7 @@ _caret_path = Path([[-1.0, 1.5], [0.0, 0.0], [1.0, 1.5]]) def _draw_caretdown(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 3.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset) renderer.draw_markers(gc, self._caret_path, transform, @@ -1057,6 +1084,7 @@ def _draw_caretup(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 3.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset).rotate_deg(180) renderer.draw_markers(gc, self._caret_path, transform, @@ -1064,6 +1092,7 @@ def _draw_caretleft(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 3.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset).rotate_deg(270) renderer.draw_markers(gc, self._caret_path, transform, @@ -1071,6 +1100,7 @@ def _draw_caretright(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 3.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset).rotate_deg(90) renderer.draw_markers(gc, self._caret_path, transform, @@ -1082,6 +1112,7 @@ [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO]) def _draw_x(self, renderer, gc, path, path_trans): + gc.set_snap(renderer.points_to_pixels(self._markersize) >= 3.0) offset = 0.5*renderer.points_to_pixels(self._markersize) transform = Affine2D().scale(offset) renderer.draw_markers(gc, self._x_path, transform, Modified: trunk/matplotlib/lib/matplotlib/patches.py =================================================================== --- trunk/matplotlib/lib/matplotlib/patches.py 2008-12-11 20:44:51 UTC (rev 6570) +++ trunk/matplotlib/lib/matplotlib/patches.py 2008-12-11 20:45:12 UTC (rev 6571) @@ -278,6 +278,7 @@ self._set_gc_clip(gc) gc.set_capstyle('projecting') gc.set_url(self._url) + gc.set_snap(self._snap) if (not self.fill or self._facecolor is None or (cbook.is_string_like(self._facecolor) and self._facecolor.lower()=='none')): @@ -1435,7 +1436,6 @@ #adding quotes for now to work around tex bug treating '-' as itemize _table.append([cls.__name__, "'%s'"%name, argstr]) - return _pprint_table(_table) @@ -1505,7 +1505,7 @@ BoxStyle("Round, pad=0.2") - The following boxstyle classes are defined. + Following boxstyle classes are defined. %(AvailableBoxstyles)s @@ -2549,6 +2549,7 @@ A arrowstyle object can be either created as:: ArrowStyle.Fancy(head_length=.4, head_width=.4, tail_width=.4) + or:: ArrowStyle("Fancy", head_length=.4, head_width=.4, tail_width=.4) Modified: trunk/matplotlib/src/_backend_agg.cpp =================================================================== --- trunk/matplotlib/src/_backend_agg.cpp 2008-12-11 20:44:51 UTC (rev 6570) +++ trunk/matplotlib/src/_backend_agg.cpp 2008-12-11 20:45:12 UTC (rev 6571) @@ -968,8 +968,6 @@ transformed_path_t tpath(path, trans); simplify_t simplified(tpath, snap, simplify, width, height); curve_t curve(simplified); - if (snap) - gc.isaa = false; try { _draw_path(curve, has_clippath, face, gc); @@ -1127,10 +1125,7 @@ if (check_snap) { snap = should_snap(gc, path, trans); - if (snap) - gc.isaa = false; - else - gc.isaa = bool(Py::Int(antialiaseds[i % Naa])); + gc.isaa = bool(Py::Int(antialiaseds[i % Naa])); transformed_path_t tpath(path, trans); simplify_t simplified(tpath, snap, false, width, height); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cm...@us...> - 2008-12-12 03:05:03
|
Revision: 6573 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6573&view=rev Author: cmoad Date: 2008-12-12 03:04:53 +0000 (Fri, 12 Dec 2008) Log Message: ----------- minor rev bump to 0.98.5 Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/__init__.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-12-11 20:45:23 UTC (rev 6572) +++ trunk/matplotlib/CHANGELOG 2008-12-12 03:04:53 UTC (rev 6573) @@ -1,3 +1,6 @@ +================================================================= +2008-12-09 Released 0.98.5 at svn r6573 + 2008-12-11 Use subprocess.Popen instead of os.popen in dviread (Windows problem reported by Jorgen Stenarson) - JKS @@ -4,7 +7,8 @@ 2008-12-10 Added Michael's font_manager fix and Jae-Joon's figure/subplot fix. Bumped version number to 0.98.5 - JDH -================================================================= 2008-12-09 Released 0.98.4 at svn r6536 +================================================================= +2008-12-09 Released 0.98.4 at svn r6536 2008-12-08 Added mdehoon's native macosx backend from sf patch 2179017 - JDH Modified: trunk/matplotlib/lib/matplotlib/__init__.py =================================================================== --- trunk/matplotlib/lib/matplotlib/__init__.py 2008-12-11 20:45:23 UTC (rev 6572) +++ trunk/matplotlib/lib/matplotlib/__init__.py 2008-12-12 03:04:53 UTC (rev 6573) @@ -89,7 +89,7 @@ """ from __future__ import generators -__version__ = '0.98.5rc' +__version__ = '0.98.5' __revision__ = '$Revision$' __date__ = '$Date$' This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2008-12-12 12:58:51
|
Revision: 6582 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6582&view=rev Author: mdboom Date: 2008-12-12 12:58:46 +0000 (Fri, 12 Dec 2008) Log Message: ----------- Merged revisions 6581 via svnmerge from https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_98_5_maint ........ r6581 | mdboom | 2008-12-12 07:57:47 -0500 (Fri, 12 Dec 2008) | 1 line Trivial change to test merging ........ Modified Paths: -------------- trunk/matplotlib/TODO Property Changed: ---------------- trunk/matplotlib/ trunk/matplotlib/doc/pyplots/README Property changes on: trunk/matplotlib ___________________________________________________________________ Modified: svnmerge-integrated - /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6578 + /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6581 Modified: svn:mergeinfo - /branches/v0_91_maint:5753-5771 + /branches/v0_91_maint:5753-5771 /branches/v0_98_5_maint:6581 Modified: trunk/matplotlib/TODO =================================================================== --- trunk/matplotlib/TODO 2008-12-12 12:57:47 UTC (rev 6581) +++ trunk/matplotlib/TODO 2008-12-12 12:58:46 UTC (rev 6582) @@ -1,3 +1,5 @@ +-- Test merging from multiple branches. + -- ALMOST DONE : add print/save functionality. Currently you can save by right clicking on the fig window, but you must have nothing in front of the window. I suppose I need to first draw to a pixbuf. I would @@ -739,4 +741,4 @@ -- support zoom to rect in x or y only --- add Ryan's patch \ No newline at end of file +-- add Ryan's patch Property changes on: trunk/matplotlib/doc/pyplots/README ___________________________________________________________________ Modified: svn:mergeinfo - + /branches/v0_98_5_maint/doc/pyplots/README:6581 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <mme...@us...> - 2008-12-12 13:03:10
|
Revision: 6583 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6583&view=rev Author: mmetz_bn Date: 2008-12-12 13:03:04 +0000 (Fri, 12 Dec 2008) Log Message: ----------- labels for multiple data histograms Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/axes.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-12-12 12:58:46 UTC (rev 6582) +++ trunk/matplotlib/CHANGELOG 2008-12-12 13:03:04 UTC (rev 6583) @@ -1,3 +1,6 @@ +2008-12-12 Added support to asign labels to histograms of multiple + data. - MM + ================================================================= 2008-12-11 Released 0.98.5 at svn r6573 Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2008-12-12 12:58:46 UTC (rev 6582) +++ trunk/matplotlib/lib/matplotlib/axes.py 2008-12-12 13:03:04 UTC (rev 6583) @@ -29,6 +29,7 @@ iterable = cbook.iterable is_string_like = cbook.is_string_like +is_sequence_of_strings = cbook.is_sequence_of_strings def _process_plot_format(fmt): @@ -6531,6 +6532,10 @@ ax.hist(12+3*np.random.randn(1000), label='women', alpha=0.5) ax.legend() + label can also be a sequence of strings. If multiple data is + provided in *x*, the labels are asigned sequentially to the + histograms. + **Example:** .. plot:: mpl_examples/pylab_examples/histogram_demo.py @@ -6711,11 +6716,18 @@ label = kwargs.pop('label', '') - for patch in patches: + if is_string_like(label): + labels = [label] + ['_nolegend_']*(len(patches)-1) + elif is_sequence_of_strings: + labels = list(label) + ['_nolegend_']*(len(patches)-1) + else: + raise ValueError, 'invalid label: must be string or sequence of strings' + + for (patch, lbl) in zip(patches, labels): for p in patch: p.update(kwargs) - p.set_label(label) - label = '_nolegend_' + p.set_label(lbl) + lbl = '_nolegend_' if binsgiven: self.set_autoscale_on(False) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ds...@us...> - 2008-12-12 13:26:54
|
Revision: 6584 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6584&view=rev Author: dsdale Date: 2008-12-12 13:26:48 +0000 (Fri, 12 Dec 2008) Log Message: ----------- removed configobj and enthought.traits Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/examples/misc/rc_traits.py trunk/matplotlib/setup.cfg.template trunk/matplotlib/setup.py trunk/matplotlib/setupext.py Removed Paths: ------------- trunk/matplotlib/lib/configobj.py trunk/matplotlib/lib/enthought/ Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-12-12 13:03:04 UTC (rev 6583) +++ trunk/matplotlib/CHANGELOG 2008-12-12 13:26:48 UTC (rev 6584) @@ -1,3 +1,14 @@ +2008-12-12 Removed external packages: configobj and enthought.traits + which are only required by the experimental traited config + and are somewhat out of date. If needed, install them + independently, see: + + http://code.enthought.com/projects/traits + + and: + + http://www.voidspace.org.uk/python/configobj.html + 2008-12-12 Added support to asign labels to histograms of multiple data. - MM Modified: trunk/matplotlib/examples/misc/rc_traits.py =================================================================== --- trunk/matplotlib/examples/misc/rc_traits.py 2008-12-12 13:03:04 UTC (rev 6583) +++ trunk/matplotlib/examples/misc/rc_traits.py 2008-12-12 13:26:48 UTC (rev 6584) @@ -1,10 +1,7 @@ # Here is some example code showing how to define some representative # rc properties and construct a matplotlib artist using traits. -# Because matplotlib ships with enthought traits already, you can run -# this script with just matplotlib. Unfortunately, we do not ship the -# ex UI component so you can't test that part. I'm a bit of a traits -# newbie so there are probably better ways to do what I have done -# below. +# matplotlib does not ship with enthought.traits, so you will need to +# install it separately. import sys, os, re import enthought.traits.api as traits Deleted: trunk/matplotlib/lib/configobj.py =================================================================== --- trunk/matplotlib/lib/configobj.py 2008-12-12 13:03:04 UTC (rev 6583) +++ trunk/matplotlib/lib/configobj.py 2008-12-12 13:26:48 UTC (rev 6584) @@ -1,2279 +0,0 @@ -# configobj.py -# A config file reader/writer that supports nested sections in config files. -# Copyright (C) 2005-2006 Michael Foord, Nicola Larosa -# E-mail: fuzzyman AT voidspace DOT org DOT uk -# nico AT tekNico DOT net - -# ConfigObj 4 -# http://www.voidspace.org.uk/python/configobj.html - -# Released subject to the BSD License -# Please see http://www.voidspace.org.uk/python/license.shtml - -# Scripts maintained at http://www.voidspace.org.uk/python/index.shtml -# For information about bugfixes, updates and support, please join the -# ConfigObj mailing list: -# http://lists.sourceforge.net/lists/listinfo/configobj-develop -# Comments, suggestions and bug reports welcome. - -from __future__ import generators - -import sys -INTP_VER = sys.version_info[:2] -if INTP_VER < (2, 2): - raise RuntimeError("Python v.2.2 or later needed") - -import os, re -compiler = None -try: - import compiler -except ImportError: - # for IronPython - pass -from types import StringTypes -from warnings import warn -try: - from codecs import BOM_UTF8, BOM_UTF16, BOM_UTF16_BE, BOM_UTF16_LE -except ImportError: - # Python 2.2 does not have these - # UTF-8 - BOM_UTF8 = '\xef\xbb\xbf' - # UTF-16, little endian - BOM_UTF16_LE = '\xff\xfe' - # UTF-16, big endian - BOM_UTF16_BE = '\xfe\xff' - if sys.byteorder == 'little': - # UTF-16, native endianness - BOM_UTF16 = BOM_UTF16_LE - else: - # UTF-16, native endianness - BOM_UTF16 = BOM_UTF16_BE - -# A dictionary mapping BOM to -# the encoding to decode with, and what to set the -# encoding attribute to. -BOMS = { - BOM_UTF8: ('utf_8', None), - BOM_UTF16_BE: ('utf16_be', 'utf_16'), - BOM_UTF16_LE: ('utf16_le', 'utf_16'), - BOM_UTF16: ('utf_16', 'utf_16'), - } -# All legal variants of the BOM codecs. -# TODO: the list of aliases is not meant to be exhaustive, is there a -# better way ? -BOM_LIST = { - 'utf_16': 'utf_16', - 'u16': 'utf_16', - 'utf16': 'utf_16', - 'utf-16': 'utf_16', - 'utf16_be': 'utf16_be', - 'utf_16_be': 'utf16_be', - 'utf-16be': 'utf16_be', - 'utf16_le': 'utf16_le', - 'utf_16_le': 'utf16_le', - 'utf-16le': 'utf16_le', - 'utf_8': 'utf_8', - 'u8': 'utf_8', - 'utf': 'utf_8', - 'utf8': 'utf_8', - 'utf-8': 'utf_8', - } - -# Map of encodings to the BOM to write. -BOM_SET = { - 'utf_8': BOM_UTF8, - 'utf_16': BOM_UTF16, - 'utf16_be': BOM_UTF16_BE, - 'utf16_le': BOM_UTF16_LE, - None: BOM_UTF8 - } - -try: - from validate import VdtMissingValue -except ImportError: - VdtMissingValue = None - -try: - enumerate -except NameError: - def enumerate(obj): - """enumerate for Python 2.2.""" - i = -1 - for item in obj: - i += 1 - yield i, item - -try: - True, False -except NameError: - True, False = 1, 0 - - -__version__ = '4.4.0-mpl' - -__revision__ = '$Id: configobj.py 156 2006-01-31 14:57:08Z fuzzyman $' - -__docformat__ = "restructuredtext en" - -__all__ = ( - '__version__', - 'DEFAULT_INDENT_TYPE', - 'DEFAULT_INTERPOLATION', - 'ConfigObjError', - 'NestingError', - 'ParseError', - 'DuplicateError', - 'ConfigspecError', - 'ConfigObj', - 'SimpleVal', - 'InterpolationError', - 'InterpolationLoopError', - 'MissingInterpolationOption', - 'RepeatSectionError', - 'UnreprError', - 'UnknownType', - '__docformat__', - 'flatten_errors', -) - -DEFAULT_INTERPOLATION = 'configparser' -DEFAULT_INDENT_TYPE = ' ' -MAX_INTERPOL_DEPTH = 10 - -OPTION_DEFAULTS = { - 'interpolation': True, - 'raise_errors': False, - 'list_values': True, - 'create_empty': False, - 'file_error': False, - 'configspec': None, - 'stringify': True, - # option may be set to one of ('', ' ', '\t') - 'indent_type': None, - 'encoding': None, - 'default_encoding': None, - 'unrepr': False, - 'write_empty_values': False, -} - - -def getObj(s): - s = "a=" + s - if compiler is None: - raise ImportError('compiler module not available') - p = compiler.parse(s) - return p.getChildren()[1].getChildren()[0].getChildren()[1] - -class UnknownType(Exception): - pass - -class Builder: - - def build(self, o): - m = getattr(self, 'build_' + o.__class__.__name__, None) - if m is None: - raise UnknownType(o.__class__.__name__) - return m(o) - - def build_List(self, o): - return map(self.build, o.getChildren()) - - def build_Const(self, o): - return o.value - - def build_Dict(self, o): - d = {} - i = iter(map(self.build, o.getChildren())) - for el in i: - d[el] = i.next() - return d - - def build_Tuple(self, o): - return tuple(self.build_List(o)) - - def build_Name(self, o): - if o.name == 'None': - return None - if o.name == 'True': - return True - if o.name == 'False': - return False - - # An undefinted Name - raise UnknownType('Undefined Name') - - def build_Add(self, o): - real, imag = map(self.build_Const, o.getChildren()) - try: - real = float(real) - except TypeError: - raise UnknownType('Add') - if not isinstance(imag, complex) or imag.real != 0.0: - raise UnknownType('Add') - return real+imag - - def build_Getattr(self, o): - parent = self.build(o.expr) - return getattr(parent, o.attrname) - - def build_UnarySub(self, o): - return -self.build_Const(o.getChildren()[0]) - - def build_UnaryAdd(self, o): - return self.build_Const(o.getChildren()[0]) - -def unrepr(s): - if not s: - return s - return Builder().build(getObj(s)) - -def _splitlines(instring): - """Split a string on lines, without losing line endings or truncating.""" - - -class ConfigObjError(SyntaxError): - """ - This is the base class for all errors that ConfigObj raises. - It is a subclass of SyntaxError. - """ - def __init__(self, message='', line_number=None, line=''): - self.line = line - self.line_number = line_number - self.message = message - SyntaxError.__init__(self, message) - -class NestingError(ConfigObjError): - """ - This error indicates a level of nesting that doesn't match. - """ - -class ParseError(ConfigObjError): - """ - This error indicates that a line is badly written. - It is neither a valid ``key = value`` line, - nor a valid section marker line. - """ - -class DuplicateError(ConfigObjError): - """ - The keyword or section specified already exists. - """ - -class ConfigspecError(ConfigObjError): - """ - An error occured whilst parsing a configspec. - """ - -class InterpolationError(ConfigObjError): - """Base class for the two interpolation errors.""" - -class InterpolationLoopError(InterpolationError): - """Maximum interpolation depth exceeded in string interpolation.""" - - def __init__(self, option): - InterpolationError.__init__( - self, - 'interpolation loop detected in value "%s".' % option) - -class RepeatSectionError(ConfigObjError): - """ - This error indicates additional sections in a section with a - ``__many__`` (repeated) section. - """ - -class MissingInterpolationOption(InterpolationError): - """A value specified for interpolation was missing.""" - - def __init__(self, option): - InterpolationError.__init__( - self, - 'missing option "%s" in interpolation.' % option) - -class UnreprError(ConfigObjError): - """An error parsing in unrepr mode.""" - - -class InterpolationEngine(object): - """ - A helper class to help perform string interpolation. - - This class is an abstract base class; its descendants perform - the actual work. - """ - - # compiled regexp to use in self.interpolate() - _KEYCRE = re.compile(r"%\(([^)]*)\)s") - - def __init__(self, section): - # the Section instance that "owns" this engine - self.section = section - - def interpolate(self, key, value): - def recursive_interpolate(key, value, section, backtrail): - """The function that does the actual work. - - ``value``: the string we're trying to interpolate. - ``section``: the section in which that string was found - ``backtrail``: a dict to keep track of where we've been, - to detect and prevent infinite recursion loops - - This is similar to a depth-first-search algorithm. - """ - # Have we been here already? - if backtrail.has_key((key, section.name)): - # Yes - infinite loop detected - raise InterpolationLoopError(key) - # Place a marker on our backtrail so we won't come back here again - backtrail[(key, section.name)] = 1 - - # Now start the actual work - match = self._KEYCRE.search(value) - while match: - # The actual parsing of the match is implementation-dependent, - # so delegate to our helper function - k, v, s = self._parse_match(match) - if k is None: - # That's the signal that no further interpolation is needed - replacement = v - else: - # Further interpolation may be needed to obtain final value - replacement = recursive_interpolate(k, v, s, backtrail) - # Replace the matched string with its final value - start, end = match.span() - value = ''.join((value[:start], replacement, value[end:])) - new_search_start = start + len(replacement) - # Pick up the next interpolation key, if any, for next time - # through the while loop - match = self._KEYCRE.search(value, new_search_start) - - # Now safe to come back here again; remove marker from backtrail - del backtrail[(key, section.name)] - - return value - - # Back in interpolate(), all we have to do is kick off the recursive - # function with appropriate starting values - value = recursive_interpolate(key, value, self.section, {}) - return value - - def _fetch(self, key): - """Helper function to fetch values from owning section. - - Returns a 2-tuple: the value, and the section where it was found. - """ - # switch off interpolation before we try and fetch anything ! - save_interp = self.section.main.interpolation - self.section.main.interpolation = False - - # Start at section that "owns" this InterpolationEngine - current_section = self.section - while True: - # try the current section first - val = current_section.get(key) - if val is not None: - break - # try "DEFAULT" next - val = current_section.get('DEFAULT', {}).get(key) - if val is not None: - break - # move up to parent and try again - # top-level's parent is itself - if current_section.parent is current_section: - # reached top level, time to give up - break - current_section = current_section.parent - - # restore interpolation to previous value before returning - self.section.main.interpolation = save_interp - if val is None: - raise MissingInterpolationOption(key) - return val, current_section - - def _parse_match(self, match): - """Implementation-dependent helper function. - - Will be passed a match object corresponding to the interpolation - key we just found (e.g., "%(foo)s" or "$foo"). Should look up that - key in the appropriate config file section (using the ``_fetch()`` - helper function) and return a 3-tuple: (key, value, section) - - ``key`` is the name of the key we're looking for - ``value`` is the value found for that key - ``section`` is a reference to the section where it was found - - ``key`` and ``section`` should be None if no further - interpolation should be performed on the resulting value - (e.g., if we interpolated "$$" and returned "$"). - """ - raise NotImplementedError - - -class ConfigParserInterpolation(InterpolationEngine): - """Behaves like ConfigParser.""" - _KEYCRE = re.compile(r"%\(([^)]*)\)s") - - def _parse_match(self, match): - key = match.group(1) - value, section = self._fetch(key) - return key, value, section - - -class TemplateInterpolation(InterpolationEngine): - """Behaves like string.Template.""" - _delimiter = '$' - _KEYCRE = re.compile(r""" - \$(?: - (?P<escaped>\$) | # Two $ signs - (?P<named>[_a-z][_a-z0-9]*) | # $name format - {(?P<braced>[^}]*)} # ${name} format - ) - """, re.IGNORECASE | re.VERBOSE) - - def _parse_match(self, match): - # Valid name (in or out of braces): fetch value from section - key = match.group('named') or match.group('braced') - if key is not None: - value, section = self._fetch(key) - return key, value, section - # Escaped delimiter (e.g., $$): return single delimiter - if match.group('escaped') is not None: - # Return None for key and section to indicate it's time to stop - return None, self._delimiter, None - # Anything else: ignore completely, just return it unchanged - return None, match.group(), None - -interpolation_engines = { - 'configparser': ConfigParserInterpolation, - 'template': TemplateInterpolation, -} - -class Section(dict): - """ - A dictionary-like object that represents a section in a config file. - - It does string interpolation if the 'interpolation' attribute - of the 'main' object is set to True. - - Interpolation is tried first from this object, then from the 'DEFAULT' - section of this object, next from the parent and its 'DEFAULT' section, - and so on until the main object is reached. - - A Section will behave like an ordered dictionary - following the - order of the ``scalars`` and ``sections`` attributes. - You can use this to change the order of members. - - Iteration follows the order: scalars, then sections. - """ - - def __init__(self, parent, depth, main, indict=None, name=None): - """ - * parent is the section above - * depth is the depth level of this section - * main is the main ConfigObj - * indict is a dictionary to initialise the section with - """ - if indict is None: - indict = {} - dict.__init__(self) - # used for nesting level *and* interpolation - self.parent = parent - # used for the interpolation attribute - self.main = main - # level of nesting depth of this Section - self.depth = depth - # the sequence of scalar values in this Section - self.scalars = [] - # the sequence of sections in this Section - self.sections = [] - # purely for information - self.name = name - # for comments :-) - self.comments = {} - self.inline_comments = {} - # for the configspec - self.configspec = {} - self._order = [] - self._configspec_comments = {} - self._configspec_inline_comments = {} - self._cs_section_comments = {} - self._cs_section_inline_comments = {} - # for defaults - self.defaults = [] - # - # we do this explicitly so that __setitem__ is used properly - # (rather than just passing to ``dict.__init__``) - for entry in indict: - self[entry] = indict[entry] - - def _interpolate(self, key, value): - try: - # do we already have an interpolation engine? - engine = self._interpolation_engine - except AttributeError: - # not yet: first time running _interpolate(), so pick the engine - name = self.main.interpolation - if name == True: # note that "if name:" would be incorrect here - # backwards-compatibility: interpolation=True means use default - name = DEFAULT_INTERPOLATION - name = name.lower() # so that "Template", "template", etc. all work - class_ = interpolation_engines.get(name, None) - if class_ is None: - # invalid value for self.main.interpolation - self.main.interpolation = False - return value - else: - # save reference to engine so we don't have to do this again - engine = self._interpolation_engine = class_(self) - # let the engine do the actual work - return engine.interpolate(key, value) - - def __getitem__(self, key): - """Fetch the item and do string interpolation.""" - val = dict.__getitem__(self, key) - if self.main.interpolation and isinstance(val, StringTypes): - return self._interpolate(key, val) - return val - - def __setitem__(self, key, value, unrepr=False): - """ - Correctly set a value. - - Making dictionary values Section instances. - (We have to special case 'Section' instances - which are also dicts) - - Keys must be strings. - Values need only be strings (or lists of strings) if - ``main.stringify`` is set. - - `unrepr`` must be set when setting a value to a dictionary, without - creating a new sub-section. - """ - if not isinstance(key, StringTypes): - raise ValueError, 'The key "%s" is not a string.' % key - # add the comment - if not self.comments.has_key(key): - self.comments[key] = [] - self.inline_comments[key] = '' - # remove the entry from defaults - if key in self.defaults: - self.defaults.remove(key) - # - if isinstance(value, Section): - if not self.has_key(key): - self.sections.append(key) - dict.__setitem__(self, key, value) - elif isinstance(value, dict) and not unrepr: - # First create the new depth level, - # then create the section - if not self.has_key(key): - self.sections.append(key) - new_depth = self.depth + 1 - dict.__setitem__( - self, - key, - Section( - self, - new_depth, - self.main, - indict=value, - name=key)) - else: - if not self.has_key(key): - self.scalars.append(key) - if not self.main.stringify: - if isinstance(value, StringTypes): - pass - elif isinstance(value, (list, tuple)): - for entry in value: - if not isinstance(entry, StringTypes): - raise TypeError, ( - 'Value is not a string "%s".' % entry) - else: - raise TypeError, 'Value is not a string "%s".' % value - dict.__setitem__(self, key, value) - - def __delitem__(self, key): - """Remove items from the sequence when deleting.""" - dict. __delitem__(self, key) - if key in self.scalars: - self.scalars.remove(key) - else: - self.sections.remove(key) - del self.comments[key] - del self.inline_comments[key] - - def get(self, key, default=None): - """A version of ``get`` that doesn't bypass string interpolation.""" - try: - return self[key] - except KeyError: - return default - - def update(self, indict): - """ - A version of update that uses our ``__setitem__``. - """ - for entry in indict: - self[entry] = indict[entry] - - def pop(self, key, *args): - """ """ - val = dict.pop(self, key, *args) - if key in self.scalars: - del self.comments[key] - del self.inline_comments[key] - self.scalars.remove(key) - elif key in self.sections: - del self.comments[key] - del self.inline_comments[key] - self.sections.remove(key) - if self.main.interpolation and isinstance(val, StringTypes): - return self._interpolate(key, val) - return val - - def popitem(self): - """Pops the first (key,val)""" - sequence = (self.scalars + self.sections) - if not sequence: - raise KeyError, ": 'popitem(): dictionary is empty'" - key = sequence[0] - val = self[key] - del self[key] - return key, val - - def clear(self): - """ - A version of clear that also affects scalars/sections - Also clears comments and configspec. - - Leaves other attributes alone : - depth/main/parent are not affected - """ - dict.clear(self) - self.scalars = [] - self.sections = [] - self.comments = {} - self.inline_comments = {} - self.configspec = {} - - def setdefault(self, key, default=None): - """A version of setdefault that sets sequence if appropriate.""" - try: - return self[key] - except KeyError: - self[key] = default - return self[key] - - def items(self): - """ """ - return zip((self.scalars + self.sections), self.values()) - - def keys(self): - """ """ - return (self.scalars + self.sections) - - def values(self): - """ """ - return [self[key] for key in (self.scalars + self.sections)] - - def iteritems(self): - """ """ - return iter(self.items()) - - def iterkeys(self): - """ """ - return iter((self.scalars + self.sections)) - - __iter__ = iterkeys - - def itervalues(self): - """ """ - return iter(self.values()) - - def __repr__(self): - return '{%s}' % ', '.join([('%s: %s' % (repr(key), repr(self[key]))) - for key in (self.scalars + self.sections)]) - - __str__ = __repr__ - - # Extra methods - not in a normal dictionary - - def dict(self): - """ - Return a deepcopy of self as a dictionary. - - All members that are ``Section`` instances are recursively turned to - ordinary dictionaries - by calling their ``dict`` method. - - >>> n = a.dict() - >>> n == a - 1 - >>> n is a - 0 - """ - newdict = {} - for entry in self: - this_entry = self[entry] - if isinstance(this_entry, Section): - this_entry = this_entry.dict() - elif isinstance(this_entry, list): - # create a copy rather than a reference - this_entry = list(this_entry) - elif isinstance(this_entry, tuple): - # create a copy rather than a reference - this_entry = tuple(this_entry) - newdict[entry] = this_entry - return newdict - - def merge(self, indict): - """ - A recursive update - useful for merging config files. - - >>> a = '''[section1] - ... option1 = True - ... [[subsection]] - ... more_options = False - ... # end of file'''.splitlines() - >>> b = '''# File is user.ini - ... [section1] - ... option1 = False - ... # end of file'''.splitlines() - >>> c1 = ConfigObj(b) - >>> c2 = ConfigObj(a) - >>> c2.merge(c1) - >>> c2 - {'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}} - """ - for key, val in indict.items(): - if (key in self and isinstance(self[key], dict) and - isinstance(val, dict)): - self[key].merge(val) - else: - self[key] = val - - def rename(self, oldkey, newkey): - """ - Change a keyname to another, without changing position in sequence. - - Implemented so that transformations can be made on keys, - as well as on values. (used by encode and decode) - - Also renames comments. - """ - if oldkey in self.scalars: - the_list = self.scalars - elif oldkey in self.sections: - the_list = self.sections - else: - raise KeyError, 'Key "%s" not found.' % oldkey - pos = the_list.index(oldkey) - # - val = self[oldkey] - dict.__delitem__(self, oldkey) - dict.__setitem__(self, newkey, val) - the_list.remove(oldkey) - the_list.insert(pos, newkey) - comm = self.comments[oldkey] - inline_comment = self.inline_comments[oldkey] - del self.comments[oldkey] - del self.inline_comments[oldkey] - self.comments[newkey] = comm - self.inline_comments[newkey] = inline_comment - - def walk(self, function, raise_errors=True, - call_on_sections=False, **keywargs): - """ - Walk every member and call a function on the keyword and value. - - Return a dictionary of the return values - - If the function raises an exception, raise the errror - unless ``raise_errors=False``, in which case set the return value to - ``False``. - - Any unrecognised keyword arguments you pass to walk, will be pased on - to the function you pass in. - - Note: if ``call_on_sections`` is ``True`` then - on encountering a - subsection, *first* the function is called for the *whole* subsection, - and then recurses into it's members. This means your function must be - able to handle strings, dictionaries and lists. This allows you - to change the key of subsections as well as for ordinary members. The - return value when called on the whole subsection has to be discarded. - - See the encode and decode methods for examples, including functions. - - .. caution:: - - You can use ``walk`` to transform the names of members of a section - but you mustn't add or delete members. - - >>> config = '''[XXXXsection] - ... XXXXkey = XXXXvalue'''.splitlines() - >>> cfg = ConfigObj(config) - >>> cfg - {'XXXXsection': {'XXXXkey': 'XXXXvalue'}} - >>> def transform(section, key): - ... val = section[key] - ... newkey = key.replace('XXXX', 'CLIENT1') - ... section.rename(key, newkey) - ... if isinstance(val, (tuple, list, dict)): - ... pass - ... else: - ... val = val.replace('XXXX', 'CLIENT1') - ... section[newkey] = val - >>> cfg.walk(transform, call_on_sections=True) - {'CLIENT1section': {'CLIENT1key': None}} - >>> cfg - {'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}} - """ - out = {} - # scalars first - for i in range(len(self.scalars)): - entry = self.scalars[i] - try: - val = function(self, entry, **keywargs) - # bound again in case name has changed - entry = self.scalars[i] - out[entry] = val - except Exception: - if raise_errors: - raise - else: - entry = self.scalars[i] - out[entry] = False - # then sections - for i in range(len(self.sections)): - entry = self.sections[i] - if call_on_sections: - try: - function(self, entry, **keywargs) - except Exception: - if raise_errors: - raise - else: - entry = self.sections[i] - out[entry] = False - # bound again in case name has changed - entry = self.sections[i] - # previous result is discarded - out[entry] = self[entry].walk( - function, - raise_errors=raise_errors, - call_on_sections=call_on_sections, - **keywargs) - return out - - def decode(self, encoding): - """ - Decode all strings and values to unicode, using the specified encoding. - - Works with subsections and list values. - - Uses the ``walk`` method. - - Testing ``encode`` and ``decode``. - >>> m = ConfigObj(a) - >>> m.decode('ascii') - >>> def testuni(val): - ... for entry in val: - ... if not isinstance(entry, unicode): - ... print >> sys.stderr, type(entry) - ... raise AssertionError, 'decode failed.' - ... if isinstance(val[entry], dict): - ... testuni(val[entry]) - ... elif not isinstance(val[entry], unicode): - ... raise AssertionError, 'decode failed.' - >>> testuni(m) - >>> m.encode('ascii') - >>> a == m - 1 - """ - warn('use of ``decode`` is deprecated.', DeprecationWarning) - def decode(section, key, encoding=encoding, warn=True): - """ """ - val = section[key] - if isinstance(val, (list, tuple)): - newval = [] - for entry in val: - newval.append(entry.decode(encoding)) - elif isinstance(val, dict): - newval = val - else: - newval = val.decode(encoding) - newkey = key.decode(encoding) - section.rename(key, newkey) - section[newkey] = newval - # using ``call_on_sections`` allows us to modify section names - self.walk(decode, call_on_sections=True) - - def encode(self, encoding): - """ - Encode all strings and values from unicode, - using the specified encoding. - - Works with subsections and list values. - Uses the ``walk`` method. - """ - warn('use of ``encode`` is deprecated.', DeprecationWarning) - def encode(section, key, encoding=encoding): - """ """ - val = section[key] - if isinstance(val, (list, tuple)): - newval = [] - for entry in val: - newval.append(entry.encode(encoding)) - elif isinstance(val, dict): - newval = val - else: - newval = val.encode(encoding) - newkey = key.encode(encoding) - section.rename(key, newkey) - section[newkey] = newval - self.walk(encode, call_on_sections=True) - - def istrue(self, key): - """A deprecated version of ``as_bool``.""" - warn('use of ``istrue`` is deprecated. Use ``as_bool`` method ' - 'instead.', DeprecationWarning) - return self.as_bool(key) - - def as_bool(self, key): - """ - Accepts a key as input. The corresponding value must be a string or - the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to - retain compatibility with Python 2.2. - - If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns - ``True``. - - If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns - ``False``. - - ``as_bool`` is not case sensitive. - - Any other input will raise a ``ValueError``. - - >>> a = ConfigObj() - >>> a['a'] = 'fish' - >>> a.as_bool('a') - Traceback (most recent call last): - ValueError: Value "fish" is neither True nor False - >>> a['b'] = 'True' - >>> a.as_bool('b') - 1 - >>> a['b'] = 'off' - >>> a.as_bool('b') - 0 - """ - val = self[key] - if val == True: - return True - elif val == False: - return False - else: - try: - if not isinstance(val, StringTypes): - raise KeyError - else: - return self.main._bools[val.lower()] - except KeyError: - raise ValueError('Value "%s" is neither True nor False' % val) - - def as_int(self, key): - """ - A convenience method which coerces the specified value to an integer. - - If the value is an invalid literal for ``int``, a ``ValueError`` will - be raised. - - >>> a = ConfigObj() - >>> a['a'] = 'fish' - >>> a.as_int('a') - Traceback (most recent call last): - ValueError: invalid literal for int(): fish - >>> a['b'] = '1' - >>> a.as_int('b') - 1 - >>> a['b'] = '3.2' - >>> a.as_int('b') - Traceback (most recent call last): - ValueError: invalid literal for int(): 3.2 - """ - return int(self[key]) - - def as_float(self, key): - """ - A convenience method which coerces the specified value to a float. - - If the value is an invalid literal for ``float``, a ``ValueError`` will - be raised. - - >>> a = ConfigObj() - >>> a['a'] = 'fish' - >>> a.as_float('a') - Traceback (most recent call last): - ValueError: invalid literal for float(): fish - >>> a['b'] = '1' - >>> a.as_float('b') - 1.0 - >>> a['b'] = '3.2' - >>> a.as_float('b') - 3.2000000000000002 - """ - return float(self[key]) - - -class ConfigObj(Section): - """An object to read, create, and write config files.""" - - _keyword = re.compile(r'''^ # line start - (\s*) # indentation - ( # keyword - (?:".*?")| # double quotes - (?:'.*?')| # single quotes - (?:[^'"=].*?) # no quotes - ) - \s*=\s* # divider - (.*) # value (including list values and comments) - $ # line end - ''', - re.VERBOSE) - - _sectionmarker = re.compile(r'''^ - (\s*) # 1: indentation - ((?:\[\s*)+) # 2: section marker open - ( # 3: section name open - (?:"\s*\S.*?\s*")| # at least one non-space with double quotes - (?:'\s*\S.*?\s*')| # at least one non-space with single quotes - (?:[^'"\s].*?) # at least one non-space unquoted - ) # section name close - ((?:\s*\])+) # 4: section marker close - \s*(\#.*)? # 5: optional comment - $''', - re.VERBOSE) - - # this regexp pulls list values out as a single string - # or single values and comments - # FIXME: this regex adds a '' to the end of comma terminated lists - # workaround in ``_handle_value`` - _valueexp = re.compile(r'''^ - (?: - (?: - ( - (?: - (?: - (?:".*?")| # double quotes - (?:'.*?')| # single quotes - (?:[^'",\#][^,\#]*?) # unquoted - ) - \s*,\s* # comma - )* # match all list items ending in a comma (if any) - ) - ( - (?:".*?")| # double quotes - (?:'.*?')| # single quotes - (?:[^'",\#\s][^,]*?)| # unquoted - (?:(?<!,)) # Empty value - )? # last item in a list - or string value - )| - (,) # alternatively a single comma - empty list - ) - \s*(\#.*)? # optional comment - $''', - re.VERBOSE) - - # use findall to get the members of a list value - _listvalueexp = re.compile(r''' - ( - (?:".*?")| # double quotes - (?:'.*?')| # single quotes - (?:[^'",\#].*?) # unquoted - ) - \s*,\s* # comma - ''', - re.VERBOSE) - - # this regexp is used for the value - # when lists are switched off - _nolistvalue = re.compile(r'''^ - ( - (?:".*?")| # double quotes - (?:'.*?')| # single quotes - (?:[^'"\#].*?)| # unquoted - (?:) # Empty value - ) - \s*(\#.*)? # optional comment - $''', - re.VERBOSE) - - # regexes for finding triple quoted values on one line - _single_line_single = re.compile(r"^'''(.*?)'''\s*(#.*)?$") - _single_line_double = re.compile(r'^"""(.*?)"""\s*(#.*)?$') - _multi_line_single = re.compile(r"^(.*?)'''\s*(#.*)?$") - _multi_line_double = re.compile(r'^(.*?)"""\s*(#.*)?$') - - _triple_quote = { - "'''": (_single_line_single, _multi_line_single), - '"""': (_single_line_double, _multi_line_double), - } - - # Used by the ``istrue`` Section method - _bools = { - 'yes': True, 'no': False, - 'on': True, 'off': False, - '1': True, '0': False, - 'true': True, 'false': False, - } - - def __init__(self, infile=None, options=None, **kwargs): - """ - Parse or create a config file object. - - ``ConfigObj(infile=None, options=None, **kwargs)`` - """ - if infile is None: - infile = [] - if options is None: - options = {} - else: - options = dict(options) - # keyword arguments take precedence over an options dictionary - options.update(kwargs) - # init the superclass - Section.__init__(self, self, 0, self) - # - defaults = OPTION_DEFAULTS.copy() - for entry in options.keys(): - if entry not in defaults.keys(): - raise TypeError, 'Unrecognised option "%s".' % entry - # TODO: check the values too. - # - # Add any explicit options to the defaults - defaults.update(options) - # - # initialise a few variables - self.filename = None - self._errors = [] - self.raise_errors = defaults['raise_errors'] - self.interpolation = defaults['interpolation'] - self.list_values = defaults['list_values'] - self.create_empty = defaults['create_empty'] - self.file_error = defaults['file_error'] - self.stringify = defaults['stringify'] - self.indent_type = defaults['indent_type'] - self.encoding = defaults['encoding'] - self.default_encoding = defaults['default_encoding'] - self.BOM = False - self.newlines = None - self.write_empty_values = defaults['write_empty_values'] - self.unrepr = defaults['unrepr'] - # - self.initial_comment = [] - self.final_comment = [] - # - self._terminated = False - # - if isinstance(infile, StringTypes): - self.filename = infile - if os.path.isfile(infile): - infile = open(infile).read() or [] - elif self.file_error: - # raise an error if the file doesn't exist - raise IOError, 'Config file not found: "%s".' % self.filename - else: - # file doesn't already exist - if self.create_empty: - # this is a good test that the filename specified - # isn't impossible - like on a non existent device - h = open(infile, 'w') - h.write('') - h.close() - infile = [] - elif isinstance(infile, (list, tuple)): - infile = list(infile) - elif isinstance(infile, dict): - # initialise self - # the Section class handles creating subsections - if isinstance(infile, ConfigObj): - # get a copy of our ConfigObj - infile = infile.dict() - for entry in infile: - self[entry] = infile[entry] - del self._errors - if defaults['configspec'] is not None: - self._handle_configspec(defaults['configspec']) - else: - self.configspec = None - return - elif hasattr(infile, 'read'): - # This supports file like objects - infile = infile.read() or [] - # needs splitting into lines - but needs doing *after* decoding - # in case it's not an 8 bit encoding - else: - raise TypeError, ('infile must be a filename,' - ' file like object, or list of lines.') - # - if infile: - # don't do it for the empty ConfigObj - infile = self._handle_bom(infile) - # infile is now *always* a list - # - # Set the newlines attribute (first line ending it finds) - # and strip trailing '\n' or '\r' from lines - for line in infile: - if (not line) or (line[-1] not in ('\r', '\n', '\r\n')): - continue - for end in ('\r\n', '\n', '\r'): - if line.endswith(end): - self.newlines = end - break - break - if infile[-1] and infile[-1] in ('\r', '\n', '\r\n'): - self._terminated = True - infile = [line.rstrip('\r\n') for line in infile] - # - self._parse(infile) - # if we had any errors, now is the time to raise them - if self._errors: - info = "at line %s." % self._errors[0].line_number - if len(self._errors) > 1: - msg = ("Parsing failed with several errors.\nFirst error %s" % - info) - error = ConfigObjError(msg) - else: - error = self._errors[0] - # set the errors attribute; it's a list of tuples: - # (error_type, message, line_number) - error.errors = self._errors - # set the config attribute - error.config = self - raise error - # delete private attributes - del self._errors - # - if defaults['configspec'] is None: - self.configspec = None - else: - self._handle_configspec(defaults['configspec']) - - def __repr__(self): - return 'ConfigObj({%s})' % ', '.join( - [('%s: %s' % (repr(key), repr(self[key]))) for key in - (self.scalars + self.sections)]) - - def _handle_bom(self, infile): - """ - Handle any BOM, and decode if necessary. - - If an encoding is specified, that *must* be used - but the BOM should - still be removed (and the BOM attribute set). - - (If the encoding is wrongly specified, then a BOM for an alternative - encoding won't be discovered or removed.) - - If an encoding is not specified, UTF8 or UTF16 BOM will be detected and - removed. The BOM attribute will be set. UTF16 will be decoded to - unicode. - - NOTE: This method must not be called with an empty ``infile``. - - Specifying the *wrong* encoding is likely to cause a - ``UnicodeDecodeError``. - - ``infile`` must always be returned as a list of lines, but may be - passed in as a single string. - """ - if ((self.encoding is not None) and - (self.encoding.lower() not in BOM_LIST)): - # No need to check for a BOM - # the encoding specified doesn't have one - # just decode - return self._decode(infile, self.encoding) - # - if isinstance(infile, (list, tuple)): - line = infile[0] - else: - line = infile - if self.encoding is not None: - # encoding explicitly supplied - # And it could have an associated BOM - # TODO: if encoding is just UTF16 - we ought to check for both - # TODO: big endian and little endian versions. - enc = BOM_LIST[self.encoding.lower()] - if enc == 'utf_16': - # For UTF16 we try big endian and little endian - for BOM, (encoding, final_encoding) in BOMS.items(): - if not final_encoding: - # skip UTF8 - continue - if infile.startswith(BOM): - ### BOM discovered - ##self.BOM = True - # Don't need to remove BOM - return self._decode(infile, encoding) - # - # If we get this far, will *probably* raise a DecodeError - # As it doesn't appear to start with a BOM - return self._decode(infile, self.encoding) - # - # Must be UTF8 - BOM = BOM_SET[enc] - if not line.startswith(BOM): - return self._decode(infile, self.encoding) - # - newline = line[len(BOM):] - # - # BOM removed - if isinstance(infile, (list, tuple)): - infile[0] = newline - else: - infile = newline - self.BOM = True - return self._decode(infile, self.encoding) - # - # No encoding specified - so we need to check for UTF8/UTF16 - for BOM, (encoding, final_encoding) in BOMS.items(): - if not line.startswith(BOM): - continue - else: - # BOM discovered - self.encoding = final_encoding - if not final_encoding: - self.BOM = True - # UTF8 - # remove BOM - newline = line[len(BOM):] - if isinstance(infile, (list, tuple)): - infile[0] = newline - else: - infile = newline - # UTF8 - don't decode - if isinstance(infile, StringTypes): - return infile.splitlines(True) - else: - return infile - # UTF16 - have to decode - return self._decode(infile, encoding) - # - # No BOM discovered and no encoding specified, just return - if isinstance(infile, StringTypes): - # infile read from a file will be a single string - return infile.splitlines(True) - else: - return infile - - def _a_to_u(self, aString): - """Decode ASCII strings to unicode if a self.encoding is specified.""" - if self.encoding: - return aString.decode('ascii') - else: - return aString - - def _decode(self, infile, encoding): - """ - Decode infile to unicode. Using the specified encoding. - - if is a string, it also needs converting to a list. - """ - if isinstance(infile, StringTypes): - # can't be unicode - # NOTE: Could raise a ``UnicodeDecodeError`` - return infile.decode(encoding).splitlines(True) - for i, line in enumerate(infile): - if not isinstance(line, unicode): - # NOTE: The isinstance test here handles mixed lists of unicode/string - # NOTE: But the decode will break on any non-string values - # NOTE: Or could raise a ``UnicodeDecodeError`` - infile[i] = line.decode(encoding) - return infile - - def _decode_element(self, line): - """Decode element to unicode if necessary.""" - if not self.encoding: - return line - if isinstance(line, str) and self.default_encoding: - return line.decode(self.default_encoding) - return line - - def _str(self, value): - """ - Used by ``stringify`` within validate, to turn non-string values - into strings. - """ - if not isinstance(value, StringTypes): - return str(value) - else: - return value - - def _parse(self, infile): - """Actually parse the config file.""" - temp_list_values = self.list_values - if self.unrepr: - self.list_values = False - comment_list = [] - done_start = False - this_section = self - maxline = len(infile) - 1 - cur_index = -1 - reset_comment = False - while cur_index < maxline: - if reset_comment: - comment_list = [] - cur_index += 1 - line = infile[cur_index] - sline = line.strip() - # do we have anything on the line ? - if not sline or sline.startswith('#'): - reset_comment = False - comment_list.append(line) - continue - if not done_start: - # preserve initial comment - self.initial_comment = comment_list - comment_list = [] - done_start = True - reset_comment = True - # first we check if it's a section marker - mat = self._sectionmarker.match(line) - if mat is not None: - # is a section line - (indent, sect_open, sect_name, sect_close, comment) = ( - mat.groups()) - if indent and (self.indent_type is None): - self.indent_type = indent - cur_depth = sect_open.count('[') - if cur_depth != sect_close.count(']'): - self._handle_error( - "Cannot compute the section depth at line %s.", - NestingError, infile, cur_index) - continue - # - if cur_depth < this_section.depth: - # the new section is dropping back to a previous level - try: - parent = self._match_depth( - this_section, - cur_depth).parent - except SyntaxError: - self._handle_error( - "Cannot compute nesting level at line %s.", - NestingError, infile, cur_index) - continue - elif cur_depth == this_section.depth: - # the new section is a sibling of the current section - parent = this_section.parent - elif cur_depth == this_section.depth + 1: - # the new section is a child the current section - parent = this_section - else: - self._handle_error( - "Section too nested at line %s.", - NestingError, infile, cur_index) - # - sect_name = self._unquote(sect_name) - if parent.has_key(sect_name): - self._handle_error( - 'Duplicate section name at line %s.', - DuplicateError, infile, cur_index) - continue - # create the new section - this_section = Section( - parent, - cur_depth, - self, - name=sect_name) - parent[sect_name] = this_section - parent.inline_comments[sect_name] = comment - parent.comments[sect_name] = comment_list - continue - # - # it's not a section marker, - # so it should be a valid ``key = value`` line - mat = self._keyword.match(line) - if mat is None: - # it neither matched as a keyword - # or a section marker - self._handle_error( - 'Invalid line at line "%s".', - ParseError, infile, cur_index) - else: - # is a keyword value - # value will include any inline comment - (indent, key, value) = mat.groups() - if indent and (self.indent_type is None): - self.indent_type = indent - # check for a multiline value - if value[:3] in ['"""', "'''"]: - try: - (value, comment, cur_index) = self._multiline( - value, infile, cur_index, maxline) - except SyntaxError: - self._handle_error( - 'Parse error in value at line %s.', - ParseError, infile, cur_index) - continue - else: - if self.unrepr: - comment = '' - try: - value = unrepr(value) - except Exception, e: - if type(e) == UnknownType: - msg = 'Unknown name or type in value at line %s.' - else: - msg = 'Parse error in value at line %s.' - self._handle_error(msg, UnreprError, infile, - cur_index) - continue - else: - if self.unrepr: - comment = '' - try: - value = unrepr(value) - except Exception, e: - if isinstance(e, UnknownType): - msg = 'Unknown name or type in value at line %s.' - else: - msg = 'Parse error in value at line %s.' - self._handle_error(msg, UnreprError, infile, - cur_index) - continue - else: - # extract comment and lists - try: - (value, comment) = self._handle_value(value) - except SyntaxError: - self._handle_error( - 'Parse error in value at line %s.', - ParseError, infile, cur_index) - continue - # - key = self._unquote(key) - if this_section.has_key(key): - self._handle_error( - 'Duplicate keyword name at line %s.', - DuplicateError, infile, cur_index) - continue - # add the key. - # we set unrepr because if we have got this far we will never - # be creating a new section - this_section.__setitem__(key, value, unrepr=True) - this_section.inline_comments[key] = comment - this_section.comments[key] = comment_list - continue - # - if self.indent_type is None: - # no indentation used, set the type accordingly - self.indent_type = '' - # - if self._terminated: - comment_list.append('') - # preserve the final comment - if not self and not self.initial_comment: - self.initial_comment = comment_list - elif not reset_comment: - self.final_comment = comment_list - self.list_values = temp_list_values - - def _match_depth(self, sect, depth): - """ - Given a section and a depth level, walk back through the sections - parents to see if the depth level matches a previous section. - - Return a reference to the right section, - or raise a SyntaxError. - """ - while depth < sect.depth: - if sect is sect.parent: - # we've reached the top level already - raise SyntaxError - sect = sect.parent - if sect.depth == depth: - return sect - # shouldn't get here - raise SyntaxError - - def _handle_error(self, text, ErrorClass, infile, cur_index): - """ - Handle an error according to the error settings. - - Either raise the error or store it. - The e... [truncated message content] |
From: <md...@us...> - 2008-12-12 13:39:02
|
Revision: 6586 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6586&view=rev Author: mdboom Date: 2008-12-12 13:38:57 +0000 (Fri, 12 Dec 2008) Log Message: ----------- Merged revisions 6585 via svnmerge from https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_98_5_maint ........ r6585 | mdboom | 2008-12-12 08:34:06 -0500 (Fri, 12 Dec 2008) | 1 line Cleanup svnmerge docs; add Andrew's git docs ........ Modified Paths: -------------- trunk/matplotlib/doc/devel/coding_guide.rst trunk/matplotlib/doc/faq/installing_faq.rst Property Changed: ---------------- trunk/matplotlib/ trunk/matplotlib/doc/pyplots/README Property changes on: trunk/matplotlib ___________________________________________________________________ Modified: svnmerge-integrated - /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6581 + /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6585 Modified: svn:mergeinfo - /branches/v0_91_maint:5753-5771 /branches/v0_98_5_maint:6581 + /branches/v0_91_maint:5753-5771 /branches/v0_98_5_maint:6581,6585 Modified: trunk/matplotlib/doc/devel/coding_guide.rst =================================================================== --- trunk/matplotlib/doc/devel/coding_guide.rst 2008-12-12 13:34:06 UTC (rev 6585) +++ trunk/matplotlib/doc/devel/coding_guide.rst 2008-12-12 13:38:57 UTC (rev 6586) @@ -9,6 +9,8 @@ Version control =============== +.. _using-svn: + svn checkouts ------------- @@ -52,7 +54,7 @@ * Can you pass :file:`examples/tests/backend_driver.py`? This is our poor man's unit test. -* Can you add a test to file:`unit/nose_tests.py` to test your changes? +* Can you add a test to :file:`unit/nose_tests.py` to test your changes? * If you have altered extension code, do you pass :file:`unit/memleak_hawaii.py`? @@ -68,6 +70,170 @@ <http://www.orcaware.com/svn/wiki/Svnmerge.py>`_ to keep them in sync. See :ref:`svn-merge` below. +.. _svn-merge: + +Using svnmerge +-------------- + +svnmerge is useful for making bugfixes to a maintenance branch, and +then bringing those changes into the trunk. + +The basic procedure is: + +* install ``svnmerge.py`` in your PATH:: + + > wget http://svn.collab.net/repos/svn/trunk/contrib/client-side/\ + svnmerge/svnmerge.py + +* get a svn checkout of the branch you'll be making bugfixes to and + the trunk (see above) + +* Create and commit the bugfix on the branch. + +* Then make sure you svn upped on the trunk and have no local + modifications, and then from your checkout of the svn trunk do:: + + svnmerge.py merge -S BRANCHNAME + + Where BRANCHNAME is the name of the branch to merge *from*, + e.g. v0_98_5_maint. + + If you wish to merge only specific revisions (in an unusual + situation), do:: + + > svnmerge.py merge -rNNN1-NNN2 + + where the ``NNN`` are the revision numbers. Ranges are also + acceptable. + + The merge may have found some conflicts (code that must be manually + resolved). Correct those conflicts, build matplotlib and test your + choices. If you have resolved any conflicts, you can let svn clean + up the conflict files for you:: + + > svn -R resolved . + + ``svnmerge.py`` automatically creates a file containing the commit + messages, so you are ready to make the commit:: + + > svn commit -F svnmerge-commit-message.txt + +Setting up svnmerge +~~~~~~~~~~~~~~~~~~~ + +.. note:: + The following applies only to release managers when there is + a new release. Most developers will not have to concern themselves + with this. + +* Creating a new branch from the trunk (if the release version is + 0.98.5 at revision 6573):: + + > svn copy \ + https://matplotlib.svn.sf.net/svnroot/matplotlib/trunk/matplotlib@6573 \ + https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_98_5_maint \ + -m "Creating maintenance branch for 0.98.5" + +* You can add a new branch for the trunk to "track" using + "svnmerge.py init", e.g., from a working copy of the trunk:: + + > svnmerge.py init https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_98_5_maint + property 'svnmerge-integrated' set on '.' + + After doing a "svn commit" on this, this merge tracking is available + to everyone, so there's no need for anyone else to do the "svnmerge + init". + +* Tracking can later be removed with the "svnmerge.py uninit" command, + e.g.:: + + > svnmerge.py -S v0_9_5_maint uninit + +.. _using-git: + +Using git +--------- + +Some matplotlib developers are experimenting with using git on top of +the subversion repository. Developers are not required to use git, as +subversion will remain the canonical central repository for the +foreseeable future. + +Cloning the git mirror +~~~~~~~~~~~~~~~~~~~~~~ + +There is an experimental `matplotlib github mirror`_ of the subversion +repository. To make a local clone of it in the directory ``mpl.git``, +enter the following commands:: + + # This will create your copy in the mpl.git directory + git clone git://github.com/astraw/matplotlib.git mpl.git + cd mpl.git + git config --add remote.origin.fetch +refs/remotes/*:refs/remotes/* + git fetch + git svn init --trunk=trunk/matplotlib --tags=tags https://matplotlib.svn.sourceforge.net/svnroot/matplotlib + + # Now just get the latest svn revisions from the SourceForge SVN repository + git svn fetch -r 6300:HEAD + +.. _matplotlib github mirror: http://github.com/astraw/matplotlib + +To install from this cloned repository, use the commands in the +:ref:`svn installation <install-svn>` section:: + + > cd mpl.git + > python setup.py install + +Using git +~~~~~~~~~ + +The following is a suggested workflow for git/git-svn. + +Start with a virgin tree in sync with the svn trunk on the git branch +"master":: + + git checkout master + git svn rebase + +To create a new, local branch called "whizbang-branch":: + + git checkout -b whizbang-branch + +Do make commits to the local branch:: + + # hack on a bunch of files + git add bunch of files + git commit -m "modified a bunch of files" + # repeat this as necessary + +Now, go back to the master branch and append the history of your branch +to the master branch, which will end up as the svn trunk:: + + git checkout master + git svn rebase # Ensure we have most recent svn + git rebase whizbang-branch # Append whizbang changes to master branch + git svn dcommit -n # Check that this will apply to svn + git svn dcommit # Actually apply to svn + +Finally, you may want to continue working on your whizbang-branch, so +rebase it to the new master:: + + git checkout whizbang-branch + git rebase master + +A note about git write access +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The matplotlib developers need to figure out if there should be write +access to the git repository. This implies using the personal URL +(``gi...@gi...:astraw/matplotlib.git``) rather than the public URL +(``git://github.com/astraw/matplotlib.git``) for the +repository. However, doing so may make life complicated in the sense +that then there are two writeable matplotlib repositories, which must +be synced to prevent divergence. This is probably not an +insurmountable problem, but it is a problem that the developers should +reach a consensus about. Watch this space... + .. _style-guide: Style guide @@ -352,84 +518,7 @@ > python simple_plot.py -d module://my_backend -.. _svn-merge: -Using svn-merge -================ - -The basic procedure is: - -* install ``svnmerge.py`` in your PATH:: - - > wget http://svn.collab.net/repos/svn/trunk/contrib/client-side/\ - svnmerge/svnmerge.py - -* get a svn copy of the maintenance branch and the trunk (see above) - -* Michael advises making the change on the branch and committing it. - Make sure you svn upped on the trunk and have no local - modifications, and then from the svn trunk do:: - - svnmerge.py merge - - If you wish to merge only specific revisions (in an unusual - situation), do:: - - > svnmerge.py merge -rNNN1-NNN2 - - where the ``NNN`` are the revision numbers. Ranges are also - acceptable. - - The merge may have found some conflicts (code that must be manually - resolved). Correct those conflicts, build matplotlib and test your - choices. If you have resolved any conflicts, you can let svn clean - up the conflict files for you:: - - > svn -R resolved . - - ``svnmerge.py`` automatically creates a file containing the commit - messages, so you are ready to make the commit:: - - > svn commit -F svnmerge-commit-message.txt - - -* You can add a new branch for the trunk to "track" using - "svnmerge.py init", e.g., from a working copy of the trunk:: - - > svnmerge.py init https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_98_4_maint - property 'svnmerge-integrated' set on '.' - - After doing a "svn commit" on this, this merge tracking is available - to everyone, so there's no need for anyone else to do the "svnmerge - init". I'll go ahead and commit this now. - - Now, the trunk is tracking two branches for merges, 0.91.x and - 0.98.4. This means that when doing a merge, one must manually - specify which branch to merge from using the "-S" parameter. You - can see which branches are available for merge using "svnmerge.py - avail":: - - > svnmerge.py avail - svnmerge: multiple sources found. Explicit source argument (-S/--source) required. - The merge sources available are: - /branches/v0_91_maint - /branches/v0_98_4_maint - - So to merge from 0.98.4, one would type:: - - > svnmerge.py --source v0_98_4_maint merge - - (rather than the "svnmerge.py merge" we used to do). - -* The tracking for 0.98.4 can be removed with the "svnmerge.py - uninit" command, e.g.:: - - > svnmerge.py --source v0_9_4_maint uninit - - This will make merging slightly easier, (since the -S parameter is - not required), and it is generally good practice in the long run to - not keep extra branches lying around. - .. _license-discussion: Licenses Modified: trunk/matplotlib/doc/faq/installing_faq.rst =================================================================== --- trunk/matplotlib/doc/faq/installing_faq.rst 2008-12-12 13:34:06 UTC (rev 6585) +++ trunk/matplotlib/doc/faq/installing_faq.rst 2008-12-12 13:38:57 UTC (rev 6586) @@ -95,7 +95,7 @@ .. _install-svn: Install from svn -======================== +================ Checking out the main source:: @@ -106,53 +106,13 @@ > cd matplotlib > python setup.py install +For more information on Subversion usage, see :ref:`using-svn`. + Install from git ================ -There is an experimental `matplotlib github mirror`_ of the subversion -repository. To make a local clone of it in the directory ``mpl.git``, -enter the following commands:: +See :ref:`using-git`. - # This will create your copy in the mpl.git directory - git clone git://github.com/astraw/matplotlib.git mpl.git - cd mpl.git - git config --add remote.origin.fetch +refs/remotes/*:refs/remotes/* - git fetch - git svn init --trunk=trunk/matplotlib --tags=tags https://matplotlib.svn.sourceforge.net/svnroot/matplotlib - - # Now just get the latest svn revisions from the SourceForge SVN repository - git svn fetch -r 6300:HEAD - -.. _matplotlib github mirror: http://github.com/astraw/matplotlib - -To install from this cloned repository, use the commands in the -:ref:`svn installation <install-svn>` section. - -To update your git repository with the latest svn updates from SourceForge:: - - git svn rebase - -To list what changes will be committed to svn:: - - git svn dcommit -n - -To commit your changes to svn:: - - git svn dcommit - -A note about git write access ------------------------------ - -The matplotlib developers need to figure out if there should be write -access to the git repository. This implies using the personal URL -(``gi...@gi...:astraw/matplotlib.git``) rather than the public URL -(``git://github.com/astraw/matplotlib.git``) for the -repository. However, doing so may make life complicated in the sense -that then there are two writeable matplotlib repositories, which must -be synced to prevent divergence. This is probably not an -insurmountable problem, but it is a problem that the developers should -reach a consensus about. Watch this space... - Backends ======== Property changes on: trunk/matplotlib/doc/pyplots/README ___________________________________________________________________ Modified: svn:mergeinfo - /branches/v0_98_5_maint/doc/pyplots/README:6581 + /branches/v0_98_5_maint/doc/pyplots/README:6581,6585 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2008-12-12 13:42:26
|
Revision: 6588 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6588&view=rev Author: mdboom Date: 2008-12-12 13:42:22 +0000 (Fri, 12 Dec 2008) Log Message: ----------- Merged revisions 6587 via svnmerge from https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_98_5_maint ........ r6587 | mdboom | 2008-12-12 08:39:32 -0500 (Fri, 12 Dec 2008) | 1 line Fix cross-reference in docs ........ Modified Paths: -------------- trunk/matplotlib/doc/faq/installing_faq.rst Property Changed: ---------------- trunk/matplotlib/ trunk/matplotlib/doc/pyplots/README Property changes on: trunk/matplotlib ___________________________________________________________________ Modified: svnmerge-integrated - /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6585 + /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6587 Modified: svn:mergeinfo - /branches/v0_91_maint:5753-5771 /branches/v0_98_5_maint:6581,6585 + /branches/v0_91_maint:5753-5771 /branches/v0_98_5_maint:6581,6585,6587 Modified: trunk/matplotlib/doc/faq/installing_faq.rst =================================================================== --- trunk/matplotlib/doc/faq/installing_faq.rst 2008-12-12 13:39:32 UTC (rev 6587) +++ trunk/matplotlib/doc/faq/installing_faq.rst 2008-12-12 13:42:22 UTC (rev 6588) @@ -106,7 +106,8 @@ > cd matplotlib > python setup.py install -For more information on Subversion usage, see :ref:`using-svn`. +There is more information on :ref:`using Subversion <using-svn>` in +the developer docs. Install from git ================ Property changes on: trunk/matplotlib/doc/pyplots/README ___________________________________________________________________ Modified: svn:mergeinfo - /branches/v0_98_5_maint/doc/pyplots/README:6581,6585 + /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <mme...@us...> - 2008-12-12 14:05:25
|
Revision: 6590 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6590&view=rev Author: mmetz_bn Date: 2008-12-12 14:05:20 +0000 (Fri, 12 Dec 2008) Log Message: ----------- Merged revisions 6589 via svnmerge from https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_98_5_maint ........ r6589 | mmetz_bn | 2008-12-12 14:58:24 +0100 (Fri, 12 Dec 2008) | 1 line fix warning in hist for numpy 1.2 ........ Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/axes.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-12-12 13:58:24 UTC (rev 6589) +++ trunk/matplotlib/CHANGELOG 2008-12-12 14:05:20 UTC (rev 6590) @@ -1,3 +1,5 @@ +2008-12-12 Fixed warning in hist() with numpy 1.2 - MM + 2008-12-12 Removed external packages: configobj and enthought.traits which are only required by the experimental traited config and are somewhat out of date. If needed, install them Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2008-12-12 13:58:24 UTC (rev 6589) +++ trunk/matplotlib/lib/matplotlib/axes.py 2008-12-12 14:05:20 UTC (rev 6590) @@ -6573,10 +6573,10 @@ binsgiven = (cbook.iterable(bins) or range != None) # check the version of the numpy - if np.__version__ < "1.2": # version 1.1 + if np.__version__ < "1.3": # version 1.1 and 1.2 hist_kwargs = dict(range=range, normed=bool(normed), new=True) - else: # version 1.2 and later, drop new=True + else: # version 1.3 and later, drop new=True hist_kwargs = dict(range=range, normed=bool(normed)) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <mme...@us...> - 2008-12-12 14:55:26
|
Revision: 6592 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6592&view=rev Author: mmetz_bn Date: 2008-12-12 14:55:12 +0000 (Fri, 12 Dec 2008) Log Message: ----------- Added support for weights to axes.hist() Modified Paths: -------------- trunk/matplotlib/CHANGELOG trunk/matplotlib/lib/matplotlib/axes.py Modified: trunk/matplotlib/CHANGELOG =================================================================== --- trunk/matplotlib/CHANGELOG 2008-12-12 14:47:38 UTC (rev 6591) +++ trunk/matplotlib/CHANGELOG 2008-12-12 14:55:12 UTC (rev 6592) @@ -1,3 +1,6 @@ +2008-12-12 Added support for the numpy.histogram() weights parameter + to the axes hist() method. Docs taken from numpy - MM + 2008-12-12 Fixed warning in hist() with numpy 1.2 - MM 2008-12-12 Removed external packages: configobj and enthought.traits Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2008-12-12 14:47:38 UTC (rev 6591) +++ trunk/matplotlib/lib/matplotlib/axes.py 2008-12-12 14:55:12 UTC (rev 6592) @@ -6422,9 +6422,10 @@ #### Data analysis - def hist(self, x, bins=10, range=None, normed=False, cumulative=False, - bottom=None, histtype='bar', align='mid', - orientation='vertical', rwidth=None, log=False, **kwargs): + def hist(self, x, bins=10, range=None, normed=False, weights=None, + cumulative=False, bottom=None, histtype='bar', align='mid', + orientation='vertical', rwidth=None, log=False, + **kwargs): """ call signature:: @@ -6468,6 +6469,13 @@ pdf, bins, patches = ax.hist(...) print np.sum(pdf * np.diff(bins)) + *weights* + An array of weights, of the same shape as *x*. Each value in + *x* only contributes its associated weight towards the bin + count (instead of 1). If *normed* is True, the weights are + normalized, so that the integral of the density over the range + remains 1. + *cumulative*: If *True*, then a histogram is computed where each bin gives the counts in that bin plus all bins for smaller values. @@ -6543,7 +6551,7 @@ if not self._hold: self.cla() # NOTE: the range keyword overwrites the built-in func range !!! - # needs to be fixed in with numpy !!! + # needs to be fixed in numpy !!! if kwargs.get('width') is not None: raise DeprecationWarning( @@ -6566,8 +6574,30 @@ tx.append( np.array(x[i]) ) x = tx else: - raise ValueError, 'Can not use providet data to create a histogram' + raise ValueError, 'Can not use provided data to create a histogram' + if weights is not None: + try: + w = np.transpose(np.array(weights)) + if len(w.shape)==1: + w.shape = (1, w.shape[0]) + except: + if iterable(weights[0]) and not is_string_like(weights[0]): + tw = [] + for i in xrange(len(weights)): + tw.append( np.array(weights[i]) ) + w = tw + else: + raise ValueError, 'Can not use provided weights to create a hist' + + if len(x) != len(w): + raise ValueError, 'weights should have the same shape as x' + for i in xrange(len(x)): + if len(x[i]) != len(w[i]): + raise ValueError, 'weights should have the same shape as x' + else: + w = [None]*len(x) + # Check whether bins or range are given explicitly. In that # case do not autoscale axes. binsgiven = (cbook.iterable(bins) or range != None) @@ -6584,7 +6614,7 @@ for i in xrange(len(x)): # this will automatically overwrite bins, # so that each histogram uses the same bins - m, bins = np.histogram(x[i], bins, **hist_kwargs) + m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs) n.append(m) if cumulative: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <md...@us...> - 2008-12-12 21:22:07
|
Revision: 6594 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6594&view=rev Author: mdboom Date: 2008-12-12 21:22:04 +0000 (Fri, 12 Dec 2008) Log Message: ----------- Fix numerous documentation warnings. Modified Paths: -------------- trunk/matplotlib/doc/api/font_manager_api.rst trunk/matplotlib/doc/faq/howto_faq.rst trunk/matplotlib/doc/users/event_handling.rst trunk/matplotlib/lib/matplotlib/artist.py trunk/matplotlib/lib/matplotlib/axes.py trunk/matplotlib/lib/matplotlib/collections.py trunk/matplotlib/lib/matplotlib/colors.py trunk/matplotlib/lib/matplotlib/lines.py trunk/matplotlib/lib/matplotlib/mlab.py trunk/matplotlib/lib/matplotlib/patches.py trunk/matplotlib/lib/matplotlib/path.py trunk/matplotlib/lib/matplotlib/pyplot.py trunk/matplotlib/lib/matplotlib/text.py trunk/matplotlib/lib/matplotlib/ticker.py Modified: trunk/matplotlib/doc/api/font_manager_api.rst =================================================================== --- trunk/matplotlib/doc/api/font_manager_api.rst 2008-12-12 17:23:57 UTC (rev 6593) +++ trunk/matplotlib/doc/api/font_manager_api.rst 2008-12-12 21:22:04 UTC (rev 6594) @@ -11,7 +11,7 @@ :show-inheritance: :mod:`matplotlib.fontconfig_pattern` -============================== +==================================== .. automodule:: matplotlib.fontconfig_pattern :members: Modified: trunk/matplotlib/doc/faq/howto_faq.rst =================================================================== --- trunk/matplotlib/doc/faq/howto_faq.rst 2008-12-12 17:23:57 UTC (rev 6593) +++ trunk/matplotlib/doc/faq/howto_faq.rst 2008-12-12 21:22:04 UTC (rev 6594) @@ -428,8 +428,10 @@ .. seealso:: :ref:`howto-webapp` + For information about running matplotlib inside of a web + application. -.. _howto-show +.. _howto-show: Use :func:`~matplotlib.pyplot.show` ------------------------------------------ Modified: trunk/matplotlib/doc/users/event_handling.rst =================================================================== --- trunk/matplotlib/doc/users/event_handling.rst 2008-12-12 17:23:57 UTC (rev 6593) +++ trunk/matplotlib/doc/users/event_handling.rst 2008-12-12 21:22:04 UTC (rev 6594) @@ -64,8 +64,8 @@ 'scroll_event' :class:`~matplotlib.backend_bases.MouseEvent` - mouse scroll wheel is rolled 'figure_enter_event' :class:`~matplotlib.backend_bases.LocationEvent` - mouse enters a new figure 'figure_leave_event' :class:`~matplotlib.backend_bases.LocationEvent` - mouse leaves a figure -'axes_enter_event' :class:`~matplotlib.backend_bases.LocationEvent` - mouse enters a new axes -'axes_leave_event' :class:`~matplotlib.backend_bases.LocationEvent` - mouse leaves an axes +'axes_enter_event' :class:`~matplotlib.backend_bases.LocationEvent` - mouse enters a new axes +'axes_leave_event' :class:`~matplotlib.backend_bases.LocationEvent` - mouse leaves an axes ======================= ====================================================================================== .. _event-attributes: Modified: trunk/matplotlib/lib/matplotlib/artist.py =================================================================== --- trunk/matplotlib/lib/matplotlib/artist.py 2008-12-12 17:23:57 UTC (rev 6593) +++ trunk/matplotlib/lib/matplotlib/artist.py 2008-12-12 21:22:04 UTC (rev 6594) @@ -144,7 +144,10 @@ Remove a callback based on its *id*. .. seealso:: + :meth:`add_callback` + For adding callbacks + """ try: del self._propobservers[oid] except KeyError: pass @@ -497,7 +500,7 @@ def set_alpha(self, alpha): """ Set the alpha value used for blending - not supported on - all backends + all backends. ACCEPTS: float (0.0 transparent through 1.0 opaque) """ Modified: trunk/matplotlib/lib/matplotlib/axes.py =================================================================== --- trunk/matplotlib/lib/matplotlib/axes.py 2008-12-12 17:23:57 UTC (rev 6593) +++ trunk/matplotlib/lib/matplotlib/axes.py 2008-12-12 21:22:04 UTC (rev 6594) @@ -43,8 +43,9 @@ * 'r--': red dashed lines .. seealso:: + :func:`~matplotlib.Line2D.lineStyles` and - :func:`~matplotlib.pyplot.colors`: + :func:`~matplotlib.pyplot.colors` for all possible styles and color format string. """ @@ -2574,7 +2575,8 @@ ACCEPTS: str .. seealso:: - :meth:`text`: + + :meth:`text` for information on how override and the optional args work """ default = { @@ -2610,7 +2612,8 @@ ACCEPTS: str .. seealso:: - :meth:`text`: + + :meth:`text` for information on how override and the optional args work """ @@ -2641,7 +2644,8 @@ ACCEPTS: str .. seealso:: - :meth:`text`: + + :meth:`text` for information on how override and the optional args work """ label = self.yaxis.get_label() @@ -2794,7 +2798,8 @@ %(Line2D)s .. seealso:: - :meth:`axhspan`: + + :meth:`axhspan` for example plot and source code """ @@ -2853,7 +2858,8 @@ %(Line2D)s .. seealso:: - :meth:`axhspan`: + + :meth:`axhspan` for example plot and source code """ @@ -2964,7 +2970,8 @@ %(Polygon)s .. seealso:: - :meth:`axhspan`: + + :meth:`axhspan` for example plot and source code """ trans = mtransforms.blended_transform_factory( @@ -3331,12 +3338,13 @@ %(Line2D)s .. seealso:: - :mod:`~matplotlib.dates`: + + :mod:`~matplotlib.dates` for helper functions :func:`~matplotlib.dates.date2num`, :func:`~matplotlib.dates.num2date` and - :func:`~matplotlib.dates.drange`: + :func:`~matplotlib.dates.drange` for help on creating the required floating point dates. """ @@ -3439,7 +3447,8 @@ %(Line2D)s .. seealso:: - :meth:`loglog`: + + :meth:`loglog` For example code and figure """ if not self._hold: self.cla() @@ -3484,7 +3493,8 @@ %(Line2D)s .. seealso:: - :meth:`loglog`: + + :meth:`loglog` For example code and figure """ if not self._hold: self.cla() @@ -3546,9 +3556,10 @@ - *b* is the *x*-axis. .. seealso:: + :meth:`~matplotlib.axes.Axes.plot` or - :meth:`~matplotlib.axes.Axes.vlines`: For documentation on - valid kwargs. + :meth:`~matplotlib.axes.Axes.vlines` + For documentation on valid kwargs. **Example:** @@ -4249,11 +4260,13 @@ *baseline*). .. seealso:: - `this document`__ for details - :file:`examples/pylab_examples/stem_plot.py`: - for a demo + `this document`__ + for details + :file:`examples/pylab_examples/stem_plot.py` + for a demo + __ http://www.mathworks.com/access/helpdesk/help/techdoc/ref/stem.html """ @@ -5594,7 +5607,7 @@ %(PolyCollection)s - .. plot:: mpl_examples/pylab_examples/fill_between.py + .. plot:: mpl_examples/pylab_examples/fill_between.py """ # Handle united data, such as dates self._process_unit_info(xdata=x, ydata=y1, kwargs=kwargs) @@ -6093,7 +6106,8 @@ %(QuadMesh)s .. seealso:: - :func:`~matplotlib.pyplot.pcolor`: + + :func:`~matplotlib.pyplot.pcolor` For an explanation of the grid orientation and the expansion of 1-D *X* and/or *Y* to 2-D arrays. """ @@ -6424,7 +6438,7 @@ def hist(self, x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', - orientation='vertical', rwidth=None, log=False, + orientation='vertical', rwidth=None, log=False, **kwargs): """ call signature:: @@ -6896,6 +6910,7 @@ .. plot:: mpl_examples/pylab_examples/csd_demo.py .. seealso: + :meth:`psd` For a description of the optional parameters. """ @@ -7093,7 +7108,9 @@ * *alpha* .. seealso:: + :func:`~matplotlib.pyplot.imshow` + For image options. For controlling colors, e.g. cyan background and red marks, use:: @@ -7114,7 +7131,9 @@ * ',' pixel .. seealso:: + :func:`~matplotlib.pyplot.plot` + For plotting options """ if precision is None: precision = 0 Modified: trunk/matplotlib/lib/matplotlib/collections.py =================================================================== --- trunk/matplotlib/lib/matplotlib/collections.py 2008-12-12 17:23:57 UTC (rev 6593) +++ trunk/matplotlib/lib/matplotlib/collections.py 2008-12-12 21:22:04 UTC (rev 6594) @@ -354,7 +354,9 @@ ACCEPTS: matplotlib color arg or sequence of rgba tuples .. seealso:: + :meth:`set_facecolor`, :meth:`set_edgecolor` + For setting the edge or face color individually. """ self.set_facecolor(c) self.set_edgecolor(c) @@ -702,8 +704,8 @@ over the regions in *x* where *where* is True. The bars range on the y-axis from *ymin* to *ymax* - A :class:`BrokenBarHCollection` is returned. - **kwargs are passed on to the collection + A :class:`BrokenBarHCollection` is returned. kwargs are + passed on to the collection. """ xranges = [] for ind0, ind1 in mlab.contiguous_regions(where): @@ -932,7 +934,7 @@ Set the color(s) of the line collection. *c* can be a matplotlib color arg (all patches have same color), or a sequence or rgba tuples; if it is a sequence the patches will - cycle through the sequence + cycle through the sequence. ACCEPTS: matplotlib color arg or sequence of rgba tuples """ Modified: trunk/matplotlib/lib/matplotlib/colors.py =================================================================== --- trunk/matplotlib/lib/matplotlib/colors.py 2008-12-12 17:23:57 UTC (rev 6593) +++ trunk/matplotlib/lib/matplotlib/colors.py 2008-12-12 21:22:04 UTC (rev 6594) @@ -594,7 +594,9 @@ .. seealso:: + :func:`makeMappingArray` + For information about making a mapping array. """ self.monochrome = False # True only if all colors in map are identical; # needed for contouring. Modified: trunk/matplotlib/lib/matplotlib/lines.py =================================================================== --- trunk/matplotlib/lib/matplotlib/lines.py 2008-12-12 17:23:57 UTC (rev 6593) +++ trunk/matplotlib/lib/matplotlib/lines.py 2008-12-12 21:22:04 UTC (rev 6594) @@ -622,7 +622,9 @@ backward-compatibility. .. seealso:: + :meth:`set_drawstyle` + To set the drawing style (stepping) of the plot. ACCEPTS: [ '-' | '--' | '-.' | ':' | 'None' | ' ' | '' ] and any drawstyle in combination with a linestyle, e.g. 'steps--'. Modified: trunk/matplotlib/lib/matplotlib/mlab.py =================================================================== --- trunk/matplotlib/lib/matplotlib/mlab.py 2008-12-12 17:23:57 UTC (rev 6593) +++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-12-12 21:22:04 UTC (rev 6594) @@ -59,7 +59,7 @@ A collection of helper methods for numpyrecord arrays -.. _htmlonly:: +.. _htmlonly: See :ref:`misc-examples-index` @@ -475,7 +475,8 @@ segments. .. seealso:: - :func:`psd`: + + :func:`psd` :func:`psd` differs in the default overlap; in returning the mean of the segment periodograms; and in not returning times. @@ -517,7 +518,8 @@ the factors cancel out. .. seealso:: - :func:`psd` and :func:`csd`: + + :func:`psd` and :func:`csd` For information about the methods used to compute :math:`P_{xy}`, :math:`P_{xx}` and :math:`P_{yy}`. """ @@ -565,7 +567,7 @@ Do a best fit polynomial of order *N* of *y* to *x*. Return value is a vector of polynomial coefficients [pk ... p1 p0]. Eg, for - *N*=2:: + *N* = 2:: p2*x0^2 + p1*x0 + p0 = y1 p2*x1^2 + p1*x1 + p0 = y1 @@ -601,7 +603,9 @@ subscripts on that page. The linear algebra is correct, however. .. seealso:: + :func:`polyval` + polyval function """ warnings.warn("use numpy.poyfit", DeprecationWarning) return np.polyfit(*args, **kwargs) @@ -623,7 +627,9 @@ resid = y - trend .. seealso:: + :func:`polyfit` + polyfit function """ warnings.warn("use numpy.polyval", DeprecationWarning) return np.polyval(*args, **kwargs) @@ -709,7 +715,8 @@ cohere. .. seealso:: - :file:`test/cohere_pairs_test.py` in the src tree: + + :file:`test/cohere_pairs_test.py` in the src tree For an example script that shows that this :func:`cohere_pairs` and :func:`cohere` give the same results for a given pair. @@ -1212,10 +1219,11 @@ \lambda = \\frac{1}{n}\\sum \\ln|f^'(x_i)| .. seealso:: - Sec 10.5 Strogatz (1994) "Nonlinear Dynamics and Chaos". - `Wikipedia article on Lyapunov Exponent - <http://en.wikipedia.org/wiki/Lyapunov_exponent>`_. + Lyapunov Exponent + Sec 10.5 Strogatz (1994) "Nonlinear Dynamics and Chaos". + `Wikipedia article on Lyapunov Exponent + <http://en.wikipedia.org/wiki/Lyapunov_exponent>`_. .. note:: What the function here calculates may not be what you really want; @@ -1426,7 +1434,8 @@ - *dtype*: the array will have this dtype. default: ``numpy.float_`` .. seealso:: - See :file:`examples/pylab_examples/load_converter.py` in the source tree: + + See :file:`examples/pylab_examples/load_converter.py` in the source tree Exercises many of these options. """ @@ -2057,6 +2066,7 @@ .. seealso:: http://projects.scipy.org/pipermail/numpy-discussion/2008-August/036429.html + Motivation for this function """ return rec.view(np.recarray) #return rec.view(dtype=(np.record, rec.dtype), type=np.recarray) @@ -2815,7 +2825,8 @@ files is automatic, if the filename ends in '.gz' .. seealso:: - :func:`csv2rec`: + + :func:`csv2rec` For information about *missing* and *missingd*, which can be used to fill in masked values into your CSV file. """ Modified: trunk/matplotlib/lib/matplotlib/patches.py =================================================================== --- trunk/matplotlib/lib/matplotlib/patches.py 2008-12-12 17:23:57 UTC (rev 6593) +++ trunk/matplotlib/lib/matplotlib/patches.py 2008-12-12 21:22:04 UTC (rev 6594) @@ -643,8 +643,10 @@ %(Patch)s .. seealso:: - :class:`Patch`: + + :class:`Patch` For additional kwargs + """ Patch.__init__(self, **kwargs) self._path = path @@ -671,8 +673,10 @@ %(Patch)s .. seealso:: - :class:`Patch`: + + :class:`Patch` For additional kwargs + """ Patch.__init__(self, **kwargs) xy = np.asarray(xy, np.float_) Modified: trunk/matplotlib/lib/matplotlib/path.py =================================================================== --- trunk/matplotlib/lib/matplotlib/path.py 2008-12-12 17:23:57 UTC (rev 6593) +++ trunk/matplotlib/lib/matplotlib/path.py 2008-12-12 21:22:04 UTC (rev 6594) @@ -223,7 +223,8 @@ Return a transformed copy of the path. .. seealso:: - :class:`matplotlib.transforms.TransformedPath`: + + :class:`matplotlib.transforms.TransformedPath` A specialized path class that will cache the transformed result and automatically update when the transform changes. Modified: trunk/matplotlib/lib/matplotlib/pyplot.py =================================================================== --- trunk/matplotlib/lib/matplotlib/pyplot.py 2008-12-12 17:23:57 UTC (rev 6593) +++ trunk/matplotlib/lib/matplotlib/pyplot.py 2008-12-12 21:22:04 UTC (rev 6594) @@ -425,7 +425,8 @@ 'upper right' ) .. seealso:: - :func:`~matplotlib.pyplot.legend`: + + :func:`~matplotlib.pyplot.legend` For information about the location codes """ l = gcf().legend(handles, labels, loc, **kwargs) @@ -616,11 +617,13 @@ registered. See :func:`matplotlib.projections.register_projection` .. seealso:: - :func:`~matplotlib.pyplot.axes`: + + :func:`~matplotlib.pyplot.axes` For additional information on :func:`axes` and :func:`subplot` keyword arguments. :file:`examples/pylab_examples/polar_scatter.py` + For an example **Example:** @@ -650,7 +653,9 @@ the right, and the *ax2* instance is returned. .. seealso:: + :file:`examples/api_examples/two_scales.py` + For an example """ if ax is None: ax=gca() @@ -746,7 +751,8 @@ 'horizontalalignment': 'center'} .. seealso:: - :func:`~matplotlib.pyplot.text`: + + :func:`~matplotlib.pyplot.text` for information on how override and the optional args work. """ l = gca().set_title(s, *args, **kwargs) @@ -812,7 +818,9 @@ The xmin, xmax, ymin, ymax tuple is returned .. seealso:: + :func:`xlim`, :func:`ylim` + For setting the x- and y-limits individually. """ ax = gca() v = ax.axis(*v, **kwargs) @@ -832,7 +840,8 @@ } .. seealso:: - :func:`~matplotlib.pyplot.text`: + + :func:`~matplotlib.pyplot.text` For information on how override and the optional args work """ l = gca().set_xlabel(s, *args, **kwargs) @@ -852,7 +861,8 @@ 'rotation'='vertical' : } .. seealso:: - :func:`~matplotlib.pyplot.text`: + + :func:`~matplotlib.pyplot.text` For information on how override and the optional args work. """ @@ -1139,9 +1149,9 @@ """ Plotting commands - ========= ================================================= + ============== ================================================= Command Description - ========= ================================================= + ============== ================================================= axes Create a new axes axis Set or return the current axis limits bar make a bar chart @@ -1162,7 +1172,7 @@ figtext add text in figure coords figure create or change active figure fill make filled polygons - fill_between make filled polygons + fill_between make filled polygons gca return the current axes gcf return the current figure gci get the current image, or None @@ -1194,7 +1204,7 @@ title add a title to the current axes xlabel add an xlabel to the current axes ylabel add a ylabel to the current axes - ========= ================================================= + ============== ================================================= The following commands will set the default colormap accordingly: Modified: trunk/matplotlib/lib/matplotlib/text.py =================================================================== --- trunk/matplotlib/lib/matplotlib/text.py 2008-12-12 17:23:57 UTC (rev 6593) +++ trunk/matplotlib/lib/matplotlib/text.py 2008-12-12 21:22:04 UTC (rev 6594) @@ -658,7 +658,9 @@ Set the background color of the text by updating the bbox. .. seealso:: + :meth:`set_bbox` + To change the position of the bounding box. ACCEPTS: any matplotlib color """ Modified: trunk/matplotlib/lib/matplotlib/ticker.py =================================================================== --- trunk/matplotlib/lib/matplotlib/ticker.py 2008-12-12 17:23:57 UTC (rev 6593) +++ trunk/matplotlib/lib/matplotlib/ticker.py 2008-12-12 21:22:04 UTC (rev 6594) @@ -213,7 +213,7 @@ 'Return fixed strings for tick labels' def __init__(self, seq): """ - seq is a sequence of strings. For positions ``i<len(seq)` return + *seq* is a sequence of strings. For positions ``i < len(seq)`` return *seq[i]* regardless of *x*. Otherwise return '' """ self.seq = seq This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |