[Yt-svn] yt-commit r842 - in branches/yt-1.0/doc: . source source/quick_guide sphinxext

mturk at wrangler.dreamhost.com mturk at wrangler.dreamhost.com
Sat Oct 25 12:02:02 PDT 2008


Author: mturk
Date: Sat Oct 25 12:01:58 2008
New Revision: 842
URL: http://yt.spacepope.org/changeset/842

Log:
Adding some sphinx extensions from matplotlib.

Changed some of the text, moved over to encouraging using IPython and iyt.

Updated documentation zipfile.



Added:
   branches/yt-1.0/doc/sphinxext/
   branches/yt-1.0/doc/sphinxext/ipython_console_highlighting.py
   branches/yt-1.0/doc/sphinxext/only_directives.py
   branches/yt-1.0/doc/sphinxext/plot_directive.py
Modified:
   branches/yt-1.0/doc/docs_html.zip
   branches/yt-1.0/doc/source/conf.py
   branches/yt-1.0/doc/source/getting_started.rst
   branches/yt-1.0/doc/source/intro.rst
   branches/yt-1.0/doc/source/quick_guide/index.rst

Modified: branches/yt-1.0/doc/docs_html.zip
==============================================================================
Binary files. No diff available.

Modified: branches/yt-1.0/doc/source/conf.py
==============================================================================
--- branches/yt-1.0/doc/source/conf.py	(original)
+++ branches/yt-1.0/doc/source/conf.py	Sat Oct 25 12:01:58 2008
@@ -16,14 +16,15 @@
 # If your extensions are in another directory, add it here. If the directory
 # is relative to the documentation root, use os.path.abspath to make it
 # absolute, like shown here.
-#sys.path.append(os.path.abspath('some/directory'))
+sys.path.append(os.path.abspath('../sphinxext'))
 
 # 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 = ['sphinx.ext.autodoc']
+extensions = ['sphinx.ext.autodoc', 'only_directives',
+              'ipython_console_highlighting']
 autoclass_content = 'both'
 
 inherited_memers = 'true'
@@ -47,7 +48,7 @@
 # The short X.Y version.
 version = '1.0'
 # The full version, including alpha/beta/rc tags.
-release = '1.0'
+release = '1.0-dev'
 
 # There are two options for replacing |today|: either, you set today to some
 # non-false value, then it is used:

Modified: branches/yt-1.0/doc/source/getting_started.rst
==============================================================================
--- branches/yt-1.0/doc/source/getting_started.rst	(original)
+++ branches/yt-1.0/doc/source/getting_started.rst	Sat Oct 25 12:01:58 2008
@@ -49,64 +49,39 @@
 Using the Installation Script
 -----------------------------
 
-In the ``doc/`` directory in the yt source distribution, there is a script,
-``install_script.sh``, that I have used in the past to set up a full
-installation of yt.  It may need tweaking or modification, but it gives a
-good idea of the roadmap to installation.
+.. note:: The installation script is now the preferred means of installing a
+   full set of packages -- but if you are comfortable with python, feel free to 
 
+In the ``doc/`` directory in the yt source distribution, there is a script,
+``install_script.sh``, designed to set up a full installation of yt, along with
+all the necessary dependencies.  You can run this script from within a checkout
+of yt or an expanded tarball.
+
+.. note:: For convenience, yt will be installed in 'develop' mode, which means
+   any changes in the source directory will be included the next time you
+   import yt!
 
 Prerequisites for yt
 --------------------
 
 A driving factor in the development of yt over the months leading to release
-0.3 has been the reduction of dependencies.  To that extent, only a few
+1.0 has been the reduction of dependencies.  To that extent, only a few
 packages are required for the base usage, and a GUI toolkit if you are going to use
 the graphical user interface, Reason.
 
- * `Python <http://python.org/>`_, at least version 2.4, but preferably 2.5.
+ * `Python <http://python.org/>`_, at least version 2.4, but preferably 2.5 or
+   2.6.
  * `HDF5 <http://www.hdfgroup.org/>`_, the data storage backend used by Enzo
    and yt (if you can run Enzo, this is already installed!)
  * `NumPy <http://numpy.scipy.org/>`_, the fast numerical backend for Python
  * `MatPlotLib <http://matplotlib.sf.net/>`_, the plotting package
