SourceForge logo
SourceForge logo
Menu

matplotlib-checkins — Commit notification. DO NOT POST to this list, just subscribe to it.

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
S M T W T F S



1
(3)
2
(3)
3
4
(2)
5
(9)
6
(4)
7
(9)
8
(7)
9
(2)
10
(3)
11
(2)
12
13
(2)
14
(10)
15
(24)
16
(17)
17
(21)
18
(3)
19
(23)
20
(6)
21
(4)
22
(14)
23
(11)
24
(15)
25
(6)
26
(1)
27
(4)
28
(3)
29
(9)
30
(6)
31
(2)

Showing 7 results of 7

From: <jd...@us...> - 2008年10月08日 19:54:07
Revision: 6173
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6173&view=rev
Author: jdh2358
Date: 2008年10月08日 19:53:57 +0000 (2008年10月08日)
Log Message:
-----------
fixed deprecation warning in legend
Modified Paths:
--------------
 trunk/matplotlib/lib/matplotlib/legend.py
 trunk/matplotlib/lib/matplotlib/mlab.py
Modified: trunk/matplotlib/lib/matplotlib/legend.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/legend.py	2008年10月08日 18:16:49 UTC (rev 6172)
+++ trunk/matplotlib/lib/matplotlib/legend.py	2008年10月08日 19:53:57 UTC (rev 6173)
@@ -124,7 +124,7 @@
 value=rcParams["legend."+name]
 setattr(self,name,value)
 if pad:
- warnings.DeprecationWarning("Use 'borderpad' instead of 'pad'.")
+ warnings.warn("Use 'borderpad' instead of 'pad'.", DeprecationWarning)
 # 2008年10月04日
 if self.numpoints <= 0:
 raise ValueError("numpoints must be >= 0; it was %d"% numpoints)
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py	2008年10月08日 18:16:49 UTC (rev 6172)
+++ trunk/matplotlib/lib/matplotlib/mlab.py	2008年10月08日 19:53:57 UTC (rev 6173)
@@ -1799,8 +1799,9 @@
 
 def rec_join(key, r1, r2, jointype='inner', defaults=None, r1postfix='1', r2postfix='2'):
 """
- join record arrays r1 and r2 on key; key is a tuple of field
- names. If r1 and r2 have equal values on all the keys in the key
+ join record arrays r1 and r2 on key; key is a tuple of field names
+ -- if key is a string it is assumed to be a single attribute
+ name. If r1 and r2 have equal values on all the keys in the key
 tuple, then their fields will be merged into a new record array
 containing the intersection of the fields of r1 and r2.
 
@@ -1812,10 +1813,13 @@
 The defaults keyword is a dictionary filled with
 {column_name:default_value} pairs.
 
- The keywords r1postfix and r2postfix are postfixed to column names 
+ The keywords r1postfix and r2postfix are postfixed to column names
 (other than keys) that are both in r1 and r2.
 """
 
+ if cbook.is_string_like(key):
+ key = (key, )
+
 for name in key:
 if name not in r1.dtype.names:
 raise ValueError('r1 does not have key field %s'%name)
@@ -1862,7 +1866,7 @@
 
 
 keydesc = [key_desc(name) for name in key]
- 
+
 def mapped_r1field(name):
 """ the column name in newrec that corresponds to the colmn in r1 """
 if name in key or name not in r2.dtype.names: return name
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 6172
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6172&view=rev
Author: mdboom
Date: 2008年10月08日 18:16:49 +0000 (2008年10月08日)
Log Message:
-----------
More informative error message when data is too large for Agg to draw it.
Modified Paths:
--------------
 trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h
Modified: trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h
===================================================================
--- trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h	2008年10月08日 16:37:15 UTC (rev 6171)
+++ trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h	2008年10月08日 18:16:49 UTC (rev 6172)
@@ -185,7 +185,10 @@
 if((m_num_cells & cell_block_mask) == 0)
 {
 if(m_num_blocks >= cell_block_limit) {
- throw "Agg rendering complexity exceeded.";
+ /* If this exception is thrown too often, one can
+ increase cell_block_limit */
+ throw "Agg rendering complexity exceeded. "
+ "Consider downsampling or decimating your data.";
 }
 allocate_block();
 }
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
From: <md...@us...> - 2008年10月08日 16:37:20
Revision: 6171
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6171&view=rev
Author: mdboom
Date: 2008年10月08日 16:37:15 +0000 (2008年10月08日)
Log Message:
-----------
Throw exception when there are too many data points.
Modified Paths:
--------------
 trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h
 trunk/matplotlib/src/_backend_agg.cpp
Modified: trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h
===================================================================
--- trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h	2008年10月08日 14:38:26 UTC (rev 6170)
+++ trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h	2008年10月08日 16:37:15 UTC (rev 6171)
@@ -29,6 +29,7 @@
 #ifndef AGG_RASTERIZER_CELLS_AA_INCLUDED
 #define AGG_RASTERIZER_CELLS_AA_INCLUDED
 
+#include <exception>
 #include <string.h>
 #include <math.h>
 #include "agg_math.h"
@@ -183,7 +184,9 @@
 {
 if((m_num_cells & cell_block_mask) == 0)
 {
- if(m_num_blocks >= cell_block_limit) return;
+ if(m_num_blocks >= cell_block_limit) {
+ throw "Agg rendering complexity exceeded.";
+ }
 allocate_block();
 }
 *m_curr_cell_ptr++ = m_curr_cell;
Modified: trunk/matplotlib/src/_backend_agg.cpp
===================================================================
--- trunk/matplotlib/src/_backend_agg.cpp	2008年10月08日 14:38:26 UTC (rev 6170)
+++ trunk/matplotlib/src/_backend_agg.cpp	2008年10月08日 16:37:15 UTC (rev 6171)
@@ -941,7 +941,11 @@
 if (snap)
 gc.isaa = false;
 
- _draw_path(curve, has_clippath, face, gc);
+ try {
+ _draw_path(curve, has_clippath, face, gc);
+ } catch (const char* e) {
+ throw Py::RuntimeError(e);
+ }
 
 return Py::Object();
 }
@@ -1175,20 +1179,24 @@
 
 PathListGenerator path_generator(paths);
 
- _draw_path_collection_generic<PathListGenerator, 1, 1>
- (master_transform,
- cliprect,
- clippath,
- clippath_trans,
- path_generator,
- transforms_obj,
- offsets_obj,
- offset_trans,
- facecolors_obj,
- edgecolors_obj,
- linewidths,
- linestyles_obj,
- antialiaseds);
+ try {
+ _draw_path_collection_generic<PathListGenerator, 1, 1>
+ (master_transform,
+ cliprect,
+ clippath,
+ clippath_trans,
+ path_generator,
+ transforms_obj,
+ offsets_obj,
+ offset_trans,
+ facecolors_obj,
+ edgecolors_obj,
+ linewidths,
+ linestyles_obj,
+ antialiaseds);
+ } catch (const char *e) {
+ throw Py::RuntimeError(e);
+ }
 
 return Py::Object();
 }
