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: <js...@us...> - 2008-06-13 15:53:16
|
Revision: 5511
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5511&view=rev
Author: jswhit
Date: 2008-06-13 08:53:02 -0700 (Fri, 13 Jun 2008)
Log Message:
-----------
more work on docstrings.
Modified Paths:
--------------
trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py
Modified: trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py
===================================================================
--- trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py 2008-06-13 15:38:46 UTC (rev 5510)
+++ trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py 2008-06-13 15:53:02 UTC (rev 5511)
@@ -192,7 +192,7 @@
area_thresh coastline or lake with an area smaller than
area_thresh in km^2 will not be plotted.
Default 10000,1000,100,10,1 for resolution
- ``c``,``l``,``i``,``h``,``f``.
+ ``c``, ``l``, ``i``, ``h``, ``f``.
rsphere radius of the sphere used to define map projection
(default 6370997 meters, close to the arithmetic mean
radius of the earth). If given as a sequence, the
@@ -1613,46 +1613,49 @@
dashes=[1,1],labels=[0,0,0,0],labelstyle=None, \
fmt='%g',xoffset=None,yoffset=None,ax=None,**kwargs):
"""
- draw parallels (latitude lines).
+ Draw and label parallels (latitude lines).
- circles - list containing latitude values to draw (in degrees).
+ ============== ====================================================
+ Keyword Description
+ ============== ====================================================
+ circles sequence containing latitude values to draw (in
+ degrees).
+ color color to draw parallels (default black).
+ linewidth line width for parallels (default 1.)
+ zorder sets the zorder for parallels (if not specified,
+ uses default zorder for matplotlib.lines.Line2D
+ objects).
+ dashes dash pattern for parallels (default [1,1], i.e.
+ 1 pixel on, 1 pixel off).
+ labels list of 4 values (default [0,0,0,0]) that control
+ whether parallels are labelled where they intersect
+ the left, right, top or bottom of the plot. For
+ example labels=[1,0,0,1] will cause parallels
+ to be labelled where they intersect the left and
+ and bottom of the plot, but not the right and top.
+ labelstyle if set to "+/-", north and south latitudes are
+ labelled with "+" and "-", otherwise they are
+ labelled with "N" and "S".
+ fmt a format string to format the parallel labels
+ (default '%g') **or** a function that takes a
+ latitude value in degrees as it's only argument
+ and returns a formatted string.
+ xoffset label offset from edge of map in x-direction
+ (default is 0.01 times width of map in map
+ projection coordinates).
+ yoffset label offset from edge of map in y-direction
+ (default is 0.01 times height of map in map
+ projection coordinates).
+ ax axes instance (overrides default axes instance)
+ \**kwargs additional keyword arguments controlling text
+ for labels that are passed on to
+ the text method of the axes instance (see
+ matplotlib.pyplot.text documentation).
+ ============== ====================================================
- color - color to draw parallels (default black).
-
- linewidth - line width for parallels (default 1.)
-
- zorder - sets the zorder for parallels (if not specified,
- uses default zorder for Line2D class).
-
- dashes - dash pattern for parallels (default [1,1], i.e. 1 pixel on,
- 1 pixel off).
-
- labels - list of 4 values (default [0,0,0,0]) that control whether
- parallels are labelled where they intersect the left, right, top or
- bottom of the plot. For example labels=[1,0,0,1] will cause parallels
- to be labelled where they intersect the left and bottom of the plot,
- but not the right and top.
-
- labelstyle - if set to "+/-", north and south latitudes are labelled
- with "+" and "-", otherwise they are labelled with "N" and "S".
-
- fmt can be is a format string to format the parallel labels
- (default '%g') or a function that takes a latitude value
- in degrees as it's only argument and returns a formatted string.
-
- xoffset - label offset from edge of map in x-direction
- (default is 0.01 times width of map in map projection coordinates).
-
- yoffset - label offset from edge of map in y-direction
- (default is 0.01 times height of map in map projection coordinates).
-
- ax - axes instance (overrides default axes instance)
-
- additional keyword arguments control text properties for labels (see
- matplotlib.pyplot.text documentation)
-
- returns a dictionary whose keys are the parallels, and
- whose values are tuples containing lists of the Line2D and Text instances
+ returns a dictionary whose keys are the parallel values, and
+ whose values are tuples containing lists of the
+ matplotlib.lines.Line2D and matplotlib.text.Text instances
associated with each parallel.
"""
# get current axes instance (if none specified).
@@ -1865,46 +1868,49 @@
dashes=[1,1],labels=[0,0,0,0],labelstyle=None,\
fmt='%g',xoffset=None,yoffset=None,ax=None,**kwargs):
"""
- draw meridians (longitude lines).
+ Draw and label meridians (longitude lines).
- meridians - list containing longitude values to draw (in degrees).
+ ============== ====================================================
+ Keyword Description
+ ============== ====================================================
+ meridians sequence containing longitude values to draw (in
+ degrees).
+ color color to draw meridians (default black).
+ linewidth line width for meridians (default 1.)
+ zorder sets the zorder for meridians (if not specified,
+ uses default zorder for matplotlib.lines.Line2D
+ objects).
+ dashes dash pattern for meridians (default [1,1], i.e.
+ 1 pixel on, 1 pixel off).
+ labels list of 4 values (default [0,0,0,0]) that control
+ whether meridians are labelled where they intersect
+ the left, right, top or bottom of the plot. For
+ example labels=[1,0,0,1] will cause meridians
+ to be labelled where they intersect the left and
+ and bottom of the plot, but not the right and top.
+ labelstyle if set to "+/-", east and west longitudes are
+ labelled with "+" and "-", otherwise they are
+ labelled with "E" and "W".
+ fmt a format string to format the meridian labels
+ (default '%g') **or** a function that takes a
+ longitude value in degrees as it's only argument
+ and returns a formatted string.
+ xoffset label offset from edge of map in x-direction
+ (default is 0.01 times width of map in map
+ projection coordinates).
+ yoffset label offset from edge of map in y-direction
+ (default is 0.01 times height of map in map
+ projection coordinates).
+ ax axes instance (overrides default axes instance)
+ \**kwargs additional keyword arguments controlling text
+ for labels that are passed on to
+ the text method of the axes instance (see
+ matplotlib.pyplot.text documentation).
+ ============== ====================================================
- color - color to draw meridians (default black).
-
- linewidth - line width for meridians (default 1.)
-
- zorder - sets the zorder for meridians (if not specified,
- uses default zorder for Line2D class).
-
- dashes - dash pattern for meridians (default [1,1], i.e. 1 pixel on,
- 1 pixel off).
-
- labels - list of 4 values (default [0,0,0,0]) that control whether
- meridians are labelled where they intersect the left, right, top or
- bottom of the plot. For example labels=[1,0,0,1] will cause meridians
- to be labelled where they intersect the left and bottom of the plot,
- but not the right and top.
-
- labelstyle - if set to "+/-", east and west longitudes are labelled
- with "+" and "-", otherwise they are labelled with "E" and "W".
-
- fmt can be is a format string to format the meridian labels
- (default '%g') or a function that takes a longitude value
- in degrees as it's only argument and returns a formatted string.
-
- xoffset - label offset from edge of map in x-direction
- (default is 0.01 times width of map in map projection coordinates).
-
- yoffset - label offset from edge of map in y-direction
- (default is 0.01 times height of map in map projection coordinates).
-
- ax - axes instance (overrides default axes instance)
-
- additional keyword arguments control text properties for labels (see
- matplotlib.pyplot.text documentation)
-
- returns a dictionary whose keys are the meridians, and
- whose values are tuples containing lists of the Line2D and Text instances
+ returns a dictionary whose keys are the meridian values, and
+ whose values are tuples containing lists of the
+ matplotlib.lines.Line2D and matplotlib.text.Text instances
associated with each meridian.
"""
# get current axes instance (if none specified).
@@ -2102,8 +2108,8 @@
def gcpoints(self,lon1,lat1,lon2,lat2,npoints):
"""
- compute npoints points along a great circle with endpoints
- (lon1,lat1) and (lon2,lat2).
+ compute ``points`` points along a great circle with endpoints
+ ``(lon1,lat1)`` and ``(lon2,lat2)``.
Returns arrays x,y with map projection coordinates.
"""
@@ -2118,21 +2124,25 @@
def drawgreatcircle(self,lon1,lat1,lon2,lat2,del_s=100.,**kwargs):
"""
- draw a great circle on the map.
+ Draw a great circle on the map.
- lon1,lat1 - longitude,latitude of one endpoint of the great circle.
+ ============== =======================================================
+ Keyword Description
+ ============== =======================================================
+ lon1,lat1 longitude,latitude of one endpoint of the great circle.
+ lon2,lat2 longitude,latitude of the other endpoint of the great
+ circle.
+ del_s points on great circle computed every del_s kilometers
+ (default 100).
+ \**kwargs other keyword arguments are passed on to :meth:`plot`
+ method of Basemap instance.
+ ============== =======================================================
- lon2,lat2 - longitude,latitude of the other endpoint of the great circle.
+ .. note::
+ Cannot handle situations in which the great circle intersects
+ the edge of the map projection domain, and then re-enters the domain.
- del_s - points on great circle computed every delta kilometers (default 100).
-
- Other keyword arguments (\**kwargs) control plotting of great circle line,
- see matplotlib.pyplot.plot documentation for details.
-
- Cannot handle situations in which the great circle intersects
- the edge of the map projection domain, and then re-enters the domain.
-
- Returns a Line2D object.
+ Returns a matplotlib.lines.Line2D object.
"""
# use great circle formula for a perfect sphere.
gc = pyproj.Geod(a=self.rmajor,b=self.rminor)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ds...@us...> - 2008-06-13 15:40:26
|
Revision: 5510
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5510&view=rev
Author: dsdale
Date: 2008-06-13 08:38:46 -0700 (Fri, 13 Jun 2008)
Log Message:
-----------
updated documentation guide to include Mike's plot directive
Modified Paths:
--------------
trunk/matplotlib/doc/devel/documenting_mpl.rst
Modified: trunk/matplotlib/doc/devel/documenting_mpl.rst
===================================================================
--- trunk/matplotlib/doc/devel/documenting_mpl.rst 2008-06-13 15:13:39 UTC (rev 5509)
+++ trunk/matplotlib/doc/devel/documenting_mpl.rst 2008-06-13 15:38:46 UTC (rev 5510)
@@ -56,11 +56,16 @@
The Sphinx website contains plenty of documentation_ concerning ReST markup and
working with Sphinx in general. Here are a few additional things to keep in mind:
+* Please familiarize yourself with the Sphinx directives for `inline
+ markup`_. Matplotlib's documentation makes heavy use of cross-referencing and
+ other semantic markup. For example, when referring to external files, use the
+ ``:file:`` directive.
+
* Sphinx does not support tables with column- or row-spanning cells for
latex output. Such tables can not be used when documenting matplotlib.
-* Mathematical expressions can be rendered as png images in html, and in
- the usual way by latex. For example:
+* Mathematical expressions can be rendered as png images in html, and in the
+ usual way by latex. For example:
``math:`sin(x_n^2)``` yields: :math:`sin(x_n^2)`, and::
@@ -88,31 +93,50 @@
In [69]: lines = plot([1,2,3])
.. _documentation: http://sphinx.pocoo.org/contents.html
+.. _`inline markup`: http://sphinx.pocoo.org/markup/inline.html
Figures
=======
+Dynamically generated figures
+-----------------------------
+
Each guide will have its own `figures/` directory for scripts to generate images
-to be included in the dcoumentation. It is not necessary to explicitly save
+to be included in the documentation. It is not necessary to explicitly save
the figure in the script, a figure will be saved with the same name as the
-filename when the documentation is generated. For example, use::
+filename when the documentation is generated. Matplotlib includes a Sphinx
+extension for generating the images from the python script and including either
+a png copy for html or a pdf for latex::
- .. literalinclude:: figures/pyplot_simple.py
+ .. plot:: figures/pyplot_simple
+ :scale: 75
+ :include-source:
- .. image:: figures/pyplot_simple.png
- :scale: 75
+The ``:scale:`` directive rescales the image to some percentage of the original
+size. ``:include-source:`` will present the contents of the file, marked up as
+source code.
+Static figures
+--------------
Any figures that rely on optional system configurations should be generated
with a script residing in doc/static_figs. The resulting figures will be saved
to doc/_static, and will be named based on the name of the script, so we can
-avoid unintentionally overwriting any existing figures. Please add a line to
+avoid unintentionally overwriting any existing figures. Please run the
+:file:`doc/static_figs/make.py` file when adding additional figures, and commit
+the script **and** the images to svn. Please also add a line to
the README in doc/static-figs for any additional requirements necessary to
-generate a new figure.
+generate a new figure. These figures are not to be generated during the
+documentation build. Please use something like the following to include the
+source code and the image::
+ .. literalinclude:: ../mpl_examples/pylab_examples/tex_unicode_demo.py
+ .. image:: ../_static/tex_unicode_demo.png
+
+
.. _referring-to-mpl-docs:
Referring to mpl documents
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-06-13 15:14:32
|
Revision: 5509
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5509&view=rev
Author: jswhit
Date: 2008-06-13 08:13:39 -0700 (Fri, 13 Jun 2008)
Log Message:
-----------
updating docstrings
Modified Paths:
--------------
trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py
Modified: trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py
===================================================================
--- trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py 2008-06-13 15:04:49 UTC (rev 5508)
+++ trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py 2008-06-13 15:13:39 UTC (rev 5509)
@@ -112,6 +112,11 @@
and creates the coastline data structures in native map projection
coordinates.
+ Calling a Basemap class instance with the arguments lon, lat will
+ convert lon/lat (in degrees) to x/y native map projection coordinates
+ (in meters). The inverse transformation is done if the optional keyword
+ ``inverse`` is set to True.
+
The desired projection is set with the projection keyword. Default is ``cyl``.
Supported values for the projection keyword are:
@@ -1296,18 +1301,19 @@
"""
Draw coastlines.
- linewidth - coastline width (default 1.)
+ ============== ====================================================
+ Keyword Description
+ ============== ====================================================
+ linewidth coastline width (default 1.)
+ color coastline color (default black)
+ antialiased antialiasing switch for coastlines (default True).
+ ax axes instance (overrides default axes instance)
+ zorder sets the zorder for the coastlines (if not specified,
+ uses default zorder for
+ matplotlib.patches.LineCollections).
+ ============== ====================================================
- color - coastline color (default black)
-
- antialiased - antialiasing switch for coastlines (default True).
-
- ax - axes instance (overrides default axes instance)
-
- zorder - sets the zorder for the coastlines (if not specified,
- uses default zorder for LineCollections).
-
- returns a LineCollection.
+ returns a matplotlib.patches.LineCollection object.
"""
if self.resolution is None:
raise AttributeError, 'there are no boundary datasets associated with this Basemap instance'
@@ -1335,18 +1341,20 @@
"""
Draw country boundaries.
- linewidth - country boundary line width (default 0.5)
+ ============== ====================================================
+ Keyword Description
+ ============== ====================================================
+ linewidth country boundary line width (default 0.5)
+ color country boundary line color (default black)
+ antialiased antialiasing switch for country boundaries (default
+ True).
+ ax axes instance (overrides default axes instance)
+ zorder sets the zorder for the country boundaries (if not
+ specified uses default zorder for
+ matplotlib.patches.LineCollections).
+ ============== ====================================================
- color - country boundary line color (default black)
-
- antialiased - antialiasing switch for country boundaries (default True).
-
- ax - axes instance (overrides default axes instance)
-
- zorder - sets the zorder for the country boundaries (if not specified,
- uses default zorder for LineCollections).
-
- returns a LineCollection.
+ returns a matplotlib.patches.LineCollection object.
"""
if self.resolution is None:
raise AttributeError, 'there are no boundary datasets associated with this Basemap instance'
@@ -1378,18 +1386,20 @@
"""
Draw state boundaries in Americas.
- linewidth - state boundary line width (default 0.5)
+ ============== ====================================================
+ Keyword Description
+ ============== ====================================================
+ linewidth state boundary line width (default 0.5)
+ color state boundary line color (default black)
+ antialiased antialiasing switch for state boundaries
+ (default True).
+ ax axes instance (overrides default axes instance)
+ zorder sets the zorder for the state boundaries (if not
+ specified, uses default zorder for
+ matplotlib.patches.LineCollections).
+ ============== ====================================================
- color - state boundary line color (default black)
-
- antialiased - antialiasing switch for state boundaries (default True).
-
- ax - axes instance (overrides default axes instance)
-
- zorder - sets the zorder for the state boundaries (if not specified,
- uses default zorder for LineCollections).
-
- returns a LineCollection.
+ returns a matplotlib.patches.LineCollection object.
"""
if self.resolution is None:
raise AttributeError, 'there are no boundary datasets associated with this Basemap instance'
@@ -1421,18 +1431,20 @@
"""
Draw major rivers.
- linewidth - river boundary line width (default 0.5)
+ ============== ====================================================
+ Keyword Description
+ ============== ====================================================
+ linewidth river boundary line width (default 0.5)
+ color river boundary line color (default black)
+ antialiased antialiasing switch for river boundaries (default
+ True).
+ ax axes instance (overrides default axes instance)
+ zorder sets the zorder for the rivers (if not
+ specified uses default zorder for
+ matplotlib.patches.LineCollections).
+ ============== ====================================================
- color - river boundary line color (default black)
-
- antialiased - antialiasing switch for river boundaries (default True).
-
- ax - axes instance (overrides default axes instance)
-
- zorder - sets the zorder for the rivers (if not specified,
- uses default zorder for LineCollections).
-
- returns a LineCollection
+ returns a matplotlib.patches.LineCollection object.
"""
if self.resolution is None:
raise AttributeError, 'there are no boundary datasets associated with this Basemap instance'
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-13 15:05:43
|
Revision: 5508
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5508&view=rev
Author: jdh2358
Date: 2008-06-13 08:04:49 -0700 (Fri, 13 Jun 2008)
Log Message:
-----------
fixed list of backends in the rc template
Modified Paths:
--------------
trunk/matplotlib/matplotlibrc.template
trunk/matplotlib/src/ft2font.cpp
Modified: trunk/matplotlib/matplotlibrc.template
===================================================================
--- trunk/matplotlib/matplotlibrc.template 2008-06-13 14:57:50 UTC (rev 5507)
+++ trunk/matplotlib/matplotlibrc.template 2008-06-13 15:04:49 UTC (rev 5508)
@@ -19,8 +19,8 @@
# such as 0.75 - a legal html color name, eg red, blue, darkslategray
#### CONFIGURATION BEGINS HERE
-# the default backend; one of GTK GTKAgg GTKCairo FltkAgg QtAgg TkAgg
-# WX WXAgg Agg Cairo GD GDK Paint PS PDF SVG Template
+# the default backend; one of GTK GTKAgg GTKCairo CocoaAgg FltkAgg
+# QtAgg Qt4Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG Template
backend : %(backend)s
numerix : %(numerix)s # numpy, Numeric or numarray
#maskedarray : False # True to use external maskedarray module
Modified: trunk/matplotlib/src/ft2font.cpp
===================================================================
--- trunk/matplotlib/src/ft2font.cpp 2008-06-13 14:57:50 UTC (rev 5507)
+++ trunk/matplotlib/src/ft2font.cpp 2008-06-13 15:04:49 UTC (rev 5508)
@@ -265,15 +265,15 @@
_VERBOSE("FT2Image::as_array");
args.verify_length(0);
- int dimensions[2];
+ npy_intp dimensions[2];
dimensions[0] = get_height(); //numrows
dimensions[1] = get_width(); //numcols
- //PyArrayObject *A = (PyArrayObject *) PyArray_SimpleNewFromData(2, dimensions, PyArray_UBYTE, _buffer);
+ PyArrayObject *A = (PyArrayObject *) PyArray_SimpleNewFromData(2, dimensions, PyArray_UBYTE, _buffer);
+ /*
-
PyArrayObject *A = (PyArrayObject *) PyArray_FromDims(2, dimensions, PyArray_UBYTE);
@@ -284,8 +284,8 @@
while (src != src_end) {
*dst++ = *src++;
}
+ */
-
return Py::asObject((PyObject*)A);
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-13 14:58:22
|
Revision: 5507
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5507&view=rev
Author: mdboom
Date: 2008-06-13 07:57:50 -0700 (Fri, 13 Jun 2008)
Log Message:
-----------
Fix typo in docstring.
Modified Paths:
--------------
trunk/matplotlib/doc/sphinxext/ipython_console_highlighting.py
Modified: trunk/matplotlib/doc/sphinxext/ipython_console_highlighting.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/ipython_console_highlighting.py 2008-06-13 14:57:01 UTC (rev 5506)
+++ trunk/matplotlib/doc/sphinxext/ipython_console_highlighting.py 2008-06-13 14:57:50 UTC (rev 5507)
@@ -13,7 +13,7 @@
Tracebacks are not currently supported.
- .. sourcecode:: pycon
+ .. sourcecode:: ipython
In [1]: a = 'foo'
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-13 14:57:38
|
Revision: 5506
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5506&view=rev
Author: mdboom
Date: 2008-06-13 07:57:01 -0700 (Fri, 13 Jun 2008)
Log Message:
-----------
Fix formatting typo
Modified Paths:
--------------
trunk/matplotlib/doc/faq/installing_faq.rst
Modified: trunk/matplotlib/doc/faq/installing_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-13 14:40:39 UTC (rev 5505)
+++ trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-13 14:57:01 UTC (rev 5506)
@@ -131,7 +131,7 @@
TkAgg Agg rendering to a Tkinter canvas (`tkinter <http://wiki.python.org/moin/TkInter>`_)
QtAgg Agg rendering to a Qt canvas (`pyqt <http://www.riverbankcomputing.co.uk/software/pyqt/intro>`_)
Qt4Agg Agg rendering to a Qt4 canvas (`pyqt <http://www.riverbankcomputing.co.uk/software/pyqt/intro>`_)
-FLTKAgg Agg rendering to a FLTK canvas (`pyfltk <http://pyfltk.sourceforge.net>`)_
+FLTKAgg Agg rendering to a FLTK canvas (`pyfltk <http://pyfltk.sourceforge.net>`_)
============ ===================================================================================================
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-13 14:40:46
|
Revision: 5505
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5505&view=rev
Author: mdboom
Date: 2008-06-13 07:40:39 -0700 (Fri, 13 Jun 2008)
Log Message:
-----------
Add "include-source" option.
Modified Paths:
--------------
trunk/matplotlib/doc/sphinxext/plot_directive.py
trunk/matplotlib/doc/users/annotations.rst
trunk/matplotlib/doc/users/artists.rst
trunk/matplotlib/doc/users/mathtext.rst
trunk/matplotlib/doc/users/pyplot_tutorial.rst
trunk/matplotlib/doc/users/text_intro.rst
trunk/matplotlib/doc/users/text_props.rst
Modified: trunk/matplotlib/doc/sphinxext/plot_directive.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/plot_directive.py 2008-06-13 14:24:40 UTC (rev 5504)
+++ trunk/matplotlib/doc/sphinxext/plot_directive.py 2008-06-13 14:40:39 UTC (rev 5505)
@@ -3,10 +3,14 @@
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.
- Underneath that, a [source] link will go to a plain text .py of
- the source.
- 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.
"""
from docutils.parsers.rst import directives
@@ -25,9 +29,23 @@
'width': directives.length_or_percentage_or_unitless,
'scale': directives.nonnegative_int,
'align': align,
- 'class': directives.class_option}
+ 'class': directives.class_option,
+ 'include-source': directives.flag }
-template = """
+template_no_source = """
+.. htmlonly::
+
+ .. image:: %(reference)s.png
+ :target: %(reference)s.hires.png
+%(options)s
+
+.. latexonly::
+ .. image:: %(reference)s.pdf
+%(options)s
+
+"""
+
+template_source = """
.. literalinclude:: %(reference)s.py
.. htmlonly::
@@ -36,7 +54,7 @@
:target: %(reference)s.hires.png
%(options)s
- `[original %(basename)s.py] <%(reference)s.py>`_
+ `[%(basename)s.py] <%(reference)s.py>`_
.. latexonly::
.. image:: %(reference)s.pdf
@@ -46,8 +64,16 @@
def run(arguments, options, state_machine, lineno):
reference = directives.uri(arguments[0])
- if reference.endswith('.py'):
- reference = reference[:-3]
+ print reference
+ for ext in ('.py', '.png', '.pdf'):
+ if reference.endswith(ext):
+ reference = reference[:-len(ext)]
+ break
+ if options.has_key('include-source'):
+ template = template_source
+ del options['include-source']
+ else:
+ template = template_no_source
options = [' :%s: %s' % (key, val) for key, val in
options.items()]
options = "\n".join(options)
Modified: trunk/matplotlib/doc/users/annotations.rst
===================================================================
--- trunk/matplotlib/doc/users/annotations.rst 2008-06-13 14:24:40 UTC (rev 5504)
+++ trunk/matplotlib/doc/users/annotations.rst 2008-06-13 14:40:39 UTC (rev 5505)
@@ -13,6 +13,7 @@
arguments are ``(x,y)`` tuples.
.. plot:: figures/annotation_basic.py
+ :include-source:
:scale: 75
In this example, both the ``xy`` (arrow tip) and ``xytext`` locations
@@ -73,6 +74,7 @@
.. plot:: figures/annotation_polar.py
:scale: 75
+ :include-source:
See the `annotations demo
<http://matplotlib.sf.net/examples/pylab_examples/annotation_demo.py>`_ for more
Modified: trunk/matplotlib/doc/users/artists.rst
===================================================================
--- trunk/matplotlib/doc/users/artists.rst 2008-06-13 14:24:40 UTC (rev 5504)
+++ trunk/matplotlib/doc/users/artists.rst 2008-06-13 14:40:39 UTC (rev 5505)
@@ -135,7 +135,7 @@
Try creating the figure below.
-.. image:: figures/fig_axes_labels_simple.png
+.. plot:: figures/fig_axes_labels_simple
:scale: 75
.. _customizing-artists:
@@ -326,7 +326,7 @@
In [195]: fig.canvas.draw()
-.. image:: figures/fig_x.png
+.. plot:: figures/fig_x
:scale: 75
@@ -606,6 +606,7 @@
.. plot:: figures/fig_axes_customize_simple.py
:scale: 75
+ :include-source:
.. _tick-container:
@@ -643,3 +644,4 @@
.. plot:: figures/dollar_ticks.py
:scale: 75
+ :include-source:
Modified: trunk/matplotlib/doc/users/mathtext.rst
===================================================================
--- trunk/matplotlib/doc/users/mathtext.rst 2008-06-13 14:24:40 UTC (rev 5504)
+++ trunk/matplotlib/doc/users/mathtext.rst 2008-06-13 14:40:39 UTC (rev 5505)
@@ -273,6 +273,7 @@
.. plot:: figures/pyplot_mathtext.py
:scale: 75
+ :include-source:
Modified: trunk/matplotlib/doc/users/pyplot_tutorial.rst
===================================================================
--- trunk/matplotlib/doc/users/pyplot_tutorial.rst 2008-06-13 14:24:40 UTC (rev 5504)
+++ trunk/matplotlib/doc/users/pyplot_tutorial.rst 2008-06-13 14:40:39 UTC (rev 5505)
@@ -14,6 +14,7 @@
.. plot:: figures/pyplot_simple
:scale: 75
+ :include-source:
You may be wondering why the x-axis ranges from 0-3 and the y-axis
from 1-4. If you provide a single list or array to the
@@ -38,6 +39,7 @@
.. plot:: figures/pyplot_formatstr.py
:scale: 75
+ :include-source:
See the :func:`~matplotlib.pyplot.plot` documentation for a complete
list of line styles and format strings. The
@@ -54,6 +56,7 @@
.. plot:: figures/pyplot_three.py
:scale: 75
+ :include-source:
.. _controlling-line-properties:
@@ -159,6 +162,7 @@
.. plot:: figures/pyplot_two_subplots.py
:scale: 75
+ :include-source:
The :func:`~matplotlib.pyplot.figure` command here is optional because
``figure(1)`` will be created by default, just as a ``subplot(111)``
@@ -218,8 +222,8 @@
.. plot:: figures/pyplot_text.py
:scale: 75
+ :include-source:
-
All of the :func:`~matplotlib.pyplot.text` commands return an
:class:`matplotlib.text.Text` instance. Just as with with lines
above, you can customize the properties by passing keyword arguments
@@ -264,6 +268,7 @@
.. plot:: figures/pyplot_annotate.py
:scale: 75
+ :include-source:
In this basic example, both the ``xy`` (arrow tip) and ``xytext``
locations (text location) are in data coordinates. There are a
Modified: trunk/matplotlib/doc/users/text_intro.rst
===================================================================
--- trunk/matplotlib/doc/users/text_intro.rst 2008-06-13 14:24:40 UTC (rev 5504)
+++ trunk/matplotlib/doc/users/text_intro.rst 2008-06-13 14:40:39 UTC (rev 5505)
@@ -57,4 +57,4 @@
.. plot:: figures/text_commands.py
:scale: 75
-
+ :include-source:
Modified: trunk/matplotlib/doc/users/text_props.rst
===================================================================
--- trunk/matplotlib/doc/users/text_props.rst 2008-06-13 14:24:40 UTC (rev 5504)
+++ trunk/matplotlib/doc/users/text_props.rst 2008-06-13 14:40:39 UTC (rev 5505)
@@ -59,3 +59,4 @@
.. plot:: figures/text_layout.py
:scale: 75
+ :include-source:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-13 14:24:42
|
Revision: 5504
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5504&view=rev
Author: mdboom
Date: 2008-06-13 07:24:40 -0700 (Fri, 13 Jun 2008)
Log Message:
-----------
Fix warnings about duplicate explicit targets.
Modified Paths:
--------------
trunk/matplotlib/doc/sphinxext/plot_directive.py
Modified: trunk/matplotlib/doc/sphinxext/plot_directive.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/plot_directive.py 2008-06-13 14:10:02 UTC (rev 5503)
+++ trunk/matplotlib/doc/sphinxext/plot_directive.py 2008-06-13 14:24:40 UTC (rev 5504)
@@ -10,6 +10,7 @@
"""
from docutils.parsers.rst import directives
+import os.path
try:
# docutils 0.4
@@ -35,7 +36,7 @@
:target: %(reference)s.hires.png
%(options)s
- `[source] <%(reference)s.py>`_
+ `[original %(basename)s.py] <%(reference)s.py>`_
.. latexonly::
.. image:: %(reference)s.pdf
@@ -50,6 +51,7 @@
options = [' :%s: %s' % (key, val) for key, val in
options.items()]
options = "\n".join(options)
+ basename = os.path.basename(reference)
lines = template % locals()
lines = lines.split('\n')
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-13 14:10:28
|
Revision: 5503
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5503&view=rev
Author: mdboom
Date: 2008-06-13 07:10:02 -0700 (Fri, 13 Jun 2008)
Log Message:
-----------
Add plot directive to include inline plots and their source.
Modified Paths:
--------------
trunk/matplotlib/doc/conf.py
trunk/matplotlib/doc/make.py
trunk/matplotlib/doc/users/annotations.rst
trunk/matplotlib/doc/users/artists.rst
trunk/matplotlib/doc/users/figures/make.py
trunk/matplotlib/doc/users/mathtext.rst
trunk/matplotlib/doc/users/pyplot_tutorial.rst
trunk/matplotlib/doc/users/text_intro.rst
trunk/matplotlib/doc/users/text_props.rst
Added Paths:
-----------
trunk/matplotlib/doc/sphinxext/only_directives.py
trunk/matplotlib/doc/sphinxext/plot_directive.py
Modified: trunk/matplotlib/doc/conf.py
===================================================================
--- trunk/matplotlib/doc/conf.py 2008-06-13 12:46:20 UTC (rev 5502)
+++ trunk/matplotlib/doc/conf.py 2008-06-13 14:10:02 UTC (rev 5503)
@@ -27,7 +27,8 @@
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = ['mathpng', 'math_symbol_table', 'sphinx.ext.autodoc']
+extensions = ['mathpng', 'math_symbol_table', 'sphinx.ext.autodoc',
+ 'only_directives', 'plot_directive']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
Modified: trunk/matplotlib/doc/make.py
===================================================================
--- trunk/matplotlib/doc/make.py 2008-06-13 12:46:20 UTC (rev 5502)
+++ trunk/matplotlib/doc/make.py 2008-06-13 14:10:02 UTC (rev 5503)
@@ -24,24 +24,32 @@
def html():
check_build()
figs()
- os.system('sphinx-build -b html -d build/doctrees . build/html')
+ if os.system('sphinx-build -b html -d build/doctrees . build/html'):
+ raise SystemExit("Building HTML failed.")
+ figures_dest_path = 'build/html/users/figures'
+ if os.path.exists(figures_dest_path):
+ shutil.rmtree(figures_dest_path)
+ shutil.copytree('users/figures', figures_dest_path)
+
def latex():
check_build()
figs()
if sys.platform != 'win32':
# LaTeX format.
- os.system('sphinx-build -b latex -d build/doctrees . build/latex')
+ if os.system('sphinx-build -b latex -d build/doctrees . build/latex'):
+ raise SystemExit("Building LaTeX failed.")
# Produce pdf.
os.chdir('build/latex')
# Copying the makefile produced by sphinx...
- os.system('pdflatex Matplotlib.tex')
- os.system('pdflatex Matplotlib.tex')
- os.system('makeindex -s python.ist Matplotlib.idx')
- os.system('makeindex -s python.ist modMatplotlib.idx')
- os.system('pdflatex Matplotlib.tex')
+ if (os.system('pdflatex Matplotlib.tex') or
+ os.system('pdflatex Matplotlib.tex') or
+ os.system('makeindex -s python.ist Matplotlib.idx') or
+ os.system('makeindex -s python.ist modMatplotlib.idx') or
+ os.system('pdflatex Matplotlib.tex')):
+ raise SystemExit("Rendering LaTeX failed.")
os.chdir('../..')
else:
Added: trunk/matplotlib/doc/sphinxext/only_directives.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/only_directives.py (rev 0)
+++ trunk/matplotlib/doc/sphinxext/only_directives.py 2008-06-13 14:10:02 UTC (rev 5503)
@@ -0,0 +1,87 @@
+#
+# A pair of directives for inserting content that will only appear in
+# either html or latex.
+#
+
+from docutils.nodes import Body, Element
+from docutils.writers.html4css1 import HTMLTranslator
+from sphinx.latexwriter import LaTeXTranslator
+from docutils.parsers.rst import directives
+
+class html_only(Body, Element):
+ pass
+
+class latex_only(Body, Element):
+ 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]
+
+try:
+ from docutils.parsers.rst import Directive
+except ImportError:
+ from docutils.parsers.rst.directives import _directives
+
+ 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)
+
+ for func in (html_only_directive, latex_only_directive):
+ func.content = 1
+ func.options = {}
+ func.arguments = None
+
+ _directives['htmlonly'] = html_only_directive
+ _directives['latexonly'] = latex_only_directive
+else:
+ class OnlyDirective(Directive):
+ has_content = True
+ required_arguments = 0
+ optional_arguments = 0
+ final_argument_whitespace = True
+ option_spec = {}
+
+ def run(self):
+ self.assert_has_content()
+ return run(self.content, self.node_class,
+ self.state, self.content_offset)
+
+ class HtmlOnlyDirective(OnlyDirective):
+ node_class = html_only
+
+ class LatexOnlyDirective(OnlyDirective):
+ node_class = latex_only
+
+ directives.register_directive('htmlonly', HtmlOnlyDirective)
+ directives.register_directive('latexonly', LatexOnlyDirective)
+
+def setup(app):
+ app.add_node(html_only)
+ app.add_node(latex_only)
+
+ # 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 = []
+
+ HTMLTranslator.visit_html_only = visit_perform
+ HTMLTranslator.depart_html_only = depart_perform
+ HTMLTranslator.visit_latex_only = visit_ignore
+ HTMLTranslator.depart_latex_only = depart_ignore
+
+ LaTeXTranslator.visit_html_only = visit_ignore
+ LaTeXTranslator.depart_html_only = depart_ignore
+ LaTeXTranslator.visit_latex_only = visit_perform
+ LaTeXTranslator.depart_latex_only = depart_perform
Added: trunk/matplotlib/doc/sphinxext/plot_directive.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/plot_directive.py (rev 0)
+++ trunk/matplotlib/doc/sphinxext/plot_directive.py 2008-06-13 14:10:02 UTC (rev 5503)
@@ -0,0 +1,85 @@
+"""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.
+ Underneath that, a [source] link will go to a plain text .py of
+ the source.
+
+- On LaTeX, will include a .pdf
+"""
+
+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
+
+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}
+
+template = """
+.. literalinclude:: %(reference)s.py
+
+.. htmlonly::
+
+ .. image:: %(reference)s.png
+ :target: %(reference)s.hires.png
+%(options)s
+
+ `[source] <%(reference)s.py>`_
+
+.. latexonly::
+ .. image:: %(reference)s.pdf
+%(options)s
+
+"""
+
+def run(arguments, options, state_machine, lineno):
+ reference = directives.uri(arguments[0])
+ if reference.endswith('.py'):
+ reference = reference[:-3]
+ options = [' :%s: %s' % (key, val) for key, val in
+ options.items()]
+ options = "\n".join(options)
+ lines = template % locals()
+ lines = lines.split('\n')
+
+ state_machine.insert_input(
+ lines, state_machine.input_lines.source(0))
+ return []
+
+try:
+ from docutils.parsers.rst import Directive
+except ImportError:
+ from docutils.parsers.rst.directives import _directives
+
+ def plot_directive(name, arguments, options, content, lineno,
+ content_offset, block_text, state, state_machine):
+ return run(arguments, options, state_machine, lineno)
+ plot_directive.__doc__ = __doc__
+ plot_directive.arguments = (1, 0, 1)
+ plot_directive.options = options
+
+ _directives['plot'] = plot_directive
+else:
+ class plot_directive(Directive):
+ required_arguments = 1
+ optional_arguments = 0
+ final_argument_whitespace = True
+ option_spec = options
+ def run(self):
+ return run(self.arguments, self.options,
+ self.state_machine, self.lineno)
+ plot_directive.__doc__ = __doc__
+
+ directives.register_directive('plot', plot_directive)
+
Modified: trunk/matplotlib/doc/users/annotations.rst
===================================================================
--- trunk/matplotlib/doc/users/annotations.rst 2008-06-13 12:46:20 UTC (rev 5502)
+++ trunk/matplotlib/doc/users/annotations.rst 2008-06-13 14:10:02 UTC (rev 5503)
@@ -12,9 +12,7 @@
``xy`` and the location of the text ``xytext``. Both of these
arguments are ``(x,y)`` tuples.
-.. literalinclude:: figures/annotation_basic.py
-
-.. image:: figures/annotation_basic.png
+.. plot:: figures/annotation_basic.py
:scale: 75
In this example, both the ``xy`` (arrow tip) and ``xytext`` locations
@@ -73,9 +71,7 @@
``fontsize are passed from the `~matplotlib.Axes.annotate` to the
``Text`` instance
-.. literalinclude:: figures/annotation_polar.py
-
-.. image:: figures/annotation_polar.png
+.. plot:: figures/annotation_polar.py
:scale: 75
See the `annotations demo
Modified: trunk/matplotlib/doc/users/artists.rst
===================================================================
--- trunk/matplotlib/doc/users/artists.rst 2008-06-13 12:46:20 UTC (rev 5502)
+++ trunk/matplotlib/doc/users/artists.rst 2008-06-13 14:10:02 UTC (rev 5503)
@@ -604,9 +604,7 @@
Here is an example, not recommended for its beauty, which customizes
the axes and tick properties
-.. literalinclude:: figures/fig_axes_customize_simple.py
-
-.. image:: figures/fig_axes_customize_simple.png
+.. plot:: figures/fig_axes_customize_simple.py
:scale: 75
@@ -643,7 +641,5 @@
Here is an example which sets the formatter for the upper ticks with
dollar signs and colors them green on the right side of the yaxis
-.. literalinclude:: figures/dollar_ticks.py
-
-.. image:: figures/dollar_ticks.png
+.. plot:: figures/dollar_ticks.py
:scale: 75
Modified: trunk/matplotlib/doc/users/figures/make.py
===================================================================
--- trunk/matplotlib/doc/users/figures/make.py 2008-06-13 12:46:20 UTC (rev 5502)
+++ trunk/matplotlib/doc/users/figures/make.py 2008-06-13 14:10:02 UTC (rev 5503)
@@ -7,27 +7,37 @@
mplshell = IPython.Shell.MatplotlibShell('mpl')
+formats = [('png', 100),
+ ('hires.png', 200),
+ ('pdf', 72)]
+
def figs():
print 'making figs'
import matplotlib.pyplot as plt
for fname in glob.glob('*.py'):
if fname==__file__: continue
basename, ext = os.path.splitext(fname)
- outfile = '%s.png'%basename
+ outfiles = ['%s.%s' % (basename, format) for format, dpi in formats]
+ all_exists = True
+ for format, dpi in formats:
+ if not os.path.exists('%s.%s' % (basename, format)):
+ all_exists = False
+ break
- if os.path.exists(outfile):
- print ' already have %s'%outfile
- continue
+ if all_exists:
+ print ' already have %s'%fname
else:
print ' building %s'%fname
- plt.close('all') # we need to clear between runs
- mplshell.magic_run(basename)
- plt.savefig(outfile)
+ plt.close('all') # we need to clear between runs
+ mplshell.magic_run(basename)
+ for format, dpi in formats:
+ plt.savefig('%s.%s' % (basename, format), dpi=dpi)
print 'all figures made'
def clean():
- patterns = ['#*', '*~', '*.png', '*pyc']
+ patterns = (['#*', '*~', '*pyc'] +
+ ['*.%s' % format for format, dpi in formats])
for pattern in patterns:
for fname in glob.glob(pattern):
os.remove(fname)
Modified: trunk/matplotlib/doc/users/mathtext.rst
===================================================================
--- trunk/matplotlib/doc/users/mathtext.rst 2008-06-13 12:46:20 UTC (rev 5502)
+++ trunk/matplotlib/doc/users/mathtext.rst 2008-06-13 14:10:02 UTC (rev 5503)
@@ -271,9 +271,7 @@
Here is an example illustrating many of these features in context.
-.. literalinclude:: figures/pyplot_mathtext.py
-
-.. image:: figures/pyplot_mathtext.png
+.. plot:: figures/pyplot_mathtext.py
:scale: 75
Modified: trunk/matplotlib/doc/users/pyplot_tutorial.rst
===================================================================
--- trunk/matplotlib/doc/users/pyplot_tutorial.rst 2008-06-13 12:46:20 UTC (rev 5502)
+++ trunk/matplotlib/doc/users/pyplot_tutorial.rst 2008-06-13 14:10:02 UTC (rev 5503)
@@ -12,12 +12,9 @@
keeps track of the current figure and plotting area, and the plotting
functions are directed to the current axes
-.. literalinclude:: figures/pyplot_simple.py
-
-.. image:: figures/pyplot_simple.png
+.. plot:: figures/pyplot_simple
:scale: 75
-
You may be wondering why the x-axis ranges from 0-3 and the y-axis
from 1-4. If you provide a single list or array to the
:func:`~matplotlib.pyplot.plot` command, matplotlib assumes it a
@@ -39,9 +36,7 @@
The default format string is 'b-', which is a solid blue line. For
example, to plot the above with red circles, you would issue
-.. literalinclude:: figures/pyplot_formatstr.py
-
-.. image:: figures/pyplot_formatstr.png
+.. plot:: figures/pyplot_formatstr.py
:scale: 75
See the :func:`~matplotlib.pyplot.plot` documentation for a complete
@@ -57,9 +52,7 @@
plotting several lines with different format styles in one command
using arrays.
-.. literalinclude:: figures/pyplot_three.py
-
-.. image:: figures/pyplot_three.png
+.. plot:: figures/pyplot_three.py
:scale: 75
.. _controlling-line-properties:
@@ -164,9 +157,7 @@
to worry about this, because it is all taken care of behind the
scenes. Below is an script to create two subplots.
-.. literalinclude:: figures/pyplot_two_subplots.py
-
-.. image:: figures/pyplot_two_subplots.png
+.. plot:: figures/pyplot_two_subplots.py
:scale: 75
The :func:`~matplotlib.pyplot.figure` command here is optional because
@@ -225,9 +216,7 @@
are used tox add text in the indicated locations (see :ref:`text-intro`
for a more detailed example)
-.. literalinclude:: figures/pyplot_text.py
-
-.. image:: figures/pyplot_text.png
+.. plot:: figures/pyplot_text.py
:scale: 75
@@ -273,9 +262,7 @@
the argument ``xy`` and the location of the text ``xytext``. Both of
these arguments are ``(x,y)`` tuples.
-.. literalinclude:: figures/pyplot_annotate.py
-
-.. image:: figures/pyplot_annotate.png
+.. plot:: figures/pyplot_annotate.py
:scale: 75
In this basic example, both the ``xy`` (arrow tip) and ``xytext``
Modified: trunk/matplotlib/doc/users/text_intro.rst
===================================================================
--- trunk/matplotlib/doc/users/text_intro.rst 2008-06-13 12:46:20 UTC (rev 5502)
+++ trunk/matplotlib/doc/users/text_intro.rst 2008-06-13 14:10:02 UTC (rev 5503)
@@ -55,8 +55,6 @@
variety of font and other properties. The example below shows all of
these commands in action.
-.. literalinclude:: figures/text_commands.py
-
-.. image:: figures/text_commands.png
+.. plot:: figures/text_commands.py
:scale: 75
Modified: trunk/matplotlib/doc/users/text_props.rst
===================================================================
--- trunk/matplotlib/doc/users/text_props.rst 2008-06-13 12:46:20 UTC (rev 5502)
+++ trunk/matplotlib/doc/users/text_props.rst 2008-06-13 14:10:02 UTC (rev 5503)
@@ -57,7 +57,5 @@
bounding box, with 0,0 being the lower left of the axes and 1,1 the
upper right.
-.. literalinclude:: figures/text_layout.py
-
-.. image:: figures/text_layout.png
+.. plot:: figures/text_layout.py
:scale: 75
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <md...@us...> - 2008-06-13 12:46:31
|
Revision: 5502
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5502&view=rev
Author: mdboom
Date: 2008-06-13 05:46:20 -0700 (Fri, 13 Jun 2008)
Log Message:
-----------
Correct label location in pie chart. Thanks Benoit Hirbec!
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-06-13 12:20:35 UTC (rev 5501)
+++ trunk/matplotlib/CHANGELOG 2008-06-13 12:46:20 UTC (rev 5502)
@@ -1,3 +1,6 @@
+2008-06-13 Change pie chart label alignment to avoid having labels
+ overwrite the pie - MGD
+
2008-06-12 Added some helper functions to the mathtext parser to
return bitmap arrays or write pngs to make it easier to use
mathtext outside the context of an mpl figure. modified
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-06-13 12:20:35 UTC (rev 5501)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-06-13 12:46:20 UTC (rev 5502)
@@ -3953,10 +3953,11 @@
xt = x + labeldistance*radius*math.cos(thetam)
yt = y + labeldistance*radius*math.sin(thetam)
+ label_alignment = xt > 0 and 'left' or 'right'
t = self.text(xt, yt, label,
size=rcParams['xtick.labelsize'],
- horizontalalignment='center',
+ horizontalalignment=label_alignment,
verticalalignment='center')
texts.append(t)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-06-13 12:20:37
|
Revision: 5501
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5501&view=rev
Author: jswhit
Date: 2008-06-13 05:20:35 -0700 (Fri, 13 Jun 2008)
Log Message:
-----------
further restifying of docstrings
Modified Paths:
--------------
trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py
Modified: trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py
===================================================================
--- trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py 2008-06-13 12:11:33 UTC (rev 5500)
+++ trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py 2008-06-13 12:20:35 UTC (rev 5501)
@@ -312,8 +312,28 @@
for the map projection as defined by PROJ.4.
================ ====================================================
- Example Usage:
+ **Converting from Geographic (lon/lat) to Map Projection (x/y) Coordinates**
+ Calling a Basemap class instance with the arguments lon, lat will
+ convert lon/lat (in degrees) to x/y native map projection
+ coordinates (in meters). If optional keyword ``inverse`` is
+ True (default is False), the inverse transformation from x/y
+ to lon/lat is performed.
+
+ For cylindrical equidistant projection (``cyl``), this
+ does nothing (i.e. x,y == lon,lat).
+
+ For non-cylindrical projections, the inverse transformation
+ always returns longitudes between -180 and 180 degrees. For
+ cylindrical projections (self.projection == ``cyl``, ``mill`` or ``merc``)
+ The inverse transformation will return longitudes between
+ self.llcrnrlon and self.llcrnrlat.
+
+ Input arguments lon, lat can be either scalar floats, sequences
+ or numpy arrays.
+
+ **Example Usage:**
+
>>> from mpl_toolkits.basemap import Basemap
>>> import numpy as np
>>> import matplotlib.pyplot as plt
@@ -739,7 +759,7 @@
Calling a Basemap class instance with the arguments lon, lat will
convert lon/lat (in degrees) to x/y native map projection
coordinates (in meters). If optional keyword ``inverse`` is
- ``True11 (default is ``False``), the inverse transformation from x/y
+ True (default is False), the inverse transformation from x/y
to lon/lat is performed.
For cylindrical equidistant projection (``cyl``), this
@@ -747,11 +767,13 @@
For non-cylindrical projections, the inverse transformation
always returns longitudes between -180 and 180 degrees. For
- cylindrical projections (self.projection == ``cyl``,``mill`` or ``merc``)
- the inverse transformation will return longitudes between
+ cylindrical projections (self.projection == ``cyl``,
+ ``mill`` or ``merc``)
+ The inverse transformation will return longitudes between
self.llcrnrlon and self.llcrnrlat.
- input arguments lon, lat can be either scalar floats or N arrays.
+ Input arguments lon, lat can be either scalar floats,
+ sequences, or numpy arrays.
"""
return self.projtran(x,y,inverse=inverse)
@@ -760,7 +782,7 @@
return arrays of shape (ny,nx) containing lon,lat coordinates of
an equally spaced native projection grid.
- if ``returnxy = True``, the x,y values of the grid are returned also.
+ If ``returnxy = True``, the x,y values of the grid are returned also.
"""
return self.projtran.makegrid(nx,ny,returnxy=returnxy)
@@ -1205,19 +1227,22 @@
"""
Fill continents.
- color - color to fill continents (default gray).
+ ============== ====================================================
+ Keyword Description
+ ============== ====================================================
+ color color to fill continents (default gray).
+ lake_color color to fill inland lakes (default axes background).
+ ax axes instance (overrides default axes instance).
+ zorder sets the zorder for the continent polygons (if not
+ specified, uses default zorder for a Polygon patch).
+ Set to zero if you want to paint over the filled
+ continents).
+ ============== ====================================================
- lake_color - color to fill inland lakes (default axes background).
+ After filling continents, lakes are re-filled with
+ axis background color.
- ax - axes instance (overrides default axes instance).
-
- zorder - sets the zorder for the continent polygons (if not specified,
- uses default zorder for a Polygon patch). Set to zero if you want to paint
- over the filled continents).
-
- After filling continents, lakes are re-filled with axis background color.
-
- returns Polygon object.
+ returns matplotlib.patches.Polygon object.
"""
if self.resolution is None:
raise AttributeError, 'there are no boundary datasets associated with this Basemap instance'
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ds...@us...> - 2008-06-13 12:11:34
|
Revision: 5500
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5500&view=rev
Author: dsdale
Date: 2008-06-13 05:11:33 -0700 (Fri, 13 Jun 2008)
Log Message:
-----------
added api file for matplotlib configuration
Modified Paths:
--------------
trunk/matplotlib/doc/users/customizing.rst
Added Paths:
-----------
trunk/matplotlib/doc/api/matplotlib_configuration_api.rst
Added: trunk/matplotlib/doc/api/matplotlib_configuration_api.rst
===================================================================
--- trunk/matplotlib/doc/api/matplotlib_configuration_api.rst (rev 0)
+++ trunk/matplotlib/doc/api/matplotlib_configuration_api.rst 2008-06-13 12:11:33 UTC (rev 5500)
@@ -0,0 +1,24 @@
+************************
+matplotlib configuration
+************************
+
+
+:mod:`matplotlib`
+=================
+
+.. autofunction:: matplotlib.get_backend
+.. autofunction:: matplotlib.get_configdir
+.. autofunction:: matplotlib.interactive
+.. autofunction:: matplotlib.rc
+.. autofunction:: matplotlib.rcdefaults
+.. autoclass:: matplotlib.RcParams
+.. autofunction:: matplotlib.use
+.. autoclass:: matplotlib.Verbose
+
+
+:mod:`matplotlib.rcsetup`
+=============================
+
+.. automodule:: matplotlib.rcsetup
+ :members:
+ :undoc-members:
\ No newline at end of file
Modified: trunk/matplotlib/doc/users/customizing.rst
===================================================================
--- trunk/matplotlib/doc/users/customizing.rst 2008-06-12 22:06:09 UTC (rev 5499)
+++ trunk/matplotlib/doc/users/customizing.rst 2008-06-13 12:11:33 UTC (rev 5500)
@@ -20,13 +20,12 @@
specific customizations that you do not want to apply elsewhere.
2. :file:`.matplotlib/matplotlibrc`, for the user's default customizations. See
:ref:`locating-matplotlib-config-dir`.
-3. :file:`{INSTALL}/matplotlib/mpl-data/matplotlibrc`, where
- :file:`{INSTALL}` is something like
- :file:`/usr/lib/python2.5/site-packages` on Linux, and maybe
- :file:`C:\\Python25\\Lib\\site-packages` on Windows. Every time you
- install matplotlib, this file will be overwritten, so if you want
- your customizations to be saved, please move this file to you
- :file:`.matplotlib` directory.
+3. :file:`{INSTALL}/matplotlib/mpl-data/matplotlibrc`, where :file:`{INSTALL}`
+ is something like :file:`/usr/lib/python2.5/site-packages` on Linux, and
+ maybe :file:`C:\\Python25\\Lib\\site-packages` on Windows. Every time you
+ install matplotlib, this file will be overwritten, so if you want your
+ customizations to be saved, please move this file to you :file:`.matplotlib`
+ directory.
See below for a sample :ref:`matplotlibrc file<matplotlibrc-sample>`.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-12 22:06:16
|
Revision: 5499
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5499&view=rev
Author: jdh2358
Date: 2008-06-12 15:06:09 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
added a couple of faqs
Modified Paths:
--------------
trunk/matplotlib/doc/faq/installing_faq.rst
trunk/matplotlib/doc/faq/troubleshooting_faq.rst
Modified: trunk/matplotlib/doc/faq/installing_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-12 21:39:18 UTC (rev 5498)
+++ trunk/matplotlib/doc/faq/installing_faq.rst 2008-06-12 22:06:09 UTC (rev 5499)
@@ -11,6 +11,8 @@
See :ref:`reporting-problems`.
+.. _clean-install:
+
How do I cleanly rebuild and reinstall everything?
==================================================
@@ -102,7 +104,7 @@
backends generate a pixel represenation of the line whose accuracy
depends on a DPI setting.
-Here is a summary of the matplotlib renders (there is an eponymous
+Here is a summary of the matplotlib renderers (there is an eponymous
backed for each):
=============================== =====================================================================================
@@ -159,3 +161,30 @@
the disk. Many Mac OS X eggs with cruft at the end of the filename,
which prevents their installation through easy_install. Renaming is
all it takes to install them; still, it's annoying.
+
+Windows questions
+=================
+
+.. _windows-installers:
+
+Where can I get binary installers for windows?
+----------------------------------------------
+
+If you have already installed python, you can use one of the
+matplotlib binary installers for windows -- you can get these from the
+`sourceforge download
+<http://sourceforge.net/project/platformdownload.php?group_id=80706>`_
+site. Choose the files that match your version of python (eg
+``py2.5`` if you instaslled Python 2.5) and have the ``exe``
+extension. If you haven't already installed python, you can get the
+official version from the `python web site
+<http://python.org/download/>`_. There are also two packaged
+distributions of python that come preloaded with matplotlib and many
+other tools like ipython, numpy, scipy, vtk and user interface
+toolkits. These packages are quite large because they come with so
+much, but you get everything with a single click installer.
+
+* the enthought python distribution `EPD
+ <http://www.enthought.com/products/epd.php>`_
+
+* `python (x, y) <http://www.pythonxy.com/foreword.php>`_
Modified: trunk/matplotlib/doc/faq/troubleshooting_faq.rst
===================================================================
--- trunk/matplotlib/doc/faq/troubleshooting_faq.rst 2008-06-12 21:39:18 UTC (rev 5498)
+++ trunk/matplotlib/doc/faq/troubleshooting_faq.rst 2008-06-12 22:06:09 UTC (rev 5499)
@@ -77,13 +77,21 @@
python -c `import matplotlib; print matplotlib.__version__`
* where you obtained matplotlib (e.g. your Linux distribution's
- packages or the matplotlib Sourceforge site)
+ packages or the matplotlib Sourceforge site, or the enthought
+ python distribution `EPD
+ <http://www.enthought.com/products/epd.php>`_.
* any customizations to your ``matplotlibrc`` file (see
:ref:`customizing-matplotlib`).
* if the problem is reproducible, please try to provide a *minimal*,
- standalone Python script that demonstrates the problem
+ standalone Python script that demonstrates the problem. This is
+ *the* critical step. If you can't post a piece of code that we
+ can run and reproduce your error, the chances of getting help are
+ significantly diminished. Very often, the mere act of trying to
+ minimize your code to the smallest bit that produces the error
+ will help you find a bug in *your* code that is causing the
+ problem.
* you can get very helpful debugging output from matlotlib by
running your script with a ``verbose-helpful`` or
@@ -116,3 +124,27 @@
the tracker so the issue doesn't get lost.
+.. _svn-trouble:
+
+I am having trouble with a recent svn update, what should I do?
+===============================================================
+
+First make sure you have a clean build and install (see
+:ref:`clean-install`), get the latest svn update, install it and run a
+simple test script in debug mode::
+
+ rm -rf build
+ rm -rf /path/to/site-packages/matplotlib*
+ svn up
+ python setup.py install > build.out
+ python examples/pylab_examples/simple_plot.py --verbose-debug > run.out
+
+and post :file:`build.out` and :file:`run.out` to the
+`matplotlib-devel
+<http://lists.sourceforge.net/mailman/listinfo/matplotlib-devel>`_
+mailing list (please do not post svn problems to the `users list
+<http://lists.sourceforge.net/mailman/listinfo/matplotlib-users>`_).
+
+Of course, you will want to clearly describe your problem, what you
+are expecting and what you are getting, but often a clean build and
+install will help. See also :ref:`reporting-problems`.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-12 21:39:25
|
Revision: 5498
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5498&view=rev
Author: jdh2358
Date: 2008-06-12 14:39:18 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
added mathpng and ipy extensions
Modified Paths:
--------------
trunk/py4science/examples/sphinx_template/README.txt
Modified: trunk/py4science/examples/sphinx_template/README.txt
===================================================================
--- trunk/py4science/examples/sphinx_template/README.txt 2008-06-12 21:37:11 UTC (rev 5497)
+++ trunk/py4science/examples/sphinx_template/README.txt 2008-06-12 21:39:18 UTC (rev 5498)
@@ -28,3 +28,8 @@
* _templates - used by the sphinx build system
+You can get the latest svn of this document at:
+
+ > svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/py4science/examples/sphinx_template
+
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-12 21:37:31
|
Revision: 5497
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5497&view=rev
Author: jdh2358
Date: 2008-06-12 14:37:11 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
added mathpng and ipy extensions
Modified Paths:
--------------
trunk/py4science/examples/sphinx_template/README.txt
trunk/py4science/examples/sphinx_template/conf.py
trunk/py4science/examples/sphinx_template/model/index.rst
trunk/py4science/examples/sphinx_template/model/introduction.rst
trunk/py4science/examples/sphinx_template/model/sphinx_helpers.rst
Added Paths:
-----------
trunk/py4science/examples/sphinx_template/model/api_docs.rst
trunk/py4science/examples/sphinx_template/sphinxext/
trunk/py4science/examples/sphinx_template/sphinxext/ipython_console_highlighting.py
trunk/py4science/examples/sphinx_template/sphinxext/mathml.py
trunk/py4science/examples/sphinx_template/sphinxext/mathpng.py
Removed Paths:
-------------
trunk/py4science/examples/sphinx_template/build/
Modified: trunk/py4science/examples/sphinx_template/README.txt
===================================================================
--- trunk/py4science/examples/sphinx_template/README.txt 2008-06-12 20:51:59 UTC (rev 5496)
+++ trunk/py4science/examples/sphinx_template/README.txt 2008-06-12 21:37:11 UTC (rev 5497)
@@ -7,7 +7,8 @@
contains
-* model - A document describing a model
+* model - A document describing a model. Be sure to see the cheat
+ sheet file model/sphinx_helpers.rst
* simulations - A document describing the simulations -- contains a
code subdir with python scripts and a make.py file to build them
@@ -16,6 +17,9 @@
* make.py - the build script to build the html or PDF docs. Do
`python make.py html` or `python make.py latex` for PDF
+* sphinxext - some extensions to sphinx to handle math, ipython syntax
+ highlighting, autodocs
+
* index.rst - the top level include document for sampledocs document
* conf.py - the sphinx configuration
Modified: trunk/py4science/examples/sphinx_template/conf.py
===================================================================
--- trunk/py4science/examples/sphinx_template/conf.py 2008-06-12 20:51:59 UTC (rev 5496)
+++ trunk/py4science/examples/sphinx_template/conf.py 2008-06-12 21:37:11 UTC (rev 5497)
@@ -16,14 +16,19 @@
# If your extensions are in another directory, add it here. If the directory
# is relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
-#sys.path.append(os.path.abspath('some/directory'))
+sys.path.append(os.path.abspath('sphinxext'))
+
+# Import support for ipython console session syntax highlighting (lives
+# in the sphinxext directory defined above)
+import ipython_console_highlighting
+
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-#extensions = []
+extensions = ['mathpng', 'sphinx.ext.autodoc']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
Added: trunk/py4science/examples/sphinx_template/model/api_docs.rst
===================================================================
--- trunk/py4science/examples/sphinx_template/model/api_docs.rst (rev 0)
+++ trunk/py4science/examples/sphinx_template/model/api_docs.rst 2008-06-12 21:37:11 UTC (rev 5497)
@@ -0,0 +1,16 @@
+.. _samplecode-api:
+
+**************
+Samplecode API
+**************
+
+It is easy to autodocument API code if the code has REST docstrings
+using the sphinx `autodoc <http://sphinx.pocoo.org/ext/autodoc.html>`_
+facilites.
+
+:mod:`matplotlib.backend_bases`
+================================
+
+.. automodule:: matplotlib.backend_bases
+ :members:
+ :undoc-members:
Modified: trunk/py4science/examples/sphinx_template/model/index.rst
===================================================================
--- trunk/py4science/examples/sphinx_template/model/index.rst 2008-06-12 20:51:59 UTC (rev 5496)
+++ trunk/py4science/examples/sphinx_template/model/index.rst 2008-06-12 21:37:11 UTC (rev 5497)
@@ -12,3 +12,4 @@
introduction.rst
next_steps.rst
sphinx_helpers.rst
+ api_docs.rst
\ No newline at end of file
Modified: trunk/py4science/examples/sphinx_template/model/introduction.rst
===================================================================
--- trunk/py4science/examples/sphinx_template/model/introduction.rst 2008-06-12 20:51:59 UTC (rev 5496)
+++ trunk/py4science/examples/sphinx_template/model/introduction.rst 2008-06-12 21:37:11 UTC (rev 5497)
@@ -4,8 +4,15 @@
Model Introduction
******************
-Wherein I describe my fancy model
+Wherein I describe my fancy model :math:`E=MC^2`
+and also
+.. math::
+
+ \frac{5 - \frac{1}{x}}{4}
+
+For more details, see :ref:`using-math`.
+
.. _other-models:
Other Models
Modified: trunk/py4science/examples/sphinx_template/model/sphinx_helpers.rst
===================================================================
--- trunk/py4science/examples/sphinx_template/model/sphinx_helpers.rst 2008-06-12 20:51:59 UTC (rev 5496)
+++ trunk/py4science/examples/sphinx_template/model/sphinx_helpers.rst 2008-06-12 21:37:11 UTC (rev 5497)
@@ -63,6 +63,31 @@
section inside this document (see :ref:`making-a-table`) or another
document (see :ref:`final-results`).
+You can also reference classes, modules, functions, etc that are
+documented using the sphinx `autodoc
+<http://sphinx.pocoo.org/ext/autodoc.html>`_ facilites. For example,
+see the module :mod:`matplotlib.backend_bases` documentation, or the
+class :class:`~matplotlib.backend_bases.LocationEvent`, or the method
+:meth:`~matplotlib.backend_bases.FigureCanvasBase.mpl_connect`.
+
+.. _ipython-highlighting:
+
+ipython sessions
+================
+
+Michael Droettboom contributed a sphinx extension which does pygments
+syntax highlighting on ipython sessions
+
+.. sourcecode:: ipython
+
+ In [69]: lines = plot([1,2,3])
+
+ In [70]: setp(lines)
+ alpha: float
+ animated: [True | False]
+ antialiased or aa: [True | False]
+ ...snip
+
.. _formatting-text:
Formatting text
@@ -80,6 +105,36 @@
.. literalinclude:: ../simulations/code/elegant.py
+.. _using-math:
+
+Using math
+==========
+
+In sphinx you can include inline math :math:`x\leftarrow y\ x\forall
+y\ x-y` or display math
+
+.. math::
+
+ W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]
+
+
+There is a :file:`spinxext/mathml.py` file in the
+:file:`spinx_template` directory which can be enabled via the
+:file:`conf.py` configuration file. However, we have found that
+resultant html is not supported across many browsers, so have added a
+sphinx extension for translating math to png. In the file
+:file:`sphinxext/mathpng.py` there are two functions ``latex2png``.
+The first one requires latex and dvipng, and the second one uses
+matplotlib mathtext (requires mpl svn rxx or later). Because the 2nd
+function replaces the first one, the matplotlib mathtext support is on
+by default, so you can generate equation enabled html anywhere
+matplotlib is installed (for PDF you will still need pdflatex
+installed). If you would rather use latex and dvipng, simply hide the
+second ``latex2png`` definition, eg by renaming the second function
+``_latex2png``.
+
+
+
.. _emacs-helpers:
Emacs helpers
Added: trunk/py4science/examples/sphinx_template/sphinxext/ipython_console_highlighting.py
===================================================================
--- trunk/py4science/examples/sphinx_template/sphinxext/ipython_console_highlighting.py (rev 0)
+++ trunk/py4science/examples/sphinx_template/sphinxext/ipython_console_highlighting.py 2008-06-12 21:37:11 UTC (rev 5497)
@@ -0,0 +1,75 @@
+from pygments.lexer import Lexer, do_insertions
+from pygments.lexers.agile import PythonConsoleLexer, PythonLexer, \
+ PythonTracebackLexer
+from pygments.token import Comment, Generic
+from sphinx import highlighting
+import re
+
+line_re = re.compile('.*?\n')
+
+class IPythonConsoleLexer(Lexer):
+ """
+ For IPython console output or doctests, such as:
+
+ Tracebacks are not currently supported.
+
+ .. sourcecode:: pycon
+
+ In [1]: a = 'foo'
+
+ In [2]: a
+ Out[2]: 'foo'
+
+ In [3]: print a
+ foo
+
+ In [4]: 1 / 0
+ """
+ name = 'IPython console session'
+ aliases = ['ipython']
+ mimetypes = ['text/x-ipython-console']
+ input_prompt = re.compile("(In \[[0-9]+\]: )|( \.\.\.+:)")
+ output_prompt = re.compile("(Out\[[0-9]+\]: )|( \.\.\.+:)")
+ continue_prompt = re.compile(" \.\.\.+:")
+ tb_start = re.compile("\-+")
+
+ def get_tokens_unprocessed(self, text):
+ pylexer = PythonLexer(**self.options)
+ tblexer = PythonTracebackLexer(**self.options)
+
+ curcode = ''
+ insertions = []
+ for match in line_re.finditer(text):
+ line = match.group()
+ input_prompt = self.input_prompt.match(line)
+ continue_prompt = self.continue_prompt.match(line.rstrip())
+ output_prompt = self.output_prompt.match(line)
+ if line.startswith("#"):
+ insertions.append((len(curcode),
+ [(0, Comment, line)]))
+ elif input_prompt is not None:
+ insertions.append((len(curcode),
+ [(0, Generic.Prompt, input_prompt.group())]))
+ curcode += line[input_prompt.end():]
+ elif continue_prompt is not None:
+ insertions.append((len(curcode),
+ [(0, Generic.Prompt, continue_prompt.group())]))
+ curcode += line[continue_prompt.end():]
+ elif output_prompt is not None:
+ insertions.append((len(curcode),
+ [(0, Generic.Output, output_prompt.group())]))
+ curcode += line[output_prompt.end():]
+ else:
+ if curcode:
+ for item in do_insertions(insertions,
+ pylexer.get_tokens_unprocessed(curcode)):
+ yield item
+ curcode = ''
+ insertions = []
+ yield match.start(), Generic.Output, line
+ if curcode:
+ for item in do_insertions(insertions,
+ pylexer.get_tokens_unprocessed(curcode)):
+ yield item
+
+highlighting.lexers['ipython'] = IPythonConsoleLexer()
Added: trunk/py4science/examples/sphinx_template/sphinxext/mathml.py
===================================================================
--- trunk/py4science/examples/sphinx_template/sphinxext/mathml.py (rev 0)
+++ trunk/py4science/examples/sphinx_template/sphinxext/mathml.py 2008-06-12 21:37:11 UTC (rev 5497)
@@ -0,0 +1,552 @@
+from docutils import nodes
+from docutils.writers.html4css1 import HTMLTranslator
+from sphinx.latexwriter import LaTeXTranslator
+
+# Define LaTeX math node:
+class latex_math(nodes.General, nodes.Element):
+ pass
+
+def math_role(role, rawtext, text, lineno, inliner,
+ options={}, content=[]):
+ i = rawtext.find('`')
+ latex = rawtext[i+1:-1]
+ try:
+ mathml_tree = parse_latex_math(latex, inline=True)
+ except SyntaxError, msg:
+ msg = inliner.reporter.error(msg, line=lineno)
+ prb = inliner.problematic(rawtext, rawtext, msg)
+ return [prb], [msg]
+ node = latex_math(rawtext)
+ node['latex'] = latex
+ node['mathml_tree'] = mathml_tree
+ return [node], []
+
+
+try:
+ from docutils.parsers.rst import Directive
+except ImportError:
+ # Register directive the old way:
+ from docutils.parsers.rst.directives import _directives
+ def math_directive(name, arguments, options, content, lineno,
+ content_offset, block_text, state, state_machine):
+ latex = ''.join(content)
+ try:
+ mathml_tree = parse_latex_math(latex, inline=False)
+ except SyntaxError, msg:
+ error = state_machine.reporter.error(
+ msg, nodes.literal_block(block_text, block_text), line=lineno)
+ return [error]
+ node = latex_math(block_text)
+ node['latex'] = latex
+ node['mathml_tree'] = mathml_tree
+ return [node]
+ math_directive.arguments = None
+ math_directive.options = {}
+ math_directive.content = 1
+ _directives['math'] = math_directive
+else:
+ class math_directive(Directive):
+ has_content = True
+ def run(self):
+ latex = ' '.join(self.content)
+ try:
+ mathml_tree = parse_latex_math(latex, inline=False)
+ except SyntaxError, msg:
+ error = self.state_machine.reporter.error(
+ msg, nodes.literal_block(self.block_text, self.block_text),
+ line=self.lineno)
+ return [error]
+ node = latex_math(self.block_text)
+ node['latex'] = latex
+ node['mathml_tree'] = mathml_tree
+ return [node]
+ from docutils.parsers.rst import directives
+ directives.register_directive('math', math_directive)
+
+def setup(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):
+ mathml = ''.join(node['mathml_tree'].xml())
+ self.body.append(mathml)
+ def depart_latex_math_html(self, node):
+ pass
+ HTMLTranslator.visit_latex_math = visit_latex_math_html
+ HTMLTranslator.depart_latex_math = depart_latex_math_html
+
+ # 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
+ LaTeXTranslator.visit_latex_math = visit_latex_math_latex
+ LaTeXTranslator.depart_latex_math = depart_latex_math_latex
+
+
+# LaTeX to MathML translation stuff:
+class math:
+ """Base class for MathML elements."""
+
+ nchildren = 1000000
+ """Required number of children"""
+
+ def __init__(self, children=None, inline=None):
+ """math([children]) -> MathML element
+
+ children can be one child or a list of children."""
+
+ self.children = []
+ if children is not None:
+ if type(children) is list:
+ for child in children:
+ self.append(child)
+ else:
+ # Only one child:
+ self.append(children)
+
+ if inline is not None:
+ self.inline = inline
+
+ def __repr__(self):
+ if hasattr(self, 'children'):
+ return self.__class__.__name__ + '(%s)' % \
+ ','.join([repr(child) for child in self.children])
+ else:
+ return self.__class__.__name__
+
+ def full(self):
+ """Room for more children?"""
+
+ return len(self.children) >= self.nchildren
+
+ def append(self, child):
+ """append(child) -> element
+
+ Appends child and returns self if self is not full or first
+ non-full parent."""
+
+ assert not self.full()
+ self.children.append(child)
+ child.parent = self
+ node = self
+ while node.full():
+ node = node.parent
+ return node
+
+ def delete_child(self):
+ """delete_child() -> child
+
+ Delete last child and return it."""
+
+ child = self.children[-1]
+ del self.children[-1]
+ return child
+
+ def close(self):
+ """close() -> parent
+
+ Close element and return first non-full element."""
+
+ parent = self.parent
+ while parent.full():
+ parent = parent.parent
+ return parent
+
+ def xml(self):
+ """xml() -> xml-string"""
+
+ return self.xml_start() + self.xml_body() + self.xml_end()
+
+ def xml_start(self):
+ if not hasattr(self, 'inline'):
+ return ['<%s>' % self.__class__.__name__]
+ xmlns = 'http://www.w3.org/1998/Math/MathML'
+ if self.inline:
+ return ['<math xmlns="%s">' % xmlns]
+ else:
+ return ['<math xmlns="%s" mode="display">' % xmlns]
+
+ def xml_end(self):
+ return ['</%s>' % self.__class__.__name__]
+
+ def xml_body(self):
+ xml = []
+ for child in self.children:
+ xml.extend(child.xml())
+ return xml
+
+class mrow(math): pass
+class mtable(math): pass
+class mtr(mrow): pass
+class mtd(mrow): pass
+
+class mx(math):
+ """Base class for mo, mi, and mn"""
+
+ nchildren = 0
+ def __init__(self, data):
+ self.data = data
+
+ def xml_body(self):
+ return [self.data]
+
+class mo(mx):
+ translation = {'<': '<', '>': '>'}
+ def xml_body(self):
+ return [self.translation.get(self.data, self.data)]
+
+class mi(mx): pass
+class mn(mx): pass
+
+class msub(math):
+ nchildren = 2
+
+class msup(math):
+ nchildren = 2
+
+class msqrt(math):
+ nchildren = 1
+
+class mroot(math):
+ nchildren = 2
+
+class mfrac(math):
+ nchildren = 2
+
+class msubsup(math):
+ nchildren = 3
+ def __init__(self, children=None, reversed=False):
+ self.reversed = reversed
+ math.__init__(self, children)
+
+ def xml(self):
+ if self.reversed:
+## self.children[1:3] = self.children[2:0:-1]
+ self.children[1:3] = [self.children[2], self.children[1]]
+ self.reversed = False
+ return math.xml(self)
+
+class mfenced(math):
+ translation = {'\\{': '{', '\\langle': u'\u2329',
+ '\\}': '}', '\\rangle': u'\u232A',
+ '.': ''}
+ def __init__(self, par):
+ self.openpar = par
+ math.__init__(self)
+
+ def xml_start(self):
+ open = self.translation.get(self.openpar, self.openpar)
+ close = self.translation.get(self.closepar, self.closepar)
+ return ['<mfenced open="%s" close="%s">' % (open, close)]
+
+class mspace(math):
+ nchildren = 0
+
+class mstyle(math):
+ def __init__(self, children=None, nchildren=None, **kwargs):
+ if nchildren is not None:
+ self.nchildren = nchildren
+ math.__init__(self, children)
+ self.attrs = kwargs
+
+ def xml_start(self):
+ return ['<mstyle '] + ['%s="%s"' % item
+ for item in self.attrs.items()] + ['>']
+
+class mover(math):
+ nchildren = 2
+ def __init__(self, children=None, reversed=False):
+ self.reversed = reversed
+ math.__init__(self, children)
+
+ def xml(self):
+ if self.reversed:
+ self.children.reverse()
+ self.reversed = False
+ return math.xml(self)
+
+class munder(math):
+ nchildren = 2
+
+class munderover(math):
+ nchildren = 3
+ def __init__(self, children=None):
+ math.__init__(self, children)
+
+class mtext(math):
+ nchildren = 0
+ def __init__(self, text):
+ self.text = text
+
+ def xml_body(self):
+ return [self.text]
+
+
+over = {'tilde': '~',
+ 'hat': '^',
+ 'bar': '_',
+ 'vec': u'\u2192'}
+
+Greek = {
+ # Upper case greek letters:
+ 'Phi': u'\u03a6', 'Xi': u'\u039e', 'Sigma': u'\u03a3', 'Psi': u'\u03a8', 'Delta': u'\u0394', 'Theta': u'\u0398', 'Upsilon': u'\u03d2', 'Pi': u'\u03a0', 'Omega': u'\u03a9', 'Gamma': u'\u0393', 'Lambda': u'\u039b'}
+greek = {
+ # Lower case greek letters:
+ 'tau': u'\u03c4', 'phi': u'\u03d5', 'xi': u'\u03be', 'iota': u'\u03b9', 'epsilon': u'\u03f5', 'varrho': u'\u03f1', 'varsigma': u'\u03c2', 'beta': u'\u03b2', 'psi': u'\u03c8', 'rho': u'\u03c1', 'delta': u'\u03b4', 'alpha': u'\u03b1', 'zeta': u'\u03b6', 'omega': u'\u03c9', 'varepsilon': u'\u03b5', 'kappa': u'\u03ba', 'vartheta': u'\u03d1', 'chi': u'\u03c7', 'upsilon': u'\u03c5', 'sigma': u'\u03c3', 'varphi': u'\u03c6', 'varpi': u'\u03d6', 'mu': u'\u03bc', 'eta': u'\u03b7', 'theta': u'\u03b8', 'pi': u'\u03c0', 'varkappa': u'\u03f0', 'nu': u'\u03bd', 'gamma': u'\u03b3', 'lambda': u'\u03bb'}
+
+special = {
+ # Binary operation symbols:
+ 'wedge': u'\u2227', 'diamond': u'\u22c4', 'star': u'\u22c6', 'amalg': u'\u2a3f', 'ast': u'\u2217', 'odot': u'\u2299', 'triangleleft': u'\u25c1', 'bigtriangleup': u'\u25b3', 'ominus': u'\u2296', 'ddagger': u'\u2021', 'wr': u'\u2240', 'otimes': u'\u2297', 'sqcup': u'\u2294', 'oplus': u'\u2295', 'bigcirc': u'\u25cb', 'oslash': u'\u2298', 'sqcap': u'\u2293', 'bullet': u'\u2219', 'cup': u'\u222a', 'cdot': u'\u22c5', 'cap': u'\u2229', 'bigtriangledown': u'\u25bd', 'times': u'\xd7', 'setminus': u'\u2216', 'circ': u'\u2218', 'vee': u'\u2228', 'uplus': u'\u228e', 'mp': u'\u2213', 'dagger': u'\u2020', 'triangleright': u'\u25b7', 'div': u'\xf7', 'pm': u'\xb1',
+ # Relation symbols:
+ 'subset': u'\u2282', 'propto': u'\u221d', 'geq': u'\u2265', 'ge': u'\u2265', 'sqsubset': u'\u228f', 'Join': u'\u2a1d', 'frown': u'\u2322', 'models': u'\u22a7', 'supset': u'\u2283', 'in': u'\u2208', 'doteq': u'\u2250', 'dashv': u'\u22a3', 'gg': u'\u226b', 'leq': u'\u2264', 'succ': u'\u227b', 'vdash': u'\u22a2', 'cong': u'\u2245', 'simeq': u'\u2243', 'subseteq': u'\u2286', 'parallel': u'\u2225', 'equiv': u'\u2261', 'ni': u'\u220b', 'le': u'\u2264', 'approx': u'\u2248', 'precsim': u'\u227e', 'sqsupset': u'\u2290', 'll': u'\u226a', 'sqsupseteq': u'\u2292', 'mid': u'\u2223', 'prec': u'\u227a', 'succsim': u'\u227f', 'bowtie': u'\u22c8', 'perp': u'\u27c2', 'sqsubseteq': u'\u2291', 'asymp': u'\u224d', 'smile': u'\u2323', 'supseteq': u'\u2287', 'sim': u'\u223c', 'neq': u'\u2260',
+ # Arrow symbols:
+ 'searrow': u'\u2198', 'updownarrow': u'\u2195', 'Uparrow': u'\u21d1', 'longleftrightarrow': u'\u27f7', 'Leftarrow': u'\u21d0', 'longmapsto': u'\u27fc', 'Longleftarrow': u'\u27f8', 'nearrow': u'\u2197', 'hookleftarrow': u'\u21a9', 'downarrow': u'\u2193', 'Leftrightarrow': u'\u21d4', 'longrightarrow': u'\u27f6', 'rightharpoondown': u'\u21c1', 'longleftarrow': u'\u27f5', 'rightarrow': u'\u2192', 'Updownarrow': u'\u21d5', 'rightharpoonup': u'\u21c0', 'Longleftrightarrow': u'\u27fa', 'leftarrow': u'\u2190', 'mapsto': u'\u21a6', 'nwarrow': u'\u2196', 'uparrow': u'\u2191', 'leftharpoonup': u'\u21bc', 'leftharpoondown': u'\u21bd', 'Downarrow': u'\u21d3', 'leftrightarrow': u'\u2194', 'Longrightarrow': u'\u27f9', 'swarrow': u'\u2199', 'hookrightarrow': u'\u21aa', 'Rightarrow': u'\u21d2',
+ # Miscellaneous symbols:
+ 'infty': u'\u221e', 'surd': u'\u221a', 'partial': u'\u2202', 'ddots': u'\u22f1', 'exists': u'\u2203', 'flat': u'\u266d', 'diamondsuit': u'\u2662', 'wp': u'\u2118', 'spadesuit': u'\u2660', 'Re': u'\u211c', 'vdots': u'\u22ee', 'aleph': u'\u2135', 'clubsuit': u'\u2663', 'sharp': u'\u266f', 'angle': u'\u2220', 'prime': u'\u2032', 'natural': u'\u266e', 'ell': u'\u2113', 'neg': u'\xac', 'top': u'\u22a4', 'nabla': u'\u2207', 'bot': u'\u22a5', 'heartsuit': u'\u2661', 'cdots': u'\u22ef', 'Im': u'\u2111', 'forall': u'\u2200', 'imath': u'\u0131', 'hbar': u'\u210f', 'emptyset': u'\u2205',
+ # Variable-sized symbols:
+ 'bigotimes': u'\u2a02', 'coprod': u'\u2210', 'int': u'\u222b', 'sum': u'\u2211', 'bigodot': u'\u2a00', 'bigcup': u'\u22c3', 'biguplus': u'\u2a04', 'bigcap': u'\u22c2', 'bigoplus': u'\u2a01', 'oint': u'\u222e', 'bigvee': u'\u22c1', 'bigwedge': u'\u22c0', 'prod': u'\u220f',
+ # Braces:
+ 'langle': u'\u2329', 'rangle': u'\u232A'}
+
+sumintprod = ''.join([special[symbol] for symbol in
+ ['sum', 'int', 'oint', 'prod']])
+
+functions = ['arccos', 'arcsin', 'arctan', 'arg', 'cos', 'cosh',
+ 'cot', 'coth', 'csc', 'deg', 'det', 'dim',
+ 'exp', 'gcd', 'hom', 'inf', 'ker', 'lg',
+ 'lim', 'liminf', 'limsup', 'ln', 'log', 'max',
+ 'min', 'Pr', 'sec', 'sin', 'sinh', 'sup',
+ 'tan', 'tanh',
+ 'injlim', 'varinjlim', 'varlimsup',
+ 'projlim', 'varliminf', 'varprojlim']
+
+
+def parse_latex_math(string, inline=True):
+ """parse_latex_math(string [,inline]) -> MathML-tree
+
+ Returns a MathML-tree parsed from string. inline=True is for
+ inline math and inline=False is for displayed math.
+
+ tree is the whole tree and node is the current element."""
+
+ # Normalize white-space:
+ string = ' '.join(string.split())
+
+ if inline:
+ node = mrow()
+ tree = math(node, inline=True)
+ else:
+ node = mtd()
+ tree = math(mtable(mtr(node)), inline=False)
+
+ while len(string) > 0:
+ n = len(string)
+ c = string[0]
+ skip = 1 # number of characters consumed
+ if n > 1:
+ c2 = string[1]
+ else:
+ c2 = ''
+## print n, string, c, c2, node.__class__.__name__
+ if c == ' ':
+ pass
+ elif c == '\\':
+ if c2 in '{}':
+ node = node.append(mo(c2))
+ skip = 2
+ elif c2 == ' ':
+ node = node.append(mspace())
+ skip = 2
+ elif c2.isalpha():
+ # We have a LaTeX-name:
+ i = 2
+ while i < n and string[i].isalpha():
+ i += 1
+ name = string[1:i]
+ node, skip = handle_keyword(name, node, string[i:])
+ skip += i
+ elif c2 == '\\':
+ # End of a row:
+ entry = mtd()
+ row = mtr(entry)
+ node.close().close().append(row)
+ node = entry
+ skip = 2
+ else:
+ raise SyntaxError('Syntax error: "%s%s"' % (c, c2))
+ elif c.isalpha():
+ node = node.append(mi(c))
+ elif c.isdigit():
+ node = node.append(mn(c))
+ elif c in "+-/()[]|=<>,.!'":
+ node = node.append(mo(c))
+ elif c == '_':
+ child = node.delete_child()
+ if isinstance(child, msup):
+ sub = msubsup(child.children, reversed=True)
+ elif isinstance(child, mo) and child.data in sumintprod:
+ sub = munder(child)
+ else:
+ sub = msub(child)
+ node.append(sub)
+ node = sub
+ elif c == '^':
+ child = node.delete_child()
+ if isinstance(child, msub):
+ sup = msubsup(child.children)
+ elif isinstance(child, mo) and child.data in sumintprod:
+ sup = mover(child)
+ elif (isinstance(child, munder) and
+ child.children[0].data in sumintprod):
+ sup = munderover(child.children)
+ else:
+ sup = msup(child)
+ node.append(sup)
+ node = sup
+ elif c == '{':
+ row = mrow()
+ node.append(row)
+ node = row
+ elif c == '}':
+ node = node.close()
+ elif c == '&':
+ entry = mtd()
+ node.close().append(entry)
+ node = entry
+ else:
+ raise SyntaxError('Illegal character: "%s"' % c)
+ string = string[skip:]
+ return tree
+
+
+mathbb = {'A': u'\U0001D538',
+ 'B': u'\U0001D539',
+ 'C': u'\u2102',
+ 'D': u'\U0001D53B',
+ 'E': u'\U0001D53C',
+ 'F': u'\U0001D53D',
+ 'G': u'\U0001D53E',
+ 'H': u'\u210D',
+ 'I': u'\U0001D540',
+ 'J': u'\U0001D541',
+ 'K': u'\U0001D542',
+ 'L': u'\U0001D543',
+ 'M': u'\U0001D544',
+ 'N': u'\u2115',
+ 'O': u'\U0001D546',
+ 'P': u'\u2119',
+ 'Q': u'\u211A',
+ 'R': u'\u211D',
+ 'S': u'\U0001D54A',
+ 'T': u'\U0001D54B',
+ 'U': u'\U0001D54C',
+ 'V': u'\U0001D54D',
+ 'W': u'\U0001D54E',
+ 'X': u'\U0001D54F',
+ 'Y': u'\U0001D550',
+ 'Z': u'\u2124'}
+
+negatables = {'=': u'\u2260',
+ '\in': u'\u2209',
+ '\equiv': u'\u2262'}
+
+
+def handle_keyword(name, node, string):
+ skip = 0
+ if len(string) > 0 and string[0] == ' ':
+ string = string[1:]
+ skip = 1
+ if name == 'begin':
+ if not string.startswith('{matrix}'):
+ raise SyntaxError('Expected "\begin{matrix}"!')
+ skip += 8
+ entry = mtd()
+ table = mtable(mtr(entry))
+ node.append(table)
+ node = entry
+ elif name == 'end':
+ if not string.startswith('{matrix}'):
+ raise SyntaxError('Expected "\end{matrix}"!')
+ skip += 8
+ node = node.close().close().close()
+ elif name == 'text':
+ if string[0] != '{':
+ raise SyntaxError('Expected "\text{...}"!')
+ i = string.find('}')
+ if i == -1:
+ raise SyntaxError('Expected "\text{...}"!')
+ node = node.append(mtext(string[1:i]))
+ skip += i + 1
+ elif name == 'sqrt':
+ sqrt = msqrt()
+ node.append(sqrt)
+ node = sqrt
+ elif name == 'frac':
+ frac = mfrac()
+ node.append(frac)
+ node = frac
+ elif name == 'left':
+ for par in ['(', '[', '|', '\\{', '\\langle', '.']:
+ if string.startswith(par):
+ break
+ else:
+ raise SyntaxError('Missing left-brace!')
+ fenced = mfenced(par)
+ node.append(fenced)
+ row = mrow()
+ fenced.append(row)
+ node = row
+ skip += len(par)
+ elif name == 'right':
+ for par in [')', ']', '|', '\\}', '\\rangle', '.']:
+ if string.startswith(par):
+ break
+ else:
+ raise SyntaxError('Missing right-brace!')
+ node = node.close()
+ node.closepar = par
+ node = node.close()
+ skip += len(par)
+ elif name == 'not':
+ for operator in negatables:
+ if string.startswith(operator):
+ break
+ else:
+ raise SyntaxError('Expected something to negate: "\\not ..."!')
+ node = node.append(mo(negatables[operator]))
+ skip += len(operator)
+ elif name == 'mathbf':
+ style = mstyle(nchildren=1, fontweight='bold')
+ node.append(style)
+ node = style
+ elif name == 'mathbb':
+ if string[0] != '{' or not string[1].isupper() or string[2] != '}':
+ raise SyntaxError('Expected something like "\mathbb{A}"!')
+ node = node.append(mi(mathbb[string[1]]))
+ skip += 3
+ elif name in greek:
+ node = node.append(mi(greek[name]))
+ elif name in Greek:
+ node = node.append(mo(Greek[name]))
+ elif name in special:
+ node = node.append(mo(special[name]))
+ elif name in functions:
+ node = node.append(mo(name))
+ else:
+ chr = over.get(name)
+ if chr is not None:
+ ovr = mover(mo(chr), reversed=True)
+ node.append(ovr)
+ node = ovr
+ else:
+ raise SyntaxError('Unknown LaTeX command: ' + name)
+
+ return node, skip
Added: trunk/py4science/examples/sphinx_template/sphinxext/mathpng.py
===================================================================
--- trunk/py4science/examples/sphinx_template/sphinxext/mathpng.py (rev 0)
+++ trunk/py4science/examples/sphinx_template/sphinxext/mathpng.py 2008-06-12 21:37:11 UTC (rev 5497)
@@ -0,0 +1,134 @@
+import os
+try:
+ from hashlib import md5
+except ImportError:
+ from md5 import md5
+
+from docutils import nodes
+from docutils.writers.html4css1 import HTMLTranslator
+from sphinx.latexwriter import LaTeXTranslator
+
+# Define LaTeX math node:
+class latex_math(nodes.General, nodes.Element):
+ pass
+
+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
+ return [node], []
+
+
+try:
+ from docutils.parsers.rst import Directive
+except ImportError:
+ # Register directive the old way:
+ from docutils.parsers.rst.directives import _directives
+ 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
+ return [node]
+ math_directive.arguments = None
+ math_directive.options = {}
+ math_directive.content = 1
+ _directives['math'] = math_directive
+else:
+ class math_directive(Directive):
+ has_content = True
+ def run(self):
+ latex = ' '.join(self.content)
+ node = latex_math(self.block_text)
+ node['latex'] = latex
+ return [node]
+ from docutils.parsers.rst import directives
+ directives.register_directive('math', math_directive)
+
+def setup(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
+ HTMLTranslator.visit_latex_math = visit_latex_math_html
+ HTMLTranslator.depart_latex_math = depart_latex_math_html
+
+ # 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
+ LaTeXTranslator.visit_latex_math = visit_latex_math_latex
+ LaTeXTranslator.depart_latex_math = depart_latex_math_latex
+
+from os.path import isfile
+
+# This calls out to LaTeX to render the expression
+def latex2png(latex, name):
+ f = open('math.tex', 'w')
+ f.write(r"""\documentclass[12pt]{article}
+ \pagestyle{empty}
+ \begin{document}""")
+ if inline:
+ f.write('$%s$' % latex)
+ else:
+ f.write(r'\[ %s \]' % latex)
+ f.write('\end{document}')
+ f.close()
+ os.system('latex --interaction=nonstopmode math.tex > /dev/null')
+ os.system('dvipng -bgTransparent -Ttight --noghostscript -l10 ' +
+ '-o %s math.dvi > /dev/null' % name)
+
+
+from matplotlib import rcParams
+from matplotlib.mathtext import MathTextParser
+rcParams['mathtext.fontset'] = 'cm'
+mathtext_parser = MathTextParser("Bitmap")
+
+
+# This uses mathtext to render the expression
+def latex2png(latex, filename):
+ if os.path.exists(filename):
+ return
+ mathtext_parser.to_png(filename, "$%s$" % latex, dpi=120)
+
+
+# LaTeX to HTML translation stuff:
+def latex2html(node, source):
+ inline = isinstance(node.parent, nodes.TextElement)
+ latex = node['latex']
+ print latex.encode("ascii", "backslashreplace")
+ name = 'math-%s' % md5(latex).hexdigest()[-10:]
+ dest = '_static/%s.png' % name
+ if not isfile(dest):
+ latex2png(latex, dest)
+
+ path = '_static'
+ count = source.split('/doc/')[-1].count('/')
+ for i in range(count):
+ if os.path.exists(path): break
+ path = '../'+path
+ path = '../'+path #specifically added for matplotlib
+ if inline and '_' in latex:
+ align = 'align="absmiddle" '
+ else:
+ align = ''
+ if inline:
+ cls = ''
+ else:
+ cls = 'class="center" '
+ return '<img src="%s/%s.png" %s%s/>' % (path, name, align, cls)
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-06-12 20:52:00
|
Revision: 5496
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5496&view=rev
Author: jswhit
Date: 2008-06-12 13:51:59 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
more restifiying docstrings
Modified Paths:
--------------
trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py
Modified: trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py
===================================================================
--- trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py 2008-06-12 20:01:24 UTC (rev 5495)
+++ trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py 2008-06-12 20:51:59 UTC (rev 5496)
@@ -1,20 +1,20 @@
"""
Module for plotting data on maps with matplotlib.
-Contains the Basemap class (which does most of the
+Contains the :class:`Basemap` class (which does most of the
heavy lifting), and the following functions:
-NetCDFFile: Read local and remote NetCDF datasets.
+:func:`NetCDFFile`: Read local and remote NetCDF datasets.
-interp: bilinear interpolation between rectilinear grids.
+:func:`interp`: bilinear interpolation between rectilinear grids.
-shiftgrid: shifts global lat/lon grids east or west.
+:func:`shiftgrid`: shifts global lat/lon grids east or west.
-addcyclic: Add cyclic (wraparound) point in longitude.
+:func:`addcyclic`: Add cyclic (wraparound) point in longitude.
-num2date: convert from a numeric time value to a datetime object.
+:func:`num2date`: convert from a numeric time value to a datetime object.
-date2num: convert from a datetime object to a numeric time value.
+:func:`date2num`: convert from a datetime object to a numeric time value.
"""
from matplotlib import __version__ as _matplotlib_version
from matplotlib.cbook import is_scalar, dedent
@@ -738,16 +738,16 @@
"""
Calling a Basemap class instance with the arguments lon, lat will
convert lon/lat (in degrees) to x/y native map projection
- coordinates (in meters). If optional keyword 'inverse' is
- True (default is False), the inverse transformation from x/y
+ coordinates (in meters). If optional keyword ``inverse`` is
+ ``True11 (default is ``False``), the inverse transformation from x/y
to lon/lat is performed.
- For cylindrical equidistant projection ('cyl'), this
+ For cylindrical equidistant projection (``cyl``), this
does nothing (i.e. x,y == lon,lat).
For non-cylindrical projections, the inverse transformation
always returns longitudes between -180 and 180 degrees. For
- cylindrical projections (self.projection == 'cyl','mill' or 'merc')
+ cylindrical projections (self.projection == ``cyl``,``mill`` or ``merc``)
the inverse transformation will return longitudes between
self.llcrnrlon and self.llcrnrlat.
@@ -760,7 +760,7 @@
return arrays of shape (ny,nx) containing lon,lat coordinates of
an equally spaced native projection grid.
- if returnxy = True, the x,y values of the grid are returned also.
+ if ``returnxy = True``, the x,y values of the grid are returned also.
"""
return self.projtran.makegrid(nx,ny,returnxy=returnxy)
@@ -1092,20 +1092,21 @@
draw boundary around map projection region, optionally
filling interior of region.
- linewidth - line width for boundary (default 1.)
+ ============== ====================================================
+ Keyword Description
+ ============== ====================================================
+ linewidth line width for boundary (default 1.)
+ color color of boundary line (default black)
+ fill_color fill the map region background with this
+ color (default is no fill or fill with axis
+ background color).
+ zorder sets the zorder for filling map background
+ (default 0).
+ ax axes instance to use
+ (default None, use default axes instance).
+ ============== ====================================================
- color - color of boundary line (default black)
-
- fill_color - fill the map region background with this
- color (default is no fill or fill with axis background color).
-
- zorder - sets the zorder for filling map background
- (default 0).
-
- ax - axes instance to use (default None, use default axes
- instance).
-
- returns PatchCollection representing map boundary.
+ returns matplotlib.collections.PatchCollection representing map boundary.
"""
# get current axes instance (if none specified).
if ax is None and self.ax is None:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-12 20:01:25
|
Revision: 5495
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5495&view=rev
Author: jdh2358
Date: 2008-06-12 13:01:24 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
revereted to manual array data fill in ft2font.as_array
Modified Paths:
--------------
trunk/matplotlib/Makefile
trunk/matplotlib/src/ft2font.cpp
Modified: trunk/matplotlib/Makefile
===================================================================
--- trunk/matplotlib/Makefile 2008-06-12 19:48:23 UTC (rev 5494)
+++ trunk/matplotlib/Makefile 2008-06-12 20:01:24 UTC (rev 5495)
@@ -32,4 +32,14 @@
CFLAGS="-Os -arch i386 -arch ppc" LDFLAGS="-Os -arch i386 -arch ppc" python setup.py build
+jdh_doc_snapshot:
+ svn up;\
+ python setup.py install --prefix=~/dev;\
+ cd doc;\
+ rm -rf build;\
+ python make.py html;\
+ python make.py sf
+
+
+
Modified: trunk/matplotlib/src/ft2font.cpp
===================================================================
--- trunk/matplotlib/src/ft2font.cpp 2008-06-12 19:48:23 UTC (rev 5494)
+++ trunk/matplotlib/src/ft2font.cpp 2008-06-12 20:01:24 UTC (rev 5495)
@@ -270,10 +270,10 @@
dimensions[1] = get_width(); //numcols
- PyArrayObject *A = (PyArrayObject *) PyArray_SimpleNewFromData(2, dimensions, PyArray_UBYTE, _buffer);
+ //PyArrayObject *A = (PyArrayObject *) PyArray_SimpleNewFromData(2, dimensions, PyArray_UBYTE, _buffer);
- /*
+
PyArrayObject *A = (PyArrayObject *) PyArray_FromDims(2, dimensions, PyArray_UBYTE);
@@ -284,8 +284,8 @@
while (src != src_end) {
*dst++ = *src++;
}
- */
+
return Py::asObject((PyObject*)A);
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-12 19:48:48
|
Revision: 5494
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5494&view=rev
Author: jdh2358
Date: 2008-06-12 12:48:23 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
applied stand setinitialsize fix
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backends/backend_wx.py
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_wx.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_wx.py 2008-06-12 19:35:41 UTC (rev 5493)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_wx.py 2008-06-12 19:48:23 UTC (rev 5494)
@@ -678,6 +678,17 @@
h = int(math.ceil(h))
wx.Panel.__init__(self, parent, id, size=wx.Size(w, h))
+
+ def do_nothing(*args, **kwargs):
+ warnings.warn('could not find a setinitialsize function for backend_wx; please report your wxpython version=%s to the matplotlib developers list'%backend_version)
+ pass
+
+ # try to find the set size func across wx versions
+ try:
+ getattr(self, 'SetInitialSize')
+ except AttributeError:
+ self.SetInitialSize = getattr(self, 'SetBestFittingSize', do_nothing)
+
# Create the drawing bitmap
self.bitmap =wx.EmptyBitmap(w, h)
DEBUG_MSG("__init__() - bitmap w:%d h:%d" % (w,h), 2, self)
@@ -1234,15 +1245,7 @@
statbar = StatusBarWx(self)
self.SetStatusBar(statbar)
self.canvas = self.get_canvas(fig)
-
- def do_nothing(*args, **kwargs):
- warnings.warn('could not find a SetSizeFunc for backend_wx; please report your wxpython version=%s to the matplotlib developers list'%backend_version)
- pass
-
- # try to find the set size func across wx versions
- self.SetSizeFunc = getattr(self.canvas, 'SetInitialSize',
- getattr(self.canvas, 'SetBestFittingSize', do_nothing))
- self.SetSizeFunc(wx.Size(fig.bbox.width, fig.bbox.height))
+ self.canvas.SetInitialSize(wx.Size(fig.bbox.width, fig.bbox.height))
self.sizer =wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND)
# By adding toolbar in sizer, we are able to put it at the bottom
@@ -1363,7 +1366,7 @@
def resize(self, width, height):
'Set the canvas size in pixels'
- self.canvas.SetSizeFunc(wx.Size(width, height))
+ self.canvas.SetInitialSize(wx.Size(width, height))
self.window.GetSizer().Fit(self.window)
# Identifiers for toolbar controls - images_wx contains bitmaps for the images
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mme...@us...> - 2008-06-12 19:35:44
|
Revision: 5493
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5493&view=rev
Author: mmetz_bn
Date: 2008-06-12 12:35:41 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
avoid accessing private member (was introduced with double-zoom patch)
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/backend_bases.py
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-06-12 19:30:00 UTC (rev 5492)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-06-12 19:35:41 UTC (rev 5493)
@@ -5653,7 +5653,15 @@
ax2.xaxis.set_label_position('top')
self.xaxis.tick_bottom()
return ax2
+
+ def get_shared_x_axes(self):
+ 'Return a copy of the shared axes Grouper object for x axes'
+ return self._shared_x_axes
+ def get_shared_y_axes(self):
+ 'Return a copy of the shared axes Grouper object for y axes'
+ return self._shared_y_axes
+
#### Data analysis
def hist(self, x, bins=10, range=None, normed=False, cumulative=False,
@@ -5662,8 +5670,8 @@
"""
call signature::
- hist(x, bins=10, normed=False, cumulative=False,
- bottom=None, histtype='bar', align='edge',
+ hist(x, bins=10, range=None, normed=False, cumulative=False,
+ bottom=None, histtype='bar', align='mid',
orientation='vertical', rwidth=None, log=False, **kwargs)
Compute the histogram of x. The return value is (n, bins, patches) or
@@ -5673,7 +5681,6 @@
Keyword arguments:
bins:
-
either an integer number of bins or a sequence giving the
bins. x are the data to be binned. x can be an array or a
2D array with multiple data in its columns. Note, if bins
@@ -5884,8 +5891,8 @@
raise ValueError, 'invalid orientation: %s' % orientation
elif histtype.startswith('step'):
- x = np.zeros( 2*len(bins), np.float_ )
- y = np.zeros( 2*len(bins), np.float_ )
+ x = np.zeros( 2*len(bins), np.float )
+ y = np.zeros( 2*len(bins), np.float )
x[0::2], x[1::2] = bins, bins
Modified: trunk/matplotlib/lib/matplotlib/backend_bases.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-06-12 19:30:00 UTC (rev 5492)
+++ trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-06-12 19:35:41 UTC (rev 5493)
@@ -1767,8 +1767,8 @@
twinx, twiny = False, False
if last_a:
for la in last_a:
- if a._shared_x_axes.joined(a,la): twinx=True
- if a._shared_y_axes.joined(a,la): twiny=True
+ if a.get_shared_x_axes().joined(a,la): twinx=True
+ if a.get_shared_y_axes().joined(a,la): twiny=True
last_a.append(a)
if twinx:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2008-06-12 19:30:07
|
Revision: 5492
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5492&view=rev
Author: efiring
Date: 2008-06-12 12:30:00 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
Some tweaks to coding_guide.rst.
Modified Paths:
--------------
trunk/matplotlib/doc/devel/coding_guide.rst
Modified: trunk/matplotlib/doc/devel/coding_guide.rst
===================================================================
--- trunk/matplotlib/doc/devel/coding_guide.rst 2008-06-12 19:15:17 UTC (rev 5491)
+++ trunk/matplotlib/doc/devel/coding_guide.rst 2008-06-12 19:30:00 UTC (rev 5492)
@@ -1,431 +1,424 @@
-.. _coding-guide:
-
-************
-Coding guide
-************
-
-.. _version-control:
-
-Version control
-===============
-
-svn checkouts
--------------
-
-Checking out everything in the trunk (matplotlib and toolkits)::
-
- svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk \
- matplotlib --username=youruser --password=yourpass
-
-Checking out the main source::
-
- svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/\
- matplotlib mpl --username=youruser --password=yourpass
-
-Branch checkouts, eg the maintenance branch::
-
- svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/\
- v0_91_maint mpl91 --username=youruser --password=yourpass
-
-Committing changes
-------------------
-
-When committing changes to matplotlib, there are a few things to bear
-in mind.
-
-* if your changes are non-trivial, please make an entry in the
- :file:`CHANGELOG`
-
-* if you change the API, please document it in :file:`API_CHANGES`,
- and consider posting to `mpl-devel
- <http://lists.sourceforge.net/mailman/listinfo/matplotlib-devel>`_
-
-* Are your changes python2.4 compatible? We still support 2.4, so
- avoid features new to 2.5
-
-* Can you pass :file:`examples/tests/backend_driver.py`? This is our
- poor man's unit test.
-
-* If you have altered extension code, do you pass
- :file:`unit/memleak_hawaii.py`?
-
-* if you have added new files or directories, or reorganized existing
- ones, are the new files included in the match patterns in
- :file:`MANIFEST.in`. This file determines what goes into the source
- distribution of the mpl build.
-
-* Keep the maintenance branch and trunk in sync where it makes sense.
- If there is a bug on both that needs fixing, use `svnmerge.py
- <http://www.orcaware.com/svn/wiki/Svnmerge.py>`_ to keep them in
- sync. The basic procedure is:
-
- * install ``svnmerge.py`` in your PATH::
-
- > wget http://svn.collab.net/repos/svn/trunk/contrib/client-side/\
- svnmerge/svnmerge.py
-
- * get a svn copy of the maintenance branch and the trunk (see above)
-
- * Michael advises making the change on the branch and committing
- it. Make sure you svn upped on the trunk and have no local
- modifications, and then from the svn trunk do::
-
- > svnmerge.py merge
-
- If you wish to merge only specific revisions (in an unusual
- situation), do::
-
- > svnmerge.py merge -rNNN1-NNN2
-
- where the ``NNN`` are the revision numbers. Ranges are also
- acceptable.
-
- The merge may have found some conflicts (code that must be
- manually resolved). Correct those conflicts, build matplotlib and
- test your choices. If you have resolved any conflicts, you can
- let svn clean up the conflict files for you::
-
- > svn -R resolved .
-
- ``svnmerge.py`` automatically creates a file containing the commit
- messages, so you are ready to make the commit::
-
- > svn commit -F svnmerge-commit-message.txt
-
-
-.. _style-guide:
-
-Style guide
-===========
-
-Importing and name spaces
--------------------------
-
-For `numpy <http://www.numpy.org>`_, use::
-
- import numpy as np
- a = np.array([1,2,3])
-
-For masked arrays, use::
-
- import numpy.ma as ma
-
-For matplotlib main module, use::
-
- import matplotlib as mpl
- mpl.rcParams['xtick.major.pad'] = 6
-
-For matplotlib modules (or any other modules), use::
-
- import matplotlib.cbook as cbook
-
- if cbook.iterable(z):
- pass
-
-We prefer this over the equivalent ``from matplotlib import cbook``
-because the latter is ambiguous whether ``cbook`` is a module or a
-function to the new developer. The former makes it explicit that you
-are importing a module or package. There are some modules whose names
-may be ambiguous in the context of local variables, eg
-:mod:`matplotlib.lines` or :mod:`matplotlib.colors`. When you want to
-disambiguate, use the prefix 'm' with the ``import some.thing as
-mthing`` syntax, eg::
-
- import matplotlib.lines as mlines
- import matplotlib.transforms as transforms # OK
- import matplotlib.transforms as mtransforms # OK, if you want to disambiguate
- import matplotlib.transforms as mtrans # OK, if you want to abbreviate
-
-Naming, spacing, and formatting conventions
--------------------------------------------
-
-In general, we want to hew as closely as possible to the standard
-coding guidelines for python written by Guido in `PEP 0008
-<http://www.python.org/dev/peps/pep-0008>`_, though we do not do this
-throughout.
-
-* functions and class methods: ``lower`` or
- ``lower_underscore_separated``
-
-* attributes and variables: ``lower`` or ``lowerUpper``
-
-* classes: ``Upper`` or ``MixedCase``
-
-Prefer the shortest names that are still readable.
-
-Also, use an editor that does not put tabs in files. Four spaces
-should be used for indentation everywhere and if there is a file with
-tabs or more or less spaces it is a bug -- please fix it. There are
-some tools to help automate this checking, such as `tabnanny
-<http://effbot.org/librarybook/tabnanny.htm>`_, which is part of the
-standard library::
-
- In [3]: cd /home/titan/johnh/mpl/lib/matplotlib/
- /home/titan/johnh/python/svn/matplotlib.trunk/matplotlib/lib/matplotlib
-
- In [4]: import tabnanny
-
- In [5]: tabnanny.check('axis.py')
-
-There is also `reindent.py
-<http://svn.python.org/projects/doctools/trunk/utils/reindent.py>`_
-which can be used to automatically change python files to use 4-space
-indents with no hard tab characters.
-
-Keep docstrings uniformly indented as in the example below, with
-nothing to the left of the triple quotes. The
-:func:`matplotlib.cbook.dedent` function is needed to remove excess
-indentation only if something will be interpolated into the docstring,
-again as in the example above.
-
-Limit line length to 80 characters. If a logical line needs to be
-longer, use parentheses to break it; do not use an escaped newline.
-It may be preferable to use a temporary variable to replace a single
-long line with two shorter and more readable lines.
-
-Please do not commit lines with trailing white space, as it causes
-noise in svn diffs. Tell your editor to strip whitespace from line
-ends when saving a file. If you are an emacs user, the following in
-your ``.emacs`` will cause emacs to strip trailing white space upon
-saving for python, C and C++:
-
-.. code-block:: cl
-
- ; and similarly for c++-mode-hook and c-mode-hook
- (add-hook 'python-mode-hook
- (lambda ()
- (add-hook 'write-file-functions 'delete-trailing-whitespace)))
-
-for older versions of emacs (emacs<22) you need to do:
-
-.. code-block:: cl
-
- (add-hook 'python-mode-hook
- (lambda ()
- (add-hook 'local-write-file-hooks 'delete-trailing-whitespace)))
-
-Keyword argument processing
----------------------------
-
-Matplotlib makes extensive use of ``**kwargs`` for pass through
-customizations from one function to another. A typical example is in
-:func:`matplotlib.pylab.text`. The definition of the pylab text
-function is a simple pass-through to
-:meth:`matplotlib.axes.Axes.text`::
-
- # in pylab.py
- def text(*args, **kwargs):
- ret = gca().text(*args, **kwargs)
- draw_if_interactive()
- return ret
-
-:meth:`~matplotlib.axes.Axes.text` in simplified form looks like this,
-i.e., it just passes them on to :meth:`matplotlib.text.Text.__init__`::
-
- # in axes.py
- def text(self, x, y, s, fontdict=None, withdash=False, **kwargs):
- t = Text(x=x, y=y, text=s, **kwargs)
-
-and :meth:`~matplotlib.text.Text.__init__` (again with liberties for
-illustration) just passes them on to the
-:meth:`matplotlib.artist.Artist.update` method::
-
- # in text.py
- def __init__(self, x=0, y=0, text='', **kwargs):
- Artist.__init__(self)
- self.update(kwargs)
-
-``update`` does the work looking for methods named like
-``set_property`` if ``property`` is a keyword argument. I.e., no one
-looks at the keywords, they just get passed through the API to the
-artist constructor which looks for suitably named methods and calls
-them with the value.
-
-As a general rule, the use of ``**kwargs`` should be reserved for
-pass-through keyword arguments, as in the example above. If all the
-keyword args to be used in the function being declared, and not passed
-on, use the key/value keyword args in the function definition rather
-than the ``**kwargs`` idiom.
-
-In some cases, you may want to consume some keys in the local
-function, and let others pass through. You can ``pop`` the ones to be
-used locally and pass on the rest. For example, in
-:meth:`~matplotlib.axes.Axes.plot`, ``scalex`` and ``scaley`` are
-local arguments and the rest are passed on as
-:meth:`~matplotlib.lines.Line2D` keyword arguments::
-
- # in axes.py
- def plot(self, *args, **kwargs):
- scalex = kwargs.pop('scalex', True)
- scaley = kwargs.pop('scaley', True)
- if not self._hold: self.cla()
- lines = []
- for line in self._get_lines(*args, **kwargs):
- self.add_line(line)
- lines.append(line)
-
-Note there is a use case when ``kwargs`` are meant to be used locally
-in the function (not passed on), but you still need the ``**kwargs``
-idiom. That is when you want to use ``*args`` to allow variable
-numbers of non-keyword args. In this case, python will not allow you
-to use named keyword args after the ``*args`` usage, so you will be
-forced to use ``**kwargs``. An example is
-:meth:`matplotlib.contour.ContourLabeler.clabel`::
-
- # in contour.py
- def clabel(self, *args, **kwargs):
- fontsize = kwargs.get('fontsize', None)
- inline = kwargs.get('inline', 1)
- self.fmt = kwargs.get('fmt', '%1.3f')
- colors = kwargs.get('colors', None)
- if len(args) == 0:
- levels = self.levels
- indices = range(len(self.levels))
- elif len(args) == 1:
- ...etc...
-
-.. _docstrings:
-
-Documentation and docstrings
-============================
-
-matplotlib uses artist introspection of docstrings to support
-properties. All properties that you want to support through ``setp``
-and ``getp`` should have a ``set_property`` and ``get_property``
-method in the :class:`~matplotlib.artist.Artist` class. Yes, this is
-not ideal given python properties or enthought traits, but it is a
-historical legacy for now. The setter methods use the docstring with
-the ACCEPTS token to indicate the type of argument the method accepts.
-Eg. in :class:`matplotlib.lines.Line2D`::
-
- # in lines.py
- def set_linestyle(self, linestyle):
- """
- Set the linestyle of the line
-
- ACCEPTS: [ '-' | '--' | '-.' | ':' | 'steps' | 'None' | ' ' | '' ]
- """
-
-Since matplotlib uses a lot of pass through ``kwargs``, eg. in every
-function that creates a line (:func:`~matplotlib.pyplot.plot`,
-:func:`~matplotlib.pyplot.semilogx`,
-:func:`~matplotlib.pyplot.semilogy`, etc...), it can be difficult for
-the new user to know which ``kwargs`` are supported. matplotlib uses
-a docstring interpolation scheme to support documentation of every
-function that takes a ``**kwargs``. The requirements are:
-
-1. single point of configuration so changes to the properties don't
- require multiple docstring edits.
-
-2. as automated as possible so that as properties change the docs
- are updated automagically.
-
-The functions :attr:`matplotlib.artist.kwdocd` and
-:func:`matplotlib.artist.kwdoc` to facilitate this. They combine
-python string interpolation in the docstring with the matplotlib
-artist introspection facility that underlies ``setp`` and ``getp``.
-The ``kwdocd`` is a single dictionary that maps class name to a
-docstring of ``kwargs``. Here is an example from
-:mod:`matplotlib.lines`::
-
- # in lines.py
- artist.kwdocd['Line2D'] = artist.kwdoc(Line2D)
-
-Then in any function accepting :class:`~matplotlib.lines.Line2D`
-passthrough ``kwargs``, eg. :meth:`matplotlib.axes.Axes.plot`::
-
- # in axes.py
- def plot(self, *args, **kwargs):
- """
- Some stuff omitted
-
- The kwargs are Line2D properties:
- %(Line2D)s
-
- kwargs scalex and scaley, if defined, are passed on
- to autoscale_view to determine whether the x and y axes are
- autoscaled; default True. See Axes.autoscale_view for more
- information
- """
- pass
- plot.__doc__ = cbook.dedent(plot.__doc__) % artist.kwdocd
-
-Note there is a problem for :class:`~matplotlib.artist.Artist`
-``__init__`` methods, eg. :meth:`matplotlib.patches.Patch.__init__`,
-which supports ``Patch`` ``kwargs``, since the artist inspector cannot
-work until the class is fully defined and we can't modify the
-``Patch.__init__.__doc__`` docstring outside the class definition.
-There are some some manual hacks in this case which violates theqq
-"single entry point" requirement above -- see the
-``artist.kwdocd['Patch']`` setting in :mod:`matplotlib.patches`.
-
-
-.. _licenses:
-
-Licenses
-========
-
-Matplotlib only uses BSD compatible code. If you bring in code from
-another project make sure it has a PSF, BSD, MIT or compatible license
-(see the Open Source Initiative `licenses page
-<http://www.opensource.org/licenses>`_ for details on individual
-licenses). If it doesn't, you may consider contacting the author and
-asking them to relicense it. GPL and LGPL code are not acceptable in
-the main code base, though we are considering an alternative way of
-distributing L/GPL code through an separate channel, possibly a
-toolkit. If you include code, make sure you include a copy of that
-code's license in the license directory if the code's license requires
-you to distribute the license with it. Non-BSD compatible licenses
-are acceptable in matplotlib toolkits (eg basemap), but make sure you
-clearly state the licenses you are using.
-
-Why BSD compatible?
--------------------
-
-The two dominant license variants in the wild are GPL-style and
-BSD-style. There are countless other licenses that place specific
-restrictions on code reuse, but there is an important different to be
-considered in the GPL and BSD variants. The best known and perhaps
-most widely used license is the GPL, which in addition to granting you
-full rights to the source code including redistribution, carries with
-it an extra obligation. If you use GPL code in your own code, or link
-with it, your product must be released under a GPL compatible
-license. I.e., you are required to give the source code to other
-people and give them the right to redistribute it as well. Many of the
-most famous and widely used open source projects are released under
-the GPL, including sagemath, linux, gcc and emacs.
-
-The second major class are the BSD-style licenses (which includes MIT
-and the python PSF license). These basically allow you to do whatever
-you want with the code: ignore it, include it in your own open source
-project, include it in your proprietary product, sell it,
-whatever. python itself is released under a BSD compatible license, in
-the sense that, quoting from the PSF license page::
-
- There is no GPL-like "copyleft" restriction. Distributing
- binary-only versions of Python, modified or not, is allowed. There
- is no requirement to release any of your source code. You can also
- write extension modules for Python and provide them only in binary
- form.
-
-Famous projects released under a BSD-style license in the permissive
-sense of the last paragraph are the BSD operating system, python and
-TeX.
-
-There are two primary reasons why early matplotlib developers selected
-a BSD compatible license. We wanted to attract as many users and
-developers as possible, and many software companies will not use GPL code
-in software they plan to distribute, even those that are highly
-committed to open source development, such as `enthought
-<http://enthought.com>`_, out of legitimate concern that use of the
-GPL will "infect" their code base by its viral nature. In effect, they
-want to retain the right to release some proprietary code. Companies,
-and institutions in general, who use matplotlib often make significant
-contributions, since they have the resources to get a job done, even a
-boring one, if they need it in their code. Two of the matplotlib
-backends (FLTK and WX) were contributed by private companies.
-
-The other reason is licensing compatibility with the other python
-extensions for scientific computing: ipython, numpy, scipy, the
-enthought tool suite and python itself are all distributed under BSD
-compatible licenses.
+.. _coding-guide:
+
+************
+Coding guide
+************
+
+.. _version-control:
+
+Version control
+===============
+
+svn checkouts
+-------------
+
+Checking out everything in the trunk (matplotlib and toolkits)::
+
+ svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk \
+ matplotlib --username=youruser --password=yourpass
+
+Checking out the main source::
+
+ svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/\
+ matplotlib mpl --username=youruser --password=yourpass
+
+Branch checkouts, eg the maintenance branch::
+
+ svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/\
+ v0_91_maint mpl91 --username=youruser --password=yourpass
+
+Committing changes
+------------------
+
+When committing changes to matplotlib, there are a few things to bear
+in mind.
+
+* if your changes are non-trivial, please make an entry in the
+ :file:`CHANGELOG`
+
+* if you change the API, please document it in :file:`API_CHANGES`,
+ and consider posting to `matplotlib-devel
+ <http://lists.sourceforge.net/mailman/listinfo/matplotlib-devel>`_
+
+* Are your changes python2.4 compatible? We still support 2.4, so
+ avoid features new to 2.5
+
+* Can you pass :file:`examples/tests/backend_driver.py`? This is our
+ poor man's unit test.
+
+* If you have altered extension code, do you pass
+ :file:`unit/memleak_hawaii.py`?
+
+* if you have added new files or directories, or reorganized existing
+ ones, are the new files included in the match patterns in
+ :file:`MANIFEST.in`. This file determines what goes into the source
+ distribution of the mpl build.
+
+* Keep the maintenance branch and trunk in sync where it makes sense.
+ If there is a bug on both that needs fixing, use `svnmerge.py
+ <http://www.orcaware.com/svn/wiki/Svnmerge.py>`_ to keep them in
+ sync. The basic procedure is:
+
+ * install ``svnmerge.py`` in your PATH::
+
+ > wget http://svn.collab.net/repos/svn/trunk/contrib/client-side/\
+ svnmerge/svnmerge.py
+
+ * get a svn copy of the maintenance branch and the trunk (see above)
+
+ * Michael advises making the change on the branch and committing
+ it. Make sure you svn upped on the trunk and have no local
+ modifications, and then from the svn trunk do::
+
+ > svnmerge.py merge
+
+ If you wish to merge only specific revisions (in an unusual
+ situation), do::
+
+ > svnmerge.py merge -rNNN1-NNN2
+
+ where the ``NNN`` are the revision numbers. Ranges are also
+ acceptable.
+
+ The merge may have found some conflicts (code that must be
+ manually resolved). Correct those conflicts, build matplotlib and
+ test your choices. If you have resolved any conflicts, you can
+ let svn clean up the conflict files for you::
+
+ > svn -R resolved .
+
+ ``svnmerge.py`` automatically creates a file containing the commit
+ messages, so you are ready to make the commit::
+
+ > svn commit -F svnmerge-commit-message.txt
+
+
+.. _style-guide:
+
+Style guide
+===========
+
+Importing and name spaces
+-------------------------
+
+For `numpy <http://www.numpy.org>`_, use::
+
+ import numpy as np
+ a = np.array([1,2,3])
+
+For masked arrays, use::
+
+ import numpy.ma as ma
+
+For matplotlib main module, use::
+
+ import matplotlib as mpl
+ mpl.rcParams['xtick.major.pad'] = 6
+
+For matplotlib modules (or any other modules), use::
+
+ import matplotlib.cbook as cbook
+
+ if cbook.iterable(z):
+ pass
+
+We prefer this over the equivalent ``from matplotlib import cbook``
+because the latter is ambiguous as to whether ``cbook`` is a module or a
+function. The former makes it explicit that you
+are importing a module or package. There are some modules with names
+that match commonly used local variable names, eg
+:mod:`matplotlib.lines` or :mod:`matplotlib.colors`. To avoid the clash,
+use the prefix 'm' with the ``import some.thing as
+mthing`` syntax, eg::
+
+ import matplotlib.lines as mlines
+ import matplotlib.transforms as transforms # OK
+ import matplotlib.transforms as mtransforms # OK, if you want to disambiguate
+ import matplotlib.transforms as mtrans # OK, if you want to abbreviate
+
+Naming, spacing, and formatting conventions
+-------------------------------------------
+
+In general, we want to hew as closely as possible to the standard
+coding guidelines for python written by Guido in `PEP 0008
+<http://www.python.org/dev/peps/pep-0008>`_, though we do not do this
+throughout.
+
+* functions and class methods: ``lower`` or
+ ``lower_underscore_separated``
+
+* attributes and variables: ``lower`` or ``lowerUpper``
+
+* classes: ``Upper`` or ``MixedCase``
+
+Prefer the shortest names that are still readable.
+
+Configure your editor to use spaces, not hard tabs. The standard
+indentation unit is always four spaces;
+if there is a file with
+tabs or a different number of spaces it is a bug -- please fix it.
+To detect and fix these and other whitespace errors (see below),
+use `reindent.py
+<http://svn.python.org/projects/doctools/trunk/utils/reindent.py>`_ as
+a command-line script. Unless you are sure your editor always
+does the right thing, please use reindent.py before checking changes into
+svn.
+
+Keep docstrings_ uniformly indented as in the example below, with
+nothing to the left of the triple quotes. The
+:func:`matplotlib.cbook.dedent` function is needed to remove excess
+indentation only if something will be interpolated into the docstring,
+again as in the example below.
+
+Limit line length to 80 characters. If a logical line needs to be
+longer, use parentheses to break it; do not use an escaped newline.
+It may be preferable to use a temporary variable to replace a single
+long line with two shorter and more readable lines.
+
+Please do not commit lines with trailing white space, as it causes
+noise in svn diffs. Tell your editor to strip whitespace from line
+ends when saving a file. If you are an emacs user, the following in
+your ``.emacs`` will cause emacs to strip trailing white space upon
+saving for python, C and C++:
+
+.. code-block:: cl
+
+ ; and similarly for c++-mode-hook and c-mode-hook
+ (add-hook 'python-mode-hook
+ (lambda ()
+ (add-hook 'write-file-functions 'delete-trailing-whitespace)))
+
+for older versions of emacs (emacs<22) you need to do:
+
+.. code-block:: cl
+
+ (add-hook 'python-mode-hook
+ (lambda ()
+ (add-hook 'local-write-file-hooks 'delete-trailing-whitespace)))
+
+Keyword argument processing
+---------------------------
+
+Matplotlib makes extensive use of ``**kwargs`` for pass-through
+customizations from one function to another. A typical example is in
+:func:`matplotlib.pylab.text`. The definition of the pylab text
+function is a simple pass-through to
+:meth:`matplotlib.axes.Axes.text`::
+
+ # in pylab.py
+ def text(*args, **kwargs):
+ ret = gca().text(*args, **kwargs)
+ draw_if_interactive()
+ return ret
+
+:meth:`~matplotlib.axes.Axes.text` in simplified form looks like this,
+i.e., it just passes all ``args`` and ``kwargs`` on to
+:meth:`matplotlib.text.Text.__init__`::
+
+ # in axes.py
+ def text(self, x, y, s, fontdict=None, withdash=False, **kwargs):
+ t = Text(x=x, y=y, text=s, **kwargs)
+
+and :meth:`~matplotlib.text.Text.__init__` (again with liberties for
+illustration) just passes them on to the
+:meth:`matplotlib.artist.Artist.update` method::
+
+ # in text.py
+ def __init__(self, x=0, y=0, text='', **kwargs):
+ Artist.__init__(self)
+ self.update(kwargs)
+
+``update`` does the work looking for methods named like
+``set_property`` if ``property`` is a keyword argument. I.e., no one
+looks at the keywords, they just get passed through the API to the
+artist constructor which looks for suitably named methods and calls
+them with the value.
+
+As a general rule, the use of ``**kwargs`` should be reserved for
+pass-through keyword arguments, as in the example above. If all the
+keyword args are to be used in the function, and not passed
+on, use the key/value keyword args in the function definition rather
+than the ``**kwargs`` idiom.
+
+In some cases, you may want to consume some keys in the local
+function, and let others pass through. You can ``pop`` the ones to be
+used locally and pass on the rest. For example, in
+:meth:`~matplotlib.axes.Axes.plot`, ``scalex`` and ``scaley`` are
+local arguments and the rest are passed on as
+:meth:`~matplotlib.lines.Line2D` keyword arguments::
+
+ # in axes.py
+ def plot(self, *args, **kwargs):
+ scalex = kwargs.pop('scalex', True)
+ scaley = kwargs.pop('scaley', True)
+ if not self._hold: self.cla()
+ lines = []
+ for line in self._get_lines(*args, **kwargs):
+ self.add_line(line)
+ lines.append(line)
+
+Note: there is a use case when ``kwargs`` are meant to be used locally
+in the function (not passed on), but you still need the ``**kwargs``
+idiom. That is when you want to use ``*args`` to allow variable
+numbers of non-keyword args. In this case, python will not allow you
+to use named keyword args after the ``*args`` usage, so you will be
+forced to use ``**kwargs``. An example is
+:meth:`matplotlib.contour.ContourLabeler.clabel`::
+
+ # in contour.py
+ def clabel(self, *args, **kwargs):
+ fontsize = kwargs.get('fontsize', None)
+ inline = kwargs.get('inline', 1)
+ self.fmt = kwargs.get('fmt', '%1.3f')
+ colors = kwargs.get('colors', None)
+ if len(args) == 0:
+ levels = self.levels
+ indices = range(len(self.levels))
+ elif len(args) == 1:
+ ...etc...
+
+.. _docstrings:
+
+Documentation and docstrings
+============================
+
+Matplotlib uses artist introspection of docstrings to support
+properties. All properties that you want to support through ``setp``
+and ``getp`` should have a ``set_property`` and ``get_property``
+method in the :class:`~matplotlib.artist.Artist` class. Yes, this is
+not ideal given python properties or enthought traits, but it is a
+historical legacy for now. The setter methods use the docstring with
+the ACCEPTS token to indicate the type of argument the method accepts.
+Eg. in :class:`matplotlib.lines.Line2D`::
+
+ # in lines.py
+ def set_linestyle(self, linestyle):
+ """
+ Set the linestyle of the line
+
+ ACCEPTS: [ '-' | '--' | '-.' | ':' | 'steps' | 'None' | ' ' | '' ]
+ """
+
+Since matplotlib uses a lot of pass-through ``kwargs``, eg. in every
+function that creates a line (:func:`~matplotlib.pyplot.plot`,
+:func:`~matplotlib.pyplot.semilogx`,
+:func:`~matplotlib.pyplot.semilogy`, etc...), it can be difficult for
+the new user to know which ``kwargs`` are supported. Matplotlib uses
+a docstring interpolation scheme to support documentation of every
+function that takes a ``**kwargs``. The requirements are:
+
+1. single point of configuration so changes to the properties don't
+ require multiple docstring edits.
+
+2. as automated as possible so that as properties change, the docs
+ are updated automagically.
+
+The functions :attr:`matplotlib.artist.kwdocd` and
+:func:`matplotlib.artist.kwdoc` to facilitate this. They combine
+python string interpolation in the docstring with the matplotlib
+artist introspection facility that underlies ``setp`` and ``getp``.
+The ``kwdocd`` is a single dictionary that maps class name to a
+docstring of ``kwargs``. Here is an example from
+:mod:`matplotlib.lines`::
+
+ # in lines.py
+ artist.kwdocd['Line2D'] = artist.kwdoc(Line2D)
+
+Then in any function accepting :class:`~matplotlib.lines.Line2D`
+pass-through ``kwargs``, eg. :meth:`matplotlib.axes.Axes.plot`::
+
+ # in axes.py
+ def plot(self, *args, **kwargs):
+ """
+ Some stuff omitted
+
+ The kwargs are Line2D properties:
+ %(Line2D)s
+
+ kwargs scalex and scaley, if defined, are passed on
+ to autoscale_view to determine whether the x and y axes are
+ autoscaled; default True. See Axes.autoscale_view for more
+ information
+ """
+ pass
+ plot.__doc__ = cbook.dedent(plot.__doc__) % artist.kwdocd
+
+Note there is a problem for :class:`~matplotlib.artist.Artist`
+``__init__`` methods, eg. :meth:`matplotlib.patches.Patch.__init__`,
+which supports ``Patch`` ``kwargs``, since the artist inspector cannot
+work until the class is fully defined and we can't modify the
+``Patch.__init__.__doc__`` docstring outside the class definition.
+There are some some manual hacks in this case, violating the
+"single entry point" requirement above -- see the
+``artist.kwdocd['Patch']`` setting in :mod:`matplotlib.patches`.
+
+
+.. _licenses:
+
+Licenses
+========
+
+Matplotlib only uses BSD compatible code. If you bring in code from
+another project make sure it has a PSF, BSD, MIT or compatible license
+(see the Open Source Initiative `licenses page
+<http://www.opensource.org/licenses>`_ for details on individual
+licenses). If it doesn't, you may consider contacting the author and
+asking them to relicense it. GPL and LGPL code are not acceptable in
+the main code base, though we are considering an alternative way of
+distributing L/GPL code through an separate channel, possibly a
+toolkit. If you include code, make sure you include a copy of that
+code's license in the license directory if the code's license requires
+you to distribute the license with it. Non-BSD compatible licenses
+are acceptable in matplotlib toolkits (eg basemap), but make sure you
+clearly state the licenses you are using.
+
+Why BSD compatible?
+-------------------
+
+The two dominant license variants in the wild are GPL-style and
+BSD-style. There are countless other licenses that place specific
+restrictions on code reuse, but there is an important different to be
+considered in the GPL and BSD variants. The best known and perhaps
+most widely used license is the GPL, which in addition to granting you
+full rights to the source code including redistribution, carries with
+it an extra obligation. If you use GPL code in your own code, or link
+with it, your product must be released under a GPL compatible
+license. I.e., you are required to give the source code to other
+people and give them the right to redistribute it as well. Many of the
+most famous and widely used open source projects are released under
+the GPL, including sagemath, linux, gcc and emacs.
+
+The second major class are the BSD-style licenses (which includes MIT
+and the python PSF license). These basically allow you to do whatever
+you want with the code: ignore it, include it in your own open source
+project, include it in your proprietary product, sell it,
+whatever. python itself is released under a BSD compatible license, in
+the sense that, quoting from the PSF license page::
+
+ There is no GPL-like "copyleft" restriction. Distributing
+ binary-only versions of Python, modified or not, is allowed. There
+ is no requirement to release any of your source code. You can also
+ write extension modules for Python and provide them only in binary
+ form.
+
+Famous projects released under a BSD-style license in the permissive
+sense of the last paragraph are the BSD operating system, python and
+TeX.
+
+There are two primary reasons why early matplotlib developers selected
+a BSD compatible license. We wanted to attract as many users and
+developers as possible, and many software companies will not use GPL code
+in software they plan to distribute, even those that are highly
+committed to open source development, such as `enthought
+<http://enthought.com>`_, out of legitimate concern that use of the
+GPL will "infect" their code base by its viral nature. In effect, they
+want to retain the right to release some proprietary code. Companies,
+and institutions in general, who use matplotlib often make significant
+contributions, since they have the resources to get a job done, even a
+boring one, if they need it in their code. Two of the matplotlib
+backends (FLTK and WX) were contributed by private companies.
+
+The other reason is licensing compatibility with the other python
+extensions for scientific computing: ipython, numpy, scipy, the
+enthought tool suite and python itself are all distributed under BSD
+compatible licenses.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-12 19:15:34
|
Revision: 5491
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5491&view=rev
Author: jdh2358
Date: 2008-06-12 12:15:17 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
added array and png helper funcs to mathtext
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-06-12 19:14:21 UTC (rev 5490)
+++ trunk/matplotlib/CHANGELOG 2008-06-12 19:15:17 UTC (rev 5491)
@@ -2,7 +2,7 @@
return bitmap arrays or write pngs to make it easier to use
mathtext outside the context of an mpl figure. modified
the mathpng sphinxext to use the mathtext png save
- functionality
+ functionality - see examples/api/mathtext_asarray.py - JDH
2008-06-11 Use matplotlib.mathtext to render math expressions in
online docs - MGD
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-06-12 19:14:25
|
Revision: 5490
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5490&view=rev
Author: jdh2358
Date: 2008-06-12 12:14:21 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
added array and png helper funcs to mathtext
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/doc/sphinxext/mathpng.py
trunk/matplotlib/lib/matplotlib/mathtext.py
trunk/matplotlib/setupext.py
trunk/matplotlib/src/ft2font.cpp
trunk/matplotlib/src/ft2font.h
Added Paths:
-----------
trunk/matplotlib/examples/api/mathtext_asarray.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-06-12 18:05:16 UTC (rev 5489)
+++ trunk/matplotlib/CHANGELOG 2008-06-12 19:14:21 UTC (rev 5490)
@@ -1,3 +1,9 @@
+2008-06-12 Added some helper functions to the mathtext parser to
+ return bitmap arrays or write pngs to make it easier to use
+ mathtext outside the context of an mpl figure. modified
+ the mathpng sphinxext to use the mathtext png save
+ functionality
+
2008-06-11 Use matplotlib.mathtext to render math expressions in
online docs - MGD
Modified: trunk/matplotlib/doc/sphinxext/mathpng.py
===================================================================
--- trunk/matplotlib/doc/sphinxext/mathpng.py 2008-06-12 18:05:16 UTC (rev 5489)
+++ trunk/matplotlib/doc/sphinxext/mathpng.py 2008-06-12 19:14:21 UTC (rev 5490)
@@ -92,17 +92,20 @@
os.system('dvipng -bgTransparent -Ttight --noghostscript -l10 ' +
'-o %s math.dvi > /dev/null' % name)
+
+from matplotlib import rcParams
+from matplotlib.mathtext import MathTextParser
+rcParams['mathtext.fontset'] = 'cm'
+mathtext_parser = MathTextParser("Bitmap")
+
+
# This uses mathtext to render the expression
def latex2png(latex, filename):
- from matplotlib import rcParams
- from matplotlib import _png
- from matplotlib.mathtext import MathTextParser
- rcParams['mathtext.fontset'] = 'cm'
- mathtext_parser = MathTextParser("Bitmap")
- ftimage = mathtext_parser.parse("$%s$" % latex, 120)
- _png.write_png(ftimage.as_rgba_str(), ftimage.get_width(),
- ftimage.get_height(), filename)
+ if os.path.exists(filename):
+ return
+ mathtext_parser.to_png(filename, "$%s$" % latex, dpi=120)
+
# LaTeX to HTML translation stuff:
def latex2html(node, source):
inline = isinstance(node.parent, nodes.TextElement)
Added: trunk/matplotlib/examples/api/mathtext_asarray.py
===================================================================
--- trunk/matplotlib/examples/api/mathtext_asarray.py (rev 0)
+++ trunk/matplotlib/examples/api/mathtext_asarray.py 2008-06-12 19:14:21 UTC (rev 5490)
@@ -0,0 +1,19 @@
+"""
+Load a mathtext image as numpy array
+"""
+
+import numpy as np
+import matplotlib.mathtext as mathtext
+import matplotlib.pyplot as plt
+
+parser = mathtext.MathTextParser("Bitmap")
+
+parser.to_png('test2.png', r'$\left[\left\lfloor\frac{5}{\frac{\left(3\right)}{4}} y\right)\right]$', color='green', fontsize=14, dpi=100)
+
+
+rgba = parser.to_rgba(r'IQ: $\sigma_i=15$', color='blue', fontsize=20, dpi=200)
+
+fig = plt.figure()
+fig.figimage(rgba.astype(float)/255., 100, 100)
+
+plt.show()
Modified: trunk/matplotlib/lib/matplotlib/mathtext.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mathtext.py 2008-06-12 18:05:16 UTC (rev 5489)
+++ trunk/matplotlib/lib/matplotlib/mathtext.py 2008-06-12 19:14:21 UTC (rev 5490)
@@ -180,7 +180,7 @@
from warnings import warn
from numpy import inf, isinf
-
+import numpy as np
from matplotlib.pyparsing import Combine, Group, Optional, Forward, \
Literal, OneOrMore, ZeroOrMore, ParseException, Empty, \
ParseResults, Suppress, oneOf, StringEnd, ParseFatalException, \
@@ -197,6 +197,10 @@
latex_to_standard, tex2uni, latex_to_cmex, stix_virtual_fonts
from matplotlib import get_data_path, rcParams
+
+
+import matplotlib.colors as mcolors
+import matplotlib._png as _png
####################
@@ -2724,3 +2728,74 @@
font_output.mathtext_backend = None
return result
+
+ def to_mask(self, texstr, dpi=120, fontsize=14):
+ """
+ return an NxM uint8 alpha ubyte mask array of rasterized tex
+
+ ''texstr''
+ A valid mathtext string, eg r'IQ: $\sigma_i=15$'
+
+ ''dpi''
+ The dots-per-inch to render the text
+
+ ''fontsize''
+ The font size in points
+ """
+ assert(self._output=="bitmap")
+ prop = FontProperties(size=fontsize)
+ ftimage = self.parse(texstr, dpi=dpi, prop=prop)
+
+ x = ftimage.as_array()
+ return x
+
+ def to_rgba(self, texstr, color='black', dpi=120, fontsize=14):
+ """
+ return an NxMx4 RGBA array of ubyte rasterized tex
+
+ ''texstr''
+ A valid mathtext string, eg r'IQ: $\sigma_i=15$'
+
+ ''color''
+ A valid matplotlib color argument
+
+ ''dpi''
+ The dots-per-inch to render the text
+
+ ''fontsize''
+ The font size in points
+ """
+ x = self.to_mask(texstr, dpi=dpi, fontsize=fontsize)
+
+ r, g, b = mcolors.colorConverter.to_rgb(color)
+ RGBA = np.zeros((x.shape[0], x.shape[1], 4), dtype=np.uint8)
+ RGBA[:,:,0] = int(255*r)
+ RGBA[:,:,1] = int(255*g)
+ RGBA[:,:,2] = int(255*b)
+ RGBA[:,:,3] = x
+ return RGBA
+
+ def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14):
+ """
+
+ ''filename''
+ A writable filename or fileobject
+
+ ''texstr''
+ A valid mathtext string, eg r'IQ: $\sigma_i=15$'
+
+ ''color''
+ A valid matplotlib color argument
+
+ ''dpi''
+ The dots-per-inch to render the text
+
+ ''fontsize''
+ The font size in points
+
+ """
+
+ rgba = self.to_rgba(texstr, color=color, dpi=dpi, fontsize=fontsize)
+ numrows, numcols, tmp = rgba.shape
+ return _png.write_png(rgba.tostring(), numcols, numrows, filename)
+
Modified: trunk/matplotlib/setupext.py
===================================================================
--- trunk/matplotlib/setupext.py 2008-06-12 18:05:16 UTC (rev 5489)
+++ trunk/matplotlib/setupext.py 2008-06-12 19:14:21 UTC (rev 5490)
@@ -589,6 +589,7 @@
def add_ft2font_flags(module):
'Add the module flags to ft2font extension'
+ add_numpy_flags(module)
if not get_pkgconfig(module, 'freetype2'):
module.libraries.extend(['freetype', 'z'])
add_base_flags(module)
Modified: trunk/matplotlib/src/ft2font.cpp
===================================================================
--- trunk/matplotlib/src/ft2font.cpp 2008-06-12 18:05:16 UTC (rev 5489)
+++ trunk/matplotlib/src/ft2font.cpp 2008-06-12 19:14:21 UTC (rev 5490)
@@ -2,6 +2,9 @@
#include "mplutils.h"
#include <sstream>
+#define PY_ARRAY_TYPES_PREFIX NumPy
+#include "numpy/arrayobject.h"
+
#define FIXED_MAJOR(val) (*((short *) &val+1))
#define FIXED_MINOR(val) (*((short *) &val+0))
@@ -251,6 +254,41 @@
);
}
+char FT2Image::as_array__doc__[] =
+"x = image.as_array()\n"
+"\n"
+"Return the image buffer as a width x height numpy array of ubyte \n"
+"\n"
+;
+Py::Object
+FT2Image::py_as_array(const Py::Tuple & args) {
+ _VERBOSE("FT2Image::as_array");
+ args.verify_length(0);
+
+ int dimensions[2];
+ dimensions[0] = get_height(); //numrows
+ dimensions[1] = get_width(); //numcols
+
+
+ PyArrayObject *A = (PyArrayObject *) PyArray_SimpleNewFromData(2, dimensions, PyArray_UBYTE, _buffer);
+
+ /*
+
+ PyArrayObject *A = (PyArrayObject *) PyArray_FromDims(2, dimensions, PyArray_UBYTE);
+
+
+ unsigned char *src = _buffer;
+ unsigned char *src_end = src + (dimensions[0] * dimensions[1]);
+ unsigned char *dst = (unsigned char *)A->data;
+
+ while (src != src_end) {
+ *dst++ = *src++;
+ }
+ */
+
+ return Py::asObject((PyObject*)A);
+}
+
void FT2Image::makeRgbCopy() {
if (!_isDirty)
return;
@@ -1697,6 +1735,8 @@
FT2Image::draw_rect__doc__);
add_varargs_method("draw_rect_filled", &FT2Image::py_draw_rect_filled,
FT2Image::draw_rect_filled__doc__);
+ add_varargs_method("as_array", &FT2Image::py_as_array,
+ FT2Image::as_array__doc__);
add_varargs_method("as_str", &FT2Image::py_as_str,
FT2Image::as_str__doc__);
add_varargs_method("as_rgb_str", &FT2Image::py_as_rgb_str,
@@ -1834,6 +1874,7 @@
initft2font(void)
{
static ft2font_module* ft2font = new ft2font_module;
+ import_array();
Py::Dict d = ft2font->moduleDictionary();
d["SCALABLE"] = Py::Int(FT_FACE_FLAG_SCALABLE);
@@ -1885,5 +1926,6 @@
}
ft2font_module::~ft2font_module() {
+
FT_Done_FreeType( _ft2Library );
}
Modified: trunk/matplotlib/src/ft2font.h
===================================================================
--- trunk/matplotlib/src/ft2font.h 2008-06-12 18:05:16 UTC (rev 5489)
+++ trunk/matplotlib/src/ft2font.h 2008-06-12 19:14:21 UTC (rev 5490)
@@ -45,6 +45,8 @@
Py::Object py_draw_rect(const Py::Tuple & args);
static char draw_rect_filled__doc__ [];
Py::Object py_draw_rect_filled(const Py::Tuple & args);
+ static char as_array__doc__ [];
+ Py::Object py_as_array(const Py::Tuple & args);
static char as_str__doc__ [];
Py::Object py_as_str(const Py::Tuple & args);
static char as_rgb_str__doc__ [];
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2008-06-12 18:05:19
|
Revision: 5489
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5489&view=rev
Author: efiring
Date: 2008-06-12 11:05:16 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
Merged revisions 5488 via svnmerge from
https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_91_maint
........
r5488 | efiring | 2008-06-12 08:02:18 -1000 (Thu, 12 Jun 2008) | 2 lines
Support hold in quiver, contour, contourf
........
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/axes.py
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Name: svnmerge-integrated
- /branches/v0_91_maint:1-5443
+ /branches/v0_91_maint:1-5443,5488
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-06-12 18:02:18 UTC (rev 5488)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-06-12 18:05:16 UTC (rev 5489)
@@ -4921,6 +4921,7 @@
quiverkey.__doc__ = mquiver.QuiverKey.quiverkey_doc
def quiver(self, *args, **kw):
+ if not self._hold: self.cla()
q = mquiver.Quiver(self, *args, **kw)
self.add_collection(q, False)
self.update_datalim(q.XY)
@@ -5578,11 +5579,13 @@
return ret
def contour(self, *args, **kwargs):
+ if not self._hold: self.cla()
kwargs['filled'] = False
return mcontour.ContourSet(self, *args, **kwargs)
contour.__doc__ = mcontour.ContourSet.contour_doc
def contourf(self, *args, **kwargs):
+ if not self._hold: self.cla()
kwargs['filled'] = True
return mcontour.ContourSet(self, *args, **kwargs)
contourf.__doc__ = mcontour.ContourSet.contour_doc
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2008-06-12 18:02:21
|
Revision: 5488
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5488&view=rev
Author: efiring
Date: 2008-06-12 11:02:18 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
Support hold in quiver, contour, contourf
Modified Paths:
--------------
branches/v0_91_maint/lib/matplotlib/axes.py
Modified: branches/v0_91_maint/lib/matplotlib/axes.py
===================================================================
--- branches/v0_91_maint/lib/matplotlib/axes.py 2008-06-12 17:16:15 UTC (rev 5487)
+++ branches/v0_91_maint/lib/matplotlib/axes.py 2008-06-12 18:02:18 UTC (rev 5488)
@@ -4334,6 +4334,7 @@
quiverkey.__doc__ = mquiver.QuiverKey.quiverkey_doc
def quiver(self, *args, **kw):
+ if not self._hold: self.cla()
q = mquiver.Quiver(self, *args, **kw)
self.add_collection(q)
self.update_datalim_numerix(q.X, q.Y)
@@ -5002,11 +5003,13 @@
def contour(self, *args, **kwargs):
+ if not self._hold: self.cla()
kwargs['filled'] = False
return mcontour.ContourSet(self, *args, **kwargs)
contour.__doc__ = mcontour.ContourSet.contour_doc
def contourf(self, *args, **kwargs):
+ if not self._hold: self.cla()
kwargs['filled'] = True
return mcontour.ContourSet(self, *args, **kwargs)
contourf.__doc__ = mcontour.ContourSet.contour_doc
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ds...@us...> - 2008-06-12 17:16:17
|
Revision: 5487
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5487&view=rev
Author: dsdale
Date: 2008-06-12 10:16:15 -0700 (Thu, 12 Jun 2008)
Log Message:
-----------
added customization api, fixed a few errors in docs
Modified Paths:
--------------
trunk/matplotlib/doc/api/index.rst
trunk/matplotlib/doc/users/customizing.rst
trunk/matplotlib/doc/users/usetex.rst
Modified: trunk/matplotlib/doc/api/index.rst
===================================================================
--- trunk/matplotlib/doc/api/index.rst 2008-06-12 16:38:47 UTC (rev 5486)
+++ trunk/matplotlib/doc/api/index.rst 2008-06-12 17:16:15 UTC (rev 5487)
@@ -9,6 +9,7 @@
.. toctree::
+ matplotlib_configuration_api.rst
artist_api.rst
axes_api.rst
pyplot_api.rst
Modified: trunk/matplotlib/doc/users/customizing.rst
===================================================================
--- trunk/matplotlib/doc/users/customizing.rst 2008-06-12 16:38:47 UTC (rev 5486)
+++ trunk/matplotlib/doc/users/customizing.rst 2008-06-12 17:16:15 UTC (rev 5487)
@@ -23,7 +23,7 @@
3. :file:`{INSTALL}/matplotlib/mpl-data/matplotlibrc`, where
:file:`{INSTALL}` is something like
:file:`/usr/lib/python2.5/site-packages` on Linux, and maybe
- :file:`C:\Python25\Lib\site-packages` on Windows. Every time you
+ :file:`C:\\Python25\\Lib\\site-packages` on Windows. Every time you
install matplotlib, this file will be overwritten, so if you want
your customizations to be saved, please move this file to you
:file:`.matplotlib` directory.
Modified: trunk/matplotlib/doc/users/usetex.rst
===================================================================
--- trunk/matplotlib/doc/users/usetex.rst 2008-06-12 16:38:47 UTC (rev 5486)
+++ trunk/matplotlib/doc/users/usetex.rst 2008-06-12 17:16:15 UTC (rev 5487)
@@ -124,8 +124,7 @@
===============
* Try deleting your :file:`.matplotlib/tex.cache` directory. If you don't know
- where to find :file:`.matplotlib`, see
- :ref:`locating-matplotlib-config-dir`.
+ where to find :file:`.matplotlib`, see :ref:`locating-matplotlib-config-dir`.
* Make sure LaTeX, dvipng and ghostscript are each working and on your
:envvar:`PATH`.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|