- * `wxPython <http://www.wxpython.org/>`_, the GUI toolkit
+ * `wxPython <http://www.wxpython.org/>`_, the GUI toolkit (optional)
 
 (If you are only interested in manipulating data without any graphical plotting
 or interfaces, you only need to install HDF5, NumPy, and Python!)
 
-Installing the Necessary Packages
----------------------------------
-
-Installing Python itself is usually quite simple, and often very fast.  Because
-we're setting up a small system of packages, even if you have a system-wide
-install of python2.5 it can be easier in some cases to create a local directory
-structure:
-
-.. code-block:: bash
-
-   $ tar xvf Python-2.5.2.tar.gz
-   $ cd Python-2.5.2
-   $ ./configure --prefix=$HOME/local/
-   $ make install
-
-This will create (if necessary) a directory named local in your home directory,
-along with the necessary subdirectories.  When the executable
-``$HOME/lcoal/bin/python2.4`` is used to install a package, it will install it
-to the ``$HOME/local/`` directory structure.
-
-The python packages are fairly straightforward to install.  The process of
-installing packages in python has been greatly simplified over the last few
-years with the addition of setuptools, but for these particular packages I
-typically recommend installing from source, which for Python packages consists
-of changing to the source directory and issues the command:
-
-.. code-block:: bash
-
-   $ tar xvfz $PKGNAME.tar.gz
-   $ cd $PKGNAME
-   $ python2.5 setup.py install
-
-This method works for NumPy, Matplotlib and yt itself, but for wxPython, I
-**strongly** suggest you seek binaries for your platform.  If they are not
-available, I recommend you read the ``INSTALL`` file and follow its directions
-closely.
-
+Instructions for installing these packages is, unfortunately, beyond the scope
+of this document.  However, there are copious directions on how to do so
+elsewhere.  You may also consider installing the
+`Enthought Python Distribution <http://www.enthought.com/products/epd.php>`_,
+which includes all of the necessary packages.

Modified: branches/yt-1.0/doc/source/intro.rst
==============================================================================
--- branches/yt-1.0/doc/source/intro.rst	(original)
+++ branches/yt-1.0/doc/source/intro.rst	Sat Oct 25 12:01:58 2008
@@ -7,9 +7,9 @@
 My name is Matthew Turk, and I am the primary author of yt.  I designed and
 implemented it during the course of my graduate studies working with Prof. Tom
 Abel at Stanford University, under the auspices of the Department of Energy
-through the Stanford Linear Accelerator Center and Los Alamos National Lab.  It
-has evolved from a simple data-reader and exporter into what I believe is a
-fully-featured toolkit.
+through the SLAC National Accelerator Center and, briefly, at Los Alamos
+National Lab.  It has evolved from a simple data-reader and exporter into what
+I believe is a fully-featured toolkit for analysis and visualization.
 
 yt was designed to be a completely Free (as in beer *and* as in freedom)
 user-extensible framework for analyzing and visualizing adaptive mesh
@@ -23,6 +23,10 @@
 it has been generalized to rely on commodity Python packages (mostly), its
 dependencies have been reduced, and thus its installation made significantly easier.
 
+In 2008, yt was extended by Jeff Oishi to include support for the Orion code.
+Additionally, it was selected for inclusion in the next public release of the
+Enzo code.
+
 What yt is and is not
 ---------------------
 
@@ -30,8 +34,9 @@
 fact that it has been written in an interpreted language, it can be somewhat
 slower than purely C-based analysis codes, although I believe that to be
 mitigated by a cleverness of algorithms and a substantially improved
-development time for the user in the case of a desire to expand the
-functionality.
+development time for the user.  Several of the most computatioanlly intensive
+problems have been written in C, or rely exclusively on C-based numerical
+libraries.
 
 The primary goal has been, and will continue to be, to present an interface to
 the user that enables selection and analysis of arbitrary subsets of data.

Modified: branches/yt-1.0/doc/source/quick_guide/index.rst
==============================================================================
--- branches/yt-1.0/doc/source/quick_guide/index.rst	(original)
+++ branches/yt-1.0/doc/source/quick_guide/index.rst	Sat Oct 25 12:01:58 2008
@@ -4,24 +4,24 @@
 If you're impatient, like me, you probably just want to pull up some data and
 take a look at it.  This guide will help you out!
 