@@ -1310,20 +1318,24 @@
 }
 
 try {
- _draw_path_collection_generic<QuadMeshGenerator, 0, 0>
- (master_transform,
- cliprect,
- clippath,
- clippath_trans,
- path_generator,
- transforms_obj,
- offsets_obj,
- offset_trans,
- facecolors_obj,
- edgecolors_obj,
- linewidths,
- linestyles_obj,
- antialiaseds);
+ try {
+ _draw_path_collection_generic<QuadMeshGenerator, 0, 0>
+ (master_transform,
+ cliprect,
+ clippath,
+ clippath_trans,
+ path_generator,
+ transforms_obj,
+ offsets_obj,
+ offset_trans,
+ facecolors_obj,
+ edgecolors_obj,
+ linewidths,
+ linestyles_obj,
+ antialiaseds);
+ } catch (const char* e) {
+ throw Py::RuntimeError(e);
+ }
 } catch (...) {
 if (free_edgecolors) Py_XDECREF(edgecolors_obj.ptr());
 throw;
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
From: <sa...@us...> - 2008年10月08日 14:38:34
Revision: 6170
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6170&view=rev
Author: sameerd
Date: 2008年10月08日 14:38:26 +0000 (2008年10月08日)
Log Message:
-----------
rec_join now handles two record arrays with the same column names with "*fixes"
Modified Paths:
--------------
 trunk/matplotlib/lib/matplotlib/mlab.py
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py	2008年10月08日 14:09:55 UTC (rev 6169)
+++ trunk/matplotlib/lib/matplotlib/mlab.py	2008年10月08日 14:38:26 UTC (rev 6170)
@@ -1665,6 +1665,14 @@
 except TypeError: return False
 else: return b
 
+def rec_view(rec):
+ """ Return a view of an ndarray as a recarray
+ http://projects.scipy.org/pipermail/numpy-discussion/2008-August/036429.html
+ Reverting Travis' fix because it doesn't work for object arrays
+ """
+ return rec.view(np.recarray)
+ #return rec.view(dtype=(np.record, rec.dtype), type=np.recarray)
+
 def rec_append_field(rec, name, arr, dtype=None):
 """
 return a new record array with field name populated with data from array arr.
@@ -1703,7 +1711,7 @@
 newrec[field] = rec[field]
 for name, arr in zip(names, arrs):
 newrec[name] = arr
- return newrec.view(np.recarray)
+ return rec_view(newrec)
 
 
 def rec_drop_fields(rec, names):
@@ -1719,7 +1727,7 @@
 for field in newdtype.names:
 newrec[field] = rec[field]
 
- return newrec.view(np.recarray)
+ return rec_view(newrec)
 
 
 
@@ -1789,7 +1797,7 @@
 return np.rec.fromarrays(arrays, names=names)
 
 
-def rec_join(key, r1, r2, jointype='inner', defaults=None):
+def rec_join(key, r1, r2, jointype='inner', defaults=None, r1postfix='1', r2postfix='2'):
 """
 join record arrays r1 and r2 on key; key is a tuple of field
 names. If r1 and r2 have equal values on all the keys in the key
@@ -1803,6 +1811,9 @@
 
 The defaults keyword is a dictionary filled with
 {column_name:default_value} pairs.
+
+ The keywords r1postfix and r2postfix are postfixed to column names 
+ (other than keys) that are both in r1 and r2.
 """
 
 for name in key:
@@ -1850,13 +1861,21 @@
 return (name, dt2.descr[0][1])
 
 
-
 keydesc = [key_desc(name) for name in key]
+ 
+ def mapped_r1field(name):
+ """ the column name in newrec that corresponds to the colmn in r1 """
+ if name in key or name not in r2.dtype.names: return name
+ else: return name + r1postfix
 
- newdtype = np.dtype(keydesc +
- [desc for desc in r1.dtype.descr if desc[0] not in key ] +
- [desc for desc in r2.dtype.descr if desc[0] not in key ] )
+ def mapped_r2field(name):
+ """ the column name in newrec that corresponds to the colmn in r2 """
+ if name in key or name not in r1.dtype.names: return name
+ else: return name + r2postfix
 
+ r1desc = [(mapped_r1field(desc[0]), desc[1]) for desc in r1.dtype.descr if desc[0] not in key]
+ r2desc = [(mapped_r2field(desc[0]), desc[1]) for desc in r2.dtype.descr if desc[0] not in key]
+ newdtype = np.dtype(keydesc + r1desc + r2desc)
 
 newrec = np.empty(common_len + left_len + right_len, dtype=newdtype)
 
@@ -1867,20 +1886,22 @@
 newrec[k] = v
 
 for field in r1.dtype.names:
+ newfield = mapped_r1field(field)
 if common_len:
- newrec[field][:common_len] = r1[field][r1ind]
+ newrec[newfield][:common_len] = r1[field][r1ind]
 if (jointype == "outer" or jointype == "leftouter") and left_len:
- newrec[field][common_len:(common_len+left_len)] = r1[field][left_ind]
+ newrec[newfield][common_len:(common_len+left_len)] = r1[field][left_ind]
 
 for field in r2.dtype.names:
+ newfield = mapped_r2field(field)
 if field not in key and common_len:
- newrec[field][:common_len] = r2[field][r2ind]
+ newrec[newfield][:common_len] = r2[field][r2ind]
 if jointype == "outer" and right_len:
- newrec[field][-right_len:] = r2[field][right_ind]
+ newrec[newfield][-right_len:] = r2[field][right_ind]
 
 newrec.sort(order=key)
 
- return newrec.view(np.recarray)
+ return rec_view(newrec)
 
 
 def csv2rec(fname, comments='#', skiprows=0, checkrows=0, delimiter=',',
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 6169
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6169&view=rev
Author: mdboom
Date: 2008年10月08日 14:09:55 +0000 (2008年10月08日)
Log Message:
-----------
Increase rendering cell limit in Agg.
Modified Paths:
--------------
 trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h
Modified: trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h
===================================================================
--- trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h	2008年10月08日 13:59:28 UTC (rev 6168)
+++ trunk/matplotlib/agg24/include/agg_rasterizer_cells_aa.h	2008年10月08日 14:09:55 UTC (rev 6169)
@@ -2,15 +2,15 @@
 // Anti-Grain Geometry - Version 2.4
 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
 //
-// Permission to copy, use, modify, sell and distribute this software 
-// is granted provided this copyright notice appears in all copies. 
+// Permission to copy, use, modify, sell and distribute this software
+// is granted provided this copyright notice appears in all copies.
 // This software is provided "as is" without express or implied
 // warranty, and with no claim as to its suitability for any purpose.
 //
 //----------------------------------------------------------------------------
 //
-// The author gratefully acknowleges the support of David Turner, 
-// Robert Wilhelm, and Werner Lemberg - the authors of the FreeType 
+// The author gratefully acknowleges the support of David Turner,
+// Robert Wilhelm, and Werner Lemberg - the authors of the FreeType
 // libray - in producing this work. See http://www.freetype.org for details.
 //
 //----------------------------------------------------------------------------
@@ -19,12 +19,12 @@
 // http://www.antigrain.com
 //----------------------------------------------------------------------------
 //
-// Adaptation for 32-bit screen coordinates has been sponsored by 
+// Adaptation for 32-bit screen coordinates has been sponsored by
 // Liberty Technology Systems, Inc., visit http://lib-sys.com
 //
 // Liberty Technology Systems, Inc. is the provider of
 // PostScript and PDF technology for software developers.
-// 
+//
 //----------------------------------------------------------------------------
 #ifndef AGG_RASTERIZER_CELLS_AA_INCLUDED
 #define AGG_RASTERIZER_CELLS_AA_INCLUDED
@@ -49,7 +49,7 @@
 cell_block_size = 1 << cell_block_shift,
 cell_block_mask = cell_block_size - 1,
 cell_block_pool = 256,
- cell_block_limit = 1024
+ cell_block_limit = 4096
 };
 
 struct sorted_y
@@ -76,19 +76,19 @@
 
 void sort_cells();
 
- unsigned total_cells() const 
+ unsigned total_cells() const
 {
 return m_num_cells;
 }
 
- unsigned scanline_num_cells(unsigned y) const 
- { 
- return m_sorted_y[y - m_min_y].num; 
+ unsigned scanline_num_cells(unsigned y) const
+ {
+ return m_sorted_y[y - m_min_y].num;
 }
 
 const cell_type* const* scanline_cells(unsigned y) const
- { 
- return m_sorted_cells.data() + m_sorted_y[y - m_min_y].start; 
+ {
+ return m_sorted_cells.data() + m_sorted_y[y - m_min_y].start;
 }
 
 bool sorted() const { return m_sorted; }
@@ -101,7 +101,7 @@
 void add_curr_cell();
 void render_hline(int ey, int x1, int y1, int x2, int y2);
 void allocate_block();
- 
+
 private:
 unsigned m_num_blocks;
 unsigned m_max_blocks;
@@ -124,7 +124,7 @@
 
 
 //------------------------------------------------------------------------
- template<class Cell> 
+ template<class Cell>
 rasterizer_cells_aa<Cell>::~rasterizer_cells_aa()
 {
 if(m_num_blocks)
@@ -140,7 +140,7 @@
 }
 
 //------------------------------------------------------------------------
- template<class Cell> 
+ template<class Cell>
 rasterizer_cells_aa<Cell>::rasterizer_cells_aa() :
 m_num_blocks(0),
 m_max_blocks(0),
@@ -161,10 +161,10 @@
 }
 
 //------------------------------------------------------------------------
- template<class Cell> 
+ template<class Cell>
 void rasterizer_cells_aa<Cell>::reset()
 {
- m_num_cells = 0; 
+ m_num_cells = 0;
 m_curr_block = 0;
 m_curr_cell.initial();
 m_style_cell.initial();
@@ -176,7 +176,7 @@
 }
 
 //------------------------------------------------------------------------
- template<class Cell> 
+ template<class Cell>
 AGG_INLINE void rasterizer_cells_aa<Cell>::add_curr_cell()
 {
 if(m_curr_cell.area | m_curr_cell.cover)
@@ -192,7 +192,7 @@
 }
 
 //------------------------------------------------------------------------
- template<class Cell> 
+ template<class Cell>
 AGG_INLINE void rasterizer_cells_aa<Cell>::set_curr_cell(int x, int y)
 {
 if(m_curr_cell.not_equal(x, y, m_style_cell))
@@ -207,9 +207,9 @@
 }
 
 //------------------------------------------------------------------------
- template<class Cell> 
- AGG_INLINE void rasterizer_cells_aa<Cell>::render_hline(int ey, 
- int x1, int y1, 
+ template<class Cell>
+ AGG_INLINE void rasterizer_cells_aa<Cell>::render_hline(int ey,
+ int x1, int y1,
 int x2, int y2)
 {
 int ex1 = x1 >> poly_subpixel_shift;
@@ -305,14 +305,14 @@
 }
 
 //------------------------------------------------------------------------
- template<class Cell> 
+ template<class Cell>
 AGG_INLINE void rasterizer_cells_aa<Cell>::style(const cell_type& style_cell)
- { 
- m_style_cell.style(style_cell); 
+ {
+ m_style_cell.style(style_cell);
 }
 
 //------------------------------------------------------------------------
- template<class Cell> 
+ template<class Cell>
 void rasterizer_cells_aa<Cell>::line(int x1, int y1, int x2, int y2)
 {
 enum dx_limit_e { dx_limit = 16384 << poly_subpixel_shift };
@@ -358,7 +358,7 @@
 
 //Vertical line - we have to calculate start and end cells,
 //and then - the common values of the area and coverage for
- //all cells of the line. We know exactly there's only one 
+ //all cells of the line. We know exactly there's only one
 //cell, so, we don't have to call render_hline().
 incr = 1;
 if(dx == 0)
@@ -463,15 +463,15 @@
 }
 
 //------------------------------------------------------------------------
- template<class Cell> 
+ template<class Cell>
 void rasterizer_cells_aa<Cell>::allocate_block()
 {
 if(m_curr_block >= m_num_blocks)
 {
 if(m_num_blocks >= m_max_blocks)
 {
- cell_type** new_cells = 
- pod_allocator<cell_type*>::allocate(m_max_blocks + 
+ cell_type** new_cells =
+ pod_allocator<cell_type*>::allocate(m_max_blocks +
 cell_block_pool);
 
 if(m_cells)
@@ -483,7 +483,7 @@
 m_max_blocks += cell_block_pool;
 }
 
- m_cells[m_num_blocks++] = 
+ m_cells[m_num_blocks++] =
 pod_allocator<cell_type>::allocate(cell_block_size);
 
 }
@@ -513,7 +513,7 @@
 void qsort_cells(Cell** start, unsigned num)
 {
 Cell** stack[80];
- Cell*** top; 
+ Cell*** top;
 Cell** limit;
 Cell** base;
 
@@ -538,7 +538,7 @@
 i = base + 1;
 j = limit - 1;
 
- // now ensure that *i <= *base <= *j 
+ // now ensure that *i <= *base <= *j
 if((*j)->x < (*i)->x)
 {
 swap_cells(i, j);
@@ -619,7 +619,7 @@
 
 
 //------------------------------------------------------------------------
- template<class Cell> 
+ template<class Cell>
 void rasterizer_cells_aa<Cell>::sort_cells()
 {
 if(m_sorted) return; //Perform sort only the first time.
@@ -636,9 +636,9 @@
 //for(unsigned nc = 0; nc < m_num_cells; nc++)
 //{
 // cell_type* cell = m_cells[nc >> cell_block_shift] + (nc & cell_block_mask);
-// if(cell->x < m_min_x || 
-// cell->y < m_min_y || 
-// cell->x > m_max_x || 
+// if(cell->x < m_min_x ||
+// cell->y < m_min_y ||
+// cell->x > m_max_x ||
 // cell->y > m_max_y)
 // {
 // cell = cell; // Breakpoint here
@@ -660,19 +660,21 @@
 {
 cell_ptr = *block_ptr++;
 i = cell_block_size;
- while(i--) 
+ while(i--)
 {
 m_sorted_y[cell_ptr->y - m_min_y].start++;
 ++cell_ptr;
 }
 }
 
- cell_ptr = *block_ptr++;
 i = m_num_cells & cell_block_mask;
- while(i--) 
- {
- m_sorted_y[cell_ptr->y - m_min_y].start++;
- ++cell_ptr;
+ if (i) {
+ cell_ptr = *block_ptr++;
+ while(i--)
+ {
+ m_sorted_y[cell_ptr->y - m_min_y].start++;
+ ++cell_ptr;
+ }
 }
 
 // Convert the Y-histogram into the array of starting indexes
@@ -691,7 +693,7 @@
 {
 cell_ptr = *block_ptr++;
 i = cell_block_size;
- while(i--) 
+ while(i--)
 {
 sorted_y& curr_y = m_sorted_y[cell_ptr->y - m_min_y];
 m_sorted_cells[curr_y.start + curr_y.num] = cell_ptr;
@@ -699,15 +701,17 @@
 ++cell_ptr;
 }
 }
- 
- cell_ptr = *block_ptr++;
+
 i = m_num_cells & cell_block_mask;
- while(i--) 
- {
- sorted_y& curr_y = m_sorted_y[cell_ptr->y - m_min_y];
- m_sorted_cells[curr_y.start + curr_y.num] = cell_ptr;
- ++curr_y.num;
- ++cell_ptr;
+ if (i) {
+ cell_ptr = *block_ptr++;
+ while(i--)
+ {
+ sorted_y& curr_y = m_sorted_y[cell_ptr->y - m_min_y];
+ m_sorted_cells[curr_y.start + curr_y.num] = cell_ptr;
+ ++curr_y.num;
+ ++cell_ptr;
+ }
 }
 
 // Finally arrange the X-arrays
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
Revision: 6168
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6168&view=rev
Author: mdboom
Date: 2008年10月08日 13:59:28 +0000 (2008年10月08日)
Log Message:
-----------
Addresses this Ubuntu bug:
https://bugs.launchpad.net/ubuntu/+source/matplotlib/+bug/278764
Display a warning when show() is called with a non-GUI backend, so that the user is not left scratching their head when running "ipython -pylab"
Modified Paths:
--------------
 trunk/matplotlib/lib/matplotlib/backends/__init__.py
Modified: trunk/matplotlib/lib/matplotlib/backends/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/__init__.py	2008年10月08日 04:07:21 UTC (rev 6167)
+++ trunk/matplotlib/lib/matplotlib/backends/__init__.py	2008年10月08日 13:59:28 UTC (rev 6168)
@@ -1,5 +1,6 @@
 
 import matplotlib
+import warnings
 
 # ipython relies on interactive_bk being defined here
 from matplotlib.rcsetup import interactive_bk
@@ -28,9 +29,15 @@
 # image backends like pdf, agg or svg do not need to do anything
 # for "show" or "draw_if_interactive", so if they are not defined
 # by the backend, just do nothing
+ def do_nothing_show(*args, **kwargs):
+ warnings.warn("""
+Your currently selected backend, '%s' does not support show().
+Please select a GUI backend in your matplotlibrc file ('%s')
+or with matplotlib.use()""" %
+ (backend, matplotlib.matplotlib_fname()))
 def do_nothing(*args, **kwargs): pass
 backend_version = getattr(backend_mod,'backend_version', 'unknown')
- show = getattr(backend_mod, 'show', do_nothing)
+ show = getattr(backend_mod, 'show', do_nothing_show)
 draw_if_interactive = getattr(backend_mod, 'draw_if_interactive', do_nothing)
 
 # Additional imports which only happen for certain backends. This section
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
From: <fer...@us...> - 2008年10月08日 04:07:40
Revision: 6167
 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=6167&view=rev
Author: fer_perez
Date: 2008年10月08日 04:07:21 +0000 (2008年10月08日)
Log Message:
-----------
Major rework of the sphinx template.
I'm committing this as a separate directory because I changed way too
much of the original code and I want to make sure others can have a
look before removing the old code.
Added Paths:
-----------
 trunk/py4science/examples/sphinx_template2/
 trunk/py4science/examples/sphinx_template2/Makefile
 trunk/py4science/examples/sphinx_template2/README.txt
 trunk/py4science/examples/sphinx_template2/conf.py
 trunk/py4science/examples/sphinx_template2/index.rst
 trunk/py4science/examples/sphinx_template2/model/
 trunk/py4science/examples/sphinx_template2/model/api_docs.rst
 trunk/py4science/examples/sphinx_template2/model/index.rst
 trunk/py4science/examples/sphinx_template2/model/introduction.rst
 trunk/py4science/examples/sphinx_template2/model/next_steps.rst
 trunk/py4science/examples/sphinx_template2/model/sphinx_helpers.rst
 trunk/py4science/examples/sphinx_template2/pyplots/
 trunk/py4science/examples/sphinx_template2/pyplots/elegant.py
 trunk/py4science/examples/sphinx_template2/pyplots/hairy.py
 trunk/py4science/examples/sphinx_template2/simulations/
 trunk/py4science/examples/sphinx_template2/simulations/finale.rst
 trunk/py4science/examples/sphinx_template2/simulations/index.rst
 trunk/py4science/examples/sphinx_template2/simulations/introduction.rst
 trunk/py4science/examples/sphinx_template2/simulations/preliminary.rst
 trunk/py4science/examples/sphinx_template2/tools/
 trunk/py4science/examples/sphinx_template2/tools/sphinxext/
 trunk/py4science/examples/sphinx_template2/tools/sphinxext/inheritance_diagram.py
 trunk/py4science/examples/sphinx_template2/tools/sphinxext/ipython_console_highlighting.py
 trunk/py4science/examples/sphinx_template2/tools/sphinxext/mathmpl.py
 trunk/py4science/examples/sphinx_template2/tools/sphinxext/only_directives.py
 trunk/py4science/examples/sphinx_template2/tools/sphinxext/plot_directive.py
 trunk/py4science/examples/sphinx_template2/tools/static/
 trunk/py4science/examples/sphinx_template2/tools/templates/
Added: trunk/py4science/examples/sphinx_template2/Makefile
===================================================================
--- trunk/py4science/examples/sphinx_template2/Makefile	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/Makefile	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,89 @@
+# Makefile for Sphinx documentation
+#
+
+PDFNAME=sampledoc
+SRCDIR=.
+
+# You can set these variables from the command line.
+SPHINXOPTS =
+SPHINXBUILD = sphinx-build
+PAPER = letter
+
+# Internal variables.
+PAPEROPT_a4 = -D latex_paper_size=a4
+PAPEROPT_letter = -D latex_paper_size=letter
+ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) $(SRCDIR)
+
+.PHONY: help clean html web pickle htmlhelp latex changes linkcheck pdf all dist
+
+help:
+	@echo "Please use \`make <target>' where <target> is one of"
+	@echo " html to make standalone HTML files"
+	@echo " pickle to make pickle files (usable by e.g. sphinx-web)"
+	@echo " htmlhelp to make HTML files and a HTML help project"
+	@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+	@echo " changes to make an overview over all changed/added/deprecated items"
+	@echo " linkcheck to check all external links for integrity"
+	@echo
+	@echo "Compound utility targets:"
+	@echo " pdf latex and then runs the PDF generation"
+	@echo " all html and pdf"
+	@echo " dist all, and then puts the results in dist/"
+
+clean:
+	-rm -rf build/ dist/ _static/ pyplots/*png pyplots/*pdf
+
+pdf: latex
+	cd build/latex && make all-pdf
+
+all: html pdf
+
+dist: clean all
+	mkdir -p dist
+	ln build/latex/$(PDFNAME).pdf dist/
+	cp -al build/html dist/
+	@echo "Build finished. Final docs are in dist/"
+
+html:
+	mkdir -p build/html build/doctrees
+	$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html
+	@echo
+	@echo "Build finished. The HTML pages are in build/html."
+
+pickle:
+	mkdir -p build/pickle build/doctrees
+	$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle
+	@echo
+	@echo "Build finished; now you can process the pickle files or run"
+	@echo " sphinx-web build/pickle"
+	@echo "to start the sphinx-web server."
+
+web: pickle
+
+htmlhelp:
+	mkdir -p build/htmlhelp build/doctrees
+	$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp
+	@echo
+	@echo "Build finished; now you can run HTML Help Workshop with the" \
+	 ".hhp project file in build/htmlhelp."
+
+latex:
+	mkdir -p build/latex build/doctrees
+	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex
+	@echo
+	@echo "Build finished; the LaTeX files are in build/latex."
+	@echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
+	 "run these through (pdf)latex."
+
+changes:
+	mkdir -p build/changes build/doctrees
+	$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes
+	@echo
+	@echo "The overview file is in build/changes."
+
+linkcheck:
+	mkdir -p build/linkcheck build/doctrees
+	$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck
+	@echo
+	@echo "Link check complete; look for any errors in the above output " \
+	 "or in build/linkcheck/output.txt."
Added: trunk/py4science/examples/sphinx_template2/README.txt
===================================================================
--- trunk/py4science/examples/sphinx_template2/README.txt	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/README.txt	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,54 @@
+===========================
+ sphinx template sampledoc
+===========================
+
+This is the top level build directory for the sphinx "sampledoc" documentation.
+You can use this as a starter template for your own projects. The name
+"sampledoc" is the mock name for the project, you'll need to configure this for
+your needs by editing the conf.py and index.rst files.
+
+All of the documentation is written using reStructuredText and is meant to be
+built Sphinx, a python documentation system built on top of ReST. As of Python
+2.6, Sphinx is the default docuentation system for Python itself, and it is
+becoming rapidly adopted by multiple projects.
+
+This directory contains:
+
+* index.rst - the top level include document for your project.
+
+* conf.py - the sphinx configuration file. You need to edit this file to set
+ your project name, authors, etc.
+
+* Makefile - just type 'make' to see a list of available targets.
+
+* model - A directory for a mock document describing a model. Be sure to see
+ the cheat sheet file "model/sphinx_helpers.rst".
+
+* simulations - A directory for another mock part of your project.
+
+* pyplots - a directory with matplotlib scripts to generate figures that can be
+ included in your document with the 'plot' directive. See the
+ sphinx_helpers.rst file for details.
+ 
+* tools - a directory that contains:
+
+ * sphinxext - some extensions to sphinx to handle math, ipython syntax
+ highlighting, autodocs.
+
+ * static - directory where you can put your static content, meant to be
+ copied on output by Sphinx into the top-level _static directory. This is
+ never overwritten, so you can keep static CSS files, etc here, that can
+ then override the Sphinx ones.
+
+ * templates - directory for your own templates, also used by sphinx.
+
+ 
+Note: The makefile and sphinx build system create three directories when
+bulding the output, named ``build``, ``dist`` and ``_static``. Do *not* make
+directories with these names as part of your project, to avoid possible
+conflicts.
+
+
+You can get the latest svn of this document with::
+
+ svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/py4science/examples/sphinx_template2
Added: trunk/py4science/examples/sphinx_template2/conf.py
===================================================================
--- trunk/py4science/examples/sphinx_template2/conf.py	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/conf.py	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,177 @@
+# -*- coding: utf-8 -*-
+#
+# sampledoc documentation build configuration file, created by
+# sphinx-quickstart on Tue Jun 3 12:40:24 2008.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# The contents of this file are pickled, so don't put values in the namespace
+# that aren't pickleable (module imports are okay, they're removed automatically).
+#
+# All configuration values have a default value; values that are commented out
+# serve to show the default value.
+
+import sys, os
+
+# 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('tools/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 = [#'mathmpl',
+ 'ipython_console_highlighting', 'sphinx.ext.autodoc',
+ 'inheritance_diagram', 'only_directives', 'plot_directive',
+ 'sphinx.ext.pngmath',
+ ]
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['tools/templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General substitutions.
+project = 'sampledoc'
+copyright = '2008, John D. Hunter, Cast of Thousands'
+
+# The default replacements for |version| and |release|, also used in various
+# other places throughout the built documents.
+#
+# The short X.Y version.
+version = '0.2'
+# The full version, including alpha/beta/rc tags.
+release = '0.2'
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+today_fmt = '%B %d, %Y'
+
+# List of documents that shouldn't be included in the build.
+#unused_docs = []
+
+# List of directories, relative to source directories, that shouldn't be
+# searched for source files.
+#exclude_dirs = []
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+
+# Options for HTML output
+# -----------------------
+
+# The style sheet to use for HTML and HTML Help pages. A file of that name
+# must exist either in Sphinx' static/ path, or in one of the custom paths
+# given in html_static_path.
+html_style = 'default.css'
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# The name of an image file (within the static path) to place at the top of
+# the sidebar.
+#html_logo = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['tools/static','_static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_use_modindex = True
+
+# If true, the reST sources are included in the HTML build as _sources/<name>.
+#html_copy_source = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it. The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = ''
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = project
+
+
+# Options for LaTeX output
+# ------------------------
+
+# The paper size ('letter' or 'a4').
+#latex_paper_size = 'letter'
+
+# The font size ('10pt', '11pt' or '12pt').
+#latex_font_size = '10pt'
+
+# Grouping the document tree into LaTeX files. List of tuples (source start
+# file, target name, title, author, document class [howto/manual]).
+
+main_manual_tex = project + '.tex'
+
+latex_documents = [
+ (master_doc,
+ main_manual_tex,
+ 'sampledoc Documentation',
+ 'John D. Hunter, Cast of Thousands',
+ 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# Additional stuff for the LaTeX preamble.
+#latex_preamble = ''
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_use_modindex = True
Added: trunk/py4science/examples/sphinx_template2/index.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/index.rst	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/index.rst	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,25 @@
+.. sampledoc documentation master file
+ You can adapt this file completely to your liking, but it should at least
+ contain the root `toctree` directive.
+
+Welcome to sampledoc's documentation!
+=====================================
+
+.. htmlonly::
+
+ :Release: |version|
+ :Date: |today|
+
+.. toctree::
+ :maxdepth: 2
+
+ model/index.rst
+ simulations/index.rst
+
+
+.. htmlonly::
+
+ * :ref:`genindex`
+ * :ref:`modindex`
+ * :ref:`search`
+
Added: trunk/py4science/examples/sphinx_template2/model/api_docs.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/model/api_docs.rst	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/model/api_docs.rst	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -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>`_
+facilities.
+
+:mod:`matplotlib.backend_bases`
+================================
+
+.. automodule:: matplotlib.backend_bases
+ :members:
+ :undoc-members:
Added: trunk/py4science/examples/sphinx_template2/model/index.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/model/index.rst	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/model/index.rst	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,13 @@
+.. _model-index:
+
+================
+ My Fancy Model
+================
+
+.. toctree::
+
+ introduction.rst
+ next_steps.rst
+ sphinx_helpers.rst
+ api_docs.rst
+ 
\ No newline at end of file
Added: trunk/py4science/examples/sphinx_template2/model/introduction.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/model/introduction.rst	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/model/introduction.rst	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,30 @@
+.. _model-introduction:
+
+******************
+Model Introduction
+******************
+
+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
+============
+
+Where in I describe
+
+* model A
+
+* model B
+
+* model C
+
+and why they all suck
+
Added: trunk/py4science/examples/sphinx_template2/model/next_steps.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/model/next_steps.rst	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/model/next_steps.rst	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,8 @@
+.. _next-steps:
+
+**********
+Next steps
+**********
+
+Wherein I describe my next steps
+
Added: trunk/py4science/examples/sphinx_template2/model/sphinx_helpers.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/model/sphinx_helpers.rst	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/model/sphinx_helpers.rst	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,220 @@
+.. _sphinx_helpers:
+
+******************
+Sphinx Cheat Sheet
+******************
+
+Wherein I show by example how to do some things in Sphinx (you can see
+a literal version of this file below in :ref:`sphinx-literal`)
+
+
+.. _making-a-list:
+
+Making a list
+=============
+
+It is easy to make lists in rest
+
+Bullet points
+-------------
+
+This is a subsection making bullet points
+
+* point A
+
+* point B
+
+* point C
+
+
+Enumerated points
+------------------
+
+This is a subsection making numbered points
+
+#. point A
+
+#. point B
+
+#. point C
+
+
+.. _making-a-table:
+
+Making a table
+==============
+
+This shows you how to make a table -- if you only want to make a list see :ref:`making-a-list`.
+
+================== ============
+Name Age
+================== ============
+John D Hunter 40
+Cast of Thousands 41
+And Still More 42
+================== ============
+
+.. _making-links:
+
+Making links
+============
+
+It is easy to make a link to `yahoo <http://yahoo.com>`_ or to some
+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
+
+This support is included in this template, but will also be included
+in a future version of Pygments by default.
+
+.. _formatting-text:
+
+Formatting text
+===============
+
+You use inline markup to make text *italics*, **bold**, or ``monotype``.
+
+You can represent code blocks fairly easily::
+
+ import numpy as np
+ x = np.random.rand(12)
+
+Or literally include code:
+
+.. literalinclude:: ../pyplots/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]
+
+This documentation framework includes a Sphinx extension,
+:file:`sphinxext/mathmpl.py`, that uses matplotlib to render math
+equations when generating HTML, and LaTeX itself when generating a
+PDF. This can be useful on systems that have matplotlib, but not
+LaTeX, installed. To use it, add ``mathmpl`` to the list of
+extensions in :file:`conf.py`.
+
+Current SVN versions of Sphinx now include built-in support for math.
+There are two flavors:
+
+ - pngmath: uses dvipng to render the equation
+
+ - jsmath: renders the math in the browser using Javascript
+
+To use these extensions instead, add ``sphinx.ext.pngmath`` or
+``sphinx.ext.jsmath`` to the list of extensions in :file:`conf.py`.
+
+All three of these options for math are designed to behave in the same
+way.
+
+.. _emacs-helpers:
+
+Inserting matplotlib plots
+==========================
+
+Inserting automatically-generated plots is easy. Simply put the
+script to generate the plot in the :file:`pyplots` directory, and
+refer to it using the ``plot`` directive. To include the source code
+for the plot in the document, pass the ``include-source`` parameter::
+
+ .. plot:: ../pyplots/elegant.py
+ :include-source:
+
+In the HTML version of the document, the plot includes links to the
+original source code, a high-resolution PNG and a PDF. In the PDF
+version of the document, the plot is included as a scalable PDF.
+
+.. plot:: ../pyplots/elegant.py
+ :include-source:
+
+Inheritance diagrams
+====================
+
+Inheritance diagrams can be inserted directly into the document by
+providing a list of class or module names to the
+``inheritance-diagram`` directive.
+
+For example::
+
+ .. inheritance-diagram:: codecs
+
+produces:
+
+.. inheritance-diagram:: codecs
+
+Emacs helpers
+=============
+
+There is an emacs mode `rst.el
+<http://docutils.sourceforge.net/tools/editors/emacs/rst.el>`_ which
+automates many important ReST tasks like building and updateing
+table-of-contents, and promoting or demoting section headings. Here
+is the basic ``.emacs`` configuration::
+
+ (require 'rst)
+ (setq auto-mode-alist
+ (append '(("\\.txt$" . rst-mode)
+ ("\\.rst$" . rst-mode)
+ ("\\.rest$" . rst-mode)) auto-mode-alist))
+
+
+Some helpful functions::
+
+ C-c TAB - rst-toc-insert
+
+ Insert table of contents at point
+
+ C-c C-u - rst-toc-update
+
+ Update the table of contents at point
+
+ C-c C-l rst-shift-region-left
+
+ Shift region to the left
+
+ C-c C-r rst-shift-region-right
+
+ Shift region to the right
+
+
+.. _sphinx-literal:
+
+This file
+=========
+
+.. literalinclude:: sphinx_helpers.rst
+
+
Added: trunk/py4science/examples/sphinx_template2/pyplots/elegant.py
===================================================================
--- trunk/py4science/examples/sphinx_template2/pyplots/elegant.py	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/pyplots/elegant.py	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,4 @@
+import matplotlib.pyplot as plt
+plt.plot([1,2,3], [4,5,6])
+plt.ylabel('some more numbers')
+
Added: trunk/py4science/examples/sphinx_template2/pyplots/hairy.py
===================================================================
--- trunk/py4science/examples/sphinx_template2/pyplots/hairy.py	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/pyplots/hairy.py	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,4 @@
+import matplotlib.pyplot as plt
+plt.plot([1,2,3])
+plt.ylabel('some numbers')
+
Added: trunk/py4science/examples/sphinx_template2/simulations/finale.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/simulations/finale.rst	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/simulations/finale.rst	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,12 @@
+.. _final-results:
+
+*************
+Final Results
+*************
+
+
+After much head scratching, I wrote this big elegant piece of code, to
+produce this much more elegant figure:
+
+.. plot:: ../pyplots/elegant.py
+ :include-source:
Added: trunk/py4science/examples/sphinx_template2/simulations/index.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/simulations/index.rst	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/simulations/index.rst	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,11 @@
+.. _simulations-index:
+
+===========================
+ My Stupendous Simulations
+===========================
+
+.. toctree::
+
+ introduction.rst
+ preliminary.rst
+ finale.rst
Added: trunk/py4science/examples/sphinx_template2/simulations/introduction.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/simulations/introduction.rst	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/simulations/introduction.rst	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,24 @@
+.. _simulations-introduction:
+
+********************
+Simulations overview
+********************
+
+Wherein I describe my fancy code and libraries to implement my fancy model (:ref:`model-introduction`)
+
+.. _python-libraries:
+
+The python libraries
+====================
+
+Why `matplotlib <http://matplotlib.sf.net>`_ rules
+
+.. _data-sources:
+
+The data sources
+====================
+
+Now how much would you pay?
+
+
+
Added: trunk/py4science/examples/sphinx_template2/simulations/preliminary.rst
===================================================================
--- trunk/py4science/examples/sphinx_template2/simulations/preliminary.rst	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/simulations/preliminary.rst	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,11 @@
+.. _preliminary-tests:
+
+*****************
+Preliminary tests
+*****************
+
+I wrote this big hairy piece of code to make the following plot:
+
+.. plot:: ../pyplots/hairy.py
+ :include-source:
+
Added: trunk/py4science/examples/sphinx_template2/tools/sphinxext/inheritance_diagram.py
===================================================================
--- trunk/py4science/examples/sphinx_template2/tools/sphinxext/inheritance_diagram.py	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/tools/sphinxext/inheritance_diagram.py	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,458 @@
+"""
+Defines a docutils directive for inserting inheritance diagrams.
+
+Provide the directive with one or more classes or modules (separated
+by whitespace). For modules, all of the classes in that module will
+be used.
+
+Example::
+
+ Given the following classes:
+
+ class A: pass
+ class B(A): pass
+ class C(A): pass
+ class D(B, C): pass
+ class E(B): pass
+
+ .. inheritance-diagram: D E
+
+ Produces a graph like the following:
+
+ A
+ / \
+ B C
+ / \ /
+ E D
+
+The graph is inserted as a PNG+image map into HTML and a PDF in
+LaTeX.
+"""
+
+#-----------------------------------------------------------------------------
+# Module and package imports
+
+# From the standard library
+
+import inspect
+import os
+import re
+import subprocess
+
+try:
+ from hashlib import md5
+except ImportError:
+ from md5 import md5
+
+# Third party
+from docutils.nodes import Body, Element
+from docutils.writers.html4css1 import HTMLTranslator
+from docutils.parsers.rst import directives
+
+from sphinx.latexwriter import LaTeXTranslator
+from sphinx.roles import xfileref_role
+
+#-----------------------------------------------------------------------------
+# Global Constants
+# Sphinx automatically copies out the contents of this directory to the html
+# output, so by putting things in here they get correctly picked up in the end
+STATIC_DIR='_static'
+
+options_spec = {
+ 'parts': directives.nonnegative_int
+ }
+
+#-----------------------------------------------------------------------------
+# Main code begins, classes and functions
+
+class DotException(Exception):
+ pass
+
+class InheritanceGraph(object):
+ """
+ Given a list of classes, determines the set of classes that
+ they inherit from all the way to the root "object", and then
+ is able to generate a graphviz dot graph from them.
+ """
+ def __init__(self, class_names, show_builtins=False):
+ """
+ *class_names* is a list of child classes to show bases from.
+
+ If *show_builtins* is True, then Python builtins will be shown
+ in the graph.
+ """
+ self.class_names = class_names
+ self.classes = self._import_classes(class_names)
+ self.all_classes = self._all_classes(self.classes)
+ if len(self.all_classes) == 0:
+ raise ValueError("No classes found for inheritance diagram")
+ self.show_builtins = show_builtins
+
+ py_sig_re = re.compile(r'''^([\w.]*\.)? # class names
+ (\w+) \s* $ # optionally arguments
+ ''', re.VERBOSE)
+
+ def _import_class_or_module(self, name):
+ """
+ Import a class using its fully-qualified *name*.
+ """
+ try:
+ path, base = self.py_sig_re.match(name).groups()
+ except:
+ raise ValueError(
+ "Invalid class or module '%s' specified for inheritance diagram" % name)
+ fullname = (path or '') + base
+ path = (path and path.rstrip('.'))
+ if not path:
+ path = base
+ if not path:
+ raise ValueError(
+ "Invalid class or module '%s' specified for inheritance diagram" % name)
+ try:
+ module = __import__(path, None, None, [])
+ except ImportError:
+ raise ValueError(
+ "Could not import class or module '%s' specified for inheritance diagram" % name)
+
+ try:
+ todoc = module
+ for comp in fullname.split('.')[1:]:
+ todoc = getattr(todoc, comp)
+ except AttributeError:
+ raise ValueError(
+ "Could not find class or module '%s' specified for inheritance diagram" % name)
+
+ # If a class, just return it
+ if inspect.isclass(todoc):
+ return [todoc]
+ elif inspect.ismodule(todoc):
+ classes = []
+ for cls in todoc.__dict__.values():
+ if inspect.isclass(cls) and cls.__module__ == todoc.__name__:
+ classes.append(cls)
+ return classes
+ raise ValueError(
+ "'%s' does not resolve to a class or module" % name)
+
+ def _import_classes(self, class_names):
+ """
+ Import a list of classes.
+ """
+ classes = []
+ for name in class_names:
+ classes.extend(self._import_class_or_module(name))
+ return classes
+
+ def _all_classes(self, classes):
+ """
+ Return a list of all classes that are ancestors of *classes*.
+ """
+ all_classes = {}
+
+ def recurse(cls):
+ all_classes[cls] = None
+ for c in cls.__bases__:
+ if c not in all_classes:
+ recurse(c)
+
+ for cls in classes:
+ recurse(cls)
+
+ return all_classes.keys()
+
+ def class_name(self, cls, parts=0):
+ """
+ Given a class object, return a fully-qualified name. This
+ works for things I've tested in matplotlib so far, but may not
+ be completely general.
+ """
+ module = cls.__module__
+ if module == '__builtin__':
+ fullname = cls.__name__
+ else:
+ fullname = "%s.%s" % (module, cls.__name__)
+ if parts == 0:
+ return fullname
+ name_parts = fullname.split('.')
+ return '.'.join(name_parts[-parts:])
+
+ def get_all_class_names(self):
+ """
+ Get all of the class names involved in the graph.
+ """
+ return [self.class_name(x) for x in self.all_classes]
+
+ # These are the default options for graphviz
+ default_graph_options = {
+ "rankdir": "LR",
+ "size": '"8.0, 12.0"'
+ }
+ default_node_options = {
+ "shape": "box",
+ "fontsize": 10,
+ "height": 0.25,
+ "fontname": "Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",
+ "style": '"setlinewidth(0.5)"'
+ }
+ default_edge_options = {
+ "arrowsize": 0.5,
+ "style": '"setlinewidth(0.5)"'
+ }
+
+ def _format_node_options(self, options):
+ return ','.join(["%s=%s" % x for x in options.items()])
+
+ def _format_graph_options(self, options):
+ return ''.join(["%s=%s;\n" % x for x in options.items()])
+
+ def generate_dot(self, fd, name, parts=0, urls={},
+ graph_options={}, node_options={},
+ edge_options={}):
+ """
+ Generate a graphviz dot graph from the classes that
+ were passed in to __init__.
+
+ *fd* is a Python file-like object to write to.
+
+ *name* is the name of the graph
+
+ *urls* is a dictionary mapping class names to http urls
+
+ *graph_options*, *node_options*, *edge_options* are
+ dictionaries containing key/value pairs to pass on as graphviz
+ properties.
+ """
+ g_options = self.default_graph_options.copy()
+ g_options.update(graph_options)
+ n_options = self.default_node_options.copy()
+ n_options.update(node_options)
+ e_options = self.default_edge_options.copy()
+ e_options.update(edge_options)
+
+ fd.write('digraph %s {\n' % name)
+ fd.write(self._format_graph_options(g_options))
+
+ for cls in self.all_classes:
+ if not self.show_builtins and cls in __builtins__.values():
+ continue
+
+ name = self.class_name(cls, parts)
+
+ # Write the node
+ this_node_options = n_options.copy()
+ url = urls.get(self.class_name(cls))
+ if url is not None:
+ this_node_options['URL'] = '"%s"' % url
+ fd.write(' "%s" [%s];\n' %
+ (name, self._format_node_options(this_node_options)))
+
+ # Write the edges
+ for base in cls.__bases__:
+ if not self.show_builtins and base in __builtins__.values():
+ continue
+
+ base_name = self.class_name(base, parts)
+ fd.write(' "%s" -> "%s" [%s];\n' %
+ (base_name, name,
+ self._format_node_options(e_options)))
+ fd.write('}\n')
+
+ def run_dot(self, args, name, parts=0, urls={},
+ graph_options={}, node_options={}, edge_options={}):
+ """
+ Run graphviz 'dot' over this graph, returning whatever 'dot'
+ writes to stdout.
+
+ *args* will be passed along as commandline arguments.
+
+ *name* is the name of the graph
+
+ *urls* is a dictionary mapping class names to http urls
+
+ Raises DotException for any of the many os and
+ installation-related errors that may occur.
+ """
+ try:
+ dot = subprocess.Popen(['dot'] + list(args),
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ close_fds=True)
+ except OSError:
+ raise DotException("Could not execute 'dot'. Are you sure you have 'graphviz' installed?")
+ except ValueError:
+ raise DotException("'dot' called with invalid arguments")
+ except:
+ raise DotException("Unexpected error calling 'dot'")
+
+ self.generate_dot(dot.stdin, name, parts, urls, graph_options,
+ node_options, edge_options)
+ dot.stdin.close()
+ result = dot.stdout.read()
+ returncode = dot.wait()
+ if returncode != 0:
+ raise DotException("'dot' returned the errorcode %d" % returncode)
+ return result
+
+
+class inheritance_diagram(Body, Element):
+ """
+ A docutils node to use as a placeholder for the inheritance
+ diagram.
+ """
+ pass
+
+
+def inheritance_diagram_directive_run(class_names, options, state):
+ """
+ Run when the inheritance_diagram directive is first encountered.
+ """
+ node = inheritance_diagram()
+
+ # Create a graph starting with the list of classes
+ graph = InheritanceGraph(class_names)
+
+ # Create xref nodes for each target of the graph's image map and
+ # add them to the doc tree so that Sphinx can resolve the
+ # references to real URLs later. These nodes will eventually be
+ # removed from the doctree after we're done with them.
+ for name in graph.get_all_class_names():
+ refnodes, x = xfileref_role(
+ 'class', ':class:`%s`' % name, name, 0, state)
+ node.extend(refnodes)
+ # Store the graph object so we can use it to generate the
+ # dot file later
+ node['graph'] = graph
+ # Store the original content for use as a hash
+ node['parts'] = options.get('parts', 0)
+ node['content'] = " ".join(class_names)
+ return [node]
+
+
+def get_graph_hash(node):
+ return md5(node['content'] + str(node['parts'])).hexdigest()[-10:]
+
+
+def html_output_graph(self, node):
+ """
+ Output the graph for HTML. This will insert a PNG with clickable
+ image map.
+ """
+ graph = node['graph']
+ parts = node['parts']
+
+ graph_hash = get_graph_hash(node)
+ name = "inheritance%s" % graph_hash
+ png_path = os.path.join(STATIC_DIR, name + ".png")
+
+ path = STATIC_DIR
+ source = self.document.attributes['source']
+ 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
+
+ # Create a mapping from fully-qualified class names to URLs.
+ urls = {}
+ for child in node:
+ if child.get('refuri') is not None:
+ urls[child['reftitle']] = child.get('refuri')
+ elif child.get('refid') is not None:
+ urls[child['reftitle']] = '#' + child.get('refid')
+
+ # These arguments to dot will save a PNG file to disk and write
+ # an HTML image map to stdout.
+ image_map = graph.run_dot(['-Tpng', '-o%s' % png_path, '-Tcmapx'],
+ name, parts, urls)
+ return ('<img src="%s/%s.png" usemap="#%s" class="inheritance"/>%s' %
+ (path, name, name, image_map))
+
+
+def latex_output_graph(self, node):
+ """
+ Output the graph for LaTeX. This will insert a PDF.
+ """
+ graph = node['graph']
+ parts = node['parts']
+
+ graph_hash = get_graph_hash(node)
+ name = "inheritance%s" % graph_hash
+ pdf_path = os.path.join(STATIC_DIR, name + ".pdf")
+
+ graph.run_dot(['-Tpdf', '-o%s' % pdf_path],
+ name, parts, graph_options={'size': '"6.0,6.0"'})
+ return '\\includegraphics{../../%s}' % pdf_path
+
+
+def visit_inheritance_diagram(inner_func):
+ """
+ This is just a wrapper around html/latex_output_graph to make it
+ easier to handle errors and insert warnings.
+ """
+ def visitor(self, node):
+ try:
+ content = inner_func(self, node)
+ except DotException, e:
+ # Insert the exception as a warning in the document
+ warning = self.document.reporter.warning(str(e), line=node.line)
+ warning.parent = node
+ node.children = [warning]
+ else:
+ source = self.document.attributes['source']
+ self.body.append(content)
+ node.children = []
+ return visitor
+
+
+def do_nothing(self, node):
+ pass
+
+
+def setup(app):
+ app.add_node(inheritance_diagram)
+
+ HTMLTranslator.visit_inheritance_diagram = \
+ visit_inheritance_diagram(html_output_graph)
+ HTMLTranslator.depart_inheritance_diagram = do_nothing
+
+ LaTeXTranslator.visit_inheritance_diagram = \
+ visit_inheritance_diagram(latex_output_graph)
+ LaTeXTranslator.depart_inheritance_diagram = do_nothing
+
+#-----------------------------------------------------------------------------
+# Main code - register the directives. Do it in a way that's compatible with
+# the old and current docutils APIs.
+
+try:
+ from docutils.parsers.rst import Directive
+except ImportError:
+ # Legacy API
+ from docutils.parsers.rst.directives import _directives
+
+ def inheritance_diagram_directive(name, arguments, options, content, lineno,
+ content_offset, block_text, state,
+ state_machine):
+ return inheritance_diagram_directive_run(arguments, options, state)
+ 
+ inheritance_diagram_directive.__doc__ = __doc__
+ inheritance_diagram_directive.arguments = (1, 100, 0)
+ inheritance_diagram_directive.options = options_spec
+ inheritance_diagram_directive.content = 0
+ _directives['inheritance-diagram'] = inheritance_diagram_directive
+
+else:
+ # New API
+ class inheritance_diagram_directive(Directive):
+ has_content = False
+ required_arguments = 1
+ optional_arguments = 100
+ final_argument_whitespace = False
+ option_spec = options_spec
+
+ def run(self):
+ return inheritance_diagram_directive_run(
+ self.arguments, self.options, self.state)
+
+ inheritance_diagram_directive.__doc__ = __doc__
+
+ directives.register_directive('inheritance-diagram',
+ inheritance_diagram_directive)
Added: trunk/py4science/examples/sphinx_template2/tools/sphinxext/ipython_console_highlighting.py
===================================================================
--- trunk/py4science/examples/sphinx_template2/tools/sphinxext/ipython_console_highlighting.py	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/tools/sphinxext/ipython_console_highlighting.py	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,98 @@
+"""reST directive for syntax-highlighting ipython interactive sessions.
+"""
+
+#-----------------------------------------------------------------------------
+# Needed modules
+
+# Standard library
+import re
+
+# Third party
+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
+
+
+#-----------------------------------------------------------------------------
+# Global constants
+line_re = re.compile('.*?\n')
+
+#-----------------------------------------------------------------------------
+# Code begins - classes and functions
+
+class IPythonConsoleLexer(Lexer):
+ """
+ For IPython console output or doctests, such as:
+
+ .. sourcecode:: ipython
+
+ In [1]: a = 'foo'
+
+ In [2]: a
+ Out[2]: 'foo'
+
+ In [3]: print a
+ foo
+
+ In [4]: 1 / 0
+
+ Notes:
+
+ - Tracebacks are not currently supported.
+
+ - It assumes the default IPython prompts, not customized ones.
+ """
+ 
+ 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
+
+#-----------------------------------------------------------------------------
+# Register the extension as a valid pygments lexer
+highlighting.lexers['ipython'] = IPythonConsoleLexer()
Added: trunk/py4science/examples/sphinx_template2/tools/sphinxext/mathmpl.py
===================================================================
--- trunk/py4science/examples/sphinx_template2/tools/sphinxext/mathmpl.py	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/tools/sphinxext/mathmpl.py	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,166 @@
+"""matplotlib-based directive for math rendering in reST using sphinx.
+
+To use this extension, add ``mathmpl`` to the list of extensions in
+:file:`conf.py`.
+
+*Warning*: this code is currently untested. ***MAY NOT WORK***
+
+Note:
+
+Current SVN versions of Sphinx now include built-in support for math.
+There are two flavors:
+
+ - pngmath: uses dvipng to render the equation
+
+ - jsmath: renders the math in the browser using Javascript
+
+To use these extensions instead of the code in this module, add
+``sphinx.ext.pngmath`` or ``sphinx.ext.jsmath`` to the list of extensions in
+:file:`conf.py`.
+
+All three of these options for math are designed to behave in the same
+way.
+"""
+
+import os
+try:
+ from hashlib import md5
+except ImportError:
+ from md5 import md5
+
+from docutils import nodes
+from docutils.parsers.rst import directives
+from docutils.writers.html4css1 import HTMLTranslator
+from sphinx.latexwriter import LaTeXTranslator
+import warnings
+
+# Constants
+STATIC_DIR='_static'
+
+# Define LaTeX math node:
+class latex_math(nodes.General, nodes.Element):
+ pass
+
+def fontset_choice(arg):
+ return directives.choice(arg, ['cm', 'stix', 'stixsans'])
+
+options_spec = {'fontset': fontset_choice}
+
+def math_role(role, rawtext, text, lineno, inliner,
+ options={}, content=[]):
+ i = rawtext.find('`')
+ latex = rawtext[i+1:-1]
+ node = latex_math(rawtext)
+ node['latex'] = latex
+ node['fontset'] = options.get('fontset', 'cm')
+ return [node], []
+math_role.options = options_spec
+
+def math_directive_run(content, block_text, options):
+ latex = ''.join(content)
+ node = latex_math(block_text)
+ node['latex'] = latex
+ node['fontset'] = options.get('fontset', 'cm')
+ 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):
+ return math_directive_run(content, block_text, options)
+ math_directive.arguments = None
+ math_directive.options = options_spec
+ math_directive.content = 1
+ _directives['math'] = math_directive
+else:
+ class math_directive(Directive):
+ has_content = True
+ option_spec = options_spec
+
+ def run(self):
+ return math_directive_run(self.content, self.block_text,
+ self.options)
+ 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 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, fontset='cm'):
+ latex = "$%s$" % latex
+ orig_fontset = rcParams['mathtext.fontset']
+ rcParams['mathtext.fontset'] = fontset
+ if os.path.exists(filename):
+ depth = mathtext_parser.get_depth(latex, dpi=100)
+ else:
+ print latex.encode("ascii", "backslashreplace")
+ try:
+ depth = mathtext_parser.to_png(filename, latex, dpi=100)
+ except:
+ warnings.warn("Could not render math expression %s" % latex,
+ Warning)
+ depth = 0
+ rcParams['mathtext.fontset'] = orig_fontset
+ return depth
+
+# LaTeX to HTML translation stuff:
+def latex2html(node, source):
+ inline = isinstance(node.parent, nodes.TextElement)
+ latex = node['latex']
+ name = 'math-%s' % md5(latex).hexdigest()[-10:]
+ dest = os.path.join(STATIC_DIR, name + ".png")
+
+ depth = latex2png(latex, dest, node.get('fontset',
+ rcParams['mathtext.fontset']))
+
+ path = STATIC_DIR
+ 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:
+ cls = ''
+ else:
+ cls = 'class="center" '
+ if inline and depth != 0:
+ style = 'style="position: relative; bottom: -%dpx"' % (depth + 1)
+ else:
+ style = ''
+
+ return '<img src="%s/%s.png" %s%s/>' % (path, name, cls, style)
+
Added: trunk/py4science/examples/sphinx_template2/tools/sphinxext/only_directives.py
===================================================================
--- trunk/py4science/examples/sphinx_template2/tools/sphinxext/only_directives.py	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/tools/sphinxext/only_directives.py	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,101 @@
+"""reST directives for selective inclusion of contents.
+
+A pair of directives for inserting content that will only appear in
+either html or latex.
+"""
+
+#-----------------------------------------------------------------------------
+# Needed packages and modules
+
+
+from docutils.nodes import Body, Element
+from docutils.writers.html4css1 import HTMLTranslator
+
+from sphinx.latexwriter import LaTeXTranslator
+
+from docutils.parsers.rst import directives
+
+
+#-----------------------------------------------------------------------------
+# Code begins
+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]
+
+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
+
+# Register the directives with code for both the legacy and the new docutils
+# APIs.
+try:
+ from docutils.parsers.rst import Directive
+except ImportError:
+ # Legacy API
+ 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:
+ # New docutils directive API
+ 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)
Added: trunk/py4science/examples/sphinx_template2/tools/sphinxext/plot_directive.py
===================================================================
--- trunk/py4science/examples/sphinx_template2/tools/sphinxext/plot_directive.py	 (rev 0)
+++ trunk/py4science/examples/sphinx_template2/tools/sphinxext/plot_directive.py	2008年10月08日 04:07:21 UTC (rev 6167)
@@ -0,0 +1,208 @@
+"""A special directive for including a matplotlib plot.
+
+Given a path to a .py file, it includes the source code inline, then:
+
+- On HTML, will include a .png with a link to a high-res .png.
+
+- On LaTeX, will include a .pdf
+
+This directive supports all of the options of the `image` directive,
+except for `target` (since plot will add its own target).
+
+Additionally, if the :include-source: option is provided, the literal
+source will be included inline, as well as a link to the source.
+"""
+
+#-----------------------------------------------------------------------------
+# Modules
+
+# Stdlib imports
+import glob
+import os
+import shutil
+import sys
+
+from os import path
+
+# Third-party imports
+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
+
+# Congigure matplotlib to only use a non-gui backend for image generations
+import matplotlib
+matplotlib.use('Agg')
+import matplotlib.pyplot as plt
+
+import IPython.Shell
+
+#-----------------------------------------------------------------------------
+# Global constants
+
+# Make an IPython instance to run scripts
+mplshell = IPython.Shell.MatplotlibShell('mpl')
+
+# HTML generation options
+options = {'alt': directives.unchanged,
+ 'height': directives.length_or_unitless,
+ 'width': directives.length_or_percentage_or_unitless,
+ 'scale': directives.nonnegative_int,
+ 'align': align,
+ 'class': directives.class_option,
+ 'include-source': directives.flag }
+
+template = """
+.. htmlonly::
+
+ [`source code <../%(outdir)s/%(basename)s.py>`__,
+ `png <../%(outdir)s/%(basename)s.hires.png>`__,
+ `pdf <../%(outdir)s/%(basename)s.pdf>`__]
+
+ .. image:: ../%(outdir)s/%(basename)s.png
+%(options)s
+
+.. latexonly::
+ .. image:: ../%(outdir)s/%(basename)s.pdf
+%(options)s
+
+"""
+
+# XXX - we're abusing things a bit by dumping all output files into the
+# top-level static direcotry that sphinx uses. Ideally we should create our
+# own and populate it with a hierarchy similar to that of the inputs, to avoid
+# possible name clashes from figures with identical names that originally
+# existed in different directories.
+static_dir = '_static'
+
+#-----------------------------------------------------------------------------
+# Code begins
+
+def makefig(fullpath, outdir):
+ """
+ run a pyplot script and save the low and high res PNGs and a PDF in outdir
+ """
+
+ # Resolutions for each formats (passed as dpi= to savefig call)
+ formats = [('png', 100),
+ ('hires.png', 200),
+ ('pdf', 72),
+ ]
+ 
+ fullpath = str(fullpath) # todo, why is unicode breaking this
+ basedir, fname = os.path.split(fullpath)
+ basename, ext = os.path.splitext(fname)
+ all_exists = True
+
+ if basedir != outdir:
+ shutil.copyfile(fullpath, os.path.join(outdir, fname))
+
+ for format, dpi in formats:
+ outname = os.path.join(outdir, '%s.%s' % (basename, format))
+ if not os.path.exists(outname):
+ all_exists = False
+ break
+
+ if all_exists:
+ print ' already have %s' % fullpath
+ return
+
+ print ' building %s' % fullpath
+ 
+ # we need to clear between runs
+ plt.close('all') 
+ matplotlib.rcdefaults()
+ # Set a figure size that doesn't overflow typical browser windows
+ matplotlib.rcParams['figure.figsize'] = (6,4)
+
+ # Run the actual script using IPython/mpl shell
+ mplshell.magic_run(fullpath)
+ 
+ # Generate output files
+ for format, dpi in formats:
+ outname = os.path.join(outdir, '%s.%s' % (basename, format))
+ if os.path.exists(outname): continue
+ plt.savefig(outname, dpi=dpi)
+
+
+def run(arguments, options, state_machine, lineno):
+ """Execution of the docutils plot directive.
+ """
+
+ # Code taken from sphinx - locate the full paths to the included script
+ # Relative filename, as given in the ori...
 
[truncated message content]

Showing 7 results of 7

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.
Thanks for helping keep SourceForge clean.
X





Briefly describe the problem (required):
Upload screenshot of ad (required):
Select a file, or drag & drop file here.
Screenshot instructions:

Click URL instructions:
Right-click on the ad, choose "Copy Link", then paste here →
(This may not be possible with some types of ads)

More information about our ad policies

Ad destination/click URL:

AltStyle によって変換されたページ (->オリジナル) /