You can subscribe to this list here.
| 2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
(115) |
Aug
(120) |
Sep
(137) |
Oct
(170) |
Nov
(461) |
Dec
(263) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2008 |
Jan
(120) |
Feb
(74) |
Mar
(35) |
Apr
(74) |
May
(245) |
Jun
(356) |
Jul
(240) |
Aug
(115) |
Sep
(78) |
Oct
(225) |
Nov
(98) |
Dec
(271) |
| 2009 |
Jan
(132) |
Feb
(84) |
Mar
(74) |
Apr
(56) |
May
(90) |
Jun
(79) |
Jul
(83) |
Aug
(296) |
Sep
(214) |
Oct
(76) |
Nov
(82) |
Dec
(66) |
| 2010 |
Jan
(46) |
Feb
(58) |
Mar
(51) |
Apr
(77) |
May
(58) |
Jun
(126) |
Jul
(128) |
Aug
(64) |
Sep
(50) |
Oct
(44) |
Nov
(48) |
Dec
(54) |
| 2011 |
Jan
(68) |
Feb
(52) |
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
| 2018 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
|
From: <jo...@us...> - 2009-02-26 19:44:35
|
Revision: 6937
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6937&view=rev
Author: jouni
Date: 2009-02-26 19:44:30 +0000 (Thu, 26 Feb 2009)
Log Message:
-----------
Support image clipping in the pdf backend
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-02-26 00:12:33 UTC (rev 6936)
+++ trunk/matplotlib/CHANGELOG 2009-02-26 19:44:30 UTC (rev 6937)
@@ -1,3 +1,5 @@
+2009-02-26 Support image clipping in pdf backend. - JKS
+
2009-02-25 Improve tick location subset choice in FixedLocator. - EF
2009-02-24 Deprecate numerix, and strip out all but the numpy
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2009-02-26 00:12:33 UTC (rev 6936)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_pdf.py 2009-02-26 19:44:30 UTC (rev 6937)
@@ -39,7 +39,7 @@
from matplotlib.ft2font import FT2Font, FIXED_WIDTH, ITALIC, LOAD_NO_SCALE, \
LOAD_NO_HINTING, KERNING_UNFITTED
from matplotlib.mathtext import MathTextParser
-from matplotlib.transforms import Affine2D, Bbox, BboxBase
+from matplotlib.transforms import Affine2D, Bbox, BboxBase, TransformedPath
from matplotlib.path import Path
from matplotlib import ttconv
@@ -1268,10 +1268,12 @@
return self.image_dpi/72.0
def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None):
- # MGDTODO: Support clippath here
gc = self.new_gc()
if bbox is not None:
gc.set_clip_rectangle(bbox)
+ if clippath is not None:
+ clippath = TransformedPath(clippath, clippath_trans)
+ gc.set_clip_path(clippath)
self.check_gc(gc)
h, w = im.get_size_out()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-02-26 00:12:45
|
Revision: 6936
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6936&view=rev
Author: efiring
Date: 2009-02-26 00:12:33 +0000 (Thu, 26 Feb 2009)
Log Message:
-----------
Improve tick location subsetting in FixedLocator.
Now it includes zero, if present.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/ticker.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-02-25 15:45:45 UTC (rev 6935)
+++ trunk/matplotlib/CHANGELOG 2009-02-26 00:12:33 UTC (rev 6936)
@@ -1,4 +1,6 @@
-2009-02-25 Deprecate numerix, and strip out all but the numpy
+2009-02-25 Improve tick location subset choice in FixedLocator. - EF
+
+2009-02-24 Deprecate numerix, and strip out all but the numpy
part of the code. - EF
2009-02-21 Improve scatter argument handling; add an early error
Modified: trunk/matplotlib/lib/matplotlib/ticker.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/ticker.py 2009-02-25 15:45:45 UTC (rev 6935)
+++ trunk/matplotlib/lib/matplotlib/ticker.py 2009-02-26 00:12:33 UTC (rev 6936)
@@ -708,10 +708,14 @@
Tick locations are fixed. If nbins is not None,
the array of possible positions will be subsampled to
keep the number of ticks <= nbins +1.
+ The subsampling will be done so as to include the smallest
+ absolute value; for example, if zero is included in the
+ array of possibilities, then it is guaranteed to be one of
+ the chosen ticks.
"""
def __init__(self, locs, nbins=None):
- self.locs = locs
+ self.locs = np.asarray(locs)
self.nbins = nbins
if self.nbins is not None:
self.nbins = max(self.nbins, 2)
@@ -721,7 +725,12 @@
if self.nbins is None:
return self.locs
step = max(int(0.99 + len(self.locs) / float(self.nbins)), 1)
- return self.locs[::step]
+ ticks = self.locs[::step]
+ for i in range(1,step):
+ ticks1 = self.locs[i::step]
+ if np.absolute(ticks1).min() < np.absolute(ticks).min():
+ ticks = ticks1
+ return ticks
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-02-25 15:46:04
|
Revision: 6935
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6935&view=rev
Author: mdboom
Date: 2009-02-25 15:45:45 +0000 (Wed, 25 Feb 2009)
Log Message:
-----------
Merged revisions 6934 via svnmerge from
https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_98_5_maint
........
r6934 | mdboom | 2009-02-25 10:39:34 -0500 (Wed, 25 Feb 2009) | 2 lines
Fix crashes with empty data and step draw style.
........
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/lines.py
Property Changed:
----------------
trunk/matplotlib/
trunk/matplotlib/doc/pyplots/README
trunk/matplotlib/doc/sphinxext/gen_gallery.py
trunk/matplotlib/doc/sphinxext/gen_rst.py
trunk/matplotlib/lib/matplotlib/sphinxext/plot_directive.py
Property changes on: trunk/matplotlib
___________________________________________________________________
Modified: svnmerge-integrated
- /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6928
+ /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6934
Modified: svn:mergeinfo
- /branches/v0_91_maint:5753-5771
/branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928
+ /branches/v0_91_maint:5753-5771
/branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934
Property changes on: trunk/matplotlib/doc/pyplots/README
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928
+ /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934
Property changes on: trunk/matplotlib/doc/sphinxext/gen_gallery.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928
+ /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934
Property changes on: trunk/matplotlib/doc/sphinxext/gen_rst.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928
+ /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928,6934
Modified: trunk/matplotlib/lib/matplotlib/lines.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/lines.py 2009-02-25 15:39:34 UTC (rev 6934)
+++ trunk/matplotlib/lib/matplotlib/lines.py 2009-02-25 15:45:45 UTC (rev 6935)
@@ -486,10 +486,11 @@
funcname = self._lineStyles.get(self._linestyle, '_draw_nothing')
if funcname != '_draw_nothing':
tpath, affine = self._transformed_path.get_transformed_path_and_affine()
- self._lineFunc = getattr(self, funcname)
- funcname = self.drawStyles.get(self._drawstyle, '_draw_lines')
- drawFunc = getattr(self, funcname)
- drawFunc(renderer, gc, tpath, affine.frozen())
+ if len(tpath.vertices):
+ self._lineFunc = getattr(self, funcname)
+ funcname = self.drawStyles.get(self._drawstyle, '_draw_lines')
+ drawFunc = getattr(self, funcname)
+ drawFunc(renderer, gc, tpath, affine.frozen())
if self._marker is not None:
gc = renderer.new_gc()
@@ -500,25 +501,25 @@
funcname = self._markers.get(self._marker, '_draw_nothing')
if funcname != '_draw_nothing':
tpath, affine = self._transformed_path.get_transformed_points_and_affine()
-
- # subsample the markers if markevery is not None
- markevery = self.get_markevery()
- if markevery is not None:
- if iterable(markevery):
- startind, stride = markevery
+ if len(tpath.vertices):
+ # subsample the markers if markevery is not None
+ markevery = self.get_markevery()
+ if markevery is not None:
+ if iterable(markevery):
+ startind, stride = markevery
+ else:
+ startind, stride = 0, markevery
+ if tpath.codes is not None:
+ codes = tpath.codes[startind::stride]
+ else:
+ codes = None
+ vertices = tpath.vertices[startind::stride]
+ subsampled = Path(vertices, codes)
else:
- startind, stride = 0, markevery
- if tpath.codes is not None:
- codes = tpath.codes[startind::stride]
- else:
- codes = None
- vertices = tpath.vertices[startind::stride]
- subsampled = Path(vertices, codes)
- else:
- subsampled = tpath
+ subsampled = tpath
- markerFunc = getattr(self, funcname)
- markerFunc(renderer, gc, subsampled, affine.frozen())
+ markerFunc = getattr(self, funcname)
+ markerFunc(renderer, gc, subsampled, affine.frozen())
renderer.close_group('line2d')
Property changes on: trunk/matplotlib/lib/matplotlib/sphinxext/plot_directive.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/sphinxext/plot_directive.py:5753-5771
/branches/v0_98_5_maint/lib/matplotlib/sphinxext/plot_directive.py:6920-6925
+ /branches/v0_91_maint/doc/sphinxext/plot_directive.py:5753-5771
/branches/v0_98_5_maint/lib/matplotlib/sphinxext/plot_directive.py:6920-6925,6934
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-02-25 15:39:44
|
Revision: 6934
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6934&view=rev
Author: mdboom
Date: 2009-02-25 15:39:34 +0000 (Wed, 25 Feb 2009)
Log Message:
-----------
Fix crashes with empty data and step draw style.
Modified Paths:
--------------
branches/v0_98_5_maint/lib/matplotlib/lines.py
Modified: branches/v0_98_5_maint/lib/matplotlib/lines.py
===================================================================
--- branches/v0_98_5_maint/lib/matplotlib/lines.py 2009-02-25 07:36:55 UTC (rev 6933)
+++ branches/v0_98_5_maint/lib/matplotlib/lines.py 2009-02-25 15:39:34 UTC (rev 6934)
@@ -458,10 +458,11 @@
funcname = self._lineStyles.get(self._linestyle, '_draw_nothing')
if funcname != '_draw_nothing':
tpath, affine = self._transformed_path.get_transformed_path_and_affine()
- self._lineFunc = getattr(self, funcname)
- funcname = self.drawStyles.get(self._drawstyle, '_draw_lines')
- drawFunc = getattr(self, funcname)
- drawFunc(renderer, gc, tpath, affine.frozen())
+ if len(tpath.vertices):
+ self._lineFunc = getattr(self, funcname)
+ funcname = self.drawStyles.get(self._drawstyle, '_draw_lines')
+ drawFunc = getattr(self, funcname)
+ drawFunc(renderer, gc, tpath, affine.frozen())
if self._marker is not None:
gc = renderer.new_gc()
@@ -472,8 +473,9 @@
funcname = self._markers.get(self._marker, '_draw_nothing')
if funcname != '_draw_nothing':
tpath, affine = self._transformed_path.get_transformed_points_and_affine()
- markerFunc = getattr(self, funcname)
- markerFunc(renderer, gc, tpath, affine.frozen())
+ if len(tpath.vertices):
+ markerFunc = getattr(self, funcname)
+ markerFunc(renderer, gc, tpath, affine.frozen())
renderer.close_group('line2d')
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-02-25 07:37:02
|
Revision: 6933
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6933&view=rev
Author: efiring
Date: 2009-02-25 07:36:55 +0000 (Wed, 25 Feb 2009)
Log Message:
-----------
Restore a stripped-down numerix with a deprecation warning.
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/setup.py
Added Paths:
-----------
trunk/matplotlib/lib/matplotlib/numerix/
trunk/matplotlib/lib/matplotlib/numerix/__init__.py
trunk/matplotlib/lib/matplotlib/numerix/_sp_imports.py
trunk/matplotlib/lib/matplotlib/numerix/fft/
trunk/matplotlib/lib/matplotlib/numerix/fft/__init__.py
trunk/matplotlib/lib/matplotlib/numerix/linear_algebra/
trunk/matplotlib/lib/matplotlib/numerix/linear_algebra/__init__.py
trunk/matplotlib/lib/matplotlib/numerix/ma/
trunk/matplotlib/lib/matplotlib/numerix/ma/__init__.py
trunk/matplotlib/lib/matplotlib/numerix/mlab/
trunk/matplotlib/lib/matplotlib/numerix/mlab/__init__.py
trunk/matplotlib/lib/matplotlib/numerix/random_array/
trunk/matplotlib/lib/matplotlib/numerix/random_array/__init__.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-02-24 21:56:19 UTC (rev 6932)
+++ trunk/matplotlib/CHANGELOG 2009-02-25 07:36:55 UTC (rev 6933)
@@ -1,4 +1,5 @@
-2009-02-25 Remove numerix; it remains in the maintenance branches. - EF
+2009-02-25 Deprecate numerix, and strip out all but the numpy
+ part of the code. - EF
2009-02-21 Improve scatter argument handling; add an early error
message, allow inputs to have more than one dimension. - EF
Added: trunk/matplotlib/lib/matplotlib/numerix/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/numerix/__init__.py (rev 0)
+++ trunk/matplotlib/lib/matplotlib/numerix/__init__.py 2009-02-25 07:36:55 UTC (rev 6933)
@@ -0,0 +1,84 @@
+"""
+numerix imports numpy with some compatibility adjustments for old
+code that had been based on Numeric.
+
+It is deprecated and will go away soon.
+"""
+
+import sys, os, struct
+from matplotlib import rcParams, verbose
+
+import warnings
+msg = """
+**********************************************************
+matplotlib.numerix and all its subpackages are deprecated.
+They will be removed soon. Please use numpy instead.
+**********************************************************
+"""
+warnings.warn(msg, DeprecationWarning)
+
+which = "numpy", "defaulted" # This is now the only choice
+
+try:
+ import numpy.oldnumeric as numpy
+ from numpy.oldnumeric import *
+except ImportError:
+ import numpy
+ from numpy import *
+ print 'except asarray', asarray
+from _sp_imports import nx, infinity, rand, randn, isnan, all, any
+from _sp_imports import UInt8, UInt16, UInt32, Infinity
+try:
+ from numpy.oldnumeric.matrix import Matrix
+except ImportError:
+ Matrix = matrix
+version = 'numpy %s' % numpy.__version__
+from numpy import nan
+
+
+from mlab import amin, amax
+newaxis = NewAxis
+from numpy import angle
+def typecode(a):
+ return a.dtype.char
+def iscontiguous(a):
+ return a.flags.contiguous
+def byteswapped(a):
+ return a.byteswap()
+def itemsize(a):
+ return a.itemsize
+
+verbose.report('numerix %s'%version)
+# a bug fix for blas numeric suggested by Fernando Perez
+matrixmultiply=dot
+asum = sum
+
+
+def _import_fail_message(module, version):
+ """Prints a message when the array package specific version of an extension
+ fails to import correctly.
+ """
+ _dict = { "which" : which[0],
+ "module" : module,
+ "specific" : version + module
+ }
+ print """
+The import of the %(which)s version of the %(module)s module,
+%(specific)s, failed. This is is either because %(which)s was
+unavailable when matplotlib was compiled, because a dependency of
+%(specific)s could not be satisfied, or because the build flag for
+this module was turned off in setup.py. If it appears that
+%(specific)s was not built, make sure you have a working copy of
+%(which)s and then re-install matplotlib. Otherwise, the following
+traceback gives more details:\n""" % _dict
+
+g = globals()
+l = locals()
+__import__('ma', g, l)
+__import__('fft', g, l)
+__import__('linear_algebra', g, l)
+__import__('random_array', g, l)
+__import__('mlab', g, l)
+
+la = linear_algebra
+ra = random_array
Added: trunk/matplotlib/lib/matplotlib/numerix/_sp_imports.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/numerix/_sp_imports.py (rev 0)
+++ trunk/matplotlib/lib/matplotlib/numerix/_sp_imports.py 2009-02-25 07:36:55 UTC (rev 6933)
@@ -0,0 +1,34 @@
+try:
+ from numpy.oldnumeric import Int8, UInt8, \
+ Int16, UInt16, \
+ Int32, UInt32, \
+ Float32, Float64, \
+ Complex32, Complex64, \
+ Float, Int, Complex
+except ImportError:
+ from numpy import Int8, UInt8, \
+ Int16, UInt16, \
+ Int32, UInt32, \
+ Float32, Float64, \
+ Complex32, Complex64, \
+ Float, Int, Complex
+
+class _TypeNamespace:
+ """Numeric compatible type aliases for use with extension functions."""
+ Int8 = Int8
+ UInt8 = UInt8
+ Int16 = Int16
+ UInt16 = UInt16
+ Int32 = Int32
+ UInt32 = UInt32
+ Float32 = Float32
+ Float64 = Float64
+ Complex32 = Complex32
+ Complex64 = Complex64
+
+nx = _TypeNamespace()
+
+from numpy import inf, infty, Infinity
+from numpy.random import rand, randn
+infinity = Infinity
+from numpy import all, isnan, any
Added: trunk/matplotlib/lib/matplotlib/numerix/fft/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/numerix/fft/__init__.py (rev 0)
+++ trunk/matplotlib/lib/matplotlib/numerix/fft/__init__.py 2009-02-25 07:36:55 UTC (rev 6933)
@@ -0,0 +1,4 @@
+try:
+ from numpy.oldnumeric.fft import *
+except ImportError:
+ from numpy.dft.old import *
Added: trunk/matplotlib/lib/matplotlib/numerix/linear_algebra/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/numerix/linear_algebra/__init__.py (rev 0)
+++ trunk/matplotlib/lib/matplotlib/numerix/linear_algebra/__init__.py 2009-02-25 07:36:55 UTC (rev 6933)
@@ -0,0 +1,4 @@
+try:
+ from numpy.oldnumeric.linear_algebra import *
+except ImportError:
+ from numpy.linalg.old import *
Added: trunk/matplotlib/lib/matplotlib/numerix/ma/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/numerix/ma/__init__.py (rev 0)
+++ trunk/matplotlib/lib/matplotlib/numerix/ma/__init__.py 2009-02-25 07:36:55 UTC (rev 6933)
@@ -0,0 +1,9 @@
+try:
+ from numpy.ma import * # numpy 1.05 and later
+except ImportError:
+ from numpy.core.ma import * # earlier
+def getmaskorNone(obj):
+ _msk = getmask(obj)
+ if _msk is nomask:
+ return None
+ return _msk
Added: trunk/matplotlib/lib/matplotlib/numerix/mlab/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/numerix/mlab/__init__.py (rev 0)
+++ trunk/matplotlib/lib/matplotlib/numerix/mlab/__init__.py 2009-02-25 07:36:55 UTC (rev 6933)
@@ -0,0 +1,7 @@
+try:
+ from numpy.oldnumeric.mlab import *
+except ImportError:
+ from numpy.lib.mlab import *
+
+amin = min
+amax = max
Added: trunk/matplotlib/lib/matplotlib/numerix/random_array/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/numerix/random_array/__init__.py (rev 0)
+++ trunk/matplotlib/lib/matplotlib/numerix/random_array/__init__.py 2009-02-25 07:36:55 UTC (rev 6933)
@@ -0,0 +1,4 @@
+try:
+ from numpy.oldnumeric.random_array import *
+except ImportError:
+ from numpy.random import *
Modified: trunk/matplotlib/setup.py
===================================================================
--- trunk/matplotlib/setup.py 2009-02-24 21:56:19 UTC (rev 6932)
+++ trunk/matplotlib/setup.py 2009-02-25 07:36:55 UTC (rev 6933)
@@ -52,7 +52,15 @@
'matplotlib.projections',
# 'matplotlib.toolkits',
'mpl_toolkits',
- 'matplotlib.sphinxext'
+ 'matplotlib.sphinxext',
+ # The following are deprecated and will be removed.
+ 'matplotlib.numerix',
+ 'matplotlib.numerix.mlab',
+ 'matplotlib.numerix.ma',
+ 'matplotlib.numerix.linear_algebra',
+ 'matplotlib.numerix.random_array',
+ 'matplotlib.numerix.fft',
+
]
py_modules = ['pylab']
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-02-24 23:22:16
|
Revision: 6932
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6932&view=rev
Author: efiring
Date: 2009-02-24 21:56:19 +0000 (Tue, 24 Feb 2009)
Log Message:
-----------
Removal of numerix, stage 2.
The only vestiges are a couple method names, and a validator
with a warning to catch numerix keys in matplotlibrc files.
Modified Paths:
--------------
trunk/matplotlib/doc/api/api_changes.rst
trunk/matplotlib/doc/devel/outline.rst
trunk/matplotlib/examples/misc/rc_traits.py
trunk/matplotlib/lib/matplotlib/backends/backend_ps.py
trunk/matplotlib/lib/matplotlib/config/mplconfig.py
trunk/matplotlib/lib/matplotlib/config/rcsetup.py
trunk/matplotlib/lib/matplotlib/rcsetup.py
trunk/matplotlib/matplotlibrc.template
trunk/matplotlib/setup.py
trunk/matplotlib/setupext.py
trunk/matplotlib/test/mplTest/units/UnitDblConverter.py
trunk/matplotlib/test/test_backends/TestAgg.py
trunk/matplotlib/unit/agg_memleak.py
trunk/matplotlib/unit/ft2font_memleak.py
trunk/matplotlib/unit/inside_poly_memleak.py
trunk/matplotlib/unit/inside_poly_profile.py
Modified: trunk/matplotlib/doc/api/api_changes.rst
===================================================================
--- trunk/matplotlib/doc/api/api_changes.rst 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/doc/api/api_changes.rst 2009-02-24 21:56:19 UTC (rev 6932)
@@ -19,11 +19,13 @@
Changes for 0.98.x
==================
+* Removed numerix package.
+
* Added new :func:`matplotlib.image.imsave` and exposed it to the
:mod:`matplotlib.pyplot` interface.
* Remove support for pyExcelerator in exceltools -- use xlwt
- instead
+ instead
* Changed the defaults of acorr and xcorr to use usevlines=True,
maxlags=10 and normed=True since these are the best defaults
Modified: trunk/matplotlib/doc/devel/outline.rst
===================================================================
--- trunk/matplotlib/doc/devel/outline.rst 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/doc/devel/outline.rst 2009-02-24 21:56:19 UTC (rev 6932)
@@ -107,7 +107,6 @@
config/rcsetup Darren needs conversion
config/tconfig Darren needs conversion
config/verbose Darren needs conversion
-numerix/__init__ needs conversion
projections/__init__ Mike converted
projections/geo Mike converted (not included--experimental)
projections/polar Mike converted
Modified: trunk/matplotlib/examples/misc/rc_traits.py
===================================================================
--- trunk/matplotlib/examples/misc/rc_traits.py 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/examples/misc/rc_traits.py 2009-02-24 21:56:19 UTC (rev 6932)
@@ -131,7 +131,6 @@
class RC(traits.HasTraits):
backend = traits.Trait(*backends)
- numerix = traits.Trait('Numeric', 'numarray')
interactive = flexible_false_trait
toolbar = traits.Trait('toolbar2', 'classic', None)
timezone = traits.Trait(*timezones)
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_ps.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_ps.py 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_ps.py 2009-02-24 21:56:19 UTC (rev 6932)
@@ -112,7 +112,7 @@
def seq_allequal(seq1, seq2):
"""
- seq1 and seq2 are either None or sequences or numerix arrays
+ seq1 and seq2 are either None or sequences or arrays
Return True if both are None or both are seqs with identical
elements
"""
Modified: trunk/matplotlib/lib/matplotlib/config/mplconfig.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/lib/matplotlib/config/mplconfig.py 2009-02-24 21:56:19 UTC (rev 6932)
@@ -58,7 +58,6 @@
toolbar = T.Trait('toolbar2', 'toolbar2', None)
timezone = T.Trait('UTC', pytz.all_timezones)
datapath = T.Trait(cutils.get_data_path())
- numerix = T.Trait('numpy', 'numpy', 'numeric', 'numarray')
units = T.false
class backend(TConfig):
@@ -290,7 +289,6 @@
self.tconfig_map = {
'backend' : (self.tconfig.backend, 'use'),
'backend_fallback' : (self.tconfig.backend, 'fallback'),
- 'numerix' : (self.tconfig, 'numerix'),
'toolbar' : (self.tconfig, 'toolbar'),
'datapath' : (self.tconfig, 'datapath'),
'units' : (self.tconfig, 'units'),
Modified: trunk/matplotlib/lib/matplotlib/config/rcsetup.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/config/rcsetup.py 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/lib/matplotlib/config/rcsetup.py 2009-02-24 21:56:19 UTC (rev 6932)
@@ -75,10 +75,6 @@
'QtAgg', 'Qt4Agg', 'SVG', 'Template', 'TkAgg', 'WX', 'WXAgg',
], ignorecase=True)
-validate_numerix = ValidateInStrings('numerix',[
- 'Numeric','numarray','numpy',
- ], ignorecase=True)
-
validate_toolbar = ValidateInStrings('toolbar',[
'None','classic','toolbar2',
], ignorecase=True)
@@ -298,7 +294,6 @@
# a map from key -> value, converter
defaultParams = {
'backend' : ['WXAgg', validate_backend],
- 'numerix' : ['numpy', validate_numerix],
'toolbar' : ['toolbar2', validate_toolbar],
'datapath' : [None, validate_path_exists], # handled by _get_data_path_cached
'units' : [False, validate_bool],
Modified: trunk/matplotlib/lib/matplotlib/rcsetup.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/rcsetup.py 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/lib/matplotlib/rcsetup.py 2009-02-24 21:56:19 UTC (rev 6932)
@@ -106,10 +106,18 @@
if s.startswith('module://'): return s
else: return _validate_standard_backends(s)
-validate_numerix = ValidateInStrings('numerix',[
- 'Numeric','numarray','numpy',
- ], ignorecase=True)
+def validate_numerix(v):
+ # 2009/02/24: start warning; later, remove all traces
+ try:
+ if v == 'obsolete':
+ return v
+ except ValueError:
+ pass
+ warnings.warn('rcParams key "numerix" is obsolete and has no effect;\n'
+ ' please delete it from your matplotlibrc file')
+
+
validate_toolbar = ValidateInStrings('toolbar',[
'None','classic','toolbar2',
], ignorecase=True)
@@ -323,7 +331,7 @@
defaultParams = {
'backend' : ['Agg', validate_backend], # agg is certainly present
'backend_fallback' : [True, validate_bool], # agg is certainly present
- 'numerix' : ['numpy', validate_numerix],
+ 'numerix' : ['obsolete', validate_numerix],
'maskedarray' : ['obsolete', validate_maskedarray], #to be removed
'toolbar' : ['toolbar2', validate_toolbar],
'datapath' : [None, validate_path_exists], # handled by _get_data_path_cached
Modified: trunk/matplotlib/matplotlibrc.template
===================================================================
--- trunk/matplotlib/matplotlibrc.template 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/matplotlibrc.template 2009-02-24 21:56:19 UTC (rev 6932)
@@ -34,7 +34,6 @@
# conflicts, we will automatically try and find a compatible one for
# you if backend_fallback is True
#backend_fallback: True
-numerix : %(numerix)s # numpy, Numeric or numarray
#interactive : False
#toolbar : toolbar2 # None | classic | toolbar2
#timezone : UTC # a pytz timezone string, eg US/Central or Europe/Paris
Modified: trunk/matplotlib/setup.py
===================================================================
--- trunk/matplotlib/setup.py 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/setup.py 2009-02-24 21:56:19 UTC (rev 6932)
@@ -18,7 +18,7 @@
# This dict will be updated as we try to select the best option during
# the build process. However, values in setup.cfg will be used, if
# defined.
-rc = {'backend':'Agg', 'numerix':'numpy'}
+rc = {'backend':'Agg'}
# BEFORE importing disutils, remove MANIFEST. distutils doesn't properly
# update it when the contents of directories change.
@@ -52,13 +52,6 @@
'matplotlib.projections',
# 'matplotlib.toolkits',
'mpl_toolkits',
- 'matplotlib.numerix',
- 'matplotlib.numerix.mlab',
- 'matplotlib.numerix.ma',
- 'matplotlib.numerix.npyma',
- 'matplotlib.numerix.linear_algebra',
- 'matplotlib.numerix.random_array',
- 'matplotlib.numerix.fft',
'matplotlib.sphinxext'
]
@@ -224,14 +217,12 @@
# Write the default matplotlibrc file
if options['backend']: rc['backend'] = options['backend']
-if options['numerix']: rc['numerix'] = options['numerix']
template = file('matplotlibrc.template').read()
file('lib/matplotlib/mpl-data/matplotlibrc', 'w').write(template%rc)
# Write the default matplotlib.conf file
template = file('lib/matplotlib/mpl-data/matplotlib.conf.template').read()
template = template.replace("datapath = ", "#datapath = ")
-template = template.replace("numerix = 'numpy'", "numerix = '%s'"%rc['numerix'])
template = template.replace(" use = 'Agg'", " use = '%s'"%rc['backend'])
file('lib/matplotlib/mpl-data/matplotlib.conf', 'w').write(template)
Modified: trunk/matplotlib/setupext.py
===================================================================
--- trunk/matplotlib/setupext.py 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/setupext.py 2009-02-24 21:56:19 UTC (rev 6932)
@@ -106,8 +106,7 @@
'build_macosx': 'auto',
'build_image': True,
'build_windowing': True,
- 'backend': None,
- 'numerix': None}
+ 'backend': None}
# Based on the contents of setup.cfg, determine the build options
if os.path.exists("setup.cfg"):
@@ -142,10 +141,7 @@
try: options['backend'] = config.get("rc_options", "backend")
except: pass
- try: options['numerix'] = config.get("rc_options", "numerix")
- except: pass
-
if options['display_status']:
def print_line(char='='):
print char * 76
Modified: trunk/matplotlib/test/mplTest/units/UnitDblConverter.py
===================================================================
--- trunk/matplotlib/test/mplTest/units/UnitDblConverter.py 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/test/mplTest/units/UnitDblConverter.py 2009-02-24 21:56:19 UTC (rev 6932)
@@ -9,9 +9,9 @@
#===========================================================================
# Place all imports after here.
#
+import numpy as np
import matplotlib.units as units
import matplotlib.ticker as ticker
-import matplotlib.numerix as nx
import matplotlib.projections.polar as polar
from matplotlib.cbook import iterable
#
@@ -27,7 +27,7 @@
# This was copied from matplotlib example code.
def rad_fn(x, pos = None ):
"""Radian function formatter."""
- n = int((x / nx.pi) * 2.0 + 0.25)
+ n = int((x / np.pi) * 2.0 + 0.25)
if n == 0:
return str(x)
elif n == 1:
Modified: trunk/matplotlib/test/test_backends/TestAgg.py
===================================================================
--- trunk/matplotlib/test/test_backends/TestAgg.py 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/test/test_backends/TestAgg.py 2009-02-24 21:56:19 UTC (rev 6932)
@@ -11,7 +11,7 @@
import sys, time, os
from matplotlib.ft2font import FT2Font
-from matplotlib.numerix import rand
+from numpy.random import rand
from matplotlib.backend_bases import GraphicsContextBase
from matplotlib.backends._backend_agg import RendererAgg
@@ -89,7 +89,7 @@
font.set_size( 12, 72 )
o.draw_text_image( font.get_image(), 30, 40, gc )
-
+
o.write_png( fname % i )
val = report_memory( i )
if i==1: start = val
Modified: trunk/matplotlib/unit/agg_memleak.py
===================================================================
--- trunk/matplotlib/unit/agg_memleak.py 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/unit/agg_memleak.py 2009-02-24 21:56:19 UTC (rev 6932)
@@ -1,6 +1,10 @@
+"""
+And another broken test...
+"""
+
import sys, time, os
from matplotlib.ft2font import FT2Font
-from matplotlib.numerix import rand
+from numpy.random import rand
from matplotlib.backend_bases import GraphicsContextBase
from matplotlib.backends._backend_agg import RendererAgg
@@ -23,7 +27,7 @@
ys = [400*int(rand()) for k in range(8)]
rgb = (1,0,0)
pnts = zip(xs, ys)
- o.draw_polygon(gc, rgb, pnts)
+ o.draw_polygon(gc, rgb, pnts) # no such method??
o.draw_polygon(gc, None, pnts)
for j in range(50):
Modified: trunk/matplotlib/unit/ft2font_memleak.py
===================================================================
--- trunk/matplotlib/unit/ft2font_memleak.py 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/unit/ft2font_memleak.py 2009-02-24 21:56:19 UTC (rev 6932)
@@ -1,7 +1,10 @@
+"""
+This appears to be obsolete as of 2009/02/24; a key import fails.
+"""
import sys, time, os
-from matplotlib.numerix import rand
+from numpy.random import rand
from matplotlib.ft2font import FT2Font
-from matplotlib.backends.backend_ps import encodeTTFasPS
+from matplotlib.backends.backend_ps import encodeTTFasPS # doesn't exist...
fname = '/usr/local/share/matplotlib/Vera.ttf'
Modified: trunk/matplotlib/unit/inside_poly_memleak.py
===================================================================
--- trunk/matplotlib/unit/inside_poly_memleak.py 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/unit/inside_poly_memleak.py 2009-02-24 21:56:19 UTC (rev 6932)
@@ -1,8 +1,11 @@
#!/usr/bin/env python
+"""
+Another broken test...
+"""
import os, sys, time
import matplotlib.nxutils as nxutils
-import matplotlib.numerix as nx
+from numpy.random import rand
def report_memory(i):
pid = os.getpid()
@@ -14,12 +17,12 @@
for i in range(500):
report_memory(i)
- verts = nx.mlab.rand(100, 2)
- b = nxutils.pnpoly(x, y, verts)
+ verts = rand(100, 2)
+ b = nxutils.pnpoly(x, y, verts) # x, y don't exist
for i in range(500):
report_memory(i)
- verts = nx.mlab.rand(100, 2)
- points = nx.mlab.rand(10000,2)
+ verts = rand(100, 2)
+ points = rand(10000,2)
mask = nxutils.points_inside_poly(points, verts)
Modified: trunk/matplotlib/unit/inside_poly_profile.py
===================================================================
--- trunk/matplotlib/unit/inside_poly_profile.py 2009-02-24 21:15:49 UTC (rev 6931)
+++ trunk/matplotlib/unit/inside_poly_profile.py 2009-02-24 21:56:19 UTC (rev 6932)
@@ -1,7 +1,11 @@
+"""
+Broken.
+"""
+
import os, sys, time
import matplotlib.nxutils as nxutils
-import matplotlib.numerix as nx
+from numpy.random import rand
import matplotlib.mlab
import matplotlib.patches as patches
if 1:
@@ -10,13 +14,14 @@
t0 = time.time()
for i in range(numtrials):
- points = nx.mlab.rand(numpoints,2)
+ points = rand(numpoints,2)
mask = matplotlib.mlab._inside_poly_deprecated(points, verts)
+ ### no such thing
told = time.time() - t0
t0 = time.time()
for i in range(numtrials):
- points = nx.mlab.rand(numpoints,2)
+ points = rand(numpoints,2)
mask = nxutils.points_inside_poly(points, verts)
tnew = time.time() - t0
print numverts, numpoints, told, tnew, told/tnew
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-02-24 21:15:57
|
Revision: 6931
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6931&view=rev
Author: efiring
Date: 2009-02-24 21:15:49 +0000 (Tue, 24 Feb 2009)
Log Message:
-----------
Deleted numerix
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
Removed Paths:
-------------
trunk/matplotlib/lib/matplotlib/numerix/
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-02-24 15:38:33 UTC (rev 6930)
+++ trunk/matplotlib/CHANGELOG 2009-02-24 21:15:49 UTC (rev 6931)
@@ -1,3 +1,5 @@
+2009-02-25 Remove numerix; it remains in the maintenance branches. - EF
+
2009-02-21 Improve scatter argument handling; add an early error
message, allow inputs to have more than one dimension. - EF
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jr...@us...> - 2009-02-24 15:38:36
|
Revision: 6930
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6930&view=rev
Author: jrevans
Date: 2009-02-24 15:38:33 +0000 (Tue, 24 Feb 2009)
Log Message:
-----------
Updated to reflect updated unit conversion interface.
Modified Paths:
--------------
trunk/matplotlib/examples/units/basic_units.py
trunk/matplotlib/examples/units/date_support.py
trunk/matplotlib/examples/units/evans_test.py
Modified: trunk/matplotlib/examples/units/basic_units.py
===================================================================
--- trunk/matplotlib/examples/units/basic_units.py 2009-02-23 17:43:26 UTC (rev 6929)
+++ trunk/matplotlib/examples/units/basic_units.py 2009-02-24 15:38:33 UTC (rev 6930)
@@ -304,7 +304,8 @@
class BasicUnitConverter(units.ConversionInterface):
- def axisinfo(unit):
+ @staticmethod
+ def axisinfo(unit, axis):
'return AxisInfo instance for x and unit'
if unit==radians:
@@ -326,9 +327,8 @@
return units.AxisInfo(label=unit.unit.fullname)
return None
- axisinfo = staticmethod(axisinfo)
-
- def convert(val, unit):
+ @staticmethod
+ def convert(val, unit, axis):
if units.ConversionInterface.is_numlike(val):
return val
#print 'convert checking iterable'
@@ -336,15 +336,14 @@
return [thisval.convert_to(unit).get_value() for thisval in val]
else:
return val.convert_to(unit).get_value()
- convert = staticmethod(convert)
- def default_units(x):
+ @staticmethod
+ def default_units(x, axis):
'return the default unit for x or None'
if iterable(x):
for thisx in x:
return thisx.unit
return x.unit
- default_units = staticmethod(default_units)
Modified: trunk/matplotlib/examples/units/date_support.py
===================================================================
--- trunk/matplotlib/examples/units/date_support.py 2009-02-23 17:43:26 UTC (rev 6929)
+++ trunk/matplotlib/examples/units/date_support.py 2009-02-24 15:38:33 UTC (rev 6930)
@@ -8,7 +8,8 @@
class DateConverter(units.ConversionInterface):
- def axisinfo(unit):
+ @staticmethod
+ def axisinfo(unit, axis):
'return the unit AxisInfo'
if unit=='date':
majloc = dates.AutoDateLocator()
@@ -19,17 +20,16 @@
label='date',
)
else: return None
- axisinfo = staticmethod(axisinfo)
- def convert(value, unit):
+ @staticmethod
+ def convert(value, unit, axis):
if units.ConversionInterface.is_numlike(value): return value
return dates.date2num(value)
- convert = staticmethod(convert)
- def default_units(x):
+ @staticmethod
+ def default_units(x, axis):
'return the default unit for x or None'
return 'date'
- default_units = staticmethod(default_units)
units.registry[datetime.date] = DateConverter()
Modified: trunk/matplotlib/examples/units/evans_test.py
===================================================================
--- trunk/matplotlib/examples/units/evans_test.py 2009-02-23 17:43:26 UTC (rev 6929)
+++ trunk/matplotlib/examples/units/evans_test.py 2009-02-24 15:38:33 UTC (rev 6930)
@@ -24,7 +24,8 @@
class FooConverter:
- def axisinfo(unit):
+ @staticmethod
+ def axisinfo(unit, axis):
'return the Foo AxisInfo'
if unit==1.0 or unit==2.0:
return units.AxisInfo(
@@ -35,9 +36,9 @@
else:
return None
- axisinfo = staticmethod(axisinfo)
- def convert(obj, unit):
+ @staticmethod
+ def convert(obj, unit, axis):
"""
convert obj using unit. If obj is a sequence, return the
converted sequence
@@ -49,16 +50,15 @@
return [o.value(unit) for o in obj]
else:
return obj.value(unit)
- convert = staticmethod(convert)
- def default_units(x):
+ @staticmethod
+ def default_units(x, axis):
'return the default unit for x or None'
if iterable(x):
for thisx in x:
return thisx.unit
else:
return x.unit
- default_units = staticmethod(default_units)
units.registry[Foo] = FooConverter()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-02-23 17:43:32
|
Revision: 6929
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6929&view=rev
Author: mdboom
Date: 2009-02-23 17:43:26 +0000 (Mon, 23 Feb 2009)
Log Message:
-----------
Merged revisions 6927-6928 via svnmerge from
https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_98_5_maint
........
r6927 | mdboom | 2009-02-23 12:30:07 -0500 (Mon, 23 Feb 2009) | 2 lines
Add credit to Allen Haldane in comments.
........
r6928 | mdboom | 2009-02-23 12:38:35 -0500 (Mon, 23 Feb 2009) | 2 lines
C++ standards compliance for use with Sun C++ compiler. These should be equivalent to what was there before on gcc.
........
Modified Paths:
--------------
trunk/matplotlib/CXX/Extensions.hxx
trunk/matplotlib/agg24/include/agg_alpha_mask_u8.h
trunk/matplotlib/src/path_converters.h
Property Changed:
----------------
trunk/matplotlib/
trunk/matplotlib/doc/pyplots/README
trunk/matplotlib/doc/sphinxext/gen_gallery.py
trunk/matplotlib/doc/sphinxext/gen_rst.py
Property changes on: trunk/matplotlib
___________________________________________________________________
Modified: svnmerge-integrated
- /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6925
+ /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6928
Modified: svn:mergeinfo
- /branches/v0_91_maint:5753-5771
/branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925
+ /branches/v0_91_maint:5753-5771
/branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925,6927-6928
Modified: trunk/matplotlib/CXX/Extensions.hxx
===================================================================
--- trunk/matplotlib/CXX/Extensions.hxx 2009-02-23 17:38:35 UTC (rev 6928)
+++ trunk/matplotlib/CXX/Extensions.hxx 2009-02-23 17:43:26 UTC (rev 6929)
@@ -203,7 +203,7 @@
{
typedef PyObject *(*method_varargs_call_handler_t)( PyObject *_self, PyObject *_args );
typedef PyObject *(*method_keyword_call_handler_t)( PyObject *_self, PyObject *_args, PyObject *_dict );
- };
+ }
template<class T>
class MethodDefExt : public PyMethodDef
Modified: trunk/matplotlib/agg24/include/agg_alpha_mask_u8.h
===================================================================
--- trunk/matplotlib/agg24/include/agg_alpha_mask_u8.h 2009-02-23 17:38:35 UTC (rev 6928)
+++ trunk/matplotlib/agg24/include/agg_alpha_mask_u8.h 2009-02-23 17:43:26 UTC (rev 6929)
@@ -2,8 +2,8 @@
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
-// Permission to copy, use, modify, sell and distribute this software
-// is granted provided this copyright notice appears in all copies.
+// Permission to copy, use, modify, sell and distribute this software
+// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
@@ -30,15 +30,15 @@
{
static unsigned calculate(const int8u* p) { return *p; }
};
-
+
//=====================================================rgb_to_gray_mask_u8
template<unsigned R, unsigned G, unsigned B>
struct rgb_to_gray_mask_u8
{
- static unsigned calculate(const int8u* p)
- {
- return (p[R]*77 + p[G]*150 + p[B]*29) >> 8;
+ static unsigned calculate(const int8u* p)
+ {
+ return (p[R]*77 + p[G]*150 + p[B]*29) >> 8;
}
};
@@ -50,7 +50,7 @@
typedef int8u cover_type;
typedef alpha_mask_u8<Step, Offset, MaskF> self_type;
enum cover_scale_e
- {
+ {
cover_shift = 8,
cover_none = 0,
cover_full = 255
@@ -64,12 +64,12 @@
MaskF& mask_function() { return m_mask_function; }
const MaskF& mask_function() const { return m_mask_function; }
-
+
//--------------------------------------------------------------------
cover_type pixel(int x, int y) const
{
- if(x >= 0 && y >= 0 &&
- x < (int)m_rbuf->width() &&
+ if(x >= 0 && y >= 0 &&
+ x < (int)m_rbuf->width() &&
y < (int)m_rbuf->height())
{
return (cover_type)m_mask_function.calculate(
@@ -81,13 +81,13 @@
//--------------------------------------------------------------------
cover_type combine_pixel(int x, int y, cover_type val) const
{
- if(x >= 0 && y >= 0 &&
- x < (int)m_rbuf->width() &&
+ if(x >= 0 && y >= 0 &&
+ x < (int)m_rbuf->width() &&
y < (int)m_rbuf->height())
{
- return (cover_type)((cover_full + val *
+ return (cover_type)((cover_full + val *
m_mask_function.calculate(
- m_rbuf->row_ptr(y) + x * Step + Offset)) >>
+ m_rbuf->row_ptr(y) + x * Step + Offset)) >>
cover_shift);
}
return 0;
@@ -112,7 +112,7 @@
if(x < 0)
{
count += x;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -126,7 +126,7 @@
{
int rest = x + count - xmax - 1;
count -= rest;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -162,7 +162,7 @@
if(x < 0)
{
count += x;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -176,7 +176,7 @@
{
int rest = x + count - xmax - 1;
count -= rest;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -187,8 +187,8 @@
const int8u* mask = m_rbuf->row_ptr(y) + x * Step + Offset;
do
{
- *covers = (cover_type)((cover_full + (*covers) *
- m_mask_function.calculate(mask)) >>
+ *covers = (cover_type)((cover_full + (*covers) *
+ m_mask_function.calculate(mask)) >>
cover_shift);
++covers;
mask += Step;
@@ -214,7 +214,7 @@
if(y < 0)
{
count += y;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -228,7 +228,7 @@
{
int rest = y + count - ymax - 1;
count -= rest;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -263,7 +263,7 @@
if(y < 0)
{
count += y;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -277,7 +277,7 @@
{
int rest = y + count - ymax - 1;
count -= rest;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -288,8 +288,8 @@
const int8u* mask = m_rbuf->row_ptr(y) + x * Step + Offset;
do
{
- *covers = (cover_type)((cover_full + (*covers) *
- m_mask_function.calculate(mask)) >>
+ *covers = (cover_type)((cover_full + (*covers) *
+ m_mask_function.calculate(mask)) >>
cover_shift);
++covers;
mask += m_rbuf->stride();
@@ -302,11 +302,11 @@
alpha_mask_u8(const self_type&);
const self_type& operator = (const self_type&);
- rendering_buffer* m_rbuf;
+ agg::rendering_buffer* m_rbuf;
MaskF m_mask_function;
};
-
+
typedef alpha_mask_u8<1, 0> alpha_mask_gray8; //----alpha_mask_gray8
typedef alpha_mask_u8<3, 0> alpha_mask_rgb24r; //----alpha_mask_rgb24r
@@ -354,7 +354,7 @@
typedef int8u cover_type;
typedef amask_no_clip_u8<Step, Offset, MaskF> self_type;
enum cover_scale_e
- {
+ {
cover_shift = 8,
cover_none = 0,
cover_full = 255
@@ -376,13 +376,13 @@
m_rbuf->row_ptr(y) + x * Step + Offset);
}
-
+
//--------------------------------------------------------------------
cover_type combine_pixel(int x, int y, cover_type val) const
{
- return (cover_type)((cover_full + val *
+ return (cover_type)((cover_full + val *
m_mask_function.calculate(
- m_rbuf->row_ptr(y) + x * Step + Offset)) >>
+ m_rbuf->row_ptr(y) + x * Step + Offset)) >>
cover_shift);
}
@@ -407,8 +407,8 @@
const int8u* mask = m_rbuf->row_ptr(y) + x * Step + Offset;
do
{
- *dst = (cover_type)((cover_full + (*dst) *
- m_mask_function.calculate(mask)) >>
+ *dst = (cover_type)((cover_full + (*dst) *
+ m_mask_function.calculate(mask)) >>
cover_shift);
++dst;
mask += Step;
@@ -436,8 +436,8 @@
const int8u* mask = m_rbuf->row_ptr(y) + x * Step + Offset;
do
{
- *dst = (cover_type)((cover_full + (*dst) *
- m_mask_function.calculate(mask)) >>
+ *dst = (cover_type)((cover_full + (*dst) *
+ m_mask_function.calculate(mask)) >>
cover_shift);
++dst;
mask += m_rbuf->stride();
@@ -449,11 +449,11 @@
amask_no_clip_u8(const self_type&);
const self_type& operator = (const self_type&);
- rendering_buffer* m_rbuf;
+ agg::rendering_buffer* m_rbuf;
MaskF m_mask_function;
};
-
+
typedef amask_no_clip_u8<1, 0> amask_no_clip_gray8; //----amask_no_clip_gray8
typedef amask_no_clip_u8<3, 0> amask_no_clip_rgb24r; //----amask_no_clip_rgb24r
Property changes on: trunk/matplotlib/doc/pyplots/README
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925
+ /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928
Property changes on: trunk/matplotlib/doc/sphinxext/gen_gallery.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925
+ /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928
Property changes on: trunk/matplotlib/doc/sphinxext/gen_rst.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925
+ /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925,6927-6928
Modified: trunk/matplotlib/src/path_converters.h
===================================================================
--- trunk/matplotlib/src/path_converters.h 2009-02-23 17:38:35 UTC (rev 6928)
+++ trunk/matplotlib/src/path_converters.h 2009-02-23 17:43:26 UTC (rev 6929)
@@ -515,15 +515,15 @@
the last line. Once it gets too big, the lines cannot be
combined. */
- /* This code was originally written by someone else (John
- Hunter?) and I have modified to work in-place -- meaning
- not creating an entirely new path list each time. In order
- to do that without too much additional code complexity, it
- keeps a small queue around so that multiple points can be
- emitted in a single call, and those points will be popped
- from the queue in subsequent calls. The following block
- will empty the queue before proceeding to the main loop
- below. -- Michael Droettboom */
+ /* This code was originally written by Allan Haldane and I
+ have modified to work in-place -- meaning not creating an
+ entirely new path list each time. In order to do that
+ without too much additional code complexity, it keeps a
+ small queue around so that multiple points can be emitted
+ in a single call, and those points will be popped from the
+ queue in subsequent calls. The following block will empty
+ the queue before proceeding to the main loop below.
+ -- Michael Droettboom */
if (queue_flush(&cmd, x, y)) {
return cmd;
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-02-23 17:38:38
|
Revision: 6928
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6928&view=rev
Author: mdboom
Date: 2009-02-23 17:38:35 +0000 (Mon, 23 Feb 2009)
Log Message:
-----------
C++ standards compliance for use with Sun C++ compiler. These should be equivalent to what was there before on gcc.
Modified Paths:
--------------
branches/v0_98_5_maint/CXX/Extensions.hxx
branches/v0_98_5_maint/agg24/include/agg_alpha_mask_u8.h
Modified: branches/v0_98_5_maint/CXX/Extensions.hxx
===================================================================
--- branches/v0_98_5_maint/CXX/Extensions.hxx 2009-02-23 17:30:07 UTC (rev 6927)
+++ branches/v0_98_5_maint/CXX/Extensions.hxx 2009-02-23 17:38:35 UTC (rev 6928)
@@ -61,7 +61,7 @@
namespace Py
{
class ExtensionModuleBase;
-
+
// Make an Exception Type for use in raising custom exceptions
class ExtensionExceptionType : public Object
{
@@ -74,44 +74,44 @@
void init( ExtensionModuleBase &module, const std::string& name );
};
-
- class MethodTable
+
+ class MethodTable
{
public:
MethodTable();
virtual ~MethodTable();
-
+
void add(const char* method_name, PyCFunction f, const char* doc="", int flag=1);
PyMethodDef* table();
-
+
protected:
std::vector<PyMethodDef> t; // accumulator of PyMethodDef's
PyMethodDef *mt; // Actual method table produced when full
-
+
static PyMethodDef method (const char* method_name, PyCFunction f, int flags = 1, const char* doc="");
-
+
private:
//
// prevent the compiler generating these unwanted functions
//
MethodTable(const MethodTable& m); //unimplemented
void operator=(const MethodTable& m); //unimplemented
-
+
}; // end class MethodTable
-
+
extern "C"
{
typedef PyObject *(*method_varargs_call_handler_t)( PyObject *_self, PyObject *_args );
typedef PyObject *(*method_keyword_call_handler_t)( PyObject *_self, PyObject *_args, PyObject *_dict );
- };
-
+ }
+
template<class T>
class MethodDefExt : public PyMethodDef
{
public:
typedef Object (T::*method_varargs_function_t)( const Tuple &args );
typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws );
-
+
MethodDefExt
(
const char *_name,
@@ -124,11 +124,11 @@
ext_meth_def.ml_meth = _handler;
ext_meth_def.ml_flags = METH_VARARGS;
ext_meth_def.ml_doc = const_cast<char *>(_doc);
-
+
ext_varargs_function = _function;
ext_keyword_function = NULL;
}
-
+
MethodDefExt
(
const char *_name,
@@ -141,57 +141,57 @@
ext_meth_def.ml_meth = method_varargs_call_handler_t( _handler );
ext_meth_def.ml_flags = METH_VARARGS|METH_KEYWORDS;
ext_meth_def.ml_doc = const_cast<char *>(_doc);
-
+
ext_varargs_function = NULL;
ext_keyword_function = _function;
}
-
+
~MethodDefExt()
{}
-
+
PyMethodDef ext_meth_def;
- method_varargs_function_t ext_varargs_function;
- method_keyword_function_t ext_keyword_function;
+ method_varargs_function_t ext_varargs_function;
+ method_keyword_function_t ext_keyword_function;
};
-
+
class ExtensionModuleBase
{
public:
ExtensionModuleBase( const char *name );
virtual ~ExtensionModuleBase();
-
+
Module module(void) const; // only valid after initialize() has been called
Dict moduleDictionary(void) const; // only valid after initialize() has been called
-
+
virtual Object invoke_method_keyword( const std::string &_name, const Tuple &_args, const Dict &_keywords ) = 0;
virtual Object invoke_method_varargs( const std::string &_name, const Tuple &_args ) = 0;
-
+
const std::string &name() const;
const std::string &fullName() const;
-
+
protected:
// Initialize the module
void initialize( const char *module_doc );
-
+
const std::string module_name;
const std::string full_module_name;
MethodTable method_table;
-
+
private:
-
+
//
// prevent the compiler generating these unwanted functions
//
ExtensionModuleBase( const ExtensionModuleBase & ); //unimplemented
void operator=( const ExtensionModuleBase & ); //unimplemented
-
+
};
-
+
extern "C" PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords );
extern "C" PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args );
extern "C" void do_not_dealloc( void * );
-
-
+
+
template<TEMPLATE_TYPENAME T>
class ExtensionModule : public ExtensionModuleBase
{
@@ -201,16 +201,16 @@
{}
virtual ~ExtensionModule()
{}
-
+
protected:
typedef Object (T::*method_varargs_function_t)( const Tuple &args );
typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws );
typedef std::map<std::string,MethodDefExt<T> *> method_map_t;
-
+
static void add_varargs_method( const char *name, method_varargs_function_t function, const char *doc="" )
{
method_map_t &mm = methods();
-
+
MethodDefExt<T> *method_definition = new MethodDefExt<T>
(
name,
@@ -218,14 +218,14 @@
method_varargs_call_handler,
doc
);
-
+
mm[std::string( name )] = method_definition;
}
-
+
static void add_keyword_method( const char *name, method_keyword_function_t function, const char *doc="" )
{
method_map_t &mm = methods();
-
+
MethodDefExt<T> *method_definition = new MethodDefExt<T>
(
name,
@@ -233,7 +233,7 @@
method_keyword_call_handler,
doc
);
-
+
mm[std::string( name )] = method_definition;
}
@@ -241,46 +241,46 @@
{
ExtensionModuleBase::initialize( module_doc );
Dict dict( moduleDictionary() );
-
+
//
// put each of the methods into the modules dictionary
// so that we get called back at the function in T.
//
method_map_t &mm = methods();
EXPLICIT_TYPENAME method_map_t::iterator i;
-
+
for( i=mm.begin(); i != mm.end(); ++i )
{
MethodDefExt<T> *method_definition = (*i).second;
-
+
static PyObject *self = PyCObject_FromVoidPtr( this, do_not_dealloc );
-
+
Tuple args( 2 );
args[0] = Object( self );
args[1] = String( (*i).first );
-
+
PyObject *func = PyCFunction_New
(
&method_definition->ext_meth_def,
new_reference_to( args )
);
-
+
dict[ (*i).first ] = Object( func );
}
}
-
+
protected: // Tom Malcolmson reports that derived classes need access to these
-
+
static method_map_t &methods(void)
{
static method_map_t *map_of_methods = NULL;
if( map_of_methods == NULL )
map_of_methods = new method_map_t;
-
+
return *map_of_methods;
}
-
-
+
+
// this invoke function must be called from within a try catch block
virtual Object invoke_method_keyword( const std::string &name, const Tuple &args, const Dict &keywords )
{
@@ -292,13 +292,13 @@
error_msg += name;
throw RuntimeError( error_msg );
}
-
+
// cast up to the derived class
T *self = static_cast<T *>(this);
-
+
return (self->*meth_def->ext_keyword_function)( args, keywords );
}
-
+
// this invoke function must be called from within a try catch block
virtual Object invoke_method_varargs( const std::string &name, const Tuple &args )
{
@@ -310,13 +310,13 @@
error_msg += name;
throw RuntimeError( error_msg );
}
-
+
// cast up to the derived class
T *self = static_cast<T *>(this);
-
+
return (self->*meth_def->ext_varargs_function)( args );
}
-
+
private:
//
// prevent the compiler generating these unwanted functions
@@ -324,17 +324,17 @@
ExtensionModule( const ExtensionModule<T> & ); //unimplemented
void operator=( const ExtensionModule<T> & ); //unimplemented
};
-
-
+
+
class PythonType
{
public:
- // if you define one sequence method you must define
+ // if you define one sequence method you must define
// all of them except the assigns
-
+
PythonType (size_t base_size, int itemsize, const char *default_name );
virtual ~PythonType ();
-
+
const char *getName () const;
const char *getDoc () const;
@@ -342,7 +342,7 @@
PythonType & name (const char* nam);
PythonType & doc (const char* d);
PythonType & dealloc(void (*f)(PyObject*));
-
+
PythonType & supportPrint(void);
PythonType & supportGetattr(void);
PythonType & supportSetattr(void);
@@ -354,61 +354,61 @@
PythonType & supportHash(void);
PythonType & supportCall(void);
PythonType & supportIter(void);
-
+
PythonType & supportSequenceType(void);
PythonType & supportMappingType(void);
PythonType & supportNumberType(void);
PythonType & supportBufferType(void);
-
+
protected:
PyTypeObject *table;
PySequenceMethods *sequence_table;
PyMappingMethods *mapping_table;
PyNumberMethods *number_table;
PyBufferProcs *buffer_table;
-
+
void init_sequence();
void init_mapping();
void init_number();
void init_buffer();
-
+
private:
//
// prevent the compiler generating these unwanted functions
//
PythonType (const PythonType& tb); // unimplemented
void operator=(const PythonType& t); // unimplemented
-
+
}; // end of PythonType
-
-
-
+
+
+
// Class PythonExtension is what you inherit from to create
// a new Python extension type. You give your class itself
// as the template paramter.
-
+
// There are two ways that extension objects can get destroyed.
// 1. Their reference count goes to zero
// 2. Someone does an explicit delete on a pointer.
- // In (1) the problem is to get the destructor called
+ // In (1) the problem is to get the destructor called
// We register a special deallocator in the Python type object
// (see behaviors()) to do this.
// In (2) there is no problem, the dtor gets called.
-
- // PythonExtension does not use the usual Python heap allocator,
+
+ // PythonExtension does not use the usual Python heap allocator,
// instead using new/delete. We do the setting of the type object
- // and reference count, usually done by PyObject_New, in the
+ // and reference count, usually done by PyObject_New, in the
// base class ctor.
-
+
// This special deallocator does a delete on the pointer.
-
-
+
+
class PythonExtensionBase : public PyObject
{
public:
PythonExtensionBase();
virtual ~PythonExtensionBase();
-
+
public:
virtual int print( FILE *, int );
virtual Object getattr( const char * ) = 0;
@@ -422,7 +422,7 @@
virtual Object call( const Object &, const Object & );
virtual Object iter();
virtual PyObject* iternext();
-
+
// Sequence methods
virtual int sequence_length();
virtual Object sequence_concat( const Object & );
@@ -431,12 +431,12 @@
virtual Object sequence_slice( Py_ssize_t, Py_ssize_t );
virtual int sequence_ass_item( Py_ssize_t, const Object & );
virtual int sequence_ass_slice( Py_ssize_t, Py_ssize_t, const Object & );
-
+
// Mapping
virtual int mapping_length();
virtual Object mapping_subscript( const Object & );
virtual int mapping_ass_subscript( const Object &, const Object & );
-
+
// Number
virtual int number_nonzero();
virtual Object number_negative();
@@ -460,38 +460,38 @@
virtual Object number_xor( const Object & );
virtual Object number_or( const Object & );
virtual Object number_power( const Object &, const Object & );
-
+
// Buffer
virtual Py_ssize_t buffer_getreadbuffer( Py_ssize_t, void** );
virtual Py_ssize_t buffer_getwritebuffer( Py_ssize_t, void** );
virtual Py_ssize_t buffer_getsegcount( Py_ssize_t* );
-
+
private:
void missing_method( void );
static PyObject *method_call_handler( PyObject *self, PyObject *args );
};
-
+
template<TEMPLATE_TYPENAME T>
- class PythonExtension: public PythonExtensionBase
+ class PythonExtension: public PythonExtensionBase
{
public:
- static PyTypeObject* type_object()
+ static PyTypeObject* type_object()
{
return behaviors().type_object();
}
-
+
static int check( PyObject *p )
{
// is p like me?
return p->ob_type == type_object();
}
-
+
static int check( const Object& ob )
{
return check( ob.ptr());
}
-
-
+
+
//
// every object needs getattr implemented
// to support methods
@@ -500,7 +500,7 @@
{
return getattr_methods( name );
}
-
+
protected:
explicit PythonExtension()
: PythonExtensionBase()
@@ -511,18 +511,18 @@
ob_refcnt = 1;
ob_type = type_object();
#endif
-
+
// every object must support getattr
behaviors().supportGetattr();
}
-
+
virtual ~PythonExtension()
- {}
-
+ {}
+
static PythonType &behaviors()
{
static PythonType* p;
- if( p == NULL )
+ if( p == NULL )
{
#if defined( _CPPRTTI ) || defined(__GNUG__)
const char *default_name = (typeid ( T )).name();
@@ -532,15 +532,15 @@
p = new PythonType( sizeof( T ), 0, default_name );
p->dealloc( extension_object_deallocator );
}
-
+
return *p;
}
-
-
+
+
typedef Object (T::*method_varargs_function_t)( const Tuple &args );
typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws );
typedef std::map<std::string,MethodDefExt<T> *> method_map_t;
-
+
// support the default attributes, __name__, __doc__ and methods
virtual Object getattr_default( const char *_name )
{
@@ -576,39 +576,39 @@
virtual Object getattr_methods( const char *_name )
{
std::string name( _name );
-
+
method_map_t &mm = methods();
-
+
if( name == "__methods__" )
{
List methods;
-
+
for( EXPLICIT_TYPENAME method_map_t::iterator i = mm.begin(); i != mm.end(); ++i )
methods.append( String( (*i).first ) );
-
+
return methods;
}
-
+
// see if name exists
if( mm.find( name ) == mm.end() )
throw AttributeError( name );
-
+
Tuple self( 2 );
-
+
self[0] = Object( this );
self[1] = String( name );
-
+
MethodDefExt<T> *method_definition = mm[ name ];
-
+
PyObject *func = PyCFunction_New( &method_definition->ext_meth_def, self.ptr() );
-
+
return Object(func, true);
}
-
+
static void add_varargs_method( const char *name, method_varargs_function_t function, const char *doc="" )
{
method_map_t &mm = methods();
-
+
MethodDefExt<T> *method_definition = new MethodDefExt<T>
(
name,
@@ -616,14 +616,14 @@
method_varargs_call_handler,
doc
);
-
+
mm[std::string( name )] = method_definition;
}
-
+
static void add_keyword_method( const char *name, method_keyword_function_t function, const char *doc="" )
{
method_map_t &mm = methods();
-
+
MethodDefExt<T> *method_definition = new MethodDefExt<T>
(
name,
@@ -631,45 +631,45 @@
method_keyword_call_handler,
doc
);
-
+
mm[std::string( name )] = method_definition;
}
-
+
private:
static method_map_t &methods(void)
{
static method_map_t *map_of_methods = NULL;
if( map_of_methods == NULL )
map_of_methods = new method_map_t;
-
+
return *map_of_methods;
}
-
+
static PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple, PyObject *_args, PyObject *_keywords )
{
try
{
Tuple self_and_name_tuple( _self_and_name_tuple );
-
+
PyObject *self_in_cobject = self_and_name_tuple[0].ptr();
T *self = static_cast<T *>( self_in_cobject );
-
+
String name( self_and_name_tuple[1] );
-
+
method_map_t &mm = methods();
MethodDefExt<T> *meth_def = mm[ name ];
if( meth_def == NULL )
return 0;
-
+
Tuple args( _args );
// _keywords may be NULL so be careful about the way the dict is created
Dict keywords;
if( _keywords != NULL )
keywords = Dict( _keywords );
-
+
Object result( (self->*meth_def->ext_keyword_function)( args, keywords ) );
-
+
return new_reference_to( result.ptr() );
}
catch( Exception & )
@@ -677,27 +677,27 @@
return 0;
}
}
-
+
static PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple, PyObject *_args )
{
try
{
Tuple self_and_name_tuple( _self_and_name_tuple );
-
+
PyObject *self_in_cobject = self_and_name_tuple[0].ptr();
T *self = static_cast<T *>( self_in_cobject );
-
+
String name( self_and_name_tuple[1] );
-
+
method_map_t &mm = methods();
MethodDefExt<T> *meth_def = mm[ name ];
if( meth_def == NULL )
return 0;
-
+
Tuple args( _args );
-
+
Object result;
-
+
// TMM: 7Jun'01 - Adding try & catch in case of STL debug-mode exceptions.
#ifdef _STLP_DEBUG
try
@@ -712,7 +712,7 @@
#else
result = (self->*meth_def->ext_varargs_function)( args );
#endif // _STLP_DEBUG
-
+
return new_reference_to( result.ptr() );
}
catch( Exception & )
@@ -720,19 +720,19 @@
return 0;
}
}
-
+
static void extension_object_deallocator ( PyObject* t )
{
delete (T *)( t );
}
-
+
//
// prevent the compiler generating these unwanted functions
//
explicit PythonExtension( const PythonExtension<T>& other );
void operator=( const PythonExtension<T>& rhs );
};
-
+
//
// ExtensionObject<T> is an Object that will accept only T's.
//
@@ -740,30 +740,30 @@
class ExtensionObject: public Object
{
public:
-
+
explicit ExtensionObject ( PyObject *pyob )
: Object( pyob )
{
validate();
}
-
+
ExtensionObject( const ExtensionObject<T>& other )
: Object( *other )
{
validate();
}
-
+
ExtensionObject( const Object& other )
: Object( *other )
{
validate();
}
-
+
ExtensionObject& operator= ( const Object& rhs )
{
return (*this = *rhs );
}
-
+
ExtensionObject& operator= ( PyObject* rhsp )
{
if( ptr() == rhsp )
@@ -771,12 +771,12 @@
set( rhsp );
return *this;
}
-
+
virtual bool accepts ( PyObject *pyob ) const
{
return ( pyob && T::check( pyob ));
- }
-
+ }
+
//
// Obtain a pointer to the PythonExtension object
//
@@ -785,7 +785,7 @@
return static_cast<T *>( ptr() );
}
};
-
+
} // Namespace Py
// End of CXX_Extensions.h
#endif
Modified: branches/v0_98_5_maint/agg24/include/agg_alpha_mask_u8.h
===================================================================
--- branches/v0_98_5_maint/agg24/include/agg_alpha_mask_u8.h 2009-02-23 17:30:07 UTC (rev 6927)
+++ branches/v0_98_5_maint/agg24/include/agg_alpha_mask_u8.h 2009-02-23 17:38:35 UTC (rev 6928)
@@ -2,8 +2,8 @@
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
-// Permission to copy, use, modify, sell and distribute this software
-// is granted provided this copyright notice appears in all copies.
+// Permission to copy, use, modify, sell and distribute this software
+// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
@@ -30,15 +30,15 @@
{
static unsigned calculate(const int8u* p) { return *p; }
};
-
+
//=====================================================rgb_to_gray_mask_u8
template<unsigned R, unsigned G, unsigned B>
struct rgb_to_gray_mask_u8
{
- static unsigned calculate(const int8u* p)
- {
- return (p[R]*77 + p[G]*150 + p[B]*29) >> 8;
+ static unsigned calculate(const int8u* p)
+ {
+ return (p[R]*77 + p[G]*150 + p[B]*29) >> 8;
}
};
@@ -50,7 +50,7 @@
typedef int8u cover_type;
typedef alpha_mask_u8<Step, Offset, MaskF> self_type;
enum cover_scale_e
- {
+ {
cover_shift = 8,
cover_none = 0,
cover_full = 255
@@ -64,12 +64,12 @@
MaskF& mask_function() { return m_mask_function; }
const MaskF& mask_function() const { return m_mask_function; }
-
+
//--------------------------------------------------------------------
cover_type pixel(int x, int y) const
{
- if(x >= 0 && y >= 0 &&
- x < (int)m_rbuf->width() &&
+ if(x >= 0 && y >= 0 &&
+ x < (int)m_rbuf->width() &&
y < (int)m_rbuf->height())
{
return (cover_type)m_mask_function.calculate(
@@ -81,13 +81,13 @@
//--------------------------------------------------------------------
cover_type combine_pixel(int x, int y, cover_type val) const
{
- if(x >= 0 && y >= 0 &&
- x < (int)m_rbuf->width() &&
+ if(x >= 0 && y >= 0 &&
+ x < (int)m_rbuf->width() &&
y < (int)m_rbuf->height())
{
- return (cover_type)((cover_full + val *
+ return (cover_type)((cover_full + val *
m_mask_function.calculate(
- m_rbuf->row_ptr(y) + x * Step + Offset)) >>
+ m_rbuf->row_ptr(y) + x * Step + Offset)) >>
cover_shift);
}
return 0;
@@ -112,7 +112,7 @@
if(x < 0)
{
count += x;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -126,7 +126,7 @@
{
int rest = x + count - xmax - 1;
count -= rest;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -162,7 +162,7 @@
if(x < 0)
{
count += x;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -176,7 +176,7 @@
{
int rest = x + count - xmax - 1;
count -= rest;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -187,8 +187,8 @@
const int8u* mask = m_rbuf->row_ptr(y) + x * Step + Offset;
do
{
- *covers = (cover_type)((cover_full + (*covers) *
- m_mask_function.calculate(mask)) >>
+ *covers = (cover_type)((cover_full + (*covers) *
+ m_mask_function.calculate(mask)) >>
cover_shift);
++covers;
mask += Step;
@@ -214,7 +214,7 @@
if(y < 0)
{
count += y;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -228,7 +228,7 @@
{
int rest = y + count - ymax - 1;
count -= rest;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -263,7 +263,7 @@
if(y < 0)
{
count += y;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -277,7 +277,7 @@
{
int rest = y + count - ymax - 1;
count -= rest;
- if(count <= 0)
+ if(count <= 0)
{
memset(dst, 0, num_pix * sizeof(cover_type));
return;
@@ -288,8 +288,8 @@
const int8u* mask = m_rbuf->row_ptr(y) + x * Step + Offset;
do
{
- *covers = (cover_type)((cover_full + (*covers) *
- m_mask_function.calculate(mask)) >>
+ *covers = (cover_type)((cover_full + (*covers) *
+ m_mask_function.calculate(mask)) >>
cover_shift);
++covers;
mask += m_rbuf->stride();
@@ -302,11 +302,11 @@
alpha_mask_u8(const self_type&);
const self_type& operator = (const self_type&);
- rendering_buffer* m_rbuf;
+ agg::rendering_buffer* m_rbuf;
MaskF m_mask_function;
};
-
+
typedef alpha_mask_u8<1, 0> alpha_mask_gray8; //----alpha_mask_gray8
typedef alpha_mask_u8<3, 0> alpha_mask_rgb24r; //----alpha_mask_rgb24r
@@ -354,7 +354,7 @@
typedef int8u cover_type;
typedef amask_no_clip_u8<Step, Offset, MaskF> self_type;
enum cover_scale_e
- {
+ {
cover_shift = 8,
cover_none = 0,
cover_full = 255
@@ -376,13 +376,13 @@
m_rbuf->row_ptr(y) + x * Step + Offset);
}
-
+
//--------------------------------------------------------------------
cover_type combine_pixel(int x, int y, cover_type val) const
{
- return (cover_type)((cover_full + val *
+ return (cover_type)((cover_full + val *
m_mask_function.calculate(
- m_rbuf->row_ptr(y) + x * Step + Offset)) >>
+ m_rbuf->row_ptr(y) + x * Step + Offset)) >>
cover_shift);
}
@@ -407,8 +407,8 @@
const int8u* mask = m_rbuf->row_ptr(y) + x * Step + Offset;
do
{
- *dst = (cover_type)((cover_full + (*dst) *
- m_mask_function.calculate(mask)) >>
+ *dst = (cover_type)((cover_full + (*dst) *
+ m_mask_function.calculate(mask)) >>
cover_shift);
++dst;
mask += Step;
@@ -436,8 +436,8 @@
const int8u* mask = m_rbuf->row_ptr(y) + x * Step + Offset;
do
{
- *dst = (cover_type)((cover_full + (*dst) *
- m_mask_function.calculate(mask)) >>
+ *dst = (cover_type)((cover_full + (*dst) *
+ m_mask_function.calculate(mask)) >>
cover_shift);
++dst;
mask += m_rbuf->stride();
@@ -449,11 +449,11 @@
amask_no_clip_u8(const self_type&);
const self_type& operator = (const self_type&);
- rendering_buffer* m_rbuf;
+ agg::rendering_buffer* m_rbuf;
MaskF m_mask_function;
};
-
+
typedef amask_no_clip_u8<1, 0> amask_no_clip_gray8; //----amask_no_clip_gray8
typedef amask_no_clip_u8<3, 0> amask_no_clip_rgb24r; //----amask_no_clip_rgb24r
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-02-23 17:30:14
|
Revision: 6927
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6927&view=rev
Author: mdboom
Date: 2009-02-23 17:30:07 +0000 (Mon, 23 Feb 2009)
Log Message:
-----------
Add credit to Allen Haldane in comments.
Modified Paths:
--------------
branches/v0_98_5_maint/src/agg_py_path_iterator.h
Modified: branches/v0_98_5_maint/src/agg_py_path_iterator.h
===================================================================
--- branches/v0_98_5_maint/src/agg_py_path_iterator.h 2009-02-23 15:00:29 UTC (rev 6926)
+++ branches/v0_98_5_maint/src/agg_py_path_iterator.h 2009-02-23 17:30:07 UTC (rev 6927)
@@ -264,7 +264,7 @@
//are close to parallel, I calculate the distance moved perpendicular to the
//last line. Once it gets too big, the lines cannot be combined.
- // This code was originally written by someone else (John Hunter?) and I
+ // This code was originally written by Allen Haldane and I
// have modified to work in-place -- meaning not creating an entirely
// new path list each time. In order to do that without too much
// additional code complexity, it keeps a small queue around so that
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-02-23 15:00:36
|
Revision: 6926
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6926&view=rev
Author: mdboom
Date: 2009-02-23 15:00:29 +0000 (Mon, 23 Feb 2009)
Log Message:
-----------
Merged revisions 6920,6925 via svnmerge from
https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_98_5_maint
........
r6920 | mmetz_bn | 2009-02-18 09:44:08 -0500 (Wed, 18 Feb 2009) | 1 line
Added scatter_hist example
........
r6925 | mdboom | 2009-02-23 09:58:08 -0500 (Mon, 23 Feb 2009) | 2 lines
Applied Fernando Perez's fix for LaTeX output.
........
Modified Paths:
--------------
trunk/matplotlib/doc/sphinxext/inheritance_diagram.py
Property Changed:
----------------
trunk/matplotlib/
trunk/matplotlib/doc/pyplots/README
trunk/matplotlib/doc/sphinxext/gen_gallery.py
trunk/matplotlib/doc/sphinxext/gen_rst.py
trunk/matplotlib/lib/matplotlib/sphinxext/plot_directive.py
Property changes on: trunk/matplotlib
___________________________________________________________________
Modified: svnmerge-integrated
- /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6918
+ /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6925
Modified: svn:mergeinfo
- /branches/v0_91_maint:5753-5771
/branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918
+ /branches/v0_91_maint:5753-5771
/branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918,6920-6925
Property changes on: trunk/matplotlib/doc/pyplots/README
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918
+ /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925
Property changes on: trunk/matplotlib/doc/sphinxext/gen_gallery.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918
+ /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925
Property changes on: trunk/matplotlib/doc/sphinxext/gen_rst.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918
+ /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918,6920-6925
Modified: trunk/matplotlib/doc/sphinxext/inheritance_diagram.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/inheritance_diagram.py 2009-02-23 14:58:08 UTC (rev 6925)
+++ trunk/matplotlib/doc/sphinxext/inheritance_diagram.py 2009-02-23 15:00:29 UTC (rev 6926)
@@ -370,7 +370,7 @@
graph.run_dot(['-Tpdf', '-o%s' % pdf_path],
name, parts, graph_options={'size': '"6.0,6.0"'})
- return '\\includegraphics{%s}' % pdf_path
+ return '\n\\includegraphics{%s}\n\n' % pdf_path
def visit_inheritance_diagram(inner_func):
"""
Property changes on: trunk/matplotlib/lib/matplotlib/sphinxext/plot_directive.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/sphinxext/plot_directive.py:5753-5771
+ /branches/v0_91_maint/doc/sphinxext/plot_directive.py:5753-5771
/branches/v0_98_5_maint/lib/matplotlib/sphinxext/plot_directive.py:6920-6925
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-02-23 14:58:12
|
Revision: 6925
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6925&view=rev
Author: mdboom
Date: 2009-02-23 14:58:08 +0000 (Mon, 23 Feb 2009)
Log Message:
-----------
Applied Fernando Perez's fix for LaTeX output.
Modified Paths:
--------------
branches/v0_98_5_maint/doc/sphinxext/inheritance_diagram.py
Modified: branches/v0_98_5_maint/doc/sphinxext/inheritance_diagram.py
===================================================================
--- branches/v0_98_5_maint/doc/sphinxext/inheritance_diagram.py 2009-02-21 20:14:08 UTC (rev 6924)
+++ branches/v0_98_5_maint/doc/sphinxext/inheritance_diagram.py 2009-02-23 14:58:08 UTC (rev 6925)
@@ -352,7 +352,7 @@
graph.run_dot(['-Tpdf', '-o%s' % pdf_path],
name, parts, graph_options={'size': '"6.0,6.0"'})
- return '\\includegraphics{%s}' % pdf_path
+ return '\n\\includegraphics{%s}\n\n' % pdf_path
def visit_inheritance_diagram(inner_func):
"""
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-02-21 20:14:13
|
Revision: 6924
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6924&view=rev
Author: efiring
Date: 2009-02-21 20:14:08 +0000 (Sat, 21 Feb 2009)
Log Message:
-----------
Add new axis arguments to units.py docstring
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/units.py
Modified: trunk/matplotlib/lib/matplotlib/units.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/units.py 2009-02-21 19:06:58 UTC (rev 6923)
+++ trunk/matplotlib/lib/matplotlib/units.py 2009-02-21 20:14:08 UTC (rev 6924)
@@ -19,12 +19,12 @@
class DateConverter(units.ConversionInterface):
@staticmethod
- def convert(value, unit):
+ def convert(value, unit, axis):
'convert value to a scalar or array'
return dates.date2num(value)
@staticmethod
- def axisinfo(unit):
+ def axisinfo(unit, axis):
'return major and minor tick locators and formatters'
if unit!='date': return None
majloc = dates.AutoDateLocator()
@@ -34,7 +34,7 @@
label='date')
@staticmethod
- def default_units(x):
+ def default_units(x, axis):
'return the default unit for x or None'
return 'date'
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2009-02-21 19:07:03
|
Revision: 6923
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6923&view=rev
Author: efiring
Date: 2009-02-21 19:06:58 +0000 (Sat, 21 Feb 2009)
Log Message:
-----------
Improve scatter argument handling
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-02-18 19:44:29 UTC (rev 6922)
+++ trunk/matplotlib/CHANGELOG 2009-02-21 19:06:58 UTC (rev 6923)
@@ -1,3 +1,6 @@
+2009-02-21 Improve scatter argument handling; add an early error
+ message, allow inputs to have more than one dimension. - EF
+
2009-02-16 Move plot_directive.py to the installed source tree. Add
support for inline code content - MGD
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2009-02-18 19:44:29 UTC (rev 6922)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2009-02-21 19:06:58 UTC (rev 6923)
@@ -4949,8 +4949,8 @@
vmin=None, vmax=None, alpha=1.0, linewidths=None,
verts=None, **kwargs)
- Make a scatter plot of *x* versus *y*, where *x*, *y* are 1-D
- sequences of the same length, *N*.
+ Make a scatter plot of *x* versus *y*, where *x*, *y* are
+ converted to 1-D sequences which must be of the same length, *N*.
Keyword arguments:
@@ -5088,24 +5088,35 @@
x = self.convert_xunits(x)
y = self.convert_yunits(y)
+ # np.ma.ravel yields an ndarray, not a masked array,
+ # unless its argument is a masked array.
+ x = np.ma.ravel(x)
+ y = np.ma.ravel(y)
+ if x.size != y.size:
+ raise ValueError("x and y must be the same size")
+
+ s = np.ma.ravel(s) # This doesn't have to match x, y in size.
+
+ c_is_stringy = is_string_like(c) or cbook.is_sequence_of_strings(c)
+ if not c_is_stringy:
+ c = np.asanyarray(c)
+ if c.size == x.size:
+ c = np.ma.ravel(c)
+
x, y, s, c = cbook.delete_masked_points(x, y, s, c)
+ scales = s # Renamed for readability below.
- if is_string_like(c) or cbook.is_sequence_of_strings(c):
+ if c_is_stringy:
colors = mcolors.colorConverter.to_rgba_array(c, alpha)
else:
- sh = np.shape(c)
# The inherent ambiguity is resolved in favor of color
# mapping, not interpretation as rgb or rgba:
- if len(sh) == 1 and sh[0] == len(x):
+ if c.size == x.size:
colors = None # use cmap, norm after collection is created
else:
colors = mcolors.colorConverter.to_rgba_array(c, alpha)
- if not iterable(s):
- scales = (s,)
- else:
- scales = s
if faceted:
edgecolors = None
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jr...@us...> - 2009-02-18 19:44:32
|
Revision: 6922
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6922&view=rev
Author: jrevans
Date: 2009-02-18 19:44:29 +0000 (Wed, 18 Feb 2009)
Log Message:
-----------
Unit-Test harness initial check-in.
Added Paths:
-----------
trunk/matplotlib/test/
trunk/matplotlib/test/README.txt
trunk/matplotlib/test/mplTest/
trunk/matplotlib/test/mplTest/MplNosePlugin.py
trunk/matplotlib/test/mplTest/MplTestCase.py
trunk/matplotlib/test/mplTest/TestTEMPLATE.py
trunk/matplotlib/test/mplTest/__init__.py
trunk/matplotlib/test/mplTest/compare.py
trunk/matplotlib/test/mplTest/directories.py
trunk/matplotlib/test/mplTest/path_utils.py
trunk/matplotlib/test/mplTest/units/
trunk/matplotlib/test/mplTest/units/Duration.py
trunk/matplotlib/test/mplTest/units/Epoch.py
trunk/matplotlib/test/mplTest/units/EpochConverter.py
trunk/matplotlib/test/mplTest/units/StrConverter.py
trunk/matplotlib/test/mplTest/units/UnitDbl.py
trunk/matplotlib/test/mplTest/units/UnitDblConverter.py
trunk/matplotlib/test/mplTest/units/UnitDblFormatter.py
trunk/matplotlib/test/mplTest/units/__init__.py
trunk/matplotlib/test/run-mpl-test.py
trunk/matplotlib/test/test_artists/
trunk/matplotlib/test/test_backends/
trunk/matplotlib/test/test_backends/TestAgg.py
trunk/matplotlib/test/test_basemap/
trunk/matplotlib/test/test_cxx/
trunk/matplotlib/test/test_mathtext/
trunk/matplotlib/test/test_matplotlib/
trunk/matplotlib/test/test_matplotlib/TestAxes.py
trunk/matplotlib/test/test_matplotlib/TestCookbook.py
trunk/matplotlib/test/test_matplotlib/TestTickers.py
trunk/matplotlib/test/test_matplotlib/baseline/
trunk/matplotlib/test/test_matplotlib/baseline/TestAxes/
trunk/matplotlib/test/test_matplotlib/baseline/TestAxes/default_datetime.png
trunk/matplotlib/test/test_matplotlib/baseline/TestAxes/empty_datetime.png
trunk/matplotlib/test/test_matplotlib/baseline/TestAxes/formatter_ticker_001.png
trunk/matplotlib/test/test_matplotlib/baseline/TestAxes/formatter_ticker_002.png
trunk/matplotlib/test/test_matplotlib/baseline/TestAxes/formatter_ticker_003.png
trunk/matplotlib/test/test_matplotlib/baseline/TestAxes/formatter_ticker_004.png
trunk/matplotlib/test/test_matplotlib/baseline/TestAxes/formatter_ticker_005.png
trunk/matplotlib/test/test_matplotlib/baseline/TestTickers/
trunk/matplotlib/test/test_matplotlib/baseline/TestTickers/DateFormatter_fractionalSeconds.png
trunk/matplotlib/test/test_matplotlib/baseline/TestTickers/RRuleLocator_bounds.png
trunk/matplotlib/test/test_numerix/
trunk/matplotlib/test/test_plots/
trunk/matplotlib/test/test_plots/TestAnnotation.py
trunk/matplotlib/test/test_plots/TestPlot.py
trunk/matplotlib/test/test_plots/TestPolar.py
trunk/matplotlib/test/test_plots/TestSpan.py
trunk/matplotlib/test/test_plots/baseline/
trunk/matplotlib/test/test_plots/baseline/TestAnnotation/
trunk/matplotlib/test/test_plots/baseline/TestAnnotation/offset_points.png
trunk/matplotlib/test/test_plots/baseline/TestAnnotation/polar_axes.png
trunk/matplotlib/test/test_plots/baseline/TestAnnotation/polar_coords.png
trunk/matplotlib/test/test_plots/baseline/TestPlot/
trunk/matplotlib/test/test_plots/baseline/TestPlot/const_xy.png
trunk/matplotlib/test/test_plots/baseline/TestPlot/shaped_data.png
trunk/matplotlib/test/test_plots/baseline/TestPlot/single_date.png
trunk/matplotlib/test/test_plots/baseline/TestPlot/single_point.png
trunk/matplotlib/test/test_plots/baseline/TestPolar/
trunk/matplotlib/test/test_plots/baseline/TestPolar/polar_units.png
trunk/matplotlib/test/test_plots/baseline/TestPolar/polar_wrap_180.png
trunk/matplotlib/test/test_plots/baseline/TestPolar/polar_wrap_360.png
trunk/matplotlib/test/test_plots/baseline/TestSpan/
trunk/matplotlib/test/test_plots/baseline/TestSpan/axhspan_epoch.png
trunk/matplotlib/test/test_plots/baseline/TestSpan/axvspan_epoch.png
trunk/matplotlib/test/test_pylab/
trunk/matplotlib/test/test_transforms/
Added: trunk/matplotlib/test/README.txt
===================================================================
--- trunk/matplotlib/test/README.txt (rev 0)
+++ trunk/matplotlib/test/README.txt 2009-02-18 19:44:29 UTC (rev 6922)
@@ -0,0 +1,290 @@
+========================================================================
+ matplotlib test structure
+========================================================================
+
+===== How To Use
+
+= Running
+
+Run the 'run-mpl-test.py' script to execute the test harness. This must
+be run with the version of python that you wish to test matplotlib with.
+This means that it must have nose installed (and PIL if image comparison
+is to be done). By default this will pick up whatever python is on your
+path, so make sure it is the correct one.
+
+- Command-Line Options
+In addition to the standard nose command-line options, there are several
+specific to the matplotlib test harness. They are as follows:
+
+ -t TAG, --with-tag=TAG
+ Will only run test cases that have the specified tag.
+ Each test case should have a 'tag' attribute (if a
+ case does not have one, then it is assumed to be an
+ empty list). The 'tag' attribute is a list of
+ strings, where each value is a representative propery
+ of the test case. Example tags are 'qt' or 'units'.
+ This can be specified multiple times.
+ --without-tag=TAG This will run those test cases that do not have the
+ specified tags.
+ --clean This will remove all output files and saved results.
+ If this is specified, no other processing will be
+ performed.
+ --all This will runn all test programs regardless of working
+ directory.
+ --keep Keep any generated output files in a directory called
+ 'saved-results'. This directory will be created if it
+ doesn't already exist. This directory is in the same
+ location as the test case whose results are being
+ saved.
+ --keep-failed This acts just like '--keep' except will only keeps
+ the results from tests that error or fail.
+ --make-test=testName
+ Creates a template test case file in the current
+ directory with the name TestFoo. Where 'Foo' is the
+ provided test name.
+
+
+- Running Specific Tests
+In order to can specify the exact test case you want to run use the
+standard nose mechanism. For example, if you have the following setup:
+
+TestFoo.py
+ def test_func():
+ ...
+
+ class TestFoo:
+ def test_bar( self ):
+ ...
+ def test_bug( self ):
+ ...
+
+Then to test everything in TestFoo.py do the following:
+$> run-mpl-test.py TestFoo.py
+
+To run all tests in the test class TestFoo do this:
+$> run-mpl-test.py TestFoo.py:TestFoo
+
+To run the specific 'test_bar' methodd do the following:
+$> run-mpl-test.py TestFoo.py:TestFoo.test_bar
+
+
+= Detecting Test Cases
+
+When running the matplotlib test script it will search for all tests
+in the current working directory and below (unless '--all' is specified).
+This is provided that the current working directory is a sub-directory
+of the matplotlib test directory. In the event that it is not, then the
+matplotlib root test directory will be used and all appropriate test cases
+will be run.
+
+This will not search outside of the test structure and will not look in
+the mplTest module. This will only search for test cases in the root
+test directory and any of its sub-directories.
+
+= Saving Results
+
+When using the keep flag any generated files in the 'output' directory
+are copied to the 'saved-results/<classname>' directory, where <classname>
+is the name of the unit-test class. This means that for each test case
+within a given test class, all output files should have unique names.
+
+The 'saved-results' directory will always contain the results from the
+last test run. This is considered a volatile directory since running
+the test cases without the '--keep' flag will remove any existing
+'saved-results' directory. This is to ensure the integrity of the
+saved results, they will always match the last test run.
+
+= Filtering Tests
+
+In the case of filtering via tags, a unit-test cane have multiple tags.
+When running the test program if any tags are specified as 'skip' then
+this will take precedence over any tags that might say 'process'. For
+example, if a test case has both the 'gui' and 'qt' tag, but the command-
+line is specified with the following flags:
+ '--with-tag=gui --without-tag=qt'
+then the example test case will not be run because it matches the skip
+tag.
+
+
+===== Directory Structure
+
+There are several directories in the matplotlib test structure. The first
+directory is the 'mplTest' directory. This is the matplotlib test module
+and contains the various python scripts that the test harness needs to
+run. The remaining directories are as follows and contain the various test
+cases for matplotlib.
+
+mplTest
+ This directory does not contain any test cases, rather it is the location
+ of the matplotlib specific utilities for performing unit tests.
+
+test_artists
+ This directory contains tests that focus on the rendering aspects of
+ the various artists. Essentially the artist derived functionality.
+
+test_backends
+ This directory contains various tests that focus on making sure the
+ various backend targets work.
+
+test_basemap
+ This directory contains test cases that excercise the basemap add-on
+ module.
+
+test_cxx
+ This directoy contains tests that focus on testing the interface of
+ the compiled code contained in matplotlib.
+
+test_mathtext
+ This directory contains tests that focus on excercising the mathtext
+ sub-system.
+
+test_numerix
+ This directory contains tests that focus on validating the numerix
+ component.
+
+test_plots
+ This directory contains tests that validate the various plot funtions.
+
+test_pylab
+ This directory has pylab specific test cases.
+
+test_transforms
+ This directory has test cases that focus on testing the various
+ transformation and projection functions.
+
+test_matplotlib
+ This directory has all other test cases. This contins test that focus
+ on making sure that Axis, Axes, Figure, etc are all acting properly. This
+ has test cases that are general to the overall funtionality of matplotlib.
+
+
+===== Writing Test Cases
+
+= The Test Case
+
+As per the nose implementation, a test case is ultimately any function that
+has the phrase 'test' in its name. The matplotlib cases however are grouped
+into directories, by what is being tested, and from there are grouped into
+classes (one class per file), by similarity.
+
+It is desireable that all matplotlib tests follow the same structure to
+not only facilitate the writing of test cases, but to make things easier
+for maintaining them and keeping things uniform.
+
+There is a class 'MplTestCase' provided to be the base class for all matplotlib
+test classes. This class provides some extra functionality in the form of
+verification functions and test data management.
+
+= Comparison Functions
+
+There are several methods provided for testing whether or not a particular
+test case should fail or succeed. The following methods are provided by
+the base matplotlib test class:
+
+- MplTestCase.checkEq( expected, actual, msg = "" )
+ Fail if the values are not equal, with the given message.
+
+- MplTestCase.checkNeq( expected, actual, msg = "" )
+ Fail if the values are equal, with the given message.
+
+- MplTestCase.checkClose( expected, actual, relTol=None, absTol=None, msg="" )
+ Fail if the floating point values are not close enough, with the given message.
+ You can specify a relative tolerance, absolute tolerance, or both.
+
+- MplTestCase.checkImage( filename, tol = 1.0e-3, msg = "" )
+ Check to see if the image is similair to the one stored in the baseline
+ directory. filename can be a fully qualified name (via the 'outFile' method),
+ or it can be the name of the file (to be passed into the 'outFile' method).
+ The default tolerance is typically fine, but might need to be adjusted in some
+ cases (see the 'compareImages' function for more details). Fails with
+ the specified message.
+
+Note that several of the tests will perform image comparison for validation
+of a specific plot. Though not 100% accurate it at least flags potential
+failures and signals a human to come and take a closer look. If an image has
+changed and after a human deems the change is acceptable, then updating the
+baseline image with the appropriate image from the 'saved-results' directory
+(when using the '--keep' or '--keep-failed' command-line arguments) will make
+the test pass properly.
+
+Image comparison depends on the python imaging library (PIL) being installed.
+If PIL is not installed, then any test cases that rely on it will not
+pass. To not run these test cases, then pass the '--without-tag=PIL'
+option on the command-line.
+
+= Directories
+
+Input data files for a given test case should be place in a directory
+called 'inputs' with the test case that uses it. A convienence function
+is provided with each test class for accessing input files.
+
+For example if a test case has an input file of the name 'inputs.txt'
+you can get the path to the file by calling 'self.inFile("inputs.txt")'.
+This is to allow for a uniform convention that all test cases can follow.
+
+Output files are handled just like input files with the exception that
+they are written to the 'output' directory and the path name can be
+had by calling 'self.outFile'. It is more important to use this mechanism
+for getting the pathname for an output file because it allows for the
+management of cleaning up and saving generated output files (It also
+significantly reduces the probability of typo errors when specifying
+where to place the files).
+
+A Third and final directory used by the test cases is the 'baseline'
+directory. This is where data files used for verifying test results
+are stored. The path name can be had by using the 'self.baseFile'
+method.
+
+Accessing these directories can be made simple (and reduce the chance of a
+typo) via the following MplTestCase methods:
+
+- MplTestCase.inFile( filename )
+ Returns the full pathname of filename in the input data directory.
+
+- MplTestCase.outFile( filename )
+ Returns the full pathname of filename in the output data directory.
+
+- MplTestCase.baseFile( filename )
+ Returns the full pathname of filename in the baseline data directory.
+
+= Units
+
+Located in the mplTest directory is a set of unit classes. These classes
+are provided for testing the various unitized data interfaces that matplotlib
+supports (ie unit conversion). These are used because they provide a very
+strict enforcement of unitized data which will test the entire spectrum of how
+unitized data might be used (it is not always meaningful to convert to
+a float without specific units given). This allows us to test for cases that
+might accidentally be performing operations that really do not make sense
+physically for unitized data.
+
+The provided classes are as follows:
+- UnitDbl
+ UnitDbl is essentially a unitized floating point number. It has a
+ minimal set of supported units (enough for testing purposes). All
+ of the mathematical operation are provided to fully test any behaviour
+ that might occur with unitized data. Remeber that unitized data has
+ rules as to how it can be applied to one another (a value of distance
+ cannot be added to a value of time). Thus we need to guard against any
+ accidental "default" conversion that will strip away the meaning of the
+ data and render it neutered.
+
+- Epoch
+ Epoch is different than a UnitDbl of time. Time is something that can be
+ measured where an Epoch is a specific moment in time. Epochs are typically
+ referenced as an offset from some predetermined epoch. Conceptally an Epoch
+ is like saying 'January 1, 2000 at 12:00 UTC'. It is a specific
+ time, but more importantly it is a time with a frame. In the example
+ the frame is 'UTC'. This class is provided to test the functionality of
+ matplotlib's various routines and mechanisms for dealing with datetimes.
+
+- Duration
+ A difference of two epochs is a Duration. The distinction between a
+ Duration and a UnitDbl of time is made because an Epoch can have different
+ frames (or units). In the case of our test Epoch class the two allowed
+ frames are 'UTC' and 'ET' (Note that these are rough estimates provided for
+ testing purposes and should not be used in production code where accuracy
+ of time frames is desired). As such a Duration also has a frame of
+ reference and therefore needs to be called out as different that a simple
+ measurement of time since a delta-t in one frame may not be the same in another.
+
Property changes on: trunk/matplotlib/test/README.txt
___________________________________________________________________
Added: svn:eol-style
+ LF
Added: trunk/matplotlib/test/mplTest/MplNosePlugin.py
===================================================================
--- trunk/matplotlib/test/mplTest/MplNosePlugin.py (rev 0)
+++ trunk/matplotlib/test/mplTest/MplNosePlugin.py 2009-02-18 19:44:29 UTC (rev 6922)
@@ -0,0 +1,836 @@
+#=======================================================================
+
+import os
+import sys
+import shutil
+import os.path
+import optparse
+
+import nose.case
+from nose.plugins import Plugin
+
+from path_utils import *
+import directories as dirs
+from MplTestCase import MplTestCase
+
+#=======================================================================
+
+__all__ = [ 'MplNosePlugin' ]
+
+#=======================================================================
+def getInstance( test ):
+ """Given a nose test case, will return the actual unit test instance.
+
+ We do this with a function call in case the method for getting the
+ actual unit test instance needs to change.
+ """
+ assert isinstance( test, nose.case.Test )
+
+ if isinstance( test.test, nose.case.MethodTestCase ):
+ return test.test.inst
+ elif isinstance( test.test, nose.case.FunctionTestCase ):
+ return test.test.test
+ # elif isinstance( test.test, unittest.TestCase ):
+ else:
+ return test.test
+
+
+#=======================================================================
+class MplNosePlugin( Plugin ):
+
+ enabled = True
+ name = "MplNosePlugin"
+ score = 0
+
+ KEEP_NONE = 0
+ KEEP_FAIL = 1
+ KEEP_ALL = 2
+
+ TEST_ERRORED = -1
+ TEST_FAILED = 0
+ TEST_PASSED = 1
+
+ #--------------------------------------------------------------------
+ # Some 'property' functions
+ def getRootDir( self ):
+ # The bottom directory of the stack is the root directory.
+ return self.dirStack[0]
+
+ def getInputDir( self ):
+ return os.path.join( self.currentDir, dirs.inputDirName )
+
+ def getOutputDir( self ):
+ return os.path.join( self.currentDir, dirs.outputDirName )
+
+ def getBaselineRootDir( self ):
+ return os.path.join( self.currentDir, dirs.baselineDirName )
+
+ def getSaveRootDir( self ):
+ return os.path.join( self.currentDir, dirs.saveDirName )
+
+ rootDir = property( getRootDir )
+ inputDir = property( getInputDir )
+ outputDir = property( getOutputDir )
+ baselineRootDir = property( getBaselineRootDir )
+ saveRootDir = property( getSaveRootDir )
+
+ def getBaselineDir( self, test ):
+ t = getInstance( test )
+ return os.path.join( self.baselineRootDir, t.__class__.__name__ )
+
+ def getSaveDir( self, test ):
+ t = getInstance( test )
+ return os.path.join( self.saveRootDir, t.__class__.__name__ )
+
+ #--------------------------------------------------------------------
+ def saveResults( self, test ):
+ """Save the output directory for the gived test."""
+ saveDir = self.getSaveDir( test )
+ if not os.path.exists( saveDir ):
+ mkdir( saveDir, recursive = True )
+
+ outDir = getInstance( test ).outputDir
+
+ for fname in walk( outDir ):
+ if os.path.isdir( fname ):
+ shutil.copytree( fname, saveDir )
+ else:
+ shutil.copy( fname, saveDir )
+
+ #--------------------------------------------------------------------
+ def filterTestItem( self, item ):
+ """Return true if you want the main test selector to collect tests from
+ this class, false if you don't, and None if you don't care.
+
+ Parameters:
+ item : An instance of the testable item that has a 'tag' attribute.
+ """
+
+ reallyWant = False
+ reallyDontWant = False
+
+ if hasattr( item, 'tags' ):
+ itemTags = item.tags
+ else:
+ itemTags = []
+
+ for tag in self.skipTags:
+ if tag in itemTags:
+ reallyDontWant = True
+ break
+
+ for tag in self.includeTags:
+ if tag in itemTags:
+ reallyWant = True
+ else:
+ reallyDontWant = True
+ break
+
+ if self.includeTags and not itemTags:
+ reallyDontWant = True
+
+ if reallyDontWant:
+ return False
+ if reallyWant:
+ return True
+
+ return None
+
+ #--------------------------------------------------------------------
+ def addError( self, test, err ):
+ """Called when a test raises an uncaught exception. DO NOT return a value
+ unless you want to stop other plugins from seeing that the test has
+ raised an error.
+
+ Parameters:
+ test : nose.case.Test
+ the test case
+ err : 3-tuple
+ sys.exc_info() tuple
+ """
+ self.testResults.append( (test, self.TEST_ERRORED, err) )
+
+ #--------------------------------------------------------------------
+ def addFailure( self, test, err ):
+ """Called when a test fails. DO NOT return a value unless you want to
+ stop other plugins from seeing that the test has failed.
+
+ Parameters:
+ test : nose.case.Test
+ the test case
+ err : 3-tuple
+ sys.exc_info() tuple
+ """
+ self.testResults.append( (test, self.TEST_FAILED, err) )
+
+ #--------------------------------------------------------------------
+ def addSuccess( self, test ):
+ """Called when a test passes. DO NOT return a value unless you want to
+ stop other plugins from seeing the passing test.
+
+ Parameters:
+ test : nose.case.Test
+ the test case
+ """
+ self.testResults.append( (test, self.TEST_PASSED, None) )
+
+ #--------------------------------------------------------------------
+ def afterContext( self ):
+ """Called after a context (generally a module) has been lazy-loaded,
+ imported, setup, had its tests loaded and executed, and torn down.
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def afterDirectory( self, path ):
+ """Called after all tests have been loaded from directory at path and run.
+
+ Parameters:
+ path : string
+ the directory that has finished processing
+ """
+ # Set the current directory to the previous directory
+ self.currentDir = self.dirStack.pop()
+ chdir( self.currentDir )
+ return None
+
+ #--------------------------------------------------------------------
+ def afterImport( self, filename, module ):
+ """Called after module is imported from filename. afterImport is called
+ even if the import failed.
+
+ Parameters:
+ filename : string
+ The file that was loaded
+ module : string
+ The name of the module
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def afterTest( self, test ):
+ """Called after the test has been run and the result recorded
+ (after stopTest).
+
+ Parameters:
+ test : nose.case.Test
+ the test case
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def beforeContext( self ):
+ """Called before a context (generally a module) is examined. Since the
+ context is not yet loaded, plugins don't get to know what the
+ context is; so any context operations should use a stack that is
+ pushed in beforeContext and popped in afterContext to ensure they
+ operate symmetrically.
+
+ beforeContext and afterContext are mainly useful for tracking and
+ restoring global state around possible changes from within a
+ context, whatever the context may be. If you need to operate on
+ contexts themselves, see startContext and stopContext, which are
+ passed the context in question, but are called after it has been
+ loaded (imported in the module case).
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def beforeDirectory( self, path ):
+ """Called before tests are loaded from directory at path.
+
+ Parameters:
+ path : string
+ the directory that is about to be processed
+ """
+ # Save the cuurent directory and set to the new directory.
+ self.dirStack.append( self.currentDir )
+ self.currentDir = path
+ chdir( self.currentDir )
+
+ # Remove any existing 'saved-results' directory
+ #NOTE: We must do this after setting 'self.currentDir'
+ rmdir( self.saveRootDir )
+
+ return None
+
+ #--------------------------------------------------------------------
+ def beforeImport( self, filename, module ):
+ """Called before module is imported from filename.
+
+ Parameters:
+ filename : string
+ The file that will be loaded
+ module : string
+ The name of the module found in file
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def beforeTest( self, test ):
+ """Called before the test is run (before startTest).
+
+ Parameters:
+ test : nose.case.Test
+ the test case
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def begin( self ):
+ """Called before any tests are collected or run. Use this to perform
+ any setup needed before testing begins.
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def configure( self, options, conf ):
+ """Called after the command line has been parsed, with the parsed
+ options and the config container. Here, implement any config
+ storage or changes to state or operation that are set by command
+ line options.
+
+ Do not return a value from this method unless you want to stop all
+ other plugins from being configured.
+ """
+ self.includeTags = [ t for t in options.mpl_process_tags ]
+ self.skipTags = [ t for t in options.mpl_skip_tags ]
+ self.keepLevel = options.mpl_keep
+
+ self.currentDir = os.getcwd()
+ self.dirStack = []
+
+ self.testResults = []
+
+ #--------------------------------------------------------------------
+ def describeTest( self, test ):
+ """Return a test description. Called by nose.case.Test.shortDescription.
+
+ Parameters:
+ test : nose.case.Test
+ the test case
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def finalize( self, result ):
+ """Called after all report output, including output from all plugins,
+ has been sent to the stream. Use this to print final test results
+ or perform final cleanup. Return None to allow other plugins to
+ continue printing, any other value to stop them.
+
+ Note
+ When tests are run under a test runner other than
+ nose.core.TextTestRunner, for example when tests are run via
+ 'python setup.py test', this method may be called before the default
+ report output is sent.
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def formatError( self, test, err ):
+ """Called in result.addError, before plugin.addError. If you want to
+ replace or modify the error tuple, return a new error tuple.
+
+ Parameters:
+ test : nose.case.Test
+ the test case
+ err : 3-tuple
+ sys.exc_info() tuple
+ """
+ return err
+
+ #--------------------------------------------------------------------
+ def formatFailure( self, test, err ):
+ """Called in result.addFailure, before plugin.addFailure. If you want to
+ replace or modify the error tuple, return a new error tuple. Since
+ this method is chainable, you must return the test as well, so you
+ you'll return something like:
+ return (test, err)
+
+ Parameters:
+ test : nose.case.Test
+ the test case
+ err : 3-tuple
+ sys.exc_info() tuple
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def handleError( self, test, err ):
+ """Called on addError. To handle the error yourself and prevent normal
+ error processing, return a true value.
+
+ Parameters:
+ test : nose.case.Test
+ the test case
+ err : 3-tuple
+ sys.exc_info() tuple
+ """
+ if (self.keepLevel == self.KEEP_FAIL) or (self.keepLevel == self.KEEP_ALL):
+ self.saveResults( test )
+
+ return None
+
+ #--------------------------------------------------------------------
+ def handleFailure( self, test, err ):
+ """Called on addFailure. To handle the failure yourself and prevent
+ normal failure processing, return a true value.
+
+ Parameters:
+ test : nose.case.Test
+ the test case
+ err : 3-tuple
+ sys.exc_info() tuple
+ """
+ if (self.keepLevel == self.KEEP_FAIL) or (self.keepLevel == self.KEEP_ALL):
+ self.saveResults( test )
+
+ return None
+
+ #--------------------------------------------------------------------
+ def loadTestsFromDir( self, path ):
+ """Return iterable of tests from a directory. May be a generator.
+ Each item returned must be a runnable unittest.TestCase
+ (or subclass) instance or suite instance. Return None if your
+ plugin cannot collect any tests from directory.
+
+ Parameters:
+ path : string
+ The path to the directory.
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def loadTestsFromFile( self, filename ):
+ """Return tests in this file. Return None if you are not interested in
+ loading any tests, or an iterable if you are and can load some. May
+ be a generator. If you are interested in loading tests from the file
+ and encounter no errors, but find no tests, yield False or
+ return [False].
+
+ Parameters:
+ filename : string
+ The full path to the file or directory.
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def loadTestsFromModule( self, module ):
+ """Return iterable of tests in a module. May be a generator. Each
+ item returned must be a runnable unittest.TestCase (or subclass)
+ instance. Return None if your plugin cannot collect any tests
+ from module.
+
+ Parameters:
+ module : python module
+ The module object
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def loadTestsFromName( self, name, module=None, importPath=None ):
+ """Return tests in this file or module. Return None if you are not able
+ to load any tests, or an iterable if you are. May be a generator.
+
+ Parameters:
+ name : string
+ The test name. May be a file or module name plus a test
+ callable. Use split_test_name to split into parts. Or it might
+ be some crazy name of your own devising, in which case, do
+ whatever you want.
+ module : python module
+ Module from which the name is to be loaded
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def loadTestsFromNames( self, names, module=None ):
+ """Return a tuple of (tests loaded, remaining names). Return None if you
+ are not able to load any tests. Multiple plugins may implement
+ loadTestsFromNames; the remaining name list from each will be passed
+ to the next as input.
+
+ Parameters:
+ names : iterable
+ List of test names.
+ module : python module
+ Module from which the names are to be loaded
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def loadTestsFromTestCase( self, cls ):
+ """Return tests in this test case class. Return None if you are not able
+ to load any tests, or an iterable if you are. May be a generator.
+
+ Parameters:
+ cls : class
+ The test case class. Must be subclass of unittest.TestCase.
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def loadTestsFromTestClass( self, cls ):
+ """Return tests in this test class. Class will not be a unittest.TestCase
+ subclass. Return None if you are not able to load any tests, an
+ iterable if you are. May be a generator.
+
+ Parameters:
+ cls : class
+ The test class. Must NOT be subclass of unittest.TestCase.
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def makeTest( self, obj, parent ):
+ """Given an object and its parent, return or yield one or more test
+ cases. Each test must be a unittest.TestCase (or subclass) instance.
+ This is called before default test loading to allow plugins to load
+ an alternate test case or cases for an object. May be a generator.
+
+ Parameters:
+ obj : any object
+ The object to be made into a test
+ parent : class, module or other object
+ The parent of obj (eg, for a method, the class)
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def options( self, parser, env = os.environ ):
+ """Called to allow plugin to register command line options with the parser.
+
+ Do not return a value from this method unless you want to stop all other
+ plugins from setting their options.
+
+ NOTE: By default, parser is a Python optparse.OptionParser instance.
+ """
+ helpMsg = "The following are options specific to the matplotlib test harness"
+ group = optparse.OptionGroup( parser, "Matplotlib Options", helpMsg )
+
+ # Options to handle tags
+ helpMsg = "Will only run test cases that have the specified tag. Each "
+ helpMsg += "test case should have a 'tag' attribute (if a case does not h"
+ helpMsg += "ave one, then it is assumed to be an empty list). The 'tag' "
+ helpMsg += "attribute is a list of strings, where each value is a "
+ helpMsg += "representative propery of the test case. Example tags are "
+ helpMsg += "'qt' or 'units'. This can be specified multiple times."
+ group.add_option( '-t', '--with-tag',
+ action = 'append', type = 'string', dest = 'mpl_process_tags',
+ default = [], metavar = 'TAG', help = helpMsg )
+
+ helpMsg = "This will run those test cases that do not have the specified tags."
+ group.add_option( '--without-tag',
+ action = 'append', type = 'string', dest = 'mpl_skip_tags',
+ default = [], metavar = 'TAG', help = helpMsg )
+
+
+ # Some Miscellaneous options
+ helpMsg = "This will remove all output files, saved results, and .pyc files. "
+ helpMsg += "If this is specified, no other processing will be performed."
+ group.add_option( '--clean',
+ action = "store_true", dest = "mpl_clean",
+ default = False, help = helpMsg )
+
+ helpMsg = "This will run all test programs regardless of working directory."
+ group.add_option( '--all',
+ action = "store_true", dest = "mpl_all",
+ default = False, help = helpMsg )
+
+
+ # Options to handle generated data files
+ helpMsg = "Keep any generated output files in a directory called "
+ helpMsg += "'saved-results'. This directory will be created if it "
+ helpMsg += "doesn't already exist. This directory is in the same "
+ helpMsg += "location as the test case whose results are being saved."
+ group.add_option( '--keep',
+ action = "store_const", dest = "mpl_keep",
+ default = self.KEEP_NONE, const = self.KEEP_ALL, help = helpMsg )
+
+ helpMsg = "This acts just like '--keep' except will only keeps the results "
+ helpMsg += "from tests that error or fail."
+ group.add_option( '--keep-failed',
+ action = "store_const", dest = "mpl_keep",
+ default = self.KEEP_NONE, const = self.KEEP_FAIL, help = helpMsg )
+
+
+ # Options to create a test case file
+ helpMsg = "Creates a template test case file in the current directory "
+ helpMsg += "with the name TestFoo. Where 'Foo' is the provided test name."
+ group.add_option( '--make-test',
+ action = 'store', dest = 'mpl_make_test',
+ default = False, metavar = 'testName', help = helpMsg )
+
+
+ parser.add_option_group( group )
+
+ #--------------------------------------------------------------------
+ def prepareTest( self, test ):
+ """Called before the test is run by the test runner. Please note the
+ article the in the previous sentence: prepareTest is called only once,
+ and is passed the test case or test suite that the test runner will
+ execute. It is not called for each individual test case. If you return
+ a non-None value, that return value will be run as the test. Use this
+ hook to wrap or decorate the test with another function. If you need
+ to modify or wrap individual test cases, use prepareTestCase instead.
+
+ Parameters:
+ test : nose.case.Test
+ the test case
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def prepareTestCase( self, test ):
+ """Prepare or wrap an individual test case. Called before execution of
+ the test. The test passed here is a nose.case.Test instance; the case
+ to be executed is in the test attribute of the passed case. To modify
+ the test to be run, you should return a callable that takes one
+ argument (the test result object) -- it is recommended that you do not
+ side-effect the nose.case.Test instance you have been passed.
+
+ Keep in mind that when you replace the test callable you are replacing
+ the run() method of the test case -- including the exception handling
+ and result calls, etc.
+
+ Parameters:
+ test : nose.case.Test
+ the test case
+ """
+ # Save the dir names in the test class instance to make it available
+ # to the individual test cases.
+ t = getInstance( test )
+ t.inputDir = self.inputDir
+ t.outputDir = self.outputDir
+ t.baselineDir = self.getBaselineDir( test )
+ t.workingDir = self.currentDir
+
+ return None
+
+ #--------------------------------------------------------------------
+ def prepareTestLoader( self, loader ):
+ """Called before tests are loaded. To replace the test loader, return a
+ test loader. To allow other plugins to process the test loader,
+ return None. Only one plugin may replace the test loader. Only valid
+ when using nose.TestProgram.
+
+ Parameters:
+ loader : nose.loader.TestLoader or other loader instance
+ the test loader
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def prepareTestResult( self, result ):
+ """Called before the first test is run. To use a different test result
+ handler for all tests than the given result, return a test result
+ handler. NOTE however that this handler will only be seen by tests,
+ that is, inside of the result proxy system. The TestRunner and
+ TestProgram -- whether nose's or other -- will continue to see the
+ original result handler. For this reason, it is usually better to
+ monkeypatch the result (for instance, if you want to handle some
+ exceptions in a unique way). Only one plugin may replace the result,
+ but many may monkeypatch it. If you want to monkeypatch and stop
+ other plugins from doing so, monkeypatch and return the patched result.
+
+ Parameters:
+ result : nose.result.TextTestResult or other result instance
+ the test result
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def prepareTestRunner( self, runner ):
+ """Called before tests are run. To replace the test runner, return a
+ test runner. To allow other plugins to process the test runner,
+ return None. Only valid when using nose.TestProgram.
+
+ Parameters:
+ runner : nose.core.TextTestRunner or other runner instance
+ the test runner
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def report( self, stream ):
+ """Called after all error output has been printed. Print your plugin's
+ report to the provided stream. Return None to allow other plugins to
+ print reports, any other value to stop them.
+
+ Parameters:
+ stream : file-like object
+ stream object; send your output here
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def setOutputStream( self, stream ):
+ """Called before test output begins. To direct test output to a new
+ stream, return a stream object, which must implement a write(msg)
+ method. If you only want to note the stream, not capture or redirect
+ it, then return None.
+
+ Parameters:
+ stream : file-like object
+ the original output stream
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def startContext( self, context ):
+ """Called before context setup and the running of tests in the context.
+ Note that tests have already been loaded from the context before this call.
+
+ Parameters:
+ context : module, class or other object
+ the context about to be setup. May be a module or class, or
+ any other object that contains tests.
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def startTest( self, test ):
+ """Called before each test is run. DO NOT return a value unless you want
+ to stop other plugins from seeing the test start.
+
+ Parameters:
+ test : nose.case.Test
+ the test case
+ """
+ # make sure there is a fresh output directory to use.
+ rmdir( self.outputDir )
+ mkdir( self.outputDir, recursive = True )
+
+ # sys.stdout.write( "%s\n %s \n" % (test.id(), test.shortDescription()) )
+ print "%s" % (test.id())
+ print " %s" % (test.shortDescription())
+
+ #--------------------------------------------------------------------
+ def stopContext( self, context ):
+ """Called after the tests in a context have run and the context has been
+ torn down.
+
+ Parameters:
+ context : module, class or other object
+ the context that has just been torn down.
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def stopTest( self, test ):
+ """Called after each test is run. DO NOT return a value unless you want
+ to stop other plugins from seeing that the test has stopped.
+
+ Parameters:
+ test : nose.case.Test
+ the test case
+ """
+ assert test == self.testResults[-1][0]
+
+ if self.keepLevel == self.KEEP_ALL:
+ self.saveResults( test )
+
+ # KEEP_FAIL is handled by the 'handleError' and 'handleFailed' methods.
+
+ rmdir( self.outputDir )
+
+ #--------------------------------------------------------------------
+ def testName( self, test ):
+ """Return a short test name. Called by nose.case.Test.__str__.
+
+ Parameters:
+ test : nose.case.Test
+ the test case
+ """
+ return None
+
+ #--------------------------------------------------------------------
+ def wantClass( self, cls ):
+ """Return true if you want the main test selector to collect tests from
+ this class, false if you don't, and None if you don't care.
+
+ Parameters:
+ cls : class
+ The class being examined by the selector
+ """
+ # Filter out classes that do not inherit from MplTestCase
+ if not issubclass( cls, MplTestCase ):
+ return False
+
+ return self.filterTestItem( cls )
+
+ #--------------------------------------------------------------------
+ def wantDirectory( self, dirname ):
+ """Return true if you want test collection to descend into this
+ directory, false if you do not, and None if you don't care.
+
+ Parameters:
+ dirname : string
+ Full path to directory being examined by the selector
+ """
+ # Skip the unit-test utility module.
+ if dirname == os.path.join( self.rootDir, 'mplTest' ):
+ return False
+
+ return None
+
+ #--------------------------------------------------------------------
+ def wantFile( self, file ):
+ """Return true if you want to collect tests from this file, false if
+ you do not and None if you don't care.
+
+ Parameters:
+ file : string
+ Full path to file being examined by the selector
+ """
+ # Skip anything not under the root test directory
+ if self.rootDir not in file:
+ return False
+
+ return None
+
+ #--------------------------------------------------------------------
+ def wantFunction( self, function ):
+ """Return true to collect this function as a test, false to prevent it
+ from being collected, and None if you don't care.
+
+ Parameters:
+ function : function
+ The function object being examined by the selector
+ """
+ #TODO: Filter out functions that exist outside of the test-structure
+ name = function.__name__.lower()
+ if "disabled" in name: return False
+ return self.filterTestItem( function )
+
+ #--------------------------------------------------------------------
+ def wantMethod( self, method ):
+ """Return true to collect this method as a test, false to prevent it
+ from being collected, and None if you don't care.
+
+ Parameters:
+ method : unbound method
+ The method object being examined by the selector
+ """
+ #TODO: Filter out methods that exist outside of the test-structure
+ name = method.__name__.lower()
+ if "disabled" in name: return False
+ return self.filterTestItem( method )
+
+ #--------------------------------------------------------------------
+ def wantModule( self, module ):
+ """Return true if you want to collection to descend into this module,
+ false to prevent the collector from descending into the module, and
+ None if you don't care.
+
+ Parameters:
+ module : python module
+ The module object being examined by the selector
+ """
+ #TODO: Filter out modules that exist outside of the test-structure
+ name = module.__name__.lower()
+ if "disabled" in name: return False
+ return self.filterTestItem( module )
+
+
Added: trunk/matplotlib/test/mplTest/MplTestCase.py
===================================================================
--- trunk/matplotlib/test/mplTest/MplTestCase.py (rev 0)
+++ trunk/matplotlib/test/mplTest/MplTestCase.py 2009-02-18 19:44:29 UTC (rev 6922)
@@ -0,0 +1,117 @@
+#=======================================================================
+"""Defines the base matplotlib test-case."""
+#=======================================================================
+
+import os
+import os.path
+import unittest
+
+import compare
+import path_utils
+
+#=======================================================================
+
+__all__ = [ 'MplTestCase' ]
+
+#=======================================================================
+class MplTestCase( unittest.TestCase ):
+ """This is the base class for the matplotlib unit-tests.
+
+ It provides a few utility functions for accessing managed directories:
+ - inputs - All input files for the test case are stored here.
+ - outputs - All output files for the test case are written here.
+ - baseline - All baseline files (those used for verifying results) for
+ athe test case are stored here.
+ """
+ #--------------------------------------------------------------------
+ def inFile( self, fname ):
+ """Returns the pathname of the specified input file."""
+ return os.path.join( self.inputDir, fname )
+
+ def outFile( self, fname ):
+ """Returns the pathname of the specified output file."""
+ return os.path.join( self.outputDir, fname )
+
+ def baseFile( self, fname ):
+ """Returns the pathname of the specified basline file."""
+ return os.path.join( self.baselineDir, fname )
+
+ #--------------------------------------------------------------------
+ def checkImage( self, outfname, tol = 1.0e-3, msg = "" ):
+ """Check to see if the image is similair to one stored in the
+ baseline directory.
+ """
+ if self.outputDir in outfname:
+ # We are passed the path name and just want the file name.
+ actualImage = outfname
+ basename = path_utils.name( outfname )
+ else:
+ basename = outfname
+ actualImage = self.outFile( basename )
+
+ baselineImage = self.baseFile( basename )
+
+ errorMessage = compare.compareImages( baselineImage, actualImage, tol )
+
+ if errorMessage:
+ self.fail( msg + "\n" + errorMessage )
+
+ #--------------------------------------------------------------------
+ def checkEq( expected, actual, msg = "" ):
+ """Fail if the values are not equal, with the given message."""
+ if not expected == actual:
+ expectedStr = str( expected )
+ actualStr = str( actual )
+ isMultiLine = ( "\n" in expectedStr or "\n" in actualStr or
+ len( expectedStr ) > 70 or len( actualStr ) > 70 )
+
+ if isMultiLine:
+ if msg:
+ msg += "\n\n"
+ msg += "Expected:\n"
+ msg += expectedStr + "\n\n"
+ msg += "Actual:\n"
+ msg += actualStr + "\n"
+ else:
+ if msg:
+ msg += "\n"
+ msg += " Expected: " + expectedStr + "\n"
+ msg += " Actual: " + actualStr + "\n"
+
+ self.fail( msg )
+
+ #--------------------------------------------------------------------
+ def checkNeq( expected, actual, msg = "" ):
+ """Fail is the values are equal, with the given message."""
+ if expected == actual:
+ expectedStr = str( expected )
+ isMultiLine = ( "\n" in expectedStr or len( expectedStr ) > 55 )
+
+ if isMultiLine:
+ if msg:
+ msg += "\n\n"
+ msg += "Expected and actual should not be equal.\n"
+ msg += "Expected and actual:\n"
+ msg += expectedStr + "\n"
+ else:
+ if msg:
+ msg += "\n"
+ msg += " Expected and actual should not be equal.\n"
+ msg += " Expected and actual: " + expectedStr + "\n"
+
+ self.fail( msg )
+
+ #--------------------------------------------------------------------
+ def checkClose( expected, actual, relTol = None, absTol = None, msg = "" ):
+ """Fail if the floating point values are not close enough, with
+ the givem message.
+
+ You can specify a relative tolerance, absolute tolerance, or both.
+ """
+ errorMessage = compare.compareFloat( expected, actual, relTol, absTol )
+
+ if errorMessage:
+ self.fail( msg + "\n" + errorMessage )
+
+ #--------------------------------------------------------------------
+
Added: trunk/matplotlib/test/mplTest/TestTEMPLATE.py
===================================================================
--- trunk/matplotlib/test/mplTest/TestTEMPLATE.py (rev 0)
+++ trunk/matplotlib/test/mplTest/TestTEMPLATE.py 2009-02-18 19:44:29 UTC (rev 6922)
@@ -0,0 +1,62 @@
+#=======================================================================
+"""The UNITTEST unit-test class implementation."""
+#=======================================================================
+
+from mplTest import *
+
+#=======================================================================
+# Add import modules below.
+import matplotlib
+matplotlib.use( "Agg", warn = False )
+
+import pylab
+import numpy as npy
+#
+#=======================================================================
+
+#=======================================================================
+class TestUNITTEST( MplTestCase ):
+ """UNITTEST unit test class."""
+
+ # Uncomment any appropriate tags
+ tags = [
+ # 'gui', # requires the creation of a gui window
+ # 'agg', # uses agg in the backend
+ # 'agg-only', # uses only agg in the backend
+ # 'wx', # uses wx in the backend
+ # 'qt', # uses qt in the backend
+ # 'ps', # uses the postscript backend
+ # 'pdf', # uses the PDF backend
+ # 'units', # uses units in the test
+ # 'PIL', # uses PIL for image comparison
+ ]
+
+ #--------------------------------------------------------------------
+ def setUp( self ):
+ """Setup any data needed for the unit test."""
+ #TODO: Put set-up code here
+ pass
+
+ #--------------------------------------------------------------------
+ def tearDown( self ):
+ """Clean-up any generated files here."""
+ #TODO: Put clean-up code here
+ pass
+
+ #--------------------------------------------------------------------
+ def test_case_001( self ):
+ """TODO: A very brief description of the test case."""
+ #TODO: Put test-case code here
+
+ fname = self.outFile( "test_case_001a" )
+ fout = open( fname, 'w' )
+ fout.write( "A UNITTEST.test_case_001 output file.\n" )
+ fout.close()
+
+ fname = self.outFile( "test_case_001b" )
+ fout = open( fname, 'w' )
+ fout.write( "Another UNITTEST.test_case_001 output file.\n" )
+ fout.close()
+
+ pass
+
Added: trunk/matplotlib/test/mplTest/__init__.py
===================================================================
--- trunk/matplotlib/test/mplTest/__init__.py (rev 0)
+++ trunk/matplotlib/test/mplTest/__init__.py 2009-02-18 19:44:29 UTC (rev 6922)
@@ -0,0 +1,13 @@
+
+"""
+A matplotlib unit test module. This module provides several utilities for
+performing unit-tests on matplotlib. Theis module depends on a properly
+installed version of 'nose'.
+"""
+
+from directories import *
+
+from mplTest.MplNosePlugin import MplNosePlugin
+from mplTest.MplTestCase import MplTestCase
+
+import mplTest.units as units
Added: trunk/matplotlib/test/mplTest/compare.py
===================================================================
--- trunk/matplotlib/test/mplTest/compare.py (rev 0)
+++ trunk/matplotlib/test/mplTest/compare.py 2009-02-18 19:44:29 UTC (rev 6922)
@@ -0,0 +1,121 @@
+#=======================================================================
+""" A set of utilities for comparing results.
+"""
+#=======================================================================
+
+import math
+import operator
+
+#=======================================================================
+
+__all__ = [
+ 'compareFloat',
+ 'compareImages',
+ ]
+
+#-----------------------------------------------------------------------
+def compareFloat( expected, actual, relTol = None, absTol = None ):
+ """Fail if the floating point values are not close enough, with
+ the givem message.
+
+ You can specify a relative tolerance, absolute tolerance, or both.
+ """
+ if relTol is None and absTol is None:
+ exMsg = "You haven't specified a 'relTol' relative tolerance "
+ exMsg += "or a 'absTol' absolute tolerance function argument. "
+ exMsg += "You must specify one."
+ raise ValueError, exMsg
+
+ msg = ""
+
+ if absTol is not None:
+ absDiff = abs( expected - actual )
+ if absTol < absDiff:
+ expectedStr = str( expected )
+ actualStr = str( actual )
+ absDiffStr = str( absDiff )
+ absTolStr = str( absTol )
+
+ msg += "\n"
+ msg += " Expected: " + expectedStr + "\n"
+ msg += " Actual: " + actualStr + "\n"
+ msg += " Abs Diff: " + absDiffStr + "\n"
+ msg += " Abs Tol: " + absTolStr + "\n"
+
+ if relTol is not None:
+ # The relative difference of the two values. If the expected value is
+ # zero, then return the absolute value of the difference.
+ relDiff = abs( expected - actual )
+ if expected:
+ relDiff = relDiff / abs( expected )
+
+ if relTol < relDiff:
+
+ # The relative difference is a ratio, so it's always unitless.
+ relDiffStr = str( relDiff )
+ relTolStr = str( relTol )
+
+ expectedStr = str( expected )
+ actualStr = str( actual )
+
+ msg += "\n"
+ msg += " Expected: " + expectedStr + "\n"
+ msg += " Actual: " + actualStr + "\n"
+ msg += " Rel Diff: " + relDiffStr + "\n"
+ msg += " Rel Tol: " + relTolStr + "\n"
+
+ if msg:
+ return msg
+ else:
+ return None
+
+#-----------------------------------------------------------------------
+def compareImages( expected, ac...
[truncated message content] |
|
From: <mme...@us...> - 2009-02-18 14:54:23
|
Revision: 6921
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6921&view=rev
Author: mmetz_bn
Date: 2009-02-18 14:54:13 +0000 (Wed, 18 Feb 2009)
Log Message:
-----------
Added scatter_hist example
Added Paths:
-----------
trunk/matplotlib/examples/pylab_examples/scatter_hist.py
Added: trunk/matplotlib/examples/pylab_examples/scatter_hist.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/scatter_hist.py (rev 0)
+++ trunk/matplotlib/examples/pylab_examples/scatter_hist.py 2009-02-18 14:54:13 UTC (rev 6921)
@@ -0,0 +1,49 @@
+import numpy as np
+import matplotlib.pyplot as plt
+from matplotlib.ticker import NullFormatter
+
+# the random data
+x = np.random.randn(1000)
+y = np.random.randn(1000)
+
+nullfmt = NullFormatter() # no labels
+
+# definitions for the axes
+left, width = 0.1, 0.65
+bottom, height = 0.1, 0.65
+bottom_h = left_h = left+width+0.02
+
+rect_scatter = [left, bottom, width, height]
+rect_histx = [left, bottom_h, width, 0.2]
+rect_histy = [left_h, bottom, 0.2, height]
+
+# start with a rectangular Figure
+plt.figure(1, figsize=(8,8))
+
+axScatter = plt.axes(rect_scatter)
+axHistx = plt.axes(rect_histx)
+axHisty = plt.axes(rect_histy)
+
+# no labels
+axHistx.xaxis.set_major_formatter(nullfmt)
+axHisty.yaxis.set_major_formatter(nullfmt)
+
+# the scatter plot:
+axScatter.scatter(x, y)
+
+# now determine nice limits by hand:
+binwidth = 0.25
+xymax = np.max( [np.max(np.fabs(x)), np.max(np.fabs(y))] )
+lim = ( int(xymax/binwidth) + 1) * binwidth
+
+axScatter.set_xlim( (-lim, lim) )
+axScatter.set_ylim( (-lim, lim) )
+
+bins = np.arange(-lim, lim + binwidth, binwidth)
+axHistx.hist(x, bins=bins)
+axHisty.hist(y, bins=bins, orientation='horizontal')
+
+axHistx.set_xlim( axScatter.get_xlim() )
+axHisty.set_ylim( axScatter.get_ylim() )
+
+plt.show()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mme...@us...> - 2009-02-18 14:44:11
|
Revision: 6920
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6920&view=rev
Author: mmetz_bn
Date: 2009-02-18 14:44:08 +0000 (Wed, 18 Feb 2009)
Log Message:
-----------
Added scatter_hist example
Added Paths:
-----------
branches/v0_98_5_maint/examples/pylab_examples/scatter_hist.py
Added: branches/v0_98_5_maint/examples/pylab_examples/scatter_hist.py
===================================================================
--- branches/v0_98_5_maint/examples/pylab_examples/scatter_hist.py (rev 0)
+++ branches/v0_98_5_maint/examples/pylab_examples/scatter_hist.py 2009-02-18 14:44:08 UTC (rev 6920)
@@ -0,0 +1,49 @@
+import numpy as np
+import matplotlib.pyplot as plt
+from matplotlib.ticker import NullFormatter
+
+# the random data
+x = np.random.randn(1000)
+y = np.random.randn(1000)
+
+nullfmt = NullFormatter() # no labels
+
+# definitions for the axes
+left, width = 0.1, 0.65
+bottom, height = 0.1, 0.65
+bottom_h = left_h = left+width+0.02
+
+rect_scatter = [left, bottom, width, height]
+rect_histx = [left, bottom_h, width, 0.2]
+rect_histy = [left_h, bottom, 0.2, height]
+
+# start with a rectangular Figure
+plt.figure(1, figsize=(8,8))
+
+axScatter = plt.axes(rect_scatter)
+axHistx = plt.axes(rect_histx)
+axHisty = plt.axes(rect_histy)
+
+# no labels
+axHistx.xaxis.set_major_formatter(nullfmt)
+axHisty.yaxis.set_major_formatter(nullfmt)
+
+# the scatter plot:
+axScatter.scatter(x, y)
+
+# now determine nice limits by hand:
+binwidth = 0.25
+xymax = np.max( [np.max(np.fabs(x)), np.max(np.fabs(y))] )
+lim = ( int(xymax/binwidth) + 1) * binwidth
+
+axScatter.set_xlim( (-lim, lim) )
+axScatter.set_ylim( (-lim, lim) )
+
+bins = np.arange(-lim, lim + binwidth, binwidth)
+axHistx.hist(x, bins=bins)
+axHisty.hist(y, bins=bins, orientation='horizontal')
+
+axHistx.set_xlim( axScatter.get_xlim() )
+axHisty.set_ylim( axScatter.get_ylim() )
+
+plt.show()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-02-16 15:31:16
|
Revision: 6919
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6919&view=rev
Author: mdboom
Date: 2009-02-16 15:31:13 +0000 (Mon, 16 Feb 2009)
Log Message:
-----------
Merged revisions 6918 via svnmerge from
https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_98_5_maint
........
r6918 | mdboom | 2009-02-16 10:23:25 -0500 (Mon, 16 Feb 2009) | 2 lines
Move plot_directive to installed source tree. Add support for inline code.
........
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/doc/conf.py
Added Paths:
-----------
trunk/matplotlib/lib/matplotlib/sphinxext/plot_directive.py
Removed Paths:
-------------
trunk/matplotlib/doc/sphinxext/plot_directive.py
Property Changed:
----------------
trunk/matplotlib/
trunk/matplotlib/doc/pyplots/README
trunk/matplotlib/doc/sphinxext/gen_gallery.py
trunk/matplotlib/doc/sphinxext/gen_rst.py
Property changes on: trunk/matplotlib
___________________________________________________________________
Modified: svnmerge-integrated
- /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6916
+ /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6918
Modified: svn:mergeinfo
- /branches/v0_91_maint:5753-5771
/branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916
+ /branches/v0_91_maint:5753-5771
/branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916,6918
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-02-16 15:23:25 UTC (rev 6918)
+++ trunk/matplotlib/CHANGELOG 2009-02-16 15:31:13 UTC (rev 6919)
@@ -1,3 +1,6 @@
+2009-02-16 Move plot_directive.py to the installed source tree. Add
+ support for inline code content - MGD
+
2009-02-16 Move mathmpl.py to the installed source tree so it is
available to other projects. - MGD
Modified: trunk/matplotlib/doc/conf.py
===================================================================
--- trunk/matplotlib/doc/conf.py 2009-02-16 15:23:25 UTC (rev 6918)
+++ trunk/matplotlib/doc/conf.py 2009-02-16 15:31:13 UTC (rev 6919)
@@ -28,8 +28,9 @@
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['matplotlib.sphinxext.mathmpl', 'math_symbol_table',
- 'sphinx.ext.autodoc', 'matplotlib.sphinxext.only_directives',
- 'plot_directive', 'inheritance_diagram', 'gen_gallery', 'gen_rst']
+ 'sphinx.ext.autodoc', # 'matplotlib.sphinxext.only_directives',
+ 'matplotlib.sphinxext.plot_directive', 'inheritance_diagram',
+ 'gen_gallery', 'gen_rst']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
Property changes on: trunk/matplotlib/doc/pyplots/README
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916
+ /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918
Property changes on: trunk/matplotlib/doc/sphinxext/gen_gallery.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916
+ /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918
Property changes on: trunk/matplotlib/doc/sphinxext/gen_rst.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916
+ /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916,6918
Deleted: trunk/matplotlib/doc/sphinxext/plot_directive.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/plot_directive.py 2009-02-16 15:23:25 UTC (rev 6918)
+++ trunk/matplotlib/doc/sphinxext/plot_directive.py 2009-02-16 15:31:13 UTC (rev 6919)
@@ -1,303 +0,0 @@
-"""A special directive for including a matplotlib plot.
-
-Given a path to a .py file, it includes the source code inline, then:
-
-- On HTML, will include a .png with a link to a high-res .png.
-
-- On LaTeX, will include a .pdf
-
-This directive supports all of the options of the `image` directive,
-except for `target` (since plot will add its own target).
-
-Additionally, if the :include-source: option is provided, the literal
-source will be included inline, as well as a link to the source.
-
-The set of file formats to generate can be specified with the
-plot_formats configuration variable.
-"""
-
-import sys, os, glob, shutil, imp, warnings, cStringIO
-from docutils.parsers.rst import directives
-try:
- # docutils 0.4
- from docutils.parsers.rst.directives.images import align
-except ImportError:
- # docutils 0.5
- from docutils.parsers.rst.directives.images import Image
- align = Image.align
-from docutils import nodes
-
-import matplotlib
-import matplotlib.cbook as cbook
-matplotlib.use('Agg')
-import matplotlib.pyplot as plt
-import matplotlib.image as image
-from matplotlib import _pylab_helpers
-
-if hasattr(os.path, 'relpath'):
- relpath = os.path.relpath
-else:
- def relpath(target, base=os.curdir):
- """
- Return a relative path to the target from either the current dir or an optional base dir.
- Base can be a directory specified either as absolute or relative to current dir.
- """
-
- if not os.path.exists(target):
- raise OSError, 'Target does not exist: '+target
-
- if not os.path.isdir(base):
- raise OSError, 'Base is not a directory or does not exist: '+base
-
- base_list = (os.path.abspath(base)).split(os.sep)
- target_list = (os.path.abspath(target)).split(os.sep)
-
- # On the windows platform the target may be on a completely different drive from the base.
- if os.name in ['nt','dos','os2'] and base_list[0] <> target_list[0]:
- raise OSError, 'Target is on a different drive to base. Target: '+target_list[0].upper()+', base: '+base_list[0].upper()
-
- # Starting from the filepath root, work out how much of the filepath is
- # shared by base and target.
- for i in range(min(len(base_list), len(target_list))):
- if base_list[i] <> target_list[i]: break
- else:
- # If we broke out of the loop, i is pointing to the first differing path elements.
- # If we didn't break out of the loop, i is pointing to identical path elements.
- # Increment i so that in all cases it points to the first differing path elements.
- i+=1
-
- rel_list = [os.pardir] * (len(base_list)-i) + target_list[i:]
- return os.path.join(*rel_list)
-
-def write_char(s):
- sys.stdout.write(s)
- sys.stdout.flush()
-
-options = {'alt': directives.unchanged,
- 'height': directives.length_or_unitless,
- 'width': directives.length_or_percentage_or_unitless,
- 'scale': directives.nonnegative_int,
- 'align': align,
- 'class': directives.class_option,
- 'include-source': directives.flag }
-
-template = """
-.. htmlonly::
-
- [%(links)s]
-
- .. image:: %(tmpdir)s/%(outname)s.png
- %(options)s
-
-.. latexonly::
- .. image:: %(tmpdir)s/%(outname)s.pdf
- %(options)s
-"""
-
-exception_template = """
-.. htmlonly::
-
- [`source code <%(linkdir)s/%(basename)s.py>`__]
-
-Exception occurred rendering plot.
-
-"""
-
-def out_of_date(original, derived):
- """
- Returns True if derivative is out-of-date wrt original,
- both of which are full file paths.
- """
- return (not os.path.exists(derived))
- # or os.stat(derived).st_mtime < os.stat(original).st_mtime)
-
-def runfile(fullpath):
- """
- Import a Python module from a path.
- """
- # Change the working directory to the directory of the example, so
- # it can get at its data files, if any.
- pwd = os.getcwd()
- path, fname = os.path.split(fullpath)
- sys.path.insert(0, os.path.abspath(path))
- stdout = sys.stdout
- sys.stdout = cStringIO.StringIO()
- os.chdir(path)
- try:
- fd = open(fname)
- module = imp.load_module("__main__", fd, fname, ('py', 'r', imp.PY_SOURCE))
- except:
- raise
- finally:
- del sys.path[0]
- os.chdir(pwd)
- sys.stdout = stdout
- return module
-
-def makefig(fullpath, outdir):
- """
- run a pyplot script and save the low and high res PNGs and a PDF in _static
- """
- formats = [('png', 80), ('hires.png', 200), ('pdf', 50)]
-
- fullpath = str(fullpath) # todo, why is unicode breaking this
-
- basedir, fname = os.path.split(fullpath)
- basename, ext = os.path.splitext(fname)
- all_exists = True
-
- # Look for single-figure output files first
- for format, dpi in formats:
- outname = os.path.join(outdir, '%s.%s' % (basename, format))
- if out_of_date(fullpath, outname):
- all_exists = False
- break
-
- if all_exists:
- write_char('.' * len(formats))
- return 1
-
- # Then look for multi-figure output files, assuming
- # if we have some we have all...
- i = 0
- while True:
- all_exists = True
- for format, dpi in formats:
- outname = os.path.join(outdir, '%s_%02d.%s' % (basename, i, format))
- if out_of_date(fullpath, outname):
- all_exists = False
- break
- if all_exists:
- i += 1
- else:
- break
-
- if i != 0:
- write_char('.' * i * len(formats))
- return i
-
- # We didn't find the files, so build them
-
- plt.close('all') # we need to clear between runs
- matplotlib.rcdefaults()
- # Set a figure size that doesn't overflow typical browser windows
- matplotlib.rcParams['figure.figsize'] = (5.5, 4.5)
-
- try:
- runfile(fullpath)
- except:
- s = cbook.exception_to_str("Exception running plot %s" % fullpath)
- warnings.warn(s)
- return 0
-
- fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
- for i, figman in enumerate(fig_managers):
- for format, dpi in formats:
- if len(fig_managers) == 1:
- outname = basename
- else:
- outname = "%s_%02d" % (basename, i)
- outpath = os.path.join(outdir, '%s.%s' % (outname, format))
- try:
- figman.canvas.figure.savefig(outpath, dpi=dpi)
- except:
- s = cbook.exception_to_str("Exception running plot %s" % fullpath)
- warnings.warn(s)
- return 0
-
- write_char('*')
-
- return len(fig_managers)
-
-def plot_directive(name, arguments, options, content, lineno,
- content_offset, block_text, state, state_machine):
- """
- Handle the plot directive.
- """
- formats = setup.config.plot_formats
- if type(formats) == str:
- formats = eval(formats)
-
- reference = directives.uri(arguments[0])
- basedir, fname = os.path.split(reference)
- basename, ext = os.path.splitext(fname)
- basedir = relpath(basedir, setup.app.builder.srcdir)
-
- # Get the directory of the rst file, and determine the relative
- # path from the resulting html file to the plot_directive links
- # (linkdir). This relative path is used for html links *only*,
- # and not the embedded image. That is given an absolute path to
- # the temporary directory, and then sphinx moves the file to
- # build/html/_images for us later.
- rstdir, rstfile = os.path.split(state_machine.document.attributes['source'])
- reldir = rstdir[len(setup.confdir)+1:]
- relparts = [p for p in os.path.split(reldir) if p.strip()]
- nparts = len(relparts)
- outdir = os.path.join('plot_directive', basedir)
- linkdir = ('../' * nparts) + outdir
-
- # tmpdir is where we build all the output files. This way the
- # plots won't have to be redone when generating latex after html.
- tmpdir = os.path.abspath(os.path.join('build', outdir))
- if not os.path.exists(tmpdir):
- cbook.mkdirs(tmpdir)
-
- # destdir is the directory within the output to store files
- # that we'll be linking to -- not the embedded images.
- destdir = os.path.abspath(os.path.join(setup.app.builder.outdir, outdir))
- if not os.path.exists(destdir):
- cbook.mkdirs(destdir)
-
- # Generate the figures, and return the number of them
- num_figs = makefig(reference, tmpdir)
-
- if options.has_key('include-source'):
- contents = open(reference, 'r').read()
- lines = ['::', ''] + [' %s'%row.rstrip() for row in contents.split('\n')]
- del options['include-source']
- else:
- lines = []
-
- if num_figs > 0:
- options = [' :%s: %s' % (key, val) for key, val in
- options.items()]
- options = "\n".join(options)
- shutil.copyfile(reference, os.path.join(destdir, fname))
-
- for i in range(num_figs):
- if num_figs == 1:
- outname = basename
- else:
- outname = "%s_%02d" % (basename, i)
-
- # Copy the linked-to files to the destination within the build tree,
- # and add a link for them
- links = ['`source code <%(linkdir)s/%(basename)s.py>`__']
- for format in formats[1:]:
- shutil.copyfile(os.path.join(tmpdir, outname + "." + format),
- os.path.join(destdir, outname + "." + format))
- links.append('`%s <%s/%s.%s>`__' % (format, linkdir, outname, format))
- links = ', '.join(links) % locals()
-
- # Output the resulting reST
- lines.extend((template % locals()).split('\n'))
- else:
- lines.extend((exception_template % locals()).split('\n'))
-
- if len(lines):
- state_machine.insert_input(
- lines, state_machine.input_lines.source(0))
-
- return []
-
-def setup(app):
- setup.app = app
- setup.config = app.config
- setup.confdir = app.confdir
-
- app.add_directive('plot', plot_directive, False, (1, 0, 1), **options)
- app.add_config_value(
- 'plot_formats',
- ['png', 'hires.png', 'pdf'],
- True)
-
Copied: trunk/matplotlib/lib/matplotlib/sphinxext/plot_directive.py (from rev 6918, branches/v0_98_5_maint/lib/matplotlib/sphinxext/plot_directive.py)
===================================================================
--- trunk/matplotlib/lib/matplotlib/sphinxext/plot_directive.py (rev 0)
+++ trunk/matplotlib/lib/matplotlib/sphinxext/plot_directive.py 2009-02-16 15:31:13 UTC (rev 6919)
@@ -0,0 +1,331 @@
+"""A special directive for including a matplotlib plot.
+
+Given a path to a .py file, it includes the source code inline, then:
+
+- On HTML, will include a .png with a link to a high-res .png.
+
+- On LaTeX, will include a .pdf
+
+This directive supports all of the options of the `image` directive,
+except for `target` (since plot will add its own target).
+
+Additionally, if the :include-source: option is provided, the literal
+source will be included inline, as well as a link to the source.
+
+The set of file formats to generate can be specified with the
+plot_formats configuration variable.
+"""
+
+import sys, os, glob, shutil, hashlib, imp, warnings, cStringIO
+try:
+ from hashlib import md5
+except ImportError:
+ from md5 import md5
+from docutils.parsers.rst import directives
+try:
+ # docutils 0.4
+ from docutils.parsers.rst.directives.images import align
+except ImportError:
+ # docutils 0.5
+ from docutils.parsers.rst.directives.images import Image
+ align = Image.align
+from docutils import nodes
+
+import matplotlib
+import matplotlib.cbook as cbook
+matplotlib.use('Agg')
+import matplotlib.pyplot as plt
+import matplotlib.image as image
+from matplotlib import _pylab_helpers
+
+import only_directives
+
+if hasattr(os.path, 'relpath'):
+ relpath = os.path.relpath
+else:
+ def relpath(target, base=os.curdir):
+ """
+ Return a relative path to the target from either the current dir or an optional base dir.
+ Base can be a directory specified either as absolute or relative to current dir.
+ """
+
+ if not os.path.exists(target):
+ raise OSError, 'Target does not exist: '+target
+
+ if not os.path.isdir(base):
+ raise OSError, 'Base is not a directory or does not exist: '+base
+
+ base_list = (os.path.abspath(base)).split(os.sep)
+ target_list = (os.path.abspath(target)).split(os.sep)
+
+ # On the windows platform the target may be on a completely different drive from the base.
+ if os.name in ['nt','dos','os2'] and base_list[0] <> target_list[0]:
+ raise OSError, 'Target is on a different drive to base. Target: '+target_list[0].upper()+', base: '+base_list[0].upper()
+
+ # Starting from the filepath root, work out how much of the filepath is
+ # shared by base and target.
+ for i in range(min(len(base_list), len(target_list))):
+ if base_list[i] <> target_list[i]: break
+ else:
+ # If we broke out of the loop, i is pointing to the first differing path elements.
+ # If we didn't break out of the loop, i is pointing to identical path elements.
+ # Increment i so that in all cases it points to the first differing path elements.
+ i+=1
+
+ rel_list = [os.pardir] * (len(base_list)-i) + target_list[i:]
+ return os.path.join(*rel_list)
+
+def write_char(s):
+ sys.stdout.write(s)
+ sys.stdout.flush()
+
+options = {'alt': directives.unchanged,
+ 'height': directives.length_or_unitless,
+ 'width': directives.length_or_percentage_or_unitless,
+ 'scale': directives.nonnegative_int,
+ 'align': align,
+ 'class': directives.class_option,
+ 'include-source': directives.flag }
+
+template = """
+.. htmlonly::
+
+ [%(links)s]
+
+ .. image:: %(tmpdir)s/%(outname)s.png
+ %(options)s
+
+.. latexonly::
+ .. image:: %(tmpdir)s/%(outname)s.pdf
+ %(options)s
+"""
+
+exception_template = """
+.. htmlonly::
+
+ [`source code <%(linkdir)s/%(basename)s.py>`__]
+
+Exception occurred rendering plot.
+
+"""
+
+def out_of_date(original, derived):
+ """
+ Returns True if derivative is out-of-date wrt original,
+ both of which are full file paths.
+ """
+ return (not os.path.exists(derived))
+ # or os.stat(derived).st_mtime < os.stat(original).st_mtime)
+
+def runfile(fullpath):
+ """
+ Import a Python module from a path.
+ """
+ # Change the working directory to the directory of the example, so
+ # it can get at its data files, if any.
+ pwd = os.getcwd()
+ path, fname = os.path.split(fullpath)
+ sys.path.insert(0, os.path.abspath(path))
+ stdout = sys.stdout
+ sys.stdout = cStringIO.StringIO()
+ os.chdir(path)
+ try:
+ fd = open(fname)
+ module = imp.load_module("__main__", fd, fname, ('py', 'r', imp.PY_SOURCE))
+ except:
+ raise
+ finally:
+ del sys.path[0]
+ os.chdir(pwd)
+ sys.stdout = stdout
+ return module
+
+def makefig(fullpath, code, outdir):
+ """
+ run a pyplot script and save the low and high res PNGs and a PDF in _static
+ """
+ formats = [('png', 80), ('hires.png', 200), ('pdf', 50)]
+
+ fullpath = str(fullpath) # todo, why is unicode breaking this
+ basedir, fname = os.path.split(fullpath)
+ basename, ext = os.path.splitext(fname)
+
+ if str(basename) == "None":
+ import pdb
+ pdb.set_trace()
+
+ all_exists = True
+
+ # Look for single-figure output files first
+ for format, dpi in formats:
+ outname = os.path.join(outdir, '%s.%s' % (basename, format))
+ if out_of_date(fullpath, outname):
+ all_exists = False
+ break
+
+ if all_exists:
+ write_char('.' * len(formats))
+ return 1
+
+ # Then look for multi-figure output files, assuming
+ # if we have some we have all...
+ i = 0
+ while True:
+ all_exists = True
+ for format, dpi in formats:
+ outname = os.path.join(outdir, '%s_%02d.%s' % (basename, i, format))
+ if out_of_date(fullpath, outname):
+ all_exists = False
+ break
+ if all_exists:
+ i += 1
+ else:
+ break
+
+ if i != 0:
+ write_char('.' * i * len(formats))
+ return i
+
+ # We didn't find the files, so build them
+
+ plt.close('all') # we need to clear between runs
+ matplotlib.rcdefaults()
+ # Set a figure size that doesn't overflow typical browser windows
+ matplotlib.rcParams['figure.figsize'] = (5.5, 4.5)
+
+ if code is not None:
+ exec(code)
+ else:
+ try:
+ runfile(fullpath)
+ except:
+ s = cbook.exception_to_str("Exception running plot %s" % fullpath)
+ warnings.warn(s)
+ return 0
+
+ fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
+ for i, figman in enumerate(fig_managers):
+ for format, dpi in formats:
+ if len(fig_managers) == 1:
+ outname = basename
+ else:
+ outname = "%s_%02d" % (basename, i)
+ outpath = os.path.join(outdir, '%s.%s' % (outname, format))
+ try:
+ figman.canvas.figure.savefig(outpath, dpi=dpi)
+ except:
+ s = cbook.exception_to_str("Exception running plot %s" % fullpath)
+ warnings.warn(s)
+ return 0
+
+ write_char('*')
+
+ return len(fig_managers)
+
+def plot_directive(name, arguments, options, content, lineno,
+ content_offset, block_text, state, state_machine):
+ """
+ Handle the plot directive.
+ """
+ formats = setup.config.plot_formats
+ if type(formats) == str:
+ formats = eval(formats)
+
+ # The user may provide a filename *or* Python code content, but not both
+ if len(arguments) == 1:
+ reference = directives.uri(arguments[0])
+ basedir, fname = os.path.split(reference)
+ basename, ext = os.path.splitext(fname)
+ basedir = relpath(basedir, setup.app.builder.srcdir)
+ if len(content):
+ raise ValueError("plot directive may not specify both a filename and inline content")
+ content = None
+ else:
+ basedir = "inline"
+ content = '\n'.join(content)
+ # Since we don't have a filename, use a hash based on the content
+ reference = basename = md5(content).hexdigest()[-10:]
+ fname = None
+
+ # Get the directory of the rst file, and determine the relative
+ # path from the resulting html file to the plot_directive links
+ # (linkdir). This relative path is used for html links *only*,
+ # and not the embedded image. That is given an absolute path to
+ # the temporary directory, and then sphinx moves the file to
+ # build/html/_images for us later.
+ rstdir, rstfile = os.path.split(state_machine.document.attributes['source'])
+ reldir = rstdir[len(setup.confdir)+1:]
+ relparts = [p for p in os.path.split(reldir) if p.strip()]
+ nparts = len(relparts)
+ outdir = os.path.join('plot_directive', basedir)
+ linkdir = ('../' * nparts) + outdir
+
+ # tmpdir is where we build all the output files. This way the
+ # plots won't have to be redone when generating latex after html.
+ tmpdir = os.path.abspath(os.path.join('build', outdir))
+ if not os.path.exists(tmpdir):
+ cbook.mkdirs(tmpdir)
+
+ # destdir is the directory within the output to store files
+ # that we'll be linking to -- not the embedded images.
+ destdir = os.path.abspath(os.path.join(setup.app.builder.outdir, outdir))
+ if not os.path.exists(destdir):
+ cbook.mkdirs(destdir)
+
+ # Generate the figures, and return the number of them
+ num_figs = makefig(reference, content, tmpdir)
+
+ if options.has_key('include-source'):
+ if content is None:
+ content = open(reference, 'r').read()
+ lines = ['::', ''] + [' %s'%row.rstrip() for row in content.split('\n')]
+ del options['include-source']
+ else:
+ lines = []
+
+ if num_figs > 0:
+ options = [' :%s: %s' % (key, val) for key, val in
+ options.items()]
+ options = "\n".join(options)
+ if fname is not None:
+ shutil.copyfile(reference, os.path.join(destdir, fname))
+
+ for i in range(num_figs):
+ if num_figs == 1:
+ outname = basename
+ else:
+ outname = "%s_%02d" % (basename, i)
+
+ # Copy the linked-to files to the destination within the build tree,
+ # and add a link for them
+ links = []
+ if fname is not None:
+ links.append('`source code <%(linkdir)s/%(basename)s.py>`__')
+ for format in formats[1:]:
+ shutil.copyfile(os.path.join(tmpdir, outname + "." + format),
+ os.path.join(destdir, outname + "." + format))
+ links.append('`%s <%s/%s.%s>`__' % (format, linkdir, outname, format))
+ links = ', '.join(links) % locals()
+
+ # Output the resulting reST
+ lines.extend((template % locals()).split('\n'))
+ else:
+ lines.extend((exception_template % locals()).split('\n'))
+
+ if len(lines):
+ state_machine.insert_input(
+ lines, state_machine.input_lines.source(0))
+
+ return []
+
+def setup(app):
+ setup.app = app
+ setup.config = app.config
+ setup.confdir = app.confdir
+
+ app.add_directive('plot', plot_directive, True, (0, 1, 0), **options)
+ app.add_config_value(
+ 'plot_formats',
+ ['png', 'hires.png', 'pdf'],
+ True)
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-02-16 15:23:29
|
Revision: 6918
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6918&view=rev
Author: mdboom
Date: 2009-02-16 15:23:25 +0000 (Mon, 16 Feb 2009)
Log Message:
-----------
Move plot_directive to installed source tree. Add support for inline code.
Modified Paths:
--------------
branches/v0_98_5_maint/CHANGELOG
branches/v0_98_5_maint/doc/conf.py
Added Paths:
-----------
branches/v0_98_5_maint/lib/matplotlib/sphinxext/plot_directive.py
Removed Paths:
-------------
branches/v0_98_5_maint/doc/sphinxext/plot_directive.py
Modified: branches/v0_98_5_maint/CHANGELOG
===================================================================
--- branches/v0_98_5_maint/CHANGELOG 2009-02-16 14:24:56 UTC (rev 6917)
+++ branches/v0_98_5_maint/CHANGELOG 2009-02-16 15:23:25 UTC (rev 6918)
@@ -1,3 +1,6 @@
+2009-02-16 Move plot_directive.py to the installed source tree. Add
+ support for inline code content - MGD
+
2009-02-16 Move mathmpl.py to the installed source tree so it is
available to other projects. - MGD
Modified: branches/v0_98_5_maint/doc/conf.py
===================================================================
--- branches/v0_98_5_maint/doc/conf.py 2009-02-16 14:24:56 UTC (rev 6917)
+++ branches/v0_98_5_maint/doc/conf.py 2009-02-16 15:23:25 UTC (rev 6918)
@@ -28,8 +28,9 @@
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['matplotlib.sphinxext.mathmpl', 'math_symbol_table',
- 'sphinx.ext.autodoc', 'matplotlib.sphinxext.only_directives',
- 'plot_directive', 'inheritance_diagram', 'gen_gallery', 'gen_rst']
+ 'sphinx.ext.autodoc', # 'matplotlib.sphinxext.only_directives',
+ 'matplotlib.sphinxext.plot_directive', 'inheritance_diagram',
+ 'gen_gallery', 'gen_rst']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
Deleted: branches/v0_98_5_maint/doc/sphinxext/plot_directive.py
===================================================================
--- branches/v0_98_5_maint/doc/sphinxext/plot_directive.py 2009-02-16 14:24:56 UTC (rev 6917)
+++ branches/v0_98_5_maint/doc/sphinxext/plot_directive.py 2009-02-16 15:23:25 UTC (rev 6918)
@@ -1,303 +0,0 @@
-"""A special directive for including a matplotlib plot.
-
-Given a path to a .py file, it includes the source code inline, then:
-
-- On HTML, will include a .png with a link to a high-res .png.
-
-- On LaTeX, will include a .pdf
-
-This directive supports all of the options of the `image` directive,
-except for `target` (since plot will add its own target).
-
-Additionally, if the :include-source: option is provided, the literal
-source will be included inline, as well as a link to the source.
-
-The set of file formats to generate can be specified with the
-plot_formats configuration variable.
-"""
-
-import sys, os, glob, shutil, imp, warnings, cStringIO
-from docutils.parsers.rst import directives
-try:
- # docutils 0.4
- from docutils.parsers.rst.directives.images import align
-except ImportError:
- # docutils 0.5
- from docutils.parsers.rst.directives.images import Image
- align = Image.align
-from docutils import nodes
-
-import matplotlib
-import matplotlib.cbook as cbook
-matplotlib.use('Agg')
-import matplotlib.pyplot as plt
-import matplotlib.image as image
-from matplotlib import _pylab_helpers
-
-if hasattr(os.path, 'relpath'):
- relpath = os.path.relpath
-else:
- def relpath(target, base=os.curdir):
- """
- Return a relative path to the target from either the current dir or an optional base dir.
- Base can be a directory specified either as absolute or relative to current dir.
- """
-
- if not os.path.exists(target):
- raise OSError, 'Target does not exist: '+target
-
- if not os.path.isdir(base):
- raise OSError, 'Base is not a directory or does not exist: '+base
-
- base_list = (os.path.abspath(base)).split(os.sep)
- target_list = (os.path.abspath(target)).split(os.sep)
-
- # On the windows platform the target may be on a completely different drive from the base.
- if os.name in ['nt','dos','os2'] and base_list[0] <> target_list[0]:
- raise OSError, 'Target is on a different drive to base. Target: '+target_list[0].upper()+', base: '+base_list[0].upper()
-
- # Starting from the filepath root, work out how much of the filepath is
- # shared by base and target.
- for i in range(min(len(base_list), len(target_list))):
- if base_list[i] <> target_list[i]: break
- else:
- # If we broke out of the loop, i is pointing to the first differing path elements.
- # If we didn't break out of the loop, i is pointing to identical path elements.
- # Increment i so that in all cases it points to the first differing path elements.
- i+=1
-
- rel_list = [os.pardir] * (len(base_list)-i) + target_list[i:]
- return os.path.join(*rel_list)
-
-def write_char(s):
- sys.stdout.write(s)
- sys.stdout.flush()
-
-options = {'alt': directives.unchanged,
- 'height': directives.length_or_unitless,
- 'width': directives.length_or_percentage_or_unitless,
- 'scale': directives.nonnegative_int,
- 'align': align,
- 'class': directives.class_option,
- 'include-source': directives.flag }
-
-template = """
-.. htmlonly::
-
- [%(links)s]
-
- .. image:: %(tmpdir)s/%(outname)s.png
- %(options)s
-
-.. latexonly::
- .. image:: %(tmpdir)s/%(outname)s.pdf
- %(options)s
-"""
-
-exception_template = """
-.. htmlonly::
-
- [`source code <%(linkdir)s/%(basename)s.py>`__]
-
-Exception occurred rendering plot.
-
-"""
-
-def out_of_date(original, derived):
- """
- Returns True if derivative is out-of-date wrt original,
- both of which are full file paths.
- """
- return (not os.path.exists(derived))
- # or os.stat(derived).st_mtime < os.stat(original).st_mtime)
-
-def runfile(fullpath):
- """
- Import a Python module from a path.
- """
- # Change the working directory to the directory of the example, so
- # it can get at its data files, if any.
- pwd = os.getcwd()
- path, fname = os.path.split(fullpath)
- sys.path.insert(0, os.path.abspath(path))
- stdout = sys.stdout
- sys.stdout = cStringIO.StringIO()
- os.chdir(path)
- try:
- fd = open(fname)
- module = imp.load_module("__main__", fd, fname, ('py', 'r', imp.PY_SOURCE))
- except:
- raise
- finally:
- del sys.path[0]
- os.chdir(pwd)
- sys.stdout = stdout
- return module
-
-def makefig(fullpath, outdir):
- """
- run a pyplot script and save the low and high res PNGs and a PDF in _static
- """
- formats = [('png', 80), ('hires.png', 200), ('pdf', 50)]
-
- fullpath = str(fullpath) # todo, why is unicode breaking this
-
- basedir, fname = os.path.split(fullpath)
- basename, ext = os.path.splitext(fname)
- all_exists = True
-
- # Look for single-figure output files first
- for format, dpi in formats:
- outname = os.path.join(outdir, '%s.%s' % (basename, format))
- if out_of_date(fullpath, outname):
- all_exists = False
- break
-
- if all_exists:
- write_char('.' * len(formats))
- return 1
-
- # Then look for multi-figure output files, assuming
- # if we have some we have all...
- i = 0
- while True:
- all_exists = True
- for format, dpi in formats:
- outname = os.path.join(outdir, '%s_%02d.%s' % (basename, i, format))
- if out_of_date(fullpath, outname):
- all_exists = False
- break
- if all_exists:
- i += 1
- else:
- break
-
- if i != 0:
- write_char('.' * i * len(formats))
- return i
-
- # We didn't find the files, so build them
-
- plt.close('all') # we need to clear between runs
- matplotlib.rcdefaults()
- # Set a figure size that doesn't overflow typical browser windows
- matplotlib.rcParams['figure.figsize'] = (5.5, 4.5)
-
- try:
- runfile(fullpath)
- except:
- s = cbook.exception_to_str("Exception running plot %s" % fullpath)
- warnings.warn(s)
- return 0
-
- fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
- for i, figman in enumerate(fig_managers):
- for format, dpi in formats:
- if len(fig_managers) == 1:
- outname = basename
- else:
- outname = "%s_%02d" % (basename, i)
- outpath = os.path.join(outdir, '%s.%s' % (outname, format))
- try:
- figman.canvas.figure.savefig(outpath, dpi=dpi)
- except:
- s = cbook.exception_to_str("Exception running plot %s" % fullpath)
- warnings.warn(s)
- return 0
-
- write_char('*')
-
- return len(fig_managers)
-
-def plot_directive(name, arguments, options, content, lineno,
- content_offset, block_text, state, state_machine):
- """
- Handle the plot directive.
- """
- formats = setup.config.plot_formats
- if type(formats) == str:
- formats = eval(formats)
-
- reference = directives.uri(arguments[0])
- basedir, fname = os.path.split(reference)
- basename, ext = os.path.splitext(fname)
- basedir = relpath(basedir, setup.app.builder.srcdir)
-
- # Get the directory of the rst file, and determine the relative
- # path from the resulting html file to the plot_directive links
- # (linkdir). This relative path is used for html links *only*,
- # and not the embedded image. That is given an absolute path to
- # the temporary directory, and then sphinx moves the file to
- # build/html/_images for us later.
- rstdir, rstfile = os.path.split(state_machine.document.attributes['source'])
- reldir = rstdir[len(setup.confdir)+1:]
- relparts = [p for p in os.path.split(reldir) if p.strip()]
- nparts = len(relparts)
- outdir = os.path.join('plot_directive', basedir)
- linkdir = ('../' * nparts) + outdir
-
- # tmpdir is where we build all the output files. This way the
- # plots won't have to be redone when generating latex after html.
- tmpdir = os.path.abspath(os.path.join('build', outdir))
- if not os.path.exists(tmpdir):
- cbook.mkdirs(tmpdir)
-
- # destdir is the directory within the output to store files
- # that we'll be linking to -- not the embedded images.
- destdir = os.path.abspath(os.path.join(setup.app.builder.outdir, outdir))
- if not os.path.exists(destdir):
- cbook.mkdirs(destdir)
-
- # Generate the figures, and return the number of them
- num_figs = makefig(reference, tmpdir)
-
- if options.has_key('include-source'):
- contents = open(reference, 'r').read()
- lines = ['::', ''] + [' %s'%row.rstrip() for row in contents.split('\n')]
- del options['include-source']
- else:
- lines = []
-
- if num_figs > 0:
- options = [' :%s: %s' % (key, val) for key, val in
- options.items()]
- options = "\n".join(options)
- shutil.copyfile(reference, os.path.join(destdir, fname))
-
- for i in range(num_figs):
- if num_figs == 1:
- outname = basename
- else:
- outname = "%s_%02d" % (basename, i)
-
- # Copy the linked-to files to the destination within the build tree,
- # and add a link for them
- links = ['`source code <%(linkdir)s/%(basename)s.py>`__']
- for format in formats[1:]:
- shutil.copyfile(os.path.join(tmpdir, outname + "." + format),
- os.path.join(destdir, outname + "." + format))
- links.append('`%s <%s/%s.%s>`__' % (format, linkdir, outname, format))
- links = ', '.join(links) % locals()
-
- # Output the resulting reST
- lines.extend((template % locals()).split('\n'))
- else:
- lines.extend((exception_template % locals()).split('\n'))
-
- if len(lines):
- state_machine.insert_input(
- lines, state_machine.input_lines.source(0))
-
- return []
-
-def setup(app):
- setup.app = app
- setup.config = app.config
- setup.confdir = app.confdir
-
- app.add_directive('plot', plot_directive, False, (1, 0, 1), **options)
- app.add_config_value(
- 'plot_formats',
- ['png', 'hires.png', 'pdf'],
- True)
-
Copied: branches/v0_98_5_maint/lib/matplotlib/sphinxext/plot_directive.py (from rev 6915, branches/v0_98_5_maint/doc/sphinxext/plot_directive.py)
===================================================================
--- branches/v0_98_5_maint/lib/matplotlib/sphinxext/plot_directive.py (rev 0)
+++ branches/v0_98_5_maint/lib/matplotlib/sphinxext/plot_directive.py 2009-02-16 15:23:25 UTC (rev 6918)
@@ -0,0 +1,331 @@
+"""A special directive for including a matplotlib plot.
+
+Given a path to a .py file, it includes the source code inline, then:
+
+- On HTML, will include a .png with a link to a high-res .png.
+
+- On LaTeX, will include a .pdf
+
+This directive supports all of the options of the `image` directive,
+except for `target` (since plot will add its own target).
+
+Additionally, if the :include-source: option is provided, the literal
+source will be included inline, as well as a link to the source.
+
+The set of file formats to generate can be specified with the
+plot_formats configuration variable.
+"""
+
+import sys, os, glob, shutil, hashlib, imp, warnings, cStringIO
+try:
+ from hashlib import md5
+except ImportError:
+ from md5 import md5
+from docutils.parsers.rst import directives
+try:
+ # docutils 0.4
+ from docutils.parsers.rst.directives.images import align
+except ImportError:
+ # docutils 0.5
+ from docutils.parsers.rst.directives.images import Image
+ align = Image.align
+from docutils import nodes
+
+import matplotlib
+import matplotlib.cbook as cbook
+matplotlib.use('Agg')
+import matplotlib.pyplot as plt
+import matplotlib.image as image
+from matplotlib import _pylab_helpers
+
+import only_directives
+
+if hasattr(os.path, 'relpath'):
+ relpath = os.path.relpath
+else:
+ def relpath(target, base=os.curdir):
+ """
+ Return a relative path to the target from either the current dir or an optional base dir.
+ Base can be a directory specified either as absolute or relative to current dir.
+ """
+
+ if not os.path.exists(target):
+ raise OSError, 'Target does not exist: '+target
+
+ if not os.path.isdir(base):
+ raise OSError, 'Base is not a directory or does not exist: '+base
+
+ base_list = (os.path.abspath(base)).split(os.sep)
+ target_list = (os.path.abspath(target)).split(os.sep)
+
+ # On the windows platform the target may be on a completely different drive from the base.
+ if os.name in ['nt','dos','os2'] and base_list[0] <> target_list[0]:
+ raise OSError, 'Target is on a different drive to base. Target: '+target_list[0].upper()+', base: '+base_list[0].upper()
+
+ # Starting from the filepath root, work out how much of the filepath is
+ # shared by base and target.
+ for i in range(min(len(base_list), len(target_list))):
+ if base_list[i] <> target_list[i]: break
+ else:
+ # If we broke out of the loop, i is pointing to the first differing path elements.
+ # If we didn't break out of the loop, i is pointing to identical path elements.
+ # Increment i so that in all cases it points to the first differing path elements.
+ i+=1
+
+ rel_list = [os.pardir] * (len(base_list)-i) + target_list[i:]
+ return os.path.join(*rel_list)
+
+def write_char(s):
+ sys.stdout.write(s)
+ sys.stdout.flush()
+
+options = {'alt': directives.unchanged,
+ 'height': directives.length_or_unitless,
+ 'width': directives.length_or_percentage_or_unitless,
+ 'scale': directives.nonnegative_int,
+ 'align': align,
+ 'class': directives.class_option,
+ 'include-source': directives.flag }
+
+template = """
+.. htmlonly::
+
+ [%(links)s]
+
+ .. image:: %(tmpdir)s/%(outname)s.png
+ %(options)s
+
+.. latexonly::
+ .. image:: %(tmpdir)s/%(outname)s.pdf
+ %(options)s
+"""
+
+exception_template = """
+.. htmlonly::
+
+ [`source code <%(linkdir)s/%(basename)s.py>`__]
+
+Exception occurred rendering plot.
+
+"""
+
+def out_of_date(original, derived):
+ """
+ Returns True if derivative is out-of-date wrt original,
+ both of which are full file paths.
+ """
+ return (not os.path.exists(derived))
+ # or os.stat(derived).st_mtime < os.stat(original).st_mtime)
+
+def runfile(fullpath):
+ """
+ Import a Python module from a path.
+ """
+ # Change the working directory to the directory of the example, so
+ # it can get at its data files, if any.
+ pwd = os.getcwd()
+ path, fname = os.path.split(fullpath)
+ sys.path.insert(0, os.path.abspath(path))
+ stdout = sys.stdout
+ sys.stdout = cStringIO.StringIO()
+ os.chdir(path)
+ try:
+ fd = open(fname)
+ module = imp.load_module("__main__", fd, fname, ('py', 'r', imp.PY_SOURCE))
+ except:
+ raise
+ finally:
+ del sys.path[0]
+ os.chdir(pwd)
+ sys.stdout = stdout
+ return module
+
+def makefig(fullpath, code, outdir):
+ """
+ run a pyplot script and save the low and high res PNGs and a PDF in _static
+ """
+ formats = [('png', 80), ('hires.png', 200), ('pdf', 50)]
+
+ fullpath = str(fullpath) # todo, why is unicode breaking this
+ basedir, fname = os.path.split(fullpath)
+ basename, ext = os.path.splitext(fname)
+
+ if str(basename) == "None":
+ import pdb
+ pdb.set_trace()
+
+ all_exists = True
+
+ # Look for single-figure output files first
+ for format, dpi in formats:
+ outname = os.path.join(outdir, '%s.%s' % (basename, format))
+ if out_of_date(fullpath, outname):
+ all_exists = False
+ break
+
+ if all_exists:
+ write_char('.' * len(formats))
+ return 1
+
+ # Then look for multi-figure output files, assuming
+ # if we have some we have all...
+ i = 0
+ while True:
+ all_exists = True
+ for format, dpi in formats:
+ outname = os.path.join(outdir, '%s_%02d.%s' % (basename, i, format))
+ if out_of_date(fullpath, outname):
+ all_exists = False
+ break
+ if all_exists:
+ i += 1
+ else:
+ break
+
+ if i != 0:
+ write_char('.' * i * len(formats))
+ return i
+
+ # We didn't find the files, so build them
+
+ plt.close('all') # we need to clear between runs
+ matplotlib.rcdefaults()
+ # Set a figure size that doesn't overflow typical browser windows
+ matplotlib.rcParams['figure.figsize'] = (5.5, 4.5)
+
+ if code is not None:
+ exec(code)
+ else:
+ try:
+ runfile(fullpath)
+ except:
+ s = cbook.exception_to_str("Exception running plot %s" % fullpath)
+ warnings.warn(s)
+ return 0
+
+ fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
+ for i, figman in enumerate(fig_managers):
+ for format, dpi in formats:
+ if len(fig_managers) == 1:
+ outname = basename
+ else:
+ outname = "%s_%02d" % (basename, i)
+ outpath = os.path.join(outdir, '%s.%s' % (outname, format))
+ try:
+ figman.canvas.figure.savefig(outpath, dpi=dpi)
+ except:
+ s = cbook.exception_to_str("Exception running plot %s" % fullpath)
+ warnings.warn(s)
+ return 0
+
+ write_char('*')
+
+ return len(fig_managers)
+
+def plot_directive(name, arguments, options, content, lineno,
+ content_offset, block_text, state, state_machine):
+ """
+ Handle the plot directive.
+ """
+ formats = setup.config.plot_formats
+ if type(formats) == str:
+ formats = eval(formats)
+
+ # The user may provide a filename *or* Python code content, but not both
+ if len(arguments) == 1:
+ reference = directives.uri(arguments[0])
+ basedir, fname = os.path.split(reference)
+ basename, ext = os.path.splitext(fname)
+ basedir = relpath(basedir, setup.app.builder.srcdir)
+ if len(content):
+ raise ValueError("plot directive may not specify both a filename and inline content")
+ content = None
+ else:
+ basedir = "inline"
+ content = '\n'.join(content)
+ # Since we don't have a filename, use a hash based on the content
+ reference = basename = md5(content).hexdigest()[-10:]
+ fname = None
+
+ # Get the directory of the rst file, and determine the relative
+ # path from the resulting html file to the plot_directive links
+ # (linkdir). This relative path is used for html links *only*,
+ # and not the embedded image. That is given an absolute path to
+ # the temporary directory, and then sphinx moves the file to
+ # build/html/_images for us later.
+ rstdir, rstfile = os.path.split(state_machine.document.attributes['source'])
+ reldir = rstdir[len(setup.confdir)+1:]
+ relparts = [p for p in os.path.split(reldir) if p.strip()]
+ nparts = len(relparts)
+ outdir = os.path.join('plot_directive', basedir)
+ linkdir = ('../' * nparts) + outdir
+
+ # tmpdir is where we build all the output files. This way the
+ # plots won't have to be redone when generating latex after html.
+ tmpdir = os.path.abspath(os.path.join('build', outdir))
+ if not os.path.exists(tmpdir):
+ cbook.mkdirs(tmpdir)
+
+ # destdir is the directory within the output to store files
+ # that we'll be linking to -- not the embedded images.
+ destdir = os.path.abspath(os.path.join(setup.app.builder.outdir, outdir))
+ if not os.path.exists(destdir):
+ cbook.mkdirs(destdir)
+
+ # Generate the figures, and return the number of them
+ num_figs = makefig(reference, content, tmpdir)
+
+ if options.has_key('include-source'):
+ if content is None:
+ content = open(reference, 'r').read()
+ lines = ['::', ''] + [' %s'%row.rstrip() for row in content.split('\n')]
+ del options['include-source']
+ else:
+ lines = []
+
+ if num_figs > 0:
+ options = [' :%s: %s' % (key, val) for key, val in
+ options.items()]
+ options = "\n".join(options)
+ if fname is not None:
+ shutil.copyfile(reference, os.path.join(destdir, fname))
+
+ for i in range(num_figs):
+ if num_figs == 1:
+ outname = basename
+ else:
+ outname = "%s_%02d" % (basename, i)
+
+ # Copy the linked-to files to the destination within the build tree,
+ # and add a link for them
+ links = []
+ if fname is not None:
+ links.append('`source code <%(linkdir)s/%(basename)s.py>`__')
+ for format in formats[1:]:
+ shutil.copyfile(os.path.join(tmpdir, outname + "." + format),
+ os.path.join(destdir, outname + "." + format))
+ links.append('`%s <%s/%s.%s>`__' % (format, linkdir, outname, format))
+ links = ', '.join(links) % locals()
+
+ # Output the resulting reST
+ lines.extend((template % locals()).split('\n'))
+ else:
+ lines.extend((exception_template % locals()).split('\n'))
+
+ if len(lines):
+ state_machine.insert_input(
+ lines, state_machine.input_lines.source(0))
+
+ return []
+
+def setup(app):
+ setup.app = app
+ setup.config = app.config
+ setup.confdir = app.confdir
+
+ app.add_directive('plot', plot_directive, True, (0, 1, 0), **options)
+ app.add_config_value(
+ 'plot_formats',
+ ['png', 'hires.png', 'pdf'],
+ True)
+
Property changes on: branches/v0_98_5_maint/lib/matplotlib/sphinxext/plot_directive.py
___________________________________________________________________
Added: svn:mergeinfo
+ /branches/v0_91_maint/doc/sphinxext/plot_directive.py:5753-5771
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-02-16 14:24:59
|
Revision: 6917
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6917&view=rev
Author: mdboom
Date: 2009-02-16 14:24:56 +0000 (Mon, 16 Feb 2009)
Log Message:
-----------
Merged revisions 6915-6916 via svnmerge from
https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v0_98_5_maint
........
r6915 | mdboom | 2009-02-16 09:12:13 -0500 (Mon, 16 Feb 2009) | 2 lines
Move the mathmpl Sphinx extension to the installed tree so that other projects can take advantage of it.
........
r6916 | mdboom | 2009-02-16 09:18:36 -0500 (Mon, 16 Feb 2009) | 1 line
Update CHANGELOG
........
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/doc/conf.py
trunk/matplotlib/lib/matplotlib/sphinxext/__init__.py
trunk/matplotlib/lib/matplotlib/sphinxext/mathmpl.py
trunk/matplotlib/lib/matplotlib/sphinxext/only_directives.py
trunk/matplotlib/setup.py
Added Paths:
-----------
trunk/matplotlib/lib/matplotlib/sphinxext/
Removed Paths:
-------------
trunk/matplotlib/doc/sphinxext/mathmpl.py
trunk/matplotlib/doc/sphinxext/only_directives.py
Property Changed:
----------------
trunk/matplotlib/
trunk/matplotlib/doc/pyplots/README
trunk/matplotlib/doc/sphinxext/gen_gallery.py
trunk/matplotlib/doc/sphinxext/gen_rst.py
Property changes on: trunk/matplotlib
___________________________________________________________________
Modified: svnmerge-integrated
- /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6912
+ /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6916
Modified: svn:mergeinfo
- /branches/v0_91_maint:5753-5771
/branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912
+ /branches/v0_91_maint:5753-5771
/branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912,6915-6916
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-02-16 14:18:36 UTC (rev 6916)
+++ trunk/matplotlib/CHANGELOG 2009-02-16 14:24:56 UTC (rev 6917)
@@ -1,3 +1,6 @@
+2009-02-16 Move mathmpl.py to the installed source tree so it is
+ available to other projects. - MGD
+
2009-02-14 Added the legend title support - JJL
2009-02-10 Fixed a bug in backend_pdf so it doesn't break when the setting
Modified: trunk/matplotlib/doc/conf.py
===================================================================
--- trunk/matplotlib/doc/conf.py 2009-02-16 14:18:36 UTC (rev 6916)
+++ trunk/matplotlib/doc/conf.py 2009-02-16 14:24:56 UTC (rev 6917)
@@ -27,9 +27,9 @@
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = ['mathmpl', 'math_symbol_table', 'sphinx.ext.autodoc',
- 'only_directives', 'plot_directive', 'inheritance_diagram',
- 'gen_gallery', 'gen_rst']
+extensions = ['matplotlib.sphinxext.mathmpl', 'math_symbol_table',
+ 'sphinx.ext.autodoc', 'matplotlib.sphinxext.only_directives',
+ 'plot_directive', 'inheritance_diagram', 'gen_gallery', 'gen_rst']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
Property changes on: trunk/matplotlib/doc/pyplots/README
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912
+ /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916
Property changes on: trunk/matplotlib/doc/sphinxext/gen_gallery.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912
+ /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916
Property changes on: trunk/matplotlib/doc/sphinxext/gen_rst.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912
+ /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912,6915-6916
Deleted: trunk/matplotlib/doc/sphinxext/mathmpl.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/mathmpl.py 2009-02-16 14:18:36 UTC (rev 6916)
+++ trunk/matplotlib/doc/sphinxext/mathmpl.py 2009-02-16 14:24:56 UTC (rev 6917)
@@ -1,141 +0,0 @@
-"""matplotlib-based directive for math rendering in reST using sphinx.
-
-To use this extension, add ``mathmpl`` to the list of extensions in
-:file:`conf.py`.
-
-Note:
-
-Current SVN versions of Sphinx now include built-in support for math.
-There are two flavors:
-
- - pngmath: uses dvipng to render the equation
-
- - jsmath: renders the math in the browser using Javascript
-
-To use these extensions instead of the code in this module, add
-``sphinx.ext.pngmath`` or ``sphinx.ext.jsmath`` to the list of extensions in
-:file:`conf.py` instead of ``mathmpl``.
-
-All three of these options for math are designed to behave in the same
-way.
-"""
-
-import os
-import sys
-try:
- from hashlib import md5
-except ImportError:
- from md5 import md5
-
-from docutils import nodes
-from docutils.parsers.rst import directives
-import warnings
-
-from matplotlib import rcParams
-from matplotlib.mathtext import MathTextParser
-rcParams['mathtext.fontset'] = 'cm'
-mathtext_parser = MathTextParser("Bitmap")
-
-# Define LaTeX math node:
-class latex_math(nodes.General, nodes.Element):
- pass
-
-def fontset_choice(arg):
- return directives.choice(arg, ['cm', 'stix', 'stixsans'])
-
-options_spec = {'fontset': fontset_choice}
-
-def math_role(role, rawtext, text, lineno, inliner,
- options={}, content=[]):
- i = rawtext.find('`')
- latex = rawtext[i+1:-1]
- node = latex_math(rawtext)
- node['latex'] = latex
- node['fontset'] = options.get('fontset', 'cm')
- return [node], []
-math_role.options = options_spec
-
-def math_directive(name, arguments, options, content, lineno,
- content_offset, block_text, state, state_machine):
- latex = ''.join(content)
- node = latex_math(block_text)
- node['latex'] = latex
- node['fontset'] = options.get('fontset', 'cm')
- return [node]
-
-# This uses mathtext to render the expression
-def latex2png(latex, filename, fontset='cm'):
- latex = "$%s$" % latex
- orig_fontset = rcParams['mathtext.fontset']
- rcParams['mathtext.fontset'] = fontset
- if os.path.exists(filename):
- depth = mathtext_parser.get_depth(latex, dpi=100)
- else:
- try:
- depth = mathtext_parser.to_png(filename, latex, dpi=100)
- except:
- warnings.warn("Could not render math expression %s" % latex,
- Warning)
- depth = 0
- rcParams['mathtext.fontset'] = orig_fontset
- sys.stdout.write("#")
- sys.stdout.flush()
- return depth
-
-# LaTeX to HTML translation stuff:
-def latex2html(node, source):
- inline = isinstance(node.parent, nodes.TextElement)
- latex = node['latex']
- name = 'math-%s' % md5(latex).hexdigest()[-10:]
-
- destdir = os.path.join(setup.app.builder.outdir, '_images', 'mathmpl')
- if not os.path.exists(destdir):
- os.makedirs(destdir)
- dest = os.path.join(destdir, '%s.png' % name)
- path = os.path.join(setup.app.builder.imgpath, 'mathmpl')
-
- depth = latex2png(latex, dest, node['fontset'])
-
- if inline:
- cls = ''
- else:
- cls = 'class="center" '
- if inline and depth != 0:
- style = 'style="position: relative; bottom: -%dpx"' % (depth + 1)
- else:
- style = ''
-
- return '<img src="%s/%s.png" %s%s/>' % (path, name, cls, style)
-
-def setup(app):
- setup.app = app
-
- app.add_node(latex_math)
- app.add_role('math', math_role)
-
- # Add visit/depart methods to HTML-Translator:
- def visit_latex_math_html(self, node):
- source = self.document.attributes['source']
- self.body.append(latex2html(node, source))
- def depart_latex_math_html(self, node):
- pass
-
- # Add visit/depart methods to LaTeX-Translator:
- def visit_latex_math_latex(self, node):
- inline = isinstance(node.parent, nodes.TextElement)
- if inline:
- self.body.append('$%s$' % node['latex'])
- else:
- self.body.extend(['\\begin{equation}',
- node['latex'],
- '\\end{equation}'])
- def depart_latex_math_latex(self, node):
- pass
-
- app.add_node(latex_math, html=(visit_latex_math_html,
- depart_latex_math_html))
- app.add_node(latex_math, latex=(visit_latex_math_latex,
- depart_latex_math_latex))
- app.add_role('math', math_role)
- app.add_directive('math', math_directive,
- True, (0, 0, 0), **options_spec)
Deleted: trunk/matplotlib/doc/sphinxext/only_directives.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/only_directives.py 2009-02-16 14:18:36 UTC (rev 6916)
+++ trunk/matplotlib/doc/sphinxext/only_directives.py 2009-02-16 14:24:56 UTC (rev 6917)
@@ -1,67 +0,0 @@
-"""Sphinx directives for selective inclusion of contents.
-
-A pair of directives for inserting content that will only appear in
-either html or latex.
-"""
-
-# Required modules
-from docutils.nodes import Body, Element
-from docutils.parsers.rst import directives
-
-
-# Code begins
-class only_base(Body, Element):
- def dont_traverse(self, *args, **kwargs):
- return []
-
-class html_only(only_base):
- pass
-
-class latex_only(only_base):
- pass
-
-def run(content, node_class, state, content_offset):
- text = '\n'.join(content)
- node = node_class(text)
- state.nested_parse(content, content_offset, node)
- return [node]
-
-def html_only_directive(name, arguments, options, content, lineno,
- content_offset, block_text, state, state_machine):
- return run(content, html_only, state, content_offset)
-
-def latex_only_directive(name, arguments, options, content, lineno,
- content_offset, block_text, state, state_machine):
- return run(content, latex_only, state, content_offset)
-
-def builder_inited(app):
- if app.builder.name == 'html':
- latex_only.traverse = only_base.dont_traverse
- else:
- html_only.traverse = only_base.dont_traverse
-
-def setup(app):
- app.add_directive('htmlonly', html_only_directive, True, (0, 0, 0))
- app.add_directive('latexonly', latex_only_directive, True, (0, 0, 0))
- app.add_node(html_only)
- app.add_node(latex_only)
-
- # This will *really* never see the light of day As it turns out,
- # this results in "broken" image nodes since they never get
- # processed, so best not to do this.
- # app.connect('builder-inited', builder_inited)
-
- # Add visit/depart methods to HTML-Translator:
- def visit_perform(self, node):
- pass
- def depart_perform(self, node):
- pass
- def visit_ignore(self, node):
- node.children = []
- def depart_ignore(self, node):
- node.children = []
-
- app.add_node(html_only, html=(visit_perform, depart_perform))
- app.add_node(html_only, latex=(visit_ignore, depart_ignore))
- app.add_node(latex_only, latex=(visit_perform, depart_perform))
- app.add_node(latex_only, html=(visit_ignore, depart_ignore))
Modified: trunk/matplotlib/setup.py
===================================================================
--- trunk/matplotlib/setup.py 2009-02-16 14:18:36 UTC (rev 6916)
+++ trunk/matplotlib/setup.py 2009-02-16 14:24:56 UTC (rev 6917)
@@ -58,7 +58,8 @@
'matplotlib.numerix.npyma',
'matplotlib.numerix.linear_algebra',
'matplotlib.numerix.random_array',
- 'matplotlib.numerix.fft'
+ 'matplotlib.numerix.fft',
+ 'matplotlib.sphinxext'
]
py_modules = ['pylab']
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-02-16 14:18:41
|
Revision: 6916
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6916&view=rev
Author: mdboom
Date: 2009-02-16 14:18:36 +0000 (Mon, 16 Feb 2009)
Log Message:
-----------
Update CHANGELOG
Modified Paths:
--------------
branches/v0_98_5_maint/CHANGELOG
Modified: branches/v0_98_5_maint/CHANGELOG
===================================================================
--- branches/v0_98_5_maint/CHANGELOG 2009-02-16 14:12:13 UTC (rev 6915)
+++ branches/v0_98_5_maint/CHANGELOG 2009-02-16 14:18:36 UTC (rev 6916)
@@ -1,3 +1,6 @@
+2009-02-16 Move mathmpl.py to the installed source tree so it is
+ available to other projects. - MGD
+
2009-02-04 Fix bug in mathtext related to \dots and \ldots - MGD
2009-01-29 Document 'resolution' kwarg for polar plots. Support it
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2009-02-16 14:12:18
|
Revision: 6915
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6915&view=rev
Author: mdboom
Date: 2009-02-16 14:12:13 +0000 (Mon, 16 Feb 2009)
Log Message:
-----------
Move the mathmpl Sphinx extension to the installed tree so that other projects can take advantage of it.
Modified Paths:
--------------
branches/v0_98_5_maint/doc/conf.py
branches/v0_98_5_maint/setup.py
Added Paths:
-----------
branches/v0_98_5_maint/lib/matplotlib/sphinxext/
branches/v0_98_5_maint/lib/matplotlib/sphinxext/__init__.py
branches/v0_98_5_maint/lib/matplotlib/sphinxext/mathmpl.py
branches/v0_98_5_maint/lib/matplotlib/sphinxext/only_directives.py
Removed Paths:
-------------
branches/v0_98_5_maint/doc/sphinxext/mathmpl.py
branches/v0_98_5_maint/doc/sphinxext/only_directives.py
Modified: branches/v0_98_5_maint/doc/conf.py
===================================================================
--- branches/v0_98_5_maint/doc/conf.py 2009-02-15 00:12:19 UTC (rev 6914)
+++ branches/v0_98_5_maint/doc/conf.py 2009-02-16 14:12:13 UTC (rev 6915)
@@ -27,9 +27,9 @@
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = ['mathmpl', 'math_symbol_table', 'sphinx.ext.autodoc',
- 'only_directives', 'plot_directive', 'inheritance_diagram',
- 'gen_gallery', 'gen_rst']
+extensions = ['matplotlib.sphinxext.mathmpl', 'math_symbol_table',
+ 'sphinx.ext.autodoc', 'matplotlib.sphinxext.only_directives',
+ 'plot_directive', 'inheritance_diagram', 'gen_gallery', 'gen_rst']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
Deleted: branches/v0_98_5_maint/doc/sphinxext/mathmpl.py
===================================================================
--- branches/v0_98_5_maint/doc/sphinxext/mathmpl.py 2009-02-15 00:12:19 UTC (rev 6914)
+++ branches/v0_98_5_maint/doc/sphinxext/mathmpl.py 2009-02-16 14:12:13 UTC (rev 6915)
@@ -1,119 +0,0 @@
-import os
-import sys
-try:
- from hashlib import md5
-except ImportError:
- from md5 import md5
-
-from docutils import nodes
-from docutils.parsers.rst import directives
-import warnings
-
-from matplotlib import rcParams
-from matplotlib.mathtext import MathTextParser
-rcParams['mathtext.fontset'] = 'cm'
-mathtext_parser = MathTextParser("Bitmap")
-
-# Define LaTeX math node:
-class latex_math(nodes.General, nodes.Element):
- pass
-
-def fontset_choice(arg):
- return directives.choice(arg, ['cm', 'stix', 'stixsans'])
-
-options_spec = {'fontset': fontset_choice}
-
-def math_role(role, rawtext, text, lineno, inliner,
- options={}, content=[]):
- i = rawtext.find('`')
- latex = rawtext[i+1:-1]
- node = latex_math(rawtext)
- node['latex'] = latex
- node['fontset'] = options.get('fontset', 'cm')
- return [node], []
-math_role.options = options_spec
-
-def math_directive(name, arguments, options, content, lineno,
- content_offset, block_text, state, state_machine):
- latex = ''.join(content)
- node = latex_math(block_text)
- node['latex'] = latex
- node['fontset'] = options.get('fontset', 'cm')
- return [node]
-
-# This uses mathtext to render the expression
-def latex2png(latex, filename, fontset='cm'):
- latex = "$%s$" % latex
- orig_fontset = rcParams['mathtext.fontset']
- rcParams['mathtext.fontset'] = fontset
- if os.path.exists(filename):
- depth = mathtext_parser.get_depth(latex, dpi=100)
- else:
- try:
- depth = mathtext_parser.to_png(filename, latex, dpi=100)
- except:
- warnings.warn("Could not render math expression %s" % latex,
- Warning)
- depth = 0
- rcParams['mathtext.fontset'] = orig_fontset
- sys.stdout.write("#")
- sys.stdout.flush()
- return depth
-
-# LaTeX to HTML translation stuff:
-def latex2html(node, source):
- inline = isinstance(node.parent, nodes.TextElement)
- latex = node['latex']
- name = 'math-%s' % md5(latex).hexdigest()[-10:]
-
- destdir = os.path.join(setup.app.builder.outdir, '_images', 'mathmpl')
- if not os.path.exists(destdir):
- os.makedirs(destdir)
- dest = os.path.join(destdir, '%s.png' % name)
- path = os.path.join(setup.app.builder.imgpath, 'mathmpl')
-
- depth = latex2png(latex, dest, node['fontset'])
-
- if inline:
- cls = ''
- else:
- cls = 'class="center" '
- if inline and depth != 0:
- style = 'style="position: relative; bottom: -%dpx"' % (depth + 1)
- else:
- style = ''
-
- return '<img src="%s/%s.png" %s%s/>' % (path, name, cls, style)
-
-def setup(app):
- setup.app = app
-
- app.add_node(latex_math)
- app.add_role('math', math_role)
-
- # Add visit/depart methods to HTML-Translator:
- def visit_latex_math_html(self, node):
- source = self.document.attributes['source']
- self.body.append(latex2html(node, source))
- def depart_latex_math_html(self, node):
- pass
-
- # Add visit/depart methods to LaTeX-Translator:
- def visit_latex_math_latex(self, node):
- inline = isinstance(node.parent, nodes.TextElement)
- if inline:
- self.body.append('$%s$' % node['latex'])
- else:
- self.body.extend(['\\begin{equation}',
- node['latex'],
- '\\end{equation}'])
- def depart_latex_math_latex(self, node):
- pass
-
- app.add_node(latex_math, html=(visit_latex_math_html,
- depart_latex_math_html))
- app.add_node(latex_math, latex=(visit_latex_math_latex,
- depart_latex_math_latex))
- app.add_role('math', math_role)
- app.add_directive('math', math_directive,
- True, (0, 0, 0), **options_spec)
Deleted: branches/v0_98_5_maint/doc/sphinxext/only_directives.py
===================================================================
--- branches/v0_98_5_maint/doc/sphinxext/only_directives.py 2009-02-15 00:12:19 UTC (rev 6914)
+++ branches/v0_98_5_maint/doc/sphinxext/only_directives.py 2009-02-16 14:12:13 UTC (rev 6915)
@@ -1,63 +0,0 @@
-#
-# A pair of directives for inserting content that will only appear in
-# either html or latex.
-#
-
-from docutils.nodes import Body, Element
-from docutils.parsers.rst import directives
-
-class only_base(Body, Element):
- def dont_traverse(self, *args, **kwargs):
- return []
-
-class html_only(only_base):
- pass
-
-class latex_only(only_base):
- pass
-
-def run(content, node_class, state, content_offset):
- text = '\n'.join(content)
- node = node_class(text)
- state.nested_parse(content, content_offset, node)
- return [node]
-
-def html_only_directive(name, arguments, options, content, lineno,
- content_offset, block_text, state, state_machine):
- return run(content, html_only, state, content_offset)
-
-def latex_only_directive(name, arguments, options, content, lineno,
- content_offset, block_text, state, state_machine):
- return run(content, latex_only, state, content_offset)
-
-def builder_inited(app):
- if app.builder.name == 'html':
- latex_only.traverse = only_base.dont_traverse
- else:
- html_only.traverse = only_base.dont_traverse
-
-def setup(app):
- app.add_directive('htmlonly', html_only_directive, True, (0, 0, 0))
- app.add_directive('latexonly', latex_only_directive, True, (0, 0, 0))
- app.add_node(html_only)
- app.add_node(latex_only)
-
- # This will *really* never see the light of day As it turns out,
- # this results in "broken" image nodes since they never get
- # processed, so best not to do this.
- # app.connect('builder-inited', builder_inited)
-
- # Add visit/depart methods to HTML-Translator:
- def visit_perform(self, node):
- pass
- def depart_perform(self, node):
- pass
- def visit_ignore(self, node):
- node.children = []
- def depart_ignore(self, node):
- node.children = []
-
- app.add_node(html_only, html=(visit_perform, depart_perform))
- app.add_node(html_only, latex=(visit_ignore, depart_ignore))
- app.add_node(latex_only, latex=(visit_perform, depart_perform))
- app.add_node(latex_only, html=(visit_ignore, depart_ignore))
Added: branches/v0_98_5_maint/lib/matplotlib/sphinxext/__init__.py
===================================================================
--- branches/v0_98_5_maint/lib/matplotlib/sphinxext/__init__.py (rev 0)
+++ branches/v0_98_5_maint/lib/matplotlib/sphinxext/__init__.py 2009-02-16 14:12:13 UTC (rev 6915)
@@ -0,0 +1 @@
+
Copied: branches/v0_98_5_maint/lib/matplotlib/sphinxext/mathmpl.py (from rev 6843, branches/v0_98_5_maint/doc/sphinxext/mathmpl.py)
===================================================================
--- branches/v0_98_5_maint/lib/matplotlib/sphinxext/mathmpl.py (rev 0)
+++ branches/v0_98_5_maint/lib/matplotlib/sphinxext/mathmpl.py 2009-02-16 14:12:13 UTC (rev 6915)
@@ -0,0 +1,119 @@
+import os
+import sys
+try:
+ from hashlib import md5
+except ImportError:
+ from md5 import md5
+
+from docutils import nodes
+from docutils.parsers.rst import directives
+import warnings
+
+from matplotlib import rcParams
+from matplotlib.mathtext import MathTextParser
+rcParams['mathtext.fontset'] = 'cm'
+mathtext_parser = MathTextParser("Bitmap")
+
+# Define LaTeX math node:
+class latex_math(nodes.General, nodes.Element):
+ pass
+
+def fontset_choice(arg):
+ return directives.choice(arg, ['cm', 'stix', 'stixsans'])
+
+options_spec = {'fontset': fontset_choice}
+
+def math_role(role, rawtext, text, lineno, inliner,
+ options={}, content=[]):
+ i = rawtext.find('`')
+ latex = rawtext[i+1:-1]
+ node = latex_math(rawtext)
+ node['latex'] = latex
+ node['fontset'] = options.get('fontset', 'cm')
+ return [node], []
+math_role.options = options_spec
+
+def math_directive(name, arguments, options, content, lineno,
+ content_offset, block_text, state, state_machine):
+ latex = ''.join(content)
+ node = latex_math(block_text)
+ node['latex'] = latex
+ node['fontset'] = options.get('fontset', 'cm')
+ return [node]
+
+# This uses mathtext to render the expression
+def latex2png(latex, filename, fontset='cm'):
+ latex = "$%s$" % latex
+ orig_fontset = rcParams['mathtext.fontset']
+ rcParams['mathtext.fontset'] = fontset
+ if os.path.exists(filename):
+ depth = mathtext_parser.get_depth(latex, dpi=100)
+ else:
+ try:
+ depth = mathtext_parser.to_png(filename, latex, dpi=100)
+ except:
+ warnings.warn("Could not render math expression %s" % latex,
+ Warning)
+ depth = 0
+ rcParams['mathtext.fontset'] = orig_fontset
+ sys.stdout.write("#")
+ sys.stdout.flush()
+ return depth
+
+# LaTeX to HTML translation stuff:
+def latex2html(node, source):
+ inline = isinstance(node.parent, nodes.TextElement)
+ latex = node['latex']
+ name = 'math-%s' % md5(latex).hexdigest()[-10:]
+
+ destdir = os.path.join(setup.app.builder.outdir, '_images', 'mathmpl')
+ if not os.path.exists(destdir):
+ os.makedirs(destdir)
+ dest = os.path.join(destdir, '%s.png' % name)
+ path = os.path.join(setup.app.builder.imgpath, 'mathmpl')
+
+ depth = latex2png(latex, dest, node['fontset'])
+
+ if inline:
+ cls = ''
+ else:
+ cls = 'class="center" '
+ if inline and depth != 0:
+ style = 'style="position: relative; bottom: -%dpx"' % (depth + 1)
+ else:
+ style = ''
+
+ return '<img src="%s/%s.png" %s%s/>' % (path, name, cls, style)
+
+def setup(app):
+ setup.app = app
+
+ app.add_node(latex_math)
+ app.add_role('math', math_role)
+
+ # Add visit/depart methods to HTML-Translator:
+ def visit_latex_math_html(self, node):
+ source = self.document.attributes['source']
+ self.body.append(latex2html(node, source))
+ def depart_latex_math_html(self, node):
+ pass
+
+ # Add visit/depart methods to LaTeX-Translator:
+ def visit_latex_math_latex(self, node):
+ inline = isinstance(node.parent, nodes.TextElement)
+ if inline:
+ self.body.append('$%s$' % node['latex'])
+ else:
+ self.body.extend(['\\begin{equation}',
+ node['latex'],
+ '\\end{equation}'])
+ def depart_latex_math_latex(self, node):
+ pass
+
+ app.add_node(latex_math, html=(visit_latex_math_html,
+ depart_latex_math_html))
+ app.add_node(latex_math, latex=(visit_latex_math_latex,
+ depart_latex_math_latex))
+ app.add_role('math', math_role)
+ app.add_directive('math', math_directive,
+ True, (0, 0, 0), **options_spec)
Property changes on: branches/v0_98_5_maint/lib/matplotlib/sphinxext/mathmpl.py
___________________________________________________________________
Added: svn:mergeinfo
+ /branches/v0_91_maint/doc/sphinxext/mathmpl.py:5753-5771
Copied: branches/v0_98_5_maint/lib/matplotlib/sphinxext/only_directives.py (from rev 6843, branches/v0_98_5_maint/doc/sphinxext/only_directives.py)
===================================================================
--- branches/v0_98_5_maint/lib/matplotlib/sphinxext/only_directives.py (rev 0)
+++ branches/v0_98_5_maint/lib/matplotlib/sphinxext/only_directives.py 2009-02-16 14:12:13 UTC (rev 6915)
@@ -0,0 +1,63 @@
+#
+# A pair of directives for inserting content that will only appear in
+# either html or latex.
+#
+
+from docutils.nodes import Body, Element
+from docutils.parsers.rst import directives
+
+class only_base(Body, Element):
+ def dont_traverse(self, *args, **kwargs):
+ return []
+
+class html_only(only_base):
+ pass
+
+class latex_only(only_base):
+ pass
+
+def run(content, node_class, state, content_offset):
+ text = '\n'.join(content)
+ node = node_class(text)
+ state.nested_parse(content, content_offset, node)
+ return [node]
+
+def html_only_directive(name, arguments, options, content, lineno,
+ content_offset, block_text, state, state_machine):
+ return run(content, html_only, state, content_offset)
+
+def latex_only_directive(name, arguments, options, content, lineno,
+ content_offset, block_text, state, state_machine):
+ return run(content, latex_only, state, content_offset)
+
+def builder_inited(app):
+ if app.builder.name == 'html':
+ latex_only.traverse = only_base.dont_traverse
+ else:
+ html_only.traverse = only_base.dont_traverse
+
+def setup(app):
+ app.add_directive('htmlonly', html_only_directive, True, (0, 0, 0))
+ app.add_directive('latexonly', latex_only_directive, True, (0, 0, 0))
+ app.add_node(html_only)
+ app.add_node(latex_only)
+
+ # This will *really* never see the light of day As it turns out,
+ # this results in "broken" image nodes since they never get
+ # processed, so best not to do this.
+ # app.connect('builder-inited', builder_inited)
+
+ # Add visit/depart methods to HTML-Translator:
+ def visit_perform(self, node):
+ pass
+ def depart_perform(self, node):
+ pass
+ def visit_ignore(self, node):
+ node.children = []
+ def depart_ignore(self, node):
+ node.children = []
+
+ app.add_node(html_only, html=(visit_perform, depart_perform))
+ app.add_node(html_only, latex=(visit_ignore, depart_ignore))
+ app.add_node(latex_only, latex=(visit_perform, depart_perform))
+ app.add_node(latex_only, html=(visit_ignore, depart_ignore))
Property changes on: branches/v0_98_5_maint/lib/matplotlib/sphinxext/only_directives.py
___________________________________________________________________
Added: svn:mergeinfo
+ /branches/v0_91_maint/doc/sphinxext/only_directives.py:5753-5771
Modified: branches/v0_98_5_maint/setup.py
===================================================================
--- branches/v0_98_5_maint/setup.py 2009-02-15 00:12:19 UTC (rev 6914)
+++ branches/v0_98_5_maint/setup.py 2009-02-16 14:12:13 UTC (rev 6915)
@@ -58,7 +58,8 @@
'matplotlib.numerix.npyma',
'matplotlib.numerix.linear_algebra',
'matplotlib.numerix.random_array',
- 'matplotlib.numerix.fft'
+ 'matplotlib.numerix.fft',
+ 'matplotlib.sphinxext'
]
py_modules = ['pylab']
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <lee...@us...> - 2009-02-15 00:12:33
|
Revision: 6914
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6914&view=rev
Author: leejjoon
Date: 2009-02-15 00:12:19 +0000 (Sun, 15 Feb 2009)
Log Message:
-----------
Legend title support
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/examples/pylab_examples/legend_demo3.py
trunk/matplotlib/lib/matplotlib/legend.py
trunk/matplotlib/lib/matplotlib/offsetbox.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2009-02-13 18:21:37 UTC (rev 6913)
+++ trunk/matplotlib/CHANGELOG 2009-02-15 00:12:19 UTC (rev 6914)
@@ -1,3 +1,5 @@
+2009-02-14 Added the legend title support - JJL
+
2009-02-10 Fixed a bug in backend_pdf so it doesn't break when the setting
pdf.use14corefonts=True is used. Added test case in
unit/test_pdf_use14corefonts.py. - NGR
Modified: trunk/matplotlib/examples/pylab_examples/legend_demo3.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/legend_demo3.py 2009-02-13 18:21:37 UTC (rev 6913)
+++ trunk/matplotlib/examples/pylab_examples/legend_demo3.py 2009-02-15 00:12:19 UTC (rev 6914)
@@ -18,9 +18,9 @@
ax2 = plt.subplot(3,1,2)
myplot(ax2)
-ax2.legend(loc=1, ncol=2, shadow=True)
+ax2.legend(loc=1, ncol=2, shadow=True, title="Legend")
+ax2.get_legend().get_title().set_color("red")
-
ax3 = plt.subplot(3,1,3)
myplot(ax3)
ax3.legend(loc=1, ncol=4, mode="expand", shadow=True)
Modified: trunk/matplotlib/lib/matplotlib/legend.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/legend.py 2009-02-13 18:21:37 UTC (rev 6913)
+++ trunk/matplotlib/lib/matplotlib/legend.py 2009-02-15 00:12:19 UTC (rev 6914)
@@ -110,7 +110,8 @@
mode=None, # mode for horizontal distribution of columns. None, "expand"
fancybox=None, # True use a fancy box, false use a rounded box, none use rc
- shadow = None,
+ shadow = None,
+ title = None, # set a title for the legend
):
"""
- *parent* : the artist that contains the legend
@@ -135,6 +136,7 @@
handletextpad the pad between the legend handle and text
borderaxespad the pad between the axes and legend border
columnspacing the spacing between columns
+ title the legend title
================ ==================================================================
The dimensions of pad and spacing are given as a fraction of the
@@ -276,6 +278,8 @@
# init with null renderer
self._init_legend_box(handles, labels)
+ self.set_title(title)
+
self._last_fontsize_points = self._fontsize
@@ -316,6 +320,7 @@
renderer.open_group('legend')
+
# find_offset function will be provided to _legend_box and
# _legend_box will draw itself at the location of the return
# value of the find_offset.
@@ -562,11 +567,19 @@
sep = self.columnspacing*fontsize
- self._legend_box = HPacker(pad=self.borderpad*fontsize,
- sep=sep, align="baseline",
- mode=mode,
- children=columnbox)
+ self._legend_handle_box = HPacker(pad=0,
+ sep=sep, align="baseline",
+ mode=mode,
+ children=columnbox)
+ self._legend_title_box = TextArea("")
+
+ self._legend_box = VPacker(pad=self.borderpad*fontsize,
+ sep=self.labelspacing*fontsize,
+ align="center",
+ children=[self._legend_title_box,
+ self._legend_handle_box])
+
self._legend_box.set_figure(self.figure)
self.texts = text_list
@@ -640,6 +653,19 @@
'return a list of text.Text instance in the legend'
return silent_list('Text', self.texts)
+ def set_title(self, title):
+ 'set the legend title'
+ self._legend_title_box._text.set_text(title)
+
+ if title:
+ self._legend_title_box.set_visible(True)
+ else:
+ self._legend_title_box.set_visible(False)
+
+ def get_title(self):
+ 'return Text instance for the legend title'
+ return self._legend_title_box._text
+
def get_window_extent(self):
'return a extent of the the legend'
return self.legendPatch.get_window_extent()
Modified: trunk/matplotlib/lib/matplotlib/offsetbox.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/offsetbox.py 2009-02-13 18:21:37 UTC (rev 6913)
+++ trunk/matplotlib/lib/matplotlib/offsetbox.py 2009-02-15 00:12:19 UTC (rev 6914)
@@ -174,6 +174,12 @@
"""
self.height = height
+ def get_visible_children(self):
+ """
+ Return a list of visible artists it contains.
+ """
+ return [c for c in self._children if c.get_visible()]
+
def get_children(self):
"""
Return a list of artists it contains.
@@ -208,7 +214,7 @@
px, py = self.get_offset(width, height, xdescent, ydescent)
- for c, (ox, oy) in zip(self.get_children(), offsets):
+ for c, (ox, oy) in zip(self.get_visible_children(), offsets):
c.set_offset((px+ox, py+oy))
c.draw(renderer)
@@ -281,7 +287,12 @@
pad = self.pad * dpicor
sep = self.sep * dpicor
- whd_list = [c.get_extent(renderer) for c in self.get_children()]
+ if self.width is not None:
+ for c in self.get_visible_children():
+ if isinstance(c, PackerBase) and c.mode == "expand":
+ c.set_width(self.width)
+
+ whd_list = [c.get_extent(renderer) for c in self.get_visible_children()]
whd_list = [(w, h, xd, (h-yd)) for w, h, xd, yd in whd_list]
@@ -341,7 +352,7 @@
pad = self.pad * dpicor
sep = self.sep * dpicor
- whd_list = [c.get_extent(renderer) for c in self.get_children()]
+ whd_list = [c.get_extent(renderer) for c in self.get_visible_children()]
if self.height is None:
height_descent = max([h-yd for w,h,xd,yd in whd_list])
@@ -520,6 +531,14 @@
self._minimumdescent = minimumdescent
+ def set_text(self, s):
+ "set text"
+ self._text.set_text(s)
+
+ def get_text(self):
+ "get text"
+ return self._text.get_text()
+
def set_multilinebaseline(self, t):
"""
Set multilinebaseline .
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2009-02-13 18:21:41
|
Revision: 6913
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6913&view=rev
Author: ryanmay
Date: 2009-02-13 18:21:37 +0000 (Fri, 13 Feb 2009)
Log Message:
-----------
Merged revisions 6911-6912 via svnmerge from
https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_98_5_maint
........
r6911 | ryanmay | 2009-02-13 11:54:52 -0600 (Fri, 13 Feb 2009) | 1 line
Backport fix for infinite recursion when finding the appropriate converter for a string. A lot of users seem to be hitting this.
........
r6912 | ryanmay | 2009-02-13 12:17:31 -0600 (Fri, 13 Feb 2009) | 1 line
Typo in docstring
........
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/axes.py
Property Changed:
----------------
trunk/matplotlib/
trunk/matplotlib/doc/pyplots/README
trunk/matplotlib/doc/sphinxext/gen_gallery.py
trunk/matplotlib/doc/sphinxext/gen_rst.py
Property changes on: trunk/matplotlib
___________________________________________________________________
Modified: svnmerge-integrated
- /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6909
+ /branches/v0_91_maint:1-6428 /branches/v0_98_5_maint:1-6912
Modified: svn:mergeinfo
- /branches/v0_91_maint:5753-5771
/branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909
+ /branches/v0_91_maint:5753-5771
/branches/v0_98_5_maint:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6809,6811,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6906-6909,6911-6912
Property changes on: trunk/matplotlib/doc/pyplots/README
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891
+ /branches/v0_98_5_maint/doc/pyplots/README:6581,6585,6587,6589-6609,6614,6616,6625,6652,6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912
Property changes on: trunk/matplotlib/doc/sphinxext/gen_gallery.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891
+ /branches/v0_91_maint/doc/_templates/gen_gallery.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_gallery.py:6660-6662,6672-6673,6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912
Property changes on: trunk/matplotlib/doc/sphinxext/gen_rst.py
___________________________________________________________________
Modified: svn:mergeinfo
- /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891
+ /branches/v0_91_maint/doc/examples/gen_rst.py:5753-5771
/branches/v0_98_5_maint/doc/sphinxext/gen_rst.py:6714-6715,6717-6732,6752-6754,6761-6773,6781,6792,6800,6802,6805,6822,6827,6850,6854,6856,6859,6861-6873,6883-6884,6886,6890-6891,6911-6912
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2009-02-13 18:17:31 UTC (rev 6912)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2009-02-13 18:21:37 UTC (rev 6913)
@@ -5933,7 +5933,7 @@
corner of the axes. If *None*, default to rc ``image.origin``.
*extent*: [ None | scalars (left, right, bottom, top) ]
- Eata values of the axes. The default assigns zero-based row,
+ Data limits for the axes. The default assigns zero-based row,
column indices to the *x*, *y* centers of the pixels.
*shape*: [ None | scalars (columns, rows) ]
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|