-Starting Python
----------------
+Starting IPython
+----------------
 
-If you've used the installation script that comes with yt, you should
-have an isolated environment containing Python 2.5, Matplotlib, wxPython, and
-yt.  Be sure to finish up the instructions by *prepending* the
+If you've used the installation script that comes with yt, you should have an
+isolated environment containing Python 2.5, Matplotlib, yt, IPython, and maybe
+wxPython.  Be sure to finish up the instructions by *prepending* the
 ``LD_LIBRARY_PATH``, ``PATH`` and ``PYTHONPATH`` environment variables with the
-output of the script!
+output of the script.
 
-If you've done that, go ahead and start up yt:
+If you've done that, go ahead and start up our interactive yt environment:
 
 .. code-block:: bash
 
-   $ yt
+   $ iyt
 
 It should start you up in an interpreter, and the namespace will be populated
-with the stuff you need.  Really, the command ``yt`` just opens up Python and
-loads up yt -- nothing too fancy!
+with the stuff you need.  Really, the command ``iyt`` just opens up IPython and
+loads up yt, with some special commands available for you.
 
 You're all set, so let's move on to the next step -- actually opening up your
 data!
@@ -31,13 +31,17 @@
 
 You'll need to know the location of the parameter file from the output you want
 to look at.  Let's pretend, for the sake of argument, it's
-``/scratch/mturk/DataDump0010.dir/DataDump0010`` and that we have all the right
+``/home/mturk/data/galaxy1200.dir/galaxy1200`` and that we have all the right
 permissions.  So let's open it, and see what the maximum density is.
 
-.. code-block:: python
+.. note:: In IPython, you get filename completion!  So hit tab and it'll guess
+   at what you want to open.
+
+.. sourcecode:: ipython
+
+  In [1]: pf = EnzoStaticOutput("/home/mturk/data/galaxy1200.dir/galaxy1200")
 
-   >>> pf = EnzoStaticOutput("/scratch/mturk/DataDump0010.dir/DataDump0010")
-   >>> v, c = pf.h.find_max("Density")
+  In [2]: v, c = pf.h.find_max("Density")
 
 And then in the variable ``v`` we have the value of the most dense cell, and in
 ``c`` we have the location of that point.
@@ -46,25 +50,32 @@
 ------------
 
 But hey, what good is the data if we can't see it?  So let's make some plots!
-First we need to get a :class:`PlotCollection` object, and then we'll add some
-slices and projections to it.  Note that we use 0, 1, 2 to refer to 'x', 'y', 'z'
-axes.
-
-.. code-block:: python
-
-   >>> pc = PlotCollection(pf)
-   >>> pc.add_slice("Temperature", 0)
-   >>> pc.add_projection("Density", 2)
-
-It makes these plots all off-screen.  (If you had used the
-:class:`PlotCollectionInteractive` object, they'd be there, displayed, as soon
-as you added them.)
+First we need to get a :class:`PlotCollectionInteractive` object, and then
+we'll add some slices and projections to it.  Note that we use 0, 1, 2 to refer
+to 'x', 'y', 'z' axes.
+
+.. sourcecode:: ipython
+
+  In [3]: pc = PlotCollectionInteractive(pf)
+  In [4]: pc.add_slice("Temperature", 0)
+  yt.raven   INFO       2008-10-25 11:42:58,429 Added slice of Temperature at x = 0.953125 with 'center' = [0.953125, 0.8046875, 0.6171875]
+  Out[4]: <yt.raven.PlotTypes.SlicePlot instance at 0x9882cec>
+
+  In [5]: pc.add_slice("Density", 0)
+  yt.raven   INFO       2008-10-25 11:43:45,608 Added slice of Density at x = 0.953125 with 'center' = [0.953125, 0.8046875, 0.6171875]
+  Out[5]: <yt.raven.PlotTypes.SlicePlot instance at 0xab83eec>
+
+
+A window should now pop up for each of these plots.  One will be a line
+integral through the simulation, and the other will be a slice.  (If you had
+used the :class:`PlotCollection` object, they'd be created off-screen -- this
+is the right way to make plots programmatically in scripts.)
 
 We can also adjust the width of the plots very easily:
 
