|
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 (Wed, 08 Oct 2008)
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] |