-.. code-block:: python
+.. sourcecode:: ipython
 
-   >>> pc.set_width(100, 'kpc')
+  In [6]: pc.set_width(100, 'kpc')
 
 The center is set to the most dense location by default.  (For more
 information, see the documentation for :class:`PlotCollection`.)
@@ -72,35 +83,42 @@
 Saving Plots
 ------------
 
-Because all of these plots are off-screen, we save to the file system before we
-can see them.
+Even though the windows are open, we can save these to the file system at high
+resolution.
 
-.. code-block:: python
+.. sourcecode:: ipython
 
-   >>> pc.save("hi")
+  In [7]: pc.save("hi")
+  Out[7]: ['hi_Slice_x_Temperature.png', 'hi_Slice_x_Density.png']
 
 And that's it!  The plots get saved out, and it returns to you a list of their
 filenames.
 
+.. note:: The *save* command will add some data to the end of the filename --
+   this helps to keep track of what each saved file is.
+
 A Few More Plots
 ----------------
 
 You can also add profiles -- radial or otherwise -- and phase diagrams very
 easily.
 
-.. code-block:: python
+.. sourcecode:: ipython
+
+  In [8]: pc.add_profile_sphere(100.0, 'kpc', ["Density", "Temperature"])
+  Out[8]: <yt.raven.PlotTypes.Profile1DPlot instance at 0xada03ec>
+
+  In [9]: pc.add_phase_sphere(10.0, 'pc', ['Density', 'Temperature', 
+     ...:                                  'H2I_Fraction'])
+  Out[9]: <yt.raven.PlotTypes.PhasePlot instance at 0xada91ef>
 
-   >>> pc.add_profile_sphere(100.0, 'kpc', ['Density', 'Temperature'])
-   >>> pc.add_phase_sphere(10.0, 'pc', ['Density', 'Temperature', 
-   ...                                  'H2I_Fraction'])
-
-But again, you have to save these out before you can view them.  Note that the
-phase plots default to showing a weighted-average in each bin -- weighted by
-the cell mass in solar masses.  If you want to see a distribution of mass,
-you'll need to specify you don't want an average:
+Note that the phase plots default to showing a weighted-average in each bin --
+weighted by the cell mass in solar masses.  If you want to see a distribution
+of mass, you'll need to specify you don't want an average:
 
 .. code-block:: python
 
-   >>> pc.add_phase_sphere(10.0, 'pc', ['Density', 'Temperature', 
-   ...                                  'CellMassMsun'], weight=None)
+  In [10]: pc.add_phase_sphere(10.0, 'pc', ['Density', 'Temperature', 
+      ...:                                   'CellMassMsun'], weight=None)
 
+  Out[10]: <yt.raven.PlotTypes.PhasePlot instance at 0xada91ef>

Added: branches/yt-1.0/doc/sphinxext/ipython_console_highlighting.py
==============================================================================
--- (empty file)
+++ branches/yt-1.0/doc/sphinxext/ipython_console_highlighting.py	Sat Oct 25 12:01:58 2008
@@ -0,0 +1,75 @@
+from pygments.lexer import Lexer, do_insertions
+from pygments.lexers.agile import PythonConsoleLexer, PythonLexer, \
+    PythonTracebackLexer
+from pygments.token import Comment, Generic
+from sphinx import highlighting
+import re
+
+line_re = re.compile('.*?\n')
+
+class IPythonConsoleLexer(Lexer):
+    """
+    For IPython console output or doctests, such as:
+
+    Tracebacks are not currently supported.
+
+    .. sourcecode:: ipython
+
+      In [1]: a = 'foo'
+
+      In [2]: a
+      Out[2]: 'foo'
+
+      In [3]: print a
+      foo
+
+      In [4]: 1 / 0
+    """
+    name = 'IPython console session'
+    aliases = ['ipython']
+    mimetypes = ['text/x-ipython-console']
+    input_prompt = re.compile("(In \[[0-9]+\]: )|(   \.\.\.+:)")
+    output_prompt = re.compile("(Out\[[0-9]+\]: )|(   \.\.\.+:)")
+    continue_prompt = re.compile("   \.\.\.+:")
+    tb_start = re.compile("\-+")
+
+    def get_tokens_unprocessed(self, text):
+        pylexer = PythonLexer(**self.options)
+        tblexer = PythonTracebackLexer(**self.options)
+
+        curcode = ''
+        insertions = []
+        for match in line_re.finditer(text):
+            line = match.group()
+            input_prompt = self.input_prompt.match(line)
+            continue_prompt = self.continue_prompt.match(line.rstrip())
+            output_prompt = self.output_prompt.match(line)
+            if line.startswith("#"):
+                insertions.append((len(curcode),
+                                   [(0, Comment, line)]))
+            elif input_prompt is not None:
+                insertions.append((len(curcode),
+                                   [(0, Generic.Prompt, input_prompt.group())]))
+                curcode += line[input_prompt.end():]
+            elif continue_prompt is not None:
+                insertions.append((len(curcode),
+                                   [(0, Generic.Prompt, continue_prompt.group())]))
+                curcode += line[continue_prompt.end():]
+            elif output_prompt is not None:
+                insertions.append((len(curcode),
+                                   [(0, Generic.Output, output_prompt.group())]))
+                curcode += line[output_prompt.end():]
+            else:
+                if curcode:
+                    for item in do_insertions(insertions,
+                                              pylexer.get_tokens_unprocessed(curcode)):
+                        yield item
+                        curcode = ''
+                        insertions = []
+                yield match.start(), Generic.Output, line
+        if curcode:
+            for item in do_insertions(insertions,
+                                      pylexer.get_tokens_unprocessed(curcode)):
+                yield item
+
+highlighting.lexers['ipython'] = IPythonConsoleLexer()

Added: branches/yt-1.0/doc/sphinxext/only_directives.py
==============================================================================
--- (empty file)
+++ branches/yt-1.0/doc/sphinxext/only_directives.py	Sat Oct 25 12:01:58 2008
@@ -0,0 +1,87 @@
+#
+# A pair of directives for inserting content that will only appear in
+# either html or latex.
+#
+
+from docutils.nodes import Body, Element
+from docutils.writers.html4css1 import HTMLTranslator
+from sphinx.latexwriter import LaTeXTranslator
+from docutils.parsers.rst import directives
+
+class html_only(Body, Element):
+    pass
+
+class latex_only(Body, Element):
+    pass
+
+def run(content, node_class, state, content_offset):
+    text = '\n'.join(content)
+    node = node_class(text)
+    state.nested_parse(content, content_offset, node)
+    return [node]
+
+try:
+    from docutils.parsers.rst import Directive
+except ImportError:
+    from docutils.parsers.rst.directives import _directives
+
+    def html_only_directive(name, arguments, options, content, lineno,
+                            content_offset, block_text, state, state_machine):
+        return run(content, html_only, state, content_offset)
+
+    def latex_only_directive(name, arguments, options, content, lineno,
+                             content_offset, block_text, state, state_machine):
+        return run(content, latex_only, state, content_offset)
+
+    for func in (html_only_directive, latex_only_directive):
+        func.content = 1
+        func.options = {}
+        func.arguments = None
+
+    _directives['htmlonly'] = html_only_directive
+    _directives['latexonly'] = latex_only_directive
+else:
+    class OnlyDirective(Directive):
+        has_content = True
+        required_arguments = 0
+        optional_arguments = 0
+        final_argument_whitespace = True
+        option_spec = {}
+
+        def run(self):
+            self.assert_has_content()
+            return run(self.content, self.node_class,
+                       self.state, self.content_offset)
+
+    class HtmlOnlyDirective(OnlyDirective):
+        node_class = html_only
+
+    class LatexOnlyDirective(OnlyDirective):
+        node_class = latex_only
+
+    directives.register_directive('htmlonly', HtmlOnlyDirective)
+    directives.register_directive('latexonly', LatexOnlyDirective)
+
+def setup(app):
+    app.add_node(html_only)
+    app.add_node(latex_only)
+
+    # Add visit/depart methods to HTML-Translator:
+    def visit_perform(self, node):
+        pass
+    def depart_perform(self, node):
+        pass
+    def visit_ignore(self, node):
+        node.children = []
+    def depart_ignore(self, node):
+        node.children = []
+
+    HTMLTranslator.visit_html_only = visit_perform
+    HTMLTranslator.depart_html_only = depart_perform
+    HTMLTranslator.visit_latex_only = visit_ignore
+    HTMLTranslator.depart_latex_only = depart_ignore
+
+    LaTeXTranslator.visit_html_only = visit_ignore
+    LaTeXTranslator.depart_html_only = depart_ignore
+    LaTeXTranslator.visit_latex_only = visit_perform
+    LaTeXTranslator.depart_latex_only = depart_perform

Added: branches/yt-1.0/doc/sphinxext/plot_directive.py
==============================================================================
--- (empty file)
+++ branches/yt-1.0/doc/sphinxext/plot_directive.py	Sat Oct 25 12:01:58 2008
@@ -0,0 +1,155 @@
+"""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.
+"""
+
+import sys, os, glob, shutil
+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
+
+
+import matplotlib
+import IPython.Shell
+matplotlib.use('Agg')
+import matplotlib.pyplot as plt
+
+mplshell = IPython.Shell.MatplotlibShell('mpl')
+
+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 <../%(srcdir)s/%(basename)s.py>`__,
+   `png <../%(srcdir)s/%(basename)s.hires.png>`__,
+   `pdf <../%(srcdir)s/%(basename)s.pdf>`__]
+
+   .. image:: ../%(srcdir)s/%(basename)s.png
+%(options)s
+
+.. latexonly::
+   .. image:: ../%(srcdir)s/%(basename)s.pdf
+%(options)s
+
+"""
+
+def makefig(fullpath, outdir):
+    """
+    run a pyplot script and save the low and high res PNGs and a PDF in _static
+    """
+
+    fullpath = str(fullpath)  # todo, why is unicode breaking this
+    formats = [('png', 100),
+               ('hires.png', 200),
+               ('pdf', 72),
+               ]
+
+    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
+    plt.close('all')    # we need to clear between runs
+    matplotlib.rcdefaults()
+
+    mplshell.magic_run(fullpath)
+    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):
+    reference = directives.uri(arguments[0])
+    basedir, fname = os.path.split(reference)
+    basename, ext = os.path.splitext(fname)
+
+    # todo - should we be using the _static dir for the outdir, I am
+    # not sure we want to corrupt that dir with autogenerated files
+    # since it also has permanent files in it which makes it difficult
+    # to clean (save an rm -rf followed by and svn up)
+    srcdir = 'pyplots'
+
+    makefig(os.path.join(srcdir, reference), srcdir)
+
+    # todo: it is not great design to assume the makefile is putting
+    # the figs into the right place, so we may want to do that here instead.
+
+    if options.has_key('include-source'):
+        lines = ['.. literalinclude:: ../pyplots/%(reference)s' % locals()]
+        del options['include-source']
+    else:
+        lines = []
+
+    options = ['      :%s: %s' % (key, val) for key, val in
+               options.items()]
+    options = "\n".join(options)
+
+    lines.extend((template % locals()).split('\n'))
+
+    state_machine.insert_input(
+        lines, state_machine.input_lines.source(0))
+    return []
+
+
+try:
+    from docutils.parsers.rst import Directive
+except ImportError:
+    from docutils.parsers.rst.directives import _directives
+
+    def plot_directive(name, arguments, options, content, lineno,
+                       content_offset, block_text, state, state_machine):
+        return run(arguments, options, state_machine, lineno)
+    plot_directive.__doc__ = __doc__
+    plot_directive.arguments = (1, 0, 1)
+    plot_directive.options = options
+
+    _directives['plot'] = plot_directive
+else:
+    class plot_directive(Directive):
+        required_arguments = 1
+        optional_arguments = 0
+        final_argument_whitespace = True
+        option_spec = options
+        def run(self):
+            return run(self.arguments, self.options,
+                       self.state_machine, self.lineno)
+    plot_directive.__doc__ = __doc__
+
+    directives.register_directive('plot', plot_directive)
+



More information about the yt-svn mailing list